ToFaRev sessions

ToFaRev review

srl-labs/containerlab · 657b1700664a

completed · 63 messages · 71 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 - `captureChain.held`/`emitted` grow without a cap during the c9s segment overlap** | [labruntime/clabernetes/capture.go:855-870](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/labruntime/clabernetes/capture.go#L855-L870) |

## P4 - `captureChain.held`/`emitted` grow without a cap during the c9s segment overlap

**Location:** [labruntime/clabernetes/capture.go:855-870](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/labruntime/clabernetes/capture.go#L855-L870)

**Problem:** During the chaining overlap, every packet of the follow-up segment is appended to `c.held` (line 864) and every packet the active segment writes adds an entry to `c.emitted`, with no size cap or consumer backpressure; they are only released when `switchSegments` runs after the active segment ends.

**Trigger:** A chained c9s capture (duration over one hour, or `CLAB_C9S_CAPTURE_SEGMENT` set) on a link with a high packet rate; the overlap is at most `maxCaptureOverlap` (10 seconds, set at line 502 as `min(maxCaptureOverlap, run.segment/3)`).

**Impact:** Transient memory in the containerlab process bounded only by overlap duration times packet rate times snap length; at line rate with the default 256 `KiB` snap length this can reach large sizes before draining. No data loss or deadlock: the drain loop at lines 932-952 releases everything. This is an optional hardening item, not a correctness defect.

**Suggested correction:** Either cap `c.held` (for example, exceed a byte budget and report it as a `CaptureGap`) or reduce the effective overlap under observed rate; at minimum add a comment documenting the overlap-bound memory characteristic. Do not block the merge on this.


## Coverage

- The full diff (7018 lines, 37 changed paths) was traversed, including all regions previously unread (6076-6357 and 6475-7018), plus the head implementations, unit tests (capture, cmd, core), the `fakeClabwire` c9s test harness, the cluster integration test, both robot suites, docs, [`mkdocs.yml`](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/mkdocs.yml#L1-L1), and the CI workflow changes.
- This is a read-only snapshot review: no tests, builds, or formatters were executed; all conclusions are from source inspection.
- Unresolved uncertainty: `handleAudit` ([`labruntime/clabernetes/capture.go`](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/labruntime/clabernetes/capture.go#L1-L1) lines 799-800) returns a `captureAuditError` for `Denied`/`Failed` even when `c.stopping` is set. If an external clabwire build reported `Failed` as a consequence of stdin-close during a Ctrl+C stop, the `PacketCapturer.Capture` contract documented in [`labruntime/runtime.go`](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/labruntime/runtime.go#L1-L1) (context ended is not an error) would surface an error on a clean exit. Whether clabwire does this cannot be verified from the snapshot; the test fake does not. Raised as a coverage note rather than a finding.
- `packetKey` truncates `InterfaceID` to 16 bits for content hashing (`capture.go` lines 973-982); safe at realistic interface counts, recorded as an accepted tradeoff.
- `setCut`&#39;s zero-cut branch is effectively unreachable in production because `window = min(maxCaptureCutWindow, overlap/4)` always satisfies `2*window < overlap`; it is a defensive path consistent with the &#39;overlap too short&#39; gap reporting.
- No topology schema changes are required&#58; the feature is a CLI and runtime API addition, outside the [`clab.schema.json`](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/schemas/clab.schema.json#L1-L1) domain, and the new smoke topology references the existing schema.

---
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": "`captureChain.held`/`emitted` grow without a cap during the c9s segment overlap",
      "location": {
        "revision": "head",
        "path": "labruntime/clabernetes/capture.go",
        "start": 855,
        "end": 870
      },
      "problem": "During the chaining overlap, every packet of the follow-up segment is appended to `c.held` (line 864) and every packet the active segment writes adds an entry to `c.emitted`, with no size cap or consumer backpressure; they are only released when `switchSegments` runs after the active segment ends.",
      "trigger": "A chained c9s capture (duration over one hour, or `CLAB_C9S_CAPTURE_SEGMENT` set) on a link with a high packet rate; the overlap is at most `maxCaptureOverlap` (10 seconds, set at line 502 as `min(maxCaptureOverlap, run.segment/3)`).",
      "impact": "Transient memory in the containerlab process bounded only by overlap duration times packet rate times snap length; at line rate with the default 256 `KiB` snap length this can reach large sizes before draining. No data loss or deadlock: the drain loop at lines 932-952 releases everything. This is an optional hardening item, not a correctness defect.",
      "suggestion": "Either cap `c.held` (for example, exceed a byte budget and report it as a `CaptureGap`) or reduce the effective overlap under observed rate; at minimum add a comment documenting the overlap-bound memory characteristic. Do not block the merge on this."
    }
  ],
  "coverage": {
    "complete": true,
    "notes": [
      "The full diff (7018 lines, 37 changed paths) was traversed, including all regions previously unread (6076-6357 and 6475-7018), plus the head implementations, unit tests (capture, cmd, core), the `fakeClabwire` c9s test harness, the cluster integration test, both robot suites, docs, `mkdocs.yml`, and the CI workflow changes.",
      "This is a read-only snapshot review: no tests, builds, or formatters were executed; all conclusions are from source inspection.",
      "Unresolved uncertainty: `handleAudit` (`labruntime/clabernetes/capture.go` lines 799-800) returns a `captureAuditError` for `Denied`/`Failed` even when `c.stopping` is set. If an external clabwire build reported `Failed` as a consequence of stdin-close during a Ctrl+C stop, the `PacketCapturer.Capture` contract documented in `labruntime/runtime.go` (context ended is not an error) would surface an error on a clean exit. Whether clabwire does this cannot be verified from the snapshot; the test fake does not. Raised as a coverage note rather than a finding.",
      "`packetKey` truncates `InterfaceID` to 16 bits for content hashing (`capture.go` lines 973-982); safe at realistic interface counts, recorded as an accepted tradeoff.",
      "`setCut`'s zero-cut branch is effectively unreachable in production because `window = min(maxCaptureCutWindow, overlap/4)` always satisfies `2*window < overlap`; it is a defensive path consistent with the 'overlap too short' gap reporting.",
      "No topology schema changes are required: the feature is a CLI and runtime API addition, outside the `clab.schema.json` domain, and the new smoke topology references the existing schema."
    ]
  }
}
```
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 37 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: 657b1700664a99c5e12c60b4cfd179eb11889bae. Comparison base: 00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4. Target base: 00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4.
GitHub permalink roots: head=https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/; base=https://github.com/srl-labs/containerlab/blob/00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4/.
Snapshot incomplete: false. The full inventory and omission details are in manifest.json; consult it when needed. 
Message metadata
{
  "role": "user",
  "id": "msg_196508bbe001tLsHPkKW57hw60",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523223487
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 2
step-start
{
  "type": "step-start",
  "id": "prt_196509271001vDxLvDj7w3DTb6",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196508dfc001Wl9eZDy77pkKXg"
}
Reasoning
Let me start by exploring the source directory structure and reading standards.json and diff.txt.
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_1965092df001JRcPKuqJUVr0Uc",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196508dfc001Wl9eZDy77pkKXg",
  "callID": "call_b75115aae8d746fc809f02de",
  "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": 1793523225320,
      "end": 1793523225329
    }
  }
}
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": "00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4",
5:     "file": "standards/karpathy-guidelines.mdc"
6:   },
7:   {
8:     "path": ".cursor/rules/ponytail.mdc",
9:     "revision": "00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4",
10:     "file": "standards/ponytail.mdc"
11:   }
12: ]

(End of file - total 12 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1965092ff001IB51QoMOffsBTf",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196508dfc001Wl9eZDy77pkKXg",
  "callID": "call_93aa70db3e734eda9b6d8e01",
  "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\": \"00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4\",\n5:     \"file\": \"standards/karpathy-guidelines.mdc\"\n6:   },\n7:   {\n8:     \"path\": \".cursor/rules/ponytail.mdc\",\n9:     \"revision\": \"00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4\",\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\": \"00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4\",\n    \"file\": \"standards/karpathy-guidelines.mdc\"\n  },\n  {\n    \"path\": \".cursor/rules/ponytail.mdc\",\n    \"revision\": \"00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4\",\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\": \"00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4\",\n    \"file\": \"standards/karpathy-guidelines.mdc\"\n  },\n  {\n    \"path\": \".cursor/rules/ponytail.mdc\",\n    \"revision\": \"00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4\",\n    \"file\": \"standards/ponytail.mdc\"\n  }\n]",
        "lineStart": 1,
        "lineEnd": 12,
        "totalLines": 12,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523225349,
      "end": 1793523225366
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19650931b00146heW6z7ou6QLt",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196508dfc001Wl9eZDy77pkKXg",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 3319,
    "input": 3278,
    "output": 23,
    "reasoning": 18,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196508dfc001Wl9eZDy77pkKXg",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523224060,
    "completed": 1793523225376
  },
  "parentID": "msg_196508bbe001tLsHPkKW57hw60",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 3319,
    "input": 3278,
    "output": 23,
    "reasoning": 18,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 3
step-start
{
  "type": "step-start",
  "id": "prt_196509758001Oi6fuAMhq4bDYk",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196509323001BDtPyZbpQXpNCn"
}
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_196509764001sbZTTQBO9hcffM",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196509323001BDtPyZbpQXpNCn",
  "callID": "call_b22feaf392934d718a5779e9",
  "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": 1793523226480,
      "end": 1793523226511
    }
  }
}
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_19650979b001MvYf53nerMn7gY",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196509323001BDtPyZbpQXpNCn",
  "callID": "call_314f13210f4b4660af0ba922",
  "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": 1793523226533,
      "end": 1793523226547
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1965097b9001557o4gpkSPKQUh",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196509323001BDtPyZbpQXpNCn",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 3730,
    "input": 810,
    "output": 39,
    "reasoning": 1,
    "cache": {
      "read": 2880,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196509323001BDtPyZbpQXpNCn",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523225379,
    "completed": 1793523226563
  },
  "parentID": "msg_196508bbe001tLsHPkKW57hw60",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 3730,
    "input": 810,
    "output": 39,
    "reasoning": 1,
    "cache": {
      "read": 2880,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 4
step-start
{
  "type": "step-start",
  "id": "prt_196509c0a001xJqlZjqh8KBPj0",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965097c9001saIYtHzqO7p3aW"
}
read · completed

Input

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

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1: diff --git a/.github/workflows/clabernetes-tests.yml b/.github/workflows/clabernetes-tests.yml
2: index b1cbd00..7785167 100644
3: --- a/.github/workflows/clabernetes-tests.yml
4: +++ b/.github/workflows/clabernetes-tests.yml
5: @@ -100,10 +100,15 @@ jobs:
6:              upgrade --install --create-namespace --namespace c9s \
7:                clabernetes oci://ghcr.io/clabernetes/clabernetes/clabernetes:0.0.0
8:  
9:            kubectl -n c9s rollout status deploy/clabernetes-manager --timeout=180s
10:  
11: +      - name: Install tshark
12: +        run: |
13: +          sudo apt-get update
14: +          sudo DEBIAN_FRONTEND=noninteractive apt-get install -y tshark
15: +
16:        - name: Run Clabernetes Robot tests
17:          run: |
18:            bash ./tests/rf-run.sh c9s ./tests/14-clabernetes
19:  
20:        - name: Upload test report
21: diff --git a/.github/workflows/smoke-tests.yml b/.github/workflows/smoke-tests.yml
22: index 807acbe..f7ee3c8 100644
23: --- a/.github/workflows/smoke-tests.yml
24: +++ b/.github/workflows/smoke-tests.yml
25: @@ -51,10 +51,11 @@ jobs:
26:            - "28*.robot"
27:            - "29*.robot"
28:            - "30*.robot"
29:            - "31*.robot"
30:            - "32*.robot"
31: +          - "33*.robot"
32:  
33:      # allow podman job to fail, since it started to fail on github actions
34:      continue-on-error: ${{ inputs.runtime == 'podman' }}
35:      steps:
36:        - name: Checkout
37: diff --git a/capture/local.go b/capture/local.go
38: new file mode 100644
39: index 0000000..58dc8aa
40: --- /dev/null
41: +++ b/capture/local.go
42: @@ -0,0 +1,430 @@
43: +package capture
44: +
45: +import (
46: +	"context"
47: +	"errors"
48: +	"fmt"
49: +	"io"
50: +	"os"
51: +	"sync"
52: +	"time"
53: +
54: +	"github.com/charmbracelet/log"
55: +	"github.com/containernetworking/plugins/pkg/ns"
56: +	"github.com/gopacket/gopacket"
57: +	"github.com/gopacket/gopacket/afpacket"
58: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
59: +)
60: +
61: +const (
62: +	// localReorderWindow is how long the merged stream holds packets of local sockets back to
63: +	// write them in timestamp order. Each socket hands over its packets within
64: +	// localBlockTimeout, so a few times that covers the delivery skew between sockets.
65: +	localReorderWindow = 100 * time.Millisecond
66: +	// localBlockTimeout is how long the kernel fills a ring block before it hands it over.
67: +	localBlockTimeout = 10 * time.Millisecond
68: +	// localPollTimeout is how often a socket reader checks whether the capture ended.
69: +	localPollTimeout = 100 * time.Millisecond
70: +	// localReopenInterval is how often a reader tries to reopen the socket of an interface
71: +	// that went down or disappeared.
72: +	localReopenInterval = 200 * time.Millisecond
73: +	// localDrainQuiet is how long after the end of a capture a reader keeps waiting for packets
74: +	// still in the socket's ring: the kernel hands over a block within two block timeouts.
75: +	localDrainQuiet = 5 * localBlockTimeout
76: +	// localDrainTimeout bounds the drain while packets keep arriving.
77: +	localDrainTimeout = 250 * time.Millisecond
78: +	// localRingBlocks and localMinBlockSize size the receive ring of each socket: eight blocks
79: +	// of at least 1 MiB, each larger than the snap length.
80: +	localRingBlocks   = 8
81: +	localMinBlockSize = 1 << 20
82: +	// vlanHeaderLength is the length of the 802.1Q tag put back into frames whose tag the
83: +	// kernel moved out of band.
84: +	vlanHeaderLength = 4
85: +)
86: +
87: +// errReadTimeout is returned by a packet source that has no packet within the poll timeout.
88: +var errReadTimeout = errors.New("no packet within the poll timeout")
89: +
90: +// ExecFunc runs f in the network namespace of a node.
91: +type ExecFunc func(ctx context.Context, f func(ns.NetNS) error) error
92: +
93: +// LocalTarget is one interface of a node on this machine (Docker or Podman) to capture.
94: +type LocalTarget struct {
95: +	// Node is the node name as the topology spells it.
96: +	Node string
97: +	// Interface is the interface name inside the node.
98: +	Interface string
99: +	// Exec runs a function in the node's network namespace.
100: +	Exec ExecFunc
101: +}
102: +
103: +// packetSource reads the packets of one interface.
104: +type packetSource interface {
105: +	// ReadPacket returns the next packet; the data is only valid until the next call. It
106: +	// returns errReadTimeout when no packet arrived within the poll timeout.
107: +	ReadPacket() ([]byte, gopacket.CaptureInfo, error)
108: +	Close()
109: +}
110: +
111: +// openSourcesFunc opens one packet source per interface in the network namespace exec enters.
112: +type openSourcesFunc func(
113: +	ctx context.Context,
114: +	exec ExecFunc,
115: +	interfaces []string,
116: +	snapLength int,
117: +) ([]packetSource, error)
118: +
119: +// CaptureLocal streams pcapng from interfaces of nodes on this machine to w, with the same
120: +// output and end conditions as labruntime.PacketCapturer.Capture: one section, one Interface
121: +// Description Block per target named <node>:<interface>, then the packets of every target in
122: +// timestamp order. targets lists the interfaces of req.Targets, resolved, in the same order.
123: +//
124: +// Each interface is read through a packet socket opened in the node's network namespace, so
125: +// nothing runs in the node and the node image needs no capture tools; it needs CAP_NET_RAW and
126: +// the right to enter the namespace, so root. An interface that goes down is reopened once it is
127: +// up again; one that disappears (its node stopped or was recreated) is reattached when it is
128: +// back, and the time it was gone is reported as a gap through req.OnGap (or logged).
129: +func CaptureLocal(
130: +	ctx context.Context,
131: +	req clablabruntime.CaptureRequest,
132: +	targets []LocalTarget,
133: +	w io.Writer,
134: +) error {
135: +	return localCapture{
136: +		open:           openPacketSockets,
137: +		window:         localReorderWindow,
138: +		reopenInterval: localReopenInterval,
139: +	}.run(ctx, req, targets, w)
140: +}
141: +
142: +// localCapture is a local capture with its socket opener and timings, which tests replace.
143: +type localCapture struct {
144: +	open           openSourcesFunc
145: +	window         time.Duration
146: +	reopenInterval time.Duration
147: +}
148: +
149: +func (l localCapture) run(
150: +	ctx context.Context,
151: +	req clablabruntime.CaptureRequest,
152: +	targets []LocalTarget,
153: +	w io.Writer,
154: +) error {
155: +	if err := ValidateRequest(&req); err != nil {
156: +		return err
157: +	}
158: +	if len(targets) != len(req.Targets) {
159: +		return fmt.Errorf("capture has %d resolved targets for %d requested ones",
160: +			len(targets), len(req.Targets))
161: +	}
162: +
163: +	sources, err := l.openAll(ctx, targets, req.SnapLength)
164: +	if err != nil {
165: +		return err
166: +	}
167: +
168: +	names := make([]string, len(targets))
169: +	for idx, target := range targets {
170: +		names[idx] = target.Node + ":" + target.Interface
171: +	}
172: +
173: +	captureCtx, stop := context.WithCancel(ctx)
174: +	defer stop()
175: +	if req.Duration > 0 {
176: +		var cancelTimeout context.CancelFunc
177: +		captureCtx, cancelTimeout = context.WithTimeout(captureCtx, req.Duration)
178: +		defer cancelTimeout()
179: +	}
180: +
181: +	out, err := NewOutput(w, names, req.SnapLength, req.PacketLimit, l.window, stop)
182: +	if err != nil {
183: +		for _, source := range sources {
184: +			source.Close()
185: +		}
186: +
187: +		return err
188: +	}
189: +
190: +	var wg sync.WaitGroup
191: +	for idx, source := range sources {
192: +		reader := &localReader{
193: +			capture: l,
194: +			out:     out,
195: +			id:      uint32(idx), //nolint:gosec // bounded by the targets
196: +			target:  targets[idx],
197: +			snap:    req.SnapLength,
198: +			onGap:   req.OnGap,
199: +		}
200: +		wg.Go(func() {
201: +			reader.run(captureCtx, source)
202: +		})
203: +	}
204: +	wg.Wait()
205: +
206: +	return out.Close()
207: +}
208: +
209: +// openAll opens the sockets of every target before anything is written, one namespace entry
210: +// per node, so a capture that cannot start fails without output.
211: +func (l localCapture) openAll(
212: +	ctx context.Context,
213: +	targets []LocalTarget,
214: +	snapLength int,
215: +) ([]packetSource, error) {
216: +	type nodeTargets struct {
217: +		exec    ExecFunc
218: +		indexes []int
219: +		names   []string
220: +	}
221: +	var order []string
222: +	byNode := map[string]*nodeTargets{}
223: +	for idx, target := range targets {
224: +		group := byNode[target.Node]
225: +		if group == nil {
226: +			group = &nodeTargets{exec: target.Exec}
227: +			byNode[target.Node] = group
228: +			order = append(order, target.Node)
229: +		}
230: +		group.indexes = append(group.indexes, idx)
231: +		group.names = append(group.names, target.Interface)
232: +	}
233: +
234: +	sources := make([]packetSource, len(targets))
235: +	closeAll := func() {
236: +		for _, source := range sources {
237: +			if source != nil {
238: +				source.Close()
239: +			}
240: +		}
241: +	}
242: +	for _, node := range order {
243: +		group := byNode[node]
244: +		opened, err := l.open(ctx, group.exec, group.names, snapLength)
245: +		if err != nil {
246: +			closeAll()
247: +			return nil, fmt.Errorf("failed to start the capture on node %q: %w", node, err)
248: +		}
249: +		for idx, source := range opened {
250: +			sources[group.indexes[idx]] = source
251: +		}
252: +	}
253: +
254: +	return sources, nil
255: +}
256: +
257: +// localReader reads one interface into the merged stream.
258: +type localReader struct {
259: +	capture localCapture
260: +	out     *Output
261: +	id      uint32
262: +	target  LocalTarget
263: +	snap    int
264: +	onGap   func(clablabruntime.CaptureGap)
265: +}
266: +
267: +func (r *localReader) run(ctx context.Context, source packetSource) {
268: +	defer func() {
269: +		if source != nil {
270: +			source.Close()
271: +		}
272: +	}()
273: +
274: +	for {
275: +		if ctx.Err() != nil {
276: +			r.drain(source, time.Now())
277: +			return
278: +		}
279: +
280: +		data, info, err := source.ReadPacket()
281: +		if errors.Is(err, errReadTimeout) {
282: +			continue
283: +		}
284: +		if err != nil {
285: +			// The socket reports an error once its interface went down or was removed, and
286: +			// keeps reporting it: it is reopened.
287: +			log.Debug("Capture socket failed, reopening it", "node", r.target.Node,
288: +				"interface", r.target.Interface, "error", err)
289: +			source.Close()
290: +			source = r.reopen(ctx)
291: +			if source == nil {
292: +				return
293: +			}
294: +
295: +			continue
296: +		}
297: +
298: +		if more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {
299: +			return
300: +		}
301: +	}
302: +}
303: +
304: +// drain writes the packets that arrived before end but were still in the socket's ring: the
305: +// kernel hands over a ring block once it is full or its block timeout passed, so the last
306: +// packets before a capture ended may not have been read yet.
307: +func (r *localReader) drain(source packetSource, end time.Time) {
308: +	deadline := end.Add(localDrainTimeout)
309: +	for time.Now().Before(deadline) {
310: +		data, info, err := source.ReadPacket()
311: +		if errors.Is(err, errReadTimeout) && time.Since(end) < localDrainQuiet {
312: +			continue
313: +		}
314: +		if err != nil || info.Timestamp.After(end) {
315: +			return
316: +		}
317: +		if more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {
318: +			return
319: +		}
320: +	}
321: +}
322: +
323: +// packet copies a packet out of the socket's ring, cut to the snap length.
324: +func (r *localReader) packet(data []byte, info gopacket.CaptureInfo) *Packet {
325: +	length := info.Length
326: +	for _, ancillary := range info.AncillaryData {
327: +		if _, ok := ancillary.(afpacket.AncillaryVLAN); ok {
328: +			// the tag was put back into the data and counts toward the frame length
329: +			length += vlanHeaderLength
330: +			break
331: +		}
332: +	}
333: +	length = max(length, len(data))
334: +
335: +	captured := make([]byte, min(len(data), r.snap))
336: +	copy(captured, data)
337: +
338: +	return &Packet{
339: +		Timestamp:      info.Timestamp.UnixNano(),
340: +		OriginalLength: uint32(length), //nolint:gosec // bounded by the interface MTU
341: +		Data:           captured,
342: +	}
343: +}
344: +
345: +// reopen opens the interface's socket again once its node and interface are back. It returns
346: +// nil when the capture ended first. Time the interface could not be opened is reported as a gap;
347: +// an interface that only went down is not, as it has no traffic while down.
348: +func (r *localReader) reopen(ctx context.Context) packetSource {
349: +	from := time.Now()
350: +	var unavailable error
351: +
352: +	timer := time.NewTimer(r.capture.reopenInterval)
353: +	defer timer.Stop()
354: +
355: +	for {
356: +		select {
357: +		case <-ctx.Done():
358: +			if unavailable != nil {
359: +				r.reportGap(from, time.Time{}, unavailable)
360: +			}
361: +
362: +			return nil
363: +		case <-timer.C:
364: +		}
365: +
366: +		opened, err := r.capture.open(ctx, r.target.Exec, []string{r.target.Interface}, r.snap)
367: +		if err != nil {
368: +			if unavailable == nil {
369: +				log.Debug("Capture interface is not available, waiting for it",
370: +					"node", r.target.Node, "interface", r.target.Interface, "error", err)
371: +			}
372: +			unavailable = err
373: +			resetTimer(timer, r.capture.reopenInterval)
374: +
375: +			continue
376: +		}
377: +		if unavailable != nil {
378: +			r.reportGap(from, time.Now(), unavailable)
379: +		}
380: +
381: +		return opened[0]
382: +	}
383: +}
384: +
385: +func (r *localReader) reportGap(from, to time.Time, cause error) {
386: +	ReportGap(r.onGap, clablabruntime.CaptureGap{
387: +		Node:       r.target.Node,
388: +		Interfaces: []string{r.target.Interface},
389: +		From:       from,
390: +		To:         to,
391: +		Reason:     fmt.Sprintf("the interface was not available: %v", cause),
392: +	})
393: +}
394: +
395: +// openPacketSockets opens one packet socket per interface in the namespace exec enters. A socket
396: +// stays bound to its interface after the thread left the namespace.
397: +func openPacketSockets(
398: +	ctx context.Context,
399: +	exec ExecFunc,
400: +	interfaces []string,
401: +	snapLength int,
402: +) ([]packetSource, error) {
403: +	sources := make([]packetSource, 0, len(interfaces))
404: +	err := exec(ctx, func(ns.NetNS) error {
405: +		for _, name := range interfaces {
406: +			source, err := openPacketSocket(name, snapLength)
407: +			if err != nil {
408: +				return fmt.Errorf("interface %q: %w", name, err)
409: +			}
410: +			sources = append(sources, source)
411: +		}
412: +
413: +		return nil
414: +	})
415: +	if err != nil {
416: +		for _, source := range sources {
417: +			source.Close()
418: +		}
419: +
420: +		return nil, err
421: +	}
422: +
423: +	return sources, nil
424: +}
425: +
426: +// afpacketSource is a TPACKET_V3 receive ring on one interface.
427: +type afpacketSource struct {
428: +	handle *afpacket.TPacket
429: +}
430: +
431: +func openPacketSocket(name string, snapLength int) (*afpacketSource, error) {
432: +	// A TPACKET_V3 block holds whole frames: it must be larger than the snap length, plus the
433: +	// block and frame headers, and a multiple of the page size.
434: +	pageSize := os.Getpagesize()
435: +	blockSize := max(localMinBlockSize, snapLength+pageSize)
436: +	blockSize = (blockSize + pageSize - 1) / pageSize * pageSize
437: +
438: +	handle, err := afpacket.NewTPacket(
439: +		afpacket.OptInterface(name),
440: +		afpacket.OptTPacketVersion(afpacket.TPacketVersion3),
441: +		afpacket.OptFrameSize(blockSize),
442: +		afpacket.OptBlockSize(blockSize),
443: +		afpacket.OptNumBlocks(localRingBlocks),
444: +		afpacket.OptBlockTimeout(localBlockTimeout),
445: +		afpacket.OptPollTimeout(localPollTimeout),
446: +		// the kernel moves 802.1Q tags out of the frame; captures show them in place
447: +		afpacket.OptAddVLANHeader(true),
448: +	)
449: +	if err != nil {
450: +		return nil, err
451: +	}
452: +	// promiscuous mode is a membership of this socket and ends with it
453: +	if err := handle.SetPromiscuous(true); err != nil {
454: +		handle.Close()
455: +		return nil, fmt.Errorf("failed to enable promiscuous mode: %w", err)
456: +	}
457: +
458: +	return &afpacketSource{handle: handle}, nil
459: +}
460: +
461: +func (s *afpacketSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {
462: +	data, info, err := s.handle.ZeroCopyReadPacketData()
463: +	if errors.Is(err, afpacket.ErrTimeout) {
464: +		return nil, info, errReadTimeout
465: +	}
466: +
467: +	return data, info, err
468: +}
469: +
470: +func (s *afpacketSource) Close() {
471: +	s.handle.Close()
472: +}
473: diff --git a/capture/local_test.go b/capture/local_test.go
474: new file mode 100644
475: index 0000000..f91bb00
476: --- /dev/null
477: +++ b/capture/local_test.go
478: @@ -0,0 +1,476 @@
479: +package capture
480: +
481: +import (
482: +	"bytes"
483: +	"context"
484: +	"errors"
485: +	"fmt"
486: +	"io"
487: +	"slices"
488: +	"strings"
489: +	"sync"
490: +	"testing"
491: +	"time"
492: +
493: +	"github.com/containernetworking/plugins/pkg/ns"
494: +	"github.com/gopacket/gopacket"
495: +	"github.com/gopacket/gopacket/afpacket"
496: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
497: +)
498: +
499: +// fakeFrame is one packet a fake source returns.
500: +type fakeFrame struct {
501: +	data   []byte
502: +	stamp  time.Time
503: +	length int
504: +	vlan   bool
505: +	// visible delays the frame like a ring block the kernel has not handed over yet.
506: +	visible time.Time
507: +	// err ends the source with this error instead of a packet.
508: +	err error
509: +}
510: +
511: +// fakeSource returns frames from a channel, errReadTimeout while none is queued.
512: +type fakeSource struct {
513: +	frames  chan fakeFrame
514: +	closed  chan struct{}
515: +	once    sync.Once
516: +	pending *fakeFrame
517: +}
518: +
519: +func newFakeSource() *fakeSource {
520: +	return &fakeSource{frames: make(chan fakeFrame, 64), closed: make(chan struct{})}
521: +}
522: +
523: +func (s *fakeSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {
524: +	if s.pending == nil {
525: +		select {
526: +		case frame := <-s.frames:
527: +			s.pending = &frame
528: +		case <-time.After(5 * time.Millisecond):
529: +			return nil, gopacket.CaptureInfo{}, errReadTimeout
530: +		}
531: +	}
532: +	if wait := time.Until(s.pending.visible); wait > 0 {
533: +		time.Sleep(min(wait, 5*time.Millisecond))
534: +		if time.Now().Before(s.pending.visible) {
535: +			return nil, gopacket.CaptureInfo{}, errReadTimeout
536: +		}
537: +	}
538: +
539: +	{
540: +		frame := *s.pending
541: +		s.pending = nil
542: +		if frame.err != nil {
543: +			return nil, gopacket.CaptureInfo{}, frame.err
544: +		}
545: +		info := gopacket.CaptureInfo{
546: +			Timestamp: frame.stamp, CaptureLength: len(frame.data), Length: frame.length,
547: +		}
548: +		if frame.vlan {
549: +			info.AncillaryData = []any{afpacket.AncillaryVLAN{VLAN: 10}}
550: +		}
551: +
552: +		return frame.data, info, nil
553: +	}
554: +}
555: +
556: +func (s *fakeSource) Close() {
557: +	s.once.Do(func() { close(s.closed) })
558: +}
559: +
560: +// fakeHost hands out fake sources per node and interface. Opening an interface listed in
561: +// missing fails, like an interface whose node does not run.
562: +type fakeHost struct {
563: +	mu      sync.Mutex
564: +	opened  map[string][]*fakeSource
565: +	missing map[string]bool
566: +	ready   chan string
567: +}
568: +
569: +func newFakeHost() *fakeHost {
570: +	return &fakeHost{
571: +		opened: map[string][]*fakeSource{}, missing: map[string]bool{},
572: +		ready: make(chan string, 64),
573: +	}
574: +}
575: +
576: +func (h *fakeHost) exec(node string) ExecFunc {
577: +	return func(_ context.Context, f func(ns.NetNS) error) error {
578: +		h.mu.Lock()
579: +		missing := h.missing[node]
580: +		h.mu.Unlock()
581: +		if missing {
582: +			return fmt.Errorf("node %q: container network namespace is not available", node)
583: +		}
584: +
585: +		return f(nil)
586: +	}
587: +}
588: +
589: +func (h *fakeHost) open(
590: +	ctx context.Context,
591: +	exec ExecFunc,
592: +	interfaces []string,
593: +	_ int,
594: +) ([]packetSource, error) {
595: +	var node string
596: +	err := exec(ctx, func(ns.NetNS) error { return nil })
597: +	if err != nil {
598: +		return nil, err
599: +	}
600: +
601: +	h.mu.Lock()
602: +	defer h.mu.Unlock()
603: +	sources := make([]packetSource, 0, len(interfaces))
604: +	for _, name := range interfaces {
605: +		if h.missing[name] {
606: +			return nil, fmt.Errorf("interface %q: no such network interface", name)
607: +		}
608: +		node = name
609: +		source := newFakeSource()
610: +		h.opened[name] = append(h.opened[name], source)
611: +		sources = append(sources, source)
612: +		h.ready <- node
613: +	}
614: +
615: +	return sources, nil
616: +}
617: +
618: +func (h *fakeHost) source(name string, generation int) *fakeSource {
619: +	h.mu.Lock()
620: +	defer h.mu.Unlock()
621: +
622: +	return h.opened[name][generation]
623: +}
624: +
625: +func (h *fakeHost) setMissing(name string, missing bool) {
626: +	h.mu.Lock()
627: +	defer h.mu.Unlock()
628: +	h.missing[name] = missing
629: +}
630: +
631: +func (h *fakeHost) capture() localCapture {
632: +	return localCapture{
633: +		open:           h.open,
634: +		window:         20 * time.Millisecond,
635: +		reopenInterval: time.Millisecond,
636: +	}
637: +}
638: +
639: +// waitOpened waits until n sources were opened.
640: +func (h *fakeHost) waitOpened(t *testing.T, n int) {
641: +	t.Helper()
642: +	for range n {
643: +		select {
644: +		case <-h.ready:
645: +		case <-time.After(2 * time.Second):
646: +			t.Fatal("source was not opened")
647: +		}
648: +	}
649: +}
650: +
651: +type parsedLocalCapture struct {
652: +	interfaces []string
653: +	packets    []Packet
654: +}
655: +
656: +func parseLocalCapture(t *testing.T, data []byte) parsedLocalCapture {
657: +	t.Helper()
658: +
659: +	var parsed parsedLocalCapture
660: +	reader := NewReader(bytes.NewReader(data))
661: +	for {
662: +		event, err := reader.Next()
663: +		if errors.Is(err, io.EOF) {
664: +			break
665: +		}
666: +		if err != nil {
667: +			t.Fatalf("invalid capture: %v", err)
668: +		}
669: +		if event.Interface != nil {
670: +			parsed.interfaces = append(parsed.interfaces, event.Interface.Name)
671: +		}
672: +		if event.Packet != nil {
673: +			parsed.packets = append(parsed.packets, *event.Packet)
674: +		}
675: +	}
676: +	if reader.Sections() != 1 {
677: +		t.Fatalf("capture has %d sections", reader.Sections())
678: +	}
679: +
680: +	return parsed
681: +}
682: +
683: +func localRequest(packetLimit int, duration time.Duration) clablabruntime.CaptureRequest {
684: +	return clablabruntime.CaptureRequest{
685: +		Name: "lab",
686: +		Targets: []clablabruntime.CaptureTarget{
687: +			{Node: "r1", Interface: "eth1"}, {Node: "r2", Interface: "eth1"},
688: +		},
689: +		PacketLimit: packetLimit,
690: +		Duration:    duration,
691: +		SnapLength:  64,
692: +	}
693: +}
694: +
695: +func TestCaptureLocalMergesInterfacesInTimestampOrder(t *testing.T) {
696: +	t.Parallel()
697: +
698: +	host := newFakeHost()
699: +	// the sources are keyed by interface name in the fake host, so the two nodes use distinct
700: +	// names behind the requested ones
701: +	targets := []LocalTarget{
702: +		{Node: "r1", Interface: "e1", Exec: host.exec("r1")},
703: +		{Node: "r2", Interface: "e2", Exec: host.exec("r2")},
704: +	}
705: +
706: +	var out bytes.Buffer
707: +	done := make(chan error, 1)
708: +	go func() {
709: +		done <- host.capture().run(context.Background(), localRequest(4, 0), targets, &out)
710: +	}()
711: +	host.waitOpened(t, 2)
712: +
713: +	base := time.Unix(1_761_559_200, 0)
714: +	// r2's packets reach containerlab first although r1 stamped one of them earlier
715: +	host.source("e2", 0).frames <- fakeFrame{
716: +		data: []byte("r2-a"), stamp: base.Add(2 * time.Millisecond), length: 4,
717: +	}
718: +	host.source("e2", 0).frames <- fakeFrame{
719: +		data: bytes.Repeat([]byte{7}, 100), stamp: base.Add(4 * time.Millisecond), length: 100,
720: +	}
721: +	host.source("e1", 0).frames <- fakeFrame{
722: +		data: []byte("r1-a"), stamp: base.Add(1 * time.Millisecond), length: 4,
723: +	}
724: +	host.source("e1", 0).frames <- fakeFrame{
725: +		data: []byte("r1-v"), stamp: base.Add(3 * time.Millisecond), length: 60, vlan: true,
726: +	}
727: +
728: +	select {
729: +	case err := <-done:
730: +		if err != nil {
731: +			t.Fatal(err)
732: +		}
733: +	case <-time.After(5 * time.Second):
734: +		t.Fatal("capture did not stop at the packet limit")
735: +	}
736: +
737: +	parsed := parseLocalCapture(t, out.Bytes())
738: +	if want := []string{"r1:e1", "r2:e2"}; !slices.Equal(parsed.interfaces, want) {
739: +		t.Fatalf("interfaces = %v, want %v", parsed.interfaces, want)
740: +	}
741: +	if len(parsed.packets) != 4 {
742: +		t.Fatalf("captured %d packets, want 4", len(parsed.packets))
743: +	}
744: +	var ids []uint32
745: +	for idx, packet := range parsed.packets {
746: +		ids = append(ids, packet.InterfaceID)
747: +		if want := base.Add(time.Duration(idx+1) * time.Millisecond).
748: +			UnixNano(); packet.Timestamp != want {
749: +			t.Fatalf("packet %d stamped %d, want %d", idx, packet.Timestamp, want)
750: +		}
751: +	}
752: +	if !slices.Equal(ids, []uint32{0, 1, 0, 1}) {
753: +		t.Fatalf("interface IDs = %v", ids)
754: +	}
755: +	// a re-inserted VLAN tag counts toward the frame length
756: +	if parsed.packets[2].OriginalLength != 64 {
757: +		t.Fatalf("VLAN frame length = %d, want 64", parsed.packets[2].OriginalLength)
758: +	}
759: +	// frames are cut to the snap length
760: +	if last := parsed.packets[3]; len(last.Data) != 64 || last.OriginalLength != 100 {
761: +		t.Fatalf("long frame kept %d of %d bytes", len(last.Data), last.OriginalLength)
762: +	}
763: +	for _, name := range []string{"e1", "e2"} {
764: +		select {
765: +		case <-host.source(name, 0).closed:
766: +		default:
767: +			t.Fatalf("source %s was not closed", name)
768: +		}
769: +	}
770: +}
771: +
772: +func TestCaptureLocalEndsAfterTheDurationOrWhenCanceled(t *testing.T) {
773: +	t.Parallel()
774: +
775: +	host := newFakeHost()
776: +	targets := []LocalTarget{
777: +		{Node: "r1", Interface: "e1", Exec: host.exec("r1")},
778: +		{Node: "r1", Interface: "e2", Exec: host.exec("r1")},
779: +	}
780: +
781: +	var out bytes.Buffer
782: +	start := time.Now()
783: +	if err := host.capture().run(context.Background(), localRequest(0, 50*time.Millisecond),
784: +		targets, &out); err != nil {
785: +		t.Fatal(err)
786: +	}
787: +	if elapsed := time.Since(start); elapsed < 50*time.Millisecond || elapsed > 2*time.Second {
788: +		t.Fatalf("capture ran %s for a 50ms duration", elapsed)
789: +	}
790: +	if parsed := parseLocalCapture(t, out.Bytes()); len(parsed.interfaces) != 2 {
791: +		t.Fatalf("interfaces = %v", parsed.interfaces)
792: +	}
793: +
794: +	ctx, cancel := context.WithCancel(context.Background())
795: +	done := make(chan error, 1)
796: +	go func() {
797: +		done <- host.capture().run(ctx, localRequest(0, 0), targets, io.Discard)
798: +	}()
799: +	host.waitOpened(t, 4)
800: +	cancel()
801: +	select {
802: +	case err := <-done:
803: +		if err != nil {
804: +			t.Fatalf("canceled capture returned %v", err)
805: +		}
806: +	case <-time.After(2 * time.Second):
807: +		t.Fatal("canceled capture did not end")
808: +	}
809: +}
810: +
811: +func TestCaptureLocalWritesPacketsStillInTheRingWhenItEnds(t *testing.T) {
812: +	t.Parallel()
813: +
814: +	host := newFakeHost()
815: +	targets := []LocalTarget{{Node: "r1", Interface: "e1", Exec: host.exec("r1")}}
816: +	req := localRequest(0, 0)
817: +	req.Targets = req.Targets[:1]
818: +
819: +	ctx, cancel := context.WithCancel(context.Background())
820: +	var out bytes.Buffer
821: +	done := make(chan error, 1)
822: +	go func() {
823: +		done <- host.capture().run(ctx, req, targets, &out)
824: +	}()
825: +	host.waitOpened(t, 1)
826: +
827: +	now := time.Now()
828: +	// stamped before the end, handed over by the kernel only after it
829: +	host.source("e1", 0).frames <- fakeFrame{
830: +		data: []byte("before"), stamp: now, length: 6, visible: now.Add(30 * time.Millisecond),
831: +	}
832: +	// stamped after the end: not part of the capture
833: +	host.source("e1", 0).frames <- fakeFrame{
834: +		data: []byte("after"), stamp: now.Add(time.Hour), length: 5,
835: +		visible: now.Add(40 * time.Millisecond),
836: +	}
837: +	cancel()
838: +
839: +	if err := <-done; err != nil {
840: +		t.Fatal(err)
841: +	}
842: +	parsed := parseLocalCapture(t, out.Bytes())
843: +	if len(parsed.packets) != 1 || string(parsed.packets[0].Data) != "before" {
844: +		t.Fatalf("packets = %+v, want only the one stamped before the end", parsed.packets)
845: +	}
846: +}
847: +
848: +func TestCaptureLocalFailsWithoutOutputWhenAnInterfaceCannotBeOpened(t *testing.T) {
849: +	t.Parallel()
850: +
851: +	host := newFakeHost()
852: +	host.setMissing("r2", true)
853: +	targets := []LocalTarget{
854: +		{Node: "r1", Interface: "e1", Exec: host.exec("r1")},
855: +		{Node: "r2", Interface: "e2", Exec: host.exec("r2")},
856: +	}
857: +
858: +	var out bytes.Buffer
859: +	err := host.capture().run(context.Background(), localRequest(0, 0), targets, &out)
860: +	if err == nil || !strings.Contains(err.Error(), `failed to start the capture on node "r2"`) {
861: +		t.Fatalf("error = %v", err)
862: +	}
863: +	if out.Len() != 0 {
864: +		t.Fatalf("wrote %d bytes before failing", out.Len())
865: +	}
866: +	select {
867: +	case <-host.source("e1", 0).closed:
868: +	default:
869: +		t.Fatal("the source opened before the failure was not closed")
870: +	}
871: +}
872: +
873: +func TestCaptureLocalReopensInterfacesAndReportsWhileTheyWereGone(t *testing.T) {
874: +	t.Parallel()
875: +
876: +	host := newFakeHost()
877: +	targets := []LocalTarget{{Node: "r1", Interface: "e1", Exec: host.exec("r1")}}
878: +	req := localRequest(2, 0)
879: +	req.Targets = req.Targets[:1]
880: +
881: +	var mu sync.Mutex
882: +	var gaps []clablabruntime.CaptureGap
883: +	req.OnGap = func(gap clablabruntime.CaptureGap) {
884: +		mu.Lock()
885: +		defer mu.Unlock()
886: +		gaps = append(gaps, gap)
887: +	}
888: +
889: +	var out bytes.Buffer
890: +	done := make(chan error, 1)
891: +	go func() {
892: +		done <- host.capture().run(context.Background(), req, targets, &out)
893: +	}()
894: +	host.waitOpened(t, 1)
895: +
896: +	base := time.Unix(1_761_559_200, 0)
897: +	host.source("e1", 0).frames <- fakeFrame{data: []byte("a"), stamp: base, length: 1}
898: +
899: +	// the interface goes down: the socket fails and is reopened at once, without a gap
900: +	host.source("e1", 0).frames <- fakeFrame{err: afpacket.ErrPoll}
901: +	host.waitOpened(t, 1)
902: +
903: +	// the node restarts: the interface is gone for a while, then back
904: +	host.setMissing("r1", true)
905: +	host.source("e1", 1).frames <- fakeFrame{err: afpacket.ErrPoll}
906: +	time.Sleep(20 * time.Millisecond)
907: +	host.setMissing("r1", false)
908: +	host.waitOpened(t, 1)
909: +	host.source("e1", 2).frames <- fakeFrame{
910: +		data: []byte("b"), stamp: base.Add(time.Second), length: 1,
911: +	}
912: +
913: +	select {
914: +	case err := <-done:
915: +		if err != nil {
916: +			t.Fatal(err)
917: +		}
918: +	case <-time.After(5 * time.Second):
919: +		t.Fatal("capture did not stop at the packet limit")
920: +	}
921: +
922: +	if parsed := parseLocalCapture(t, out.Bytes()); len(parsed.packets) != 2 {
923: +		t.Fatalf("captured %d packets across the reopen, want 2", len(parsed.packets))
924: +	}
925: +	mu.Lock()
926: +	defer mu.Unlock()
927: +	if len(gaps) != 1 {
928: +		t.Fatalf("gaps = %+v, want one for the restart", gaps)
929: +	}
930: +	gap := gaps[0]
931: +	if gap.Node != "r1" || !slices.Equal(gap.Interfaces, []string{"e1"}) || gap.To.IsZero() ||
932: +		!gap.To.After(gap.From) || !strings.Contains(gap.Reason, "not available") {
933: +		t.Fatalf("gap = %+v", gap)
934: +	}
935: +}
936: +
937: +func TestCaptureLocalChecksTheRequest(t *testing.T) {
938: +	t.Parallel()
939: +
940: +	host := newFakeHost()
941: +	targets := []LocalTarget{{Node: "r1", Interface: "e1", Exec: host.exec("r1")}}
942: +
943: +	req := localRequest(0, 0)
944: +	req.SnapLength = 10
945: +	if err := host.capture().run(context.Background(), req, targets[:1], io.Discard); err == nil ||
946: +		!strings.Contains(err.Error(), "snap length 10") {
947: +		t.Fatalf("small snap length: error = %v", err)
948: +	}
949: +
950: +	if err := host.capture().run(context.Background(), localRequest(0, 0), targets,
951: +		io.Discard); err == nil || !strings.Contains(err.Error(), "1 resolved targets for 2") {
952: +		t.Fatalf("target mismatch: error = %v", err)
953: +	}
954: +}
955: diff --git a/capture/output.go b/capture/output.go
956: new file mode 100644
957: index 0000000..574c33a
958: --- /dev/null
959: +++ b/capture/output.go
960: @@ -0,0 +1,203 @@
961: +package capture
962: +
963: +import (
964: +	"context"
965: +	"fmt"
966: +	"io"
967: +	"strings"
968: +	"sync/atomic"
969: +	"time"
970: +
971: +	"github.com/charmbracelet/log"
972: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
973: +)
974: +
975: +// Snap length bounds of a capture.
976: +const (
977: +	// DefaultSnapLength is the snap length of a request without one.
978: +	DefaultSnapLength = 256 << 10
979: +	MinSnapLength     = 64
980: +	MaxSnapLength     = 1 << 20
981: +)
982: +
983: +// ValidateRequest checks the bounds of a capture request and fills the default snap length.
984: +func ValidateRequest(req *clablabruntime.CaptureRequest) error {
985: +	if req.Name == "" {
986: +		return fmt.Errorf("topology name is required")
987: +	}
988: +	if len(req.Targets) == 0 {
989: +		return fmt.Errorf("at least one capture target (node and interface) is required")
990: +	}
991: +	for _, target := range req.Targets {
992: +		if target.Node == "" || target.Interface == "" {
993: +			return fmt.Errorf("capture target %+v needs a node and an interface", target)
994: +		}
995: +	}
996: +	if req.Duration < 0 {
997: +		return fmt.Errorf("capture duration must not be negative")
998: +	}
999: +	if req.PacketLimit < 0 {
1000: +		return fmt.Errorf("capture packet limit must not be negative")
1001: +	}
1002: +	if req.SnapLength == 0 {
1003: +		req.SnapLength = DefaultSnapLength
1004: +	}
1005: +	if req.SnapLength < MinSnapLength || req.SnapLength > MaxSnapLength {
1006: +		return fmt.Errorf("capture snap length %d is outside %d to %d bytes", req.SnapLength,
1007: +			MinSnapLength, MaxSnapLength)
1008: +	}
1009: +
1010: +	return nil
1011: +}
1012: +
1013: +// FindInterface matches a requested interface by its name, then by its alias.
1014: +func FindInterface(
1015: +	entries []clablabruntime.CaptureInterface,
1016: +	name string,
1017: +) (clablabruntime.CaptureInterface, bool) {
1018: +	for _, entry := range entries {
1019: +		if entry.Interface == name {
1020: +			return entry, true
1021: +		}
1022: +	}
1023: +	for _, entry := range entries {
1024: +		if entry.Alias != "" && entry.Alias == name {
1025: +			return entry, true
1026: +		}
1027: +	}
1028: +
1029: +	return clablabruntime.CaptureInterface{}, false
1030: +}
1031: +
1032: +// DescribeInterfaces lists interfaces for an error message: name (alias), ...
1033: +func DescribeInterfaces(entries []clablabruntime.CaptureInterface) string {
1034: +	if len(entries) == 0 {
1035: +		return "none"
1036: +	}
1037: +
1038: +	names := make([]string, 0, len(entries))
1039: +	for _, entry := range entries {
1040: +		name := entry.Interface
1041: +		if entry.Alias != "" {
1042: +			name += " (" + entry.Alias + ")"
1043: +		}
1044: +		names = append(names, name)
1045: +	}
1046: +
1047: +	return strings.Join(names, ", ")
1048: +}
1049: +
1050: +// ReportGap hands a gap to onGap, or logs it as a warning when onGap is nil.
1051: +func ReportGap(onGap func(clablabruntime.CaptureGap), gap clablabruntime.CaptureGap) {
1052: +	if onGap != nil {
1053: +		onGap(gap)
1054: +		return
1055: +	}
1056: +
1057: +	to := "unknown"
1058: +	if !gap.To.IsZero() {
1059: +		to = gap.To.Format(time.RFC3339Nano)
1060: +	}
1061: +	log.Warn("Capture has a gap", "node", gap.Node, "interfaces", strings.Join(gap.Interfaces, ","),
1062: +		"from", gap.From.Format(time.RFC3339Nano), "to", to, "reason", gap.Reason)
1063: +}
1064: +
1065: +// Output is the merged pcapng stream of one capture: the section header with one interface per
1066: +// capture target, then the packets of every target in timestamp order (through a Reorder), up
1067: +// to an optional packet limit.
1068: +type Output struct {
1069: +	writer  *Writer
1070: +	reorder *Reorder
1071: +	limit   int64
1072: +	written atomic.Int64
1073: +	stop    func()
1074: +
1075: +	cancelRun context.CancelFunc
1076: +	runDone   chan struct{}
1077: +}
1078: +
1079: +// NewOutput writes the section header and one Interface Description Block per name to w, then
1080: +// starts the reorder buffer with the given window (zero or less writes packets as they come).
1081: +// stop is called once the packet limit is reached or a write failed. Close must be called.
1082: +func NewOutput(
1083: +	w io.Writer,
1084: +	names []string,
1085: +	snapLength, packetLimit int,
1086: +	window time.Duration,
1087: +	stop func(),
1088: +) (*Output, error) {
1089: +	writer := NewWriter(w)
1090: +	if err := writer.WriteHeader(
1091: +		names,
1092: +		uint32(snapLength),
1093: +	); err != nil { //nolint:gosec // validated
1094: +		return nil, err
1095: +	}
1096: +
1097: +	out := &Output{
1098: +		writer:  writer,
1099: +		reorder: NewReorder(window, writer.WritePacket, stop),
1100: +		limit:   int64(packetLimit),
1101: +		stop:    stop,
1102: +		runDone: make(chan struct{}),
1103: +	}
1104: +
1105: +	var runCtx context.Context
1106: +	runCtx, out.cancelRun = context.WithCancel(context.Background())
1107: +	go func() {
1108: +		defer close(out.runDone)
1109: +		out.reorder.Run(runCtx)
1110: +	}()
1111: +
1112: +	return out, nil
1113: +}
1114: +
1115: +// Emit hands a packet of the interface with the given index to the stream. It reports false
1116: +// once the packet limit is reached and the capture stops, and returns the error of a failed
1117: +// write.
1118: +func (o *Output) Emit(id uint32, packet *Packet) (bool, error) {
1119: +	if o.limit > 0 {
1120: +		count := o.written.Add(1)
1121: +		if count > o.limit {
1122: +			o.stop()
1123: +			return false, nil
1124: +		}
1125: +		if err := o.reorder.Push(id, packet); err != nil {
1126: +			return false, err
1127: +		}
1128: +		if count == o.limit {
1129: +			o.stop()
1130: +			return false, nil
1131: +		}
1132: +
1133: +		return true, nil
1134: +	}
1135: +
1136: +	o.written.Add(1)
1137: +
1138: +	return true, o.reorder.Push(id, packet)
1139: +}
1140: +
1141: +// Written returns the number of packets handed to the stream so far.
1142: +func (o *Output) Written() int64 {
1143: +	return o.written.Load()
1144: +}
1145: +
1146: +// Hold keeps packets stamped after timestamp back until Release(key).
1147: +func (o *Output) Hold(key any, timestamp int64) {
1148: +	o.reorder.Hold(key, timestamp)
1149: +}
1150: +
1151: +// Release removes the hold of key.
1152: +func (o *Output) Release(key any) {
1153: +	o.reorder.Release(key)
1154: +}
1155: +
1156: +// Close writes the packets still held back and returns the first write error.
1157: +func (o *Output) Close() error {
1158: +	o.cancelRun()
1159: +	<-o.runDone
1160: +	o.reorder.Flush()
1161: +
1162: +	return o.writer.Err()
1163: +}
1164: diff --git a/capture/pcapng.go b/capture/pcapng.go
1165: new file mode 100644
1166: index 0000000..246ac84
1167: --- /dev/null
1168: +++ b/capture/pcapng.go
1169: @@ -0,0 +1,333 @@
1170: +// Package capture writes the pcapng streams of `containerlab capture`: one section with one
1171: +// interface per capture target, packets merged across targets in timestamp order. The local
1172: +// capturer reads lab link interfaces of Docker and Podman nodes through packet sockets; the c9s
1173: +// lab runtime feeds the same writer from clabwire streams.
1174: +package capture
1175: +
1176: +import (
1177: +	"bufio"
1178: +	"encoding/binary"
1179: +	"errors"
1180: +	"fmt"
1181: +	"io"
1182: +	"math"
1183: +	"sync"
1184: +)
1185: +
1186: +// pcapng block layout (https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html). clabwire
1187: +// writes little-endian sections, and so does the merged stream containerlab writes.
1188: +const (
1189: +	pcapngSectionHeaderType  = 0x0a0d0d0a
1190: +	pcapngInterfaceType      = 0x00000001
1191: +	pcapngEnhancedPacketType = 0x00000006
1192: +	pcapngByteOrderMagic     = 0x1a2b3c4d
1193: +	pcapngOptionEnd          = 0
1194: +	pcapngOptionUserAppl     = 4
1195: +	pcapngOptionIfName       = 2
1196: +	pcapngOptionIfTSResol    = 9
1197: +	pcapngLinkTypeEthernet   = 1
1198: +	// pcapngNanoseconds is the if_tsresol value for 10^-9 s resolution.
1199: +	pcapngNanoseconds = 9
1200: +	// pcapngMaxBlockLength bounds a block read from a capture stream: a packet of the largest
1201: +	// clabwire snap length (1 MiB) plus framing.
1202: +	pcapngMaxBlockLength = 1<<20 + 1024
1203: +	// captureUserApplication names the writer in the merged section header.
1204: +	captureUserApplication = "containerlab"
1205: +)
1206: +
1207: +var errPCAPNGByteOrder = errors.New("pcapng section is not little-endian")
1208: +
1209: +// InterfaceDescription is an Interface Description Block.
1210: +type InterfaceDescription struct {
1211: +	LinkType   uint16
1212: +	SnapLength uint32
1213: +	Name       string
1214: +	// TSResol is the raw if_tsresol value; 6 (microseconds) when the block has none.
1215: +	TSResol byte
1216: +}
1217: +
1218: +// Packet is an Enhanced Packet Block with its timestamp in nanoseconds.
1219: +type Packet struct {
1220: +	InterfaceID    uint32
1221: +	Timestamp      int64
1222: +	OriginalLength uint32
1223: +	Data           []byte
1224: +}
1225: +
1226: +// Reader reads the blocks of a pcapng stream as clabwire writes it: one or more
1227: +// little-endian sections, each with its Interface Description Blocks before its packets.
1228: +type Reader struct {
1229: +	r          *bufio.Reader
1230: +	interfaces []InterfaceDescription
1231: +	// sections counts the Section Header Blocks read so far.
1232: +	sections int
1233: +}
1234: +
1235: +// NewReader returns a reader of the pcapng stream r.
1236: +func NewReader(r io.Reader) *Reader {
1237: +	return &Reader{r: bufio.NewReaderSize(r, 64<<10)}
1238: +}
1239: +
1240: +// Sections returns the number of Section Header Blocks read so far.
1241: +func (p *Reader) Sections() int {
1242: +	return p.sections
1243: +}
1244: +
1245: +// Event is one block of interest: a new interface or a packet.
1246: +type Event struct {
1247: +	Interface *InterfaceDescription
1248: +	Packet    *Packet
1249: +}
1250: +
1251: +// Next returns the next interface or packet, skipping other block types. It returns io.EOF at
1252: +// the clean end of the stream, and io.ErrUnexpectedEOF for a stream cut inside a block.
1253: +func (p *Reader) Next() (Event, error) {
1254: +	for {
1255: +		var header [8]byte
1256: +		if _, err := io.ReadFull(p.r, header[:]); err != nil {
1257: +			if errors.Is(err, io.EOF) {
1258: +				return Event{}, io.EOF
1259: +			}
1260: +
1261: +			return Event{}, io.ErrUnexpectedEOF
1262: +		}
1263: +
1264: +		blockType := binary.LittleEndian.Uint32(header[0:4])
1265: +		length := binary.LittleEndian.Uint32(header[4:8])
1266: +		if blockType == pcapngSectionHeaderType {
1267: +			// the byte-order magic tells a big-endian section apart before its length is
1268: +			// trusted: that length reads byte swapped
1269: +			magic, err := p.r.Peek(4)
1270: +			if err != nil {
1271: +				return Event{}, io.ErrUnexpectedEOF
1272: +			}
1273: +			if binary.BigEndian.Uint32(magic) == pcapngByteOrderMagic {
1274: +				return Event{}, errPCAPNGByteOrder
1275: +			}
1276: +		}
1277: +		if length < 12 || length%4 != 0 || length > pcapngMaxBlockLength {
1278: +			return Event{}, fmt.Errorf("invalid pcapng block length %d (at most %d)", length,
1279: +				pcapngMaxBlockLength)
1280: +		}
1281: +
1282: +		body := make([]byte, length-8)
1283: +		if _, err := io.ReadFull(p.r, body); err != nil {
1284: +			return Event{}, io.ErrUnexpectedEOF
1285: +		}
1286: +		if binary.LittleEndian.Uint32(body[len(body)-4:]) != length {
1287: +			return Event{}, fmt.Errorf("pcapng block lengths do not match")
1288: +		}
1289: +		body = body[:len(body)-4]
1290: +
1291: +		switch blockType {
1292: +		case pcapngSectionHeaderType:
1293: +			if len(body) < 16 {
1294: +				return Event{}, fmt.Errorf("short pcapng section header")
1295: +			}
1296: +			if binary.LittleEndian.Uint32(body[0:4]) != pcapngByteOrderMagic {
1297: +				return Event{}, errPCAPNGByteOrder
1298: +			}
1299: +			p.sections++
1300: +			p.interfaces = nil
1301: +		case pcapngInterfaceType:
1302: +			if p.sections == 0 {
1303: +				return Event{}, fmt.Errorf("pcapng interface before a section header")
1304: +			}
1305: +			intf, err := parsePCAPNGInterface(body)
1306: +			if err != nil {
1307: +				return Event{}, err
1308: +			}
1309: +			p.interfaces = append(p.interfaces, intf)
1310: +
1311: +			return Event{Interface: &p.interfaces[len(p.interfaces)-1]}, nil
1312: +		case pcapngEnhancedPacketType:
1313: +			packet, err := p.parsePacket(body)
1314: +			if err != nil {
1315: +				return Event{}, err
1316: +			}
1317: +
1318: +			return Event{Packet: &packet}, nil
1319: +		}
1320: +	}
1321: +}
1322: +
1323: +func parsePCAPNGInterface(body []byte) (InterfaceDescription, error) {
1324: +	if len(body) < 8 {
1325: +		return InterfaceDescription{}, fmt.Errorf("short pcapng interface description")
1326: +	}
1327: +	intf := InterfaceDescription{
1328: +		LinkType:   binary.LittleEndian.Uint16(body[0:2]),
1329: +		SnapLength: binary.LittleEndian.Uint32(body[4:8]),
1330: +		TSResol:    6,
1331: +	}
1332: +
1333: +	options := body[8:]
1334: +	for len(options) >= 4 {
1335: +		code := binary.LittleEndian.Uint16(options[0:2])
1336: +		size := int(binary.LittleEndian.Uint16(options[2:4]))
1337: +		if code == pcapngOptionEnd {
1338: +			break
1339: +		}
1340: +		padded := size + pcapngPadding(size)
1341: +		if 4+padded > len(options) {
1342: +			return InterfaceDescription{}, fmt.Errorf("truncated pcapng interface option")
1343: +		}
1344: +		value := options[4 : 4+size]
1345: +		switch code {
1346: +		case pcapngOptionIfName:
1347: +			intf.Name = string(value)
1348: +		case pcapngOptionIfTSResol:
1349: +			if size == 1 {
1350: +				intf.TSResol = value[0]
1351: +			}
1352: +		}
1353: +		options = options[4+padded:]
1354: +	}
1355: +
1356: +	return intf, nil
1357: +}
1358: +
1359: +func (p *Reader) parsePacket(body []byte) (Packet, error) {
1360: +	if len(body) < 20 {
1361: +		return Packet{}, fmt.Errorf("short pcapng enhanced packet")
1362: +	}
1363: +	packet := Packet{
1364: +		InterfaceID:    binary.LittleEndian.Uint32(body[0:4]),
1365: +		OriginalLength: binary.LittleEndian.Uint32(body[16:20]),
1366: +	}
1367: +	if int(packet.InterfaceID) >= len(p.interfaces) {
1368: +		return Packet{}, fmt.Errorf("pcapng packet for undeclared interface %d",
1369: +			packet.InterfaceID)
1370: +	}
1371: +	captured := binary.LittleEndian.Uint32(body[12:16])
1372: +	if int(captured) > len(body)-20 {
1373: +		return Packet{}, fmt.Errorf("pcapng packet data exceeds its block")
1374: +	}
1375: +	packet.Data = body[20 : 20+captured]
1376: +
1377: +	raw := uint64(binary.LittleEndian.Uint32(body[4:8]))<<32 |
1378: +		uint64(binary.LittleEndian.Uint32(body[8:12]))
1379: +	timestamp, err := pcapngNanosecondsFrom(raw, p.interfaces[packet.InterfaceID].TSResol)
1380: +	if err != nil {
1381: +		return Packet{}, err
1382: +	}
1383: +	packet.Timestamp = timestamp
1384: +
1385: +	return packet, nil
1386: +}
1387: +
1388: +// pcapngNanosecondsFrom converts a timestamp in an interface's resolution to nanoseconds.
1389: +// Only decimal resolutions up to nanoseconds occur in clabwire streams.
1390: +func pcapngNanosecondsFrom(raw uint64, tsresol byte) (int64, error) {
1391: +	if tsresol&0x80 != 0 || tsresol > pcapngNanoseconds {
1392: +		return 0, fmt.Errorf("unsupported pcapng timestamp resolution %#x", tsresol)
1393: +	}
1394: +	scale := uint64(1)
1395: +	for range pcapngNanoseconds - int(tsresol) {
1396: +		scale *= 10
1397: +	}
1398: +	if raw > math.MaxInt64/scale {
1399: +		return 0, fmt.Errorf("pcapng timestamp out of range")
1400: +	}
1401: +
1402: +	return int64(raw * scale), nil //nolint:gosec // bounded above
1403: +}
1404: +
1405: +// Writer writes one little-endian section with nanosecond timestamps. Every block goes out
1406: +// in one Write under a lock, so concurrent writers never interleave blocks and a stream cut
1407: +// between writes is still a valid capture.
1408: +type Writer struct {
1409: +	mu  sync.Mutex
1410: +	w   io.Writer
1411: +	err error
1412: +}
1413: +
1414: +// NewWriter returns a writer of one pcapng section to w.
1415: +func NewWriter(w io.Writer) *Writer {
1416: +	return &Writer{w: w}
1417: +}
1418: +
1419: +// WriteHeader writes the Section Header Block and one Interface Description Block per name, in
1420: +// order; packets refer to the interfaces by that index.
1421: +func (p *Writer) WriteHeader(names []string, snapLength uint32) error {
1422: +	section := make([]byte, 16)
1423: +	binary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)
1424: +	binary.LittleEndian.PutUint16(section[4:], 1)
1425: +	binary.LittleEndian.PutUint16(section[6:], 0)
1426: +	binary.LittleEndian.PutUint64(section[8:], math.MaxUint64)
1427: +	section = appendPCAPNGOption(section, pcapngOptionUserAppl, []byte(captureUserApplication))
1428: +	section = appendPCAPNGOption(section, pcapngOptionEnd, nil)
1429: +
1430: +	header := pcapngBlock(pcapngSectionHeaderType, section)
1431: +	for _, name := range names {
1432: +		description := make([]byte, 8)
1433: +		binary.LittleEndian.PutUint16(description[0:], pcapngLinkTypeEthernet)
1434: +		binary.LittleEndian.PutUint32(description[4:], snapLength)
1435: +		description = appendPCAPNGOption(description, pcapngOptionIfName, []byte(name))
1436: +		description = appendPCAPNGOption(description, pcapngOptionIfTSResol,
1437: +			[]byte{pcapngNanoseconds})
1438: +		description = appendPCAPNGOption(description, pcapngOptionEnd, nil)
1439: +		header = append(header, pcapngBlock(pcapngInterfaceType, description)...)
1440: +	}
1441: +
1442: +	return p.write(header)
1443: +}
1444: +
1445: +// WritePacket writes an Enhanced Packet Block for the interface with the given index.
1446: +func (p *Writer) WritePacket(interfaceID uint32, packet *Packet) error {
1447: +	timestamp := uint64(packet.Timestamp) //nolint:gosec // capture timestamps are positive
1448: +	body := make([]byte, 20, 20+len(packet.Data)+3)
1449: +	binary.LittleEndian.PutUint32(body[0:], interfaceID)
1450: +	binary.LittleEndian.PutUint32(body[4:], uint32(timestamp>>32))
1451: +	binary.LittleEndian.PutUint32(body[8:], uint32(timestamp)) //nolint:gosec // low 32 bits
1452: +	binary.LittleEndian.PutUint32(body[12:], uint32(len(packet.Data)))
1453: +	binary.LittleEndian.PutUint32(body[16:], packet.OriginalLength)
1454: +	body = append(body, packet.Data...)
1455: +	body = append(body, make([]byte, pcapngPadding(len(packet.Data)))...)
1456: +
1457: +	return p.write(pcapngBlock(pcapngEnhancedPacketType, body))
1458: +}
1459: +
1460: +// Err returns the first write error, or nil.
1461: +func (p *Writer) Err() error {
1462: +	p.mu.Lock()
1463: +	defer p.mu.Unlock()
1464: +
1465: +	return p.err
1466: +}
1467: +
1468: +func (p *Writer) write(block []byte) error {
1469: +	p.mu.Lock()
1470: +	defer p.mu.Unlock()
1471: +
1472: +	if p.err != nil {
1473: +		return p.err
1474: +	}
1475: +	if _, err := p.w.Write(block); err != nil {
1476: +		p.err = fmt.Errorf("failed to write the capture: %w", err)
1477: +	}
1478: +
1479: +	return p.err
1480: +}
1481: +
1482: +func pcapngBlock(blockType uint32, body []byte) []byte {
1483: +	total := uint32(12 + len(body)) //nolint:gosec // bounded by the snap length
1484: +	block := make([]byte, 8, total)
1485: +	binary.LittleEndian.PutUint32(block[0:], blockType)
1486: +	binary.LittleEndian.PutUint32(block[4:], total)
1487: +	block = append(block, body...)
1488: +
1489: +	return binary.LittleEndian.AppendUint32(block, total)
1490: +}
1491: +
1492: +func appendPCAPNGOption(body []byte, code uint16, value []byte) []byte {
1493: +	body = binary.LittleEndian.AppendUint16(body, code)
1494: +	body = binary.LittleEndian.AppendUint16(body, uint16(len(value))) //nolint:gosec // short
1495: +	body = append(body, value...)
1496: +
1497: +	return append(body, make([]byte, pcapngPadding(len(value)))...)
1498: +}
1499: +
1500: +func pcapngPadding(length int) int {
1501: +	return (4 - length%4) % 4
1502: +}
1503: diff --git a/capture/pcapng_test.go b/capture/pcapng_test.go
1504: new file mode 100644
1505: index 0000000..0917d16
1506: --- /dev/null
1507: +++ b/capture/pcapng_test.go
1508: @@ -0,0 +1,167 @@
1509: +package capture
1510: +
1511: +import (
1512: +	"bytes"
1513: +	"encoding/binary"
1514: +	"errors"
1515: +	"io"
1516: +	"strings"
1517: +	"testing"
1518: +)
1519: +
1520: +func TestPCAPNGWriterAndReaderRoundTrip(t *testing.T) {
1521: +	t.Parallel()
1522: +
1523: +	var out bytes.Buffer
1524: +	writer := NewWriter(&out)
1525: +	if err := writer.WriteHeader([]string{"r1:e1-1", "r2:eth1"}, 1500); err != nil {
1526: +		t.Fatal(err)
1527: +	}
1528: +	packets := []Packet{
1529: +		{
1530: +			InterfaceID:    1,
1531: +			Timestamp:      1_761_559_200_123_456_789,
1532: +			OriginalLength: 98,
1533: +			Data:           []byte("abcde"),
1534: +		},
1535: +		{
1536: +			InterfaceID:    0,
1537: +			Timestamp:      1_761_559_200_123_456_790,
1538: +			OriginalLength: 4,
1539: +			Data:           []byte("wxyz"),
1540: +		},
1541: +	}
1542: +	for idx := range packets {
1543: +		if err := writer.WritePacket(packets[idx].InterfaceID, &packets[idx]); err != nil {
1544: +			t.Fatal(err)
1545: +		}
1546: +	}
1547: +
1548: +	data := out.Bytes()
1549: +	// the section header names the writer
1550: +	if !bytes.Contains(data[:64], []byte(captureUserApplication)) {
1551: +		t.Fatal("section header has no shb_userappl")
1552: +	}
1553: +	if len(data)%4 != 0 {
1554: +		t.Fatalf("stream length %d is not 32-bit aligned", len(data))
1555: +	}
1556: +
1557: +	reader := NewReader(bytes.NewReader(data))
1558: +	var names []string
1559: +	var read []Packet
1560: +	for {
1561: +		event, err := reader.Next()
1562: +		if errors.Is(err, io.EOF) {
1563: +			break
1564: +		}
1565: +		if err != nil {
1566: +			t.Fatal(err)
1567: +		}
1568: +		if event.Interface != nil {
1569: +			names = append(names, event.Interface.Name)
1570: +			if event.Interface.SnapLength != 1500 || event.Interface.LinkType != 1 {
1571: +				t.Fatalf("interface = %+v", event.Interface)
1572: +			}
1573: +		}
1574: +		if event.Packet != nil {
1575: +			read = append(read, *event.Packet)
1576: +		}
1577: +	}
1578: +	if len(names) != 2 || names[0] != "r1:e1-1" || names[1] != "r2:eth1" {
1579: +		t.Fatalf("names = %v", names)
1580: +	}
1581: +	for idx := range packets {
1582: +		if read[idx].InterfaceID != packets[idx].InterfaceID ||
1583: +			read[idx].Timestamp != packets[idx].Timestamp ||
1584: +			read[idx].OriginalLength != packets[idx].OriginalLength ||
1585: +			!bytes.Equal(read[idx].Data, packets[idx].Data) {
1586: +			t.Fatalf("packet %d = %+v, want %+v", idx, read[idx], packets[idx])
1587: +		}
1588: +	}
1589: +}
1590: +
1591: +func TestPCAPNGReaderHandlesRepeatedSectionsAndResolutions(t *testing.T) {
1592: +	t.Parallel()
1593: +
1594: +	var out bytes.Buffer
1595: +	first := NewWriter(&out)
1596: +	_ = first.WriteHeader([]string{"eth1"}, 64)
1597: +	_ = first.WritePacket(0, &Packet{Timestamp: 5, Data: []byte{1}})
1598: +
1599: +	// a second section whose interface has microsecond timestamps (no if_tsresol)
1600: +	section := make([]byte, 16)
1601: +	binary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)
1602: +	binary.LittleEndian.PutUint16(section[4:], 1)
1603: +	out.Write(pcapngBlock(pcapngSectionHeaderType, section))
1604: +	description := make([]byte, 8)
1605: +	binary.LittleEndian.PutUint16(description[0:], 1)
1606: +	description = appendPCAPNGOption(description, pcapngOptionIfName, []byte("eth2"))
1607: +	out.Write(pcapngBlock(pcapngInterfaceType, description))
1608: +	body := make([]byte, 20)
1609: +	binary.LittleEndian.PutUint32(body[8:], 7) // 7 microseconds
1610: +	out.Write(pcapngBlock(pcapngEnhancedPacketType, body))
1611: +
1612: +	reader := NewReader(&out)
1613: +	var timestamps []int64
1614: +	for {
1615: +		event, err := reader.Next()
1616: +		if errors.Is(err, io.EOF) {
1617: +			break
1618: +		}
1619: +		if err != nil {
1620: +			t.Fatal(err)
1621: +		}
1622: +		if event.Packet != nil {
1623: +			timestamps = append(timestamps, event.Packet.Timestamp)
1624: +		}
1625: +	}
1626: +	if reader.sections != 2 || len(timestamps) != 2 || timestamps[0] != 5 || timestamps[1] != 7000 {
1627: +		t.Fatalf("sections %d, timestamps %v", reader.sections, timestamps)
1628: +	}
1629: +}
1630: +
1631: +func TestPCAPNGReaderRejectsInvalidStreams(t *testing.T) {
1632: +	t.Parallel()
1633: +
1634: +	var valid bytes.Buffer
1635: +	writer := NewWriter(&valid)
1636: +	_ = writer.WriteHeader([]string{"eth1"}, 64)
1637: +	_ = writer.WritePacket(0, &Packet{Timestamp: 1, Data: []byte("data")})
1638: +
1639: +	readAll := func(data []byte) error {
1640: +		reader := NewReader(bytes.NewReader(data))
1641: +		for {
1642: +			_, err := reader.Next()
1643: +			if errors.Is(err, io.EOF) {
1644: +				return nil
1645: +			}
1646: +			if err != nil {
1647: +				return err
1648: +			}
1649: +		}
1650: +	}
1651: +
1652: +	if err := readAll(valid.Bytes()[:valid.Len()-6]); !errors.Is(err, io.ErrUnexpectedEOF) {
1653: +		t.Fatalf("truncated stream: %v", err)
1654: +	}
1655: +
1656: +	bigEndian := append([]byte(nil), valid.Bytes()...)
1657: +	binary.BigEndian.PutUint32(bigEndian[4:], binary.LittleEndian.Uint32(bigEndian[4:]))
1658: +	binary.BigEndian.PutUint32(bigEndian[8:], pcapngByteOrderMagic)
1659: +	if err := readAll(bigEndian); !errors.Is(err, errPCAPNGByteOrder) {
1660: +		t.Fatalf("big-endian section: %v", err)
1661: +	}
1662: +
1663: +	// a little-endian section header longer than the reader accepts is not a byte-order error
1664: +	oversized := append([]byte(nil), valid.Bytes()...)
1665: +	binary.LittleEndian.PutUint32(oversized[4:], 2<<20)
1666: +	if err := readAll(oversized); err == nil || errors.Is(err, errPCAPNGByteOrder) ||
1667: +		!strings.Contains(err.Error(), "invalid pcapng block length") {
1668: +		t.Fatalf("oversized little-endian section: %v", err)
1669: +	}
1670: +
1671: +	packetFirst := pcapngBlock(pcapngEnhancedPacketType, make([]byte, 20))
1672: +	if err := readAll(packetFirst); err == nil {
1673: +		t.Fatal("packet before any interface accepted")
1674: +	}
1675: +}
1676: diff --git a/capture/reorder.go b/capture/reorder.go
1677: new file mode 100644
1678: index 0000000..277ba1a
1679: --- /dev/null
1680: +++ b/capture/reorder.go
1681: @@ -0,0 +1,271 @@
1682: +package capture
1683: +
1684: +import (
1685: +	"container/heap"
1686: +	"context"
1687: +	"sync"
1688: +	"time"
1689: +
1690: +	"github.com/charmbracelet/log"
1691: +)
1692: +
1693: +// maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets
1694: +// are written early, which can put them out of order.
1695: +const maxReorderBytes = 64 << 20
1696: +
1697: +// Reorder writes the packets of several capture sources in timestamp order.
1698: +//
1699: +// Each source (a node's capture stream, or a local interface socket) delivers its packets with
1700: +// its own delay. The buffer holds every packet for `window` after it arrived and writes the held
1701: +// packets in timestamp order, so a packet that was stamped earlier but delivered up to `window`

(Output capped at 50 KB. Showing lines 1-1701. Use offset=1702 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196509c0e001seJvBuFmBanC24",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965097c9001saIYtHzqO7p3aW",
  "callID": "call_1da7296e19f24883ae842f65",
  "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/.github/workflows/clabernetes-tests.yml b/.github/workflows/clabernetes-tests.yml\n2: index b1cbd00..7785167 100644\n3: --- a/.github/workflows/clabernetes-tests.yml\n4: +++ b/.github/workflows/clabernetes-tests.yml\n5: @@ -100,10 +100,15 @@ jobs:\n6:              upgrade --install --create-namespace --namespace c9s \\\n7:                clabernetes oci://ghcr.io/clabernetes/clabernetes/clabernetes:0.0.0\n8:  \n9:            kubectl -n c9s rollout status deploy/clabernetes-manager --timeout=180s\n10:  \n11: +      - name: Install tshark\n12: +        run: |\n13: +          sudo apt-get update\n14: +          sudo DEBIAN_FRONTEND=noninteractive apt-get install -y tshark\n15: +\n16:        - name: Run Clabernetes Robot tests\n17:          run: |\n18:            bash ./tests/rf-run.sh c9s ./tests/14-clabernetes\n19:  \n20:        - name: Upload test report\n21: diff --git a/.github/workflows/smoke-tests.yml b/.github/workflows/smoke-tests.yml\n22: index 807acbe..f7ee3c8 100644\n23: --- a/.github/workflows/smoke-tests.yml\n24: +++ b/.github/workflows/smoke-tests.yml\n25: @@ -51,10 +51,11 @@ jobs:\n26:            - \"28*.robot\"\n27:            - \"29*.robot\"\n28:            - \"30*.robot\"\n29:            - \"31*.robot\"\n30:            - \"32*.robot\"\n31: +          - \"33*.robot\"\n32:  \n33:      # allow podman job to fail, since it started to fail on github actions\n34:      continue-on-error: ${{ inputs.runtime == 'podman' }}\n35:      steps:\n36:        - name: Checkout\n37: diff --git a/capture/local.go b/capture/local.go\n38: new file mode 100644\n39: index 0000000..58dc8aa\n40: --- /dev/null\n41: +++ b/capture/local.go\n42: @@ -0,0 +1,430 @@\n43: +package capture\n44: +\n45: +import (\n46: +\t\"context\"\n47: +\t\"errors\"\n48: +\t\"fmt\"\n49: +\t\"io\"\n50: +\t\"os\"\n51: +\t\"sync\"\n52: +\t\"time\"\n53: +\n54: +\t\"github.com/charmbracelet/log\"\n55: +\t\"github.com/containernetworking/plugins/pkg/ns\"\n56: +\t\"github.com/gopacket/gopacket\"\n57: +\t\"github.com/gopacket/gopacket/afpacket\"\n58: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n59: +)\n60: +\n61: +const (\n62: +\t// localReorderWindow is how long the merged stream holds packets of local sockets back to\n63: +\t// write them in timestamp order. Each socket hands over its packets within\n64: +\t// localBlockTimeout, so a few times that covers the delivery skew between sockets.\n65: +\tlocalReorderWindow = 100 * time.Millisecond\n66: +\t// localBlockTimeout is how long the kernel fills a ring block before it hands it over.\n67: +\tlocalBlockTimeout = 10 * time.Millisecond\n68: +\t// localPollTimeout is how often a socket reader checks whether the capture ended.\n69: +\tlocalPollTimeout = 100 * time.Millisecond\n70: +\t// localReopenInterval is how often a reader tries to reopen the socket of an interface\n71: +\t// that went down or disappeared.\n72: +\tlocalReopenInterval = 200 * time.Millisecond\n73: +\t// localDrainQuiet is how long after the end of a capture a reader keeps waiting for packets\n74: +\t// still in the socket's ring: the kernel hands over a block within two block timeouts.\n75: +\tlocalDrainQuiet = 5 * localBlockTimeout\n76: +\t// localDrainTimeout bounds the drain while packets keep arriving.\n77: +\tlocalDrainTimeout = 250 * time.Millisecond\n78: +\t// localRingBlocks and localMinBlockSize size the receive ring of each socket: eight blocks\n79: +\t// of at least 1 MiB, each larger than the snap length.\n80: +\tlocalRingBlocks   = 8\n81: +\tlocalMinBlockSize = 1 << 20\n82: +\t// vlanHeaderLength is the length of the 802.1Q tag put back into frames whose tag the\n83: +\t// kernel moved out of band.\n84: +\tvlanHeaderLength = 4\n85: +)\n86: +\n87: +// errReadTimeout is returned by a packet source that has no packet within the poll timeout.\n88: +var errReadTimeout = errors.New(\"no packet within the poll timeout\")\n89: +\n90: +// ExecFunc runs f in the network namespace of a node.\n91: +type ExecFunc func(ctx context.Context, f func(ns.NetNS) error) error\n92: +\n93: +// LocalTarget is one interface of a node on this machine (Docker or Podman) to capture.\n94: +type LocalTarget struct {\n95: +\t// Node is the node name as the topology spells it.\n96: +\tNode string\n97: +\t// Interface is the interface name inside the node.\n98: +\tInterface string\n99: +\t// Exec runs a function in the node's network namespace.\n100: +\tExec ExecFunc\n101: +}\n102: +\n103: +// packetSource reads the packets of one interface.\n104: +type packetSource interface {\n105: +\t// ReadPacket returns the next packet; the data is only valid until the next call. It\n106: +\t// returns errReadTimeout when no packet arrived within the poll timeout.\n107: +\tReadPacket() ([]byte, gopacket.CaptureInfo, error)\n108: +\tClose()\n109: +}\n110: +\n111: +// openSourcesFunc opens one packet source per interface in the network namespace exec enters.\n112: +type openSourcesFunc func(\n113: +\tctx context.Context,\n114: +\texec ExecFunc,\n115: +\tinterfaces []string,\n116: +\tsnapLength int,\n117: +) ([]packetSource, error)\n118: +\n119: +// CaptureLocal streams pcapng from interfaces of nodes on this machine to w, with the same\n120: +// output and end conditions as labruntime.PacketCapturer.Capture: one section, one Interface\n121: +// Description Block per target named <node>:<interface>, then the packets of every target in\n122: +// timestamp order. targets lists the interfaces of req.Targets, resolved, in the same order.\n123: +//\n124: +// Each interface is read through a packet socket opened in the node's network namespace, so\n125: +// nothing runs in the node and the node image needs no capture tools; it needs CAP_NET_RAW and\n126: +// the right to enter the namespace, so root. An interface that goes down is reopened once it is\n127: +// up again; one that disappears (its node stopped or was recreated) is reattached when it is\n128: +// back, and the time it was gone is reported as a gap through req.OnGap (or logged).\n129: +func CaptureLocal(\n130: +\tctx context.Context,\n131: +\treq clablabruntime.CaptureRequest,\n132: +\ttargets []LocalTarget,\n133: +\tw io.Writer,\n134: +) error {\n135: +\treturn localCapture{\n136: +\t\topen:           openPacketSockets,\n137: +\t\twindow:         localReorderWindow,\n138: +\t\treopenInterval: localReopenInterval,\n139: +\t}.run(ctx, req, targets, w)\n140: +}\n141: +\n142: +// localCapture is a local capture with its socket opener and timings, which tests replace.\n143: +type localCapture struct {\n144: +\topen           openSourcesFunc\n145: +\twindow         time.Duration\n146: +\treopenInterval time.Duration\n147: +}\n148: +\n149: +func (l localCapture) run(\n150: +\tctx context.Context,\n151: +\treq clablabruntime.CaptureRequest,\n152: +\ttargets []LocalTarget,\n153: +\tw io.Writer,\n154: +) error {\n155: +\tif err := ValidateRequest(&req); err != nil {\n156: +\t\treturn err\n157: +\t}\n158: +\tif len(targets) != len(req.Targets) {\n159: +\t\treturn fmt.Errorf(\"capture has %d resolved targets for %d requested ones\",\n160: +\t\t\tlen(targets), len(req.Targets))\n161: +\t}\n162: +\n163: +\tsources, err := l.openAll(ctx, targets, req.SnapLength)\n164: +\tif err != nil {\n165: +\t\treturn err\n166: +\t}\n167: +\n168: +\tnames := make([]string, len(targets))\n169: +\tfor idx, target := range targets {\n170: +\t\tnames[idx] = target.Node + \":\" + target.Interface\n171: +\t}\n172: +\n173: +\tcaptureCtx, stop := context.WithCancel(ctx)\n174: +\tdefer stop()\n175: +\tif req.Duration > 0 {\n176: +\t\tvar cancelTimeout context.CancelFunc\n177: +\t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx, req.Duration)\n178: +\t\tdefer cancelTimeout()\n179: +\t}\n180: +\n181: +\tout, err := NewOutput(w, names, req.SnapLength, req.PacketLimit, l.window, stop)\n182: +\tif err != nil {\n183: +\t\tfor _, source := range sources {\n184: +\t\t\tsource.Close()\n185: +\t\t}\n186: +\n187: +\t\treturn err\n188: +\t}\n189: +\n190: +\tvar wg sync.WaitGroup\n191: +\tfor idx, source := range sources {\n192: +\t\treader := &localReader{\n193: +\t\t\tcapture: l,\n194: +\t\t\tout:     out,\n195: +\t\t\tid:      uint32(idx), //nolint:gosec // bounded by the targets\n196: +\t\t\ttarget:  targets[idx],\n197: +\t\t\tsnap:    req.SnapLength,\n198: +\t\t\tonGap:   req.OnGap,\n199: +\t\t}\n200: +\t\twg.Go(func() {\n201: +\t\t\treader.run(captureCtx, source)\n202: +\t\t})\n203: +\t}\n204: +\twg.Wait()\n205: +\n206: +\treturn out.Close()\n207: +}\n208: +\n209: +// openAll opens the sockets of every target before anything is written, one namespace entry\n210: +// per node, so a capture that cannot start fails without output.\n211: +func (l localCapture) openAll(\n212: +\tctx context.Context,\n213: +\ttargets []LocalTarget,\n214: +\tsnapLength int,\n215: +) ([]packetSource, error) {\n216: +\ttype nodeTargets struct {\n217: +\t\texec    ExecFunc\n218: +\t\tindexes []int\n219: +\t\tnames   []string\n220: +\t}\n221: +\tvar order []string\n222: +\tbyNode := map[string]*nodeTargets{}\n223: +\tfor idx, target := range targets {\n224: +\t\tgroup := byNode[target.Node]\n225: +\t\tif group == nil {\n226: +\t\t\tgroup = &nodeTargets{exec: target.Exec}\n227: +\t\t\tbyNode[target.Node] = group\n228: +\t\t\torder = append(order, target.Node)\n229: +\t\t}\n230: +\t\tgroup.indexes = append(group.indexes, idx)\n231: +\t\tgroup.names = append(group.names, target.Interface)\n232: +\t}\n233: +\n234: +\tsources := make([]packetSource, len(targets))\n235: +\tcloseAll := func() {\n236: +\t\tfor _, source := range sources {\n237: +\t\t\tif source != nil {\n238: +\t\t\t\tsource.Close()\n239: +\t\t\t}\n240: +\t\t}\n241: +\t}\n242: +\tfor _, node := range order {\n243: +\t\tgroup := byNode[node]\n244: +\t\topened, err := l.open(ctx, group.exec, group.names, snapLength)\n245: +\t\tif err != nil {\n246: +\t\t\tcloseAll()\n247: +\t\t\treturn nil, fmt.Errorf(\"failed to start the capture on node %q: %w\", node, err)\n248: +\t\t}\n249: +\t\tfor idx, source := range opened {\n250: +\t\t\tsources[group.indexes[idx]] = source\n251: +\t\t}\n252: +\t}\n253: +\n254: +\treturn sources, nil\n255: +}\n256: +\n257: +// localReader reads one interface into the merged stream.\n258: +type localReader struct {\n259: +\tcapture localCapture\n260: +\tout     *Output\n261: +\tid      uint32\n262: +\ttarget  LocalTarget\n263: +\tsnap    int\n264: +\tonGap   func(clablabruntime.CaptureGap)\n265: +}\n266: +\n267: +func (r *localReader) run(ctx context.Context, source packetSource) {\n268: +\tdefer func() {\n269: +\t\tif source != nil {\n270: +\t\t\tsource.Close()\n271: +\t\t}\n272: +\t}()\n273: +\n274: +\tfor {\n275: +\t\tif ctx.Err() != nil {\n276: +\t\t\tr.drain(source, time.Now())\n277: +\t\t\treturn\n278: +\t\t}\n279: +\n280: +\t\tdata, info, err := source.ReadPacket()\n281: +\t\tif errors.Is(err, errReadTimeout) {\n282: +\t\t\tcontinue\n283: +\t\t}\n284: +\t\tif err != nil {\n285: +\t\t\t// The socket reports an error once its interface went down or was removed, and\n286: +\t\t\t// keeps reporting it: it is reopened.\n287: +\t\t\tlog.Debug(\"Capture socket failed, reopening it\", \"node\", r.target.Node,\n288: +\t\t\t\t\"interface\", r.target.Interface, \"error\", err)\n289: +\t\t\tsource.Close()\n290: +\t\t\tsource = r.reopen(ctx)\n291: +\t\t\tif source == nil {\n292: +\t\t\t\treturn\n293: +\t\t\t}\n294: +\n295: +\t\t\tcontinue\n296: +\t\t}\n297: +\n298: +\t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n299: +\t\t\treturn\n300: +\t\t}\n301: +\t}\n302: +}\n303: +\n304: +// drain writes the packets that arrived before end but were still in the socket's ring: the\n305: +// kernel hands over a ring block once it is full or its block timeout passed, so the last\n306: +// packets before a capture ended may not have been read yet.\n307: +func (r *localReader) drain(source packetSource, end time.Time) {\n308: +\tdeadline := end.Add(localDrainTimeout)\n309: +\tfor time.Now().Before(deadline) {\n310: +\t\tdata, info, err := source.ReadPacket()\n311: +\t\tif errors.Is(err, errReadTimeout) && time.Since(end) < localDrainQuiet {\n312: +\t\t\tcontinue\n313: +\t\t}\n314: +\t\tif err != nil || info.Timestamp.After(end) {\n315: +\t\t\treturn\n316: +\t\t}\n317: +\t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n318: +\t\t\treturn\n319: +\t\t}\n320: +\t}\n321: +}\n322: +\n323: +// packet copies a packet out of the socket's ring, cut to the snap length.\n324: +func (r *localReader) packet(data []byte, info gopacket.CaptureInfo) *Packet {\n325: +\tlength := info.Length\n326: +\tfor _, ancillary := range info.AncillaryData {\n327: +\t\tif _, ok := ancillary.(afpacket.AncillaryVLAN); ok {\n328: +\t\t\t// the tag was put back into the data and counts toward the frame length\n329: +\t\t\tlength += vlanHeaderLength\n330: +\t\t\tbreak\n331: +\t\t}\n332: +\t}\n333: +\tlength = max(length, len(data))\n334: +\n335: +\tcaptured := make([]byte, min(len(data), r.snap))\n336: +\tcopy(captured, data)\n337: +\n338: +\treturn &Packet{\n339: +\t\tTimestamp:      info.Timestamp.UnixNano(),\n340: +\t\tOriginalLength: uint32(length), //nolint:gosec // bounded by the interface MTU\n341: +\t\tData:           captured,\n342: +\t}\n343: +}\n344: +\n345: +// reopen opens the interface's socket again once its node and interface are back. It returns\n346: +// nil when the capture ended first. Time the interface could not be opened is reported as a gap;\n347: +// an interface that only went down is not, as it has no traffic while down.\n348: +func (r *localReader) reopen(ctx context.Context) packetSource {\n349: +\tfrom := time.Now()\n350: +\tvar unavailable error\n351: +\n352: +\ttimer := time.NewTimer(r.capture.reopenInterval)\n353: +\tdefer timer.Stop()\n354: +\n355: +\tfor {\n356: +\t\tselect {\n357: +\t\tcase <-ctx.Done():\n358: +\t\t\tif unavailable != nil {\n359: +\t\t\t\tr.reportGap(from, time.Time{}, unavailable)\n360: +\t\t\t}\n361: +\n362: +\t\t\treturn nil\n363: +\t\tcase <-timer.C:\n364: +\t\t}\n365: +\n366: +\t\topened, err := r.capture.open(ctx, r.target.Exec, []string{r.target.Interface}, r.snap)\n367: +\t\tif err != nil {\n368: +\t\t\tif unavailable == nil {\n369: +\t\t\t\tlog.Debug(\"Capture interface is not available, waiting for it\",\n370: +\t\t\t\t\t\"node\", r.target.Node, \"interface\", r.target.Interface, \"error\", err)\n371: +\t\t\t}\n372: +\t\t\tunavailable = err\n373: +\t\t\tresetTimer(timer, r.capture.reopenInterval)\n374: +\n375: +\t\t\tcontinue\n376: +\t\t}\n377: +\t\tif unavailable != nil {\n378: +\t\t\tr.reportGap(from, time.Now(), unavailable)\n379: +\t\t}\n380: +\n381: +\t\treturn opened[0]\n382: +\t}\n383: +}\n384: +\n385: +func (r *localReader) reportGap(from, to time.Time, cause error) {\n386: +\tReportGap(r.onGap, clablabruntime.CaptureGap{\n387: +\t\tNode:       r.target.Node,\n388: +\t\tInterfaces: []string{r.target.Interface},\n389: +\t\tFrom:       from,\n390: +\t\tTo:         to,\n391: +\t\tReason:     fmt.Sprintf(\"the interface was not available: %v\", cause),\n392: +\t})\n393: +}\n394: +\n395: +// openPacketSockets opens one packet socket per interface in the namespace exec enters. A socket\n396: +// stays bound to its interface after the thread left the namespace.\n397: +func openPacketSockets(\n398: +\tctx context.Context,\n399: +\texec ExecFunc,\n400: +\tinterfaces []string,\n401: +\tsnapLength int,\n402: +) ([]packetSource, error) {\n403: +\tsources := make([]packetSource, 0, len(interfaces))\n404: +\terr := exec(ctx, func(ns.NetNS) error {\n405: +\t\tfor _, name := range interfaces {\n406: +\t\t\tsource, err := openPacketSocket(name, snapLength)\n407: +\t\t\tif err != nil {\n408: +\t\t\t\treturn fmt.Errorf(\"interface %q: %w\", name, err)\n409: +\t\t\t}\n410: +\t\t\tsources = append(sources, source)\n411: +\t\t}\n412: +\n413: +\t\treturn nil\n414: +\t})\n415: +\tif err != nil {\n416: +\t\tfor _, source := range sources {\n417: +\t\t\tsource.Close()\n418: +\t\t}\n419: +\n420: +\t\treturn nil, err\n421: +\t}\n422: +\n423: +\treturn sources, nil\n424: +}\n425: +\n426: +// afpacketSource is a TPACKET_V3 receive ring on one interface.\n427: +type afpacketSource struct {\n428: +\thandle *afpacket.TPacket\n429: +}\n430: +\n431: +func openPacketSocket(name string, snapLength int) (*afpacketSource, error) {\n432: +\t// A TPACKET_V3 block holds whole frames: it must be larger than the snap length, plus the\n433: +\t// block and frame headers, and a multiple of the page size.\n434: +\tpageSize := os.Getpagesize()\n435: +\tblockSize := max(localMinBlockSize, snapLength+pageSize)\n436: +\tblockSize = (blockSize + pageSize - 1) / pageSize * pageSize\n437: +\n438: +\thandle, err := afpacket.NewTPacket(\n439: +\t\tafpacket.OptInterface(name),\n440: +\t\tafpacket.OptTPacketVersion(afpacket.TPacketVersion3),\n441: +\t\tafpacket.OptFrameSize(blockSize),\n442: +\t\tafpacket.OptBlockSize(blockSize),\n443: +\t\tafpacket.OptNumBlocks(localRingBlocks),\n444: +\t\tafpacket.OptBlockTimeout(localBlockTimeout),\n445: +\t\tafpacket.OptPollTimeout(localPollTimeout),\n446: +\t\t// the kernel moves 802.1Q tags out of the frame; captures show them in place\n447: +\t\tafpacket.OptAddVLANHeader(true),\n448: +\t)\n449: +\tif err != nil {\n450: +\t\treturn nil, err\n451: +\t}\n452: +\t// promiscuous mode is a membership of this socket and ends with it\n453: +\tif err := handle.SetPromiscuous(true); err != nil {\n454: +\t\thandle.Close()\n455: +\t\treturn nil, fmt.Errorf(\"failed to enable promiscuous mode: %w\", err)\n456: +\t}\n457: +\n458: +\treturn &afpacketSource{handle: handle}, nil\n459: +}\n460: +\n461: +func (s *afpacketSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {\n462: +\tdata, info, err := s.handle.ZeroCopyReadPacketData()\n463: +\tif errors.Is(err, afpacket.ErrTimeout) {\n464: +\t\treturn nil, info, errReadTimeout\n465: +\t}\n466: +\n467: +\treturn data, info, err\n468: +}\n469: +\n470: +func (s *afpacketSource) Close() {\n471: +\ts.handle.Close()\n472: +}\n473: diff --git a/capture/local_test.go b/capture/local_test.go\n474: new file mode 100644\n475: index 0000000..f91bb00\n476: --- /dev/null\n477: +++ b/capture/local_test.go\n478: @@ -0,0 +1,476 @@\n479: +package capture\n480: +\n481: +import (\n482: +\t\"bytes\"\n483: +\t\"context\"\n484: +\t\"errors\"\n485: +\t\"fmt\"\n486: +\t\"io\"\n487: +\t\"slices\"\n488: +\t\"strings\"\n489: +\t\"sync\"\n490: +\t\"testing\"\n491: +\t\"time\"\n492: +\n493: +\t\"github.com/containernetworking/plugins/pkg/ns\"\n494: +\t\"github.com/gopacket/gopacket\"\n495: +\t\"github.com/gopacket/gopacket/afpacket\"\n496: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n497: +)\n498: +\n499: +// fakeFrame is one packet a fake source returns.\n500: +type fakeFrame struct {\n501: +\tdata   []byte\n502: +\tstamp  time.Time\n503: +\tlength int\n504: +\tvlan   bool\n505: +\t// visible delays the frame like a ring block the kernel has not handed over yet.\n506: +\tvisible time.Time\n507: +\t// err ends the source with this error instead of a packet.\n508: +\terr error\n509: +}\n510: +\n511: +// fakeSource returns frames from a channel, errReadTimeout while none is queued.\n512: +type fakeSource struct {\n513: +\tframes  chan fakeFrame\n514: +\tclosed  chan struct{}\n515: +\tonce    sync.Once\n516: +\tpending *fakeFrame\n517: +}\n518: +\n519: +func newFakeSource() *fakeSource {\n520: +\treturn &fakeSource{frames: make(chan fakeFrame, 64), closed: make(chan struct{})}\n521: +}\n522: +\n523: +func (s *fakeSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {\n524: +\tif s.pending == nil {\n525: +\t\tselect {\n526: +\t\tcase frame := <-s.frames:\n527: +\t\t\ts.pending = &frame\n528: +\t\tcase <-time.After(5 * time.Millisecond):\n529: +\t\t\treturn nil, gopacket.CaptureInfo{}, errReadTimeout\n530: +\t\t}\n531: +\t}\n532: +\tif wait := time.Until(s.pending.visible); wait > 0 {\n533: +\t\ttime.Sleep(min(wait, 5*time.Millisecond))\n534: +\t\tif time.Now().Before(s.pending.visible) {\n535: +\t\t\treturn nil, gopacket.CaptureInfo{}, errReadTimeout\n536: +\t\t}\n537: +\t}\n538: +\n539: +\t{\n540: +\t\tframe := *s.pending\n541: +\t\ts.pending = nil\n542: +\t\tif frame.err != nil {\n543: +\t\t\treturn nil, gopacket.CaptureInfo{}, frame.err\n544: +\t\t}\n545: +\t\tinfo := gopacket.CaptureInfo{\n546: +\t\t\tTimestamp: frame.stamp, CaptureLength: len(frame.data), Length: frame.length,\n547: +\t\t}\n548: +\t\tif frame.vlan {\n549: +\t\t\tinfo.AncillaryData = []any{afpacket.AncillaryVLAN{VLAN: 10}}\n550: +\t\t}\n551: +\n552: +\t\treturn frame.data, info, nil\n553: +\t}\n554: +}\n555: +\n556: +func (s *fakeSource) Close() {\n557: +\ts.once.Do(func() { close(s.closed) })\n558: +}\n559: +\n560: +// fakeHost hands out fake sources per node and interface. Opening an interface listed in\n561: +// missing fails, like an interface whose node does not run.\n562: +type fakeHost struct {\n563: +\tmu      sync.Mutex\n564: +\topened  map[string][]*fakeSource\n565: +\tmissing map[string]bool\n566: +\tready   chan string\n567: +}\n568: +\n569: +func newFakeHost() *fakeHost {\n570: +\treturn &fakeHost{\n571: +\t\topened: map[string][]*fakeSource{}, missing: map[string]bool{},\n572: +\t\tready: make(chan string, 64),\n573: +\t}\n574: +}\n575: +\n576: +func (h *fakeHost) exec(node string) ExecFunc {\n577: +\treturn func(_ context.Context, f func(ns.NetNS) error) error {\n578: +\t\th.mu.Lock()\n579: +\t\tmissing := h.missing[node]\n580: +\t\th.mu.Unlock()\n581: +\t\tif missing {\n582: +\t\t\treturn fmt.Errorf(\"node %q: container network namespace is not available\", node)\n583: +\t\t}\n584: +\n585: +\t\treturn f(nil)\n586: +\t}\n587: +}\n588: +\n589: +func (h *fakeHost) open(\n590: +\tctx context.Context,\n591: +\texec ExecFunc,\n592: +\tinterfaces []string,\n593: +\t_ int,\n594: +) ([]packetSource, error) {\n595: +\tvar node string\n596: +\terr := exec(ctx, func(ns.NetNS) error { return nil })\n597: +\tif err != nil {\n598: +\t\treturn nil, err\n599: +\t}\n600: +\n601: +\th.mu.Lock()\n602: +\tdefer h.mu.Unlock()\n603: +\tsources := make([]packetSource, 0, len(interfaces))\n604: +\tfor _, name := range interfaces {\n605: +\t\tif h.missing[name] {\n606: +\t\t\treturn nil, fmt.Errorf(\"interface %q: no such network interface\", name)\n607: +\t\t}\n608: +\t\tnode = name\n609: +\t\tsource := newFakeSource()\n610: +\t\th.opened[name] = append(h.opened[name], source)\n611: +\t\tsources = append(sources, source)\n612: +\t\th.ready <- node\n613: +\t}\n614: +\n615: +\treturn sources, nil\n616: +}\n617: +\n618: +func (h *fakeHost) source(name string, generation int) *fakeSource {\n619: +\th.mu.Lock()\n620: +\tdefer h.mu.Unlock()\n621: +\n622: +\treturn h.opened[name][generation]\n623: +}\n624: +\n625: +func (h *fakeHost) setMissing(name string, missing bool) {\n626: +\th.mu.Lock()\n627: +\tdefer h.mu.Unlock()\n628: +\th.missing[name] = missing\n629: +}\n630: +\n631: +func (h *fakeHost) capture() localCapture {\n632: +\treturn localCapture{\n633: +\t\topen:           h.open,\n634: +\t\twindow:         20 * time.Millisecond,\n635: +\t\treopenInterval: time.Millisecond,\n636: +\t}\n637: +}\n638: +\n639: +// waitOpened waits until n sources were opened.\n640: +func (h *fakeHost) waitOpened(t *testing.T, n int) {\n641: +\tt.Helper()\n642: +\tfor range n {\n643: +\t\tselect {\n644: +\t\tcase <-h.ready:\n645: +\t\tcase <-time.After(2 * time.Second):\n646: +\t\t\tt.Fatal(\"source was not opened\")\n647: +\t\t}\n648: +\t}\n649: +}\n650: +\n651: +type parsedLocalCapture struct {\n652: +\tinterfaces []string\n653: +\tpackets    []Packet\n654: +}\n655: +\n656: +func parseLocalCapture(t *testing.T, data []byte) parsedLocalCapture {\n657: +\tt.Helper()\n658: +\n659: +\tvar parsed parsedLocalCapture\n660: +\treader := NewReader(bytes.NewReader(data))\n661: +\tfor {\n662: +\t\tevent, err := reader.Next()\n663: +\t\tif errors.Is(err, io.EOF) {\n664: +\t\t\tbreak\n665: +\t\t}\n666: +\t\tif err != nil {\n667: +\t\t\tt.Fatalf(\"invalid capture: %v\", err)\n668: +\t\t}\n669: +\t\tif event.Interface != nil {\n670: +\t\t\tparsed.interfaces = append(parsed.interfaces, event.Interface.Name)\n671: +\t\t}\n672: +\t\tif event.Packet != nil {\n673: +\t\t\tparsed.packets = append(parsed.packets, *event.Packet)\n674: +\t\t}\n675: +\t}\n676: +\tif reader.Sections() != 1 {\n677: +\t\tt.Fatalf(\"capture has %d sections\", reader.Sections())\n678: +\t}\n679: +\n680: +\treturn parsed\n681: +}\n682: +\n683: +func localRequest(packetLimit int, duration time.Duration) clablabruntime.CaptureRequest {\n684: +\treturn clablabruntime.CaptureRequest{\n685: +\t\tName: \"lab\",\n686: +\t\tTargets: []clablabruntime.CaptureTarget{\n687: +\t\t\t{Node: \"r1\", Interface: \"eth1\"}, {Node: \"r2\", Interface: \"eth1\"},\n688: +\t\t},\n689: +\t\tPacketLimit: packetLimit,\n690: +\t\tDuration:    duration,\n691: +\t\tSnapLength:  64,\n692: +\t}\n693: +}\n694: +\n695: +func TestCaptureLocalMergesInterfacesInTimestampOrder(t *testing.T) {\n696: +\tt.Parallel()\n697: +\n698: +\thost := newFakeHost()\n699: +\t// the sources are keyed by interface name in the fake host, so the two nodes use distinct\n700: +\t// names behind the requested ones\n701: +\ttargets := []LocalTarget{\n702: +\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n703: +\t\t{Node: \"r2\", Interface: \"e2\", Exec: host.exec(\"r2\")},\n704: +\t}\n705: +\n706: +\tvar out bytes.Buffer\n707: +\tdone := make(chan error, 1)\n708: +\tgo func() {\n709: +\t\tdone <- host.capture().run(context.Background(), localRequest(4, 0), targets, &out)\n710: +\t}()\n711: +\thost.waitOpened(t, 2)\n712: +\n713: +\tbase := time.Unix(1_761_559_200, 0)\n714: +\t// r2's packets reach containerlab first although r1 stamped one of them earlier\n715: +\thost.source(\"e2\", 0).frames <- fakeFrame{\n716: +\t\tdata: []byte(\"r2-a\"), stamp: base.Add(2 * time.Millisecond), length: 4,\n717: +\t}\n718: +\thost.source(\"e2\", 0).frames <- fakeFrame{\n719: +\t\tdata: bytes.Repeat([]byte{7}, 100), stamp: base.Add(4 * time.Millisecond), length: 100,\n720: +\t}\n721: +\thost.source(\"e1\", 0).frames <- fakeFrame{\n722: +\t\tdata: []byte(\"r1-a\"), stamp: base.Add(1 * time.Millisecond), length: 4,\n723: +\t}\n724: +\thost.source(\"e1\", 0).frames <- fakeFrame{\n725: +\t\tdata: []byte(\"r1-v\"), stamp: base.Add(3 * time.Millisecond), length: 60, vlan: true,\n726: +\t}\n727: +\n728: +\tselect {\n729: +\tcase err := <-done:\n730: +\t\tif err != nil {\n731: +\t\t\tt.Fatal(err)\n732: +\t\t}\n733: +\tcase <-time.After(5 * time.Second):\n734: +\t\tt.Fatal(\"capture did not stop at the packet limit\")\n735: +\t}\n736: +\n737: +\tparsed := parseLocalCapture(t, out.Bytes())\n738: +\tif want := []string{\"r1:e1\", \"r2:e2\"}; !slices.Equal(parsed.interfaces, want) {\n739: +\t\tt.Fatalf(\"interfaces = %v, want %v\", parsed.interfaces, want)\n740: +\t}\n741: +\tif len(parsed.packets) != 4 {\n742: +\t\tt.Fatalf(\"captured %d packets, want 4\", len(parsed.packets))\n743: +\t}\n744: +\tvar ids []uint32\n745: +\tfor idx, packet := range parsed.packets {\n746: +\t\tids = append(ids, packet.InterfaceID)\n747: +\t\tif want := base.Add(time.Duration(idx+1) * time.Millisecond).\n748: +\t\t\tUnixNano(); packet.Timestamp != want {\n749: +\t\t\tt.Fatalf(\"packet %d stamped %d, want %d\", idx, packet.Timestamp, want)\n750: +\t\t}\n751: +\t}\n752: +\tif !slices.Equal(ids, []uint32{0, 1, 0, 1}) {\n753: +\t\tt.Fatalf(\"interface IDs = %v\", ids)\n754: +\t}\n755: +\t// a re-inserted VLAN tag counts toward the frame length\n756: +\tif parsed.packets[2].OriginalLength != 64 {\n757: +\t\tt.Fatalf(\"VLAN frame length = %d, want 64\", parsed.packets[2].OriginalLength)\n758: +\t}\n759: +\t// frames are cut to the snap length\n760: +\tif last := parsed.packets[3]; len(last.Data) != 64 || last.OriginalLength != 100 {\n761: +\t\tt.Fatalf(\"long frame kept %d of %d bytes\", len(last.Data), last.OriginalLength)\n762: +\t}\n763: +\tfor _, name := range []string{\"e1\", \"e2\"} {\n764: +\t\tselect {\n765: +\t\tcase <-host.source(name, 0).closed:\n766: +\t\tdefault:\n767: +\t\t\tt.Fatalf(\"source %s was not closed\", name)\n768: +\t\t}\n769: +\t}\n770: +}\n771: +\n772: +func TestCaptureLocalEndsAfterTheDurationOrWhenCanceled(t *testing.T) {\n773: +\tt.Parallel()\n774: +\n775: +\thost := newFakeHost()\n776: +\ttargets := []LocalTarget{\n777: +\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n778: +\t\t{Node: \"r1\", Interface: \"e2\", Exec: host.exec(\"r1\")},\n779: +\t}\n780: +\n781: +\tvar out bytes.Buffer\n782: +\tstart := time.Now()\n783: +\tif err := host.capture().run(context.Background(), localRequest(0, 50*time.Millisecond),\n784: +\t\ttargets, &out); err != nil {\n785: +\t\tt.Fatal(err)\n786: +\t}\n787: +\tif elapsed := time.Since(start); elapsed < 50*time.Millisecond || elapsed > 2*time.Second {\n788: +\t\tt.Fatalf(\"capture ran %s for a 50ms duration\", elapsed)\n789: +\t}\n790: +\tif parsed := parseLocalCapture(t, out.Bytes()); len(parsed.interfaces) != 2 {\n791: +\t\tt.Fatalf(\"interfaces = %v\", parsed.interfaces)\n792: +\t}\n793: +\n794: +\tctx, cancel := context.WithCancel(context.Background())\n795: +\tdone := make(chan error, 1)\n796: +\tgo func() {\n797: +\t\tdone <- host.capture().run(ctx, localRequest(0, 0), targets, io.Discard)\n798: +\t}()\n799: +\thost.waitOpened(t, 4)\n800: +\tcancel()\n801: +\tselect {\n802: +\tcase err := <-done:\n803: +\t\tif err != nil {\n804: +\t\t\tt.Fatalf(\"canceled capture returned %v\", err)\n805: +\t\t}\n806: +\tcase <-time.After(2 * time.Second):\n807: +\t\tt.Fatal(\"canceled capture did not end\")\n808: +\t}\n809: +}\n810: +\n811: +func TestCaptureLocalWritesPacketsStillInTheRingWhenItEnds(t *testing.T) {\n812: +\tt.Parallel()\n813: +\n814: +\thost := newFakeHost()\n815: +\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n816: +\treq := localRequest(0, 0)\n817: +\treq.Targets = req.Targets[:1]\n818: +\n819: +\tctx, cancel := context.WithCancel(context.Background())\n820: +\tvar out bytes.Buffer\n821: +\tdone := make(chan error, 1)\n822: +\tgo func() {\n823: +\t\tdone <- host.capture().run(ctx, req, targets, &out)\n824: +\t}()\n825: +\thost.waitOpened(t, 1)\n826: +\n827: +\tnow := time.Now()\n828: +\t// stamped before the end, handed over by the kernel only after it\n829: +\thost.source(\"e1\", 0).frames <- fakeFrame{\n830: +\t\tdata: []byte(\"before\"), stamp: now, length: 6, visible: now.Add(30 * time.Millisecond),\n831: +\t}\n832: +\t// stamped after the end: not part of the capture\n833: +\thost.source(\"e1\", 0).frames <- fakeFrame{\n834: +\t\tdata: []byte(\"after\"), stamp: now.Add(time.Hour), length: 5,\n835: +\t\tvisible: now.Add(40 * time.Millisecond),\n836: +\t}\n837: +\tcancel()\n838: +\n839: +\tif err := <-done; err != nil {\n840: +\t\tt.Fatal(err)\n841: +\t}\n842: +\tparsed := parseLocalCapture(t, out.Bytes())\n843: +\tif len(parsed.packets) != 1 || string(parsed.packets[0].Data) != \"before\" {\n844: +\t\tt.Fatalf(\"packets = %+v, want only the one stamped before the end\", parsed.packets)\n845: +\t}\n846: +}\n847: +\n848: +func TestCaptureLocalFailsWithoutOutputWhenAnInterfaceCannotBeOpened(t *testing.T) {\n849: +\tt.Parallel()\n850: +\n851: +\thost := newFakeHost()\n852: +\thost.setMissing(\"r2\", true)\n853: +\ttargets := []LocalTarget{\n854: +\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n855: +\t\t{Node: \"r2\", Interface: \"e2\", Exec: host.exec(\"r2\")},\n856: +\t}\n857: +\n858: +\tvar out bytes.Buffer\n859: +\terr := host.capture().run(context.Background(), localRequest(0, 0), targets, &out)\n860: +\tif err == nil || !strings.Contains(err.Error(), `failed to start the capture on node \"r2\"`) {\n861: +\t\tt.Fatalf(\"error = %v\", err)\n862: +\t}\n863: +\tif out.Len() != 0 {\n864: +\t\tt.Fatalf(\"wrote %d bytes before failing\", out.Len())\n865: +\t}\n866: +\tselect {\n867: +\tcase <-host.source(\"e1\", 0).closed:\n868: +\tdefault:\n869: +\t\tt.Fatal(\"the source opened before the failure was not closed\")\n870: +\t}\n871: +}\n872: +\n873: +func TestCaptureLocalReopensInterfacesAndReportsWhileTheyWereGone(t *testing.T) {\n874: +\tt.Parallel()\n875: +\n876: +\thost := newFakeHost()\n877: +\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n878: +\treq := localRequest(2, 0)\n879: +\treq.Targets = req.Targets[:1]\n880: +\n881: +\tvar mu sync.Mutex\n882: +\tvar gaps []clablabruntime.CaptureGap\n883: +\treq.OnGap = func(gap clablabruntime.CaptureGap) {\n884: +\t\tmu.Lock()\n885: +\t\tdefer mu.Unlock()\n886: +\t\tgaps = append(gaps, gap)\n887: +\t}\n888: +\n889: +\tvar out bytes.Buffer\n890: +\tdone := make(chan error, 1)\n891: +\tgo func() {\n892: +\t\tdone <- host.capture().run(context.Background(), req, targets, &out)\n893: +\t}()\n894: +\thost.waitOpened(t, 1)\n895: +\n896: +\tbase := time.Unix(1_761_559_200, 0)\n897: +\thost.source(\"e1\", 0).frames <- fakeFrame{data: []byte(\"a\"), stamp: base, length: 1}\n898: +\n899: +\t// the interface goes down: the socket fails and is reopened at once, without a gap\n900: +\thost.source(\"e1\", 0).frames <- fakeFrame{err: afpacket.ErrPoll}\n901: +\thost.waitOpened(t, 1)\n902: +\n903: +\t// the node restarts: the interface is gone for a while, then back\n904: +\thost.setMissing(\"r1\", true)\n905: +\thost.source(\"e1\", 1).frames <- fakeFrame{err: afpacket.ErrPoll}\n906: +\ttime.Sleep(20 * time.Millisecond)\n907: +\thost.setMissing(\"r1\", false)\n908: +\thost.waitOpened(t, 1)\n909: +\thost.source(\"e1\", 2).frames <- fakeFrame{\n910: +\t\tdata: []byte(\"b\"), stamp: base.Add(time.Second), length: 1,\n911: +\t}\n912: +\n913: +\tselect {\n914: +\tcase err := <-done:\n915: +\t\tif err != nil {\n916: +\t\t\tt.Fatal(err)\n917: +\t\t}\n918: +\tcase <-time.After(5 * time.Second):\n919: +\t\tt.Fatal(\"capture did not stop at the packet limit\")\n920: +\t}\n921: +\n922: +\tif parsed := parseLocalCapture(t, out.Bytes()); len(parsed.packets) != 2 {\n923: +\t\tt.Fatalf(\"captured %d packets across the reopen, want 2\", len(parsed.packets))\n924: +\t}\n925: +\tmu.Lock()\n926: +\tdefer mu.Unlock()\n927: +\tif len(gaps) != 1 {\n928: +\t\tt.Fatalf(\"gaps = %+v, want one for the restart\", gaps)\n929: +\t}\n930: +\tgap := gaps[0]\n931: +\tif gap.Node != \"r1\" || !slices.Equal(gap.Interfaces, []string{\"e1\"}) || gap.To.IsZero() ||\n932: +\t\t!gap.To.After(gap.From) || !strings.Contains(gap.Reason, \"not available\") {\n933: +\t\tt.Fatalf(\"gap = %+v\", gap)\n934: +\t}\n935: +}\n936: +\n937: +func TestCaptureLocalChecksTheRequest(t *testing.T) {\n938: +\tt.Parallel()\n939: +\n940: +\thost := newFakeHost()\n941: +\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n942: +\n943: +\treq := localRequest(0, 0)\n944: +\treq.SnapLength = 10\n945: +\tif err := host.capture().run(context.Background(), req, targets[:1], io.Discard); err == nil ||\n946: +\t\t!strings.Contains(err.Error(), \"snap length 10\") {\n947: +\t\tt.Fatalf(\"small snap length: error = %v\", err)\n948: +\t}\n949: +\n950: +\tif err := host.capture().run(context.Background(), localRequest(0, 0), targets,\n951: +\t\tio.Discard); err == nil || !strings.Contains(err.Error(), \"1 resolved targets for 2\") {\n952: +\t\tt.Fatalf(\"target mismatch: error = %v\", err)\n953: +\t}\n954: +}\n955: diff --git a/capture/output.go b/capture/output.go\n956: new file mode 100644\n957: index 0000000..574c33a\n958: --- /dev/null\n959: +++ b/capture/output.go\n960: @@ -0,0 +1,203 @@\n961: +package capture\n962: +\n963: +import (\n964: +\t\"context\"\n965: +\t\"fmt\"\n966: +\t\"io\"\n967: +\t\"strings\"\n968: +\t\"sync/atomic\"\n969: +\t\"time\"\n970: +\n971: +\t\"github.com/charmbracelet/log\"\n972: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n973: +)\n974: +\n975: +// Snap length bounds of a capture.\n976: +const (\n977: +\t// DefaultSnapLength is the snap length of a request without one.\n978: +\tDefaultSnapLength = 256 << 10\n979: +\tMinSnapLength     = 64\n980: +\tMaxSnapLength     = 1 << 20\n981: +)\n982: +\n983: +// ValidateRequest checks the bounds of a capture request and fills the default snap length.\n984: +func ValidateRequest(req *clablabruntime.CaptureRequest) error {\n985: +\tif req.Name == \"\" {\n986: +\t\treturn fmt.Errorf(\"topology name is required\")\n987: +\t}\n988: +\tif len(req.Targets) == 0 {\n989: +\t\treturn fmt.Errorf(\"at least one capture target (node and interface) is required\")\n990: +\t}\n991: +\tfor _, target := range req.Targets {\n992: +\t\tif target.Node == \"\" || target.Interface == \"\" {\n993: +\t\t\treturn fmt.Errorf(\"capture target %+v needs a node and an interface\", target)\n994: +\t\t}\n995: +\t}\n996: +\tif req.Duration < 0 {\n997: +\t\treturn fmt.Errorf(\"capture duration must not be negative\")\n998: +\t}\n999: +\tif req.PacketLimit < 0 {\n1000: +\t\treturn fmt.Errorf(\"capture packet limit must not be negative\")\n1001: +\t}\n1002: +\tif req.SnapLength == 0 {\n1003: +\t\treq.SnapLength = DefaultSnapLength\n1004: +\t}\n1005: +\tif req.SnapLength < MinSnapLength || req.SnapLength > MaxSnapLength {\n1006: +\t\treturn fmt.Errorf(\"capture snap length %d is outside %d to %d bytes\", req.SnapLength,\n1007: +\t\t\tMinSnapLength, MaxSnapLength)\n1008: +\t}\n1009: +\n1010: +\treturn nil\n1011: +}\n1012: +\n1013: +// FindInterface matches a requested interface by its name, then by its alias.\n1014: +func FindInterface(\n1015: +\tentries []clablabruntime.CaptureInterface,\n1016: +\tname string,\n1017: +) (clablabruntime.CaptureInterface, bool) {\n1018: +\tfor _, entry := range entries {\n1019: +\t\tif entry.Interface == name {\n1020: +\t\t\treturn entry, true\n1021: +\t\t}\n1022: +\t}\n1023: +\tfor _, entry := range entries {\n1024: +\t\tif entry.Alias != \"\" && entry.Alias == name {\n1025: +\t\t\treturn entry, true\n1026: +\t\t}\n1027: +\t}\n1028: +\n1029: +\treturn clablabruntime.CaptureInterface{}, false\n1030: +}\n1031: +\n1032: +// DescribeInterfaces lists interfaces for an error message: name (alias), ...\n1033: +func DescribeInterfaces(entries []clablabruntime.CaptureInterface) string {\n1034: +\tif len(entries) == 0 {\n1035: +\t\treturn \"none\"\n1036: +\t}\n1037: +\n1038: +\tnames := make([]string, 0, len(entries))\n1039: +\tfor _, entry := range entries {\n1040: +\t\tname := entry.Interface\n1041: +\t\tif entry.Alias != \"\" {\n1042: +\t\t\tname += \" (\" + entry.Alias + \")\"\n1043: +\t\t}\n1044: +\t\tnames = append(names, name)\n1045: +\t}\n1046: +\n1047: +\treturn strings.Join(names, \", \")\n1048: +}\n1049: +\n1050: +// ReportGap hands a gap to onGap, or logs it as a warning when onGap is nil.\n1051: +func ReportGap(onGap func(clablabruntime.CaptureGap), gap clablabruntime.CaptureGap) {\n1052: +\tif onGap != nil {\n1053: +\t\tonGap(gap)\n1054: +\t\treturn\n1055: +\t}\n1056: +\n1057: +\tto := \"unknown\"\n1058: +\tif !gap.To.IsZero() {\n1059: +\t\tto = gap.To.Format(time.RFC3339Nano)\n1060: +\t}\n1061: +\tlog.Warn(\"Capture has a gap\", \"node\", gap.Node, \"interfaces\", strings.Join(gap.Interfaces, \",\"),\n1062: +\t\t\"from\", gap.From.Format(time.RFC3339Nano), \"to\", to, \"reason\", gap.Reason)\n1063: +}\n1064: +\n1065: +// Output is the merged pcapng stream of one capture: the section header with one interface per\n1066: +// capture target, then the packets of every target in timestamp order (through a Reorder), up\n1067: +// to an optional packet limit.\n1068: +type Output struct {\n1069: +\twriter  *Writer\n1070: +\treorder *Reorder\n1071: +\tlimit   int64\n1072: +\twritten atomic.Int64\n1073: +\tstop    func()\n1074: +\n1075: +\tcancelRun context.CancelFunc\n1076: +\trunDone   chan struct{}\n1077: +}\n1078: +\n1079: +// NewOutput writes the section header and one Interface Description Block per name to w, then\n1080: +// starts the reorder buffer with the given window (zero or less writes packets as they come).\n1081: +// stop is called once the packet limit is reached or a write failed. Close must be called.\n1082: +func NewOutput(\n1083: +\tw io.Writer,\n1084: +\tnames []string,\n1085: +\tsnapLength, packetLimit int,\n1086: +\twindow time.Duration,\n1087: +\tstop func(),\n1088: +) (*Output, error) {\n1089: +\twriter := NewWriter(w)\n1090: +\tif err := writer.WriteHeader(\n1091: +\t\tnames,\n1092: +\t\tuint32(snapLength),\n1093: +\t); err != nil { //nolint:gosec // validated\n1094: +\t\treturn nil, err\n1095: +\t}\n1096: +\n1097: +\tout := &Output{\n1098: +\t\twriter:  writer,\n1099: +\t\treorder: NewReorder(window, writer.WritePacket, stop),\n1100: +\t\tlimit:   int64(packetLimit),\n1101: +\t\tstop:    stop,\n1102: +\t\trunDone: make(chan struct{}),\n1103: +\t}\n1104: +\n1105: +\tvar runCtx context.Context\n1106: +\trunCtx, out.cancelRun = context.WithCancel(context.Background())\n1107: +\tgo func() {\n1108: +\t\tdefer close(out.runDone)\n1109: +\t\tout.reorder.Run(runCtx)\n1110: +\t}()\n1111: +\n1112: +\treturn out, nil\n1113: +}\n1114: +\n1115: +// Emit hands a packet of the interface with the given index to the stream. It reports false\n1116: +// once the packet limit is reached and the capture stops, and returns the error of a failed\n1117: +// write.\n1118: +func (o *Output) Emit(id uint32, packet *Packet) (bool, error) {\n1119: +\tif o.limit > 0 {\n1120: +\t\tcount := o.written.Add(1)\n1121: +\t\tif count > o.limit {\n1122: +\t\t\to.stop()\n1123: +\t\t\treturn false, nil\n1124: +\t\t}\n1125: +\t\tif err := o.reorder.Push(id, packet); err != nil {\n1126: +\t\t\treturn false, err\n1127: +\t\t}\n1128: +\t\tif count == o.limit {\n1129: +\t\t\to.stop()\n1130: +\t\t\treturn false, nil\n1131: +\t\t}\n1132: +\n1133: +\t\treturn true, nil\n1134: +\t}\n1135: +\n1136: +\to.written.Add(1)\n1137: +\n1138: +\treturn true, o.reorder.Push(id, packet)\n1139: +}\n1140: +\n1141: +// Written returns the number of packets handed to the stream so far.\n1142: +func (o *Output) Written() int64 {\n1143: +\treturn o.written.Load()\n1144: +}\n1145: +\n1146: +// Hold keeps packets stamped after timestamp back until Release(key).\n1147: +func (o *Output) Hold(key any, timestamp int64) {\n1148: +\to.reorder.Hold(key, timestamp)\n1149: +}\n1150: +\n1151: +// Release removes the hold of key.\n1152: +func (o *Output) Release(key any) {\n1153: +\to.reorder.Release(key)\n1154: +}\n1155: +\n1156: +// Close writes the packets still held back and returns the first write error.\n1157: +func (o *Output) Close() error {\n1158: +\to.cancelRun()\n1159: +\t<-o.runDone\n1160: +\to.reorder.Flush()\n1161: +\n1162: +\treturn o.writer.Err()\n1163: +}\n1164: diff --git a/capture/pcapng.go b/capture/pcapng.go\n1165: new file mode 100644\n1166: index 0000000..246ac84\n1167: --- /dev/null\n1168: +++ b/capture/pcapng.go\n1169: @@ -0,0 +1,333 @@\n1170: +// Package capture writes the pcapng streams of `containerlab capture`: one section with one\n1171: +// interface per capture target, packets merged across targets in timestamp order. The local\n1172: +// capturer reads lab link interfaces of Docker and Podman nodes through packet sockets; the c9s\n1173: +// lab runtime feeds the same writer from clabwire streams.\n1174: +package capture\n1175: +\n1176: +import (\n1177: +\t\"bufio\"\n1178: +\t\"encoding/binary\"\n1179: +\t\"errors\"\n1180: +\t\"fmt\"\n1181: +\t\"io\"\n1182: +\t\"math\"\n1183: +\t\"sync\"\n1184: +)\n1185: +\n1186: +// pcapng block layout (https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html). clabwire\n1187: +// writes little-endian sections, and so does the merged stream containerlab writes.\n1188: +const (\n1189: +\tpcapngSectionHeaderType  = 0x0a0d0d0a\n1190: +\tpcapngInterfaceType      = 0x00000001\n1191: +\tpcapngEnhancedPacketType = 0x00000006\n1192: +\tpcapngByteOrderMagic     = 0x1a2b3c4d\n1193: +\tpcapngOptionEnd          = 0\n1194: +\tpcapngOptionUserAppl     = 4\n1195: +\tpcapngOptionIfName       = 2\n1196: +\tpcapngOptionIfTSResol    = 9\n1197: +\tpcapngLinkTypeEthernet   = 1\n1198: +\t// pcapngNanoseconds is the if_tsresol value for 10^-9 s resolution.\n1199: +\tpcapngNanoseconds = 9\n1200: +\t// pcapngMaxBlockLength bounds a block read from a capture stream: a packet of the largest\n1201: +\t// clabwire snap length (1 MiB) plus framing.\n1202: +\tpcapngMaxBlockLength = 1<<20 + 1024\n1203: +\t// captureUserApplication names the writer in the merged section header.\n1204: +\tcaptureUserApplication = \"containerlab\"\n1205: +)\n1206: +\n1207: +var errPCAPNGByteOrder = errors.New(\"pcapng section is not little-endian\")\n1208: +\n1209: +// InterfaceDescription is an Interface Description Block.\n1210: +type InterfaceDescription struct {\n1211: +\tLinkType   uint16\n1212: +\tSnapLength uint32\n1213: +\tName       string\n1214: +\t// TSResol is the raw if_tsresol value; 6 (microseconds) when the block has none.\n1215: +\tTSResol byte\n1216: +}\n1217: +\n1218: +// Packet is an Enhanced Packet Block with its timestamp in nanoseconds.\n1219: +type Packet struct {\n1220: +\tInterfaceID    uint32\n1221: +\tTimestamp      int64\n1222: +\tOriginalLength uint32\n1223: +\tData           []byte\n1224: +}\n1225: +\n1226: +// Reader reads the blocks of a pcapng stream as clabwire writes it: one or more\n1227: +// little-endian sections, each with its Interface Description Blocks before its packets.\n1228: +type Reader struct {\n1229: +\tr          *bufio.Reader\n1230: +\tinterfaces []InterfaceDescription\n1231: +\t// sections counts the Section Header Blocks read so far.\n1232: +\tsections int\n1233: +}\n1234: +\n1235: +// NewReader returns a reader of the pcapng stream r.\n1236: +func NewReader(r io.Reader) *Reader {\n1237: +\treturn &Reader{r: bufio.NewReaderSize(r, 64<<10)}\n1238: +}\n1239: +\n1240: +// Sections returns the number of Section Header Blocks read so far.\n1241: +func (p *Reader) Sections() int {\n1242: +\treturn p.sections\n1243: +}\n1244: +\n1245: +// Event is one block of interest: a new interface or a packet.\n1246: +type Event struct {\n1247: +\tInterface *InterfaceDescription\n1248: +\tPacket    *Packet\n1249: +}\n1250: +\n1251: +// Next returns the next interface or packet, skipping other block types. It returns io.EOF at\n1252: +// the clean end of the stream, and io.ErrUnexpectedEOF for a stream cut inside a block.\n1253: +func (p *Reader) Next() (Event, error) {\n1254: +\tfor {\n1255: +\t\tvar header [8]byte\n1256: +\t\tif _, err := io.ReadFull(p.r, header[:]); err != nil {\n1257: +\t\t\tif errors.Is(err, io.EOF) {\n1258: +\t\t\t\treturn Event{}, io.EOF\n1259: +\t\t\t}\n1260: +\n1261: +\t\t\treturn Event{}, io.ErrUnexpectedEOF\n1262: +\t\t}\n1263: +\n1264: +\t\tblockType := binary.LittleEndian.Uint32(header[0:4])\n1265: +\t\tlength := binary.LittleEndian.Uint32(header[4:8])\n1266: +\t\tif blockType == pcapngSectionHeaderType {\n1267: +\t\t\t// the byte-order magic tells a big-endian section apart before its length is\n1268: +\t\t\t// trusted: that length reads byte swapped\n1269: +\t\t\tmagic, err := p.r.Peek(4)\n1270: +\t\t\tif err != nil {\n1271: +\t\t\t\treturn Event{}, io.ErrUnexpectedEOF\n1272: +\t\t\t}\n1273: +\t\t\tif binary.BigEndian.Uint32(magic) == pcapngByteOrderMagic {\n1274: +\t\t\t\treturn Event{}, errPCAPNGByteOrder\n1275: +\t\t\t}\n1276: +\t\t}\n1277: +\t\tif length < 12 || length%4 != 0 || length > pcapngMaxBlockLength {\n1278: +\t\t\treturn Event{}, fmt.Errorf(\"invalid pcapng block length %d (at most %d)\", length,\n1279: +\t\t\t\tpcapngMaxBlockLength)\n1280: +\t\t}\n1281: +\n1282: +\t\tbody := make([]byte, length-8)\n1283: +\t\tif _, err := io.ReadFull(p.r, body); err != nil {\n1284: +\t\t\treturn Event{}, io.ErrUnexpectedEOF\n1285: +\t\t}\n1286: +\t\tif binary.LittleEndian.Uint32(body[len(body)-4:]) != length {\n1287: +\t\t\treturn Event{}, fmt.Errorf(\"pcapng block lengths do not match\")\n1288: +\t\t}\n1289: +\t\tbody = body[:len(body)-4]\n1290: +\n1291: +\t\tswitch blockType {\n1292: +\t\tcase pcapngSectionHeaderType:\n1293: +\t\t\tif len(body) < 16 {\n1294: +\t\t\t\treturn Event{}, fmt.Errorf(\"short pcapng section header\")\n1295: +\t\t\t}\n1296: +\t\t\tif binary.LittleEndian.Uint32(body[0:4]) != pcapngByteOrderMagic {\n1297: +\t\t\t\treturn Event{}, errPCAPNGByteOrder\n1298: +\t\t\t}\n1299: +\t\t\tp.sections++\n1300: +\t\t\tp.interfaces = nil\n1301: +\t\tcase pcapngInterfaceType:\n1302: +\t\t\tif p.sections == 0 {\n1303: +\t\t\t\treturn Event{}, fmt.Errorf(\"pcapng interface before a section header\")\n1304: +\t\t\t}\n1305: +\t\t\tintf, err := parsePCAPNGInterface(body)\n1306: +\t\t\tif err != nil {\n1307: +\t\t\t\treturn Event{}, err\n1308: +\t\t\t}\n1309: +\t\t\tp.interfaces = append(p.interfaces, intf)\n1310: +\n1311: +\t\t\treturn Event{Interface: &p.interfaces[len(p.interfaces)-1]}, nil\n1312: +\t\tcase pcapngEnhancedPacketType:\n1313: +\t\t\tpacket, err := p.parsePacket(body)\n1314: +\t\t\tif err != nil {\n1315: +\t\t\t\treturn Event{}, err\n1316: +\t\t\t}\n1317: +\n1318: +\t\t\treturn Event{Packet: &packet}, nil\n1319: +\t\t}\n1320: +\t}\n1321: +}\n1322: +\n1323: +func parsePCAPNGInterface(body []byte) (InterfaceDescription, error) {\n1324: +\tif len(body) < 8 {\n1325: +\t\treturn InterfaceDescription{}, fmt.Errorf(\"short pcapng interface description\")\n1326: +\t}\n1327: +\tintf := InterfaceDescription{\n1328: +\t\tLinkType:   binary.LittleEndian.Uint16(body[0:2]),\n1329: +\t\tSnapLength: binary.LittleEndian.Uint32(body[4:8]),\n1330: +\t\tTSResol:    6,\n1331: +\t}\n1332: +\n1333: +\toptions := body[8:]\n1334: +\tfor len(options) >= 4 {\n1335: +\t\tcode := binary.LittleEndian.Uint16(options[0:2])\n1336: +\t\tsize := int(binary.LittleEndian.Uint16(options[2:4]))\n1337: +\t\tif code == pcapngOptionEnd {\n1338: +\t\t\tbreak\n1339: +\t\t}\n1340: +\t\tpadded := size + pcapngPadding(size)\n1341: +\t\tif 4+padded > len(options) {\n1342: +\t\t\treturn InterfaceDescription{}, fmt.Errorf(\"truncated pcapng interface option\")\n1343: +\t\t}\n1344: +\t\tvalue := options[4 : 4+size]\n1345: +\t\tswitch code {\n1346: +\t\tcase pcapngOptionIfName:\n1347: +\t\t\tintf.Name = string(value)\n1348: +\t\tcase pcapngOptionIfTSResol:\n1349: +\t\t\tif size == 1 {\n1350: +\t\t\t\tintf.TSResol = value[0]\n1351: +\t\t\t}\n1352: +\t\t}\n1353: +\t\toptions = options[4+padded:]\n1354: +\t}\n1355: +\n1356: +\treturn intf, nil\n1357: +}\n1358: +\n1359: +func (p *Reader) parsePacket(body []byte) (Packet, error) {\n1360: +\tif len(body) < 20 {\n1361: +\t\treturn Packet{}, fmt.Errorf(\"short pcapng enhanced packet\")\n1362: +\t}\n1363: +\tpacket := Packet{\n1364: +\t\tInterfaceID:    binary.LittleEndian.Uint32(body[0:4]),\n1365: +\t\tOriginalLength: binary.LittleEndian.Uint32(body[16:20]),\n1366: +\t}\n1367: +\tif int(packet.InterfaceID) >= len(p.interfaces) {\n1368: +\t\treturn Packet{}, fmt.Errorf(\"pcapng packet for undeclared interface %d\",\n1369: +\t\t\tpacket.InterfaceID)\n1370: +\t}\n1371: +\tcaptured := binary.LittleEndian.Uint32(body[12:16])\n1372: +\tif int(captured) > len(body)-20 {\n1373: +\t\treturn Packet{}, fmt.Errorf(\"pcapng packet data exceeds its block\")\n1374: +\t}\n1375: +\tpacket.Data = body[20 : 20+captured]\n1376: +\n1377: +\traw := uint64(binary.LittleEndian.Uint32(body[4:8]))<<32 |\n1378: +\t\tuint64(binary.LittleEndian.Uint32(body[8:12]))\n1379: +\ttimestamp, err := pcapngNanosecondsFrom(raw, p.interfaces[packet.InterfaceID].TSResol)\n1380: +\tif err != nil {\n1381: +\t\treturn Packet{}, err\n1382: +\t}\n1383: +\tpacket.Timestamp = timestamp\n1384: +\n1385: +\treturn packet, nil\n1386: +}\n1387: +\n1388: +// pcapngNanosecondsFrom converts a timestamp in an interface's resolution to nanoseconds.\n1389: +// Only decimal resolutions up to nanoseconds occur in clabwire streams.\n1390: +func pcapngNanosecondsFrom(raw uint64, tsresol byte) (int64, error) {\n1391: +\tif tsresol&0x80 != 0 || tsresol > pcapngNanoseconds {\n1392: +\t\treturn 0, fmt.Errorf(\"unsupported pcapng timestamp resolution %#x\", tsresol)\n1393: +\t}\n1394: +\tscale := uint64(1)\n1395: +\tfor range pcapngNanoseconds - int(tsresol) {\n1396: +\t\tscale *= 10\n1397: +\t}\n1398: +\tif raw > math.MaxInt64/scale {\n1399: +\t\treturn 0, fmt.Errorf(\"pcapng timestamp out of range\")\n1400: +\t}\n1401: +\n1402: +\treturn int64(raw * scale), nil //nolint:gosec // bounded above\n1403: +}\n1404: +\n1405: +// Writer writes one little-endian section with nanosecond timestamps. Every block goes out\n1406: +// in one Write under a lock, so concurrent writers never interleave blocks and a stream cut\n1407: +// between writes is still a valid capture.\n1408: +type Writer struct {\n1409: +\tmu  sync.Mutex\n1410: +\tw   io.Writer\n1411: +\terr error\n1412: +}\n1413: +\n1414: +// NewWriter returns a writer of one pcapng section to w.\n1415: +func NewWriter(w io.Writer) *Writer {\n1416: +\treturn &Writer{w: w}\n1417: +}\n1418: +\n1419: +// WriteHeader writes the Section Header Block and one Interface Description Block per name, in\n1420: +// order; packets refer to the interfaces by that index.\n1421: +func (p *Writer) WriteHeader(names []string, snapLength uint32) error {\n1422: +\tsection := make([]byte, 16)\n1423: +\tbinary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)\n1424: +\tbinary.LittleEndian.PutUint16(section[4:], 1)\n1425: +\tbinary.LittleEndian.PutUint16(section[6:], 0)\n1426: +\tbinary.LittleEndian.PutUint64(section[8:], math.MaxUint64)\n1427: +\tsection = appendPCAPNGOption(section, pcapngOptionUserAppl, []byte(captureUserApplication))\n1428: +\tsection = appendPCAPNGOption(section, pcapngOptionEnd, nil)\n1429: +\n1430: +\theader := pcapngBlock(pcapngSectionHeaderType, section)\n1431: +\tfor _, name := range names {\n1432: +\t\tdescription := make([]byte, 8)\n1433: +\t\tbinary.LittleEndian.PutUint16(description[0:], pcapngLinkTypeEthernet)\n1434: +\t\tbinary.LittleEndian.PutUint32(description[4:], snapLength)\n1435: +\t\tdescription = appendPCAPNGOption(description, pcapngOptionIfName, []byte(name))\n1436: +\t\tdescription = appendPCAPNGOption(description, pcapngOptionIfTSResol,\n1437: +\t\t\t[]byte{pcapngNanoseconds})\n1438: +\t\tdescription = appendPCAPNGOption(description, pcapngOptionEnd, nil)\n1439: +\t\theader = append(header, pcapngBlock(pcapngInterfaceType, description)...)\n1440: +\t}\n1441: +\n1442: +\treturn p.write(header)\n1443: +}\n1444: +\n1445: +// WritePacket writes an Enhanced Packet Block for the interface with the given index.\n1446: +func (p *Writer) WritePacket(interfaceID uint32, packet *Packet) error {\n1447: +\ttimestamp := uint64(packet.Timestamp) //nolint:gosec // capture timestamps are positive\n1448: +\tbody := make([]byte, 20, 20+len(packet.Data)+3)\n1449: +\tbinary.LittleEndian.PutUint32(body[0:], interfaceID)\n1450: +\tbinary.LittleEndian.PutUint32(body[4:], uint32(timestamp>>32))\n1451: +\tbinary.LittleEndian.PutUint32(body[8:], uint32(timestamp)) //nolint:gosec // low 32 bits\n1452: +\tbinary.LittleEndian.PutUint32(body[12:], uint32(len(packet.Data)))\n1453: +\tbinary.LittleEndian.PutUint32(body[16:], packet.OriginalLength)\n1454: +\tbody = append(body, packet.Data...)\n1455: +\tbody = append(body, make([]byte, pcapngPadding(len(packet.Data)))...)\n1456: +\n1457: +\treturn p.write(pcapngBlock(pcapngEnhancedPacketType, body))\n1458: +}\n1459: +\n1460: +// Err returns the first write error, or nil.\n1461: +func (p *Writer) Err() error {\n1462: +\tp.mu.Lock()\n1463: +\tdefer p.mu.Unlock()\n1464: +\n1465: +\treturn p.err\n1466: +}\n1467: +\n1468: +func (p *Writer) write(block []byte) error {\n1469: +\tp.mu.Lock()\n1470: +\tdefer p.mu.Unlock()\n1471: +\n1472: +\tif p.err != nil {\n1473: +\t\treturn p.err\n1474: +\t}\n1475: +\tif _, err := p.w.Write(block); err != nil {\n1476: +\t\tp.err = fmt.Errorf(\"failed to write the capture: %w\", err)\n1477: +\t}\n1478: +\n1479: +\treturn p.err\n1480: +}\n1481: +\n1482: +func pcapngBlock(blockType uint32, body []byte) []byte {\n1483: +\ttotal := uint32(12 + len(body)) //nolint:gosec // bounded by the snap length\n1484: +\tblock := make([]byte, 8, total)\n1485: +\tbinary.LittleEndian.PutUint32(block[0:], blockType)\n1486: +\tbinary.LittleEndian.PutUint32(block[4:], total)\n1487: +\tblock = append(block, body...)\n1488: +\n1489: +\treturn binary.LittleEndian.AppendUint32(block, total)\n1490: +}\n1491: +\n1492: +func appendPCAPNGOption(body []byte, code uint16, value []byte) []byte {\n1493: +\tbody = binary.LittleEndian.AppendUint16(body, code)\n1494: +\tbody = binary.LittleEndian.AppendUint16(body, uint16(len(value))) //nolint:gosec // short\n1495: +\tbody = append(body, value...)\n1496: +\n1497: +\treturn append(body, make([]byte, pcapngPadding(len(value)))...)\n1498: +}\n1499: +\n1500: +func pcapngPadding(length int) int {\n1501: +\treturn (4 - length%4) % 4\n1502: +}\n1503: diff --git a/capture/pcapng_test.go b/capture/pcapng_test.go\n1504: new file mode 100644\n1505: index 0000000..0917d16\n1506: --- /dev/null\n1507: +++ b/capture/pcapng_test.go\n1508: @@ -0,0 +1,167 @@\n1509: +package capture\n1510: +\n1511: +import (\n1512: +\t\"bytes\"\n1513: +\t\"encoding/binary\"\n1514: +\t\"errors\"\n1515: +\t\"io\"\n1516: +\t\"strings\"\n1517: +\t\"testing\"\n1518: +)\n1519: +\n1520: +func TestPCAPNGWriterAndReaderRoundTrip(t *testing.T) {\n1521: +\tt.Parallel()\n1522: +\n1523: +\tvar out bytes.Buffer\n1524: +\twriter := NewWriter(&out)\n1525: +\tif err := writer.WriteHeader([]string{\"r1:e1-1\", \"r2:eth1\"}, 1500); err != nil {\n1526: +\t\tt.Fatal(err)\n1527: +\t}\n1528: +\tpackets := []Packet{\n1529: +\t\t{\n1530: +\t\t\tInterfaceID:    1,\n1531: +\t\t\tTimestamp:      1_761_559_200_123_456_789,\n1532: +\t\t\tOriginalLength: 98,\n1533: +\t\t\tData:           []byte(\"abcde\"),\n1534: +\t\t},\n1535: +\t\t{\n1536: +\t\t\tInterfaceID:    0,\n1537: +\t\t\tTimestamp:      1_761_559_200_123_456_790,\n1538: +\t\t\tOriginalLength: 4,\n1539: +\t\t\tData:           []byte(\"wxyz\"),\n1540: +\t\t},\n1541: +\t}\n1542: +\tfor idx := range packets {\n1543: +\t\tif err := writer.WritePacket(packets[idx].InterfaceID, &packets[idx]); err != nil {\n1544: +\t\t\tt.Fatal(err)\n1545: +\t\t}\n1546: +\t}\n1547: +\n1548: +\tdata := out.Bytes()\n1549: +\t// the section header names the writer\n1550: +\tif !bytes.Contains(data[:64], []byte(captureUserApplication)) {\n1551: +\t\tt.Fatal(\"section header has no shb_userappl\")\n1552: +\t}\n1553: +\tif len(data)%4 != 0 {\n1554: +\t\tt.Fatalf(\"stream length %d is not 32-bit aligned\", len(data))\n1555: +\t}\n1556: +\n1557: +\treader := NewReader(bytes.NewReader(data))\n1558: +\tvar names []string\n1559: +\tvar read []Packet\n1560: +\tfor {\n1561: +\t\tevent, err := reader.Next()\n1562: +\t\tif errors.Is(err, io.EOF) {\n1563: +\t\t\tbreak\n1564: +\t\t}\n1565: +\t\tif err != nil {\n1566: +\t\t\tt.Fatal(err)\n1567: +\t\t}\n1568: +\t\tif event.Interface != nil {\n1569: +\t\t\tnames = append(names, event.Interface.Name)\n1570: +\t\t\tif event.Interface.SnapLength != 1500 || event.Interface.LinkType != 1 {\n1571: +\t\t\t\tt.Fatalf(\"interface = %+v\", event.Interface)\n1572: +\t\t\t}\n1573: +\t\t}\n1574: +\t\tif event.Packet != nil {\n1575: +\t\t\tread = append(read, *event.Packet)\n1576: +\t\t}\n1577: +\t}\n1578: +\tif len(names) != 2 || names[0] != \"r1:e1-1\" || names[1] != \"r2:eth1\" {\n1579: +\t\tt.Fatalf(\"names = %v\", names)\n1580: +\t}\n1581: +\tfor idx := range packets {\n1582: +\t\tif read[idx].InterfaceID != packets[idx].InterfaceID ||\n1583: +\t\t\tread[idx].Timestamp != packets[idx].Timestamp ||\n1584: +\t\t\tread[idx].OriginalLength != packets[idx].OriginalLength ||\n1585: +\t\t\t!bytes.Equal(read[idx].Data, packets[idx].Data) {\n1586: +\t\t\tt.Fatalf(\"packet %d = %+v, want %+v\", idx, read[idx], packets[idx])\n1587: +\t\t}\n1588: +\t}\n1589: +}\n1590: +\n1591: +func TestPCAPNGReaderHandlesRepeatedSectionsAndResolutions(t *testing.T) {\n1592: +\tt.Parallel()\n1593: +\n1594: +\tvar out bytes.Buffer\n1595: +\tfirst := NewWriter(&out)\n1596: +\t_ = first.WriteHeader([]string{\"eth1\"}, 64)\n1597: +\t_ = first.WritePacket(0, &Packet{Timestamp: 5, Data: []byte{1}})\n1598: +\n1599: +\t// a second section whose interface has microsecond timestamps (no if_tsresol)\n1600: +\tsection := make([]byte, 16)\n1601: +\tbinary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)\n1602: +\tbinary.LittleEndian.PutUint16(section[4:], 1)\n1603: +\tout.Write(pcapngBlock(pcapngSectionHeaderType, section))\n1604: +\tdescription := make([]byte, 8)\n1605: +\tbinary.LittleEndian.PutUint16(description[0:], 1)\n1606: +\tdescription = appendPCAPNGOption(description, pcapngOptionIfName, []byte(\"eth2\"))\n1607: +\tout.Write(pcapngBlock(pcapngInterfaceType, description))\n1608: +\tbody := make([]byte, 20)\n1609: +\tbinary.LittleEndian.PutUint32(body[8:], 7) // 7 microseconds\n1610: +\tout.Write(pcapngBlock(pcapngEnhancedPacketType, body))\n1611: +\n1612: +\treader := NewReader(&out)\n1613: +\tvar timestamps []int64\n1614: +\tfor {\n1615: +\t\tevent, err := reader.Next()\n1616: +\t\tif errors.Is(err, io.EOF) {\n1617: +\t\t\tbreak\n1618: +\t\t}\n1619: +\t\tif err != nil {\n1620: +\t\t\tt.Fatal(err)\n1621: +\t\t}\n1622: +\t\tif event.Packet != nil {\n1623: +\t\t\ttimestamps = append(timestamps, event.Packet.Timestamp)\n1624: +\t\t}\n1625: +\t}\n1626: +\tif reader.sections != 2 || len(timestamps) != 2 || timestamps[0] != 5 || timestamps[1] != 7000 {\n1627: +\t\tt.Fatalf(\"sections %d, timestamps %v\", reader.sections, timestamps)\n1628: +\t}\n1629: +}\n1630: +\n1631: +func TestPCAPNGReaderRejectsInvalidStreams(t *testing.T) {\n1632: +\tt.Parallel()\n1633: +\n1634: +\tvar valid bytes.Buffer\n1635: +\twriter := NewWriter(&valid)\n1636: +\t_ = writer.WriteHeader([]string{\"eth1\"}, 64)\n1637: +\t_ = writer.WritePacket(0, &Packet{Timestamp: 1, Data: []byte(\"data\")})\n1638: +\n1639: +\treadAll := func(data []byte) error {\n1640: +\t\treader := NewReader(bytes.NewReader(data))\n1641: +\t\tfor {\n1642: +\t\t\t_, err := reader.Next()\n1643: +\t\t\tif errors.Is(err, io.EOF) {\n1644: +\t\t\t\treturn nil\n1645: +\t\t\t}\n1646: +\t\t\tif err != nil {\n1647: +\t\t\t\treturn err\n1648: +\t\t\t}\n1649: +\t\t}\n1650: +\t}\n1651: +\n1652: +\tif err := readAll(valid.Bytes()[:valid.Len()-6]); !errors.Is(err, io.ErrUnexpectedEOF) {\n1653: +\t\tt.Fatalf(\"truncated stream: %v\", err)\n1654: +\t}\n1655: +\n1656: +\tbigEndian := append([]byte(nil), valid.Bytes()...)\n1657: +\tbinary.BigEndian.PutUint32(bigEndian[4:], binary.LittleEndian.Uint32(bigEndian[4:]))\n1658: +\tbinary.BigEndian.PutUint32(bigEndian[8:], pcapngByteOrderMagic)\n1659: +\tif err := readAll(bigEndian); !errors.Is(err, errPCAPNGByteOrder) {\n1660: +\t\tt.Fatalf(\"big-endian section: %v\", err)\n1661: +\t}\n1662: +\n1663: +\t// a little-endian section header longer than the reader accepts is not a byte-order error\n1664: +\toversized := append([]byte(nil), valid.Bytes()...)\n1665: +\tbinary.LittleEndian.PutUint32(oversized[4:], 2<<20)\n1666: +\tif err := readAll(oversized); err == nil || errors.Is(err, errPCAPNGByteOrder) ||\n1667: +\t\t!strings.Contains(err.Error(), \"invalid pcapng block length\") {\n1668: +\t\tt.Fatalf(\"oversized little-endian section: %v\", err)\n1669: +\t}\n1670: +\n1671: +\tpacketFirst := pcapngBlock(pcapngEnhancedPacketType, make([]byte, 20))\n1672: +\tif err := readAll(packetFirst); err == nil {\n1673: +\t\tt.Fatal(\"packet before any interface accepted\")\n1674: +\t}\n1675: +}\n1676: diff --git a/capture/reorder.go b/capture/reorder.go\n1677: new file mode 100644\n1678: index 0000000..277ba1a\n1679: --- /dev/null\n1680: +++ b/capture/reorder.go\n1681: @@ -0,0 +1,271 @@\n1682: +package capture\n1683: +\n1684: +import (\n1685: +\t\"container/heap\"\n1686: +\t\"context\"\n1687: +\t\"sync\"\n1688: +\t\"time\"\n1689: +\n1690: +\t\"github.com/charmbracelet/log\"\n1691: +)\n1692: +\n1693: +// maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets\n1694: +// are written early, which can put them out of order.\n1695: +const maxReorderBytes = 64 << 20\n1696: +\n1697: +// Reorder writes the packets of several capture sources in timestamp order.\n1698: +//\n1699: +// Each source (a node's capture stream, or a local interface socket) delivers its packets with\n1700: +// its own delay. The buffer holds every packet for `window` after it arrived and writes the held\n1701: +// packets in timestamp order, so a packet that was stamped earlier but delivered up to `window`\n\n(Output capped at 50 KB. Showing lines 1-1701. Use offset=1702 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "diff --git a/.github/workflows/clabernetes-tests.yml b/.github/workflows/clabernetes-tests.yml\nindex b1cbd00..7785167 100644\n--- a/.github/workflows/clabernetes-tests.yml\n+++ b/.github/workflows/clabernetes-tests.yml\n@@ -100,10 +100,15 @@ jobs:\n             upgrade --install --create-namespace --namespace c9s \\\n               clabernetes oci://ghcr.io/clabernetes/clabernetes/clabernetes:0.0.0\n \n           kubectl -n c9s rollout status deploy/clabernetes-manager --timeout=180s\n \n+      - name: Install tshark\n+        run: |\n+          sudo apt-get update\n+          sudo DEBIAN_FRONTEND=noninteractive apt-get install -y tshark\n+\n       - name: Run Clabernetes Robot tests\n         run: |\n           bash ./tests/rf-run.sh c9s ./tests/14-clabernetes\n \n       - name: Upload test report",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "diff --git a/.github/workflows/clabernetes-tests.yml b/.github/workflows/clabernetes-tests.yml\nindex b1cbd00..7785167 100644\n--- a/.github/workflows/clabernetes-tests.yml\n+++ b/.github/workflows/clabernetes-tests.yml\n@@ -100,10 +100,15 @@ jobs:\n             upgrade --install --create-namespace --namespace c9s \\\n               clabernetes oci://ghcr.io/clabernetes/clabernetes/clabernetes:0.0.0\n \n           kubectl -n c9s rollout status deploy/clabernetes-manager --timeout=180s\n \n+      - name: Install tshark\n+        run: |\n+          sudo apt-get update\n+          sudo DEBIAN_FRONTEND=noninteractive apt-get install -y tshark\n+\n       - name: Run Clabernetes Robot tests\n         run: |\n           bash ./tests/rf-run.sh c9s ./tests/14-clabernetes\n \n       - name: Upload test report\ndiff --git a/.github/workflows/smoke-tests.yml b/.github/workflows/smoke-tests.yml\nindex 807acbe..f7ee3c8 100644\n--- a/.github/workflows/smoke-tests.yml\n+++ b/.github/workflows/smoke-tests.yml\n@@ -51,10 +51,11 @@ jobs:\n           - \"28*.robot\"\n           - \"29*.robot\"\n           - \"30*.robot\"\n           - \"31*.robot\"\n           - \"32*.robot\"\n+          - \"33*.robot\"\n \n     # allow podman job to fail, since it started to fail on github actions\n     continue-on-error: ${{ inputs.runtime == 'podman' }}\n     steps:\n       - name: Checkout\ndiff --git a/capture/local.go b/capture/local.go\nnew file mode 100644\nindex 0000000..58dc8aa\n--- /dev/null\n+++ b/capture/local.go\n@@ -0,0 +1,430 @@\n+package capture\n+\n+import (\n+\t\"context\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"os\"\n+\t\"sync\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\t\"github.com/containernetworking/plugins/pkg/ns\"\n+\t\"github.com/gopacket/gopacket\"\n+\t\"github.com/gopacket/gopacket/afpacket\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+)\n+\n+const (\n+\t// localReorderWindow is how long the merged stream holds packets of local sockets back to\n+\t// write them in timestamp order. Each socket hands over its packets within\n+\t// localBlockTimeout, so a few times that covers the delivery skew between sockets.\n+\tlocalReorderWindow = 100 * time.Millisecond\n+\t// localBlockTimeout is how long the kernel fills a ring block before it hands it over.\n+\tlocalBlockTimeout = 10 * time.Millisecond\n+\t// localPollTimeout is how often a socket reader checks whether the capture ended.\n+\tlocalPollTimeout = 100 * time.Millisecond\n+\t// localReopenInterval is how often a reader tries to reopen the socket of an interface\n+\t// that went down or disappeared.\n+\tlocalReopenInterval = 200 * time.Millisecond\n+\t// localDrainQuiet is how long after the end of a capture a reader keeps waiting for packets\n+\t// still in the socket's ring: the kernel hands over a block within two block timeouts.\n+\tlocalDrainQuiet = 5 * localBlockTimeout\n+\t// localDrainTimeout bounds the drain while packets keep arriving.\n+\tlocalDrainTimeout = 250 * time.Millisecond\n+\t// localRingBlocks and localMinBlockSize size the receive ring of each socket: eight blocks\n+\t// of at least 1 MiB, each larger than the snap length.\n+\tlocalRingBlocks   = 8\n+\tlocalMinBlockSize = 1 << 20\n+\t// vlanHeaderLength is the length of the 802.1Q tag put back into frames whose tag the\n+\t// kernel moved out of band.\n+\tvlanHeaderLength = 4\n+)\n+\n+// errReadTimeout is returned by a packet source that has no packet within the poll timeout.\n+var errReadTimeout = errors.New(\"no packet within the poll timeout\")\n+\n+// ExecFunc runs f in the network namespace of a node.\n+type ExecFunc func(ctx context.Context, f func(ns.NetNS) error) error\n+\n+// LocalTarget is one interface of a node on this machine (Docker or Podman) to capture.\n+type LocalTarget struct {\n+\t// Node is the node name as the topology spells it.\n+\tNode string\n+\t// Interface is the interface name inside the node.\n+\tInterface string\n+\t// Exec runs a function in the node's network namespace.\n+\tExec ExecFunc\n+}\n+\n+// packetSource reads the packets of one interface.\n+type packetSource interface {\n+\t// ReadPacket returns the next packet; the data is only valid until the next call. It\n+\t// returns errReadTimeout when no packet arrived within the poll timeout.\n+\tReadPacket() ([]byte, gopacket.CaptureInfo, error)\n+\tClose()\n+}\n+\n+// openSourcesFunc opens one packet source per interface in the network namespace exec enters.\n+type openSourcesFunc func(\n+\tctx context.Context,\n+\texec ExecFunc,\n+\tinterfaces []string,\n+\tsnapLength int,\n+) ([]packetSource, error)\n+\n+// CaptureLocal streams pcapng from interfaces of nodes on this machine to w, with the same\n+// output and end conditions as labruntime.PacketCapturer.Capture: one section, one Interface\n+// Description Block per target named <node>:<interface>, then the packets of every target in\n+// timestamp order. targets lists the interfaces of req.Targets, resolved, in the same order.\n+//\n+// Each interface is read through a packet socket opened in the node's network namespace, so\n+// nothing runs in the node and the node image needs no capture tools; it needs CAP_NET_RAW and\n+// the right to enter the namespace, so root. An interface that goes down is reopened once it is\n+// up again; one that disappears (its node stopped or was recreated) is reattached when it is\n+// back, and the time it was gone is reported as a gap through req.OnGap (or logged).\n+func CaptureLocal(\n+\tctx context.Context,\n+\treq clablabruntime.CaptureRequest,\n+\ttargets []LocalTarget,\n+\tw io.Writer,\n+) error {\n+\treturn localCapture{\n+\t\topen:           openPacketSockets,\n+\t\twindow:         localReorderWindow,\n+\t\treopenInterval: localReopenInterval,\n+\t}.run(ctx, req, targets, w)\n+}\n+\n+// localCapture is a local capture with its socket opener and timings, which tests replace.\n+type localCapture struct {\n+\topen           openSourcesFunc\n+\twindow         time.Duration\n+\treopenInterval time.Duration\n+}\n+\n+func (l localCapture) run(\n+\tctx context.Context,\n+\treq clablabruntime.CaptureRequest,\n+\ttargets []LocalTarget,\n+\tw io.Writer,\n+) error {\n+\tif err := ValidateRequest(&req); err != nil {\n+\t\treturn err\n+\t}\n+\tif len(targets) != len(req.Targets) {\n+\t\treturn fmt.Errorf(\"capture has %d resolved targets for %d requested ones\",\n+\t\t\tlen(targets), len(req.Targets))\n+\t}\n+\n+\tsources, err := l.openAll(ctx, targets, req.SnapLength)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tnames := make([]string, len(targets))\n+\tfor idx, target := range targets {\n+\t\tnames[idx] = target.Node + \":\" + target.Interface\n+\t}\n+\n+\tcaptureCtx, stop := context.WithCancel(ctx)\n+\tdefer stop()\n+\tif req.Duration > 0 {\n+\t\tvar cancelTimeout context.CancelFunc\n+\t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx, req.Duration)\n+\t\tdefer cancelTimeout()\n+\t}\n+\n+\tout, err := NewOutput(w, names, req.SnapLength, req.PacketLimit, l.window, stop)\n+\tif err != nil {\n+\t\tfor _, source := range sources {\n+\t\t\tsource.Close()\n+\t\t}\n+\n+\t\treturn err\n+\t}\n+\n+\tvar wg sync.WaitGroup\n+\tfor idx, source := range sources {\n+\t\treader := &localReader{\n+\t\t\tcapture: l,\n+\t\t\tout:     out,\n+\t\t\tid:      uint32(idx), //nolint:gosec // bounded by the targets\n+\t\t\ttarget:  targets[idx],\n+\t\t\tsnap:    req.SnapLength,\n+\t\t\tonGap:   req.OnGap,\n+\t\t}\n+\t\twg.Go(func() {\n+\t\t\treader.run(captureCtx, source)\n+\t\t})\n+\t}\n+\twg.Wait()\n+\n+\treturn out.Close()\n+}\n+\n+// openAll opens the sockets of every target before anything is written, one namespace entry\n+// per node, so a capture that cannot start fails without output.\n+func (l localCapture) openAll(\n+\tctx context.Context,\n+\ttargets []LocalTarget,\n+\tsnapLength int,\n+) ([]packetSource, error) {\n+\ttype nodeTargets struct {\n+\t\texec    ExecFunc\n+\t\tindexes []int\n+\t\tnames   []string\n+\t}\n+\tvar order []string\n+\tbyNode := map[string]*nodeTargets{}\n+\tfor idx, target := range targets {\n+\t\tgroup := byNode[target.Node]\n+\t\tif group == nil {\n+\t\t\tgroup = &nodeTargets{exec: target.Exec}\n+\t\t\tbyNode[target.Node] = group\n+\t\t\torder = append(order, target.Node)\n+\t\t}\n+\t\tgroup.indexes = append(group.indexes, idx)\n+\t\tgroup.names = append(group.names, target.Interface)\n+\t}\n+\n+\tsources := make([]packetSource, len(targets))\n+\tcloseAll := func() {\n+\t\tfor _, source := range sources {\n+\t\t\tif source != nil {\n+\t\t\t\tsource.Close()\n+\t\t\t}\n+\t\t}\n+\t}\n+\tfor _, node := range order {\n+\t\tgroup := byNode[node]\n+\t\topened, err := l.open(ctx, group.exec, group.names, snapLength)\n+\t\tif err != nil {\n+\t\t\tcloseAll()\n+\t\t\treturn nil, fmt.Errorf(\"failed to start the capture on node %q: %w\", node, err)\n+\t\t}\n+\t\tfor idx, source := range opened {\n+\t\t\tsources[group.indexes[idx]] = source\n+\t\t}\n+\t}\n+\n+\treturn sources, nil\n+}\n+\n+// localReader reads one interface into the merged stream.\n+type localReader struct {\n+\tcapture localCapture\n+\tout     *Output\n+\tid      uint32\n+\ttarget  LocalTarget\n+\tsnap    int\n+\tonGap   func(clablabruntime.CaptureGap)\n+}\n+\n+func (r *localReader) run(ctx context.Context, source packetSource) {\n+\tdefer func() {\n+\t\tif source != nil {\n+\t\t\tsource.Close()\n+\t\t}\n+\t}()\n+\n+\tfor {\n+\t\tif ctx.Err() != nil {\n+\t\t\tr.drain(source, time.Now())\n+\t\t\treturn\n+\t\t}\n+\n+\t\tdata, info, err := source.ReadPacket()\n+\t\tif errors.Is(err, errReadTimeout) {\n+\t\t\tcontinue\n+\t\t}\n+\t\tif err != nil {\n+\t\t\t// The socket reports an error once its interface went down or was removed, and\n+\t\t\t// keeps reporting it: it is reopened.\n+\t\t\tlog.Debug(\"Capture socket failed, reopening it\", \"node\", r.target.Node,\n+\t\t\t\t\"interface\", r.target.Interface, \"error\", err)\n+\t\t\tsource.Close()\n+\t\t\tsource = r.reopen(ctx)\n+\t\t\tif source == nil {\n+\t\t\t\treturn\n+\t\t\t}\n+\n+\t\t\tcontinue\n+\t\t}\n+\n+\t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n+\t\t\treturn\n+\t\t}\n+\t}\n+}\n+\n+// drain writes the packets that arrived before end but were still in the socket's ring: the\n+// kernel hands over a ring block once it is full or its block timeout passed, so the last\n+// packets before a capture ended may not have been read yet.\n+func (r *localReader) drain(source packetSource, end time.Time) {\n+\tdeadline := end.Add(localDrainTimeout)\n+\tfor time.Now().Before(deadline) {\n+\t\tdata, info, err := source.ReadPacket()\n+\t\tif errors.Is(err, errReadTimeout) && time.Since(end) < localDrainQuiet {\n+\t\t\tcontinue\n+\t\t}\n+\t\tif err != nil || info.Timestamp.After(end) {\n+\t\t\treturn\n+\t\t}\n+\t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n+\t\t\treturn\n+\t\t}\n+\t}\n+}\n+\n+// packet copies a packet out of the socket's ring, cut to the snap length.\n+func (r *localReader) packet(data []byte, info gopacket.CaptureInfo) *Packet {\n+\tlength := info.Length\n+\tfor _, ancillary := range info.AncillaryData {\n+\t\tif _, ok := ancillary.(afpacket.AncillaryVLAN); ok {\n+\t\t\t// the tag was put back into the data and counts toward the frame length\n+\t\t\tlength += vlanHeaderLength\n+\t\t\tbreak\n+\t\t}\n+\t}\n+\tlength = max(length, len(data))\n+\n+\tcaptured := make([]byte, min(len(data), r.snap))\n+\tcopy(captured, data)\n+\n+\treturn &Packet{\n+\t\tTimestamp:      info.Timestamp.UnixNano(),\n+\t\tOriginalLength: uint32(length), //nolint:gosec // bounded by the interface MTU\n+\t\tData:           captured,\n+\t}\n+}\n+\n+// reopen opens the interface's socket again once its node and interface are back. It returns\n+// nil when the capture ended first. Time the interface could not be opened is reported as a gap;\n+// an interface that only went down is not, as it has no traffic while down.\n+func (r *localReader) reopen(ctx context.Context) packetSource {\n+\tfrom := time.Now()\n+\tvar unavailable error\n+\n+\ttimer := time.NewTimer(r.capture.reopenInterval)\n+\tdefer timer.Stop()\n+\n+\tfor {\n+\t\tselect {\n+\t\tcase <-ctx.Done():\n+\t\t\tif unavailable != nil {\n+\t\t\t\tr.reportGap(from, time.Time{}, unavailable)\n+\t\t\t}\n+\n+\t\t\treturn nil\n+\t\tcase <-timer.C:\n+\t\t}\n+\n+\t\topened, err := r.capture.open(ctx, r.target.Exec, []string{r.target.Interface}, r.snap)\n+\t\tif err != nil {\n+\t\t\tif unavailable == nil {\n+\t\t\t\tlog.Debug(\"Capture interface is not available, waiting for it\",\n+\t\t\t\t\t\"node\", r.target.Node, \"interface\", r.target.Interface, \"error\", err)\n+\t\t\t}\n+\t\t\tunavailable = err\n+\t\t\tresetTimer(timer, r.capture.reopenInterval)\n+\n+\t\t\tcontinue\n+\t\t}\n+\t\tif unavailable != nil {\n+\t\t\tr.reportGap(from, time.Now(), unavailable)\n+\t\t}\n+\n+\t\treturn opened[0]\n+\t}\n+}\n+\n+func (r *localReader) reportGap(from, to time.Time, cause error) {\n+\tReportGap(r.onGap, clablabruntime.CaptureGap{\n+\t\tNode:       r.target.Node,\n+\t\tInterfaces: []string{r.target.Interface},\n+\t\tFrom:       from,\n+\t\tTo:         to,\n+\t\tReason:     fmt.Sprintf(\"the interface was not available: %v\", cause),\n+\t})\n+}\n+\n+// openPacketSockets opens one packet socket per interface in the namespace exec enters. A socket\n+// stays bound to its interface after the thread left the namespace.\n+func openPacketSockets(\n+\tctx context.Context,\n+\texec ExecFunc,\n+\tinterfaces []string,\n+\tsnapLength int,\n+) ([]packetSource, error) {\n+\tsources := make([]packetSource, 0, len(interfaces))\n+\terr := exec(ctx, func(ns.NetNS) error {\n+\t\tfor _, name := range interfaces {\n+\t\t\tsource, err := openPacketSocket(name, snapLength)\n+\t\t\tif err != nil {\n+\t\t\t\treturn fmt.Errorf(\"interface %q: %w\", name, err)\n+\t\t\t}\n+\t\t\tsources = append(sources, source)\n+\t\t}\n+\n+\t\treturn nil\n+\t})\n+\tif err != nil {\n+\t\tfor _, source := range sources {\n+\t\t\tsource.Close()\n+\t\t}\n+\n+\t\treturn nil, err\n+\t}\n+\n+\treturn sources, nil\n+}\n+\n+// afpacketSource is a TPACKET_V3 receive ring on one interface.\n+type afpacketSource struct {\n+\thandle *afpacket.TPacket\n+}\n+\n+func openPacketSocket(name string, snapLength int) (*afpacketSource, error) {\n+\t// A TPACKET_V3 block holds whole frames: it must be larger than the snap length, plus the\n+\t// block and frame headers, and a multiple of the page size.\n+\tpageSize := os.Getpagesize()\n+\tblockSize := max(localMinBlockSize, snapLength+pageSize)\n+\tblockSize = (blockSize + pageSize - 1) / pageSize * pageSize\n+\n+\thandle, err := afpacket.NewTPacket(\n+\t\tafpacket.OptInterface(name),\n+\t\tafpacket.OptTPacketVersion(afpacket.TPacketVersion3),\n+\t\tafpacket.OptFrameSize(blockSize),\n+\t\tafpacket.OptBlockSize(blockSize),\n+\t\tafpacket.OptNumBlocks(localRingBlocks),\n+\t\tafpacket.OptBlockTimeout(localBlockTimeout),\n+\t\tafpacket.OptPollTimeout(localPollTimeout),\n+\t\t// the kernel moves 802.1Q tags out of the frame; captures show them in place\n+\t\tafpacket.OptAddVLANHeader(true),\n+\t)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\t// promiscuous mode is a membership of this socket and ends with it\n+\tif err := handle.SetPromiscuous(true); err != nil {\n+\t\thandle.Close()\n+\t\treturn nil, fmt.Errorf(\"failed to enable promiscuous mode: %w\", err)\n+\t}\n+\n+\treturn &afpacketSource{handle: handle}, nil\n+}\n+\n+func (s *afpacketSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {\n+\tdata, info, err := s.handle.ZeroCopyReadPacketData()\n+\tif errors.Is(err, afpacket.ErrTimeout) {\n+\t\treturn nil, info, errReadTimeout\n+\t}\n+\n+\treturn data, info, err\n+}\n+\n+func (s *afpacketSource) Close() {\n+\ts.handle.Close()\n+}\ndiff --git a/capture/local_test.go b/capture/local_test.go\nnew file mode 100644\nindex 0000000..f91bb00\n--- /dev/null\n+++ b/capture/local_test.go\n@@ -0,0 +1,476 @@\n+package capture\n+\n+import (\n+\t\"bytes\"\n+\t\"context\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"slices\"\n+\t\"strings\"\n+\t\"sync\"\n+\t\"testing\"\n+\t\"time\"\n+\n+\t\"github.com/containernetworking/plugins/pkg/ns\"\n+\t\"github.com/gopacket/gopacket\"\n+\t\"github.com/gopacket/gopacket/afpacket\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+)\n+\n+// fakeFrame is one packet a fake source returns.\n+type fakeFrame struct {\n+\tdata   []byte\n+\tstamp  time.Time\n+\tlength int\n+\tvlan   bool\n+\t// visible delays the frame like a ring block the kernel has not handed over yet.\n+\tvisible time.Time\n+\t// err ends the source with this error instead of a packet.\n+\terr error\n+}\n+\n+// fakeSource returns frames from a channel, errReadTimeout while none is queued.\n+type fakeSource struct {\n+\tframes  chan fakeFrame\n+\tclosed  chan struct{}\n+\tonce    sync.Once\n+\tpending *fakeFrame\n+}\n+\n+func newFakeSource() *fakeSource {\n+\treturn &fakeSource{frames: make(chan fakeFrame, 64), closed: make(chan struct{})}\n+}\n+\n+func (s *fakeSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {\n+\tif s.pending == nil {\n+\t\tselect {\n+\t\tcase frame := <-s.frames:\n+\t\t\ts.pending = &frame\n+\t\tcase <-time.After(5 * time.Millisecond):\n+\t\t\treturn nil, gopacket.CaptureInfo{}, errReadTimeout\n+\t\t}\n+\t}\n+\tif wait := time.Until(s.pending.visible); wait > 0 {\n+\t\ttime.Sleep(min(wait, 5*time.Millisecond))\n+\t\tif time.Now().Before(s.pending.visible) {\n+\t\t\treturn nil, gopacket.CaptureInfo{}, errReadTimeout\n+\t\t}\n+\t}\n+\n+\t{\n+\t\tframe := *s.pending\n+\t\ts.pending = nil\n+\t\tif frame.err != nil {\n+\t\t\treturn nil, gopacket.CaptureInfo{}, frame.err\n+\t\t}\n+\t\tinfo := gopacket.CaptureInfo{\n+\t\t\tTimestamp: frame.stamp, CaptureLength: len(frame.data), Length: frame.length,\n+\t\t}\n+\t\tif frame.vlan {\n+\t\t\tinfo.AncillaryData = []any{afpacket.AncillaryVLAN{VLAN: 10}}\n+\t\t}\n+\n+\t\treturn frame.data, info, nil\n+\t}\n+}\n+\n+func (s *fakeSource) Close() {\n+\ts.once.Do(func() { close(s.closed) })\n+}\n+\n+// fakeHost hands out fake sources per node and interface. Opening an interface listed in\n+// missing fails, like an interface whose node does not run.\n+type fakeHost struct {\n+\tmu      sync.Mutex\n+\topened  map[string][]*fakeSource\n+\tmissing map[string]bool\n+\tready   chan string\n+}\n+\n+func newFakeHost() *fakeHost {\n+\treturn &fakeHost{\n+\t\topened: map[string][]*fakeSource{}, missing: map[string]bool{},\n+\t\tready: make(chan string, 64),\n+\t}\n+}\n+\n+func (h *fakeHost) exec(node string) ExecFunc {\n+\treturn func(_ context.Context, f func(ns.NetNS) error) error {\n+\t\th.mu.Lock()\n+\t\tmissing := h.missing[node]\n+\t\th.mu.Unlock()\n+\t\tif missing {\n+\t\t\treturn fmt.Errorf(\"node %q: container network namespace is not available\", node)\n+\t\t}\n+\n+\t\treturn f(nil)\n+\t}\n+}\n+\n+func (h *fakeHost) open(\n+\tctx context.Context,\n+\texec ExecFunc,\n+\tinterfaces []string,\n+\t_ int,\n+) ([]packetSource, error) {\n+\tvar node string\n+\terr := exec(ctx, func(ns.NetNS) error { return nil })\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\th.mu.Lock()\n+\tdefer h.mu.Unlock()\n+\tsources := make([]packetSource, 0, len(interfaces))\n+\tfor _, name := range interfaces {\n+\t\tif h.missing[name] {\n+\t\t\treturn nil, fmt.Errorf(\"interface %q: no such network interface\", name)\n+\t\t}\n+\t\tnode = name\n+\t\tsource := newFakeSource()\n+\t\th.opened[name] = append(h.opened[name], source)\n+\t\tsources = append(sources, source)\n+\t\th.ready <- node\n+\t}\n+\n+\treturn sources, nil\n+}\n+\n+func (h *fakeHost) source(name string, generation int) *fakeSource {\n+\th.mu.Lock()\n+\tdefer h.mu.Unlock()\n+\n+\treturn h.opened[name][generation]\n+}\n+\n+func (h *fakeHost) setMissing(name string, missing bool) {\n+\th.mu.Lock()\n+\tdefer h.mu.Unlock()\n+\th.missing[name] = missing\n+}\n+\n+func (h *fakeHost) capture() localCapture {\n+\treturn localCapture{\n+\t\topen:           h.open,\n+\t\twindow:         20 * time.Millisecond,\n+\t\treopenInterval: time.Millisecond,\n+\t}\n+}\n+\n+// waitOpened waits until n sources were opened.\n+func (h *fakeHost) waitOpened(t *testing.T, n int) {\n+\tt.Helper()\n+\tfor range n {\n+\t\tselect {\n+\t\tcase <-h.ready:\n+\t\tcase <-time.After(2 * time.Second):\n+\t\t\tt.Fatal(\"source was not opened\")\n+\t\t}\n+\t}\n+}\n+\n+type parsedLocalCapture struct {\n+\tinterfaces []string\n+\tpackets    []Packet\n+}\n+\n+func parseLocalCapture(t *testing.T, data []byte) parsedLocalCapture {\n+\tt.Helper()\n+\n+\tvar parsed parsedLocalCapture\n+\treader := NewReader(bytes.NewReader(data))\n+\tfor {\n+\t\tevent, err := reader.Next()\n+\t\tif errors.Is(err, io.EOF) {\n+\t\t\tbreak\n+\t\t}\n+\t\tif err != nil {\n+\t\t\tt.Fatalf(\"invalid capture: %v\", err)\n+\t\t}\n+\t\tif event.Interface != nil {\n+\t\t\tparsed.interfaces = append(parsed.interfaces, event.Interface.Name)\n+\t\t}\n+\t\tif event.Packet != nil {\n+\t\t\tparsed.packets = append(parsed.packets, *event.Packet)\n+\t\t}\n+\t}\n+\tif reader.Sections() != 1 {\n+\t\tt.Fatalf(\"capture has %d sections\", reader.Sections())\n+\t}\n+\n+\treturn parsed\n+}\n+\n+func localRequest(packetLimit int, duration time.Duration) clablabruntime.CaptureRequest {\n+\treturn clablabruntime.CaptureRequest{\n+\t\tName: \"lab\",\n+\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t{Node: \"r1\", Interface: \"eth1\"}, {Node: \"r2\", Interface: \"eth1\"},\n+\t\t},\n+\t\tPacketLimit: packetLimit,\n+\t\tDuration:    duration,\n+\t\tSnapLength:  64,\n+\t}\n+}\n+\n+func TestCaptureLocalMergesInterfacesInTimestampOrder(t *testing.T) {\n+\tt.Parallel()\n+\n+\thost := newFakeHost()\n+\t// the sources are keyed by interface name in the fake host, so the two nodes use distinct\n+\t// names behind the requested ones\n+\ttargets := []LocalTarget{\n+\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n+\t\t{Node: \"r2\", Interface: \"e2\", Exec: host.exec(\"r2\")},\n+\t}\n+\n+\tvar out bytes.Buffer\n+\tdone := make(chan error, 1)\n+\tgo func() {\n+\t\tdone <- host.capture().run(context.Background(), localRequest(4, 0), targets, &out)\n+\t}()\n+\thost.waitOpened(t, 2)\n+\n+\tbase := time.Unix(1_761_559_200, 0)\n+\t// r2's packets reach containerlab first although r1 stamped one of them earlier\n+\thost.source(\"e2\", 0).frames <- fakeFrame{\n+\t\tdata: []byte(\"r2-a\"), stamp: base.Add(2 * time.Millisecond), length: 4,\n+\t}\n+\thost.source(\"e2\", 0).frames <- fakeFrame{\n+\t\tdata: bytes.Repeat([]byte{7}, 100), stamp: base.Add(4 * time.Millisecond), length: 100,\n+\t}\n+\thost.source(\"e1\", 0).frames <- fakeFrame{\n+\t\tdata: []byte(\"r1-a\"), stamp: base.Add(1 * time.Millisecond), length: 4,\n+\t}\n+\thost.source(\"e1\", 0).frames <- fakeFrame{\n+\t\tdata: []byte(\"r1-v\"), stamp: base.Add(3 * time.Millisecond), length: 60, vlan: true,\n+\t}\n+\n+\tselect {\n+\tcase err := <-done:\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\tcase <-time.After(5 * time.Second):\n+\t\tt.Fatal(\"capture did not stop at the packet limit\")\n+\t}\n+\n+\tparsed := parseLocalCapture(t, out.Bytes())\n+\tif want := []string{\"r1:e1\", \"r2:e2\"}; !slices.Equal(parsed.interfaces, want) {\n+\t\tt.Fatalf(\"interfaces = %v, want %v\", parsed.interfaces, want)\n+\t}\n+\tif len(parsed.packets) != 4 {\n+\t\tt.Fatalf(\"captured %d packets, want 4\", len(parsed.packets))\n+\t}\n+\tvar ids []uint32\n+\tfor idx, packet := range parsed.packets {\n+\t\tids = append(ids, packet.InterfaceID)\n+\t\tif want := base.Add(time.Duration(idx+1) * time.Millisecond).\n+\t\t\tUnixNano(); packet.Timestamp != want {\n+\t\t\tt.Fatalf(\"packet %d stamped %d, want %d\", idx, packet.Timestamp, want)\n+\t\t}\n+\t}\n+\tif !slices.Equal(ids, []uint32{0, 1, 0, 1}) {\n+\t\tt.Fatalf(\"interface IDs = %v\", ids)\n+\t}\n+\t// a re-inserted VLAN tag counts toward the frame length\n+\tif parsed.packets[2].OriginalLength != 64 {\n+\t\tt.Fatalf(\"VLAN frame length = %d, want 64\", parsed.packets[2].OriginalLength)\n+\t}\n+\t// frames are cut to the snap length\n+\tif last := parsed.packets[3]; len(last.Data) != 64 || last.OriginalLength != 100 {\n+\t\tt.Fatalf(\"long frame kept %d of %d bytes\", len(last.Data), last.OriginalLength)\n+\t}\n+\tfor _, name := range []string{\"e1\", \"e2\"} {\n+\t\tselect {\n+\t\tcase <-host.source(name, 0).closed:\n+\t\tdefault:\n+\t\t\tt.Fatalf(\"source %s was not closed\", name)\n+\t\t}\n+\t}\n+}\n+\n+func TestCaptureLocalEndsAfterTheDurationOrWhenCanceled(t *testing.T) {\n+\tt.Parallel()\n+\n+\thost := newFakeHost()\n+\ttargets := []LocalTarget{\n+\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n+\t\t{Node: \"r1\", Interface: \"e2\", Exec: host.exec(\"r1\")},\n+\t}\n+\n+\tvar out bytes.Buffer\n+\tstart := time.Now()\n+\tif err := host.capture().run(context.Background(), localRequest(0, 50*time.Millisecond),\n+\t\ttargets, &out); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif elapsed := time.Since(start); elapsed < 50*time.Millisecond || elapsed > 2*time.Second {\n+\t\tt.Fatalf(\"capture ran %s for a 50ms duration\", elapsed)\n+\t}\n+\tif parsed := parseLocalCapture(t, out.Bytes()); len(parsed.interfaces) != 2 {\n+\t\tt.Fatalf(\"interfaces = %v\", parsed.interfaces)\n+\t}\n+\n+\tctx, cancel := context.WithCancel(context.Background())\n+\tdone := make(chan error, 1)\n+\tgo func() {\n+\t\tdone <- host.capture().run(ctx, localRequest(0, 0), targets, io.Discard)\n+\t}()\n+\thost.waitOpened(t, 4)\n+\tcancel()\n+\tselect {\n+\tcase err := <-done:\n+\t\tif err != nil {\n+\t\t\tt.Fatalf(\"canceled capture returned %v\", err)\n+\t\t}\n+\tcase <-time.After(2 * time.Second):\n+\t\tt.Fatal(\"canceled capture did not end\")\n+\t}\n+}\n+\n+func TestCaptureLocalWritesPacketsStillInTheRingWhenItEnds(t *testing.T) {\n+\tt.Parallel()\n+\n+\thost := newFakeHost()\n+\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n+\treq := localRequest(0, 0)\n+\treq.Targets = req.Targets[:1]\n+\n+\tctx, cancel := context.WithCancel(context.Background())\n+\tvar out bytes.Buffer\n+\tdone := make(chan error, 1)\n+\tgo func() {\n+\t\tdone <- host.capture().run(ctx, req, targets, &out)\n+\t}()\n+\thost.waitOpened(t, 1)\n+\n+\tnow := time.Now()\n+\t// stamped before the end, handed over by the kernel only after it\n+\thost.source(\"e1\", 0).frames <- fakeFrame{\n+\t\tdata: []byte(\"before\"), stamp: now, length: 6, visible: now.Add(30 * time.Millisecond),\n+\t}\n+\t// stamped after the end: not part of the capture\n+\thost.source(\"e1\", 0).frames <- fakeFrame{\n+\t\tdata: []byte(\"after\"), stamp: now.Add(time.Hour), length: 5,\n+\t\tvisible: now.Add(40 * time.Millisecond),\n+\t}\n+\tcancel()\n+\n+\tif err := <-done; err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tparsed := parseLocalCapture(t, out.Bytes())\n+\tif len(parsed.packets) != 1 || string(parsed.packets[0].Data) != \"before\" {\n+\t\tt.Fatalf(\"packets = %+v, want only the one stamped before the end\", parsed.packets)\n+\t}\n+}\n+\n+func TestCaptureLocalFailsWithoutOutputWhenAnInterfaceCannotBeOpened(t *testing.T) {\n+\tt.Parallel()\n+\n+\thost := newFakeHost()\n+\thost.setMissing(\"r2\", true)\n+\ttargets := []LocalTarget{\n+\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n+\t\t{Node: \"r2\", Interface: \"e2\", Exec: host.exec(\"r2\")},\n+\t}\n+\n+\tvar out bytes.Buffer\n+\terr := host.capture().run(context.Background(), localRequest(0, 0), targets, &out)\n+\tif err == nil || !strings.Contains(err.Error(), `failed to start the capture on node \"r2\"`) {\n+\t\tt.Fatalf(\"error = %v\", err)\n+\t}\n+\tif out.Len() != 0 {\n+\t\tt.Fatalf(\"wrote %d bytes before failing\", out.Len())\n+\t}\n+\tselect {\n+\tcase <-host.source(\"e1\", 0).closed:\n+\tdefault:\n+\t\tt.Fatal(\"the source opened before the failure was not closed\")\n+\t}\n+}\n+\n+func TestCaptureLocalReopensInterfacesAndReportsWhileTheyWereGone(t *testing.T) {\n+\tt.Parallel()\n+\n+\thost := newFakeHost()\n+\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n+\treq := localRequest(2, 0)\n+\treq.Targets = req.Targets[:1]\n+\n+\tvar mu sync.Mutex\n+\tvar gaps []clablabruntime.CaptureGap\n+\treq.OnGap = func(gap clablabruntime.CaptureGap) {\n+\t\tmu.Lock()\n+\t\tdefer mu.Unlock()\n+\t\tgaps = append(gaps, gap)\n+\t}\n+\n+\tvar out bytes.Buffer\n+\tdone := make(chan error, 1)\n+\tgo func() {\n+\t\tdone <- host.capture().run(context.Background(), req, targets, &out)\n+\t}()\n+\thost.waitOpened(t, 1)\n+\n+\tbase := time.Unix(1_761_559_200, 0)\n+\thost.source(\"e1\", 0).frames <- fakeFrame{data: []byte(\"a\"), stamp: base, length: 1}\n+\n+\t// the interface goes down: the socket fails and is reopened at once, without a gap\n+\thost.source(\"e1\", 0).frames <- fakeFrame{err: afpacket.ErrPoll}\n+\thost.waitOpened(t, 1)\n+\n+\t// the node restarts: the interface is gone for a while, then back\n+\thost.setMissing(\"r1\", true)\n+\thost.source(\"e1\", 1).frames <- fakeFrame{err: afpacket.ErrPoll}\n+\ttime.Sleep(20 * time.Millisecond)\n+\thost.setMissing(\"r1\", false)\n+\thost.waitOpened(t, 1)\n+\thost.source(\"e1\", 2).frames <- fakeFrame{\n+\t\tdata: []byte(\"b\"), stamp: base.Add(time.Second), length: 1,\n+\t}\n+\n+\tselect {\n+\tcase err := <-done:\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\tcase <-time.After(5 * time.Second):\n+\t\tt.Fatal(\"capture did not stop at the packet limit\")\n+\t}\n+\n+\tif parsed := parseLocalCapture(t, out.Bytes()); len(parsed.packets) != 2 {\n+\t\tt.Fatalf(\"captured %d packets across the reopen, want 2\", len(parsed.packets))\n+\t}\n+\tmu.Lock()\n+\tdefer mu.Unlock()\n+\tif len(gaps) != 1 {\n+\t\tt.Fatalf(\"gaps = %+v, want one for the restart\", gaps)\n+\t}\n+\tgap := gaps[0]\n+\tif gap.Node != \"r1\" || !slices.Equal(gap.Interfaces, []string{\"e1\"}) || gap.To.IsZero() ||\n+\t\t!gap.To.After(gap.From) || !strings.Contains(gap.Reason, \"not available\") {\n+\t\tt.Fatalf(\"gap = %+v\", gap)\n+\t}\n+}\n+\n+func TestCaptureLocalChecksTheRequest(t *testing.T) {\n+\tt.Parallel()\n+\n+\thost := newFakeHost()\n+\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n+\n+\treq := localRequest(0, 0)\n+\treq.SnapLength = 10\n+\tif err := host.capture().run(context.Background(), req, targets[:1], io.Discard); err == nil ||\n+\t\t!strings.Contains(err.Error(), \"snap length 10\") {\n+\t\tt.Fatalf(\"small snap length: error = %v\", err)\n+\t}\n+\n+\tif err := host.capture().run(context.Background(), localRequest(0, 0), targets,\n+\t\tio.Discard); err == nil || !strings.Contains(err.Error(), \"1 resolved targets for 2\") {\n+\t\tt.Fatalf(\"target mismatch: error = %v\", err)\n+\t}\n+}\ndiff --git a/capture/output.go b/capture/output.go\nnew file mode 100644\nindex 0000000..574c33a\n--- /dev/null\n+++ b/capture/output.go\n@@ -0,0 +1,203 @@\n+package capture\n+\n+import (\n+\t\"context\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"strings\"\n+\t\"sync/atomic\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+)\n+\n+// Snap length bounds of a capture.\n+const (\n+\t// DefaultSnapLength is the snap length of a request without one.\n+\tDefaultSnapLength = 256 << 10\n+\tMinSnapLength     = 64\n+\tMaxSnapLength     = 1 << 20\n+)\n+\n+// ValidateRequest checks the bounds of a capture request and fills the default snap length.\n+func ValidateRequest(req *clablabruntime.CaptureRequest) error {\n+\tif req.Name == \"\" {\n+\t\treturn fmt.Errorf(\"topology name is required\")\n+\t}\n+\tif len(req.Targets) == 0 {\n+\t\treturn fmt.Errorf(\"at least one capture target (node and interface) is required\")\n+\t}\n+\tfor _, target := range req.Targets {\n+\t\tif target.Node == \"\" || target.Interface == \"\" {\n+\t\t\treturn fmt.Errorf(\"capture target %+v needs a node and an interface\", target)\n+\t\t}\n+\t}\n+\tif req.Duration < 0 {\n+\t\treturn fmt.Errorf(\"capture duration must not be negative\")\n+\t}\n+\tif req.PacketLimit < 0 {\n+\t\treturn fmt.Errorf(\"capture packet limit must not be negative\")\n+\t}\n+\tif req.SnapLength == 0 {\n+\t\treq.SnapLength = DefaultSnapLength\n+\t}\n+\tif req.SnapLength < MinSnapLength || req.SnapLength > MaxSnapLength {\n+\t\treturn fmt.Errorf(\"capture snap length %d is outside %d to %d bytes\", req.SnapLength,\n+\t\t\tMinSnapLength, MaxSnapLength)\n+\t}\n+\n+\treturn nil\n+}\n+\n+// FindInterface matches a requested interface by its name, then by its alias.\n+func FindInterface(\n+\tentries []clablabruntime.CaptureInterface,\n+\tname string,\n+) (clablabruntime.CaptureInterface, bool) {\n+\tfor _, entry := range entries {\n+\t\tif entry.Interface == name {\n+\t\t\treturn entry, true\n+\t\t}\n+\t}\n+\tfor _, entry := range entries {\n+\t\tif entry.Alias != \"\" && entry.Alias == name {\n+\t\t\treturn entry, true\n+\t\t}\n+\t}\n+\n+\treturn clablabruntime.CaptureInterface{}, false\n+}\n+\n+// DescribeInterfaces lists interfaces for an error message: name (alias), ...\n+func DescribeInterfaces(entries []clablabruntime.CaptureInterface) string {\n+\tif len(entries) == 0 {\n+\t\treturn \"none\"\n+\t}\n+\n+\tnames := make([]string, 0, len(entries))\n+\tfor _, entry := range entries {\n+\t\tname := entry.Interface\n+\t\tif entry.Alias != \"\" {\n+\t\t\tname += \" (\" + entry.Alias + \")\"\n+\t\t}\n+\t\tnames = append(names, name)\n+\t}\n+\n+\treturn strings.Join(names, \", \")\n+}\n+\n+// ReportGap hands a gap to onGap, or logs it as a warning when onGap is nil.\n+func ReportGap(onGap func(clablabruntime.CaptureGap), gap clablabruntime.CaptureGap) {\n+\tif onGap != nil {\n+\t\tonGap(gap)\n+\t\treturn\n+\t}\n+\n+\tto := \"unknown\"\n+\tif !gap.To.IsZero() {\n+\t\tto = gap.To.Format(time.RFC3339Nano)\n+\t}\n+\tlog.Warn(\"Capture has a gap\", \"node\", gap.Node, \"interfaces\", strings.Join(gap.Interfaces, \",\"),\n+\t\t\"from\", gap.From.Format(time.RFC3339Nano), \"to\", to, \"reason\", gap.Reason)\n+}\n+\n+// Output is the merged pcapng stream of one capture: the section header with one interface per\n+// capture target, then the packets of every target in timestamp order (through a Reorder), up\n+// to an optional packet limit.\n+type Output struct {\n+\twriter  *Writer\n+\treorder *Reorder\n+\tlimit   int64\n+\twritten atomic.Int64\n+\tstop    func()\n+\n+\tcancelRun context.CancelFunc\n+\trunDone   chan struct{}\n+}\n+\n+// NewOutput writes the section header and one Interface Description Block per name to w, then\n+// starts the reorder buffer with the given window (zero or less writes packets as they come).\n+// stop is called once the packet limit is reached or a write failed. Close must be called.\n+func NewOutput(\n+\tw io.Writer,\n+\tnames []string,\n+\tsnapLength, packetLimit int,\n+\twindow time.Duration,\n+\tstop func(),\n+) (*Output, error) {\n+\twriter := NewWriter(w)\n+\tif err := writer.WriteHeader(\n+\t\tnames,\n+\t\tuint32(snapLength),\n+\t); err != nil { //nolint:gosec // validated\n+\t\treturn nil, err\n+\t}\n+\n+\tout := &Output{\n+\t\twriter:  writer,\n+\t\treorder: NewReorder(window, writer.WritePacket, stop),\n+\t\tlimit:   int64(packetLimit),\n+\t\tstop:    stop,\n+\t\trunDone: make(chan struct{}),\n+\t}\n+\n+\tvar runCtx context.Context\n+\trunCtx, out.cancelRun = context.WithCancel(context.Background())\n+\tgo func() {\n+\t\tdefer close(out.runDone)\n+\t\tout.reorder.Run(runCtx)\n+\t}()\n+\n+\treturn out, nil\n+}\n+\n+// Emit hands a packet of the interface with the given index to the stream. It reports false\n+// once the packet limit is reached and the capture stops, and returns the error of a failed\n+// write.\n+func (o *Output) Emit(id uint32, packet *Packet) (bool, error) {\n+\tif o.limit > 0 {\n+\t\tcount := o.written.Add(1)\n+\t\tif count > o.limit {\n+\t\t\to.stop()\n+\t\t\treturn false, nil\n+\t\t}\n+\t\tif err := o.reorder.Push(id, packet); err != nil {\n+\t\t\treturn false, err\n+\t\t}\n+\t\tif count == o.limit {\n+\t\t\to.stop()\n+\t\t\treturn false, nil\n+\t\t}\n+\n+\t\treturn true, nil\n+\t}\n+\n+\to.written.Add(1)\n+\n+\treturn true, o.reorder.Push(id, packet)\n+}\n+\n+// Written returns the number of packets handed to the stream so far.\n+func (o *Output) Written() int64 {\n+\treturn o.written.Load()\n+}\n+\n+// Hold keeps packets stamped after timestamp back until Release(key).\n+func (o *Output) Hold(key any, timestamp int64) {\n+\to.reorder.Hold(key, timestamp)\n+}\n+\n+// Release removes the hold of key.\n+func (o *Output) Release(key any) {\n+\to.reorder.Release(key)\n+}\n+\n+// Close writes the packets still held back and returns the first write error.\n+func (o *Output) Close() error {\n+\to.cancelRun()\n+\t<-o.runDone\n+\to.reorder.Flush()\n+\n+\treturn o.writer.Err()\n+}\ndiff --git a/capture/pcapng.go b/capture/pcapng.go\nnew file mode 100644\nindex 0000000..246ac84\n--- /dev/null\n+++ b/capture/pcapng.go\n@@ -0,0 +1,333 @@\n+// Package capture writes the pcapng streams of `containerlab capture`: one section with one\n+// interface per capture target, packets merged across targets in timestamp order. The local\n+// capturer reads lab link interfaces of Docker and Podman nodes through packet sockets; the c9s\n+// lab runtime feeds the same writer from clabwire streams.\n+package capture\n+\n+import (\n+\t\"bufio\"\n+\t\"encoding/binary\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"math\"\n+\t\"sync\"\n+)\n+\n+// pcapng block layout (https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html). clabwire\n+// writes little-endian sections, and so does the merged stream containerlab writes.\n+const (\n+\tpcapngSectionHeaderType  = 0x0a0d0d0a\n+\tpcapngInterfaceType      = 0x00000001\n+\tpcapngEnhancedPacketType = 0x00000006\n+\tpcapngByteOrderMagic     = 0x1a2b3c4d\n+\tpcapngOptionEnd          = 0\n+\tpcapngOptionUserAppl     = 4\n+\tpcapngOptionIfName       = 2\n+\tpcapngOptionIfTSResol    = 9\n+\tpcapngLinkTypeEthernet   = 1\n+\t// pcapngNanoseconds is the if_tsresol value for 10^-9 s resolution.\n+\tpcapngNanoseconds = 9\n+\t// pcapngMaxBlockLength bounds a block read from a capture stream: a packet of the largest\n+\t// clabwire snap length (1 MiB) plus framing.\n+\tpcapngMaxBlockLength = 1<<20 + 1024\n+\t// captureUserApplication names the writer in the merged section header.\n+\tcaptureUserApplication = \"containerlab\"\n+)\n+\n+var errPCAPNGByteOrder = errors.New(\"pcapng section is not little-endian\")\n+\n+// InterfaceDescription is an Interface Description Block.\n+type InterfaceDescription struct {\n+\tLinkType   uint16\n+\tSnapLength uint32\n+\tName       string\n+\t// TSResol is the raw if_tsresol value; 6 (microseconds) when the block has none.\n+\tTSResol byte\n+}\n+\n+// Packet is an Enhanced Packet Block with its timestamp in nanoseconds.\n+type Packet struct {\n+\tInterfaceID    uint32\n+\tTimestamp      int64\n+\tOriginalLength uint32\n+\tData           []byte\n+}\n+\n+// Reader reads the blocks of a pcapng stream as clabwire writes it: one or more\n+// little-endian sections, each with its Interface Description Blocks before its packets.\n+type Reader struct {\n+\tr          *bufio.Reader\n+\tinterfaces []InterfaceDescription\n+\t// sections counts the Section Header Blocks read so far.\n+\tsections int\n+}\n+\n+// NewReader returns a reader of the pcapng stream r.\n+func NewReader(r io.Reader) *Reader {\n+\treturn &Reader{r: bufio.NewReaderSize(r, 64<<10)}\n+}\n+\n+// Sections returns the number of Section Header Blocks read so far.\n+func (p *Reader) Sections() int {\n+\treturn p.sections\n+}\n+\n+// Event is one block of interest: a new interface or a packet.\n+type Event struct {\n+\tInterface *InterfaceDescription\n+\tPacket    *Packet\n+}\n+\n+// Next returns the next interface or packet, skipping other block types. It returns io.EOF at\n+// the clean end of the stream, and io.ErrUnexpectedEOF for a stream cut inside a block.\n+func (p *Reader) Next() (Event, error) {\n+\tfor {\n+\t\tvar header [8]byte\n+\t\tif _, err := io.ReadFull(p.r, header[:]); err != nil {\n+\t\t\tif errors.Is(err, io.EOF) {\n+\t\t\t\treturn Event{}, io.EOF\n+\t\t\t}\n+\n+\t\t\treturn Event{}, io.ErrUnexpectedEOF\n+\t\t}\n+\n+\t\tblockType := binary.LittleEndian.Uint32(header[0:4])\n+\t\tlength := binary.LittleEndian.Uint32(header[4:8])\n+\t\tif blockType == pcapngSectionHeaderType {\n+\t\t\t// the byte-order magic tells a big-endian section apart before its length is\n+\t\t\t// trusted: that length reads byte swapped\n+\t\t\tmagic, err := p.r.Peek(4)\n+\t\t\tif err != nil {\n+\t\t\t\treturn Event{}, io.ErrUnexpectedEOF\n+\t\t\t}\n+\t\t\tif binary.BigEndian.Uint32(magic) == pcapngByteOrderMagic {\n+\t\t\t\treturn Event{}, errPCAPNGByteOrder\n+\t\t\t}\n+\t\t}\n+\t\tif length < 12 || length%4 != 0 || length > pcapngMaxBlockLength {\n+\t\t\treturn Event{}, fmt.Errorf(\"invalid pcapng block length %d (at most %d)\", length,\n+\t\t\t\tpcapngMaxBlockLength)\n+\t\t}\n+\n+\t\tbody := make([]byte, length-8)\n+\t\tif _, err := io.ReadFull(p.r, body); err != nil {\n+\t\t\treturn Event{}, io.ErrUnexpectedEOF\n+\t\t}\n+\t\tif binary.LittleEndian.Uint32(body[len(body)-4:]) != length {\n+\t\t\treturn Event{}, fmt.Errorf(\"pcapng block lengths do not match\")\n+\t\t}\n+\t\tbody = body[:len(body)-4]\n+\n+\t\tswitch blockType {\n+\t\tcase pcapngSectionHeaderType:\n+\t\t\tif len(body) < 16 {\n+\t\t\t\treturn Event{}, fmt.Errorf(\"short pcapng section header\")\n+\t\t\t}\n+\t\t\tif binary.LittleEndian.Uint32(body[0:4]) != pcapngByteOrderMagic {\n+\t\t\t\treturn Event{}, errPCAPNGByteOrder\n+\t\t\t}\n+\t\t\tp.sections++\n+\t\t\tp.interfaces = nil\n+\t\tcase pcapngInterfaceType:\n+\t\t\tif p.sections == 0 {\n+\t\t\t\treturn Event{}, fmt.Errorf(\"pcapng interface before a section header\")\n+\t\t\t}\n+\t\t\tintf, err := parsePCAPNGInterface(body)\n+\t\t\tif err != nil {\n+\t\t\t\treturn Event{}, err\n+\t\t\t}\n+\t\t\tp.interfaces = append(p.interfaces, intf)\n+\n+\t\t\treturn Event{Interface: &p.interfaces[len(p.interfaces)-1]}, nil\n+\t\tcase pcapngEnhancedPacketType:\n+\t\t\tpacket, err := p.parsePacket(body)\n+\t\t\tif err != nil {\n+\t\t\t\treturn Event{}, err\n+\t\t\t}\n+\n+\t\t\treturn Event{Packet: &packet}, nil\n+\t\t}\n+\t}\n+}\n+\n+func parsePCAPNGInterface(body []byte) (InterfaceDescription, error) {\n+\tif len(body) < 8 {\n+\t\treturn InterfaceDescription{}, fmt.Errorf(\"short pcapng interface description\")\n+\t}\n+\tintf := InterfaceDescription{\n+\t\tLinkType:   binary.LittleEndian.Uint16(body[0:2]),\n+\t\tSnapLength: binary.LittleEndian.Uint32(body[4:8]),\n+\t\tTSResol:    6,\n+\t}\n+\n+\toptions := body[8:]\n+\tfor len(options) >= 4 {\n+\t\tcode := binary.LittleEndian.Uint16(options[0:2])\n+\t\tsize := int(binary.LittleEndian.Uint16(options[2:4]))\n+\t\tif code == pcapngOptionEnd {\n+\t\t\tbreak\n+\t\t}\n+\t\tpadded := size + pcapngPadding(size)\n+\t\tif 4+padded > len(options) {\n+\t\t\treturn InterfaceDescription{}, fmt.Errorf(\"truncated pcapng interface option\")\n+\t\t}\n+\t\tvalue := options[4 : 4+size]\n+\t\tswitch code {\n+\t\tcase pcapngOptionIfName:\n+\t\t\tintf.Name = string(value)\n+\t\tcase pcapngOptionIfTSResol:\n+\t\t\tif size == 1 {\n+\t\t\t\tintf.TSResol = value[0]\n+\t\t\t}\n+\t\t}\n+\t\toptions = options[4+padded:]\n+\t}\n+\n+\treturn intf, nil\n+}\n+\n+func (p *Reader) parsePacket(body []byte) (Packet, error) {\n+\tif len(body) < 20 {\n+\t\treturn Packet{}, fmt.Errorf(\"short pcapng enhanced packet\")\n+\t}\n+\tpacket := Packet{\n+\t\tInterfaceID:    binary.LittleEndian.Uint32(body[0:4]),\n+\t\tOriginalLength: binary.LittleEndian.Uint32(body[16:20]),\n+\t}\n+\tif int(packet.InterfaceID) >= len(p.interfaces) {\n+\t\treturn Packet{}, fmt.Errorf(\"pcapng packet for undeclared interface %d\",\n+\t\t\tpacket.InterfaceID)\n+\t}\n+\tcaptured := binary.LittleEndian.Uint32(body[12:16])\n+\tif int(captured) > len(body)-20 {\n+\t\treturn Packet{}, fmt.Errorf(\"pcapng packet data exceeds its block\")\n+\t}\n+\tpacket.Data = body[20 : 20+captured]\n+\n+\traw := uint64(binary.LittleEndian.Uint32(body[4:8]))<<32 |\n+\t\tuint64(binary.LittleEndian.Uint32(body[8:12]))\n+\ttimestamp, err := pcapngNanosecondsFrom(raw, p.interfaces[packet.InterfaceID].TSResol)\n+\tif err != nil {\n+\t\treturn Packet{}, err\n+\t}\n+\tpacket.Timestamp = timestamp\n+\n+\treturn packet, nil\n+}\n+\n+// pcapngNanosecondsFrom converts a timestamp in an interface's resolution to nanoseconds.\n+// Only decimal resolutions up to nanoseconds occur in clabwire streams.\n+func pcapngNanosecondsFrom(raw uint64, tsresol byte) (int64, error) {\n+\tif tsresol&0x80 != 0 || tsresol > pcapngNanoseconds {\n+\t\treturn 0, fmt.Errorf(\"unsupported pcapng timestamp resolution %#x\", tsresol)\n+\t}\n+\tscale := uint64(1)\n+\tfor range pcapngNanoseconds - int(tsresol) {\n+\t\tscale *= 10\n+\t}\n+\tif raw > math.MaxInt64/scale {\n+\t\treturn 0, fmt.Errorf(\"pcapng timestamp out of range\")\n+\t}\n+\n+\treturn int64(raw * scale), nil //nolint:gosec // bounded above\n+}\n+\n+// Writer writes one little-endian section with nanosecond timestamps. Every block goes out\n+// in one Write under a lock, so concurrent writers never interleave blocks and a stream cut\n+// between writes is still a valid capture.\n+type Writer struct {\n+\tmu  sync.Mutex\n+\tw   io.Writer\n+\terr error\n+}\n+\n+// NewWriter returns a writer of one pcapng section to w.\n+func NewWriter(w io.Writer) *Writer {\n+\treturn &Writer{w: w}\n+}\n+\n+// WriteHeader writes the Section Header Block and one Interface Description Block per name, in\n+// order; packets refer to the interfaces by that index.\n+func (p *Writer) WriteHeader(names []string, snapLength uint32) error {\n+\tsection := make([]byte, 16)\n+\tbinary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)\n+\tbinary.LittleEndian.PutUint16(section[4:], 1)\n+\tbinary.LittleEndian.PutUint16(section[6:], 0)\n+\tbinary.LittleEndian.PutUint64(section[8:], math.MaxUint64)\n+\tsection = appendPCAPNGOption(section, pcapngOptionUserAppl, []byte(captureUserApplication))\n+\tsection = appendPCAPNGOption(section, pcapngOptionEnd, nil)\n+\n+\theader := pcapngBlock(pcapngSectionHeaderType, section)\n+\tfor _, name := range names {\n+\t\tdescription := make([]byte, 8)\n+\t\tbinary.LittleEndian.PutUint16(description[0:], pcapngLinkTypeEthernet)\n+\t\tbinary.LittleEndian.PutUint32(description[4:], snapLength)\n+\t\tdescription = appendPCAPNGOption(description, pcapngOptionIfName, []byte(name))\n+\t\tdescription = appendPCAPNGOption(description, pcapngOptionIfTSResol,\n+\t\t\t[]byte{pcapngNanoseconds})\n+\t\tdescription = appendPCAPNGOption(description, pcapngOptionEnd, nil)\n+\t\theader = append(header, pcapngBlock(pcapngInterfaceType, description)...)\n+\t}\n+\n+\treturn p.write(header)\n+}\n+\n+// WritePacket writes an Enhanced Packet Block for the interface with the given index.\n+func (p *Writer) WritePacket(interfaceID uint32, packet *Packet) error {\n+\ttimestamp := uint64(packet.Timestamp) //nolint:gosec // capture timestamps are positive\n+\tbody := make([]byte, 20, 20+len(packet.Data)+3)\n+\tbinary.LittleEndian.PutUint32(body[0:], interfaceID)\n+\tbinary.LittleEndian.PutUint32(body[4:], uint32(timestamp>>32))\n+\tbinary.LittleEndian.PutUint32(body[8:], uint32(timestamp)) //nolint:gosec // low 32 bits\n+\tbinary.LittleEndian.PutUint32(body[12:], uint32(len(packet.Data)))\n+\tbinary.LittleEndian.PutUint32(body[16:], packet.OriginalLength)\n+\tbody = append(body, packet.Data...)\n+\tbody = append(body, make([]byte, pcapngPadding(len(packet.Data)))...)\n+\n+\treturn p.write(pcapngBlock(pcapngEnhancedPacketType, body))\n+}\n+\n+// Err returns the first write error, or nil.\n+func (p *Writer) Err() error {\n+\tp.mu.Lock()\n+\tdefer p.mu.Unlock()\n+\n+\treturn p.err\n+}\n+\n+func (p *Writer) write(block []byte) error {\n+\tp.mu.Lock()\n+\tdefer p.mu.Unlock()\n+\n+\tif p.err != nil {\n+\t\treturn p.err\n+\t}\n+\tif _, err := p.w.Write(block); err != nil {\n+\t\tp.err = fmt.Errorf(\"failed to write the capture: %w\", err)\n+\t}\n+\n+\treturn p.err\n+}\n+\n+func pcapngBlock(blockType uint32, body []byte) []byte {\n+\ttotal := uint32(12 + len(body)) //nolint:gosec // bounded by the snap length\n+\tblock := make([]byte, 8, total)\n+\tbinary.LittleEndian.PutUint32(block[0:], blockType)\n+\tbinary.LittleEndian.PutUint32(block[4:], total)\n+\tblock = append(block, body...)\n+\n+\treturn binary.LittleEndian.AppendUint32(block, total)\n+}\n+\n+func appendPCAPNGOption(body []byte, code uint16, value []byte) []byte {\n+\tbody = binary.LittleEndian.AppendUint16(body, code)\n+\tbody = binary.LittleEndian.AppendUint16(body, uint16(len(value))) //nolint:gosec // short\n+\tbody = append(body, value...)\n+\n+\treturn append(body, make([]byte, pcapngPadding(len(value)))...)\n+}\n+\n+func pcapngPadding(length int) int {\n+\treturn (4 - length%4) % 4\n+}\ndiff --git a/capture/pcapng_test.go b/capture/pcapng_test.go\nnew file mode 100644\nindex 0000000..0917d16\n--- /dev/null\n+++ b/capture/pcapng_test.go\n@@ -0,0 +1,167 @@\n+package capture\n+\n+import (\n+\t\"bytes\"\n+\t\"encoding/binary\"\n+\t\"errors\"\n+\t\"io\"\n+\t\"strings\"\n+\t\"testing\"\n+)\n+\n+func TestPCAPNGWriterAndReaderRoundTrip(t *testing.T) {\n+\tt.Parallel()\n+\n+\tvar out bytes.Buffer\n+\twriter := NewWriter(&out)\n+\tif err := writer.WriteHeader([]string{\"r1:e1-1\", \"r2:eth1\"}, 1500); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tpackets := []Packet{\n+\t\t{\n+\t\t\tInterfaceID:    1,\n+\t\t\tTimestamp:      1_761_559_200_123_456_789,\n+\t\t\tOriginalLength: 98,\n+\t\t\tData:           []byte(\"abcde\"),\n+\t\t},\n+\t\t{\n+\t\t\tInterfaceID:    0,\n+\t\t\tTimestamp:      1_761_559_200_123_456_790,\n+\t\t\tOriginalLength: 4,\n+\t\t\tData:           []byte(\"wxyz\"),\n+\t\t},\n+\t}\n+\tfor idx := range packets {\n+\t\tif err := writer.WritePacket(packets[idx].InterfaceID, &packets[idx]); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t}\n+\n+\tdata := out.Bytes()\n+\t// the section header names the writer\n+\tif !bytes.Contains(data[:64], []byte(captureUserApplication)) {\n+\t\tt.Fatal(\"section header has no shb_userappl\")\n+\t}\n+\tif len(data)%4 != 0 {\n+\t\tt.Fatalf(\"stream length %d is not 32-bit aligned\", len(data))\n+\t}\n+\n+\treader := NewReader(bytes.NewReader(data))\n+\tvar names []string\n+\tvar read []Packet\n+\tfor {\n+\t\tevent, err := reader.Next()\n+\t\tif errors.Is(err, io.EOF) {\n+\t\t\tbreak\n+\t\t}\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\tif event.Interface != nil {\n+\t\t\tnames = append(names, event.Interface.Name)\n+\t\t\tif event.Interface.SnapLength != 1500 || event.Interface.LinkType != 1 {\n+\t\t\t\tt.Fatalf(\"interface = %+v\", event.Interface)\n+\t\t\t}\n+\t\t}\n+\t\tif event.Packet != nil {\n+\t\t\tread = append(read, *event.Packet)\n+\t\t}\n+\t}\n+\tif len(names) != 2 || names[0] != \"r1:e1-1\" || names[1] != \"r2:eth1\" {\n+\t\tt.Fatalf(\"names = %v\", names)\n+\t}\n+\tfor idx := range packets {\n+\t\tif read[idx].InterfaceID != packets[idx].InterfaceID ||\n+\t\t\tread[idx].Timestamp != packets[idx].Timestamp ||\n+\t\t\tread[idx].OriginalLength != packets[idx].OriginalLength ||\n+\t\t\t!bytes.Equal(read[idx].Data, packets[idx].Data) {\n+\t\t\tt.Fatalf(\"packet %d = %+v, want %+v\", idx, read[idx], packets[idx])\n+\t\t}\n+\t}\n+}\n+\n+func TestPCAPNGReaderHandlesRepeatedSectionsAndResolutions(t *testing.T) {\n+\tt.Parallel()\n+\n+\tvar out bytes.Buffer\n+\tfirst := NewWriter(&out)\n+\t_ = first.WriteHeader([]string{\"eth1\"}, 64)\n+\t_ = first.WritePacket(0, &Packet{Timestamp: 5, Data: []byte{1}})\n+\n+\t// a second section whose interface has microsecond timestamps (no if_tsresol)\n+\tsection := make([]byte, 16)\n+\tbinary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)\n+\tbinary.LittleEndian.PutUint16(section[4:], 1)\n+\tout.Write(pcapngBlock(pcapngSectionHeaderType, section))\n+\tdescription := make([]byte, 8)\n+\tbinary.LittleEndian.PutUint16(description[0:], 1)\n+\tdescription = appendPCAPNGOption(description, pcapngOptionIfName, []byte(\"eth2\"))\n+\tout.Write(pcapngBlock(pcapngInterfaceType, description))\n+\tbody := make([]byte, 20)\n+\tbinary.LittleEndian.PutUint32(body[8:], 7) // 7 microseconds\n+\tout.Write(pcapngBlock(pcapngEnhancedPacketType, body))\n+\n+\treader := NewReader(&out)\n+\tvar timestamps []int64\n+\tfor {\n+\t\tevent, err := reader.Next()\n+\t\tif errors.Is(err, io.EOF) {\n+\t\t\tbreak\n+\t\t}\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\tif event.Packet != nil {\n+\t\t\ttimestamps = append(timestamps, event.Packet.Timestamp)\n+\t\t}\n+\t}\n+\tif reader.sections != 2 || len(timestamps) != 2 || timestamps[0] != 5 || timestamps[1] != 7000 {\n+\t\tt.Fatalf(\"sections %d, timestamps %v\", reader.sections, timestamps)\n+\t}\n+}\n+\n+func TestPCAPNGReaderRejectsInvalidStreams(t *testing.T) {\n+\tt.Parallel()\n+\n+\tvar valid bytes.Buffer\n+\twriter := NewWriter(&valid)\n+\t_ = writer.WriteHeader([]string{\"eth1\"}, 64)\n+\t_ = writer.WritePacket(0, &Packet{Timestamp: 1, Data: []byte(\"data\")})\n+\n+\treadAll := func(data []byte) error {\n+\t\treader := NewReader(bytes.NewReader(data))\n+\t\tfor {\n+\t\t\t_, err := reader.Next()\n+\t\t\tif errors.Is(err, io.EOF) {\n+\t\t\t\treturn nil\n+\t\t\t}\n+\t\t\tif err != nil {\n+\t\t\t\treturn err\n+\t\t\t}\n+\t\t}\n+\t}\n+\n+\tif err := readAll(valid.Bytes()[:valid.Len()-6]); !errors.Is(err, io.ErrUnexpectedEOF) {\n+\t\tt.Fatalf(\"truncated stream: %v\", err)\n+\t}\n+\n+\tbigEndian := append([]byte(nil), valid.Bytes()...)\n+\tbinary.BigEndian.PutUint32(bigEndian[4:], binary.LittleEndian.Uint32(bigEndian[4:]))\n+\tbinary.BigEndian.PutUint32(bigEndian[8:], pcapngByteOrderMagic)\n+\tif err := readAll(bigEndian); !errors.Is(err, errPCAPNGByteOrder) {\n+\t\tt.Fatalf(\"big-endian section: %v\", err)\n+\t}\n+\n+\t// a little-endian section header longer than the reader accepts is not a byte-order error\n+\toversized := append([]byte(nil), valid.Bytes()...)\n+\tbinary.LittleEndian.PutUint32(oversized[4:], 2<<20)\n+\tif err := readAll(oversized); err == nil || errors.Is(err, errPCAPNGByteOrder) ||\n+\t\t!strings.Contains(err.Error(), \"invalid pcapng block length\") {\n+\t\tt.Fatalf(\"oversized little-endian section: %v\", err)\n+\t}\n+\n+\tpacketFirst := pcapngBlock(pcapngEnhancedPacketType, make([]byte, 20))\n+\tif err := readAll(packetFirst); err == nil {\n+\t\tt.Fatal(\"packet before any interface accepted\")\n+\t}\n+}\ndiff --git a/capture/reorder.go b/capture/reorder.go\nnew file mode 100644\nindex 0000000..277ba1a\n--- /dev/null\n+++ b/capture/reorder.go\n@@ -0,0 +1,271 @@\n+package capture\n+\n+import (\n+\t\"container/heap\"\n+\t\"context\"\n+\t\"sync\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+)\n+\n+// maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets\n+// are written early, which can put them out of order.\n+const maxReorderBytes = 64 << 20\n+\n+// Reorder writes the packets of several capture sources in timestamp order.\n+//\n+// Each source (a node's capture stream, or a local interface socket) delivers its packets with\n+// its own delay. The buffer holds every packet for `window` after it arrived and writes the held\n+// packets in timestamp order, so a packet that was stamped earlier but delivered up to `window`",
        "lineStart": 1,
        "lineEnd": 1701,
        "totalLines": 1702,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523227668,
      "end": 1793523227806
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196509ca2001fy8LXTVsI3aiFM",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965097c9001saIYtHzqO7p3aW",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 5260,
    "input": 1598,
    "output": 13,
    "reasoning": 1,
    "cache": {
      "read": 3648,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1965097c9001saIYtHzqO7p3aW",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523226569,
    "completed": 1793523227816
  },
  "parentID": "msg_196508bbe001tLsHPkKW57hw60",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 5260,
    "input": 1598,
    "output": 13,
    "reasoning": 1,
    "cache": {
      "read": 3648,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 5
step-start
{
  "type": "step-start",
  "id": "prt_19650a8000013ubzqzLivXBjEA",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196509cac001qwe5hzZrXtg7xQ"
}
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "offset": 1702
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1702: +// later still goes out first. A packet stamped before the last packet written arrived too late
1703: +// to be ordered: it is written as it comes and counted, and the count goes to the debug log when
1704: +// the capture ends.
1705: +//
1706: +// A source can place a hold at the earliest timestamp it may still write (Hold); packets stamped
1707: +// after a hold wait for it to be released (Release). The c9s runtime holds while it switches
1708: +// between chained capture segments.
1709: +type Reorder struct {
1710: +	write  func(id uint32, packet *Packet) error
1711: +	onFail func()
1712: +	window time.Duration
1713: +	now    func() time.Time
1714: +
1715: +	mu     sync.Mutex
1716: +	queue  reorderQueue
1717: +	bytes  int
1718: +	seq    uint64
1719: +	holds  map[any]int64
1720: +	err    error
1721: +	wake   chan struct{}
1722: +	stats  reorderStats
1723: +	cursor int64 // timestamp of the latest packet written in order
1724: +}
1725: +
1726: +type reorderStats struct {
1727: +	late    int
1728: +	maxLate time.Duration
1729: +	forced  int
1730: +}
1731: +
1732: +// reorderedPacket is a packet waiting in the buffer.
1733: +type reorderedPacket struct {
1734: +	id      uint32
1735: +	packet  *Packet
1736: +	arrived time.Time
1737: +	seq     uint64
1738: +}
1739: +
1740: +// reorderQueue is a min-heap by timestamp, then arrival.
1741: +type reorderQueue []reorderedPacket
1742: +
1743: +func (q reorderQueue) Len() int { return len(q) }
1744: +
1745: +func (q reorderQueue) Less(i, j int) bool {
1746: +	if q[i].packet.Timestamp != q[j].packet.Timestamp {
1747: +		return q[i].packet.Timestamp < q[j].packet.Timestamp
1748: +	}
1749: +
1750: +	return q[i].seq < q[j].seq
1751: +}
1752: +
1753: +func (q reorderQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
1754: +
1755: +func (q *reorderQueue) Push(
1756: +	x any,
1757: +) {
1758: +	*q = append(*q, x.(reorderedPacket))
1759: +} //nolint:forcetypeassert // heap contract
1760: +
1761: +func (q *reorderQueue) Pop() any {
1762: +	old := *q
1763: +	item := old[len(old)-1]
1764: +	*q = old[:len(old)-1]
1765: +
1766: +	return item
1767: +}
1768: +
1769: +// NewReorder returns a buffer that writes through write; onFail is called once a write
1770: +// failed. A window of zero or less writes every packet as it arrives.
1771: +func NewReorder(
1772: +	window time.Duration,
1773: +	write func(id uint32, packet *Packet) error,
1774: +	onFail func(),
1775: +) *Reorder {
1776: +	return &Reorder{
1777: +		write: write, onFail: onFail, window: window, now: time.Now,
1778: +		holds: map[any]int64{}, wake: make(chan struct{}, 1),
1779: +	}
1780: +}
1781: +
1782: +// push hands a packet to the buffer. It returns the error of a failed write.
1783: +func (q *Reorder) Push(id uint32, packet *Packet) error {
1784: +	q.mu.Lock()
1785: +	defer q.mu.Unlock()
1786: +
1787: +	if q.err != nil {
1788: +		return q.err
1789: +	}
1790: +	if q.window <= 0 {
1791: +		return q.writeLocked(id, packet)
1792: +	}
1793: +	if q.cursor != 0 && packet.Timestamp < q.cursor {
1794: +		q.stats.late++
1795: +		q.stats.maxLate = max(q.stats.maxLate, time.Duration(q.cursor-packet.Timestamp))
1796: +		if q.stats.late == 1 {
1797: +			log.Debug("Capture packet arrived after the reorder window, writing it out of order",
1798: +				"late_by", time.Duration(q.cursor-packet.Timestamp), "window", q.window)
1799: +		}
1800: +
1801: +		return q.writeLocked(id, packet)
1802: +	}
1803: +
1804: +	q.seq++
1805: +	heap.Push(&q.queue, reorderedPacket{id: id, packet: packet, arrived: q.now(), seq: q.seq})
1806: +	q.bytes += len(packet.Data)
1807: +	for q.bytes > maxReorderBytes && q.queue.Len() > 0 {
1808: +		q.stats.forced++
1809: +		if err := q.popLocked(); err != nil {
1810: +			return err
1811: +		}
1812: +	}
1813: +
1814: +	select {
1815: +	case q.wake <- struct{}{}:
1816: +	default:
1817: +	}
1818: +
1819: +	return nil
1820: +}
1821: +
1822: +// hold keeps packets stamped after timestamp in the buffer until release(key).
1823: +func (q *Reorder) Hold(key any, timestamp int64) {
1824: +	q.mu.Lock()
1825: +	defer q.mu.Unlock()
1826: +
1827: +	q.holds[key] = timestamp
1828: +}
1829: +
1830: +// release removes the hold of key.
1831: +func (q *Reorder) Release(key any) {
1832: +	q.mu.Lock()
1833: +	_, held := q.holds[key]
1834: +	delete(q.holds, key)
1835: +	q.mu.Unlock()
1836: +
1837: +	if held {
1838: +		select {
1839: +		case q.wake <- struct{}{}:
1840: +		default:
1841: +		}
1842: +	}
1843: +}
1844: +
1845: +// run writes due packets until ctx ends.
1846: +func (q *Reorder) Run(ctx context.Context) {
1847: +	if q.window <= 0 {
1848: +		return
1849: +	}
1850: +
1851: +	timer := time.NewTimer(time.Hour)
1852: +	defer timer.Stop()
1853: +
1854: +	for {
1855: +		next := q.writeDue()
1856: +		wait := time.Hour
1857: +		if !next.IsZero() {
1858: +			wait = max(next.Sub(q.now()), time.Millisecond)
1859: +		}
1860: +		resetTimer(timer, wait)
1861: +
1862: +		select {
1863: +		case <-ctx.Done():
1864: +			return
1865: +		case <-q.wake:
1866: +		case <-timer.C:
1867: +		}
1868: +	}
1869: +}
1870: +
1871: +// writeDue writes the packets that waited for the window and are not behind a hold, in
1872: +// timestamp order. It returns when the next packet is due, or zero when that depends on a new
1873: +// packet or a released hold.
1874: +func (q *Reorder) writeDue() time.Time {
1875: +	q.mu.Lock()
1876: +	defer q.mu.Unlock()
1877: +
1878: +	held, limit := false, int64(0)
1879: +	for _, timestamp := range q.holds {
1880: +		if !held || timestamp < limit {
1881: +			held, limit = true, timestamp
1882: +		}
1883: +	}
1884: +
1885: +	now := q.now()
1886: +	for q.queue.Len() > 0 && q.err == nil {
1887: +		head := q.queue[0]
1888: +		if held && head.packet.Timestamp > limit {
1889: +			return time.Time{}
1890: +		}
1891: +		if due := head.arrived.Add(q.window); due.After(now) {
1892: +			return due
1893: +		}
1894: +		if q.popLocked() != nil {
1895: +			return time.Time{}
1896: +		}
1897: +	}
1898: +
1899: +	return time.Time{}
1900: +}
1901: +
1902: +// flush writes every remaining packet in timestamp order and logs what could not be ordered.
1903: +func (q *Reorder) Flush() {
1904: +	q.mu.Lock()
1905: +	defer q.mu.Unlock()
1906: +
1907: +	for q.queue.Len() > 0 && q.err == nil {
1908: +		if q.popLocked() != nil {
1909: +			break
1910: +		}
1911: +	}
1912: +	q.queue, q.bytes = nil, 0
1913: +
1914: +	if q.stats.late > 0 || q.stats.forced > 0 {
1915: +		log.Debug("Capture wrote packets out of timestamp order",
1916: +			"late_packets", q.stats.late, "max_late_by", q.stats.maxLate,
1917: +			"window", q.window, "buffer_overflow_packets", q.stats.forced)
1918: +	}
1919: +}
1920: +
1921: +func (q *Reorder) popLocked() error {
1922: +	item := heap.Pop(&q.queue).(reorderedPacket) //nolint:forcetypeassert // heap contract
1923: +	q.bytes -= len(item.packet.Data)
1924: +	q.cursor = max(q.cursor, item.packet.Timestamp)
1925: +
1926: +	return q.writeLocked(item.id, item.packet)
1927: +}
1928: +
1929: +func (q *Reorder) writeLocked(id uint32, packet *Packet) error {
1930: +	if err := q.write(id, packet); err != nil {
1931: +		if q.err == nil {
1932: +			q.err = err
1933: +			if q.onFail != nil {
1934: +				q.onFail()
1935: +			}
1936: +		}
1937: +
1938: +		return err
1939: +	}
1940: +
1941: +	return nil
1942: +}
1943: +
1944: +func resetTimer(timer *time.Timer, d time.Duration) {
1945: +	if !timer.Stop() {
1946: +		select {
1947: +		case <-timer.C:
1948: +		default:
1949: +		}
1950: +	}
1951: +	timer.Reset(d)
1952: +}
1953: diff --git a/capture/reorder_test.go b/capture/reorder_test.go
1954: new file mode 100644
1955: index 0000000..d281bed
1956: --- /dev/null
1957: +++ b/capture/reorder_test.go
1958: @@ -0,0 +1,202 @@
1959: +package capture
1960: +
1961: +import (
1962: +	"context"
1963: +	"errors"
1964: +	"slices"
1965: +	"sync"
1966: +	"testing"
1967: +	"time"
1968: +)
1969: +
1970: +// reorderSink records what a reorder buffer writes.
1971: +type reorderSink struct {
1972: +	mu      sync.Mutex
1973: +	written []int64
1974: +	ids     []uint32
1975: +	failAt  int
1976: +}
1977: +
1978: +func (s *reorderSink) write(id uint32, packet *Packet) error {
1979: +	s.mu.Lock()
1980: +	defer s.mu.Unlock()
1981: +	if s.failAt > 0 && len(s.written) == s.failAt {
1982: +		return errors.New("write |1: broken pipe")
1983: +	}
1984: +	s.written = append(s.written, packet.Timestamp)
1985: +	s.ids = append(s.ids, id)
1986: +
1987: +	return nil
1988: +}
1989: +
1990: +func (s *reorderSink) timestamps() []int64 {
1991: +	s.mu.Lock()
1992: +	defer s.mu.Unlock()
1993: +
1994: +	return slices.Clone(s.written)
1995: +}
1996: +
1997: +// interleavedStreams pushes two synthetic streams of ticks, interleaved in time: stream 0 is
1998: +// delivered at once, stream 1 `delay` after its packets were stamped. Both stamp a packet every
1999: +// 2 ms, offset by 1 ms.
2000: +func interleavedStreams(t *testing.T, q *Reorder, ticks int, delay time.Duration) {
2001: +	t.Helper()
2002: +
2003: +	start := time.Now()
2004: +	type delivery struct {
2005: +		at time.Time
2006: +		id uint32
2007: +		ts int64
2008: +	}
2009: +	var deliveries []delivery
2010: +	for tick := range ticks {
2011: +		stamp := start.Add(time.Duration(tick) * 2 * time.Millisecond)
2012: +		deliveries = append(deliveries,
2013: +			delivery{at: stamp, id: 0, ts: stamp.UnixNano()},
2014: +			delivery{
2015: +				at: stamp.Add(time.Millisecond + delay), id: 1,
2016: +				ts: stamp.Add(time.Millisecond).UnixNano(),
2017: +			})
2018: +	}
2019: +	slices.SortStableFunc(deliveries, func(a, b delivery) int { return a.at.Compare(b.at) })
2020: +
2021: +	for _, next := range deliveries {
2022: +		time.Sleep(time.Until(next.at))
2023: +		if err := q.Push(
2024: +			next.id,
2025: +			&Packet{InterfaceID: next.id, Timestamp: next.ts},
2026: +		); err != nil {
2027: +			t.Fatal(err)
2028: +		}
2029: +	}
2030: +}
2031: +
2032: +func runReorder(q *Reorder) func() {
2033: +	ctx, cancel := context.WithCancel(context.Background())
2034: +	done := make(chan struct{})
2035: +	go func() {
2036: +		defer close(done)
2037: +		q.Run(ctx)
2038: +	}()
2039: +
2040: +	return func() {
2041: +		cancel()
2042: +		<-done
2043: +		q.Flush()
2044: +	}
2045: +}
2046: +
2047: +func TestReorderOrdersStreamsWithinTheWindow(t *testing.T) {
2048: +	t.Parallel()
2049: +
2050: +	sink := &reorderSink{}
2051: +	q := NewReorder(100*time.Millisecond, sink.write, nil)
2052: +	stop := runReorder(q)
2053: +	interleavedStreams(t, q, 60, 40*time.Millisecond)
2054: +
2055: +	// packets go out while the capture runs, not only at the end
2056: +	time.Sleep(150 * time.Millisecond)
2057: +	if len(sink.timestamps()) == 0 {
2058: +		t.Fatal("nothing written while the streams ran")
2059: +	}
2060: +	stop()
2061: +
2062: +	written := sink.timestamps()
2063: +	if len(written) != 120 || !slices.IsSorted(written) {
2064: +		t.Fatalf("written %d packets, sorted %v", len(written), slices.IsSorted(written))
2065: +	}
2066: +	if q.stats.late != 0 {
2067: +		t.Fatalf("late packets = %d", q.stats.late)
2068: +	}
2069: +}
2070: +
2071: +func TestReorderWritesLatePacketsAsTheyCome(t *testing.T) {
2072: +	t.Parallel()
2073: +
2074: +	sink := &reorderSink{}
2075: +	q := NewReorder(20*time.Millisecond, sink.write, nil)
2076: +	stop := runReorder(q)
2077: +	// stream 1 arrives 80 ms after its stamps, far beyond the 20 ms window
2078: +	interleavedStreams(t, q, 60, 80*time.Millisecond)
2079: +	stop()
2080: +
2081: +	written := sink.timestamps()
2082: +	if len(written) != 120 {
2083: +		t.Fatalf("written %d packets, want all 120", len(written))
2084: +	}
2085: +	if q.stats.late == 0 || q.stats.maxLate < 40*time.Millisecond || slices.IsSorted(written) {
2086: +		t.Fatalf("late = %d (max %s), sorted %v; want late packets written out of order",
2087: +			q.stats.late, q.stats.maxLate, slices.IsSorted(written))
2088: +	}
2089: +}
2090: +
2091: +func TestReorderHoldsPacketsAfterAHold(t *testing.T) {
2092: +	t.Parallel()
2093: +
2094: +	sink := &reorderSink{}
2095: +	q := NewReorder(time.Millisecond, sink.write, nil)
2096: +	stop := runReorder(q)
2097: +	defer stop()
2098: +
2099: +	chain := &struct{ name string }{"chain"}
2100: +	q.Hold(chain, 100)
2101: +	for _, ts := range []int64{50, 150, 100, 200} {
2102: +		if err := q.Push(0, &Packet{Timestamp: ts}); err != nil {
2103: +			t.Fatal(err)
2104: +		}
2105: +	}
2106: +	time.Sleep(30 * time.Millisecond)
2107: +	if got := sink.timestamps(); !slices.Equal(got, []int64{50, 100}) {
2108: +		t.Fatalf("written under the hold = %v, want [50 100]", got)
2109: +	}
2110: +
2111: +	// the chain writes what it held back, then releases
2112: +	if err := q.Push(1, &Packet{Timestamp: 120}); err != nil {
2113: +		t.Fatal(err)
2114: +	}
2115: +	q.Release(chain)
2116: +	time.Sleep(30 * time.Millisecond)
2117: +	if got := sink.timestamps(); !slices.Equal(got, []int64{50, 100, 120, 150, 200}) {
2118: +		t.Fatalf("written after the release = %v", got)
2119: +	}
2120: +}
2121: +
2122: +func TestReorderStopsAtTheFirstWriteError(t *testing.T) {
2123: +	t.Parallel()
2124: +
2125: +	sink := &reorderSink{failAt: 2}
2126: +	failed := 0
2127: +	q := NewReorder(time.Millisecond, sink.write, func() { failed++ })
2128: +	stop := runReorder(q)
2129: +
2130: +	var err error
2131: +	for ts := int64(1); ts < 50 && err == nil; ts++ {
2132: +		err = q.Push(0, &Packet{Timestamp: ts})
2133: +		time.Sleep(2 * time.Millisecond)
2134: +	}
2135: +	stop()
2136: +
2137: +	if err == nil || failed != 1 || len(sink.timestamps()) != 2 {
2138: +		t.Fatalf(
2139: +			"push error = %v, onFail calls %d, written %d",
2140: +			err,
2141: +			failed,
2142: +			len(sink.timestamps()),
2143: +		)
2144: +	}
2145: +}
2146: +
2147: +func TestReorderWithoutWindowWritesThrough(t *testing.T) {
2148: +	t.Parallel()
2149: +
2150: +	sink := &reorderSink{}
2151: +	q := NewReorder(0, sink.write, nil)
2152: +	for _, ts := range []int64{30, 10, 20} {
2153: +		if err := q.Push(0, &Packet{Timestamp: ts}); err != nil {
2154: +			t.Fatal(err)
2155: +		}
2156: +	}
2157: +	if got := sink.timestamps(); !slices.Equal(got, []int64{30, 10, 20}) {
2158: +		t.Fatalf("written = %v, want arrival order", got)
2159: +	}
2160: +}
2161: diff --git a/cmd/capture.go b/cmd/capture.go
2162: new file mode 100644
2163: index 0000000..20117bc
2164: --- /dev/null
2165: +++ b/cmd/capture.go
2166: @@ -0,0 +1,262 @@
2167: +package cmd
2168: +
2169: +import (
2170: +	"encoding/json"
2171: +	"fmt"
2172: +	"io"
2173: +	"os"
2174: +	"strings"
2175: +	"time"
2176: +
2177: +	"github.com/charmbracelet/log"
2178: +	tableWriter "github.com/jedib0t/go-pretty/v6/table"
2179: +	"github.com/jedib0t/go-pretty/v6/text"
2180: +	"github.com/spf13/cobra"
2181: +	clabconstants "github.com/srl-labs/containerlab/constants"
2182: +	clabcore "github.com/srl-labs/containerlab/core"
2183: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2184: +	clabutils "github.com/srl-labs/containerlab/utils"
2185: +)
2186: +
2187: +// CaptureOptions are the flags of the capture command.
2188: +type CaptureOptions struct {
2189: +	Targets     []string
2190: +	Duration    time.Duration
2191: +	PacketLimit int
2192: +	SnapLength  int
2193: +	Write       string
2194: +	List        bool
2195: +	Format      string
2196: +}
2197: +
2198: +func captureCmd(o *Options) (*cobra.Command, error) {
2199: +	c := &cobra.Command{
2200: +		Use:   "capture",
2201: +		Short: "capture packets on lab link interfaces",
2202: +		Long: "capture packets on lab link interfaces of one or more nodes into one pcapng " +
2203: +			"stream\nreference: https://containerlab.dev/cmd/capture/",
2204: +		PreRunE: func(_ *cobra.Command, _ []string) error {
2205: +			if commandSkipsRoot(o.Global.Runtime) {
2206: +				return nil
2207: +			}
2208: +
2209: +			// Docker and Podman captures open packet sockets in the nodes' namespaces
2210: +			return clabutils.CheckAndGetRootPrivs()
2211: +		},
2212: +		SilenceUsage: true,
2213: +		RunE: func(cmd *cobra.Command, _ []string) error {
2214: +			return captureFn(cmd, o)
2215: +		},
2216: +	}
2217: +
2218: +	c.Flags().StringArrayVar(
2219: +		&o.Capture.Targets,
2220: +		"target",
2221: +		o.Capture.Targets,
2222: +		"node and interfaces to capture, as <node>:<interface>[,<interface>...]; repeatable",
2223: +	)
2224: +	c.Flags().DurationVar(
2225: +		&o.Capture.Duration,
2226: +		"duration",
2227: +		o.Capture.Duration,
2228: +		"stop after this duration; 0 captures until interrupted",
2229: +	)
2230: +	c.Flags().IntVar(
2231: +		&o.Capture.PacketLimit,
2232: +		"packet-limit",
2233: +		o.Capture.PacketLimit,
2234: +		"stop after this many packets across all targets; 0 means no limit",
2235: +	)
2236: +	c.Flags().IntVar(
2237: +		&o.Capture.SnapLength,
2238: +		"snap-length",
2239: +		o.Capture.SnapLength,
2240: +		"bytes kept of each packet (64 to 1048576); 0 uses the runtime default",
2241: +	)
2242: +	c.Flags().StringVarP(
2243: +		&o.Capture.Write,
2244: +		"write",
2245: +		"w",
2246: +		o.Capture.Write,
2247: +		"pcapng output file; - writes to stdout",
2248: +	)
2249: +	c.Flags().BoolVar(
2250: +		&o.Capture.List,
2251: +		"list",
2252: +		o.Capture.List,
2253: +		"list the capturable interfaces instead of capturing",
2254: +	)
2255: +	c.Flags().StringVarP(
2256: +		&o.Capture.Format,
2257: +		"format",
2258: +		"f",
2259: +		o.Capture.Format,
2260: +		"output format of --list: table or json",
2261: +	)
2262: +
2263: +	c.Example = `# Capture e1-1 of srl1 and e1-1 of srl2 for 30 seconds into one file
2264: +containerlab capture -t srl.clab.yml --target srl1:e1-1 --target srl2:e1-1 \
2265: +  --duration 30s -w srl.pcapng
2266: +
2267: +# Capture two interfaces of one node and watch them live in Wireshark
2268: +containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -
2269: +
2270: +# List the interfaces capture accepts
2271: +containerlab capture --name srl --list -f json
2272: +
2273: +# Capture a lab running on the c9s runtime
2274: +containerlab -r c9s capture --name srl --target srl1:e1-1 -w srl.pcapng`
2275: +
2276: +	return c, nil
2277: +}
2278: +
2279: +func captureFn(cmd *cobra.Command, o *Options) error {
2280: +	if o.Global.TopologyName == "" && o.Global.TopologyFile == "" {
2281: +		return fmt.Errorf("provide either a lab name (--name) or a topology file path (--topo)")
2282: +	}
2283: +
2284: +	if o.Capture.List {
2285: +		return captureListFn(cmd, o)
2286: +	}
2287: +
2288: +	targets, err := parseCaptureTargets(o.Capture.Targets)
2289: +	if err != nil {
2290: +		return err
2291: +	}
2292: +
2293: +	c, err := clabcore.NewContainerLab(o.ToClabOptions()...)
2294: +	if err != nil {
2295: +		return err
2296: +	}
2297: +
2298: +	// An interrupt ends the capture; the command still finishes the file and exits cleanly.
2299: +	// Armed before the file is created, so an interrupt never leaves it empty.
2300: +	o.Global.FinishOnCancel.Store(true)
2301: +	defer o.Global.FinishOnCancel.Store(false)
2302: +
2303: +	output := cmd.OutOrStdout()
2304: +	if o.Capture.Write != "" && o.Capture.Write != "-" {
2305: +		file, err := os.Create(o.Capture.Write)
2306: +		if err != nil {
2307: +			return fmt.Errorf("failed to create the capture file: %w", err)
2308: +		}
2309: +		defer file.Close()
2310: +		output = file
2311: +
2312: +		// the file belongs to the user who ran the command, also through sudo or setuid
2313: +		if err := clabutils.SetUIDAndGID(o.Capture.Write); err != nil {
2314: +			log.Debug("Cannot hand the capture file to the user", "file", o.Capture.Write,
2315: +				"error", err)
2316: +		}
2317: +	}
2318: +
2319: +	err = c.Capture(cmd.Context(), clablabruntime.CaptureRequest{
2320: +		Targets:     targets,
2321: +		Duration:    o.Capture.Duration,
2322: +		PacketLimit: o.Capture.PacketLimit,
2323: +		SnapLength:  o.Capture.SnapLength,
2324: +	}, output)
2325: +	if err != nil {
2326: +		return err
2327: +	}
2328: +
2329: +	if file, ok := output.(*os.File); ok && output != cmd.OutOrStdout() {
2330: +		if err := file.Sync(); err != nil {
2331: +			return fmt.Errorf("failed to write the capture file: %w", err)
2332: +		}
2333: +	}
2334: +
2335: +	return nil
2336: +}
2337: +
2338: +// parseCaptureTargets parses --target values: <node>:<interface>[,<interface>...]. The node name
2339: +// ends at the first colon, so interface names may contain colons or slashes.
2340: +func parseCaptureTargets(values []string) ([]clablabruntime.CaptureTarget, error) {
2341: +	if len(values) == 0 {
2342: +		return nil, fmt.Errorf("provide at least one --target <node>:<interface>[,<interface>...]")
2343: +	}
2344: +
2345: +	targets := make([]clablabruntime.CaptureTarget, 0, len(values))
2346: +	for _, value := range values {
2347: +		node, interfaces, ok := strings.Cut(strings.TrimSpace(value), ":")
2348: +		node = strings.TrimSpace(node)
2349: +		if !ok || node == "" || strings.TrimSpace(interfaces) == "" {
2350: +			return nil, fmt.Errorf("invalid --target %q: use <node>:<interface>[,<interface>...]",
2351: +				value)
2352: +		}
2353: +
2354: +		for _, name := range strings.Split(interfaces, ",") {
2355: +			name = strings.TrimSpace(name)
2356: +			if name == "" {
2357: +				return nil, fmt.Errorf("invalid --target %q: empty interface name", value)
2358: +			}
2359: +			targets = append(targets, clablabruntime.CaptureTarget{Node: node, Interface: name})
2360: +		}
2361: +	}
2362: +
2363: +	return targets, nil
2364: +}
2365: +
2366: +func captureListFn(cmd *cobra.Command, o *Options) error {
2367: +	format := o.Capture.Format
2368: +	if format == "" {
2369: +		format = clabconstants.FormatTable
2370: +	}
2371: +	if format != clabconstants.FormatTable && format != clabconstants.FormatJSON {
2372: +		return fmt.Errorf("output format %q is not supported, use 'table' or 'json'", format)
2373: +	}
2374: +	if len(o.Capture.Targets) != 0 {
2375: +		return fmt.Errorf("--list lists every running node's interfaces; it takes no --target")
2376: +	}
2377: +
2378: +	c, err := clabcore.NewContainerLab(o.ToClabOptions()...)
2379: +	if err != nil {
2380: +		return err
2381: +	}
2382: +
2383: +	interfaces, err := c.CaptureInterfaces(cmd.Context())
2384: +	if err != nil {
2385: +		return err
2386: +	}
2387: +
2388: +	return printCaptureInterfaces(cmd.OutOrStdout(), interfaces, format)
2389: +}
2390: +
2391: +func printCaptureInterfaces(
2392: +	w io.Writer,
2393: +	interfaces []clablabruntime.CaptureInterface,
2394: +	format string,
2395: +) error {
2396: +	if format == clabconstants.FormatJSON {
2397: +		if interfaces == nil {
2398: +			interfaces = []clablabruntime.CaptureInterface{}
2399: +		}
2400: +		data, err := json.MarshalIndent(interfaces, "", "  ")
2401: +		if err != nil {
2402: +			return err
2403: +		}
2404: +		_, err = fmt.Fprintln(w, string(data))
2405: +
2406: +		return err
2407: +	}
2408: +
2409: +	table := tableWriter.NewWriter()
2410: +	table.SetOutputMirror(w)
2411: +	table.SetStyle(tableWriter.StyleRounded)
2412: +	table.Style().Format.Header = text.FormatTitle
2413: +	table.Style().Format.HeaderAlign = text.AlignCenter
2414: +	table.AppendHeader(tableWriter.Row{"Node", "Interface", "Alias", "Peer Node", "Peer Interface"})
2415: +	table.SetColumnConfigs([]tableWriter.ColumnConfig{{Number: 1, AutoMerge: true}})
2416: +	for _, intf := range interfaces {
2417: +		alias := intf.Alias
2418: +		if alias == "" {
2419: +			alias = clabconstants.NotApplicable
2420: +		}
2421: +		table.AppendRow(tableWriter.Row{
2422: +			intf.Node, intf.Interface, alias, intf.PeerNode, intf.PeerInterface,
2423: +		})
2424: +	}
2425: +	table.Render()
2426: +
2427: +	return nil
2428: +}
2429: diff --git a/cmd/capture_test.go b/cmd/capture_test.go
2430: new file mode 100644
2431: index 0000000..da12d66
2432: --- /dev/null
2433: +++ b/cmd/capture_test.go
2434: @@ -0,0 +1,109 @@
2435: +package cmd
2436: +
2437: +import (
2438: +	"bytes"
2439: +	"encoding/json"
2440: +	"slices"
2441: +	"strings"
2442: +	"testing"
2443: +
2444: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2445: +)
2446: +
2447: +func TestParseCaptureTargets(t *testing.T) {
2448: +	t.Parallel()
2449: +
2450: +	targets, err := parseCaptureTargets([]string{
2451: +		"srl1:e1-1,ethernet-1/2", " sros : 1/1/3 ", "r1:eth1",
2452: +	})
2453: +	if err != nil {
2454: +		t.Fatal(err)
2455: +	}
2456: +	want := []clablabruntime.CaptureTarget{
2457: +		{Node: "srl1", Interface: "e1-1"},
2458: +		{Node: "srl1", Interface: "ethernet-1/2"},
2459: +		{Node: "sros", Interface: "1/1/3"},
2460: +		{Node: "r1", Interface: "eth1"},
2461: +	}
2462: +	if !slices.Equal(targets, want) {
2463: +		t.Fatalf("targets = %+v, want %+v", targets, want)
2464: +	}
2465: +
2466: +	for _, bad := range [][]string{nil, {"srl1"}, {":e1-1"}, {"srl1:"}, {"srl1:e1-1,,e1-2"}} {
2467: +		if _, err := parseCaptureTargets(bad); err == nil {
2468: +			t.Errorf("parseCaptureTargets(%q) succeeded", bad)
2469: +		}
2470: +	}
2471: +}
2472: +
2473: +func TestCaptureCommandFlags(t *testing.T) {
2474: +	o := GetOptions()
2475: +	cmd, err := captureCmd(o)
2476: +	if err != nil {
2477: +		t.Fatal(err)
2478: +	}
2479: +	if err := cmd.ParseFlags([]string{
2480: +		"--target", "srl1:e1-1", "--target", "srl2:e1-1,e1-2", "--duration", "90m",
2481: +		"--packet-limit", "100", "--snap-length", "128", "-w", "out.pcapng",
2482: +	}); err != nil {
2483: +		t.Fatal(err)
2484: +	}
2485: +	if !slices.Equal(o.Capture.Targets, []string{"srl1:e1-1", "srl2:e1-1,e1-2"}) ||
2486: +		o.Capture.Duration.Minutes() != 90 || o.Capture.PacketLimit != 100 ||
2487: +		o.Capture.SnapLength != 128 || o.Capture.Write != "out.pcapng" {
2488: +		t.Fatalf("capture options = %+v", o.Capture)
2489: +	}
2490: +	if def := cmd.Flag("write").DefValue; def != "-" {
2491: +		t.Fatalf("--write default = %q, want stdout", def)
2492: +	}
2493: +}
2494: +
2495: +func TestPrintCaptureInterfaces(t *testing.T) {
2496: +	t.Parallel()
2497: +
2498: +	interfaces := []clablabruntime.CaptureInterface{
2499: +		{
2500: +			Node:          "srl1",
2501: +			Interface:     "e1-1",
2502: +			Alias:         "ethernet-1/1",
2503: +			PeerNode:      "srl2",
2504: +			PeerInterface: "ethernet-1/1",
2505: +		},
2506: +		{Node: "srl1", Interface: "e1-2", PeerNode: "host", PeerInterface: "srl1-e1-2"},
2507: +	}
2508: +
2509: +	var out bytes.Buffer
2510: +	if err := printCaptureInterfaces(&out, interfaces, "json"); err != nil {
2511: +		t.Fatal(err)
2512: +	}
2513: +	var decoded []map[string]any
2514: +	if err := json.Unmarshal(out.Bytes(), &decoded); err != nil {
2515: +		t.Fatal(err)
2516: +	}
2517: +	if decoded[0]["peer_node"] != "srl2" || decoded[0]["alias"] != "ethernet-1/1" {
2518: +		t.Fatalf("json = %s", out.String())
2519: +	}
2520: +	if _, hasAlias := decoded[1]["alias"]; hasAlias {
2521: +		t.Fatalf("an empty alias is printed: %s", out.String())
2522: +	}
2523: +
2524: +	out.Reset()
2525: +	if err := printCaptureInterfaces(
2526: +		&out,
2527: +		nil,
2528: +		"json",
2529: +	); err != nil ||
2530: +		strings.TrimSpace(out.String()) != "[]" {
2531: +		t.Fatalf("empty json = %q, %v", out.String(), err)
2532: +	}
2533: +
2534: +	out.Reset()
2535: +	if err := printCaptureInterfaces(&out, interfaces, "table"); err != nil {
2536: +		t.Fatal(err)
2537: +	}
2538: +	for _, want := range []string{"Peer Interface", "ethernet-1/1", "srl1-e1-2", "N/A"} {
2539: +		if !strings.Contains(out.String(), want) {
2540: +			t.Fatalf("table does not contain %q:\n%s", want, out.String())
2541: +		}
2542: +	}
2543: +}
2544: diff --git a/cmd/context.go b/cmd/context.go
2545: index 223cb1d..21d5bea 100644
2546: --- a/cmd/context.go
2547: +++ b/cmd/context.go
2548: @@ -51,10 +51,20 @@ func SignalHandledContext() (context.Context, context.CancelFunc) {
2549:  
2550:  		cancel()
2551:  
2552:  		options := GetOptions()
2553:  
2554: +		if options.Global.FinishOnCancel.Load() {
2555: +			log.Info("Stopping, press Ctrl+C again to abort")
2556: +
2557: +			sig = <-sigs
2558: +
2559: +			log.Errorf("received signal %q while stopping, exiting", sig)
2560: +
2561: +			os.Exit(1)
2562: +		}
2563: +
2564:  		if !options.Global.CleanOnCancel.Load() {
2565:  			log.Debug("clean on cancel is not true, exiting")
2566:  
2567:  			os.Exit(1)
2568:  		}
2569: diff --git a/cmd/inspect.go b/cmd/inspect.go
2570: index 1b6f41d..55fb61f 100644
2571: --- a/cmd/inspect.go
2572: +++ b/cmd/inspect.go
2573: @@ -70,10 +70,14 @@ func inspectCmd(o *Options) (*cobra.Command, error) {
2574:  		Short: "inspect interfaces of one or multiple nodes in a lab",
2575:  		Long: "show interfaces and their attributes in a specific deployed lab\n" +
2576:  			"reference: https://containerlab.dev/cmd/inspect/interfaces/",
2577:  		Aliases: []string{"int", "intf"},
2578:  		PreRunE: func(_ *cobra.Command, _ []string) error {
2579: +			if commandSkipsRoot(o.Global.Runtime) {
2580: +				return nil
2581: +			}
2582: +
2583:  			return clabutils.CheckAndGetRootPrivs()
2584:  		},
2585:  		RunE: func(cobraCmd *cobra.Command, _ []string) error {
2586:  			return inspectInterfacesFn(cobraCmd, o)
2587:  		},
2588: diff --git a/cmd/inspect_interfaces.go b/cmd/inspect_interfaces.go
2589: index 0f64f03..91035c2 100644
2590: --- a/cmd/inspect_interfaces.go
2591: +++ b/cmd/inspect_interfaces.go
2592: @@ -33,10 +33,25 @@ func inspectInterfacesFn(cobraCmd *cobra.Command, o *Options) error {
2593:  	c, err := clabcore.NewContainerLab(o.ToClabOptions()...)
2594:  	if err != nil {
2595:  		return fmt.Errorf("could not parse the topology file: %v", err)
2596:  	}
2597:  
2598: +	if c.LabRuntime != nil {
2599: +		// lab runtimes list the link interfaces packet capture accepts, with their state
2600: +		containerInterfaces, err := c.LabRuntimeInterfaces(cobraCmd.Context(),
2601: +			o.Inspect.InterfacesNode)
2602: +		if err != nil {
2603: +			return fmt.Errorf("failed to list node interfaces: %w", err)
2604: +		}
2605: +		if len(containerInterfaces) == 0 {
2606: +			log.Info("no running nodes found")
2607: +			return nil
2608: +		}
2609: +
2610: +		return printContainerInterfaces(containerInterfaces, o.Inspect.InterfacesFormat)
2611: +	}
2612: +
2613:  	var labNameFilterLabel string
2614:  
2615:  	switch {
2616:  	case o.Global.TopologyName != "":
2617:  		labNameFilterLabel = o.Global.TopologyName
2618: diff --git a/cmd/options.go b/cmd/options.go
2619: index 8717d3b..6037551 100644
2620: --- a/cmd/options.go
2621: +++ b/cmd/options.go
2622: @@ -53,10 +53,14 @@ func GetOptions() *Options {
2623:  				InterfacesFormat: "table",
2624:  			},
2625:  			Logs: &LogsOptions{
2626:  				Tail: -1,
2627:  			},
2628: +			Capture: &CaptureOptions{
2629: +				Write:  "-",
2630: +				Format: "table",
2631: +			},
2632:  			Graph: &GraphOptions{
2633:  				Server:           "0.0.0.0:50080",
2634:  				MermaidDirection: "TD",
2635:  				DrawIOVersion:    "latest",
2636:  			},
2637: @@ -142,10 +146,11 @@ type Options struct {
2638:  	Exec           *ExecOptions
2639:  	Inspect        *InspectOptions
2640:  	Graph          *GraphOptions
2641:  	Events         *EventsOptions
2642:  	Logs           *LogsOptions
2643: +	Capture        *CaptureOptions
2644:  	ToolsAPI       *ToolsApiOptions
2645:  	ToolsCert      *ToolsCertOptions
2646:  	ToolsTxOffload *ToolsDisableTxOffloadOptions
2647:  	ToolsGoTTY     *ToolsGoTTYOptions
2648:  	ToolsNetem     *ToolsNetemOptions
2649: @@ -257,10 +262,15 @@ type GlobalOptions struct {
2650:  	// special flag that should only be set by deploy, informs the context handler to destroy
2651:  	// (or not) when root context is canceled. The signal handler goroutine reads it while
2652:  	// deploy is running, so it is atomic.
2653:  	CleanOnCancel atomic.Bool
2654:  
2655: +	// FinishOnCancel informs the context handler that the running command ends cleanly on its
2656: +	// own once the root context is canceled (capture finishes its output), so the handler
2657: +	// waits for it instead of exiting.
2658: +	FinishOnCancel atomic.Bool
2659: +
2660:  	// special flag that is only set on deploy,
2661:  	// if true, the topology file backup is created at /tmp/.clab/bak
2662:  	BackupTopologyFile bool
2663:  }
2664:  
2665: diff --git a/cmd/root.go b/cmd/root.go
2666: index 0baf203..a9b1c8b 100644
2667: --- a/cmd/root.go
2668: +++ b/cmd/root.go
2669: @@ -35,10 +35,11 @@ func subcommandRegisterFuncs() []func(*Options) (*cobra.Command, error) {
2670:  		generateCmd,
2671:  		graphCmd,
2672:  		eventsCmd,
2673:  		inspectCmd,
2674:  		logsCmd,
2675: +		captureCmd,
2676:  		redeployCmd,
2677:  		saveCmd,
2678:  		toolsCmd,
2679:  		validateCmd,
2680:  	}
2681: @@ -263,15 +264,10 @@ func checkLabRuntimeCommandSupport(cobraCmd *cobra.Command, runtimeName string)
2682:  			"the %q command needs running containers with lab runtime %q unless it renders "+
2683:  				"from the topology file alone; use --offline, --dot, --mermaid or --drawio",
2684:  			"graph", runtimeName)
2685:  	}
2686:  
2687: -	if getCommandPath(cobraCmd) == "inspect.interfaces" {
2688: -		return fmt.Errorf("the %q command is not supported with lab runtime %q",
2689: -			"inspect interfaces", runtimeName)
2690: -	}
2691: -
2692:  	var unsupported []string
2693:  	for _, flagName := range labRuntimeUnsupportedFlags[getCommandPath(cobraCmd)] {
2694:  		if labRuntimeFlagWasSet(cobraCmd, flagName) {
2695:  			unsupported = append(unsupported, "--"+flagName)
2696:  		}
2697: @@ -339,10 +335,11 @@ func getTopoFilePath(cobraCmd *cobra.Command, o *Options) error { // skipcq: GO-
2698:  		cobraCmd.Name() != "inspect" &&
2699:  		cobraCmd.Name() != "save" &&
2700:  		cobraCmd.Name() != "graph" &&
2701:  		cobraCmd.Name() != "validate" &&
2702:  		cobraCmd.Name() != "logs" &&
2703: +		cobraCmd.Name() != "capture" &&
2704:  		cobraCmd.Name() != "interfaces" {
2705:  		return nil
2706:  	}
2707:  
2708:  	// start/stop/restart topology lookup applies only to top-level lifecycle commands.
2709: diff --git a/cmd/root_test.go b/cmd/root_test.go
2710: index 418a947..af02e34 100644
2711: --- a/cmd/root_test.go
2712: +++ b/cmd/root_test.go
2713: @@ -289,20 +289,23 @@ func TestCheckLabRuntimeFlagAndNestedCommandSupport(t *testing.T) {
2714:  				t.Fatalf("checkLabRuntimeCommandSupport() error = %v, wantErr %v", err, tt.wantErr)
2715:  			}
2716:  		})
2717:  	}
2718:  
2719: -	t.Run("inspect interfaces rejected", func(t *testing.T) {
2720: +	t.Run("inspect interfaces and capture accepted", func(t *testing.T) {
2721:  		root := &cobra.Command{Use: "containerlab"}
2722:  		inspect := &cobra.Command{Use: "inspect"}
2723:  		interfaces := &cobra.Command{Use: "interfaces"}
2724: -		root.AddCommand(inspect)
2725: +		capture := &cobra.Command{Use: "capture"}
2726: +		root.AddCommand(inspect, capture)
2727:  		inspect.AddCommand(interfaces)
2728:  
2729: -		if err := checkLabRuntimeCommandSupport(
2730: -			interfaces,
2731: -			clablabruntime.ClabernetesRuntimeName,
2732: -		); err == nil {
2733: -			t.Fatal("inspect interfaces was accepted for clabernetes")
2734: +		for _, cmd := range []*cobra.Command{interfaces, capture} {
2735: +			if err := checkLabRuntimeCommandSupport(
2736: +				cmd,
2737: +				clablabruntime.ClabernetesRuntimeName,
2738: +			); err != nil {
2739: +				t.Fatalf("%s rejected for clabernetes: %v", cmd.Name(), err)
2740: +			}
2741:  		}
2742:  	})
2743:  }
2744: diff --git a/core/capture.go b/core/capture.go
2745: new file mode 100644
2746: index 0000000..2e12fc2
2747: --- /dev/null
2748: +++ b/core/capture.go
2749: @@ -0,0 +1,93 @@
2750: +package core
2751: +
2752: +import (
2753: +	"context"
2754: +	"io"
2755: +
2756: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2757: +	clabtypes "github.com/srl-labs/containerlab/types"
2758: +)
2759: +
2760: +// CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for
2761: +// every running node, with the peer at the other end of each link. With Docker and Podman, the
2762: +// interfaces come from the topology's links; lab runtimes list them through their packet
2763: +// capturer.
2764: +func (c *CLab) CaptureInterfaces(
2765: +	ctx context.Context,
2766: +	nodeNames ...string,
2767: +) ([]clablabruntime.CaptureInterface, error) {
2768: +	if c.LabRuntime == nil {
2769: +		return c.localCaptureInterfacesOf(ctx, nodeNames)
2770: +	}
2771: +
2772: +	capturer, err := c.packetCapturer()
2773: +	if err != nil {
2774: +		return nil, err
2775: +	}
2776: +
2777: +	return capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{
2778: +		Name:     c.Config.Name,
2779: +		Nodes:    nodeNames,
2780: +		Identity: c.labRuntimeIdentity,
2781: +	})
2782: +}
2783: +
2784: +// Capture streams pcapng from lab link interfaces to w until req.Duration passed,
2785: +// req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name
2786: +// and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces
2787: +// itself through packet sockets in the nodes' network namespaces, which needs root; lab
2788: +// runtimes capture through their packet capturer.
2789: +func (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {
2790: +	if c.LabRuntime == nil {
2791: +		return c.captureLocal(ctx, req, w)
2792: +	}
2793: +
2794: +	capturer, err := c.packetCapturer()
2795: +	if err != nil {
2796: +		return err
2797: +	}
2798: +
2799: +	if req.Name == "" {
2800: +		req.Name = c.Config.Name
2801: +	}
2802: +	if req.Identity.IsZero() {
2803: +		req.Identity = c.labRuntimeIdentity
2804: +	}
2805: +
2806: +	return capturer.Capture(ctx, req, w)
2807: +}
2808: +
2809: +// LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their
2810: +// state, in the shape ListContainersInterfaces reports for local containers.
2811: +func (c *CLab) LabRuntimeInterfaces(
2812: +	ctx context.Context,
2813: +	nodeName string,
2814: +) ([]*clabtypes.ContainerInterfaces, error) {
2815: +	inspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](
2816: +		c, "inspecting interfaces")
2817: +	if err != nil {
2818: +		return nil, err
2819: +	}
2820: +	if err := c.requireLabName(); err != nil {
2821: +		return nil, err
2822: +	}
2823: +
2824: +	req := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}
2825: +	if nodeName != "" {
2826: +		req.Nodes = []string{nodeName}
2827: +	}
2828: +
2829: +	return inspector.InspectInterfaces(ctx, req)
2830: +}
2831: +
2832: +func (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {
2833: +	capturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, "packet capture")
2834: +	if err != nil {
2835: +		return nil, err
2836: +	}
2837: +	if err := c.requireLabName(); err != nil {
2838: +		return nil, err
2839: +	}
2840: +
2841: +	return capturer, nil
2842: +}
2843: diff --git a/core/capture_local.go b/core/capture_local.go
2844: new file mode 100644
2845: index 0000000..fada0bf
2846: --- /dev/null
2847: +++ b/core/capture_local.go
2848: @@ -0,0 +1,255 @@
2849: +package core
2850: +
2851: +import (
2852: +	"context"
2853: +	"fmt"
2854: +	"io"
2855: +	"slices"
2856: +	"sort"
2857: +	"strings"
2858: +
2859: +	clabcapture "github.com/srl-labs/containerlab/capture"
2860: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2861: +	clablinks "github.com/srl-labs/containerlab/links"
2862: +	clabnodes "github.com/srl-labs/containerlab/nodes"
2863: +	clabruntime "github.com/srl-labs/containerlab/runtime"
2864: +)
2865: +
2866: +// localCaptureInterface is a lab link interface of a node on this machine.
2867: +type localCaptureInterface struct {
2868: +	node clabnodes.Node
2869: +	info clablabruntime.CaptureInterface
2870: +}
2871: +
2872: +// localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with
2873: +// the far end of each link, per node name. Host and management network endpoints are the far
2874: +// ends of links, not nodes to capture on.
2875: +func (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {
2876: +	if len(c.Nodes) == 0 {
2877: +		return nil, fmt.Errorf("the topology of lab %q is not available; capture reads the "+
2878: +			"lab's links from it, pass it with --topo", c.Config.Name)
2879: +	}
2880: +	if len(c.Links) == 0 {
2881: +		if err := c.ResolveLinks(); err != nil {
2882: +			return nil, fmt.Errorf("failed to resolve the links of lab %q: %w", c.Config.Name, err)
2883: +		}
2884: +	}
2885: +
2886: +	indexes := make([]int, 0, len(c.Links))
2887: +	for idx := range c.Links {
2888: +		indexes = append(indexes, idx)
2889: +	}
2890: +	sort.Ints(indexes)
2891: +
2892: +	result := map[string][]localCaptureInterface{}
2893: +	for _, idx := range indexes {
2894: +		endpoints := c.Links[idx].GetEndpoints()
2895: +		for epIdx, endpoint := range endpoints {
2896: +			if endpoint.IsNodeless() || endpoint.IsRuntimeDiscovered() ||
2897: +				endpoint.GetNode() == nil {
2898: +				continue
2899: +			}
2900: +			name := endpoint.GetNode().GetShortName()
2901: +			node, ok := c.Nodes[name]
2902: +			if !ok {
2903: +				continue
2904: +			}
2905: +
2906: +			info := clablabruntime.CaptureInterface{
2907: +				Node:      name,
2908: +				Interface: endpoint.GetIfaceName(),
2909: +			}
2910: +			if alias := endpoint.GetIfaceAlias(); alias != info.Interface {
2911: +				info.Alias = alias
2912: +			}
2913: +			if len(endpoints) == 2 {
2914: +				peer := endpoints[1-epIdx]
2915: +				info.PeerNode = capturePeerNode(peer)
2916: +				info.PeerInterface = peer.GetIfaceDisplayName()
2917: +			}
2918: +
2919: +			result[name] = append(result[name], localCaptureInterface{node: node, info: info})
2920: +		}
2921: +	}
2922: +
2923: +	return result, nil
2924: +}
2925: +
2926: +// capturePeerNode names the node at the far end of a link: "host" for a host endpoint and
2927: +// "mgmt-net" for the management network, whose shared link nodes carry other names once a lab
2928: +// was deployed.
2929: +func capturePeerNode(peer clablinks.Endpoint) string {
2930: +	if peer.IsNodeless() {
2931: +		if _, ok := peer.(*clablinks.EndpointBridge); ok {
2932: +			return string(clablinks.LinkTypeMgmtNet)
2933: +		}
2934: +
2935: +		return string(clablinks.LinkTypeHost)
2936: +	}
2937: +	if peer.GetNode() == nil {
2938: +		return ""
2939: +	}
2940: +
2941: +	return peer.GetNode().GetShortName()
2942: +}
2943: +
2944: +// lookupLocalNode finds a lab node by its topology name or its container name.
2945: +func (c *CLab) lookupLocalNode(name string) (clabnodes.Node, error) {
2946: +	if node, ok := c.Nodes[name]; ok {
2947: +		return node, nil
2948: +	}
2949: +	for _, node := range c.Nodes {
2950: +		if node.Config().LongName == name {
2951: +			return node, nil
2952: +		}
2953: +	}
2954: +
2955: +	names := make([]string, 0, len(c.Nodes))
2956: +	for nodeName := range c.Nodes {
2957: +		names = append(names, nodeName)
2958: +	}
2959: +	slices.Sort(names)
2960: +
2961: +	return nil, fmt.Errorf("node %q is not part of lab %q; nodes: %s", name, c.Config.Name,
2962: +		strings.Join(names, ", "))
2963: +}
2964: +
2965: +// nodeRuns reports whether a node's network namespace can be entered.
2966: +func nodeRuns(ctx context.Context, node clabnodes.Node) bool {
2967: +	if node.Config().IsRootNamespaceBased {
2968: +		return true
2969: +	}
2970: +
2971: +	return clabruntime.ContainerHasJoinableNetns(node.GetContainerStatus(ctx))
2972: +}
2973: +
2974: +// localCaptureInterfacesOf implements CaptureInterfaces for Docker and Podman: the requested
2975: +// nodes, or every running node.
2976: +func (c *CLab) localCaptureInterfacesOf(
2977: +	ctx context.Context,
2978: +	nodeNames []string,
2979: +) ([]clablabruntime.CaptureInterface, error) {
2980: +	if err := c.requireLabName(); err != nil {
2981: +		return nil, err
2982: +	}
2983: +	byNode, err := c.localCaptureInterfaces()
2984: +	if err != nil {
2985: +		return nil, err
2986: +	}
2987: +
2988: +	var nodes []clabnodes.Node
2989: +	if len(nodeNames) == 0 {
2990: +		for _, node := range c.Nodes {
2991: +			if nodeRuns(ctx, node) {
2992: +				nodes = append(nodes, node)
2993: +			}
2994: +		}
2995: +	} else {
2996: +		for _, name := range nodeNames {
2997: +			node, err := c.lookupLocalNode(name)
2998: +			if err != nil {
2999: +				return nil, err
3000: +			}
3001: +			nodes = append(nodes, node)
3002: +		}
3003: +	}
3004: +
3005: +	result := make([]clablabruntime.CaptureInterface, 0)
3006: +	seen := map[string]bool{}
3007: +	for _, node := range nodes {
3008: +		name := node.Config().ShortName
3009: +		if seen[name] {
3010: +			continue
3011: +		}
3012: +		seen[name] = true
3013: +		for _, entry := range byNode[name] {
3014: +			result = append(result, entry.info)
3015: +		}
3016: +	}
3017: +	sortCaptureInterfaces(result)
3018: +
3019: +	return result, nil
3020: +}
3021: +
3022: +func sortCaptureInterfaces(interfaces []clablabruntime.CaptureInterface) {
3023: +	sort.SliceStable(interfaces, func(i, j int) bool {
3024: +		if interfaces[i].Node != interfaces[j].Node {
3025: +			return interfaces[i].Node < interfaces[j].Node
3026: +		}
3027: +
3028: +		return interfaces[i].Interface < interfaces[j].Interface
3029: +	})
3030: +}
3031: +
3032: +// resolveLocalCaptureTargets checks every target against the node's link interfaces, by name or
3033: +// alias, and returns them in request order.
3034: +func (c *CLab) resolveLocalCaptureTargets(
3035: +	targets []clablabruntime.CaptureTarget,
3036: +) ([]clabcapture.LocalTarget, error) {
3037: +	byNode, err := c.localCaptureInterfaces()
3038: +	if err != nil {
3039: +		return nil, err
3040: +	}
3041: +
3042: +	resolved := make([]clabcapture.LocalTarget, 0, len(targets))
3043: +	seen := map[string]bool{}
3044: +	for _, target := range targets {
3045: +		node, err := c.lookupLocalNode(target.Node)
3046: +		if err != nil {
3047: +			return nil, err
3048: +		}
3049: +		name := node.Config().ShortName
3050: +
3051: +		infos := make([]clablabruntime.CaptureInterface, 0, len(byNode[name]))
3052: +		for _, entry := range byNode[name] {
3053: +			infos = append(infos, entry.info)
3054: +		}
3055: +		sortCaptureInterfaces(infos)
3056: +		info, ok := clabcapture.FindInterface(infos, target.Interface)
3057: +		if !ok {
3058: +			return nil, fmt.Errorf("interface %q of node %q is not a capturable link "+
3059: +				"interface; capturable: %s", target.Interface, target.Node,
3060: +				clabcapture.DescribeInterfaces(infos))
3061: +		}
3062: +
3063: +		key := name + "\x00" + info.Interface
3064: +		if seen[key] {
3065: +			return nil, fmt.Errorf("interface %q of node %q is requested more than once",
3066: +				info.Interface, target.Node)
3067: +		}
3068: +		seen[key] = true
3069: +
3070: +		resolved = append(resolved, clabcapture.LocalTarget{
3071: +			Node:      name,
3072: +			Interface: info.Interface,
3073: +			Exec:      node.ExecFunction,
3074: +		})
3075: +	}
3076: +
3077: +	return resolved, nil
3078: +}
3079: +
3080: +// captureLocal implements Capture for Docker and Podman through packet sockets in the nodes'
3081: +// network namespaces.
3082: +func (c *CLab) captureLocal(
3083: +	ctx context.Context,
3084: +	req clablabruntime.CaptureRequest,
3085: +	w io.Writer,
3086: +) error {
3087: +	if err := c.requireLabName(); err != nil {
3088: +		return err
3089: +	}
3090: +	if req.Name == "" {
3091: +		req.Name = c.Config.Name
3092: +	}
3093: +	if err := clabcapture.ValidateRequest(&req); err != nil {
3094: +		return err
3095: +	}
3096: +
3097: +	targets, err := c.resolveLocalCaptureTargets(req.Targets)
3098: +	if err != nil {
3099: +		return err
3100: +	}
3101: +
3102: +	return clabcapture.CaptureLocal(ctx, req, targets, w)
3103: +}
3104: diff --git a/core/capture_test.go b/core/capture_test.go
3105: new file mode 100644
3106: index 0000000..b5d34b0
3107: --- /dev/null
3108: +++ b/core/capture_test.go
3109: @@ -0,0 +1,210 @@
3110: +package core
3111: +
3112: +import (
3113: +	"bytes"
3114: +	"context"
3115: +	"io"
3116: +	"slices"
3117: +	"strings"
3118: +	"testing"
3119: +
3120: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
3121: +	clabtypes "github.com/srl-labs/containerlab/types"
3122: +)
3123: +
3124: +// captureLabRuntime records the capture requests core sends.
3125: +type captureLabRuntime struct {
3126: +	clablabruntime.LabRuntime
3127: +
3128: +	nodeRequest    clablabruntime.NodeRequest
3129: +	captureRequest clablabruntime.CaptureRequest
3130: +}
3131: +
3132: +func (r *captureLabRuntime) CaptureInterfaces(
3133: +	_ context.Context,
3134: +	req clablabruntime.NodeRequest,
3135: +) ([]clablabruntime.CaptureInterface, error) {
3136: +	r.nodeRequest = req
3137: +
3138: +	return []clablabruntime.CaptureInterface{{Node: "r1", Interface: "eth1"}}, nil
3139: +}
3140: +
3141: +func (r *captureLabRuntime) Capture(
3142: +	_ context.Context,
3143: +	req clablabruntime.CaptureRequest,
3144: +	w io.Writer,
3145: +) error {
3146: +	r.captureRequest = req
3147: +	_, err := io.WriteString(w, "pcapng")
3148: +
3149: +	return err
3150: +}
3151: +
3152: +func (r *captureLabRuntime) InspectInterfaces(
3153: +	_ context.Context,
3154: +	req clablabruntime.NodeRequest,
3155: +) ([]*clabtypes.ContainerInterfaces, error) {
3156: +	r.nodeRequest = req
3157: +
3158: +	return []*clabtypes.ContainerInterfaces{{ContainerName: "lab1-r1"}}, nil
3159: +}
3160: +
3161: +func TestCaptureHelpersFillLabAndIdentity(t *testing.T) {
3162: +	t.Parallel()
3163: +
3164: +	lr := &captureLabRuntime{}
3165: +	c := newAccessTestCLab(lr)
3166: +	ctx := context.Background()
3167: +
3168: +	interfaces, err := c.CaptureInterfaces(ctx, "R1")
3169: +	if err != nil || len(interfaces) != 1 {
3170: +		t.Fatalf("CaptureInterfaces() = %+v, %v", interfaces, err)
3171: +	}
3172: +	if lr.nodeRequest.Name != "lab1" || lr.nodeRequest.Nodes[0] != "R1" ||
3173: +		!lr.nodeRequest.Identity.Equal(testIdentity) {
3174: +		t.Fatalf("interfaces request = %+v", lr.nodeRequest)
3175: +	}
3176: +
3177: +	var out bytes.Buffer
3178: +	if err := c.Capture(ctx, clablabruntime.CaptureRequest{
3179: +		Targets: []clablabruntime.CaptureTarget{{Node: "r1", Interface: "eth1"}},
3180: +	}, &out); err != nil {
3181: +		t.Fatal(err)
3182: +	}
3183: +	if out.String() != "pcapng" || lr.captureRequest.Name != "lab1" ||
3184: +		!lr.captureRequest.Identity.Equal(testIdentity) {
3185: +		t.Fatalf("capture request = %+v, output %q", lr.captureRequest, out.String())
3186: +	}
3187: +
3188: +	ifaces, err := c.LabRuntimeInterfaces(ctx, "r1")
3189: +	if err != nil || len(ifaces) != 1 || lr.nodeRequest.Nodes[0] != "r1" {
3190: +		t.Fatalf("LabRuntimeInterfaces() = %+v, %v, request %+v", ifaces, err, lr.nodeRequest)
3191: +	}
3192: +	if _, err := c.LabRuntimeInterfaces(ctx, ""); err != nil || lr.nodeRequest.Nodes != nil {
3193: +		t.Fatalf("all nodes request = %+v, %v", lr.nodeRequest, err)
3194: +	}
3195: +}
3196: +
3197: +// newLocalCaptureCLab loads the capture test topology. Its host and mgmt-net links register
3198: +// endpoints on link nodes the whole process shares, so the tests using it do not run in
3199: +// parallel and release the endpoints when they end.
3200: +func newLocalCaptureCLab(t *testing.T) *CLab {
3201: +	t.Helper()
3202: +
3203: +	c, err := NewContainerLab(WithTopoPath("test_data/capture.clab.yml", nil))
3204: +	if err != nil {
3205: +		t.Fatal(err)
3206: +	}
3207: +	t.Cleanup(c.resetResolvedLinks)
3208: +
3209: +	return c
3210: +}
3211: +
3212: +func TestLocalCaptureInterfacesComeFromTheTopologyLinks(t *testing.T) {
3213: +	c := newLocalCaptureCLab(t)
3214: +
3215: +	got, err := c.CaptureInterfaces(context.Background(), "srl1", "client")
3216: +	if err != nil {
3217: +		t.Fatal(err)
3218: +	}
3219: +	want := []clablabruntime.CaptureInterface{
3220: +		{Node: "client", Interface: "eth1", PeerNode: "srl1", PeerInterface: "e1-2"},
3221: +		{Node: "client", Interface: "eth2", PeerNode: "host", PeerInterface: "client-eth2"},
3222: +		{Node: "client", Interface: "eth3", PeerNode: "mgmt-net", PeerInterface: "client-eth3"},
3223: +		{
3224: +			Node: "srl1", Interface: "e1-1", Alias: "ethernet-1/1",
3225: +			PeerNode: "srl2", PeerInterface: "e1-1",
3226: +		},
3227: +		{Node: "srl1", Interface: "e1-2", PeerNode: "client", PeerInterface: "eth1"},
3228: +	}
3229: +	if !slices.Equal(got, want) {
3230: +		t.Fatalf("CaptureInterfaces() =\n%+v\nwant\n%+v", got, want)
3231: +	}
3232: +
3233: +	if _, err := c.CaptureInterfaces(context.Background(), "r9"); err == nil ||
3234: +		!strings.Contains(err.Error(), `node "r9" is not part of lab "capture"`) {
3235: +		t.Fatalf("unknown node: error = %v", err)
3236: +	}
3237: +}
3238: +
3239: +func TestLocalCaptureTargetsResolveByNameOrAlias(t *testing.T) {
3240: +	c := newLocalCaptureCLab(t)
3241: +
3242: +	targets, err := c.resolveLocalCaptureTargets([]clablabruntime.CaptureTarget{
3243: +		{Node: "srl2", Interface: "e1-1"},
3244: +		{Node: "srl1", Interface: "ethernet-1/1"},
3245: +		{Node: "clab-capture-client", Interface: "eth2"},
3246: +	})
3247: +	if err != nil {
3248: +		t.Fatal(err)
3249: +	}
3250: +	var got []string
3251: +	for _, target := range targets {
3252: +		if target.Exec == nil {
3253: +			t.Fatalf("target %s:%s has no namespace exec", target.Node, target.Interface)
3254: +		}
3255: +		got = append(got, target.Node+":"+target.Interface)
3256: +	}
3257: +	if want := []string{"srl2:e1-1", "srl1:e1-1", "client:eth2"}; !slices.Equal(got, want) {
3258: +		t.Fatalf("targets = %v, want %v", got, want)
3259: +	}
3260: +
3261: +	for _, tc := range []struct {
3262: +		name    string
3263: +		targets []clablabruntime.CaptureTarget
3264: +		want    string
3265: +	}{
3266: +		{
3267: +			name:    "management interface",
3268: +			targets: []clablabruntime.CaptureTarget{{Node: "client", Interface: "eth0"}},
3269: +			want: `interface "eth0" of node "client" is not a capturable link interface; ` +
3270: +				"capturable: eth1, eth2, eth3",
3271: +		},
3272: +		{
3273: +			name: "same interface twice",
3274: +			targets: []clablabruntime.CaptureTarget{
3275: +				{Node: "srl1", Interface: "e1-1"}, {Node: "srl1", Interface: "ethernet-1/1"},
3276: +			},
3277: +			want: `interface "e1-1" of node "srl1" is requested more than once`,
3278: +		},
3279: +		{
3280: +			name:    "unknown node",
3281: +			targets: []clablabruntime.CaptureTarget{{Node: "r9", Interface: "eth1"}},
3282: +			want:    `node "r9" is not part of lab "capture"`,
3283: +		},
3284: +	} {
3285: +		if _, err := c.resolveLocalCaptureTargets(tc.targets); err == nil ||
3286: +			!strings.Contains(err.Error(), tc.want) {
3287: +			t.Errorf("%s: error = %v, want %q", tc.name, err, tc.want)
3288: +		}
3289: +	}
3290: +}
3291: +
3292: +func TestLocalCaptureNeedsTheTopology(t *testing.T) {
3293: +	t.Parallel()
3294: +
3295: +	c := &CLab{Config: &Config{Name: "lab1"}, globalRuntimeName: "docker"}
3296: +	err := c.Capture(context.Background(), clablabruntime.CaptureRequest{
3297: +		Targets: []clablabruntime.CaptureTarget{{Node: "r1", Interface: "eth1"}},
3298: +	}, io.Discard)
3299: +	if err == nil || !strings.Contains(err.Error(), `the topology of lab "lab1" is not available`) {
3300: +		t.Fatalf("error = %v", err)
3301: +	}
3302: +	if err := c.Capture(context.Background(), clablabruntime.CaptureRequest{},
3303: +		io.Discard); err == nil || !strings.Contains(err.Error(), "at least one capture target") {
3304: +		t.Fatalf("no targets: error = %v", err)
3305: +	}
3306: +}
3307: +
3308: +func TestLabRuntimeWithoutCaptureFails(t *testing.T) {
3309: +	t.Parallel()
3310: +
3311: +	unsupported := newAccessTestCLab(&recordingDestroyLabRuntime{})
3312: +	if err := unsupported.Capture(
3313: +		context.Background(),
3314: +		clablabruntime.CaptureRequest{},
3315: +		io.Discard,
3316: +	); err == nil || !strings.Contains(err.Error(), "does not support packet capture") {
3317: +		t.Fatalf("lab runtime without capture: error = %v", err)
3318: +	}
3319: +}
3320: diff --git a/core/labruntime_cluster_test.go b/core/labruntime_cluster_test.go
3321: index 06ecf57..981a302 100644
3322: --- a/core/labruntime_cluster_test.go
3323: +++ b/core/labruntime_cluster_test.go
3324: @@ -1,10 +1,11 @@
3325:  package core
3326:  
3327:  import (
3328:  	"bytes"
3329:  	"context"
3330: +	"encoding/binary"
3331:  	"errors"
3332:  	"io"
3333:  	"net"
3334:  	"net/http"
3335:  	"os"
3336: @@ -175,5 +176,153 @@ func TestC9sClusterNodeAccess(t *testing.T) {
3337:  		if err == nil || !strings.Contains(err.Error(), "forbidden") {
3338:  			t.Fatalf("impersonated user without rights: error = %v, want forbidden", err)
3339:  		}
3340:  	})
3341:  }
3342: +
3343: +// TestC9sClusterCapture captures through the library against a deployed c9s lab, as an identity
3344: +// that holds only the clabernetes-lab-editor role in the lab namespace. It runs only when
3345: +// CLAB_C9S_TEST_LAB names the lab and CLAB_C9S_TEST_CAPTURE_USER the identity (tests/14-clabernetes
3346: +// sets both). The lab must have linux nodes "client" (10.10.10.1) and "server" (10.10.10.2)
3347: +// linked by eth1. CLAB_C9S_TEST_FORBIDDEN_USER names an identity without a binding.
3348: +func TestC9sClusterCapture(t *testing.T) {
3349: +	lab := os.Getenv("CLAB_C9S_TEST_LAB")
3350: +	user := os.Getenv("CLAB_C9S_TEST_CAPTURE_USER")
3351: +	if lab == "" || user == "" {
3352: +		t.Skip("CLAB_C9S_TEST_LAB or CLAB_C9S_TEST_CAPTURE_USER is not set")
3353: +	}
3354: +
3355: +	newCLab := func(t *testing.T, user string) *CLab {
3356: +		t.Helper()
3357: +
3358: +		c, err := NewContainerLab(
3359: +			WithRuntime(clablabruntime.ClabernetesRuntimeName, nil),
3360: +			WithTopologyName(lab),
3361: +			WithLabRuntimeIdentity(clablabruntime.Identity{User: user}),
3362: +		)
3363: +		if err != nil {
3364: +			t.Fatal(err)
3365: +		}
3366: +
3367: +		return c
3368: +	}
3369: +	c := newCLab(t, user)
3370: +
3371: +	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
3372: +	defer cancel()
3373: +
3374: +	t.Run("version check", func(t *testing.T) {
3375: +		if err := c.CheckLabRuntimeSupport(ctx); err != nil {
3376: +			t.Fatal(err)
3377: +		}
3378: +	})
3379: +
3380: +	t.Run("capture interfaces", func(t *testing.T) {
3381: +		interfaces, err := c.CaptureInterfaces(ctx)
3382: +		if err != nil {
3383: +			t.Fatal(err)
3384: +		}
3385: +		want := []clablabruntime.CaptureInterface{
3386: +			{Node: "client", Interface: "eth1", PeerNode: "server", PeerInterface: "eth1"},
3387: +			{Node: "server", Interface: "eth1", PeerNode: "client", PeerInterface: "eth1"},
3388: +		}
3389: +		if len(interfaces) != 2 || interfaces[0] != want[0] || interfaces[1] != want[1] {
3390: +			t.Fatalf("interfaces = %+v", interfaces)
3391: +		}
3392: +	})
3393: +
3394: +	t.Run("capture both ends of a link", func(t *testing.T) {
3395: +		pinged := make(chan error, 1)
3396: +		go func() {
3397: +			time.Sleep(time.Second)
3398: +			pinged <- c.AttachLabRuntimeNode(ctx, clablabruntime.AttachRequest{
3399: +				NodeName: "client",
3400: +				Command:  []string{"ping", "-c", "4", "-i", "0.3", "10.10.10.2"},
3401: +			}, clablabruntime.AttachStreams{Stdout: io.Discard})
3402: +		}()
3403: +
3404: +		var out bytes.Buffer
3405: +		err := c.Capture(ctx, clablabruntime.CaptureRequest{
3406: +			Targets: []clablabruntime.CaptureTarget{
3407: +				{Node: "client", Interface: "eth1"}, {Node: "server", Interface: "eth1"},
3408: +			},
3409: +			Duration: 5 * time.Second,
3410: +		}, &out)
3411: +		if err != nil {
3412: +			t.Fatal(err)
3413: +		}
3414: +		if err := <-pinged; err != nil {
3415: +			t.Fatalf("ping: %v", err)
3416: +		}
3417: +
3418: +		names, icmp := summarizePCAPNG(t, out.Bytes())
3419: +		if len(names) != 2 || names[0] != "client:eth1" || names[1] != "server:eth1" {
3420: +			t.Fatalf("interfaces = %v", names)
3421: +		}
3422: +		// every echo request and reply crosses both ends
3423: +		if icmp[0] < 8 || icmp[1] < 8 {
3424: +			t.Fatalf("ICMP packets per interface = %v, want at least 8 on each", icmp)
3425: +		}
3426: +	})
3427: +
3428: +	t.Run("restart as lab editor", func(t *testing.T) {
3429: +		if err := c.RestartNodes(ctx, []string{"server"}); err != nil {
3430: +			t.Fatal(err)
3431: +		}
3432: +	})
3433: +
3434: +	t.Run("forbidden identity", func(t *testing.T) {
3435: +		forbidden := os.Getenv("CLAB_C9S_TEST_FORBIDDEN_USER")
3436: +		if forbidden == "" {
3437: +			t.Skip("CLAB_C9S_TEST_FORBIDDEN_USER is not set")
3438: +		}
3439: +
3440: +		err := newCLab(t, forbidden).Capture(ctx, clablabruntime.CaptureRequest{
3441: +			Targets:  []clablabruntime.CaptureTarget{{Node: "client", Interface: "eth1"}},
3442: +			Duration: time.Second,
3443: +		}, io.Discard)
3444: +		if err == nil || !strings.Contains(err.Error(), "forbidden") {
3445: +			t.Fatalf("capture as %s = %v, want forbidden", forbidden, err)
3446: +		}
3447: +	})
3448: +}
3449: +
3450: +// summarizePCAPNG returns the interface names of a little-endian pcapng stream and its IPv4 ICMP
3451: +// packets per interface ID.
3452: +func summarizePCAPNG(t *testing.T, data []byte) ([]string, map[uint32]int) {
3453: +	t.Helper()
3454: +
3455: +	var names []string
3456: +	icmp := map[uint32]int{}
3457: +	for len(data) >= 12 {
3458: +		blockType := binary.LittleEndian.Uint32(data[0:4])
3459: +		length := int(binary.LittleEndian.Uint32(data[4:8]))
3460: +		if length < 12 || length > len(data) {
3461: +			t.Fatalf("invalid block length %d", length)
3462: +		}
3463: +		body := data[8 : length-4]
3464: +		switch blockType {
3465: +		case 1: // Interface Description Block
3466: +			options := body[8:]
3467: +			for len(options) >= 4 {
3468: +				code := binary.LittleEndian.Uint16(options[0:2])
3469: +				size := int(binary.LittleEndian.Uint16(options[2:4]))
3470: +				if code == 0 {
3471: +					break
3472: +				}
3473: +				if code == 2 {
3474: +					names = append(names, string(options[4:4+size]))
3475: +				}
3476: +				options = options[4+size+(4-size%4)%4:]
3477: +			}

(Output capped at 50 KB. Showing lines 1702-3477. Use offset=3478 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19650a82f001Q9fv1L743J8c71",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196509cac001qwe5hzZrXtg7xQ",
  "callID": "call_bc6d0e096b734dd1bb838627",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "offset": 1702
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n1702: +// later still goes out first. A packet stamped before the last packet written arrived too late\n1703: +// to be ordered: it is written as it comes and counted, and the count goes to the debug log when\n1704: +// the capture ends.\n1705: +//\n1706: +// A source can place a hold at the earliest timestamp it may still write (Hold); packets stamped\n1707: +// after a hold wait for it to be released (Release). The c9s runtime holds while it switches\n1708: +// between chained capture segments.\n1709: +type Reorder struct {\n1710: +\twrite  func(id uint32, packet *Packet) error\n1711: +\tonFail func()\n1712: +\twindow time.Duration\n1713: +\tnow    func() time.Time\n1714: +\n1715: +\tmu     sync.Mutex\n1716: +\tqueue  reorderQueue\n1717: +\tbytes  int\n1718: +\tseq    uint64\n1719: +\tholds  map[any]int64\n1720: +\terr    error\n1721: +\twake   chan struct{}\n1722: +\tstats  reorderStats\n1723: +\tcursor int64 // timestamp of the latest packet written in order\n1724: +}\n1725: +\n1726: +type reorderStats struct {\n1727: +\tlate    int\n1728: +\tmaxLate time.Duration\n1729: +\tforced  int\n1730: +}\n1731: +\n1732: +// reorderedPacket is a packet waiting in the buffer.\n1733: +type reorderedPacket struct {\n1734: +\tid      uint32\n1735: +\tpacket  *Packet\n1736: +\tarrived time.Time\n1737: +\tseq     uint64\n1738: +}\n1739: +\n1740: +// reorderQueue is a min-heap by timestamp, then arrival.\n1741: +type reorderQueue []reorderedPacket\n1742: +\n1743: +func (q reorderQueue) Len() int { return len(q) }\n1744: +\n1745: +func (q reorderQueue) Less(i, j int) bool {\n1746: +\tif q[i].packet.Timestamp != q[j].packet.Timestamp {\n1747: +\t\treturn q[i].packet.Timestamp < q[j].packet.Timestamp\n1748: +\t}\n1749: +\n1750: +\treturn q[i].seq < q[j].seq\n1751: +}\n1752: +\n1753: +func (q reorderQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }\n1754: +\n1755: +func (q *reorderQueue) Push(\n1756: +\tx any,\n1757: +) {\n1758: +\t*q = append(*q, x.(reorderedPacket))\n1759: +} //nolint:forcetypeassert // heap contract\n1760: +\n1761: +func (q *reorderQueue) Pop() any {\n1762: +\told := *q\n1763: +\titem := old[len(old)-1]\n1764: +\t*q = old[:len(old)-1]\n1765: +\n1766: +\treturn item\n1767: +}\n1768: +\n1769: +// NewReorder returns a buffer that writes through write; onFail is called once a write\n1770: +// failed. A window of zero or less writes every packet as it arrives.\n1771: +func NewReorder(\n1772: +\twindow time.Duration,\n1773: +\twrite func(id uint32, packet *Packet) error,\n1774: +\tonFail func(),\n1775: +) *Reorder {\n1776: +\treturn &Reorder{\n1777: +\t\twrite: write, onFail: onFail, window: window, now: time.Now,\n1778: +\t\tholds: map[any]int64{}, wake: make(chan struct{}, 1),\n1779: +\t}\n1780: +}\n1781: +\n1782: +// push hands a packet to the buffer. It returns the error of a failed write.\n1783: +func (q *Reorder) Push(id uint32, packet *Packet) error {\n1784: +\tq.mu.Lock()\n1785: +\tdefer q.mu.Unlock()\n1786: +\n1787: +\tif q.err != nil {\n1788: +\t\treturn q.err\n1789: +\t}\n1790: +\tif q.window <= 0 {\n1791: +\t\treturn q.writeLocked(id, packet)\n1792: +\t}\n1793: +\tif q.cursor != 0 && packet.Timestamp < q.cursor {\n1794: +\t\tq.stats.late++\n1795: +\t\tq.stats.maxLate = max(q.stats.maxLate, time.Duration(q.cursor-packet.Timestamp))\n1796: +\t\tif q.stats.late == 1 {\n1797: +\t\t\tlog.Debug(\"Capture packet arrived after the reorder window, writing it out of order\",\n1798: +\t\t\t\t\"late_by\", time.Duration(q.cursor-packet.Timestamp), \"window\", q.window)\n1799: +\t\t}\n1800: +\n1801: +\t\treturn q.writeLocked(id, packet)\n1802: +\t}\n1803: +\n1804: +\tq.seq++\n1805: +\theap.Push(&q.queue, reorderedPacket{id: id, packet: packet, arrived: q.now(), seq: q.seq})\n1806: +\tq.bytes += len(packet.Data)\n1807: +\tfor q.bytes > maxReorderBytes && q.queue.Len() > 0 {\n1808: +\t\tq.stats.forced++\n1809: +\t\tif err := q.popLocked(); err != nil {\n1810: +\t\t\treturn err\n1811: +\t\t}\n1812: +\t}\n1813: +\n1814: +\tselect {\n1815: +\tcase q.wake <- struct{}{}:\n1816: +\tdefault:\n1817: +\t}\n1818: +\n1819: +\treturn nil\n1820: +}\n1821: +\n1822: +// hold keeps packets stamped after timestamp in the buffer until release(key).\n1823: +func (q *Reorder) Hold(key any, timestamp int64) {\n1824: +\tq.mu.Lock()\n1825: +\tdefer q.mu.Unlock()\n1826: +\n1827: +\tq.holds[key] = timestamp\n1828: +}\n1829: +\n1830: +// release removes the hold of key.\n1831: +func (q *Reorder) Release(key any) {\n1832: +\tq.mu.Lock()\n1833: +\t_, held := q.holds[key]\n1834: +\tdelete(q.holds, key)\n1835: +\tq.mu.Unlock()\n1836: +\n1837: +\tif held {\n1838: +\t\tselect {\n1839: +\t\tcase q.wake <- struct{}{}:\n1840: +\t\tdefault:\n1841: +\t\t}\n1842: +\t}\n1843: +}\n1844: +\n1845: +// run writes due packets until ctx ends.\n1846: +func (q *Reorder) Run(ctx context.Context) {\n1847: +\tif q.window <= 0 {\n1848: +\t\treturn\n1849: +\t}\n1850: +\n1851: +\ttimer := time.NewTimer(time.Hour)\n1852: +\tdefer timer.Stop()\n1853: +\n1854: +\tfor {\n1855: +\t\tnext := q.writeDue()\n1856: +\t\twait := time.Hour\n1857: +\t\tif !next.IsZero() {\n1858: +\t\t\twait = max(next.Sub(q.now()), time.Millisecond)\n1859: +\t\t}\n1860: +\t\tresetTimer(timer, wait)\n1861: +\n1862: +\t\tselect {\n1863: +\t\tcase <-ctx.Done():\n1864: +\t\t\treturn\n1865: +\t\tcase <-q.wake:\n1866: +\t\tcase <-timer.C:\n1867: +\t\t}\n1868: +\t}\n1869: +}\n1870: +\n1871: +// writeDue writes the packets that waited for the window and are not behind a hold, in\n1872: +// timestamp order. It returns when the next packet is due, or zero when that depends on a new\n1873: +// packet or a released hold.\n1874: +func (q *Reorder) writeDue() time.Time {\n1875: +\tq.mu.Lock()\n1876: +\tdefer q.mu.Unlock()\n1877: +\n1878: +\theld, limit := false, int64(0)\n1879: +\tfor _, timestamp := range q.holds {\n1880: +\t\tif !held || timestamp < limit {\n1881: +\t\t\theld, limit = true, timestamp\n1882: +\t\t}\n1883: +\t}\n1884: +\n1885: +\tnow := q.now()\n1886: +\tfor q.queue.Len() > 0 && q.err == nil {\n1887: +\t\thead := q.queue[0]\n1888: +\t\tif held && head.packet.Timestamp > limit {\n1889: +\t\t\treturn time.Time{}\n1890: +\t\t}\n1891: +\t\tif due := head.arrived.Add(q.window); due.After(now) {\n1892: +\t\t\treturn due\n1893: +\t\t}\n1894: +\t\tif q.popLocked() != nil {\n1895: +\t\t\treturn time.Time{}\n1896: +\t\t}\n1897: +\t}\n1898: +\n1899: +\treturn time.Time{}\n1900: +}\n1901: +\n1902: +// flush writes every remaining packet in timestamp order and logs what could not be ordered.\n1903: +func (q *Reorder) Flush() {\n1904: +\tq.mu.Lock()\n1905: +\tdefer q.mu.Unlock()\n1906: +\n1907: +\tfor q.queue.Len() > 0 && q.err == nil {\n1908: +\t\tif q.popLocked() != nil {\n1909: +\t\t\tbreak\n1910: +\t\t}\n1911: +\t}\n1912: +\tq.queue, q.bytes = nil, 0\n1913: +\n1914: +\tif q.stats.late > 0 || q.stats.forced > 0 {\n1915: +\t\tlog.Debug(\"Capture wrote packets out of timestamp order\",\n1916: +\t\t\t\"late_packets\", q.stats.late, \"max_late_by\", q.stats.maxLate,\n1917: +\t\t\t\"window\", q.window, \"buffer_overflow_packets\", q.stats.forced)\n1918: +\t}\n1919: +}\n1920: +\n1921: +func (q *Reorder) popLocked() error {\n1922: +\titem := heap.Pop(&q.queue).(reorderedPacket) //nolint:forcetypeassert // heap contract\n1923: +\tq.bytes -= len(item.packet.Data)\n1924: +\tq.cursor = max(q.cursor, item.packet.Timestamp)\n1925: +\n1926: +\treturn q.writeLocked(item.id, item.packet)\n1927: +}\n1928: +\n1929: +func (q *Reorder) writeLocked(id uint32, packet *Packet) error {\n1930: +\tif err := q.write(id, packet); err != nil {\n1931: +\t\tif q.err == nil {\n1932: +\t\t\tq.err = err\n1933: +\t\t\tif q.onFail != nil {\n1934: +\t\t\t\tq.onFail()\n1935: +\t\t\t}\n1936: +\t\t}\n1937: +\n1938: +\t\treturn err\n1939: +\t}\n1940: +\n1941: +\treturn nil\n1942: +}\n1943: +\n1944: +func resetTimer(timer *time.Timer, d time.Duration) {\n1945: +\tif !timer.Stop() {\n1946: +\t\tselect {\n1947: +\t\tcase <-timer.C:\n1948: +\t\tdefault:\n1949: +\t\t}\n1950: +\t}\n1951: +\ttimer.Reset(d)\n1952: +}\n1953: diff --git a/capture/reorder_test.go b/capture/reorder_test.go\n1954: new file mode 100644\n1955: index 0000000..d281bed\n1956: --- /dev/null\n1957: +++ b/capture/reorder_test.go\n1958: @@ -0,0 +1,202 @@\n1959: +package capture\n1960: +\n1961: +import (\n1962: +\t\"context\"\n1963: +\t\"errors\"\n1964: +\t\"slices\"\n1965: +\t\"sync\"\n1966: +\t\"testing\"\n1967: +\t\"time\"\n1968: +)\n1969: +\n1970: +// reorderSink records what a reorder buffer writes.\n1971: +type reorderSink struct {\n1972: +\tmu      sync.Mutex\n1973: +\twritten []int64\n1974: +\tids     []uint32\n1975: +\tfailAt  int\n1976: +}\n1977: +\n1978: +func (s *reorderSink) write(id uint32, packet *Packet) error {\n1979: +\ts.mu.Lock()\n1980: +\tdefer s.mu.Unlock()\n1981: +\tif s.failAt > 0 && len(s.written) == s.failAt {\n1982: +\t\treturn errors.New(\"write |1: broken pipe\")\n1983: +\t}\n1984: +\ts.written = append(s.written, packet.Timestamp)\n1985: +\ts.ids = append(s.ids, id)\n1986: +\n1987: +\treturn nil\n1988: +}\n1989: +\n1990: +func (s *reorderSink) timestamps() []int64 {\n1991: +\ts.mu.Lock()\n1992: +\tdefer s.mu.Unlock()\n1993: +\n1994: +\treturn slices.Clone(s.written)\n1995: +}\n1996: +\n1997: +// interleavedStreams pushes two synthetic streams of ticks, interleaved in time: stream 0 is\n1998: +// delivered at once, stream 1 `delay` after its packets were stamped. Both stamp a packet every\n1999: +// 2 ms, offset by 1 ms.\n2000: +func interleavedStreams(t *testing.T, q *Reorder, ticks int, delay time.Duration) {\n2001: +\tt.Helper()\n2002: +\n2003: +\tstart := time.Now()\n2004: +\ttype delivery struct {\n2005: +\t\tat time.Time\n2006: +\t\tid uint32\n2007: +\t\tts int64\n2008: +\t}\n2009: +\tvar deliveries []delivery\n2010: +\tfor tick := range ticks {\n2011: +\t\tstamp := start.Add(time.Duration(tick) * 2 * time.Millisecond)\n2012: +\t\tdeliveries = append(deliveries,\n2013: +\t\t\tdelivery{at: stamp, id: 0, ts: stamp.UnixNano()},\n2014: +\t\t\tdelivery{\n2015: +\t\t\t\tat: stamp.Add(time.Millisecond + delay), id: 1,\n2016: +\t\t\t\tts: stamp.Add(time.Millisecond).UnixNano(),\n2017: +\t\t\t})\n2018: +\t}\n2019: +\tslices.SortStableFunc(deliveries, func(a, b delivery) int { return a.at.Compare(b.at) })\n2020: +\n2021: +\tfor _, next := range deliveries {\n2022: +\t\ttime.Sleep(time.Until(next.at))\n2023: +\t\tif err := q.Push(\n2024: +\t\t\tnext.id,\n2025: +\t\t\t&Packet{InterfaceID: next.id, Timestamp: next.ts},\n2026: +\t\t); err != nil {\n2027: +\t\t\tt.Fatal(err)\n2028: +\t\t}\n2029: +\t}\n2030: +}\n2031: +\n2032: +func runReorder(q *Reorder) func() {\n2033: +\tctx, cancel := context.WithCancel(context.Background())\n2034: +\tdone := make(chan struct{})\n2035: +\tgo func() {\n2036: +\t\tdefer close(done)\n2037: +\t\tq.Run(ctx)\n2038: +\t}()\n2039: +\n2040: +\treturn func() {\n2041: +\t\tcancel()\n2042: +\t\t<-done\n2043: +\t\tq.Flush()\n2044: +\t}\n2045: +}\n2046: +\n2047: +func TestReorderOrdersStreamsWithinTheWindow(t *testing.T) {\n2048: +\tt.Parallel()\n2049: +\n2050: +\tsink := &reorderSink{}\n2051: +\tq := NewReorder(100*time.Millisecond, sink.write, nil)\n2052: +\tstop := runReorder(q)\n2053: +\tinterleavedStreams(t, q, 60, 40*time.Millisecond)\n2054: +\n2055: +\t// packets go out while the capture runs, not only at the end\n2056: +\ttime.Sleep(150 * time.Millisecond)\n2057: +\tif len(sink.timestamps()) == 0 {\n2058: +\t\tt.Fatal(\"nothing written while the streams ran\")\n2059: +\t}\n2060: +\tstop()\n2061: +\n2062: +\twritten := sink.timestamps()\n2063: +\tif len(written) != 120 || !slices.IsSorted(written) {\n2064: +\t\tt.Fatalf(\"written %d packets, sorted %v\", len(written), slices.IsSorted(written))\n2065: +\t}\n2066: +\tif q.stats.late != 0 {\n2067: +\t\tt.Fatalf(\"late packets = %d\", q.stats.late)\n2068: +\t}\n2069: +}\n2070: +\n2071: +func TestReorderWritesLatePacketsAsTheyCome(t *testing.T) {\n2072: +\tt.Parallel()\n2073: +\n2074: +\tsink := &reorderSink{}\n2075: +\tq := NewReorder(20*time.Millisecond, sink.write, nil)\n2076: +\tstop := runReorder(q)\n2077: +\t// stream 1 arrives 80 ms after its stamps, far beyond the 20 ms window\n2078: +\tinterleavedStreams(t, q, 60, 80*time.Millisecond)\n2079: +\tstop()\n2080: +\n2081: +\twritten := sink.timestamps()\n2082: +\tif len(written) != 120 {\n2083: +\t\tt.Fatalf(\"written %d packets, want all 120\", len(written))\n2084: +\t}\n2085: +\tif q.stats.late == 0 || q.stats.maxLate < 40*time.Millisecond || slices.IsSorted(written) {\n2086: +\t\tt.Fatalf(\"late = %d (max %s), sorted %v; want late packets written out of order\",\n2087: +\t\t\tq.stats.late, q.stats.maxLate, slices.IsSorted(written))\n2088: +\t}\n2089: +}\n2090: +\n2091: +func TestReorderHoldsPacketsAfterAHold(t *testing.T) {\n2092: +\tt.Parallel()\n2093: +\n2094: +\tsink := &reorderSink{}\n2095: +\tq := NewReorder(time.Millisecond, sink.write, nil)\n2096: +\tstop := runReorder(q)\n2097: +\tdefer stop()\n2098: +\n2099: +\tchain := &struct{ name string }{\"chain\"}\n2100: +\tq.Hold(chain, 100)\n2101: +\tfor _, ts := range []int64{50, 150, 100, 200} {\n2102: +\t\tif err := q.Push(0, &Packet{Timestamp: ts}); err != nil {\n2103: +\t\t\tt.Fatal(err)\n2104: +\t\t}\n2105: +\t}\n2106: +\ttime.Sleep(30 * time.Millisecond)\n2107: +\tif got := sink.timestamps(); !slices.Equal(got, []int64{50, 100}) {\n2108: +\t\tt.Fatalf(\"written under the hold = %v, want [50 100]\", got)\n2109: +\t}\n2110: +\n2111: +\t// the chain writes what it held back, then releases\n2112: +\tif err := q.Push(1, &Packet{Timestamp: 120}); err != nil {\n2113: +\t\tt.Fatal(err)\n2114: +\t}\n2115: +\tq.Release(chain)\n2116: +\ttime.Sleep(30 * time.Millisecond)\n2117: +\tif got := sink.timestamps(); !slices.Equal(got, []int64{50, 100, 120, 150, 200}) {\n2118: +\t\tt.Fatalf(\"written after the release = %v\", got)\n2119: +\t}\n2120: +}\n2121: +\n2122: +func TestReorderStopsAtTheFirstWriteError(t *testing.T) {\n2123: +\tt.Parallel()\n2124: +\n2125: +\tsink := &reorderSink{failAt: 2}\n2126: +\tfailed := 0\n2127: +\tq := NewReorder(time.Millisecond, sink.write, func() { failed++ })\n2128: +\tstop := runReorder(q)\n2129: +\n2130: +\tvar err error\n2131: +\tfor ts := int64(1); ts < 50 && err == nil; ts++ {\n2132: +\t\terr = q.Push(0, &Packet{Timestamp: ts})\n2133: +\t\ttime.Sleep(2 * time.Millisecond)\n2134: +\t}\n2135: +\tstop()\n2136: +\n2137: +\tif err == nil || failed != 1 || len(sink.timestamps()) != 2 {\n2138: +\t\tt.Fatalf(\n2139: +\t\t\t\"push error = %v, onFail calls %d, written %d\",\n2140: +\t\t\terr,\n2141: +\t\t\tfailed,\n2142: +\t\t\tlen(sink.timestamps()),\n2143: +\t\t)\n2144: +\t}\n2145: +}\n2146: +\n2147: +func TestReorderWithoutWindowWritesThrough(t *testing.T) {\n2148: +\tt.Parallel()\n2149: +\n2150: +\tsink := &reorderSink{}\n2151: +\tq := NewReorder(0, sink.write, nil)\n2152: +\tfor _, ts := range []int64{30, 10, 20} {\n2153: +\t\tif err := q.Push(0, &Packet{Timestamp: ts}); err != nil {\n2154: +\t\t\tt.Fatal(err)\n2155: +\t\t}\n2156: +\t}\n2157: +\tif got := sink.timestamps(); !slices.Equal(got, []int64{30, 10, 20}) {\n2158: +\t\tt.Fatalf(\"written = %v, want arrival order\", got)\n2159: +\t}\n2160: +}\n2161: diff --git a/cmd/capture.go b/cmd/capture.go\n2162: new file mode 100644\n2163: index 0000000..20117bc\n2164: --- /dev/null\n2165: +++ b/cmd/capture.go\n2166: @@ -0,0 +1,262 @@\n2167: +package cmd\n2168: +\n2169: +import (\n2170: +\t\"encoding/json\"\n2171: +\t\"fmt\"\n2172: +\t\"io\"\n2173: +\t\"os\"\n2174: +\t\"strings\"\n2175: +\t\"time\"\n2176: +\n2177: +\t\"github.com/charmbracelet/log\"\n2178: +\ttableWriter \"github.com/jedib0t/go-pretty/v6/table\"\n2179: +\t\"github.com/jedib0t/go-pretty/v6/text\"\n2180: +\t\"github.com/spf13/cobra\"\n2181: +\tclabconstants \"github.com/srl-labs/containerlab/constants\"\n2182: +\tclabcore \"github.com/srl-labs/containerlab/core\"\n2183: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2184: +\tclabutils \"github.com/srl-labs/containerlab/utils\"\n2185: +)\n2186: +\n2187: +// CaptureOptions are the flags of the capture command.\n2188: +type CaptureOptions struct {\n2189: +\tTargets     []string\n2190: +\tDuration    time.Duration\n2191: +\tPacketLimit int\n2192: +\tSnapLength  int\n2193: +\tWrite       string\n2194: +\tList        bool\n2195: +\tFormat      string\n2196: +}\n2197: +\n2198: +func captureCmd(o *Options) (*cobra.Command, error) {\n2199: +\tc := &cobra.Command{\n2200: +\t\tUse:   \"capture\",\n2201: +\t\tShort: \"capture packets on lab link interfaces\",\n2202: +\t\tLong: \"capture packets on lab link interfaces of one or more nodes into one pcapng \" +\n2203: +\t\t\t\"stream\\nreference: https://containerlab.dev/cmd/capture/\",\n2204: +\t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n2205: +\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n2206: +\t\t\t\treturn nil\n2207: +\t\t\t}\n2208: +\n2209: +\t\t\t// Docker and Podman captures open packet sockets in the nodes' namespaces\n2210: +\t\t\treturn clabutils.CheckAndGetRootPrivs()\n2211: +\t\t},\n2212: +\t\tSilenceUsage: true,\n2213: +\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n2214: +\t\t\treturn captureFn(cmd, o)\n2215: +\t\t},\n2216: +\t}\n2217: +\n2218: +\tc.Flags().StringArrayVar(\n2219: +\t\t&o.Capture.Targets,\n2220: +\t\t\"target\",\n2221: +\t\to.Capture.Targets,\n2222: +\t\t\"node and interfaces to capture, as <node>:<interface>[,<interface>...]; repeatable\",\n2223: +\t)\n2224: +\tc.Flags().DurationVar(\n2225: +\t\t&o.Capture.Duration,\n2226: +\t\t\"duration\",\n2227: +\t\to.Capture.Duration,\n2228: +\t\t\"stop after this duration; 0 captures until interrupted\",\n2229: +\t)\n2230: +\tc.Flags().IntVar(\n2231: +\t\t&o.Capture.PacketLimit,\n2232: +\t\t\"packet-limit\",\n2233: +\t\to.Capture.PacketLimit,\n2234: +\t\t\"stop after this many packets across all targets; 0 means no limit\",\n2235: +\t)\n2236: +\tc.Flags().IntVar(\n2237: +\t\t&o.Capture.SnapLength,\n2238: +\t\t\"snap-length\",\n2239: +\t\to.Capture.SnapLength,\n2240: +\t\t\"bytes kept of each packet (64 to 1048576); 0 uses the runtime default\",\n2241: +\t)\n2242: +\tc.Flags().StringVarP(\n2243: +\t\t&o.Capture.Write,\n2244: +\t\t\"write\",\n2245: +\t\t\"w\",\n2246: +\t\to.Capture.Write,\n2247: +\t\t\"pcapng output file; - writes to stdout\",\n2248: +\t)\n2249: +\tc.Flags().BoolVar(\n2250: +\t\t&o.Capture.List,\n2251: +\t\t\"list\",\n2252: +\t\to.Capture.List,\n2253: +\t\t\"list the capturable interfaces instead of capturing\",\n2254: +\t)\n2255: +\tc.Flags().StringVarP(\n2256: +\t\t&o.Capture.Format,\n2257: +\t\t\"format\",\n2258: +\t\t\"f\",\n2259: +\t\to.Capture.Format,\n2260: +\t\t\"output format of --list: table or json\",\n2261: +\t)\n2262: +\n2263: +\tc.Example = `# Capture e1-1 of srl1 and e1-1 of srl2 for 30 seconds into one file\n2264: +containerlab capture -t srl.clab.yml --target srl1:e1-1 --target srl2:e1-1 \\\n2265: +  --duration 30s -w srl.pcapng\n2266: +\n2267: +# Capture two interfaces of one node and watch them live in Wireshark\n2268: +containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n2269: +\n2270: +# List the interfaces capture accepts\n2271: +containerlab capture --name srl --list -f json\n2272: +\n2273: +# Capture a lab running on the c9s runtime\n2274: +containerlab -r c9s capture --name srl --target srl1:e1-1 -w srl.pcapng`\n2275: +\n2276: +\treturn c, nil\n2277: +}\n2278: +\n2279: +func captureFn(cmd *cobra.Command, o *Options) error {\n2280: +\tif o.Global.TopologyName == \"\" && o.Global.TopologyFile == \"\" {\n2281: +\t\treturn fmt.Errorf(\"provide either a lab name (--name) or a topology file path (--topo)\")\n2282: +\t}\n2283: +\n2284: +\tif o.Capture.List {\n2285: +\t\treturn captureListFn(cmd, o)\n2286: +\t}\n2287: +\n2288: +\ttargets, err := parseCaptureTargets(o.Capture.Targets)\n2289: +\tif err != nil {\n2290: +\t\treturn err\n2291: +\t}\n2292: +\n2293: +\tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n2294: +\tif err != nil {\n2295: +\t\treturn err\n2296: +\t}\n2297: +\n2298: +\t// An interrupt ends the capture; the command still finishes the file and exits cleanly.\n2299: +\t// Armed before the file is created, so an interrupt never leaves it empty.\n2300: +\to.Global.FinishOnCancel.Store(true)\n2301: +\tdefer o.Global.FinishOnCancel.Store(false)\n2302: +\n2303: +\toutput := cmd.OutOrStdout()\n2304: +\tif o.Capture.Write != \"\" && o.Capture.Write != \"-\" {\n2305: +\t\tfile, err := os.Create(o.Capture.Write)\n2306: +\t\tif err != nil {\n2307: +\t\t\treturn fmt.Errorf(\"failed to create the capture file: %w\", err)\n2308: +\t\t}\n2309: +\t\tdefer file.Close()\n2310: +\t\toutput = file\n2311: +\n2312: +\t\t// the file belongs to the user who ran the command, also through sudo or setuid\n2313: +\t\tif err := clabutils.SetUIDAndGID(o.Capture.Write); err != nil {\n2314: +\t\t\tlog.Debug(\"Cannot hand the capture file to the user\", \"file\", o.Capture.Write,\n2315: +\t\t\t\t\"error\", err)\n2316: +\t\t}\n2317: +\t}\n2318: +\n2319: +\terr = c.Capture(cmd.Context(), clablabruntime.CaptureRequest{\n2320: +\t\tTargets:     targets,\n2321: +\t\tDuration:    o.Capture.Duration,\n2322: +\t\tPacketLimit: o.Capture.PacketLimit,\n2323: +\t\tSnapLength:  o.Capture.SnapLength,\n2324: +\t}, output)\n2325: +\tif err != nil {\n2326: +\t\treturn err\n2327: +\t}\n2328: +\n2329: +\tif file, ok := output.(*os.File); ok && output != cmd.OutOrStdout() {\n2330: +\t\tif err := file.Sync(); err != nil {\n2331: +\t\t\treturn fmt.Errorf(\"failed to write the capture file: %w\", err)\n2332: +\t\t}\n2333: +\t}\n2334: +\n2335: +\treturn nil\n2336: +}\n2337: +\n2338: +// parseCaptureTargets parses --target values: <node>:<interface>[,<interface>...]. The node name\n2339: +// ends at the first colon, so interface names may contain colons or slashes.\n2340: +func parseCaptureTargets(values []string) ([]clablabruntime.CaptureTarget, error) {\n2341: +\tif len(values) == 0 {\n2342: +\t\treturn nil, fmt.Errorf(\"provide at least one --target <node>:<interface>[,<interface>...]\")\n2343: +\t}\n2344: +\n2345: +\ttargets := make([]clablabruntime.CaptureTarget, 0, len(values))\n2346: +\tfor _, value := range values {\n2347: +\t\tnode, interfaces, ok := strings.Cut(strings.TrimSpace(value), \":\")\n2348: +\t\tnode = strings.TrimSpace(node)\n2349: +\t\tif !ok || node == \"\" || strings.TrimSpace(interfaces) == \"\" {\n2350: +\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: use <node>:<interface>[,<interface>...]\",\n2351: +\t\t\t\tvalue)\n2352: +\t\t}\n2353: +\n2354: +\t\tfor _, name := range strings.Split(interfaces, \",\") {\n2355: +\t\t\tname = strings.TrimSpace(name)\n2356: +\t\t\tif name == \"\" {\n2357: +\t\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: empty interface name\", value)\n2358: +\t\t\t}\n2359: +\t\t\ttargets = append(targets, clablabruntime.CaptureTarget{Node: node, Interface: name})\n2360: +\t\t}\n2361: +\t}\n2362: +\n2363: +\treturn targets, nil\n2364: +}\n2365: +\n2366: +func captureListFn(cmd *cobra.Command, o *Options) error {\n2367: +\tformat := o.Capture.Format\n2368: +\tif format == \"\" {\n2369: +\t\tformat = clabconstants.FormatTable\n2370: +\t}\n2371: +\tif format != clabconstants.FormatTable && format != clabconstants.FormatJSON {\n2372: +\t\treturn fmt.Errorf(\"output format %q is not supported, use 'table' or 'json'\", format)\n2373: +\t}\n2374: +\tif len(o.Capture.Targets) != 0 {\n2375: +\t\treturn fmt.Errorf(\"--list lists every running node's interfaces; it takes no --target\")\n2376: +\t}\n2377: +\n2378: +\tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n2379: +\tif err != nil {\n2380: +\t\treturn err\n2381: +\t}\n2382: +\n2383: +\tinterfaces, err := c.CaptureInterfaces(cmd.Context())\n2384: +\tif err != nil {\n2385: +\t\treturn err\n2386: +\t}\n2387: +\n2388: +\treturn printCaptureInterfaces(cmd.OutOrStdout(), interfaces, format)\n2389: +}\n2390: +\n2391: +func printCaptureInterfaces(\n2392: +\tw io.Writer,\n2393: +\tinterfaces []clablabruntime.CaptureInterface,\n2394: +\tformat string,\n2395: +) error {\n2396: +\tif format == clabconstants.FormatJSON {\n2397: +\t\tif interfaces == nil {\n2398: +\t\t\tinterfaces = []clablabruntime.CaptureInterface{}\n2399: +\t\t}\n2400: +\t\tdata, err := json.MarshalIndent(interfaces, \"\", \"  \")\n2401: +\t\tif err != nil {\n2402: +\t\t\treturn err\n2403: +\t\t}\n2404: +\t\t_, err = fmt.Fprintln(w, string(data))\n2405: +\n2406: +\t\treturn err\n2407: +\t}\n2408: +\n2409: +\ttable := tableWriter.NewWriter()\n2410: +\ttable.SetOutputMirror(w)\n2411: +\ttable.SetStyle(tableWriter.StyleRounded)\n2412: +\ttable.Style().Format.Header = text.FormatTitle\n2413: +\ttable.Style().Format.HeaderAlign = text.AlignCenter\n2414: +\ttable.AppendHeader(tableWriter.Row{\"Node\", \"Interface\", \"Alias\", \"Peer Node\", \"Peer Interface\"})\n2415: +\ttable.SetColumnConfigs([]tableWriter.ColumnConfig{{Number: 1, AutoMerge: true}})\n2416: +\tfor _, intf := range interfaces {\n2417: +\t\talias := intf.Alias\n2418: +\t\tif alias == \"\" {\n2419: +\t\t\talias = clabconstants.NotApplicable\n2420: +\t\t}\n2421: +\t\ttable.AppendRow(tableWriter.Row{\n2422: +\t\t\tintf.Node, intf.Interface, alias, intf.PeerNode, intf.PeerInterface,\n2423: +\t\t})\n2424: +\t}\n2425: +\ttable.Render()\n2426: +\n2427: +\treturn nil\n2428: +}\n2429: diff --git a/cmd/capture_test.go b/cmd/capture_test.go\n2430: new file mode 100644\n2431: index 0000000..da12d66\n2432: --- /dev/null\n2433: +++ b/cmd/capture_test.go\n2434: @@ -0,0 +1,109 @@\n2435: +package cmd\n2436: +\n2437: +import (\n2438: +\t\"bytes\"\n2439: +\t\"encoding/json\"\n2440: +\t\"slices\"\n2441: +\t\"strings\"\n2442: +\t\"testing\"\n2443: +\n2444: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2445: +)\n2446: +\n2447: +func TestParseCaptureTargets(t *testing.T) {\n2448: +\tt.Parallel()\n2449: +\n2450: +\ttargets, err := parseCaptureTargets([]string{\n2451: +\t\t\"srl1:e1-1,ethernet-1/2\", \" sros : 1/1/3 \", \"r1:eth1\",\n2452: +\t})\n2453: +\tif err != nil {\n2454: +\t\tt.Fatal(err)\n2455: +\t}\n2456: +\twant := []clablabruntime.CaptureTarget{\n2457: +\t\t{Node: \"srl1\", Interface: \"e1-1\"},\n2458: +\t\t{Node: \"srl1\", Interface: \"ethernet-1/2\"},\n2459: +\t\t{Node: \"sros\", Interface: \"1/1/3\"},\n2460: +\t\t{Node: \"r1\", Interface: \"eth1\"},\n2461: +\t}\n2462: +\tif !slices.Equal(targets, want) {\n2463: +\t\tt.Fatalf(\"targets = %+v, want %+v\", targets, want)\n2464: +\t}\n2465: +\n2466: +\tfor _, bad := range [][]string{nil, {\"srl1\"}, {\":e1-1\"}, {\"srl1:\"}, {\"srl1:e1-1,,e1-2\"}} {\n2467: +\t\tif _, err := parseCaptureTargets(bad); err == nil {\n2468: +\t\t\tt.Errorf(\"parseCaptureTargets(%q) succeeded\", bad)\n2469: +\t\t}\n2470: +\t}\n2471: +}\n2472: +\n2473: +func TestCaptureCommandFlags(t *testing.T) {\n2474: +\to := GetOptions()\n2475: +\tcmd, err := captureCmd(o)\n2476: +\tif err != nil {\n2477: +\t\tt.Fatal(err)\n2478: +\t}\n2479: +\tif err := cmd.ParseFlags([]string{\n2480: +\t\t\"--target\", \"srl1:e1-1\", \"--target\", \"srl2:e1-1,e1-2\", \"--duration\", \"90m\",\n2481: +\t\t\"--packet-limit\", \"100\", \"--snap-length\", \"128\", \"-w\", \"out.pcapng\",\n2482: +\t}); err != nil {\n2483: +\t\tt.Fatal(err)\n2484: +\t}\n2485: +\tif !slices.Equal(o.Capture.Targets, []string{\"srl1:e1-1\", \"srl2:e1-1,e1-2\"}) ||\n2486: +\t\to.Capture.Duration.Minutes() != 90 || o.Capture.PacketLimit != 100 ||\n2487: +\t\to.Capture.SnapLength != 128 || o.Capture.Write != \"out.pcapng\" {\n2488: +\t\tt.Fatalf(\"capture options = %+v\", o.Capture)\n2489: +\t}\n2490: +\tif def := cmd.Flag(\"write\").DefValue; def != \"-\" {\n2491: +\t\tt.Fatalf(\"--write default = %q, want stdout\", def)\n2492: +\t}\n2493: +}\n2494: +\n2495: +func TestPrintCaptureInterfaces(t *testing.T) {\n2496: +\tt.Parallel()\n2497: +\n2498: +\tinterfaces := []clablabruntime.CaptureInterface{\n2499: +\t\t{\n2500: +\t\t\tNode:          \"srl1\",\n2501: +\t\t\tInterface:     \"e1-1\",\n2502: +\t\t\tAlias:         \"ethernet-1/1\",\n2503: +\t\t\tPeerNode:      \"srl2\",\n2504: +\t\t\tPeerInterface: \"ethernet-1/1\",\n2505: +\t\t},\n2506: +\t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"srl1-e1-2\"},\n2507: +\t}\n2508: +\n2509: +\tvar out bytes.Buffer\n2510: +\tif err := printCaptureInterfaces(&out, interfaces, \"json\"); err != nil {\n2511: +\t\tt.Fatal(err)\n2512: +\t}\n2513: +\tvar decoded []map[string]any\n2514: +\tif err := json.Unmarshal(out.Bytes(), &decoded); err != nil {\n2515: +\t\tt.Fatal(err)\n2516: +\t}\n2517: +\tif decoded[0][\"peer_node\"] != \"srl2\" || decoded[0][\"alias\"] != \"ethernet-1/1\" {\n2518: +\t\tt.Fatalf(\"json = %s\", out.String())\n2519: +\t}\n2520: +\tif _, hasAlias := decoded[1][\"alias\"]; hasAlias {\n2521: +\t\tt.Fatalf(\"an empty alias is printed: %s\", out.String())\n2522: +\t}\n2523: +\n2524: +\tout.Reset()\n2525: +\tif err := printCaptureInterfaces(\n2526: +\t\t&out,\n2527: +\t\tnil,\n2528: +\t\t\"json\",\n2529: +\t); err != nil ||\n2530: +\t\tstrings.TrimSpace(out.String()) != \"[]\" {\n2531: +\t\tt.Fatalf(\"empty json = %q, %v\", out.String(), err)\n2532: +\t}\n2533: +\n2534: +\tout.Reset()\n2535: +\tif err := printCaptureInterfaces(&out, interfaces, \"table\"); err != nil {\n2536: +\t\tt.Fatal(err)\n2537: +\t}\n2538: +\tfor _, want := range []string{\"Peer Interface\", \"ethernet-1/1\", \"srl1-e1-2\", \"N/A\"} {\n2539: +\t\tif !strings.Contains(out.String(), want) {\n2540: +\t\t\tt.Fatalf(\"table does not contain %q:\\n%s\", want, out.String())\n2541: +\t\t}\n2542: +\t}\n2543: +}\n2544: diff --git a/cmd/context.go b/cmd/context.go\n2545: index 223cb1d..21d5bea 100644\n2546: --- a/cmd/context.go\n2547: +++ b/cmd/context.go\n2548: @@ -51,10 +51,20 @@ func SignalHandledContext() (context.Context, context.CancelFunc) {\n2549:  \n2550:  \t\tcancel()\n2551:  \n2552:  \t\toptions := GetOptions()\n2553:  \n2554: +\t\tif options.Global.FinishOnCancel.Load() {\n2555: +\t\t\tlog.Info(\"Stopping, press Ctrl+C again to abort\")\n2556: +\n2557: +\t\t\tsig = <-sigs\n2558: +\n2559: +\t\t\tlog.Errorf(\"received signal %q while stopping, exiting\", sig)\n2560: +\n2561: +\t\t\tos.Exit(1)\n2562: +\t\t}\n2563: +\n2564:  \t\tif !options.Global.CleanOnCancel.Load() {\n2565:  \t\t\tlog.Debug(\"clean on cancel is not true, exiting\")\n2566:  \n2567:  \t\t\tos.Exit(1)\n2568:  \t\t}\n2569: diff --git a/cmd/inspect.go b/cmd/inspect.go\n2570: index 1b6f41d..55fb61f 100644\n2571: --- a/cmd/inspect.go\n2572: +++ b/cmd/inspect.go\n2573: @@ -70,10 +70,14 @@ func inspectCmd(o *Options) (*cobra.Command, error) {\n2574:  \t\tShort: \"inspect interfaces of one or multiple nodes in a lab\",\n2575:  \t\tLong: \"show interfaces and their attributes in a specific deployed lab\\n\" +\n2576:  \t\t\t\"reference: https://containerlab.dev/cmd/inspect/interfaces/\",\n2577:  \t\tAliases: []string{\"int\", \"intf\"},\n2578:  \t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n2579: +\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n2580: +\t\t\t\treturn nil\n2581: +\t\t\t}\n2582: +\n2583:  \t\t\treturn clabutils.CheckAndGetRootPrivs()\n2584:  \t\t},\n2585:  \t\tRunE: func(cobraCmd *cobra.Command, _ []string) error {\n2586:  \t\t\treturn inspectInterfacesFn(cobraCmd, o)\n2587:  \t\t},\n2588: diff --git a/cmd/inspect_interfaces.go b/cmd/inspect_interfaces.go\n2589: index 0f64f03..91035c2 100644\n2590: --- a/cmd/inspect_interfaces.go\n2591: +++ b/cmd/inspect_interfaces.go\n2592: @@ -33,10 +33,25 @@ func inspectInterfacesFn(cobraCmd *cobra.Command, o *Options) error {\n2593:  \tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n2594:  \tif err != nil {\n2595:  \t\treturn fmt.Errorf(\"could not parse the topology file: %v\", err)\n2596:  \t}\n2597:  \n2598: +\tif c.LabRuntime != nil {\n2599: +\t\t// lab runtimes list the link interfaces packet capture accepts, with their state\n2600: +\t\tcontainerInterfaces, err := c.LabRuntimeInterfaces(cobraCmd.Context(),\n2601: +\t\t\to.Inspect.InterfacesNode)\n2602: +\t\tif err != nil {\n2603: +\t\t\treturn fmt.Errorf(\"failed to list node interfaces: %w\", err)\n2604: +\t\t}\n2605: +\t\tif len(containerInterfaces) == 0 {\n2606: +\t\t\tlog.Info(\"no running nodes found\")\n2607: +\t\t\treturn nil\n2608: +\t\t}\n2609: +\n2610: +\t\treturn printContainerInterfaces(containerInterfaces, o.Inspect.InterfacesFormat)\n2611: +\t}\n2612: +\n2613:  \tvar labNameFilterLabel string\n2614:  \n2615:  \tswitch {\n2616:  \tcase o.Global.TopologyName != \"\":\n2617:  \t\tlabNameFilterLabel = o.Global.TopologyName\n2618: diff --git a/cmd/options.go b/cmd/options.go\n2619: index 8717d3b..6037551 100644\n2620: --- a/cmd/options.go\n2621: +++ b/cmd/options.go\n2622: @@ -53,10 +53,14 @@ func GetOptions() *Options {\n2623:  \t\t\t\tInterfacesFormat: \"table\",\n2624:  \t\t\t},\n2625:  \t\t\tLogs: &LogsOptions{\n2626:  \t\t\t\tTail: -1,\n2627:  \t\t\t},\n2628: +\t\t\tCapture: &CaptureOptions{\n2629: +\t\t\t\tWrite:  \"-\",\n2630: +\t\t\t\tFormat: \"table\",\n2631: +\t\t\t},\n2632:  \t\t\tGraph: &GraphOptions{\n2633:  \t\t\t\tServer:           \"0.0.0.0:50080\",\n2634:  \t\t\t\tMermaidDirection: \"TD\",\n2635:  \t\t\t\tDrawIOVersion:    \"latest\",\n2636:  \t\t\t},\n2637: @@ -142,10 +146,11 @@ type Options struct {\n2638:  \tExec           *ExecOptions\n2639:  \tInspect        *InspectOptions\n2640:  \tGraph          *GraphOptions\n2641:  \tEvents         *EventsOptions\n2642:  \tLogs           *LogsOptions\n2643: +\tCapture        *CaptureOptions\n2644:  \tToolsAPI       *ToolsApiOptions\n2645:  \tToolsCert      *ToolsCertOptions\n2646:  \tToolsTxOffload *ToolsDisableTxOffloadOptions\n2647:  \tToolsGoTTY     *ToolsGoTTYOptions\n2648:  \tToolsNetem     *ToolsNetemOptions\n2649: @@ -257,10 +262,15 @@ type GlobalOptions struct {\n2650:  \t// special flag that should only be set by deploy, informs the context handler to destroy\n2651:  \t// (or not) when root context is canceled. The signal handler goroutine reads it while\n2652:  \t// deploy is running, so it is atomic.\n2653:  \tCleanOnCancel atomic.Bool\n2654:  \n2655: +\t// FinishOnCancel informs the context handler that the running command ends cleanly on its\n2656: +\t// own once the root context is canceled (capture finishes its output), so the handler\n2657: +\t// waits for it instead of exiting.\n2658: +\tFinishOnCancel atomic.Bool\n2659: +\n2660:  \t// special flag that is only set on deploy,\n2661:  \t// if true, the topology file backup is created at /tmp/.clab/bak\n2662:  \tBackupTopologyFile bool\n2663:  }\n2664:  \n2665: diff --git a/cmd/root.go b/cmd/root.go\n2666: index 0baf203..a9b1c8b 100644\n2667: --- a/cmd/root.go\n2668: +++ b/cmd/root.go\n2669: @@ -35,10 +35,11 @@ func subcommandRegisterFuncs() []func(*Options) (*cobra.Command, error) {\n2670:  \t\tgenerateCmd,\n2671:  \t\tgraphCmd,\n2672:  \t\teventsCmd,\n2673:  \t\tinspectCmd,\n2674:  \t\tlogsCmd,\n2675: +\t\tcaptureCmd,\n2676:  \t\tredeployCmd,\n2677:  \t\tsaveCmd,\n2678:  \t\ttoolsCmd,\n2679:  \t\tvalidateCmd,\n2680:  \t}\n2681: @@ -263,15 +264,10 @@ func checkLabRuntimeCommandSupport(cobraCmd *cobra.Command, runtimeName string)\n2682:  \t\t\t\"the %q command needs running containers with lab runtime %q unless it renders \"+\n2683:  \t\t\t\t\"from the topology file alone; use --offline, --dot, --mermaid or --drawio\",\n2684:  \t\t\t\"graph\", runtimeName)\n2685:  \t}\n2686:  \n2687: -\tif getCommandPath(cobraCmd) == \"inspect.interfaces\" {\n2688: -\t\treturn fmt.Errorf(\"the %q command is not supported with lab runtime %q\",\n2689: -\t\t\t\"inspect interfaces\", runtimeName)\n2690: -\t}\n2691: -\n2692:  \tvar unsupported []string\n2693:  \tfor _, flagName := range labRuntimeUnsupportedFlags[getCommandPath(cobraCmd)] {\n2694:  \t\tif labRuntimeFlagWasSet(cobraCmd, flagName) {\n2695:  \t\t\tunsupported = append(unsupported, \"--\"+flagName)\n2696:  \t\t}\n2697: @@ -339,10 +335,11 @@ func getTopoFilePath(cobraCmd *cobra.Command, o *Options) error { // skipcq: GO-\n2698:  \t\tcobraCmd.Name() != \"inspect\" &&\n2699:  \t\tcobraCmd.Name() != \"save\" &&\n2700:  \t\tcobraCmd.Name() != \"graph\" &&\n2701:  \t\tcobraCmd.Name() != \"validate\" &&\n2702:  \t\tcobraCmd.Name() != \"logs\" &&\n2703: +\t\tcobraCmd.Name() != \"capture\" &&\n2704:  \t\tcobraCmd.Name() != \"interfaces\" {\n2705:  \t\treturn nil\n2706:  \t}\n2707:  \n2708:  \t// start/stop/restart topology lookup applies only to top-level lifecycle commands.\n2709: diff --git a/cmd/root_test.go b/cmd/root_test.go\n2710: index 418a947..af02e34 100644\n2711: --- a/cmd/root_test.go\n2712: +++ b/cmd/root_test.go\n2713: @@ -289,20 +289,23 @@ func TestCheckLabRuntimeFlagAndNestedCommandSupport(t *testing.T) {\n2714:  \t\t\t\tt.Fatalf(\"checkLabRuntimeCommandSupport() error = %v, wantErr %v\", err, tt.wantErr)\n2715:  \t\t\t}\n2716:  \t\t})\n2717:  \t}\n2718:  \n2719: -\tt.Run(\"inspect interfaces rejected\", func(t *testing.T) {\n2720: +\tt.Run(\"inspect interfaces and capture accepted\", func(t *testing.T) {\n2721:  \t\troot := &cobra.Command{Use: \"containerlab\"}\n2722:  \t\tinspect := &cobra.Command{Use: \"inspect\"}\n2723:  \t\tinterfaces := &cobra.Command{Use: \"interfaces\"}\n2724: -\t\troot.AddCommand(inspect)\n2725: +\t\tcapture := &cobra.Command{Use: \"capture\"}\n2726: +\t\troot.AddCommand(inspect, capture)\n2727:  \t\tinspect.AddCommand(interfaces)\n2728:  \n2729: -\t\tif err := checkLabRuntimeCommandSupport(\n2730: -\t\t\tinterfaces,\n2731: -\t\t\tclablabruntime.ClabernetesRuntimeName,\n2732: -\t\t); err == nil {\n2733: -\t\t\tt.Fatal(\"inspect interfaces was accepted for clabernetes\")\n2734: +\t\tfor _, cmd := range []*cobra.Command{interfaces, capture} {\n2735: +\t\t\tif err := checkLabRuntimeCommandSupport(\n2736: +\t\t\t\tcmd,\n2737: +\t\t\t\tclablabruntime.ClabernetesRuntimeName,\n2738: +\t\t\t); err != nil {\n2739: +\t\t\t\tt.Fatalf(\"%s rejected for clabernetes: %v\", cmd.Name(), err)\n2740: +\t\t\t}\n2741:  \t\t}\n2742:  \t})\n2743:  }\n2744: diff --git a/core/capture.go b/core/capture.go\n2745: new file mode 100644\n2746: index 0000000..2e12fc2\n2747: --- /dev/null\n2748: +++ b/core/capture.go\n2749: @@ -0,0 +1,93 @@\n2750: +package core\n2751: +\n2752: +import (\n2753: +\t\"context\"\n2754: +\t\"io\"\n2755: +\n2756: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2757: +\tclabtypes \"github.com/srl-labs/containerlab/types\"\n2758: +)\n2759: +\n2760: +// CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for\n2761: +// every running node, with the peer at the other end of each link. With Docker and Podman, the\n2762: +// interfaces come from the topology's links; lab runtimes list them through their packet\n2763: +// capturer.\n2764: +func (c *CLab) CaptureInterfaces(\n2765: +\tctx context.Context,\n2766: +\tnodeNames ...string,\n2767: +) ([]clablabruntime.CaptureInterface, error) {\n2768: +\tif c.LabRuntime == nil {\n2769: +\t\treturn c.localCaptureInterfacesOf(ctx, nodeNames)\n2770: +\t}\n2771: +\n2772: +\tcapturer, err := c.packetCapturer()\n2773: +\tif err != nil {\n2774: +\t\treturn nil, err\n2775: +\t}\n2776: +\n2777: +\treturn capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{\n2778: +\t\tName:     c.Config.Name,\n2779: +\t\tNodes:    nodeNames,\n2780: +\t\tIdentity: c.labRuntimeIdentity,\n2781: +\t})\n2782: +}\n2783: +\n2784: +// Capture streams pcapng from lab link interfaces to w until req.Duration passed,\n2785: +// req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name\n2786: +// and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces\n2787: +// itself through packet sockets in the nodes' network namespaces, which needs root; lab\n2788: +// runtimes capture through their packet capturer.\n2789: +func (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {\n2790: +\tif c.LabRuntime == nil {\n2791: +\t\treturn c.captureLocal(ctx, req, w)\n2792: +\t}\n2793: +\n2794: +\tcapturer, err := c.packetCapturer()\n2795: +\tif err != nil {\n2796: +\t\treturn err\n2797: +\t}\n2798: +\n2799: +\tif req.Name == \"\" {\n2800: +\t\treq.Name = c.Config.Name\n2801: +\t}\n2802: +\tif req.Identity.IsZero() {\n2803: +\t\treq.Identity = c.labRuntimeIdentity\n2804: +\t}\n2805: +\n2806: +\treturn capturer.Capture(ctx, req, w)\n2807: +}\n2808: +\n2809: +// LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their\n2810: +// state, in the shape ListContainersInterfaces reports for local containers.\n2811: +func (c *CLab) LabRuntimeInterfaces(\n2812: +\tctx context.Context,\n2813: +\tnodeName string,\n2814: +) ([]*clabtypes.ContainerInterfaces, error) {\n2815: +\tinspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](\n2816: +\t\tc, \"inspecting interfaces\")\n2817: +\tif err != nil {\n2818: +\t\treturn nil, err\n2819: +\t}\n2820: +\tif err := c.requireLabName(); err != nil {\n2821: +\t\treturn nil, err\n2822: +\t}\n2823: +\n2824: +\treq := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}\n2825: +\tif nodeName != \"\" {\n2826: +\t\treq.Nodes = []string{nodeName}\n2827: +\t}\n2828: +\n2829: +\treturn inspector.InspectInterfaces(ctx, req)\n2830: +}\n2831: +\n2832: +func (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {\n2833: +\tcapturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, \"packet capture\")\n2834: +\tif err != nil {\n2835: +\t\treturn nil, err\n2836: +\t}\n2837: +\tif err := c.requireLabName(); err != nil {\n2838: +\t\treturn nil, err\n2839: +\t}\n2840: +\n2841: +\treturn capturer, nil\n2842: +}\n2843: diff --git a/core/capture_local.go b/core/capture_local.go\n2844: new file mode 100644\n2845: index 0000000..fada0bf\n2846: --- /dev/null\n2847: +++ b/core/capture_local.go\n2848: @@ -0,0 +1,255 @@\n2849: +package core\n2850: +\n2851: +import (\n2852: +\t\"context\"\n2853: +\t\"fmt\"\n2854: +\t\"io\"\n2855: +\t\"slices\"\n2856: +\t\"sort\"\n2857: +\t\"strings\"\n2858: +\n2859: +\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n2860: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2861: +\tclablinks \"github.com/srl-labs/containerlab/links\"\n2862: +\tclabnodes \"github.com/srl-labs/containerlab/nodes\"\n2863: +\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n2864: +)\n2865: +\n2866: +// localCaptureInterface is a lab link interface of a node on this machine.\n2867: +type localCaptureInterface struct {\n2868: +\tnode clabnodes.Node\n2869: +\tinfo clablabruntime.CaptureInterface\n2870: +}\n2871: +\n2872: +// localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with\n2873: +// the far end of each link, per node name. Host and management network endpoints are the far\n2874: +// ends of links, not nodes to capture on.\n2875: +func (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {\n2876: +\tif len(c.Nodes) == 0 {\n2877: +\t\treturn nil, fmt.Errorf(\"the topology of lab %q is not available; capture reads the \"+\n2878: +\t\t\t\"lab's links from it, pass it with --topo\", c.Config.Name)\n2879: +\t}\n2880: +\tif len(c.Links) == 0 {\n2881: +\t\tif err := c.ResolveLinks(); err != nil {\n2882: +\t\t\treturn nil, fmt.Errorf(\"failed to resolve the links of lab %q: %w\", c.Config.Name, err)\n2883: +\t\t}\n2884: +\t}\n2885: +\n2886: +\tindexes := make([]int, 0, len(c.Links))\n2887: +\tfor idx := range c.Links {\n2888: +\t\tindexes = append(indexes, idx)\n2889: +\t}\n2890: +\tsort.Ints(indexes)\n2891: +\n2892: +\tresult := map[string][]localCaptureInterface{}\n2893: +\tfor _, idx := range indexes {\n2894: +\t\tendpoints := c.Links[idx].GetEndpoints()\n2895: +\t\tfor epIdx, endpoint := range endpoints {\n2896: +\t\t\tif endpoint.IsNodeless() || endpoint.IsRuntimeDiscovered() ||\n2897: +\t\t\t\tendpoint.GetNode() == nil {\n2898: +\t\t\t\tcontinue\n2899: +\t\t\t}\n2900: +\t\t\tname := endpoint.GetNode().GetShortName()\n2901: +\t\t\tnode, ok := c.Nodes[name]\n2902: +\t\t\tif !ok {\n2903: +\t\t\t\tcontinue\n2904: +\t\t\t}\n2905: +\n2906: +\t\t\tinfo := clablabruntime.CaptureInterface{\n2907: +\t\t\t\tNode:      name,\n2908: +\t\t\t\tInterface: endpoint.GetIfaceName(),\n2909: +\t\t\t}\n2910: +\t\t\tif alias := endpoint.GetIfaceAlias(); alias != info.Interface {\n2911: +\t\t\t\tinfo.Alias = alias\n2912: +\t\t\t}\n2913: +\t\t\tif len(endpoints) == 2 {\n2914: +\t\t\t\tpeer := endpoints[1-epIdx]\n2915: +\t\t\t\tinfo.PeerNode = capturePeerNode(peer)\n2916: +\t\t\t\tinfo.PeerInterface = peer.GetIfaceDisplayName()\n2917: +\t\t\t}\n2918: +\n2919: +\t\t\tresult[name] = append(result[name], localCaptureInterface{node: node, info: info})\n2920: +\t\t}\n2921: +\t}\n2922: +\n2923: +\treturn result, nil\n2924: +}\n2925: +\n2926: +// capturePeerNode names the node at the far end of a link: \"host\" for a host endpoint and\n2927: +// \"mgmt-net\" for the management network, whose shared link nodes carry other names once a lab\n2928: +// was deployed.\n2929: +func capturePeerNode(peer clablinks.Endpoint) string {\n2930: +\tif peer.IsNodeless() {\n2931: +\t\tif _, ok := peer.(*clablinks.EndpointBridge); ok {\n2932: +\t\t\treturn string(clablinks.LinkTypeMgmtNet)\n2933: +\t\t}\n2934: +\n2935: +\t\treturn string(clablinks.LinkTypeHost)\n2936: +\t}\n2937: +\tif peer.GetNode() == nil {\n2938: +\t\treturn \"\"\n2939: +\t}\n2940: +\n2941: +\treturn peer.GetNode().GetShortName()\n2942: +}\n2943: +\n2944: +// lookupLocalNode finds a lab node by its topology name or its container name.\n2945: +func (c *CLab) lookupLocalNode(name string) (clabnodes.Node, error) {\n2946: +\tif node, ok := c.Nodes[name]; ok {\n2947: +\t\treturn node, nil\n2948: +\t}\n2949: +\tfor _, node := range c.Nodes {\n2950: +\t\tif node.Config().LongName == name {\n2951: +\t\t\treturn node, nil\n2952: +\t\t}\n2953: +\t}\n2954: +\n2955: +\tnames := make([]string, 0, len(c.Nodes))\n2956: +\tfor nodeName := range c.Nodes {\n2957: +\t\tnames = append(names, nodeName)\n2958: +\t}\n2959: +\tslices.Sort(names)\n2960: +\n2961: +\treturn nil, fmt.Errorf(\"node %q is not part of lab %q; nodes: %s\", name, c.Config.Name,\n2962: +\t\tstrings.Join(names, \", \"))\n2963: +}\n2964: +\n2965: +// nodeRuns reports whether a node's network namespace can be entered.\n2966: +func nodeRuns(ctx context.Context, node clabnodes.Node) bool {\n2967: +\tif node.Config().IsRootNamespaceBased {\n2968: +\t\treturn true\n2969: +\t}\n2970: +\n2971: +\treturn clabruntime.ContainerHasJoinableNetns(node.GetContainerStatus(ctx))\n2972: +}\n2973: +\n2974: +// localCaptureInterfacesOf implements CaptureInterfaces for Docker and Podman: the requested\n2975: +// nodes, or every running node.\n2976: +func (c *CLab) localCaptureInterfacesOf(\n2977: +\tctx context.Context,\n2978: +\tnodeNames []string,\n2979: +) ([]clablabruntime.CaptureInterface, error) {\n2980: +\tif err := c.requireLabName(); err != nil {\n2981: +\t\treturn nil, err\n2982: +\t}\n2983: +\tbyNode, err := c.localCaptureInterfaces()\n2984: +\tif err != nil {\n2985: +\t\treturn nil, err\n2986: +\t}\n2987: +\n2988: +\tvar nodes []clabnodes.Node\n2989: +\tif len(nodeNames) == 0 {\n2990: +\t\tfor _, node := range c.Nodes {\n2991: +\t\t\tif nodeRuns(ctx, node) {\n2992: +\t\t\t\tnodes = append(nodes, node)\n2993: +\t\t\t}\n2994: +\t\t}\n2995: +\t} else {\n2996: +\t\tfor _, name := range nodeNames {\n2997: +\t\t\tnode, err := c.lookupLocalNode(name)\n2998: +\t\t\tif err != nil {\n2999: +\t\t\t\treturn nil, err\n3000: +\t\t\t}\n3001: +\t\t\tnodes = append(nodes, node)\n3002: +\t\t}\n3003: +\t}\n3004: +\n3005: +\tresult := make([]clablabruntime.CaptureInterface, 0)\n3006: +\tseen := map[string]bool{}\n3007: +\tfor _, node := range nodes {\n3008: +\t\tname := node.Config().ShortName\n3009: +\t\tif seen[name] {\n3010: +\t\t\tcontinue\n3011: +\t\t}\n3012: +\t\tseen[name] = true\n3013: +\t\tfor _, entry := range byNode[name] {\n3014: +\t\t\tresult = append(result, entry.info)\n3015: +\t\t}\n3016: +\t}\n3017: +\tsortCaptureInterfaces(result)\n3018: +\n3019: +\treturn result, nil\n3020: +}\n3021: +\n3022: +func sortCaptureInterfaces(interfaces []clablabruntime.CaptureInterface) {\n3023: +\tsort.SliceStable(interfaces, func(i, j int) bool {\n3024: +\t\tif interfaces[i].Node != interfaces[j].Node {\n3025: +\t\t\treturn interfaces[i].Node < interfaces[j].Node\n3026: +\t\t}\n3027: +\n3028: +\t\treturn interfaces[i].Interface < interfaces[j].Interface\n3029: +\t})\n3030: +}\n3031: +\n3032: +// resolveLocalCaptureTargets checks every target against the node's link interfaces, by name or\n3033: +// alias, and returns them in request order.\n3034: +func (c *CLab) resolveLocalCaptureTargets(\n3035: +\ttargets []clablabruntime.CaptureTarget,\n3036: +) ([]clabcapture.LocalTarget, error) {\n3037: +\tbyNode, err := c.localCaptureInterfaces()\n3038: +\tif err != nil {\n3039: +\t\treturn nil, err\n3040: +\t}\n3041: +\n3042: +\tresolved := make([]clabcapture.LocalTarget, 0, len(targets))\n3043: +\tseen := map[string]bool{}\n3044: +\tfor _, target := range targets {\n3045: +\t\tnode, err := c.lookupLocalNode(target.Node)\n3046: +\t\tif err != nil {\n3047: +\t\t\treturn nil, err\n3048: +\t\t}\n3049: +\t\tname := node.Config().ShortName\n3050: +\n3051: +\t\tinfos := make([]clablabruntime.CaptureInterface, 0, len(byNode[name]))\n3052: +\t\tfor _, entry := range byNode[name] {\n3053: +\t\t\tinfos = append(infos, entry.info)\n3054: +\t\t}\n3055: +\t\tsortCaptureInterfaces(infos)\n3056: +\t\tinfo, ok := clabcapture.FindInterface(infos, target.Interface)\n3057: +\t\tif !ok {\n3058: +\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n3059: +\t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n3060: +\t\t\t\tclabcapture.DescribeInterfaces(infos))\n3061: +\t\t}\n3062: +\n3063: +\t\tkey := name + \"\\x00\" + info.Interface\n3064: +\t\tif seen[key] {\n3065: +\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n3066: +\t\t\t\tinfo.Interface, target.Node)\n3067: +\t\t}\n3068: +\t\tseen[key] = true\n3069: +\n3070: +\t\tresolved = append(resolved, clabcapture.LocalTarget{\n3071: +\t\t\tNode:      name,\n3072: +\t\t\tInterface: info.Interface,\n3073: +\t\t\tExec:      node.ExecFunction,\n3074: +\t\t})\n3075: +\t}\n3076: +\n3077: +\treturn resolved, nil\n3078: +}\n3079: +\n3080: +// captureLocal implements Capture for Docker and Podman through packet sockets in the nodes'\n3081: +// network namespaces.\n3082: +func (c *CLab) captureLocal(\n3083: +\tctx context.Context,\n3084: +\treq clablabruntime.CaptureRequest,\n3085: +\tw io.Writer,\n3086: +) error {\n3087: +\tif err := c.requireLabName(); err != nil {\n3088: +\t\treturn err\n3089: +\t}\n3090: +\tif req.Name == \"\" {\n3091: +\t\treq.Name = c.Config.Name\n3092: +\t}\n3093: +\tif err := clabcapture.ValidateRequest(&req); err != nil {\n3094: +\t\treturn err\n3095: +\t}\n3096: +\n3097: +\ttargets, err := c.resolveLocalCaptureTargets(req.Targets)\n3098: +\tif err != nil {\n3099: +\t\treturn err\n3100: +\t}\n3101: +\n3102: +\treturn clabcapture.CaptureLocal(ctx, req, targets, w)\n3103: +}\n3104: diff --git a/core/capture_test.go b/core/capture_test.go\n3105: new file mode 100644\n3106: index 0000000..b5d34b0\n3107: --- /dev/null\n3108: +++ b/core/capture_test.go\n3109: @@ -0,0 +1,210 @@\n3110: +package core\n3111: +\n3112: +import (\n3113: +\t\"bytes\"\n3114: +\t\"context\"\n3115: +\t\"io\"\n3116: +\t\"slices\"\n3117: +\t\"strings\"\n3118: +\t\"testing\"\n3119: +\n3120: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n3121: +\tclabtypes \"github.com/srl-labs/containerlab/types\"\n3122: +)\n3123: +\n3124: +// captureLabRuntime records the capture requests core sends.\n3125: +type captureLabRuntime struct {\n3126: +\tclablabruntime.LabRuntime\n3127: +\n3128: +\tnodeRequest    clablabruntime.NodeRequest\n3129: +\tcaptureRequest clablabruntime.CaptureRequest\n3130: +}\n3131: +\n3132: +func (r *captureLabRuntime) CaptureInterfaces(\n3133: +\t_ context.Context,\n3134: +\treq clablabruntime.NodeRequest,\n3135: +) ([]clablabruntime.CaptureInterface, error) {\n3136: +\tr.nodeRequest = req\n3137: +\n3138: +\treturn []clablabruntime.CaptureInterface{{Node: \"r1\", Interface: \"eth1\"}}, nil\n3139: +}\n3140: +\n3141: +func (r *captureLabRuntime) Capture(\n3142: +\t_ context.Context,\n3143: +\treq clablabruntime.CaptureRequest,\n3144: +\tw io.Writer,\n3145: +) error {\n3146: +\tr.captureRequest = req\n3147: +\t_, err := io.WriteString(w, \"pcapng\")\n3148: +\n3149: +\treturn err\n3150: +}\n3151: +\n3152: +func (r *captureLabRuntime) InspectInterfaces(\n3153: +\t_ context.Context,\n3154: +\treq clablabruntime.NodeRequest,\n3155: +) ([]*clabtypes.ContainerInterfaces, error) {\n3156: +\tr.nodeRequest = req\n3157: +\n3158: +\treturn []*clabtypes.ContainerInterfaces{{ContainerName: \"lab1-r1\"}}, nil\n3159: +}\n3160: +\n3161: +func TestCaptureHelpersFillLabAndIdentity(t *testing.T) {\n3162: +\tt.Parallel()\n3163: +\n3164: +\tlr := &captureLabRuntime{}\n3165: +\tc := newAccessTestCLab(lr)\n3166: +\tctx := context.Background()\n3167: +\n3168: +\tinterfaces, err := c.CaptureInterfaces(ctx, \"R1\")\n3169: +\tif err != nil || len(interfaces) != 1 {\n3170: +\t\tt.Fatalf(\"CaptureInterfaces() = %+v, %v\", interfaces, err)\n3171: +\t}\n3172: +\tif lr.nodeRequest.Name != \"lab1\" || lr.nodeRequest.Nodes[0] != \"R1\" ||\n3173: +\t\t!lr.nodeRequest.Identity.Equal(testIdentity) {\n3174: +\t\tt.Fatalf(\"interfaces request = %+v\", lr.nodeRequest)\n3175: +\t}\n3176: +\n3177: +\tvar out bytes.Buffer\n3178: +\tif err := c.Capture(ctx, clablabruntime.CaptureRequest{\n3179: +\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n3180: +\t}, &out); err != nil {\n3181: +\t\tt.Fatal(err)\n3182: +\t}\n3183: +\tif out.String() != \"pcapng\" || lr.captureRequest.Name != \"lab1\" ||\n3184: +\t\t!lr.captureRequest.Identity.Equal(testIdentity) {\n3185: +\t\tt.Fatalf(\"capture request = %+v, output %q\", lr.captureRequest, out.String())\n3186: +\t}\n3187: +\n3188: +\tifaces, err := c.LabRuntimeInterfaces(ctx, \"r1\")\n3189: +\tif err != nil || len(ifaces) != 1 || lr.nodeRequest.Nodes[0] != \"r1\" {\n3190: +\t\tt.Fatalf(\"LabRuntimeInterfaces() = %+v, %v, request %+v\", ifaces, err, lr.nodeRequest)\n3191: +\t}\n3192: +\tif _, err := c.LabRuntimeInterfaces(ctx, \"\"); err != nil || lr.nodeRequest.Nodes != nil {\n3193: +\t\tt.Fatalf(\"all nodes request = %+v, %v\", lr.nodeRequest, err)\n3194: +\t}\n3195: +}\n3196: +\n3197: +// newLocalCaptureCLab loads the capture test topology. Its host and mgmt-net links register\n3198: +// endpoints on link nodes the whole process shares, so the tests using it do not run in\n3199: +// parallel and release the endpoints when they end.\n3200: +func newLocalCaptureCLab(t *testing.T) *CLab {\n3201: +\tt.Helper()\n3202: +\n3203: +\tc, err := NewContainerLab(WithTopoPath(\"test_data/capture.clab.yml\", nil))\n3204: +\tif err != nil {\n3205: +\t\tt.Fatal(err)\n3206: +\t}\n3207: +\tt.Cleanup(c.resetResolvedLinks)\n3208: +\n3209: +\treturn c\n3210: +}\n3211: +\n3212: +func TestLocalCaptureInterfacesComeFromTheTopologyLinks(t *testing.T) {\n3213: +\tc := newLocalCaptureCLab(t)\n3214: +\n3215: +\tgot, err := c.CaptureInterfaces(context.Background(), \"srl1\", \"client\")\n3216: +\tif err != nil {\n3217: +\t\tt.Fatal(err)\n3218: +\t}\n3219: +\twant := []clablabruntime.CaptureInterface{\n3220: +\t\t{Node: \"client\", Interface: \"eth1\", PeerNode: \"srl1\", PeerInterface: \"e1-2\"},\n3221: +\t\t{Node: \"client\", Interface: \"eth2\", PeerNode: \"host\", PeerInterface: \"client-eth2\"},\n3222: +\t\t{Node: \"client\", Interface: \"eth3\", PeerNode: \"mgmt-net\", PeerInterface: \"client-eth3\"},\n3223: +\t\t{\n3224: +\t\t\tNode: \"srl1\", Interface: \"e1-1\", Alias: \"ethernet-1/1\",\n3225: +\t\t\tPeerNode: \"srl2\", PeerInterface: \"e1-1\",\n3226: +\t\t},\n3227: +\t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"client\", PeerInterface: \"eth1\"},\n3228: +\t}\n3229: +\tif !slices.Equal(got, want) {\n3230: +\t\tt.Fatalf(\"CaptureInterfaces() =\\n%+v\\nwant\\n%+v\", got, want)\n3231: +\t}\n3232: +\n3233: +\tif _, err := c.CaptureInterfaces(context.Background(), \"r9\"); err == nil ||\n3234: +\t\t!strings.Contains(err.Error(), `node \"r9\" is not part of lab \"capture\"`) {\n3235: +\t\tt.Fatalf(\"unknown node: error = %v\", err)\n3236: +\t}\n3237: +}\n3238: +\n3239: +func TestLocalCaptureTargetsResolveByNameOrAlias(t *testing.T) {\n3240: +\tc := newLocalCaptureCLab(t)\n3241: +\n3242: +\ttargets, err := c.resolveLocalCaptureTargets([]clablabruntime.CaptureTarget{\n3243: +\t\t{Node: \"srl2\", Interface: \"e1-1\"},\n3244: +\t\t{Node: \"srl1\", Interface: \"ethernet-1/1\"},\n3245: +\t\t{Node: \"clab-capture-client\", Interface: \"eth2\"},\n3246: +\t})\n3247: +\tif err != nil {\n3248: +\t\tt.Fatal(err)\n3249: +\t}\n3250: +\tvar got []string\n3251: +\tfor _, target := range targets {\n3252: +\t\tif target.Exec == nil {\n3253: +\t\t\tt.Fatalf(\"target %s:%s has no namespace exec\", target.Node, target.Interface)\n3254: +\t\t}\n3255: +\t\tgot = append(got, target.Node+\":\"+target.Interface)\n3256: +\t}\n3257: +\tif want := []string{\"srl2:e1-1\", \"srl1:e1-1\", \"client:eth2\"}; !slices.Equal(got, want) {\n3258: +\t\tt.Fatalf(\"targets = %v, want %v\", got, want)\n3259: +\t}\n3260: +\n3261: +\tfor _, tc := range []struct {\n3262: +\t\tname    string\n3263: +\t\ttargets []clablabruntime.CaptureTarget\n3264: +\t\twant    string\n3265: +\t}{\n3266: +\t\t{\n3267: +\t\t\tname:    \"management interface\",\n3268: +\t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"client\", Interface: \"eth0\"}},\n3269: +\t\t\twant: `interface \"eth0\" of node \"client\" is not a capturable link interface; ` +\n3270: +\t\t\t\t\"capturable: eth1, eth2, eth3\",\n3271: +\t\t},\n3272: +\t\t{\n3273: +\t\t\tname: \"same interface twice\",\n3274: +\t\t\ttargets: []clablabruntime.CaptureTarget{\n3275: +\t\t\t\t{Node: \"srl1\", Interface: \"e1-1\"}, {Node: \"srl1\", Interface: \"ethernet-1/1\"},\n3276: +\t\t\t},\n3277: +\t\t\twant: `interface \"e1-1\" of node \"srl1\" is requested more than once`,\n3278: +\t\t},\n3279: +\t\t{\n3280: +\t\t\tname:    \"unknown node\",\n3281: +\t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"r9\", Interface: \"eth1\"}},\n3282: +\t\t\twant:    `node \"r9\" is not part of lab \"capture\"`,\n3283: +\t\t},\n3284: +\t} {\n3285: +\t\tif _, err := c.resolveLocalCaptureTargets(tc.targets); err == nil ||\n3286: +\t\t\t!strings.Contains(err.Error(), tc.want) {\n3287: +\t\t\tt.Errorf(\"%s: error = %v, want %q\", tc.name, err, tc.want)\n3288: +\t\t}\n3289: +\t}\n3290: +}\n3291: +\n3292: +func TestLocalCaptureNeedsTheTopology(t *testing.T) {\n3293: +\tt.Parallel()\n3294: +\n3295: +\tc := &CLab{Config: &Config{Name: \"lab1\"}, globalRuntimeName: \"docker\"}\n3296: +\terr := c.Capture(context.Background(), clablabruntime.CaptureRequest{\n3297: +\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n3298: +\t}, io.Discard)\n3299: +\tif err == nil || !strings.Contains(err.Error(), `the topology of lab \"lab1\" is not available`) {\n3300: +\t\tt.Fatalf(\"error = %v\", err)\n3301: +\t}\n3302: +\tif err := c.Capture(context.Background(), clablabruntime.CaptureRequest{},\n3303: +\t\tio.Discard); err == nil || !strings.Contains(err.Error(), \"at least one capture target\") {\n3304: +\t\tt.Fatalf(\"no targets: error = %v\", err)\n3305: +\t}\n3306: +}\n3307: +\n3308: +func TestLabRuntimeWithoutCaptureFails(t *testing.T) {\n3309: +\tt.Parallel()\n3310: +\n3311: +\tunsupported := newAccessTestCLab(&recordingDestroyLabRuntime{})\n3312: +\tif err := unsupported.Capture(\n3313: +\t\tcontext.Background(),\n3314: +\t\tclablabruntime.CaptureRequest{},\n3315: +\t\tio.Discard,\n3316: +\t); err == nil || !strings.Contains(err.Error(), \"does not support packet capture\") {\n3317: +\t\tt.Fatalf(\"lab runtime without capture: error = %v\", err)\n3318: +\t}\n3319: +}\n3320: diff --git a/core/labruntime_cluster_test.go b/core/labruntime_cluster_test.go\n3321: index 06ecf57..981a302 100644\n3322: --- a/core/labruntime_cluster_test.go\n3323: +++ b/core/labruntime_cluster_test.go\n3324: @@ -1,10 +1,11 @@\n3325:  package core\n3326:  \n3327:  import (\n3328:  \t\"bytes\"\n3329:  \t\"context\"\n3330: +\t\"encoding/binary\"\n3331:  \t\"errors\"\n3332:  \t\"io\"\n3333:  \t\"net\"\n3334:  \t\"net/http\"\n3335:  \t\"os\"\n3336: @@ -175,5 +176,153 @@ func TestC9sClusterNodeAccess(t *testing.T) {\n3337:  \t\tif err == nil || !strings.Contains(err.Error(), \"forbidden\") {\n3338:  \t\t\tt.Fatalf(\"impersonated user without rights: error = %v, want forbidden\", err)\n3339:  \t\t}\n3340:  \t})\n3341:  }\n3342: +\n3343: +// TestC9sClusterCapture captures through the library against a deployed c9s lab, as an identity\n3344: +// that holds only the clabernetes-lab-editor role in the lab namespace. It runs only when\n3345: +// CLAB_C9S_TEST_LAB names the lab and CLAB_C9S_TEST_CAPTURE_USER the identity (tests/14-clabernetes\n3346: +// sets both). The lab must have linux nodes \"client\" (10.10.10.1) and \"server\" (10.10.10.2)\n3347: +// linked by eth1. CLAB_C9S_TEST_FORBIDDEN_USER names an identity without a binding.\n3348: +func TestC9sClusterCapture(t *testing.T) {\n3349: +\tlab := os.Getenv(\"CLAB_C9S_TEST_LAB\")\n3350: +\tuser := os.Getenv(\"CLAB_C9S_TEST_CAPTURE_USER\")\n3351: +\tif lab == \"\" || user == \"\" {\n3352: +\t\tt.Skip(\"CLAB_C9S_TEST_LAB or CLAB_C9S_TEST_CAPTURE_USER is not set\")\n3353: +\t}\n3354: +\n3355: +\tnewCLab := func(t *testing.T, user string) *CLab {\n3356: +\t\tt.Helper()\n3357: +\n3358: +\t\tc, err := NewContainerLab(\n3359: +\t\t\tWithRuntime(clablabruntime.ClabernetesRuntimeName, nil),\n3360: +\t\t\tWithTopologyName(lab),\n3361: +\t\t\tWithLabRuntimeIdentity(clablabruntime.Identity{User: user}),\n3362: +\t\t)\n3363: +\t\tif err != nil {\n3364: +\t\t\tt.Fatal(err)\n3365: +\t\t}\n3366: +\n3367: +\t\treturn c\n3368: +\t}\n3369: +\tc := newCLab(t, user)\n3370: +\n3371: +\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)\n3372: +\tdefer cancel()\n3373: +\n3374: +\tt.Run(\"version check\", func(t *testing.T) {\n3375: +\t\tif err := c.CheckLabRuntimeSupport(ctx); err != nil {\n3376: +\t\t\tt.Fatal(err)\n3377: +\t\t}\n3378: +\t})\n3379: +\n3380: +\tt.Run(\"capture interfaces\", func(t *testing.T) {\n3381: +\t\tinterfaces, err := c.CaptureInterfaces(ctx)\n3382: +\t\tif err != nil {\n3383: +\t\t\tt.Fatal(err)\n3384: +\t\t}\n3385: +\t\twant := []clablabruntime.CaptureInterface{\n3386: +\t\t\t{Node: \"client\", Interface: \"eth1\", PeerNode: \"server\", PeerInterface: \"eth1\"},\n3387: +\t\t\t{Node: \"server\", Interface: \"eth1\", PeerNode: \"client\", PeerInterface: \"eth1\"},\n3388: +\t\t}\n3389: +\t\tif len(interfaces) != 2 || interfaces[0] != want[0] || interfaces[1] != want[1] {\n3390: +\t\t\tt.Fatalf(\"interfaces = %+v\", interfaces)\n3391: +\t\t}\n3392: +\t})\n3393: +\n3394: +\tt.Run(\"capture both ends of a link\", func(t *testing.T) {\n3395: +\t\tpinged := make(chan error, 1)\n3396: +\t\tgo func() {\n3397: +\t\t\ttime.Sleep(time.Second)\n3398: +\t\t\tpinged <- c.AttachLabRuntimeNode(ctx, clablabruntime.AttachRequest{\n3399: +\t\t\t\tNodeName: \"client\",\n3400: +\t\t\t\tCommand:  []string{\"ping\", \"-c\", \"4\", \"-i\", \"0.3\", \"10.10.10.2\"},\n3401: +\t\t\t}, clablabruntime.AttachStreams{Stdout: io.Discard})\n3402: +\t\t}()\n3403: +\n3404: +\t\tvar out bytes.Buffer\n3405: +\t\terr := c.Capture(ctx, clablabruntime.CaptureRequest{\n3406: +\t\t\tTargets: []clablabruntime.CaptureTarget{\n3407: +\t\t\t\t{Node: \"client\", Interface: \"eth1\"}, {Node: \"server\", Interface: \"eth1\"},\n3408: +\t\t\t},\n3409: +\t\t\tDuration: 5 * time.Second,\n3410: +\t\t}, &out)\n3411: +\t\tif err != nil {\n3412: +\t\t\tt.Fatal(err)\n3413: +\t\t}\n3414: +\t\tif err := <-pinged; err != nil {\n3415: +\t\t\tt.Fatalf(\"ping: %v\", err)\n3416: +\t\t}\n3417: +\n3418: +\t\tnames, icmp := summarizePCAPNG(t, out.Bytes())\n3419: +\t\tif len(names) != 2 || names[0] != \"client:eth1\" || names[1] != \"server:eth1\" {\n3420: +\t\t\tt.Fatalf(\"interfaces = %v\", names)\n3421: +\t\t}\n3422: +\t\t// every echo request and reply crosses both ends\n3423: +\t\tif icmp[0] < 8 || icmp[1] < 8 {\n3424: +\t\t\tt.Fatalf(\"ICMP packets per interface = %v, want at least 8 on each\", icmp)\n3425: +\t\t}\n3426: +\t})\n3427: +\n3428: +\tt.Run(\"restart as lab editor\", func(t *testing.T) {\n3429: +\t\tif err := c.RestartNodes(ctx, []string{\"server\"}); err != nil {\n3430: +\t\t\tt.Fatal(err)\n3431: +\t\t}\n3432: +\t})\n3433: +\n3434: +\tt.Run(\"forbidden identity\", func(t *testing.T) {\n3435: +\t\tforbidden := os.Getenv(\"CLAB_C9S_TEST_FORBIDDEN_USER\")\n3436: +\t\tif forbidden == \"\" {\n3437: +\t\t\tt.Skip(\"CLAB_C9S_TEST_FORBIDDEN_USER is not set\")\n3438: +\t\t}\n3439: +\n3440: +\t\terr := newCLab(t, forbidden).Capture(ctx, clablabruntime.CaptureRequest{\n3441: +\t\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"client\", Interface: \"eth1\"}},\n3442: +\t\t\tDuration: time.Second,\n3443: +\t\t}, io.Discard)\n3444: +\t\tif err == nil || !strings.Contains(err.Error(), \"forbidden\") {\n3445: +\t\t\tt.Fatalf(\"capture as %s = %v, want forbidden\", forbidden, err)\n3446: +\t\t}\n3447: +\t})\n3448: +}\n3449: +\n3450: +// summarizePCAPNG returns the interface names of a little-endian pcapng stream and its IPv4 ICMP\n3451: +// packets per interface ID.\n3452: +func summarizePCAPNG(t *testing.T, data []byte) ([]string, map[uint32]int) {\n3453: +\tt.Helper()\n3454: +\n3455: +\tvar names []string\n3456: +\ticmp := map[uint32]int{}\n3457: +\tfor len(data) >= 12 {\n3458: +\t\tblockType := binary.LittleEndian.Uint32(data[0:4])\n3459: +\t\tlength := int(binary.LittleEndian.Uint32(data[4:8]))\n3460: +\t\tif length < 12 || length > len(data) {\n3461: +\t\t\tt.Fatalf(\"invalid block length %d\", length)\n3462: +\t\t}\n3463: +\t\tbody := data[8 : length-4]\n3464: +\t\tswitch blockType {\n3465: +\t\tcase 1: // Interface Description Block\n3466: +\t\t\toptions := body[8:]\n3467: +\t\t\tfor len(options) >= 4 {\n3468: +\t\t\t\tcode := binary.LittleEndian.Uint16(options[0:2])\n3469: +\t\t\t\tsize := int(binary.LittleEndian.Uint16(options[2:4]))\n3470: +\t\t\t\tif code == 0 {\n3471: +\t\t\t\t\tbreak\n3472: +\t\t\t\t}\n3473: +\t\t\t\tif code == 2 {\n3474: +\t\t\t\t\tnames = append(names, string(options[4:4+size]))\n3475: +\t\t\t\t}\n3476: +\t\t\t\toptions = options[4+size+(4-size%4)%4:]\n3477: +\t\t\t}\n\n(Output capped at 50 KB. Showing lines 1702-3477. Use offset=3478 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+// later still goes out first. A packet stamped before the last packet written arrived too late\n+// to be ordered: it is written as it comes and counted, and the count goes to the debug log when\n+// the capture ends.\n+//\n+// A source can place a hold at the earliest timestamp it may still write (Hold); packets stamped\n+// after a hold wait for it to be released (Release). The c9s runtime holds while it switches\n+// between chained capture segments.\n+type Reorder struct {\n+\twrite  func(id uint32, packet *Packet) error\n+\tonFail func()\n+\twindow time.Duration\n+\tnow    func() time.Time\n+\n+\tmu     sync.Mutex\n+\tqueue  reorderQueue\n+\tbytes  int\n+\tseq    uint64\n+\tholds  map[any]int64\n+\terr    error\n+\twake   chan struct{}",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+// later still goes out first. A packet stamped before the last packet written arrived too late\n+// to be ordered: it is written as it comes and counted, and the count goes to the debug log when\n+// the capture ends.\n+//\n+// A source can place a hold at the earliest timestamp it may still write (Hold); packets stamped\n+// after a hold wait for it to be released (Release). The c9s runtime holds while it switches\n+// between chained capture segments.\n+type Reorder struct {\n+\twrite  func(id uint32, packet *Packet) error\n+\tonFail func()\n+\twindow time.Duration\n+\tnow    func() time.Time\n+\n+\tmu     sync.Mutex\n+\tqueue  reorderQueue\n+\tbytes  int\n+\tseq    uint64\n+\tholds  map[any]int64\n+\terr    error\n+\twake   chan struct{}\n+\tstats  reorderStats\n+\tcursor int64 // timestamp of the latest packet written in order\n+}\n+\n+type reorderStats struct {\n+\tlate    int\n+\tmaxLate time.Duration\n+\tforced  int\n+}\n+\n+// reorderedPacket is a packet waiting in the buffer.\n+type reorderedPacket struct {\n+\tid      uint32\n+\tpacket  *Packet\n+\tarrived time.Time\n+\tseq     uint64\n+}\n+\n+// reorderQueue is a min-heap by timestamp, then arrival.\n+type reorderQueue []reorderedPacket\n+\n+func (q reorderQueue) Len() int { return len(q) }\n+\n+func (q reorderQueue) Less(i, j int) bool {\n+\tif q[i].packet.Timestamp != q[j].packet.Timestamp {\n+\t\treturn q[i].packet.Timestamp < q[j].packet.Timestamp\n+\t}\n+\n+\treturn q[i].seq < q[j].seq\n+}\n+\n+func (q reorderQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }\n+\n+func (q *reorderQueue) Push(\n+\tx any,\n+) {\n+\t*q = append(*q, x.(reorderedPacket))\n+} //nolint:forcetypeassert // heap contract\n+\n+func (q *reorderQueue) Pop() any {\n+\told := *q\n+\titem := old[len(old)-1]\n+\t*q = old[:len(old)-1]\n+\n+\treturn item\n+}\n+\n+// NewReorder returns a buffer that writes through write; onFail is called once a write\n+// failed. A window of zero or less writes every packet as it arrives.\n+func NewReorder(\n+\twindow time.Duration,\n+\twrite func(id uint32, packet *Packet) error,\n+\tonFail func(),\n+) *Reorder {\n+\treturn &Reorder{\n+\t\twrite: write, onFail: onFail, window: window, now: time.Now,\n+\t\tholds: map[any]int64{}, wake: make(chan struct{}, 1),\n+\t}\n+}\n+\n+// push hands a packet to the buffer. It returns the error of a failed write.\n+func (q *Reorder) Push(id uint32, packet *Packet) error {\n+\tq.mu.Lock()\n+\tdefer q.mu.Unlock()\n+\n+\tif q.err != nil {\n+\t\treturn q.err\n+\t}\n+\tif q.window <= 0 {\n+\t\treturn q.writeLocked(id, packet)\n+\t}\n+\tif q.cursor != 0 && packet.Timestamp < q.cursor {\n+\t\tq.stats.late++\n+\t\tq.stats.maxLate = max(q.stats.maxLate, time.Duration(q.cursor-packet.Timestamp))\n+\t\tif q.stats.late == 1 {\n+\t\t\tlog.Debug(\"Capture packet arrived after the reorder window, writing it out of order\",\n+\t\t\t\t\"late_by\", time.Duration(q.cursor-packet.Timestamp), \"window\", q.window)\n+\t\t}\n+\n+\t\treturn q.writeLocked(id, packet)\n+\t}\n+\n+\tq.seq++\n+\theap.Push(&q.queue, reorderedPacket{id: id, packet: packet, arrived: q.now(), seq: q.seq})\n+\tq.bytes += len(packet.Data)\n+\tfor q.bytes > maxReorderBytes && q.queue.Len() > 0 {\n+\t\tq.stats.forced++\n+\t\tif err := q.popLocked(); err != nil {\n+\t\t\treturn err\n+\t\t}\n+\t}\n+\n+\tselect {\n+\tcase q.wake <- struct{}{}:\n+\tdefault:\n+\t}\n+\n+\treturn nil\n+}\n+\n+// hold keeps packets stamped after timestamp in the buffer until release(key).\n+func (q *Reorder) Hold(key any, timestamp int64) {\n+\tq.mu.Lock()\n+\tdefer q.mu.Unlock()\n+\n+\tq.holds[key] = timestamp\n+}\n+\n+// release removes the hold of key.\n+func (q *Reorder) Release(key any) {\n+\tq.mu.Lock()\n+\t_, held := q.holds[key]\n+\tdelete(q.holds, key)\n+\tq.mu.Unlock()\n+\n+\tif held {\n+\t\tselect {\n+\t\tcase q.wake <- struct{}{}:\n+\t\tdefault:\n+\t\t}\n+\t}\n+}\n+\n+// run writes due packets until ctx ends.\n+func (q *Reorder) Run(ctx context.Context) {\n+\tif q.window <= 0 {\n+\t\treturn\n+\t}\n+\n+\ttimer := time.NewTimer(time.Hour)\n+\tdefer timer.Stop()\n+\n+\tfor {\n+\t\tnext := q.writeDue()\n+\t\twait := time.Hour\n+\t\tif !next.IsZero() {\n+\t\t\twait = max(next.Sub(q.now()), time.Millisecond)\n+\t\t}\n+\t\tresetTimer(timer, wait)\n+\n+\t\tselect {\n+\t\tcase <-ctx.Done():\n+\t\t\treturn\n+\t\tcase <-q.wake:\n+\t\tcase <-timer.C:\n+\t\t}\n+\t}\n+}\n+\n+// writeDue writes the packets that waited for the window and are not behind a hold, in\n+// timestamp order. It returns when the next packet is due, or zero when that depends on a new\n+// packet or a released hold.\n+func (q *Reorder) writeDue() time.Time {\n+\tq.mu.Lock()\n+\tdefer q.mu.Unlock()\n+\n+\theld, limit := false, int64(0)\n+\tfor _, timestamp := range q.holds {\n+\t\tif !held || timestamp < limit {\n+\t\t\theld, limit = true, timestamp\n+\t\t}\n+\t}\n+\n+\tnow := q.now()\n+\tfor q.queue.Len() > 0 && q.err == nil {\n+\t\thead := q.queue[0]\n+\t\tif held && head.packet.Timestamp > limit {\n+\t\t\treturn time.Time{}\n+\t\t}\n+\t\tif due := head.arrived.Add(q.window); due.After(now) {\n+\t\t\treturn due\n+\t\t}\n+\t\tif q.popLocked() != nil {\n+\t\t\treturn time.Time{}\n+\t\t}\n+\t}\n+\n+\treturn time.Time{}\n+}\n+\n+// flush writes every remaining packet in timestamp order and logs what could not be ordered.\n+func (q *Reorder) Flush() {\n+\tq.mu.Lock()\n+\tdefer q.mu.Unlock()\n+\n+\tfor q.queue.Len() > 0 && q.err == nil {\n+\t\tif q.popLocked() != nil {\n+\t\t\tbreak\n+\t\t}\n+\t}\n+\tq.queue, q.bytes = nil, 0\n+\n+\tif q.stats.late > 0 || q.stats.forced > 0 {\n+\t\tlog.Debug(\"Capture wrote packets out of timestamp order\",\n+\t\t\t\"late_packets\", q.stats.late, \"max_late_by\", q.stats.maxLate,\n+\t\t\t\"window\", q.window, \"buffer_overflow_packets\", q.stats.forced)\n+\t}\n+}\n+\n+func (q *Reorder) popLocked() error {\n+\titem := heap.Pop(&q.queue).(reorderedPacket) //nolint:forcetypeassert // heap contract\n+\tq.bytes -= len(item.packet.Data)\n+\tq.cursor = max(q.cursor, item.packet.Timestamp)\n+\n+\treturn q.writeLocked(item.id, item.packet)\n+}\n+\n+func (q *Reorder) writeLocked(id uint32, packet *Packet) error {\n+\tif err := q.write(id, packet); err != nil {\n+\t\tif q.err == nil {\n+\t\t\tq.err = err\n+\t\t\tif q.onFail != nil {\n+\t\t\t\tq.onFail()\n+\t\t\t}\n+\t\t}\n+\n+\t\treturn err\n+\t}\n+\n+\treturn nil\n+}\n+\n+func resetTimer(timer *time.Timer, d time.Duration) {\n+\tif !timer.Stop() {\n+\t\tselect {\n+\t\tcase <-timer.C:\n+\t\tdefault:\n+\t\t}\n+\t}\n+\ttimer.Reset(d)\n+}\ndiff --git a/capture/reorder_test.go b/capture/reorder_test.go\nnew file mode 100644\nindex 0000000..d281bed\n--- /dev/null\n+++ b/capture/reorder_test.go\n@@ -0,0 +1,202 @@\n+package capture\n+\n+import (\n+\t\"context\"\n+\t\"errors\"\n+\t\"slices\"\n+\t\"sync\"\n+\t\"testing\"\n+\t\"time\"\n+)\n+\n+// reorderSink records what a reorder buffer writes.\n+type reorderSink struct {\n+\tmu      sync.Mutex\n+\twritten []int64\n+\tids     []uint32\n+\tfailAt  int\n+}\n+\n+func (s *reorderSink) write(id uint32, packet *Packet) error {\n+\ts.mu.Lock()\n+\tdefer s.mu.Unlock()\n+\tif s.failAt > 0 && len(s.written) == s.failAt {\n+\t\treturn errors.New(\"write |1: broken pipe\")\n+\t}\n+\ts.written = append(s.written, packet.Timestamp)\n+\ts.ids = append(s.ids, id)\n+\n+\treturn nil\n+}\n+\n+func (s *reorderSink) timestamps() []int64 {\n+\ts.mu.Lock()\n+\tdefer s.mu.Unlock()\n+\n+\treturn slices.Clone(s.written)\n+}\n+\n+// interleavedStreams pushes two synthetic streams of ticks, interleaved in time: stream 0 is\n+// delivered at once, stream 1 `delay` after its packets were stamped. Both stamp a packet every\n+// 2 ms, offset by 1 ms.\n+func interleavedStreams(t *testing.T, q *Reorder, ticks int, delay time.Duration) {\n+\tt.Helper()\n+\n+\tstart := time.Now()\n+\ttype delivery struct {\n+\t\tat time.Time\n+\t\tid uint32\n+\t\tts int64\n+\t}\n+\tvar deliveries []delivery\n+\tfor tick := range ticks {\n+\t\tstamp := start.Add(time.Duration(tick) * 2 * time.Millisecond)\n+\t\tdeliveries = append(deliveries,\n+\t\t\tdelivery{at: stamp, id: 0, ts: stamp.UnixNano()},\n+\t\t\tdelivery{\n+\t\t\t\tat: stamp.Add(time.Millisecond + delay), id: 1,\n+\t\t\t\tts: stamp.Add(time.Millisecond).UnixNano(),\n+\t\t\t})\n+\t}\n+\tslices.SortStableFunc(deliveries, func(a, b delivery) int { return a.at.Compare(b.at) })\n+\n+\tfor _, next := range deliveries {\n+\t\ttime.Sleep(time.Until(next.at))\n+\t\tif err := q.Push(\n+\t\t\tnext.id,\n+\t\t\t&Packet{InterfaceID: next.id, Timestamp: next.ts},\n+\t\t); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t}\n+}\n+\n+func runReorder(q *Reorder) func() {\n+\tctx, cancel := context.WithCancel(context.Background())\n+\tdone := make(chan struct{})\n+\tgo func() {\n+\t\tdefer close(done)\n+\t\tq.Run(ctx)\n+\t}()\n+\n+\treturn func() {\n+\t\tcancel()\n+\t\t<-done\n+\t\tq.Flush()\n+\t}\n+}\n+\n+func TestReorderOrdersStreamsWithinTheWindow(t *testing.T) {\n+\tt.Parallel()\n+\n+\tsink := &reorderSink{}\n+\tq := NewReorder(100*time.Millisecond, sink.write, nil)\n+\tstop := runReorder(q)\n+\tinterleavedStreams(t, q, 60, 40*time.Millisecond)\n+\n+\t// packets go out while the capture runs, not only at the end\n+\ttime.Sleep(150 * time.Millisecond)\n+\tif len(sink.timestamps()) == 0 {\n+\t\tt.Fatal(\"nothing written while the streams ran\")\n+\t}\n+\tstop()\n+\n+\twritten := sink.timestamps()\n+\tif len(written) != 120 || !slices.IsSorted(written) {\n+\t\tt.Fatalf(\"written %d packets, sorted %v\", len(written), slices.IsSorted(written))\n+\t}\n+\tif q.stats.late != 0 {\n+\t\tt.Fatalf(\"late packets = %d\", q.stats.late)\n+\t}\n+}\n+\n+func TestReorderWritesLatePacketsAsTheyCome(t *testing.T) {\n+\tt.Parallel()\n+\n+\tsink := &reorderSink{}\n+\tq := NewReorder(20*time.Millisecond, sink.write, nil)\n+\tstop := runReorder(q)\n+\t// stream 1 arrives 80 ms after its stamps, far beyond the 20 ms window\n+\tinterleavedStreams(t, q, 60, 80*time.Millisecond)\n+\tstop()\n+\n+\twritten := sink.timestamps()\n+\tif len(written) != 120 {\n+\t\tt.Fatalf(\"written %d packets, want all 120\", len(written))\n+\t}\n+\tif q.stats.late == 0 || q.stats.maxLate < 40*time.Millisecond || slices.IsSorted(written) {\n+\t\tt.Fatalf(\"late = %d (max %s), sorted %v; want late packets written out of order\",\n+\t\t\tq.stats.late, q.stats.maxLate, slices.IsSorted(written))\n+\t}\n+}\n+\n+func TestReorderHoldsPacketsAfterAHold(t *testing.T) {\n+\tt.Parallel()\n+\n+\tsink := &reorderSink{}\n+\tq := NewReorder(time.Millisecond, sink.write, nil)\n+\tstop := runReorder(q)\n+\tdefer stop()\n+\n+\tchain := &struct{ name string }{\"chain\"}\n+\tq.Hold(chain, 100)\n+\tfor _, ts := range []int64{50, 150, 100, 200} {\n+\t\tif err := q.Push(0, &Packet{Timestamp: ts}); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t}\n+\ttime.Sleep(30 * time.Millisecond)\n+\tif got := sink.timestamps(); !slices.Equal(got, []int64{50, 100}) {\n+\t\tt.Fatalf(\"written under the hold = %v, want [50 100]\", got)\n+\t}\n+\n+\t// the chain writes what it held back, then releases\n+\tif err := q.Push(1, &Packet{Timestamp: 120}); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tq.Release(chain)\n+\ttime.Sleep(30 * time.Millisecond)\n+\tif got := sink.timestamps(); !slices.Equal(got, []int64{50, 100, 120, 150, 200}) {\n+\t\tt.Fatalf(\"written after the release = %v\", got)\n+\t}\n+}\n+\n+func TestReorderStopsAtTheFirstWriteError(t *testing.T) {\n+\tt.Parallel()\n+\n+\tsink := &reorderSink{failAt: 2}\n+\tfailed := 0\n+\tq := NewReorder(time.Millisecond, sink.write, func() { failed++ })\n+\tstop := runReorder(q)\n+\n+\tvar err error\n+\tfor ts := int64(1); ts < 50 && err == nil; ts++ {\n+\t\terr = q.Push(0, &Packet{Timestamp: ts})\n+\t\ttime.Sleep(2 * time.Millisecond)\n+\t}\n+\tstop()\n+\n+\tif err == nil || failed != 1 || len(sink.timestamps()) != 2 {\n+\t\tt.Fatalf(\n+\t\t\t\"push error = %v, onFail calls %d, written %d\",\n+\t\t\terr,\n+\t\t\tfailed,\n+\t\t\tlen(sink.timestamps()),\n+\t\t)\n+\t}\n+}\n+\n+func TestReorderWithoutWindowWritesThrough(t *testing.T) {\n+\tt.Parallel()\n+\n+\tsink := &reorderSink{}\n+\tq := NewReorder(0, sink.write, nil)\n+\tfor _, ts := range []int64{30, 10, 20} {\n+\t\tif err := q.Push(0, &Packet{Timestamp: ts}); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t}\n+\tif got := sink.timestamps(); !slices.Equal(got, []int64{30, 10, 20}) {\n+\t\tt.Fatalf(\"written = %v, want arrival order\", got)\n+\t}\n+}\ndiff --git a/cmd/capture.go b/cmd/capture.go\nnew file mode 100644\nindex 0000000..20117bc\n--- /dev/null\n+++ b/cmd/capture.go\n@@ -0,0 +1,262 @@\n+package cmd\n+\n+import (\n+\t\"encoding/json\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"os\"\n+\t\"strings\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\ttableWriter \"github.com/jedib0t/go-pretty/v6/table\"\n+\t\"github.com/jedib0t/go-pretty/v6/text\"\n+\t\"github.com/spf13/cobra\"\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+\tclabutils \"github.com/srl-labs/containerlab/utils\"\n+)\n+\n+// CaptureOptions are the flags of the capture command.\n+type CaptureOptions struct {\n+\tTargets     []string\n+\tDuration    time.Duration\n+\tPacketLimit int\n+\tSnapLength  int\n+\tWrite       string\n+\tList        bool\n+\tFormat      string\n+}\n+\n+func captureCmd(o *Options) (*cobra.Command, error) {\n+\tc := &cobra.Command{\n+\t\tUse:   \"capture\",\n+\t\tShort: \"capture packets on lab link interfaces\",\n+\t\tLong: \"capture packets on lab link interfaces of one or more nodes into one pcapng \" +\n+\t\t\t\"stream\\nreference: https://containerlab.dev/cmd/capture/\",\n+\t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n+\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n+\t\t\t\treturn nil\n+\t\t\t}\n+\n+\t\t\t// Docker and Podman captures open packet sockets in the nodes' namespaces\n+\t\t\treturn clabutils.CheckAndGetRootPrivs()\n+\t\t},\n+\t\tSilenceUsage: true,\n+\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n+\t\t\treturn captureFn(cmd, o)\n+\t\t},\n+\t}\n+\n+\tc.Flags().StringArrayVar(\n+\t\t&o.Capture.Targets,\n+\t\t\"target\",\n+\t\to.Capture.Targets,\n+\t\t\"node and interfaces to capture, as <node>:<interface>[,<interface>...]; repeatable\",\n+\t)\n+\tc.Flags().DurationVar(\n+\t\t&o.Capture.Duration,\n+\t\t\"duration\",\n+\t\to.Capture.Duration,\n+\t\t\"stop after this duration; 0 captures until interrupted\",\n+\t)\n+\tc.Flags().IntVar(\n+\t\t&o.Capture.PacketLimit,\n+\t\t\"packet-limit\",\n+\t\to.Capture.PacketLimit,\n+\t\t\"stop after this many packets across all targets; 0 means no limit\",\n+\t)\n+\tc.Flags().IntVar(\n+\t\t&o.Capture.SnapLength,\n+\t\t\"snap-length\",\n+\t\to.Capture.SnapLength,\n+\t\t\"bytes kept of each packet (64 to 1048576); 0 uses the runtime default\",\n+\t)\n+\tc.Flags().StringVarP(\n+\t\t&o.Capture.Write,\n+\t\t\"write\",\n+\t\t\"w\",\n+\t\to.Capture.Write,\n+\t\t\"pcapng output file; - writes to stdout\",\n+\t)\n+\tc.Flags().BoolVar(\n+\t\t&o.Capture.List,\n+\t\t\"list\",\n+\t\to.Capture.List,\n+\t\t\"list the capturable interfaces instead of capturing\",\n+\t)\n+\tc.Flags().StringVarP(\n+\t\t&o.Capture.Format,\n+\t\t\"format\",\n+\t\t\"f\",\n+\t\to.Capture.Format,\n+\t\t\"output format of --list: table or json\",\n+\t)\n+\n+\tc.Example = `# Capture e1-1 of srl1 and e1-1 of srl2 for 30 seconds into one file\n+containerlab capture -t srl.clab.yml --target srl1:e1-1 --target srl2:e1-1 \\\n+  --duration 30s -w srl.pcapng\n+\n+# Capture two interfaces of one node and watch them live in Wireshark\n+containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n+\n+# List the interfaces capture accepts\n+containerlab capture --name srl --list -f json\n+\n+# Capture a lab running on the c9s runtime\n+containerlab -r c9s capture --name srl --target srl1:e1-1 -w srl.pcapng`\n+\n+\treturn c, nil\n+}\n+\n+func captureFn(cmd *cobra.Command, o *Options) error {\n+\tif o.Global.TopologyName == \"\" && o.Global.TopologyFile == \"\" {\n+\t\treturn fmt.Errorf(\"provide either a lab name (--name) or a topology file path (--topo)\")\n+\t}\n+\n+\tif o.Capture.List {\n+\t\treturn captureListFn(cmd, o)\n+\t}\n+\n+\ttargets, err := parseCaptureTargets(o.Capture.Targets)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\t// An interrupt ends the capture; the command still finishes the file and exits cleanly.\n+\t// Armed before the file is created, so an interrupt never leaves it empty.\n+\to.Global.FinishOnCancel.Store(true)\n+\tdefer o.Global.FinishOnCancel.Store(false)\n+\n+\toutput := cmd.OutOrStdout()\n+\tif o.Capture.Write != \"\" && o.Capture.Write != \"-\" {\n+\t\tfile, err := os.Create(o.Capture.Write)\n+\t\tif err != nil {\n+\t\t\treturn fmt.Errorf(\"failed to create the capture file: %w\", err)\n+\t\t}\n+\t\tdefer file.Close()\n+\t\toutput = file\n+\n+\t\t// the file belongs to the user who ran the command, also through sudo or setuid\n+\t\tif err := clabutils.SetUIDAndGID(o.Capture.Write); err != nil {\n+\t\t\tlog.Debug(\"Cannot hand the capture file to the user\", \"file\", o.Capture.Write,\n+\t\t\t\t\"error\", err)\n+\t\t}\n+\t}\n+\n+\terr = c.Capture(cmd.Context(), clablabruntime.CaptureRequest{\n+\t\tTargets:     targets,\n+\t\tDuration:    o.Capture.Duration,\n+\t\tPacketLimit: o.Capture.PacketLimit,\n+\t\tSnapLength:  o.Capture.SnapLength,\n+\t}, output)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tif file, ok := output.(*os.File); ok && output != cmd.OutOrStdout() {\n+\t\tif err := file.Sync(); err != nil {\n+\t\t\treturn fmt.Errorf(\"failed to write the capture file: %w\", err)\n+\t\t}\n+\t}\n+\n+\treturn nil\n+}\n+\n+// parseCaptureTargets parses --target values: <node>:<interface>[,<interface>...]. The node name\n+// ends at the first colon, so interface names may contain colons or slashes.\n+func parseCaptureTargets(values []string) ([]clablabruntime.CaptureTarget, error) {\n+\tif len(values) == 0 {\n+\t\treturn nil, fmt.Errorf(\"provide at least one --target <node>:<interface>[,<interface>...]\")\n+\t}\n+\n+\ttargets := make([]clablabruntime.CaptureTarget, 0, len(values))\n+\tfor _, value := range values {\n+\t\tnode, interfaces, ok := strings.Cut(strings.TrimSpace(value), \":\")\n+\t\tnode = strings.TrimSpace(node)\n+\t\tif !ok || node == \"\" || strings.TrimSpace(interfaces) == \"\" {\n+\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: use <node>:<interface>[,<interface>...]\",\n+\t\t\t\tvalue)\n+\t\t}\n+\n+\t\tfor _, name := range strings.Split(interfaces, \",\") {\n+\t\t\tname = strings.TrimSpace(name)\n+\t\t\tif name == \"\" {\n+\t\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: empty interface name\", value)\n+\t\t\t}\n+\t\t\ttargets = append(targets, clablabruntime.CaptureTarget{Node: node, Interface: name})\n+\t\t}\n+\t}\n+\n+\treturn targets, nil\n+}\n+\n+func captureListFn(cmd *cobra.Command, o *Options) error {\n+\tformat := o.Capture.Format\n+\tif format == \"\" {\n+\t\tformat = clabconstants.FormatTable\n+\t}\n+\tif format != clabconstants.FormatTable && format != clabconstants.FormatJSON {\n+\t\treturn fmt.Errorf(\"output format %q is not supported, use 'table' or 'json'\", format)\n+\t}\n+\tif len(o.Capture.Targets) != 0 {\n+\t\treturn fmt.Errorf(\"--list lists every running node's interfaces; it takes no --target\")\n+\t}\n+\n+\tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tinterfaces, err := c.CaptureInterfaces(cmd.Context())\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\treturn printCaptureInterfaces(cmd.OutOrStdout(), interfaces, format)\n+}\n+\n+func printCaptureInterfaces(\n+\tw io.Writer,\n+\tinterfaces []clablabruntime.CaptureInterface,\n+\tformat string,\n+) error {\n+\tif format == clabconstants.FormatJSON {\n+\t\tif interfaces == nil {\n+\t\t\tinterfaces = []clablabruntime.CaptureInterface{}\n+\t\t}\n+\t\tdata, err := json.MarshalIndent(interfaces, \"\", \"  \")\n+\t\tif err != nil {\n+\t\t\treturn err\n+\t\t}\n+\t\t_, err = fmt.Fprintln(w, string(data))\n+\n+\t\treturn err\n+\t}\n+\n+\ttable := tableWriter.NewWriter()\n+\ttable.SetOutputMirror(w)\n+\ttable.SetStyle(tableWriter.StyleRounded)\n+\ttable.Style().Format.Header = text.FormatTitle\n+\ttable.Style().Format.HeaderAlign = text.AlignCenter\n+\ttable.AppendHeader(tableWriter.Row{\"Node\", \"Interface\", \"Alias\", \"Peer Node\", \"Peer Interface\"})\n+\ttable.SetColumnConfigs([]tableWriter.ColumnConfig{{Number: 1, AutoMerge: true}})\n+\tfor _, intf := range interfaces {\n+\t\talias := intf.Alias\n+\t\tif alias == \"\" {\n+\t\t\talias = clabconstants.NotApplicable\n+\t\t}\n+\t\ttable.AppendRow(tableWriter.Row{\n+\t\t\tintf.Node, intf.Interface, alias, intf.PeerNode, intf.PeerInterface,\n+\t\t})\n+\t}\n+\ttable.Render()\n+\n+\treturn nil\n+}\ndiff --git a/cmd/capture_test.go b/cmd/capture_test.go\nnew file mode 100644\nindex 0000000..da12d66\n--- /dev/null\n+++ b/cmd/capture_test.go\n@@ -0,0 +1,109 @@\n+package cmd\n+\n+import (\n+\t\"bytes\"\n+\t\"encoding/json\"\n+\t\"slices\"\n+\t\"strings\"\n+\t\"testing\"\n+\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+)\n+\n+func TestParseCaptureTargets(t *testing.T) {\n+\tt.Parallel()\n+\n+\ttargets, err := parseCaptureTargets([]string{\n+\t\t\"srl1:e1-1,ethernet-1/2\", \" sros : 1/1/3 \", \"r1:eth1\",\n+\t})\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\twant := []clablabruntime.CaptureTarget{\n+\t\t{Node: \"srl1\", Interface: \"e1-1\"},\n+\t\t{Node: \"srl1\", Interface: \"ethernet-1/2\"},\n+\t\t{Node: \"sros\", Interface: \"1/1/3\"},\n+\t\t{Node: \"r1\", Interface: \"eth1\"},\n+\t}\n+\tif !slices.Equal(targets, want) {\n+\t\tt.Fatalf(\"targets = %+v, want %+v\", targets, want)\n+\t}\n+\n+\tfor _, bad := range [][]string{nil, {\"srl1\"}, {\":e1-1\"}, {\"srl1:\"}, {\"srl1:e1-1,,e1-2\"}} {\n+\t\tif _, err := parseCaptureTargets(bad); err == nil {\n+\t\t\tt.Errorf(\"parseCaptureTargets(%q) succeeded\", bad)\n+\t\t}\n+\t}\n+}\n+\n+func TestCaptureCommandFlags(t *testing.T) {\n+\to := GetOptions()\n+\tcmd, err := captureCmd(o)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif err := cmd.ParseFlags([]string{\n+\t\t\"--target\", \"srl1:e1-1\", \"--target\", \"srl2:e1-1,e1-2\", \"--duration\", \"90m\",\n+\t\t\"--packet-limit\", \"100\", \"--snap-length\", \"128\", \"-w\", \"out.pcapng\",\n+\t}); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif !slices.Equal(o.Capture.Targets, []string{\"srl1:e1-1\", \"srl2:e1-1,e1-2\"}) ||\n+\t\to.Capture.Duration.Minutes() != 90 || o.Capture.PacketLimit != 100 ||\n+\t\to.Capture.SnapLength != 128 || o.Capture.Write != \"out.pcapng\" {\n+\t\tt.Fatalf(\"capture options = %+v\", o.Capture)\n+\t}\n+\tif def := cmd.Flag(\"write\").DefValue; def != \"-\" {\n+\t\tt.Fatalf(\"--write default = %q, want stdout\", def)\n+\t}\n+}\n+\n+func TestPrintCaptureInterfaces(t *testing.T) {\n+\tt.Parallel()\n+\n+\tinterfaces := []clablabruntime.CaptureInterface{\n+\t\t{\n+\t\t\tNode:          \"srl1\",\n+\t\t\tInterface:     \"e1-1\",\n+\t\t\tAlias:         \"ethernet-1/1\",\n+\t\t\tPeerNode:      \"srl2\",\n+\t\t\tPeerInterface: \"ethernet-1/1\",\n+\t\t},\n+\t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"srl1-e1-2\"},\n+\t}\n+\n+\tvar out bytes.Buffer\n+\tif err := printCaptureInterfaces(&out, interfaces, \"json\"); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tvar decoded []map[string]any\n+\tif err := json.Unmarshal(out.Bytes(), &decoded); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif decoded[0][\"peer_node\"] != \"srl2\" || decoded[0][\"alias\"] != \"ethernet-1/1\" {\n+\t\tt.Fatalf(\"json = %s\", out.String())\n+\t}\n+\tif _, hasAlias := decoded[1][\"alias\"]; hasAlias {\n+\t\tt.Fatalf(\"an empty alias is printed: %s\", out.String())\n+\t}\n+\n+\tout.Reset()\n+\tif err := printCaptureInterfaces(\n+\t\t&out,\n+\t\tnil,\n+\t\t\"json\",\n+\t); err != nil ||\n+\t\tstrings.TrimSpace(out.String()) != \"[]\" {\n+\t\tt.Fatalf(\"empty json = %q, %v\", out.String(), err)\n+\t}\n+\n+\tout.Reset()\n+\tif err := printCaptureInterfaces(&out, interfaces, \"table\"); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tfor _, want := range []string{\"Peer Interface\", \"ethernet-1/1\", \"srl1-e1-2\", \"N/A\"} {\n+\t\tif !strings.Contains(out.String(), want) {\n+\t\t\tt.Fatalf(\"table does not contain %q:\\n%s\", want, out.String())\n+\t\t}\n+\t}\n+}\ndiff --git a/cmd/context.go b/cmd/context.go\nindex 223cb1d..21d5bea 100644\n--- a/cmd/context.go\n+++ b/cmd/context.go\n@@ -51,10 +51,20 @@ func SignalHandledContext() (context.Context, context.CancelFunc) {\n \n \t\tcancel()\n \n \t\toptions := GetOptions()\n \n+\t\tif options.Global.FinishOnCancel.Load() {\n+\t\t\tlog.Info(\"Stopping, press Ctrl+C again to abort\")\n+\n+\t\t\tsig = <-sigs\n+\n+\t\t\tlog.Errorf(\"received signal %q while stopping, exiting\", sig)\n+\n+\t\t\tos.Exit(1)\n+\t\t}\n+\n \t\tif !options.Global.CleanOnCancel.Load() {\n \t\t\tlog.Debug(\"clean on cancel is not true, exiting\")\n \n \t\t\tos.Exit(1)\n \t\t}\ndiff --git a/cmd/inspect.go b/cmd/inspect.go\nindex 1b6f41d..55fb61f 100644\n--- a/cmd/inspect.go\n+++ b/cmd/inspect.go\n@@ -70,10 +70,14 @@ func inspectCmd(o *Options) (*cobra.Command, error) {\n \t\tShort: \"inspect interfaces of one or multiple nodes in a lab\",\n \t\tLong: \"show interfaces and their attributes in a specific deployed lab\\n\" +\n \t\t\t\"reference: https://containerlab.dev/cmd/inspect/interfaces/\",\n \t\tAliases: []string{\"int\", \"intf\"},\n \t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n+\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n+\t\t\t\treturn nil\n+\t\t\t}\n+\n \t\t\treturn clabutils.CheckAndGetRootPrivs()\n \t\t},\n \t\tRunE: func(cobraCmd *cobra.Command, _ []string) error {\n \t\t\treturn inspectInterfacesFn(cobraCmd, o)\n \t\t},\ndiff --git a/cmd/inspect_interfaces.go b/cmd/inspect_interfaces.go\nindex 0f64f03..91035c2 100644\n--- a/cmd/inspect_interfaces.go\n+++ b/cmd/inspect_interfaces.go\n@@ -33,10 +33,25 @@ func inspectInterfacesFn(cobraCmd *cobra.Command, o *Options) error {\n \tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"could not parse the topology file: %v\", err)\n \t}\n \n+\tif c.LabRuntime != nil {\n+\t\t// lab runtimes list the link interfaces packet capture accepts, with their state\n+\t\tcontainerInterfaces, err := c.LabRuntimeInterfaces(cobraCmd.Context(),\n+\t\t\to.Inspect.InterfacesNode)\n+\t\tif err != nil {\n+\t\t\treturn fmt.Errorf(\"failed to list node interfaces: %w\", err)\n+\t\t}\n+\t\tif len(containerInterfaces) == 0 {\n+\t\t\tlog.Info(\"no running nodes found\")\n+\t\t\treturn nil\n+\t\t}\n+\n+\t\treturn printContainerInterfaces(containerInterfaces, o.Inspect.InterfacesFormat)\n+\t}\n+\n \tvar labNameFilterLabel string\n \n \tswitch {\n \tcase o.Global.TopologyName != \"\":\n \t\tlabNameFilterLabel = o.Global.TopologyName\ndiff --git a/cmd/options.go b/cmd/options.go\nindex 8717d3b..6037551 100644\n--- a/cmd/options.go\n+++ b/cmd/options.go\n@@ -53,10 +53,14 @@ func GetOptions() *Options {\n \t\t\t\tInterfacesFormat: \"table\",\n \t\t\t},\n \t\t\tLogs: &LogsOptions{\n \t\t\t\tTail: -1,\n \t\t\t},\n+\t\t\tCapture: &CaptureOptions{\n+\t\t\t\tWrite:  \"-\",\n+\t\t\t\tFormat: \"table\",\n+\t\t\t},\n \t\t\tGraph: &GraphOptions{\n \t\t\t\tServer:           \"0.0.0.0:50080\",\n \t\t\t\tMermaidDirection: \"TD\",\n \t\t\t\tDrawIOVersion:    \"latest\",\n \t\t\t},\n@@ -142,10 +146,11 @@ type Options struct {\n \tExec           *ExecOptions\n \tInspect        *InspectOptions\n \tGraph          *GraphOptions\n \tEvents         *EventsOptions\n \tLogs           *LogsOptions\n+\tCapture        *CaptureOptions\n \tToolsAPI       *ToolsApiOptions\n \tToolsCert      *ToolsCertOptions\n \tToolsTxOffload *ToolsDisableTxOffloadOptions\n \tToolsGoTTY     *ToolsGoTTYOptions\n \tToolsNetem     *ToolsNetemOptions\n@@ -257,10 +262,15 @@ type GlobalOptions struct {\n \t// special flag that should only be set by deploy, informs the context handler to destroy\n \t// (or not) when root context is canceled. The signal handler goroutine reads it while\n \t// deploy is running, so it is atomic.\n \tCleanOnCancel atomic.Bool\n \n+\t// FinishOnCancel informs the context handler that the running command ends cleanly on its\n+\t// own once the root context is canceled (capture finishes its output), so the handler\n+\t// waits for it instead of exiting.\n+\tFinishOnCancel atomic.Bool\n+\n \t// special flag that is only set on deploy,\n \t// if true, the topology file backup is created at /tmp/.clab/bak\n \tBackupTopologyFile bool\n }\n \ndiff --git a/cmd/root.go b/cmd/root.go\nindex 0baf203..a9b1c8b 100644\n--- a/cmd/root.go\n+++ b/cmd/root.go\n@@ -35,10 +35,11 @@ func subcommandRegisterFuncs() []func(*Options) (*cobra.Command, error) {\n \t\tgenerateCmd,\n \t\tgraphCmd,\n \t\teventsCmd,\n \t\tinspectCmd,\n \t\tlogsCmd,\n+\t\tcaptureCmd,\n \t\tredeployCmd,\n \t\tsaveCmd,\n \t\ttoolsCmd,\n \t\tvalidateCmd,\n \t}\n@@ -263,15 +264,10 @@ func checkLabRuntimeCommandSupport(cobraCmd *cobra.Command, runtimeName string)\n \t\t\t\"the %q command needs running containers with lab runtime %q unless it renders \"+\n \t\t\t\t\"from the topology file alone; use --offline, --dot, --mermaid or --drawio\",\n \t\t\t\"graph\", runtimeName)\n \t}\n \n-\tif getCommandPath(cobraCmd) == \"inspect.interfaces\" {\n-\t\treturn fmt.Errorf(\"the %q command is not supported with lab runtime %q\",\n-\t\t\t\"inspect interfaces\", runtimeName)\n-\t}\n-\n \tvar unsupported []string\n \tfor _, flagName := range labRuntimeUnsupportedFlags[getCommandPath(cobraCmd)] {\n \t\tif labRuntimeFlagWasSet(cobraCmd, flagName) {\n \t\t\tunsupported = append(unsupported, \"--\"+flagName)\n \t\t}\n@@ -339,10 +335,11 @@ func getTopoFilePath(cobraCmd *cobra.Command, o *Options) error { // skipcq: GO-\n \t\tcobraCmd.Name() != \"inspect\" &&\n \t\tcobraCmd.Name() != \"save\" &&\n \t\tcobraCmd.Name() != \"graph\" &&\n \t\tcobraCmd.Name() != \"validate\" &&\n \t\tcobraCmd.Name() != \"logs\" &&\n+\t\tcobraCmd.Name() != \"capture\" &&\n \t\tcobraCmd.Name() != \"interfaces\" {\n \t\treturn nil\n \t}\n \n \t// start/stop/restart topology lookup applies only to top-level lifecycle commands.\ndiff --git a/cmd/root_test.go b/cmd/root_test.go\nindex 418a947..af02e34 100644\n--- a/cmd/root_test.go\n+++ b/cmd/root_test.go\n@@ -289,20 +289,23 @@ func TestCheckLabRuntimeFlagAndNestedCommandSupport(t *testing.T) {\n \t\t\t\tt.Fatalf(\"checkLabRuntimeCommandSupport() error = %v, wantErr %v\", err, tt.wantErr)\n \t\t\t}\n \t\t})\n \t}\n \n-\tt.Run(\"inspect interfaces rejected\", func(t *testing.T) {\n+\tt.Run(\"inspect interfaces and capture accepted\", func(t *testing.T) {\n \t\troot := &cobra.Command{Use: \"containerlab\"}\n \t\tinspect := &cobra.Command{Use: \"inspect\"}\n \t\tinterfaces := &cobra.Command{Use: \"interfaces\"}\n-\t\troot.AddCommand(inspect)\n+\t\tcapture := &cobra.Command{Use: \"capture\"}\n+\t\troot.AddCommand(inspect, capture)\n \t\tinspect.AddCommand(interfaces)\n \n-\t\tif err := checkLabRuntimeCommandSupport(\n-\t\t\tinterfaces,\n-\t\t\tclablabruntime.ClabernetesRuntimeName,\n-\t\t); err == nil {\n-\t\t\tt.Fatal(\"inspect interfaces was accepted for clabernetes\")\n+\t\tfor _, cmd := range []*cobra.Command{interfaces, capture} {\n+\t\t\tif err := checkLabRuntimeCommandSupport(\n+\t\t\t\tcmd,\n+\t\t\t\tclablabruntime.ClabernetesRuntimeName,\n+\t\t\t); err != nil {\n+\t\t\t\tt.Fatalf(\"%s rejected for clabernetes: %v\", cmd.Name(), err)\n+\t\t\t}\n \t\t}\n \t})\n }\ndiff --git a/core/capture.go b/core/capture.go\nnew file mode 100644\nindex 0000000..2e12fc2\n--- /dev/null\n+++ b/core/capture.go\n@@ -0,0 +1,93 @@\n+package core\n+\n+import (\n+\t\"context\"\n+\t\"io\"\n+\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tclabtypes \"github.com/srl-labs/containerlab/types\"\n+)\n+\n+// CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for\n+// every running node, with the peer at the other end of each link. With Docker and Podman, the\n+// interfaces come from the topology's links; lab runtimes list them through their packet\n+// capturer.\n+func (c *CLab) CaptureInterfaces(\n+\tctx context.Context,\n+\tnodeNames ...string,\n+) ([]clablabruntime.CaptureInterface, error) {\n+\tif c.LabRuntime == nil {\n+\t\treturn c.localCaptureInterfacesOf(ctx, nodeNames)\n+\t}\n+\n+\tcapturer, err := c.packetCapturer()\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treturn capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{\n+\t\tName:     c.Config.Name,\n+\t\tNodes:    nodeNames,\n+\t\tIdentity: c.labRuntimeIdentity,\n+\t})\n+}\n+\n+// Capture streams pcapng from lab link interfaces to w until req.Duration passed,\n+// req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name\n+// and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces\n+// itself through packet sockets in the nodes' network namespaces, which needs root; lab\n+// runtimes capture through their packet capturer.\n+func (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {\n+\tif c.LabRuntime == nil {\n+\t\treturn c.captureLocal(ctx, req, w)\n+\t}\n+\n+\tcapturer, err := c.packetCapturer()\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tif req.Name == \"\" {\n+\t\treq.Name = c.Config.Name\n+\t}\n+\tif req.Identity.IsZero() {\n+\t\treq.Identity = c.labRuntimeIdentity\n+\t}\n+\n+\treturn capturer.Capture(ctx, req, w)\n+}\n+\n+// LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their\n+// state, in the shape ListContainersInterfaces reports for local containers.\n+func (c *CLab) LabRuntimeInterfaces(\n+\tctx context.Context,\n+\tnodeName string,\n+) ([]*clabtypes.ContainerInterfaces, error) {\n+\tinspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](\n+\t\tc, \"inspecting interfaces\")\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tif err := c.requireLabName(); err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treq := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}\n+\tif nodeName != \"\" {\n+\t\treq.Nodes = []string{nodeName}\n+\t}\n+\n+\treturn inspector.InspectInterfaces(ctx, req)\n+}\n+\n+func (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {\n+\tcapturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, \"packet capture\")\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tif err := c.requireLabName(); err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treturn capturer, nil\n+}\ndiff --git a/core/capture_local.go b/core/capture_local.go\nnew file mode 100644\nindex 0000000..fada0bf\n--- /dev/null\n+++ b/core/capture_local.go\n@@ -0,0 +1,255 @@\n+package core\n+\n+import (\n+\t\"context\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"slices\"\n+\t\"sort\"\n+\t\"strings\"\n+\n+\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tclablinks \"github.com/srl-labs/containerlab/links\"\n+\tclabnodes \"github.com/srl-labs/containerlab/nodes\"\n+\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n+)\n+\n+// localCaptureInterface is a lab link interface of a node on this machine.\n+type localCaptureInterface struct {\n+\tnode clabnodes.Node\n+\tinfo clablabruntime.CaptureInterface\n+}\n+\n+// localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with\n+// the far end of each link, per node name. Host and management network endpoints are the far\n+// ends of links, not nodes to capture on.\n+func (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {\n+\tif len(c.Nodes) == 0 {\n+\t\treturn nil, fmt.Errorf(\"the topology of lab %q is not available; capture reads the \"+\n+\t\t\t\"lab's links from it, pass it with --topo\", c.Config.Name)\n+\t}\n+\tif len(c.Links) == 0 {\n+\t\tif err := c.ResolveLinks(); err != nil {\n+\t\t\treturn nil, fmt.Errorf(\"failed to resolve the links of lab %q: %w\", c.Config.Name, err)\n+\t\t}\n+\t}\n+\n+\tindexes := make([]int, 0, len(c.Links))\n+\tfor idx := range c.Links {\n+\t\tindexes = append(indexes, idx)\n+\t}\n+\tsort.Ints(indexes)\n+\n+\tresult := map[string][]localCaptureInterface{}\n+\tfor _, idx := range indexes {\n+\t\tendpoints := c.Links[idx].GetEndpoints()\n+\t\tfor epIdx, endpoint := range endpoints {\n+\t\t\tif endpoint.IsNodeless() || endpoint.IsRuntimeDiscovered() ||\n+\t\t\t\tendpoint.GetNode() == nil {\n+\t\t\t\tcontinue\n+\t\t\t}\n+\t\t\tname := endpoint.GetNode().GetShortName()\n+\t\t\tnode, ok := c.Nodes[name]\n+\t\t\tif !ok {\n+\t\t\t\tcontinue\n+\t\t\t}\n+\n+\t\t\tinfo := clablabruntime.CaptureInterface{\n+\t\t\t\tNode:      name,\n+\t\t\t\tInterface: endpoint.GetIfaceName(),\n+\t\t\t}\n+\t\t\tif alias := endpoint.GetIfaceAlias(); alias != info.Interface {\n+\t\t\t\tinfo.Alias = alias\n+\t\t\t}\n+\t\t\tif len(endpoints) == 2 {\n+\t\t\t\tpeer := endpoints[1-epIdx]\n+\t\t\t\tinfo.PeerNode = capturePeerNode(peer)\n+\t\t\t\tinfo.PeerInterface = peer.GetIfaceDisplayName()\n+\t\t\t}\n+\n+\t\t\tresult[name] = append(result[name], localCaptureInterface{node: node, info: info})\n+\t\t}\n+\t}\n+\n+\treturn result, nil\n+}\n+\n+// capturePeerNode names the node at the far end of a link: \"host\" for a host endpoint and\n+// \"mgmt-net\" for the management network, whose shared link nodes carry other names once a lab\n+// was deployed.\n+func capturePeerNode(peer clablinks.Endpoint) string {\n+\tif peer.IsNodeless() {\n+\t\tif _, ok := peer.(*clablinks.EndpointBridge); ok {\n+\t\t\treturn string(clablinks.LinkTypeMgmtNet)\n+\t\t}\n+\n+\t\treturn string(clablinks.LinkTypeHost)\n+\t}\n+\tif peer.GetNode() == nil {\n+\t\treturn \"\"\n+\t}\n+\n+\treturn peer.GetNode().GetShortName()\n+}\n+\n+// lookupLocalNode finds a lab node by its topology name or its container name.\n+func (c *CLab) lookupLocalNode(name string) (clabnodes.Node, error) {\n+\tif node, ok := c.Nodes[name]; ok {\n+\t\treturn node, nil\n+\t}\n+\tfor _, node := range c.Nodes {\n+\t\tif node.Config().LongName == name {\n+\t\t\treturn node, nil\n+\t\t}\n+\t}\n+\n+\tnames := make([]string, 0, len(c.Nodes))\n+\tfor nodeName := range c.Nodes {\n+\t\tnames = append(names, nodeName)\n+\t}\n+\tslices.Sort(names)\n+\n+\treturn nil, fmt.Errorf(\"node %q is not part of lab %q; nodes: %s\", name, c.Config.Name,\n+\t\tstrings.Join(names, \", \"))\n+}\n+\n+// nodeRuns reports whether a node's network namespace can be entered.\n+func nodeRuns(ctx context.Context, node clabnodes.Node) bool {\n+\tif node.Config().IsRootNamespaceBased {\n+\t\treturn true\n+\t}\n+\n+\treturn clabruntime.ContainerHasJoinableNetns(node.GetContainerStatus(ctx))\n+}\n+\n+// localCaptureInterfacesOf implements CaptureInterfaces for Docker and Podman: the requested\n+// nodes, or every running node.\n+func (c *CLab) localCaptureInterfacesOf(\n+\tctx context.Context,\n+\tnodeNames []string,\n+) ([]clablabruntime.CaptureInterface, error) {\n+\tif err := c.requireLabName(); err != nil {\n+\t\treturn nil, err\n+\t}\n+\tbyNode, err := c.localCaptureInterfaces()\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\tvar nodes []clabnodes.Node\n+\tif len(nodeNames) == 0 {\n+\t\tfor _, node := range c.Nodes {\n+\t\t\tif nodeRuns(ctx, node) {\n+\t\t\t\tnodes = append(nodes, node)\n+\t\t\t}\n+\t\t}\n+\t} else {\n+\t\tfor _, name := range nodeNames {\n+\t\t\tnode, err := c.lookupLocalNode(name)\n+\t\t\tif err != nil {\n+\t\t\t\treturn nil, err\n+\t\t\t}\n+\t\t\tnodes = append(nodes, node)\n+\t\t}\n+\t}\n+\n+\tresult := make([]clablabruntime.CaptureInterface, 0)\n+\tseen := map[string]bool{}\n+\tfor _, node := range nodes {\n+\t\tname := node.Config().ShortName\n+\t\tif seen[name] {\n+\t\t\tcontinue\n+\t\t}\n+\t\tseen[name] = true\n+\t\tfor _, entry := range byNode[name] {\n+\t\t\tresult = append(result, entry.info)\n+\t\t}\n+\t}\n+\tsortCaptureInterfaces(result)\n+\n+\treturn result, nil\n+}\n+\n+func sortCaptureInterfaces(interfaces []clablabruntime.CaptureInterface) {\n+\tsort.SliceStable(interfaces, func(i, j int) bool {\n+\t\tif interfaces[i].Node != interfaces[j].Node {\n+\t\t\treturn interfaces[i].Node < interfaces[j].Node\n+\t\t}\n+\n+\t\treturn interfaces[i].Interface < interfaces[j].Interface\n+\t})\n+}\n+\n+// resolveLocalCaptureTargets checks every target against the node's link interfaces, by name or\n+// alias, and returns them in request order.\n+func (c *CLab) resolveLocalCaptureTargets(\n+\ttargets []clablabruntime.CaptureTarget,\n+) ([]clabcapture.LocalTarget, error) {\n+\tbyNode, err := c.localCaptureInterfaces()\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\tresolved := make([]clabcapture.LocalTarget, 0, len(targets))\n+\tseen := map[string]bool{}\n+\tfor _, target := range targets {\n+\t\tnode, err := c.lookupLocalNode(target.Node)\n+\t\tif err != nil {\n+\t\t\treturn nil, err\n+\t\t}\n+\t\tname := node.Config().ShortName\n+\n+\t\tinfos := make([]clablabruntime.CaptureInterface, 0, len(byNode[name]))\n+\t\tfor _, entry := range byNode[name] {\n+\t\t\tinfos = append(infos, entry.info)\n+\t\t}\n+\t\tsortCaptureInterfaces(infos)\n+\t\tinfo, ok := clabcapture.FindInterface(infos, target.Interface)\n+\t\tif !ok {\n+\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n+\t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n+\t\t\t\tclabcapture.DescribeInterfaces(infos))\n+\t\t}\n+\n+\t\tkey := name + \"\\x00\" + info.Interface\n+\t\tif seen[key] {\n+\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n+\t\t\t\tinfo.Interface, target.Node)\n+\t\t}\n+\t\tseen[key] = true\n+\n+\t\tresolved = append(resolved, clabcapture.LocalTarget{\n+\t\t\tNode:      name,\n+\t\t\tInterface: info.Interface,\n+\t\t\tExec:      node.ExecFunction,\n+\t\t})\n+\t}\n+\n+\treturn resolved, nil\n+}\n+\n+// captureLocal implements Capture for Docker and Podman through packet sockets in the nodes'\n+// network namespaces.\n+func (c *CLab) captureLocal(\n+\tctx context.Context,\n+\treq clablabruntime.CaptureRequest,\n+\tw io.Writer,\n+) error {\n+\tif err := c.requireLabName(); err != nil {\n+\t\treturn err\n+\t}\n+\tif req.Name == \"\" {\n+\t\treq.Name = c.Config.Name\n+\t}\n+\tif err := clabcapture.ValidateRequest(&req); err != nil {\n+\t\treturn err\n+\t}\n+\n+\ttargets, err := c.resolveLocalCaptureTargets(req.Targets)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\treturn clabcapture.CaptureLocal(ctx, req, targets, w)\n+}\ndiff --git a/core/capture_test.go b/core/capture_test.go\nnew file mode 100644\nindex 0000000..b5d34b0\n--- /dev/null\n+++ b/core/capture_test.go\n@@ -0,0 +1,210 @@\n+package core\n+\n+import (\n+\t\"bytes\"\n+\t\"context\"\n+\t\"io\"\n+\t\"slices\"\n+\t\"strings\"\n+\t\"testing\"\n+\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tclabtypes \"github.com/srl-labs/containerlab/types\"\n+)\n+\n+// captureLabRuntime records the capture requests core sends.\n+type captureLabRuntime struct {\n+\tclablabruntime.LabRuntime\n+\n+\tnodeRequest    clablabruntime.NodeRequest\n+\tcaptureRequest clablabruntime.CaptureRequest\n+}\n+\n+func (r *captureLabRuntime) CaptureInterfaces(\n+\t_ context.Context,\n+\treq clablabruntime.NodeRequest,\n+) ([]clablabruntime.CaptureInterface, error) {\n+\tr.nodeRequest = req\n+\n+\treturn []clablabruntime.CaptureInterface{{Node: \"r1\", Interface: \"eth1\"}}, nil\n+}\n+\n+func (r *captureLabRuntime) Capture(\n+\t_ context.Context,\n+\treq clablabruntime.CaptureRequest,\n+\tw io.Writer,\n+) error {\n+\tr.captureRequest = req\n+\t_, err := io.WriteString(w, \"pcapng\")\n+\n+\treturn err\n+}\n+\n+func (r *captureLabRuntime) InspectInterfaces(\n+\t_ context.Context,\n+\treq clablabruntime.NodeRequest,\n+) ([]*clabtypes.ContainerInterfaces, error) {\n+\tr.nodeRequest = req\n+\n+\treturn []*clabtypes.ContainerInterfaces{{ContainerName: \"lab1-r1\"}}, nil\n+}\n+\n+func TestCaptureHelpersFillLabAndIdentity(t *testing.T) {\n+\tt.Parallel()\n+\n+\tlr := &captureLabRuntime{}\n+\tc := newAccessTestCLab(lr)\n+\tctx := context.Background()\n+\n+\tinterfaces, err := c.CaptureInterfaces(ctx, \"R1\")\n+\tif err != nil || len(interfaces) != 1 {\n+\t\tt.Fatalf(\"CaptureInterfaces() = %+v, %v\", interfaces, err)\n+\t}\n+\tif lr.nodeRequest.Name != \"lab1\" || lr.nodeRequest.Nodes[0] != \"R1\" ||\n+\t\t!lr.nodeRequest.Identity.Equal(testIdentity) {\n+\t\tt.Fatalf(\"interfaces request = %+v\", lr.nodeRequest)\n+\t}\n+\n+\tvar out bytes.Buffer\n+\tif err := c.Capture(ctx, clablabruntime.CaptureRequest{\n+\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n+\t}, &out); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif out.String() != \"pcapng\" || lr.captureRequest.Name != \"lab1\" ||\n+\t\t!lr.captureRequest.Identity.Equal(testIdentity) {\n+\t\tt.Fatalf(\"capture request = %+v, output %q\", lr.captureRequest, out.String())\n+\t}\n+\n+\tifaces, err := c.LabRuntimeInterfaces(ctx, \"r1\")\n+\tif err != nil || len(ifaces) != 1 || lr.nodeRequest.Nodes[0] != \"r1\" {\n+\t\tt.Fatalf(\"LabRuntimeInterfaces() = %+v, %v, request %+v\", ifaces, err, lr.nodeRequest)\n+\t}\n+\tif _, err := c.LabRuntimeInterfaces(ctx, \"\"); err != nil || lr.nodeRequest.Nodes != nil {\n+\t\tt.Fatalf(\"all nodes request = %+v, %v\", lr.nodeRequest, err)\n+\t}\n+}\n+\n+// newLocalCaptureCLab loads the capture test topology. Its host and mgmt-net links register\n+// endpoints on link nodes the whole process shares, so the tests using it do not run in\n+// parallel and release the endpoints when they end.\n+func newLocalCaptureCLab(t *testing.T) *CLab {\n+\tt.Helper()\n+\n+\tc, err := NewContainerLab(WithTopoPath(\"test_data/capture.clab.yml\", nil))\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tt.Cleanup(c.resetResolvedLinks)\n+\n+\treturn c\n+}\n+\n+func TestLocalCaptureInterfacesComeFromTheTopologyLinks(t *testing.T) {\n+\tc := newLocalCaptureCLab(t)\n+\n+\tgot, err := c.CaptureInterfaces(context.Background(), \"srl1\", \"client\")\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\twant := []clablabruntime.CaptureInterface{\n+\t\t{Node: \"client\", Interface: \"eth1\", PeerNode: \"srl1\", PeerInterface: \"e1-2\"},\n+\t\t{Node: \"client\", Interface: \"eth2\", PeerNode: \"host\", PeerInterface: \"client-eth2\"},\n+\t\t{Node: \"client\", Interface: \"eth3\", PeerNode: \"mgmt-net\", PeerInterface: \"client-eth3\"},\n+\t\t{\n+\t\t\tNode: \"srl1\", Interface: \"e1-1\", Alias: \"ethernet-1/1\",\n+\t\t\tPeerNode: \"srl2\", PeerInterface: \"e1-1\",\n+\t\t},\n+\t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"client\", PeerInterface: \"eth1\"},\n+\t}\n+\tif !slices.Equal(got, want) {\n+\t\tt.Fatalf(\"CaptureInterfaces() =\\n%+v\\nwant\\n%+v\", got, want)\n+\t}\n+\n+\tif _, err := c.CaptureInterfaces(context.Background(), \"r9\"); err == nil ||\n+\t\t!strings.Contains(err.Error(), `node \"r9\" is not part of lab \"capture\"`) {\n+\t\tt.Fatalf(\"unknown node: error = %v\", err)\n+\t}\n+}\n+\n+func TestLocalCaptureTargetsResolveByNameOrAlias(t *testing.T) {\n+\tc := newLocalCaptureCLab(t)\n+\n+\ttargets, err := c.resolveLocalCaptureTargets([]clablabruntime.CaptureTarget{\n+\t\t{Node: \"srl2\", Interface: \"e1-1\"},\n+\t\t{Node: \"srl1\", Interface: \"ethernet-1/1\"},\n+\t\t{Node: \"clab-capture-client\", Interface: \"eth2\"},\n+\t})\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tvar got []string\n+\tfor _, target := range targets {\n+\t\tif target.Exec == nil {\n+\t\t\tt.Fatalf(\"target %s:%s has no namespace exec\", target.Node, target.Interface)\n+\t\t}\n+\t\tgot = append(got, target.Node+\":\"+target.Interface)\n+\t}\n+\tif want := []string{\"srl2:e1-1\", \"srl1:e1-1\", \"client:eth2\"}; !slices.Equal(got, want) {\n+\t\tt.Fatalf(\"targets = %v, want %v\", got, want)\n+\t}\n+\n+\tfor _, tc := range []struct {\n+\t\tname    string\n+\t\ttargets []clablabruntime.CaptureTarget\n+\t\twant    string\n+\t}{\n+\t\t{\n+\t\t\tname:    \"management interface\",\n+\t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"client\", Interface: \"eth0\"}},\n+\t\t\twant: `interface \"eth0\" of node \"client\" is not a capturable link interface; ` +\n+\t\t\t\t\"capturable: eth1, eth2, eth3\",\n+\t\t},\n+\t\t{\n+\t\t\tname: \"same interface twice\",\n+\t\t\ttargets: []clablabruntime.CaptureTarget{\n+\t\t\t\t{Node: \"srl1\", Interface: \"e1-1\"}, {Node: \"srl1\", Interface: \"ethernet-1/1\"},\n+\t\t\t},\n+\t\t\twant: `interface \"e1-1\" of node \"srl1\" is requested more than once`,\n+\t\t},\n+\t\t{\n+\t\t\tname:    \"unknown node\",\n+\t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"r9\", Interface: \"eth1\"}},\n+\t\t\twant:    `node \"r9\" is not part of lab \"capture\"`,\n+\t\t},\n+\t} {\n+\t\tif _, err := c.resolveLocalCaptureTargets(tc.targets); err == nil ||\n+\t\t\t!strings.Contains(err.Error(), tc.want) {\n+\t\t\tt.Errorf(\"%s: error = %v, want %q\", tc.name, err, tc.want)\n+\t\t}\n+\t}\n+}\n+\n+func TestLocalCaptureNeedsTheTopology(t *testing.T) {\n+\tt.Parallel()\n+\n+\tc := &CLab{Config: &Config{Name: \"lab1\"}, globalRuntimeName: \"docker\"}\n+\terr := c.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n+\t}, io.Discard)\n+\tif err == nil || !strings.Contains(err.Error(), `the topology of lab \"lab1\" is not available`) {\n+\t\tt.Fatalf(\"error = %v\", err)\n+\t}\n+\tif err := c.Capture(context.Background(), clablabruntime.CaptureRequest{},\n+\t\tio.Discard); err == nil || !strings.Contains(err.Error(), \"at least one capture target\") {\n+\t\tt.Fatalf(\"no targets: error = %v\", err)\n+\t}\n+}\n+\n+func TestLabRuntimeWithoutCaptureFails(t *testing.T) {\n+\tt.Parallel()\n+\n+\tunsupported := newAccessTestCLab(&recordingDestroyLabRuntime{})\n+\tif err := unsupported.Capture(\n+\t\tcontext.Background(),\n+\t\tclablabruntime.CaptureRequest{},\n+\t\tio.Discard,\n+\t); err == nil || !strings.Contains(err.Error(), \"does not support packet capture\") {\n+\t\tt.Fatalf(\"lab runtime without capture: error = %v\", err)\n+\t}\n+}\ndiff --git a/core/labruntime_cluster_test.go b/core/labruntime_cluster_test.go\nindex 06ecf57..981a302 100644\n--- a/core/labruntime_cluster_test.go\n+++ b/core/labruntime_cluster_test.go\n@@ -1,10 +1,11 @@\n package core\n \n import (\n \t\"bytes\"\n \t\"context\"\n+\t\"encoding/binary\"\n \t\"errors\"\n \t\"io\"\n \t\"net\"\n \t\"net/http\"\n \t\"os\"\n@@ -175,5 +176,153 @@ func TestC9sClusterNodeAccess(t *testing.T) {\n \t\tif err == nil || !strings.Contains(err.Error(), \"forbidden\") {\n \t\t\tt.Fatalf(\"impersonated user without rights: error = %v, want forbidden\", err)\n \t\t}\n \t})\n }\n+\n+// TestC9sClusterCapture captures through the library against a deployed c9s lab, as an identity\n+// that holds only the clabernetes-lab-editor role in the lab namespace. It runs only when\n+// CLAB_C9S_TEST_LAB names the lab and CLAB_C9S_TEST_CAPTURE_USER the identity (tests/14-clabernetes\n+// sets both). The lab must have linux nodes \"client\" (10.10.10.1) and \"server\" (10.10.10.2)\n+// linked by eth1. CLAB_C9S_TEST_FORBIDDEN_USER names an identity without a binding.\n+func TestC9sClusterCapture(t *testing.T) {\n+\tlab := os.Getenv(\"CLAB_C9S_TEST_LAB\")\n+\tuser := os.Getenv(\"CLAB_C9S_TEST_CAPTURE_USER\")\n+\tif lab == \"\" || user == \"\" {\n+\t\tt.Skip(\"CLAB_C9S_TEST_LAB or CLAB_C9S_TEST_CAPTURE_USER is not set\")\n+\t}\n+\n+\tnewCLab := func(t *testing.T, user string) *CLab {\n+\t\tt.Helper()\n+\n+\t\tc, err := NewContainerLab(\n+\t\t\tWithRuntime(clablabruntime.ClabernetesRuntimeName, nil),\n+\t\t\tWithTopologyName(lab),\n+\t\t\tWithLabRuntimeIdentity(clablabruntime.Identity{User: user}),\n+\t\t)\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\n+\t\treturn c\n+\t}\n+\tc := newCLab(t, user)\n+\n+\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)\n+\tdefer cancel()\n+\n+\tt.Run(\"version check\", func(t *testing.T) {\n+\t\tif err := c.CheckLabRuntimeSupport(ctx); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t})\n+\n+\tt.Run(\"capture interfaces\", func(t *testing.T) {\n+\t\tinterfaces, err := c.CaptureInterfaces(ctx)\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\twant := []clablabruntime.CaptureInterface{\n+\t\t\t{Node: \"client\", Interface: \"eth1\", PeerNode: \"server\", PeerInterface: \"eth1\"},\n+\t\t\t{Node: \"server\", Interface: \"eth1\", PeerNode: \"client\", PeerInterface: \"eth1\"},\n+\t\t}\n+\t\tif len(interfaces) != 2 || interfaces[0] != want[0] || interfaces[1] != want[1] {\n+\t\t\tt.Fatalf(\"interfaces = %+v\", interfaces)\n+\t\t}\n+\t})\n+\n+\tt.Run(\"capture both ends of a link\", func(t *testing.T) {\n+\t\tpinged := make(chan error, 1)\n+\t\tgo func() {\n+\t\t\ttime.Sleep(time.Second)\n+\t\t\tpinged <- c.AttachLabRuntimeNode(ctx, clablabruntime.AttachRequest{\n+\t\t\t\tNodeName: \"client\",\n+\t\t\t\tCommand:  []string{\"ping\", \"-c\", \"4\", \"-i\", \"0.3\", \"10.10.10.2\"},\n+\t\t\t}, clablabruntime.AttachStreams{Stdout: io.Discard})\n+\t\t}()\n+\n+\t\tvar out bytes.Buffer\n+\t\terr := c.Capture(ctx, clablabruntime.CaptureRequest{\n+\t\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t\t{Node: \"client\", Interface: \"eth1\"}, {Node: \"server\", Interface: \"eth1\"},\n+\t\t\t},\n+\t\t\tDuration: 5 * time.Second,\n+\t\t}, &out)\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\tif err := <-pinged; err != nil {\n+\t\t\tt.Fatalf(\"ping: %v\", err)\n+\t\t}\n+\n+\t\tnames, icmp := summarizePCAPNG(t, out.Bytes())\n+\t\tif len(names) != 2 || names[0] != \"client:eth1\" || names[1] != \"server:eth1\" {\n+\t\t\tt.Fatalf(\"interfaces = %v\", names)\n+\t\t}\n+\t\t// every echo request and reply crosses both ends\n+\t\tif icmp[0] < 8 || icmp[1] < 8 {\n+\t\t\tt.Fatalf(\"ICMP packets per interface = %v, want at least 8 on each\", icmp)\n+\t\t}\n+\t})\n+\n+\tt.Run(\"restart as lab editor\", func(t *testing.T) {\n+\t\tif err := c.RestartNodes(ctx, []string{\"server\"}); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t})\n+\n+\tt.Run(\"forbidden identity\", func(t *testing.T) {\n+\t\tforbidden := os.Getenv(\"CLAB_C9S_TEST_FORBIDDEN_USER\")\n+\t\tif forbidden == \"\" {\n+\t\t\tt.Skip(\"CLAB_C9S_TEST_FORBIDDEN_USER is not set\")\n+\t\t}\n+\n+\t\terr := newCLab(t, forbidden).Capture(ctx, clablabruntime.CaptureRequest{\n+\t\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"client\", Interface: \"eth1\"}},\n+\t\t\tDuration: time.Second,\n+\t\t}, io.Discard)\n+\t\tif err == nil || !strings.Contains(err.Error(), \"forbidden\") {\n+\t\t\tt.Fatalf(\"capture as %s = %v, want forbidden\", forbidden, err)\n+\t\t}\n+\t})\n+}\n+\n+// summarizePCAPNG returns the interface names of a little-endian pcapng stream and its IPv4 ICMP\n+// packets per interface ID.\n+func summarizePCAPNG(t *testing.T, data []byte) ([]string, map[uint32]int) {\n+\tt.Helper()\n+\n+\tvar names []string\n+\ticmp := map[uint32]int{}\n+\tfor len(data) >= 12 {\n+\t\tblockType := binary.LittleEndian.Uint32(data[0:4])\n+\t\tlength := int(binary.LittleEndian.Uint32(data[4:8]))\n+\t\tif length < 12 || length > len(data) {\n+\t\t\tt.Fatalf(\"invalid block length %d\", length)\n+\t\t}\n+\t\tbody := data[8 : length-4]\n+\t\tswitch blockType {\n+\t\tcase 1: // Interface Description Block\n+\t\t\toptions := body[8:]\n+\t\t\tfor len(options) >= 4 {\n+\t\t\t\tcode := binary.LittleEndian.Uint16(options[0:2])\n+\t\t\t\tsize := int(binary.LittleEndian.Uint16(options[2:4]))\n+\t\t\t\tif code == 0 {\n+\t\t\t\t\tbreak\n+\t\t\t\t}\n+\t\t\t\tif code == 2 {\n+\t\t\t\t\tnames = append(names, string(options[4:4+size]))\n+\t\t\t\t}\n+\t\t\t\toptions = options[4+size+(4-size%4)%4:]\n+\t\t\t}",
        "lineStart": 1702,
        "lineEnd": 3477,
        "totalLines": 3478,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523230771,
      "end": 1793523230793
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19650a84e001xB9BKr8hFdXJBR",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196509cac001qwe5hzZrXtg7xQ",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 25522,
    "input": 25501,
    "output": 20,
    "reasoning": 1,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196509cac001qwe5hzZrXtg7xQ",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523227820,
    "completed": 1793523230802
  },
  "parentID": "msg_196508bbe001tLsHPkKW57hw60",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 25522,
    "input": 25501,
    "output": 20,
    "reasoning": 1,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 6
step-start
{
  "type": "step-start",
  "id": "prt_19650b2ad001y2LI1XaMOpP5IJ",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650a855001ooGiCUj8bm23MA"
}
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "offset": 3478
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
3478: +		case 6: // Enhanced Packet Block
3479: +			id := binary.LittleEndian.Uint32(body[0:4])
3480: +			frame := body[20 : 20+binary.LittleEndian.Uint32(body[12:16])]
3481: +			if len(frame) > 23 && frame[12] == 0x08 && frame[13] == 0x00 && frame[23] == 1 {
3482: +				icmp[id]++
3483: +			}
3484: +		}
3485: +		data = data[length:]
3486: +	}
3487: +
3488: +	return names, icmp
3489: +}
3490: diff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml
3491: new file mode 100644
3492: index 0000000..0422c22
3493: --- /dev/null
3494: +++ b/core/test_data/capture.clab.yml
3495: @@ -0,0 +1,15 @@
3496: +name: capture
3497: +topology:
3498: +  nodes:
3499: +    srl1:
3500: +      kind: nokia_srlinux
3501: +    srl2:
3502: +      kind: nokia_srlinux
3503: +    client:
3504: +      kind: linux
3505: +      image: alpine:3
3506: +  links:
3507: +    - endpoints: ["srl1:ethernet-1/1", "srl2:e1-1"]
3508: +    - endpoints: ["srl1:e1-2", "client:eth1"]
3509: +    - endpoints: ["client:eth2", "host:client-eth2"]
3510: +    - endpoints: ["client:eth3", "mgmt-net:client-eth3"]
3511: diff --git a/docs/cmd/capture.md b/docs/cmd/capture.md
3512: new file mode 100644
3513: index 0000000..15006ff
3514: --- /dev/null
3515: +++ b/docs/cmd/capture.md
3516: @@ -0,0 +1,134 @@
3517: +# capture command
3518: +
3519: +### Description
3520: +
3521: +The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.
3522: +
3523: +It works with every runtime:
3524: +
3525: +- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).
3526: +- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).
3527: +
3528: +The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.
3529: +
3530: +--8<-- "docs/cmd/deploy.md:env-vars-flags"
3531: +
3532: +### Usage
3533: +
3534: +`containerlab [global-flags] capture [local-flags]`
3535: +
3536: +### Flags
3537: +
3538: +#### topology | name
3539: +
3540: +Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.
3541: +
3542: +With Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.
3543: +
3544: +#### target
3545: +
3546: +The local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:
3547: +
3548: +```text
3549: +--target srl1:e1-1,e1-2 --target srl2:e1-1
3550: +```
3551: +
3552: +The node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.
3553: +
3554: +Only lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.
3555: +
3556: +#### duration
3557: +
3558: +The local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).
3559: +
3560: +#### packet-limit
3561: +
3562: +The local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.
3563: +
3564: +#### snap-length
3565: +
3566: +The local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.
3567: +
3568: +#### write
3569: +
3570: +The local `--write | -w` flag names the output file. The default `-` writes to stdout.
3571: +
3572: +#### list
3573: +
3574: +The local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.
3575: +
3576: +### Output
3577: +
3578: +The output is one pcapng section:
3579: +
3580: +- a Section Header Block with `shb_userappl` set to `containerlab`
3581: +- one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it
3582: +- Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes
3583: +
3584: +The interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.
3585: +
3586: +When the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.
3587: +
3588: +`--list -f json` prints an array:
3589: +
3590: +```json
3591: +[
3592: +  {
3593: +    "node": "srl1",
3594: +    "interface": "e1-1",
3595: +    "alias": "ethernet-1/1",
3596: +    "peer_node": "srl2",
3597: +    "peer_interface": "ethernet-1/1"
3598: +  }
3599: +]
3600: +```
3601: +
3602: +`alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.
3603: +
3604: +### How Docker and Podman captures work
3605: +
3606: +For each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.
3607: +
3608: +- Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.
3609: +- 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.
3610: +- Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.
3611: +- An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.
3612: +
3613: +The command needs root (to open packet sockets and enter network namespaces), as other lab commands do.
3614: +
3615: +### Long captures
3616: +
3617: +Docker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.
3618: +
3619: +### Examples
3620: +
3621: +#### Capture two nodes for 30 seconds into one file
3622: +
3623: +```bash
3624: +containerlab capture -t srl.clab.yml \
3625: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng
3626: +```
3627: +
3628: +#### Watch a capture live in Wireshark
3629: +
3630: +```bash
3631: +containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -
3632: +```
3633: +
3634: +#### Capture the first 100 packets with tshark
3635: +
3636: +```bash
3637: +containerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -
3638: +```
3639: +
3640: +#### List the capturable interfaces
3641: +
3642: +```bash
3643: +containerlab capture --name srl --list
3644: +```
3645: +
3646: +#### Capture a c9s lab
3647: +
3648: +```bash
3649: +containerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng
3650: +```
3651: diff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md
3652: index 3dc8e27..2354dc1 100644
3653: --- a/docs/cmd/inspect/interfaces.md
3654: +++ b/docs/cmd/inspect/interfaces.md
3655: @@ -3,10 +3,12 @@
3656:  ### Description
3657:  
3658:  The `inspect interfaces` subcommand provides information about the network interfaces of deployed nodes of a deployed lab.
3659:  The subcommand gathers information directly from deployed containers, and displays information about their operational state, network interface type, and if applicable, the applied network interface alias.
3660:  
3661: +With the [c9s runtime](../../manual/clabernetes/runtime.md#packet-capture), the listing covers the lab link interfaces of each running node, the ones [`capture`](../capture.md) accepts, with the alias the topology used, and the MAC address, index, MTU and operational state read in the node's device container. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields are the same as with Docker.
3662: +
3663:  ### Usage
3664:  
3665:  `containerlab [global-flags] inspect interfaces [local-flags]`
3666:  
3667:  A shorthand can be used for this subcommand: `int` or `intf`.
3668: diff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md
3669: index 0ce708d..8174c98 100644
3670: --- a/docs/manual/clabernetes/runtime.md
3671: +++ b/docs/manual/clabernetes/runtime.md
3672: @@ -110,10 +110,13 @@ The c9s runtime currently supports the main lab lifecycle and node operations:
3673:  | `start` | sets the node's `spec.runState` to `Running` |
3674:  | `stop` | sets the node's `spec.runState` to `Stopped` |
3675:  | `restart` | requests a Pod replacement with a `c9s.run/restart-requested` token |
3676:  | `save` | runs the node's save lifecycle inside its device container |
3677:  | `events` | watches Clabernetes resources and pods |
3678: +| `logs` | streams the device container log |
3679: +| `capture` | captures lab link interfaces through the `clabwire` sidecar into one pcapng stream |
3680: +| `inspect interfaces` | lists the capturable link interfaces with their sysfs state |
3681:  | `validate` | checks c9s compatibility without creating Kubernetes resources |
3682:  | `deploy --dry-run` | compiles and diffs Namespace, ConfigMap, NodeProfile, Link, and Node resources without changing them |
3683:  | `deploy --emit-crs` | prints the Namespace, ConfigMap, and Topology (or NodeProfile, Link, and Node) manifests deploy would create, without contacting the cluster |
3684:  
3685:  ## Requirements
3686: @@ -141,11 +144,11 @@ Containerlab needs a clabernetes release that has:
3687:  
3688:  - Node run state: `nodes.c9s.run` `spec.runState` (`Running` | `Stopped`), the
3689:    `Stopped` condition, and restart requests through the
3690:    `c9s.run/restart-requested` annotation
3691:  - the clabwire packet capture contract: `--nodeName`, repeated `--interface`,
3692: -  `--format pcapng` and `--list-interfaces`
3693: +  `--format pcapng`, `--list-interfaces` and `--stop-on-stdin-close`
3694:  - the namespace-bindable `clabernetes-lab-viewer` and `clabernetes-lab-editor`
3695:    roles
3696:  
3697:  Both features ship in the same release, so containerlab checks one field: the
3698:  published OpenAPI schema of `nodes.c9s.run` (`/openapi/v3/apis/c9s.run/v1alpha1`)
3699: @@ -159,10 +162,21 @@ an older release every other command fails like this:
3700:  the clabernetes release on this cluster is not supported: nodes.c9s.run has no
3701:  spec.runState (Node run state); the c9s runtime needs clabernetes with Node run
3702:  state and the clabwire capture contract (0.11 or newer)
3703:  ```
3704:  
3705: +A cluster that passes this check but runs a `clabwire` without
3706: +`--stop-on-stdin-close` (a development build between the two features) fails
3707: +the first capture with the same kind of error, naming the pod:
3708: +
3709: +```text
3710: +the clabernetes release on this cluster is not supported: clabwire in pod
3711: +<namespace>/<pod> does not accept packet-capture --stop-on-stdin-close; the c9s
3712: +runtime needs clabernetes with Node run state and the clabwire capture contract
3713: +(0.11 or newer)
3714: +```
3715: +
3716:  Library users can run the check up front with
3717:  `(*core.CLab).CheckLabRuntimeSupport(ctx)` or the optional
3718:  `labruntime.SupportChecker` interface; the error wraps
3719:  `labruntime.ErrUnsupportedRuntimeVersion`.
3720:  
3721: @@ -579,10 +593,82 @@ containerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timest
3722:  
3723:  It reads the `pods/log` subresource of the node's pod, so RBAC must allow
3724:  `get` on `pods/log`. Kubernetes returns stdout and stderr as one stream. See
3725:  the [`logs` command](../../cmd/logs.md) for the flags.
3726:  
3727: +## Packet capture
3728: +
3729: +[`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of
3730: +one or more nodes into one pcapng stream. Each node's pod runs the `clabwire`
3731: +sidecar, which realized the node's links; containerlab execs its capture
3732: +command (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.
3733: +No capture service runs in the cluster, and nothing is captured outside the
3734: +lab's planned link interfaces.
3735: +
3736: +```bash
3737: +# both ends of a link, for 30 seconds
3738: +containerlab -r c9s capture -t clos.clab.yml \
3739: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng
3740: +
3741: +# live in Wireshark until Wireshark or Ctrl+C ends it
3742: +containerlab -r c9s capture --name clos --target srl1:e1-1,e1-2 -w - | wireshark -k -i -
3743: +
3744: +# what can be captured, with the peer of each link
3745: +containerlab -r c9s capture --name clos --list
3746: +```
3747: +
3748: +How it works:
3749: +
3750: +- containerlab locates each target node's pod and runs one `clabwire` capture
3751: +  per node, with `--nodeName`, every requested interface of that node,
3752: +  `--format pcapng` and `--stop-on-stdin-close`, with stdin attached.
3753: +- The streams are merged into one section: one Interface Description Block per
3754: +  target named `<node>:<interface>` (the node as the topology spells it),
3755: +  written before the first packet, and the packets of every target with their
3756: +  interface IDs remapped.
3757: +- Packets are written in timestamp order. Each node's stream arrives over its
3758: +  own exec stream, so the merged stream holds every packet for 250 ms and
3759: +  writes the held packets ordered by timestamp. A packet that arrives later
3760: +  than that, stamped before a packet already written, is written as it comes;
3761: +  the number of such packets goes to the debug log.
3762: +- `clabwire` limits one capture to one hour. Longer captures, and captures
3763: +  without `--duration`, chain captures with a few seconds of overlap and switch
3764: +  in the middle of it; packets near the switch are matched by content so each
3765: +  is written once. A follow-up that does not start in time is reported as a
3766: +  gap, with its time span.
3767: +- `clabwire` audit records (JSON on its stderr, schema
3768: +  `c9s.direct-packet-capture-audit/v1alpha1`) with status `Denied` or `Failed`
3769: +  end the command with their reason. `Started` and `Succeeded` go to the debug
3770: +  log.
3771: +
3772: +Interface names are the names inside the node; targets may also use the alias
3773: +the topology used for an interface:
3774: +
3775: +| Kind | Interface | Alias |
3776: +| ---- | --------- | ----- |
3777: +| linux | `eth1` | |
3778: +| SR Linux | `e1-1` | `ethernet-1/1` |
3779: +| vr-sros / nokia_sros | `eth3` | `1/1/3` |
3780: +
3781: +The management interface and the pod's `c9s0` interface cannot be captured.
3782: +
3783: +Ctrl+C or SIGTERM ends a capture cleanly: the output stays a valid pcapng
3784: +file and the command exits with code 0. Kubernetes does not stop a command
3785: +when its exec stream closes, but it closes the command's stdin. containerlab
3786: +closes the stdin of every `clabwire` capture when the capture ends for any
3787: +reason (the duration or packet limit, Ctrl+C, an error, a failed write of the
3788: +output such as a closed Wireshark, or a newer segment taking over), and
3789: +`clabwire` then ends the capture within milliseconds. If the process does not
3790: +end within three seconds, containerlab cuts the exec stream. A killed
3791: +containerlab drops the connection, which closes stdin as well.
3792: +
3793: +Capturing needs `get` and `create` on `pods/exec` in the lab namespace, which
3794: +`clabernetes-lab-editor` grants. `inspect interfaces -r c9s` lists the same
3795: +interfaces, with the MAC address, index, MTU and operational state read from
3796: +sysfs in the device container (type `veth`, which is how `clabwire` realizes
3797: +lab links).
3798: +
3799:  ## Start, stop, and restart
3800:  
3801:  Node lifecycle commands ask the clabernetes controllers for a run state; they
3802:  never touch Deployments or Pods.
3803:  
3804: @@ -863,16 +949,22 @@ implemented by the c9s runtime:
3805:  | `NodeLocator` | `LocateNode(ctx, NodeRequest) ([]NodeLocation, error)` | the namespace, pod, primary device container, Node UID, exposed ports and LoadBalancer address of nodes |
3806:  | `NodeAttacher` | `Attach(ctx, AttachRequest, AttachStreams) error` | an interactive exec with stdin, an optional TTY and a resize channel, in the device container or a chosen container |
3807:  | `NodeLogStreamer` | `StreamLogs(ctx, LogRequest, io.Writer) error` | the device container log, with tail, follow and timestamps |
3808:  | `NodePortForwarder` | `DialPort(ctx, NodeRequest, port) (net.Conn, error)` | a connection to a TCP port of the node's pod through `pods/portforward` (SSH, web UIs) |
3809:  | `NodeStatsSampler` | `SampleStats(ctx, InspectRequest) ([]NodeStats, error)` | CPU and memory per node from `metrics.k8s.io` PodMetrics, summing the node's device containers; without the metrics API the error wraps `labruntime.ErrMetricsUnavailable` |
3810: +| `PacketCapturer` | `CaptureInterfaces(ctx, NodeRequest) ([]CaptureInterface, error)` | the capturable link interfaces of nodes, with alias, peer node and peer interface |
3811: +| `PacketCapturer` | `Capture(ctx, CaptureRequest, io.Writer) error` | one pcapng stream of the request's targets, for `Duration` (0: until ctx ends), `PacketLimit` and `SnapLength`; gaps go to `OnGap` |
3812: +| `InterfaceInspector` | `InspectInterfaces(ctx, NodeRequest) ([]*types.ContainerInterfaces, error)` | the `inspect interfaces` view of the link interfaces |
3813: +| `SupportChecker` | `CheckSupport(ctx, Identity) error` | the clabernetes release check |
3814:  
3815:  The `core` package wraps them per lab and node name, accepting the node name
3816:  as the topology file spells it or as it was sanitized:
3817:  `CLab.LocateLabRuntimeNodes`, `CLab.AttachLabRuntimeNode`,
3818: -`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats` and
3819: -`CLab.NodeLogs`, which also serves Docker and Podman.
3820: +`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats`,
3821: +`CLab.CaptureInterfaces`, `CLab.Capture`, `CLab.LabRuntimeInterfaces`,
3822: +`CLab.CheckLabRuntimeSupport` and `CLab.NodeLogs`, which also serves Docker and
3823: +Podman.
3824:  
3825:  ```go
3826:  c, err := clabcore.NewContainerLab(
3827:  	clabcore.WithRuntime("c9s", nil),
3828:  	clabcore.WithTopologyName("clos"),
3829: @@ -884,10 +976,18 @@ c, err := clabcore.NewContainerLab(
3830:  if err != nil {
3831:  	return err
3832:  }
3833:  
3834:  conn, err := c.DialLabRuntimeNodePort(ctx, "srl1", 22)
3835: +
3836: +// stream pcapng to a websocket, a file or Wireshark until ctx ends
3837: +err = c.Capture(ctx, clablabruntime.CaptureRequest{
3838: +	Targets: []clablabruntime.CaptureTarget{
3839: +		{Node: "srl1", Interface: "ethernet-1/1"},
3840: +		{Node: "srl2", Interface: "e1-1"},
3841: +	},
3842: +}, w)
3843:  ```
3844:  
3845:  ### Acting as a user
3846:  
3847:  A server that runs labs for many users acts as each user, so the cluster's RBAC
3848: @@ -936,11 +1036,12 @@ to:
3849:  - create, get, list, watch, and delete c9s `Link` and `NodeProfile` resources
3850:  - get, list, watch, and delete `Topology` resources when Topology-based labs
3851:    must remain manageable
3852:  - list and watch Pods
3853:  - create, get, list, update, and delete ConfigMaps used for local files
3854: -- exec into device Pods with `pods/exec`
3855: +- exec into device Pods with `pods/exec`, also for `capture` and `inspect
3856: +  interfaces` (in the `clabwire` and device containers)
3857:  - list and delete PersistentVolumeClaims for `destroy --cleanup`
3858:  - read container logs with `pods/log` for `logs`
3859:  - port-forward with `pods/portforward` for `NodePortForwarder`
3860:  - list `pods.metrics.k8s.io` for `NodeStatsSampler`
3861:  
3862: @@ -1152,12 +1253,14 @@ Known command differences:
3863:    `--export-template`, `--restore`, and `--restore-all` are rejected.
3864:  - Destroy flags `--graceful` and `--keep-mgmt-net` are rejected. `--cleanup`
3865:    also deletes the lab's persistent claims (saved device state) and removes
3866:    the local lab directory; a plain destroy keeps the claims.
3867:  - Local Docker commands on the outer host are not authoritative for c9s labs.
3868: -- `inspect interfaces` is rejected. Host-side `tc` or netem operations do not
3869: -  have the same local namespace access they have with Docker labs.
3870: +- `inspect interfaces` lists only the lab link interfaces (those `capture`
3871: +  accepts), not the management or pod interfaces. Host-side `tc` or netem
3872: +  operations do not have the same local namespace access they have with Docker
3873: +  labs.
3874:  - `graph` renders from the topology file only: `--mermaid`, `--dot`, `--drawio`
3875:    and `--offline` work, the default mode that reads running containers is
3876:    rejected, and so is `--node-filter`. `--drawio` runs the clab-io-draw
3877:    container, so it needs Docker or Podman on the outer host.
3878:  - `tools` commands operate on local containers and host networking and are
3879: diff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md
3880: index b194b29..4654128 100644
3881: --- a/docs/manual/wireshark.md
3882: +++ b/docs/manual/wireshark.md
3883: @@ -15,10 +15,16 @@ Every lab emulation software must provide its users with the packet capturing ab
3884:  
3885:  Containerlab offers a simple way to capture the packets from any interface of any node in the lab. This article will explain how to do that.
3886:  
3887:  ///tip
3888:  
3889: +The [`containerlab capture`](../cmd/capture.md) command captures one or more lab link interfaces, of one or more nodes, into one pcapng file or stream, with nothing to install in the nodes or on the host:
3890: +
3891: +```bash
3892: +containerlab capture --name quickstart --target srl:e1-1 -w - | wireshark -k -i -
3893: +```
3894: +
3895:  If you are looking for a free Web UI for packet capture with Wireshark, check out our [Edgeshark integration](#edgeshark-integration).
3896:  ///
3897:  
3898:  Consider the following lab topology which highlights the typical points of packet capture.
3899:  
3900: diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go
3901: new file mode 100644
3902: index 0000000..69d4072
3903: --- /dev/null
3904: +++ b/labruntime/clabernetes/capture.go
3905: @@ -0,0 +1,1202 @@
3906: +package clabernetes
3907: +
3908: +import (
3909: +	"bytes"
3910: +	"context"
3911: +	"encoding/json"
3912: +	"errors"
3913: +	"fmt"
3914: +	"hash/fnv"
3915: +	"io"
3916: +	"os"
3917: +	"sort"
3918: +	"strconv"
3919: +	"strings"
3920: +	"sync"
3921: +	"time"
3922: +
3923: +	"github.com/charmbracelet/log"
3924: +	clabcapture "github.com/srl-labs/containerlab/capture"
3925: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
3926: +	"golang.org/x/sync/errgroup"
3927: +)
3928: +
3929: +// The clabwire packet capture contract (clabernetes 0.11 or newer).
3930: +const (
3931: +	clabwireContainer = "clabwire"
3932: +	clabwireManager   = "/clabernetes/manager"
3933: +	// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.
3934: +	captureAuditSchema = "c9s.direct-packet-capture-audit/v1alpha1"
3935: +
3936: +	captureAuditStarted   = "Started"
3937: +	captureAuditSucceeded = "Succeeded"
3938: +	captureAuditFailed    = "Failed"
3939: +	captureAuditDenied    = "Denied"
3940: +
3941: +	// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.
3942: +	maxCaptureSegment = time.Hour
3943: +	// maxClabwirePackets is the packet limit of a single clabwire capture.
3944: +	maxClabwirePackets = 1_000_000
3945: +	// maxCaptureOverlap is how long two chained segments run side by side.
3946: +	maxCaptureOverlap = 10 * time.Second
3947: +	// maxCaptureCutWindow is the half-width of the window around the cut in which packets of
3948: +	// two segments are matched by content; it covers the difference between the timestamps
3949: +	// two clabwire processes give the same packet.
3950: +	maxCaptureCutWindow = 500 * time.Millisecond
3951: +	// minCaptureSegment is the shortest segment the chain requests.
3952: +	minCaptureSegment = 100 * time.Millisecond
3953: +	// captureEndGrace is how long a capture with a duration waits for its last clabwire
3954: +	// process to end after the duration passed.
3955: +	captureEndGrace = 30 * time.Second
3956: +	// captureStartRetries bounds the attempts to start a follow-up segment.
3957: +	captureStartRetries = 3
3958: +	// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was
3959: +	// closed before the stream is cut.
3960: +	captureStdinCloseGrace = 3 * time.Second
3961: +	// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A
3962: +	// Kubernetes exec does not stop its process when the stream ends, but it closes the
3963: +	// process's stdin, so every capture runs with stdin attached and this flag.
3964: +	clabwireStopOnStdinClose = "--stop-on-stdin-close"
3965: +
3966: +	// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests
3967: +	// without hour-long captures.
3968: +	envCaptureSegment = "CLAB_C9S_CAPTURE_SEGMENT"
3969: +	// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets
3970: +	// of other nodes stamped earlier but delivered later still go out before it.
3971: +	defaultCaptureReorderWindow = 250 * time.Millisecond
3972: +	// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.
3973: +	// It is an internal knob, not a supported setting.
3974: +	envCaptureReorderWindow = "CLAB_C9S_CAPTURE_REORDER_WINDOW"
3975: +)
3976: +
3977: +// podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns
3978: +// a *labruntime.CommandExitError.
3979: +type podExecFunc func(
3980: +	ctx context.Context,
3981: +	namespace, pod, container string,
3982: +	command []string,
3983: +	stdin io.Reader,
3984: +	stdout, stderr io.Writer,
3985: +) error
3986: +
3987: +// clabwireInterface is one entry of `packet-capture --list-interfaces`.
3988: +type clabwireInterface struct {
3989: +	Node          string `json:"node"`
3990: +	Interface     string `json:"interface"`
3991: +	Alias         string `json:"alias,omitempty"`
3992: +	PeerNode      string `json:"peerNode"`
3993: +	PeerInterface string `json:"peerInterface"`
3994: +}
3995: +
3996: +// captureAudit is one clabwire audit line.
3997: +type captureAudit struct {
3998: +	SchemaVersion string    `json:"schemaVersion"`
3999: +	Time          time.Time `json:"time"`
4000: +	Status        string    `json:"status"`
4001: +	NodeName      string    `json:"nodeName"`
4002: +	Format        string    `json:"format"`
4003: +	Reason        string    `json:"reason"`
4004: +	Packets       int       `json:"packets"`
4005: +	Interfaces    []struct {
4006: +		Name    string `json:"name"`
4007: +		ID      string `json:"id"`
4008: +		Packets int    `json:"packets"`
4009: +	} `json:"interfaces"`
4010: +}
4011: +
4012: +func (r *Runtime) execInPodContainer() podExecFunc {
4013: +	if r.podExec != nil {
4014: +		return r.podExec
4015: +	}
4016: +
4017: +	return r.streamPodExec
4018: +}
4019: +
4020: +// captureSegmentLength is the length of one clabwire capture before the next takes over.
4021: +func (r *Runtime) captureSegmentLength() time.Duration {
4022: +	if r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {
4023: +		return r.captureSegment
4024: +	}
4025: +
4026: +	return maxCaptureSegment
4027: +}
4028: +
4029: +// captureReorderWindowLength is the reorder window of the merged stream; zero disables
4030: +// reordering.
4031: +func (r *Runtime) captureReorderWindowLength() time.Duration {
4032: +	switch {
4033: +	case r.captureReorderWindow < 0:
4034: +		return 0
4035: +	case r.captureReorderWindow > 0:
4036: +		return r.captureReorderWindow
4037: +	}
4038: +
4039: +	return defaultCaptureReorderWindow
4040: +}
4041: +
4042: +// captureReorderWindowFromEnv reads the reorder window knob: unset or invalid keeps the
4043: +// default (0), "0" disables reordering (-1).
4044: +func captureReorderWindowFromEnv() time.Duration {
4045: +	value, err := time.ParseDuration(os.Getenv(envCaptureReorderWindow))
4046: +	switch {
4047: +	case err != nil || value < 0:
4048: +		return 0
4049: +	case value == 0:
4050: +		return -1
4051: +	}
4052: +
4053: +	return value
4054: +}
4055: +
4056: +func captureSegmentFromEnv() time.Duration {
4057: +	value, err := time.ParseDuration(os.Getenv(envCaptureSegment))
4058: +	if err != nil || value <= 0 {
4059: +		return 0
4060: +	}
4061: +
4062: +	return value
4063: +}
4064: +
4065: +// CaptureInterfaces lists the capturable lab link interfaces of the requested nodes, or of every
4066: +// node, as clabwire reports them, with their peers. Node names are reported as the topology
4067: +// spells them.
4068: +func (r *Runtime) CaptureInterfaces(
4069: +	ctx context.Context,
4070: +	req clablabruntime.NodeRequest,
4071: +) ([]clablabruntime.CaptureInterface, error) {
4072: +	r, err := r.connect(ctx, req.Identity)
4073: +	if err != nil {
4074: +		return nil, err
4075: +	}
4076: +
4077: +	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{
4078: +		Name: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,
4079: +	})
4080: +	if err != nil {
4081: +		return nil, err
4082: +	}
4083: +	if len(req.Nodes) == 0 {
4084: +		// a lab-wide listing skips nodes that do not run
4085: +		running := locations[:0]
4086: +		for _, location := range locations {
4087: +			if location.Pod != "" {
4088: +				running = append(running, location)
4089: +			}
4090: +		}
4091: +		locations = running
4092: +	}
4093: +
4094: +	listed, err := r.listCaptureInterfaces(ctx, req.Name, locations)
4095: +	if err != nil {
4096: +		return nil, err
4097: +	}
4098: +	names, err := r.nodeDisplayNames(ctx, req.Name, locations)
4099: +	if err != nil {
4100: +		return nil, err
4101: +	}
4102: +
4103: +	result := make([]clablabruntime.CaptureInterface, 0)
4104: +	for _, location := range locations {
4105: +		for _, entry := range listed[location.NodeName] {
4106: +			result = append(result, clablabruntime.CaptureInterface{
4107: +				Node:          names.display(entry.Node),
4108: +				Interface:     entry.Interface,
4109: +				Alias:         entry.Alias,
4110: +				PeerNode:      names.display(entry.PeerNode),
4111: +				PeerInterface: entry.PeerInterface,
4112: +			})
4113: +		}
4114: +	}
4115: +	sort.SliceStable(result, func(i, j int) bool {
4116: +		if result[i].Node != result[j].Node {
4117: +			return result[i].Node < result[j].Node
4118: +		}
4119: +
4120: +		return result[i].Interface < result[j].Interface
4121: +	})
4122: +
4123: +	return result, nil
4124: +}
4125: +
4126: +// listCaptureInterfaces runs one --list-interfaces per pod and returns the entries per Node.
4127: +func (r *Runtime) listCaptureInterfaces(
4128: +	ctx context.Context,
4129: +	lab string,
4130: +	locations []clablabruntime.NodeLocation,
4131: +) (map[string][]clabwireInterface, error) {
4132: +	pods := map[string]clablabruntime.NodeLocation{}
4133: +	wanted := map[string]bool{}
4134: +	for _, location := range locations {
4135: +		if location.Pod == "" {
4136: +			return nil, fmt.Errorf("c9s node %s/%s/%s has no pod; is it running?",
4137: +				location.Namespace, lab, location.NodeName)
4138: +		}
4139: +		pods[location.Namespace+"/"+location.Pod] = location
4140: +		wanted[location.NodeName] = true
4141: +	}
4142: +
4143: +	var mu sync.Mutex
4144: +	result := map[string][]clabwireInterface{}
4145: +	group, groupCtx := errgroup.WithContext(ctx)
4146: +	group.SetLimit(interfaceSampleWorkers)
4147: +	exec := r.execInPodContainer()
4148: +	for _, location := range pods {
4149: +		group.Go(func() error {
4150: +			var stdout, stderr bytes.Buffer
4151: +			err := exec(groupCtx, location.Namespace, location.Pod, clabwireContainer,
4152: +				[]string{clabwireManager, "node-runtime", "packet-capture", "--list-interfaces"},
4153: +				nil, &stdout, &stderr)
4154: +			if err != nil {
4155: +				return fmt.Errorf("failed to list the capturable interfaces of pod %s/%s: %w%s",
4156: +					location.Namespace, location.Pod, err, stderrSuffix(stderr.Bytes()))
4157: +			}
4158: +
4159: +			var entries []clabwireInterface
4160: +			if err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {
4161: +				return fmt.Errorf("failed to parse the capturable interfaces of pod %s/%s: %w",
4162: +					location.Namespace, location.Pod, err)
4163: +			}
4164: +
4165: +			mu.Lock()
4166: +			defer mu.Unlock()
4167: +			for _, entry := range entries {
4168: +				if wanted[entry.Node] {
4169: +					result[entry.Node] = append(result[entry.Node], entry)
4170: +				}
4171: +			}
4172: +
4173: +			return nil
4174: +		})
4175: +	}
4176: +	if err := group.Wait(); err != nil {
4177: +		return nil, err
4178: +	}
4179: +
4180: +	return result, nil
4181: +}
4182: +
4183: +func stderrSuffix(stderr []byte) string {
4184: +	text := strings.TrimSpace(string(stderr))
4185: +	if text == "" {
4186: +		return ""
4187: +	}
4188: +
4189: +	return ": " + text
4190: +}
4191: +
4192: +// nodeNames maps the node names the cluster carries to the names the topology file uses.
4193: +type nodeNames map[string]string
4194: +
4195: +func (n nodeNames) display(name string) string {
4196: +	if original := n[name]; original != "" {
4197: +		return original
4198: +	}
4199: +
4200: +	return name
4201: +}
4202: +
4203: +// nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the
4204: +// lab's Nodes.
4205: +func (r *Runtime) nodeDisplayNames(
4206: +	ctx context.Context,
4207: +	lab string,
4208: +	locations []clablabruntime.NodeLocation,
4209: +) (nodeNames, error) {
4210: +	names := nodeNames{}
4211: +	if len(locations) == 0 {
4212: +		return names, nil
4213: +	}
4214: +
4215: +	nodes, err := r.nodesForTopology(ctx, lab, locations[0].Namespace)
4216: +	if err != nil {
4217: +		return nil, err
4218: +	}
4219: +	for idx := range nodes.Items {
4220: +		if original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != "" {
4221: +			names[nodes.Items[idx].GetName()] = original
4222: +		}
4223: +	}
4224: +
4225: +	return names, nil
4226: +}
4227: +
4228: +// captureGroup is the part of a capture one clabwire process serves: the requested interfaces of
4229: +// one node, in one pod.
4230: +type captureGroup struct {
4231: +	location clablabruntime.NodeLocation
4232: +	display  string
4233: +	// interfaces are the planned interface names, in the order the merged stream lists them.
4234: +	interfaces []string
4235: +	// ids are the merged interface IDs of interfaces.
4236: +	ids []uint32
4237: +}
4238: +
4239: +// resolvedCapture is a validated capture request.
4240: +type resolvedCapture struct {
4241: +	groups []*captureGroup
4242: +	// names are the merged interface names (<node>:<interface>), indexed by merged ID.
4243: +	names []string
4244: +}
4245: +
4246: +// resolveCaptureTargets locates every target node, checks every interface against the
4247: +// interfaces clabwire allows, and groups the targets per node.
4248: +func (r *Runtime) resolveCaptureTargets(
4249: +	ctx context.Context,
4250: +	req clablabruntime.CaptureRequest,
4251: +) (*resolvedCapture, error) {
4252: +	nodeOrder := make([]string, 0, len(req.Targets))
4253: +	seenNodes := map[string]bool{}
4254: +	for _, target := range req.Targets {
4255: +		if !seenNodes[target.Node] {
4256: +			seenNodes[target.Node] = true
4257: +			nodeOrder = append(nodeOrder, target.Node)
4258: +		}
4259: +	}
4260: +
4261: +	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{
4262: +		Name: req.Name, Namespace: req.Namespace, Nodes: nodeOrder, Identity: req.Identity,
4263: +	})
4264: +	if err != nil {
4265: +		return nil, err
4266: +	}
4267: +	byRequest := make(map[string]clablabruntime.NodeLocation, len(nodeOrder))
4268: +	for idx, name := range nodeOrder {
4269: +		byRequest[name] = locations[idx]
4270: +	}
4271: +
4272: +	listed, err := r.listCaptureInterfaces(ctx, req.Name, locations)
4273: +	if err != nil {
4274: +		return nil, err
4275: +	}
4276: +	names, err := r.nodeDisplayNames(ctx, req.Name, locations)
4277: +	if err != nil {
4278: +		return nil, err
4279: +	}
4280: +
4281: +	resolved := &resolvedCapture{}
4282: +	groups := map[string]*captureGroup{}
4283: +	seen := map[string]bool{}
4284: +	for _, target := range req.Targets {
4285: +		location := byRequest[target.Node]
4286: +		entry, ok := findCaptureInterface(listed[location.NodeName], target.Interface)
4287: +		if !ok {
4288: +			return nil, fmt.Errorf("interface %q of node %q is not a capturable link "+
4289: +				"interface; capturable: %s", target.Interface, target.Node,
4290: +				describeCaptureInterfaces(listed[location.NodeName]))
4291: +		}
4292: +
4293: +		key := location.NodeName + "\x00" + entry.Interface
4294: +		if seen[key] {
4295: +			return nil, fmt.Errorf("interface %q of node %q is requested more than once",
4296: +				entry.Interface, target.Node)
4297: +		}
4298: +		seen[key] = true
4299: +
4300: +		group := groups[location.NodeName]
4301: +		if group == nil {
4302: +			group = &captureGroup{
4303: +				location: location,
4304: +				display:  names.display(location.NodeName),
4305: +			}
4306: +			groups[location.NodeName] = group
4307: +			resolved.groups = append(resolved.groups, group)
4308: +		}
4309: +
4310: +		id := uint32(len(resolved.names)) //nolint:gosec // bounded by the targets
4311: +		group.interfaces = append(group.interfaces, entry.Interface)
4312: +		group.ids = append(group.ids, id)
4313: +		resolved.names = append(resolved.names, group.display+":"+entry.Interface)
4314: +	}
4315: +
4316: +	return resolved, nil
4317: +}
4318: +
4319: +// findCaptureInterface matches a requested interface by its planned name or its alias.
4320: +func findCaptureInterface(entries []clabwireInterface, name string) (clabwireInterface, bool) {
4321: +	for _, entry := range entries {
4322: +		if entry.Interface == name {
4323: +			return entry, true
4324: +		}
4325: +	}
4326: +	for _, entry := range entries {
4327: +		if entry.Alias != "" && entry.Alias == name {
4328: +			return entry, true
4329: +		}
4330: +	}
4331: +
4332: +	return clabwireInterface{}, false
4333: +}
4334: +
4335: +func describeCaptureInterfaces(entries []clabwireInterface) string {
4336: +	if len(entries) == 0 {
4337: +		return "none"
4338: +	}
4339: +
4340: +	names := make([]string, 0, len(entries))
4341: +	for _, entry := range entries {
4342: +		name := entry.Interface
4343: +		if entry.Alias != "" {
4344: +			name += " (" + entry.Alias + ")"
4345: +		}
4346: +		names = append(names, name)
4347: +	}
4348: +
4349: +	return strings.Join(names, ", ")
4350: +}
4351: +
4352: +// Capture streams pcapng from lab link interfaces to w: one section, one Interface Description
4353: +// Block per target in request order named <node>:<interface>, then the packets of every target.
4354: +//
4355: +// Each node's interfaces are captured by one clabwire process in the node's pod. clabwire limits
4356: +// a capture to one hour, so a longer capture (or one without Duration) chains captures: the next
4357: +// one starts before the current one ends, and the stream switches at a cut in the overlap. See
4358: +// captureChain for how packets of the overlap are kept once.
4359: +//
4360: +// Packets go out in timestamp order across nodes, through a reorder buffer (captureReorder).
4361: +//
4362: +// Every clabwire process runs with stdin attached and --stop-on-stdin-close: a Kubernetes exec
4363: +// does not stop its process when the stream closes, so containerlab closes stdin whenever a
4364: +// segment ends (the capture ends, fails, its output fails, or a newer segment took over) and
4365: +// clabwire ends the capture itself.
4366: +//
4367: +// Capture returns when Duration has passed, PacketLimit packets were written, or ctx ends; an
4368: +// ended ctx is not an error. Every block reaches w in one write, so the stream is a valid capture
4369: +// whenever it stops. A clabwire Denied or Failed audit record is returned as an error.
4370: +func (r *Runtime) Capture(
4371: +	ctx context.Context,
4372: +	req clablabruntime.CaptureRequest,
4373: +	w io.Writer,
4374: +) error {
4375: +	if err := clabcapture.ValidateRequest(&req); err != nil {
4376: +		return err
4377: +	}
4378: +
4379: +	r, err := r.connect(ctx, req.Identity)
4380: +	if err != nil {
4381: +		return err
4382: +	}
4383: +
4384: +	resolved, err := r.resolveCaptureTargets(ctx, req)
4385: +	if err != nil {
4386: +		return err
4387: +	}
4388: +
4389: +	captureCtx, stop := context.WithCancel(ctx)
4390: +	defer stop()
4391: +
4392: +	out, err := clabcapture.NewOutput(w, resolved.names, req.SnapLength, req.PacketLimit,
4393: +		r.captureReorderWindowLength(), stop)
4394: +	if err != nil {
4395: +		return err
4396: +	}
4397: +
4398: +	run := &captureRun{
4399: +		r:       r,
4400: +		req:     req,
4401: +		out:     out,
4402: +		segment: r.captureSegmentLength(),
4403: +	}
4404: +	if req.Duration > 0 {
4405: +		run.deadline = time.Now().Add(req.Duration)
4406: +	}
4407: +	run.overlap = min(maxCaptureOverlap, run.segment/3)
4408: +	run.window = min(maxCaptureCutWindow, run.overlap/4)
4409: +
4410: +	if req.Duration > 0 {
4411: +		// a clabwire process that does not end on its own does not hold the capture open
4412: +		var cancelTimeout context.CancelFunc
4413: +		captureCtx, cancelTimeout = context.WithTimeout(captureCtx,
4414: +			req.Duration+run.overlap+captureEndGrace)
4415: +		defer cancelTimeout()
4416: +	}
4417: +
4418: +	group, groupCtx := errgroup.WithContext(captureCtx)
4419: +	for _, captureGroup := range resolved.groups {
4420: +		chain := &captureChain{capture: run, group: captureGroup}
4421: +		group.Go(func() error {
4422: +			return chain.run(groupCtx)
4423: +		})
4424: +	}
4425: +
4426: +	err = group.Wait()
4427: +	if writeErr := out.Close(); writeErr != nil {
4428: +		return writeErr
4429: +	}
4430: +	if err != nil && !(errors.Is(err, context.Canceled) && captureCtx.Err() != nil) {
4431: +		return err
4432: +	}
4433: +
4434: +	return nil
4435: +}
4436: +
4437: +// captureRun is the state a capture's chains share.
4438: +type captureRun struct {
4439: +	r   *Runtime
4440: +	req clablabruntime.CaptureRequest
4441: +	// out is the merged stream; it writes the packets of every chain in timestamp order and
4442: +	// stops every chain once the packet limit is reached.
4443: +	out *clabcapture.Output
4444: +
4445: +	segment  time.Duration
4446: +	overlap  time.Duration
4447: +	window   time.Duration
4448: +	deadline time.Time
4449: +}
4450: +
4451: +// emit writes a packet under its merged interface ID. It reports false once the packet limit is
4452: +// reached and the capture stops.
4453: +func (run *captureRun) emit(id uint32, packet *clabcapture.Packet) (bool, error) {
4454: +	return run.out.Emit(id, packet)
4455: +}
4456: +
4457: +func (run *captureRun) reportGap(gap clablabruntime.CaptureGap) {
4458: +	clabcapture.ReportGap(run.req.OnGap, gap)
4459: +}
4460: +
4461: +// captureSegment is one clabwire capture process of a chain.
4462: +type captureSegment struct {
4463: +	index      int
4464: +	localStart time.Time
4465: +	duration   time.Duration
4466: +	cancel     context.CancelFunc
4467: +	// closeStdin closes the stdin of the segment's clabwire process, which ends it; it may be
4468: +	// called any number of times.
4469: +	closeStdin func()
4470: +	// stopTimer closes stdin once the segment is no longer needed after a switch-over.
4471: +	stopTimer *time.Timer
4472: +	// started and ended are the pod-clock times of the Started and Succeeded audit records.
4473: +	started time.Time
4474: +	ended   time.Time
4475: +	done    bool
4476: +}
4477: +
4478: +func (s *captureSegment) plannedEnd() time.Time {
4479: +	return s.started.Add(s.duration)
4480: +}
4481: +
4482: +// segmentEvent is something a segment reported: a packet, an audit record, or its end.
4483: +type segmentEvent struct {
4484: +	segment *captureSegment
4485: +	packet  *clabcapture.Packet
4486: +	audit   *captureAudit
4487: +	done    bool
4488: +	err     error
4489: +}
4490: +
4491: +// captureChain runs the chained clabwire captures of one group.
4492: +//
4493: +// Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both
4494: +// capture the same packets for a while. clabwire stamps packets when it reads them, so two
4495: +// processes give the same packet timestamps a few microseconds apart, and timestamps alone
4496: +// cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by
4497: +// content close to the cut:
4498: +//
4499: +//  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is
4500: +//     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.
4501: +//  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the
4502: +//     content of what it wrote since segment k+1 started.
4503: +//  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped
4504: +//     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped
4505: +//     when segment k wrote the same bytes on the same interface, and every other one is written.
4506: +//     From then on segment k+1 streams live.
4507: +//
4508: +// Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its
4509: +// planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other
4510: +// nodes' later packets do not overtake them in the merged stream.
4511: +//
4512: +// W (500 ms, less for short test segments) covers the stamping difference. Identical frames on
4513: +// the same interface within W of the cut can be paired with each other, which can drop a true
4514: +// repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves
4515: +// a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.
4516: +type captureChain struct {
4517: +	capture *captureRun
4518: +	group   *captureGroup
4519: +
4520: +	events chan segmentEvent
4521: +	wg     sync.WaitGroup
4522: +
4523: +	active *captureSegment
4524: +	next   *captureSegment
4525: +	// cut is the switch time between active and next, in nanoseconds; zero until known.
4526: +	cut int64
4527: +	// emitted remembers the content of the packets active wrote while next runs.
4528: +	emitted map[uint64]int
4529: +	// held are the packets of next until active ends.
4530: +	held     []*clabcapture.Packet
4531: +	segments int
4532: +	retries  int
4533: +	// final is set once no further segment is due.
4534: +	final bool
4535: +	// stopping is set once ctx ended: the segments are asked to end and what they still
4536: +	// deliver is written.
4537: +	stopping bool
4538: +}
4539: +
4540: +// run runs the chain until its last segment ended. When ctx ends, it stops the segments and
4541: +// keeps writing the packets they read until then; a segment that does not end within
4542: +// captureStdinCloseGrace is cut.
4543: +func (c *captureChain) run(ctx context.Context) error {
4544: +	c.events = make(chan segmentEvent, 256)
4545: +	// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them
4546: +	segmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
4547: +	var abort *time.Timer
4548: +	defer func() {
4549: +		if abort != nil {
4550: +			abort.Stop()
4551: +		}
4552: +		cancel()
4553: +		c.drain()
4554: +		c.capture.out.Release(c)
4555: +	}()
4556: +
4557: +	c.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))
4558: +	timer := time.NewTimer(c.nextStartIn())
4559: +	defer timer.Stop()
4560: +
4561: +	done := ctx.Done()
4562: +	for {
4563: +		select {
4564: +		case <-done:
4565: +			done = nil
4566: +			c.stop(timer)
4567: +			abort = time.AfterFunc(captureStdinCloseGrace, cancel)
4568: +		case <-segmentsCtx.Done():
4569: +			return nil
4570: +		case <-timer.C:
4571: +			if c.next == nil && !c.final {
4572: +				c.startNext(segmentsCtx)
4573: +			}
4574: +		case event := <-c.events:
4575: +			stop, err := c.handle(segmentsCtx, event, timer)
4576: +			if err != nil || stop {
4577: +				return err
4578: +			}
4579: +		}
4580: +	}
4581: +}
4582: +
4583: +// stop ends the chain early, like a deadline would: no further segment starts and the running
4584: +// ones are asked to end. The chain then writes what they deliver until they ended.
4585: +func (c *captureChain) stop(timer *time.Timer) {
4586: +	c.stopping = true
4587: +	c.final = true
4588: +	timer.Stop()
4589: +	c.active.closeStdin()
4590: +	if c.next != nil {
4591: +		c.next.closeStdin()
4592: +	}
4593: +}
4594: +
4595: +// drain waits for the segment goroutines after the chain ended.
4596: +func (c *captureChain) drain() {
4597: +	done := make(chan struct{})
4598: +	go func() {
4599: +		c.wg.Wait()
4600: +		close(done)
4601: +	}()
4602: +	for {
4603: +		select {
4604: +		case <-done:
4605: +			return
4606: +		case <-c.events:
4607: +		}
4608: +	}
4609: +}
4610: +
4611: +// segmentDuration is the requested duration of a segment starting now.
4612: +func (c *captureChain) segmentDuration(now time.Time) time.Duration {
4613: +	duration := c.capture.segment
4614: +	if !c.capture.deadline.IsZero() {
4615: +		duration = min(duration, c.capture.deadline.Sub(now))
4616: +	}
4617: +
4618: +	return max(duration, minCaptureSegment)
4619: +}
4620: +
4621: +// nextStartIn is the time until the follow-up of the active segment is due. It marks the chain
4622: +// final when none is due.
4623: +func (c *captureChain) nextStartIn() time.Duration {
4624: +	if c.stopping {
4625: +		c.final = true
4626: +		return maxCaptureSegment
4627: +	}
4628: +	activeEnd := c.active.localStart.Add(c.active.duration)
4629: +	if !c.capture.deadline.IsZero() &&
4630: +		!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {
4631: +		c.final = true
4632: +		return maxCaptureSegment
4633: +	}
4634: +	c.final = false
4635: +
4636: +	return max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)
4637: +}
4638: +
4639: +func (c *captureChain) startNext(ctx context.Context) {
4640: +	c.next = c.start(ctx, c.segmentDuration(time.Now()))
4641: +	c.emitted = map[uint64]int{}
4642: +	c.held = nil
4643: +	c.cut = 0
4644: +}
4645: +
4646: +func (c *captureChain) handle(
4647: +	ctx context.Context,
4648: +	event segmentEvent,
4649: +	timer *time.Timer,
4650: +) (bool, error) {
4651: +	segment := event.segment
4652: +
4653: +	switch {
4654: +	case event.audit != nil:
4655: +		return false, c.handleAudit(segment, event.audit)
4656: +	case event.packet != nil:
4657: +		return c.handlePacket(segment, event.packet)
4658: +	case event.done:
4659: +		segment.done = true
4660: +		if segment.stopTimer != nil {
4661: +			segment.stopTimer.Stop()
4662: +		}
4663: +		if event.err != nil && !c.stopping {
4664: +			if segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {
4665: +				// the follow-up did not start; try again while the active one still runs
4666: +				c.retries++
4667: +				log.Warn("Capture follow-up segment failed to start, retrying",
4668: +					"node", c.group.display, "error", event.err)
4669: +				c.next = nil
4670: +				resetTimer(timer, time.Second)
4671: +
4672: +				return false, nil
4673: +			}
4674: +
4675: +			return true, fmt.Errorf("capture on c9s node %s/%s/%s failed: %w",
4676: +				c.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)
4677: +		}
4678: +		if segment != c.active {
4679: +			return false, nil
4680: +		}
4681: +
4682: +		return c.switchSegments(ctx, timer)
4683: +	}
4684: +
4685: +	return false, nil
4686: +}
4687: +
4688: +func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {
4689: +	switch audit.Status {
4690: +	case captureAuditStarted:
4691: +		segment.started = audit.Time
4692: +		log.Debug("Capture segment started", "node", c.group.display, "segment", segment.index,
4693: +			"interfaces", strings.Join(c.group.interfaces, ","), "duration", segment.duration)
4694: +		if segment == c.next && !c.active.started.IsZero() {
4695: +			c.setCut()
4696: +		}
4697: +		if segment == c.next {
4698: +			c.retries = 0
4699: +		}
4700: +	case captureAuditSucceeded:
4701: +		segment.ended = audit.Time
4702: +		log.Debug("Capture segment succeeded", "node", c.group.display,
4703: +			"segment", segment.index, "packets", audit.Packets)
4704: +	case captureAuditDenied, captureAuditFailed:
4705: +		return captureAuditError(c.group.display, audit)
4706: +	}
4707: +
4708: +	return nil
4709: +}
4710: +
4711: +// captureAuditError turns a Denied or Failed clabwire audit record into an error.
4712: +func captureAuditError(node string, audit *captureAudit) error {
4713: +	verb := "failed"
4714: +	if audit.Status == captureAuditDenied {
4715: +		verb = "was denied"
4716: +	}
4717: +	interfaces := make([]string, 0, len(audit.Interfaces))
4718: +	for _, intf := range audit.Interfaces {
4719: +		interfaces = append(interfaces, intf.Name)
4720: +	}
4721: +
4722: +	return fmt.Errorf("capture of %s on node %s %s by clabwire: %s",
4723: +		strings.Join(interfaces, ","), node, verb, audit.Reason)
4724: +}
4725: +
4726: +// setCut places the cut in the middle of the overlap of the active and the next segment, both
4727: +// measured on the pod clock.
4728: +func (c *captureChain) setCut() {
4729: +	overlapStart := c.next.started
4730: +	overlapEnd := c.active.plannedEnd()
4731: +	if overlapEnd.Sub(overlapStart) < 2*c.capture.window {
4732: +		// the overlap is too short to match packets around a cut: the switch is reported as a
4733: +		// gap once the active segment ended
4734: +		c.cut = 0
4735: +		return
4736: +	}
4737: +	c.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()
4738: +
4739: +	window := c.capture.window.Nanoseconds()
4740: +	// Packets the next segment holds back are stamped from T-W on: other chains' packets after
4741: +	// that wait in the reorder buffer until the switch, so the merged stream stays in order.
4742: +	c.capture.out.Hold(c, c.cut-window)
4743: +
4744: +	// The active segment only matters for packets stamped before T. Once the pod clock passed
4745: +	// T+W, it is closed: packets it read until then are still delivered, and the ones it reads
4746: +	// later are stamped after T and dropped anyway. The next segment's Started record was
4747: +	// written on the pod clock no later than now, so the pod clock passes T+W no later than
4748: +	// (T - Started + W) from now.
4749: +	active := c.active
4750: +	active.stopTimer = time.AfterFunc(
4751: +		time.Duration(c.cut-c.next.started.UnixNano()+window), active.closeStdin)
4752: +}
4753: +
4754: +func (c *captureChain) handlePacket(
4755: +	segment *captureSegment,
4756: +	packet *clabcapture.Packet,
4757: +) (bool, error) {
4758: +	switch segment {
4759: +	case c.active:
4760: +		if c.cut != 0 && packet.Timestamp >= c.cut {
4761: +			return false, nil
4762: +		}
4763: +		if c.next != nil {
4764: +			c.emitted[packetKey(packet)]++
4765: +		}
4766: +
4767: +		return c.emit(packet)
4768: +	case c.next:
4769: +		c.held = append(c.held, packet)
4770: +	}
4771: +
4772: +	return false, nil
4773: +}
4774: +
4775: +func (c *captureChain) emit(packet *clabcapture.Packet) (bool, error) {
4776: +	if int(packet.InterfaceID) >= len(c.group.ids) {
4777: +		return true, fmt.Errorf("clabwire wrote a packet for interface %d of %d",
4778: +			packet.InterfaceID, len(c.group.ids))
4779: +	}

(Output capped at 50 KB. Showing lines 3478-4779. Use offset=4780 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19650b2f1001DcJEW7AlBg7z6x",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650a855001ooGiCUj8bm23MA",
  "callID": "call_89fa504d09054443986ec92c",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "offset": 3478
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n3478: +\t\tcase 6: // Enhanced Packet Block\n3479: +\t\t\tid := binary.LittleEndian.Uint32(body[0:4])\n3480: +\t\t\tframe := body[20 : 20+binary.LittleEndian.Uint32(body[12:16])]\n3481: +\t\t\tif len(frame) > 23 && frame[12] == 0x08 && frame[13] == 0x00 && frame[23] == 1 {\n3482: +\t\t\t\ticmp[id]++\n3483: +\t\t\t}\n3484: +\t\t}\n3485: +\t\tdata = data[length:]\n3486: +\t}\n3487: +\n3488: +\treturn names, icmp\n3489: +}\n3490: diff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml\n3491: new file mode 100644\n3492: index 0000000..0422c22\n3493: --- /dev/null\n3494: +++ b/core/test_data/capture.clab.yml\n3495: @@ -0,0 +1,15 @@\n3496: +name: capture\n3497: +topology:\n3498: +  nodes:\n3499: +    srl1:\n3500: +      kind: nokia_srlinux\n3501: +    srl2:\n3502: +      kind: nokia_srlinux\n3503: +    client:\n3504: +      kind: linux\n3505: +      image: alpine:3\n3506: +  links:\n3507: +    - endpoints: [\"srl1:ethernet-1/1\", \"srl2:e1-1\"]\n3508: +    - endpoints: [\"srl1:e1-2\", \"client:eth1\"]\n3509: +    - endpoints: [\"client:eth2\", \"host:client-eth2\"]\n3510: +    - endpoints: [\"client:eth3\", \"mgmt-net:client-eth3\"]\n3511: diff --git a/docs/cmd/capture.md b/docs/cmd/capture.md\n3512: new file mode 100644\n3513: index 0000000..15006ff\n3514: --- /dev/null\n3515: +++ b/docs/cmd/capture.md\n3516: @@ -0,0 +1,134 @@\n3517: +# capture command\n3518: +\n3519: +### Description\n3520: +\n3521: +The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.\n3522: +\n3523: +It works with every runtime:\n3524: +\n3525: +- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).\n3526: +- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).\n3527: +\n3528: +The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.\n3529: +\n3530: +--8<-- \"docs/cmd/deploy.md:env-vars-flags\"\n3531: +\n3532: +### Usage\n3533: +\n3534: +`containerlab [global-flags] capture [local-flags]`\n3535: +\n3536: +### Flags\n3537: +\n3538: +#### topology | name\n3539: +\n3540: +Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.\n3541: +\n3542: +With Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.\n3543: +\n3544: +#### target\n3545: +\n3546: +The local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:\n3547: +\n3548: +```text\n3549: +--target srl1:e1-1,e1-2 --target srl2:e1-1\n3550: +```\n3551: +\n3552: +The node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.\n3553: +\n3554: +Only lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.\n3555: +\n3556: +#### duration\n3557: +\n3558: +The local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).\n3559: +\n3560: +#### packet-limit\n3561: +\n3562: +The local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.\n3563: +\n3564: +#### snap-length\n3565: +\n3566: +The local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.\n3567: +\n3568: +#### write\n3569: +\n3570: +The local `--write | -w` flag names the output file. The default `-` writes to stdout.\n3571: +\n3572: +#### list\n3573: +\n3574: +The local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.\n3575: +\n3576: +### Output\n3577: +\n3578: +The output is one pcapng section:\n3579: +\n3580: +- a Section Header Block with `shb_userappl` set to `containerlab`\n3581: +- one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it\n3582: +- Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes\n3583: +\n3584: +The interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.\n3585: +\n3586: +When the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.\n3587: +\n3588: +`--list -f json` prints an array:\n3589: +\n3590: +```json\n3591: +[\n3592: +  {\n3593: +    \"node\": \"srl1\",\n3594: +    \"interface\": \"e1-1\",\n3595: +    \"alias\": \"ethernet-1/1\",\n3596: +    \"peer_node\": \"srl2\",\n3597: +    \"peer_interface\": \"ethernet-1/1\"\n3598: +  }\n3599: +]\n3600: +```\n3601: +\n3602: +`alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.\n3603: +\n3604: +### How Docker and Podman captures work\n3605: +\n3606: +For each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.\n3607: +\n3608: +- Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.\n3609: +- 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.\n3610: +- Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.\n3611: +- An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.\n3612: +\n3613: +The command needs root (to open packet sockets and enter network namespaces), as other lab commands do.\n3614: +\n3615: +### Long captures\n3616: +\n3617: +Docker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.\n3618: +\n3619: +### Examples\n3620: +\n3621: +#### Capture two nodes for 30 seconds into one file\n3622: +\n3623: +```bash\n3624: +containerlab capture -t srl.clab.yml \\\n3625: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n3626: +```\n3627: +\n3628: +#### Watch a capture live in Wireshark\n3629: +\n3630: +```bash\n3631: +containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n3632: +```\n3633: +\n3634: +#### Capture the first 100 packets with tshark\n3635: +\n3636: +```bash\n3637: +containerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -\n3638: +```\n3639: +\n3640: +#### List the capturable interfaces\n3641: +\n3642: +```bash\n3643: +containerlab capture --name srl --list\n3644: +```\n3645: +\n3646: +#### Capture a c9s lab\n3647: +\n3648: +```bash\n3649: +containerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng\n3650: +```\n3651: diff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md\n3652: index 3dc8e27..2354dc1 100644\n3653: --- a/docs/cmd/inspect/interfaces.md\n3654: +++ b/docs/cmd/inspect/interfaces.md\n3655: @@ -3,10 +3,12 @@\n3656:  ### Description\n3657:  \n3658:  The `inspect interfaces` subcommand provides information about the network interfaces of deployed nodes of a deployed lab.\n3659:  The subcommand gathers information directly from deployed containers, and displays information about their operational state, network interface type, and if applicable, the applied network interface alias.\n3660:  \n3661: +With the [c9s runtime](../../manual/clabernetes/runtime.md#packet-capture), the listing covers the lab link interfaces of each running node, the ones [`capture`](../capture.md) accepts, with the alias the topology used, and the MAC address, index, MTU and operational state read in the node's device container. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields are the same as with Docker.\n3662: +\n3663:  ### Usage\n3664:  \n3665:  `containerlab [global-flags] inspect interfaces [local-flags]`\n3666:  \n3667:  A shorthand can be used for this subcommand: `int` or `intf`.\n3668: diff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md\n3669: index 0ce708d..8174c98 100644\n3670: --- a/docs/manual/clabernetes/runtime.md\n3671: +++ b/docs/manual/clabernetes/runtime.md\n3672: @@ -110,10 +110,13 @@ The c9s runtime currently supports the main lab lifecycle and node operations:\n3673:  | `start` | sets the node's `spec.runState` to `Running` |\n3674:  | `stop` | sets the node's `spec.runState` to `Stopped` |\n3675:  | `restart` | requests a Pod replacement with a `c9s.run/restart-requested` token |\n3676:  | `save` | runs the node's save lifecycle inside its device container |\n3677:  | `events` | watches Clabernetes resources and pods |\n3678: +| `logs` | streams the device container log |\n3679: +| `capture` | captures lab link interfaces through the `clabwire` sidecar into one pcapng stream |\n3680: +| `inspect interfaces` | lists the capturable link interfaces with their sysfs state |\n3681:  | `validate` | checks c9s compatibility without creating Kubernetes resources |\n3682:  | `deploy --dry-run` | compiles and diffs Namespace, ConfigMap, NodeProfile, Link, and Node resources without changing them |\n3683:  | `deploy --emit-crs` | prints the Namespace, ConfigMap, and Topology (or NodeProfile, Link, and Node) manifests deploy would create, without contacting the cluster |\n3684:  \n3685:  ## Requirements\n3686: @@ -141,11 +144,11 @@ Containerlab needs a clabernetes release that has:\n3687:  \n3688:  - Node run state: `nodes.c9s.run` `spec.runState` (`Running` | `Stopped`), the\n3689:    `Stopped` condition, and restart requests through the\n3690:    `c9s.run/restart-requested` annotation\n3691:  - the clabwire packet capture contract: `--nodeName`, repeated `--interface`,\n3692: -  `--format pcapng` and `--list-interfaces`\n3693: +  `--format pcapng`, `--list-interfaces` and `--stop-on-stdin-close`\n3694:  - the namespace-bindable `clabernetes-lab-viewer` and `clabernetes-lab-editor`\n3695:    roles\n3696:  \n3697:  Both features ship in the same release, so containerlab checks one field: the\n3698:  published OpenAPI schema of `nodes.c9s.run` (`/openapi/v3/apis/c9s.run/v1alpha1`)\n3699: @@ -159,10 +162,21 @@ an older release every other command fails like this:\n3700:  the clabernetes release on this cluster is not supported: nodes.c9s.run has no\n3701:  spec.runState (Node run state); the c9s runtime needs clabernetes with Node run\n3702:  state and the clabwire capture contract (0.11 or newer)\n3703:  ```\n3704:  \n3705: +A cluster that passes this check but runs a `clabwire` without\n3706: +`--stop-on-stdin-close` (a development build between the two features) fails\n3707: +the first capture with the same kind of error, naming the pod:\n3708: +\n3709: +```text\n3710: +the clabernetes release on this cluster is not supported: clabwire in pod\n3711: +<namespace>/<pod> does not accept packet-capture --stop-on-stdin-close; the c9s\n3712: +runtime needs clabernetes with Node run state and the clabwire capture contract\n3713: +(0.11 or newer)\n3714: +```\n3715: +\n3716:  Library users can run the check up front with\n3717:  `(*core.CLab).CheckLabRuntimeSupport(ctx)` or the optional\n3718:  `labruntime.SupportChecker` interface; the error wraps\n3719:  `labruntime.ErrUnsupportedRuntimeVersion`.\n3720:  \n3721: @@ -579,10 +593,82 @@ containerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timest\n3722:  \n3723:  It reads the `pods/log` subresource of the node's pod, so RBAC must allow\n3724:  `get` on `pods/log`. Kubernetes returns stdout and stderr as one stream. See\n3725:  the [`logs` command](../../cmd/logs.md) for the flags.\n3726:  \n3727: +## Packet capture\n3728: +\n3729: +[`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of\n3730: +one or more nodes into one pcapng stream. Each node's pod runs the `clabwire`\n3731: +sidecar, which realized the node's links; containerlab execs its capture\n3732: +command (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.\n3733: +No capture service runs in the cluster, and nothing is captured outside the\n3734: +lab's planned link interfaces.\n3735: +\n3736: +```bash\n3737: +# both ends of a link, for 30 seconds\n3738: +containerlab -r c9s capture -t clos.clab.yml \\\n3739: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n3740: +\n3741: +# live in Wireshark until Wireshark or Ctrl+C ends it\n3742: +containerlab -r c9s capture --name clos --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n3743: +\n3744: +# what can be captured, with the peer of each link\n3745: +containerlab -r c9s capture --name clos --list\n3746: +```\n3747: +\n3748: +How it works:\n3749: +\n3750: +- containerlab locates each target node's pod and runs one `clabwire` capture\n3751: +  per node, with `--nodeName`, every requested interface of that node,\n3752: +  `--format pcapng` and `--stop-on-stdin-close`, with stdin attached.\n3753: +- The streams are merged into one section: one Interface Description Block per\n3754: +  target named `<node>:<interface>` (the node as the topology spells it),\n3755: +  written before the first packet, and the packets of every target with their\n3756: +  interface IDs remapped.\n3757: +- Packets are written in timestamp order. Each node's stream arrives over its\n3758: +  own exec stream, so the merged stream holds every packet for 250 ms and\n3759: +  writes the held packets ordered by timestamp. A packet that arrives later\n3760: +  than that, stamped before a packet already written, is written as it comes;\n3761: +  the number of such packets goes to the debug log.\n3762: +- `clabwire` limits one capture to one hour. Longer captures, and captures\n3763: +  without `--duration`, chain captures with a few seconds of overlap and switch\n3764: +  in the middle of it; packets near the switch are matched by content so each\n3765: +  is written once. A follow-up that does not start in time is reported as a\n3766: +  gap, with its time span.\n3767: +- `clabwire` audit records (JSON on its stderr, schema\n3768: +  `c9s.direct-packet-capture-audit/v1alpha1`) with status `Denied` or `Failed`\n3769: +  end the command with their reason. `Started` and `Succeeded` go to the debug\n3770: +  log.\n3771: +\n3772: +Interface names are the names inside the node; targets may also use the alias\n3773: +the topology used for an interface:\n3774: +\n3775: +| Kind | Interface | Alias |\n3776: +| ---- | --------- | ----- |\n3777: +| linux | `eth1` | |\n3778: +| SR Linux | `e1-1` | `ethernet-1/1` |\n3779: +| vr-sros / nokia_sros | `eth3` | `1/1/3` |\n3780: +\n3781: +The management interface and the pod's `c9s0` interface cannot be captured.\n3782: +\n3783: +Ctrl+C or SIGTERM ends a capture cleanly: the output stays a valid pcapng\n3784: +file and the command exits with code 0. Kubernetes does not stop a command\n3785: +when its exec stream closes, but it closes the command's stdin. containerlab\n3786: +closes the stdin of every `clabwire` capture when the capture ends for any\n3787: +reason (the duration or packet limit, Ctrl+C, an error, a failed write of the\n3788: +output such as a closed Wireshark, or a newer segment taking over), and\n3789: +`clabwire` then ends the capture within milliseconds. If the process does not\n3790: +end within three seconds, containerlab cuts the exec stream. A killed\n3791: +containerlab drops the connection, which closes stdin as well.\n3792: +\n3793: +Capturing needs `get` and `create` on `pods/exec` in the lab namespace, which\n3794: +`clabernetes-lab-editor` grants. `inspect interfaces -r c9s` lists the same\n3795: +interfaces, with the MAC address, index, MTU and operational state read from\n3796: +sysfs in the device container (type `veth`, which is how `clabwire` realizes\n3797: +lab links).\n3798: +\n3799:  ## Start, stop, and restart\n3800:  \n3801:  Node lifecycle commands ask the clabernetes controllers for a run state; they\n3802:  never touch Deployments or Pods.\n3803:  \n3804: @@ -863,16 +949,22 @@ implemented by the c9s runtime:\n3805:  | `NodeLocator` | `LocateNode(ctx, NodeRequest) ([]NodeLocation, error)` | the namespace, pod, primary device container, Node UID, exposed ports and LoadBalancer address of nodes |\n3806:  | `NodeAttacher` | `Attach(ctx, AttachRequest, AttachStreams) error` | an interactive exec with stdin, an optional TTY and a resize channel, in the device container or a chosen container |\n3807:  | `NodeLogStreamer` | `StreamLogs(ctx, LogRequest, io.Writer) error` | the device container log, with tail, follow and timestamps |\n3808:  | `NodePortForwarder` | `DialPort(ctx, NodeRequest, port) (net.Conn, error)` | a connection to a TCP port of the node's pod through `pods/portforward` (SSH, web UIs) |\n3809:  | `NodeStatsSampler` | `SampleStats(ctx, InspectRequest) ([]NodeStats, error)` | CPU and memory per node from `metrics.k8s.io` PodMetrics, summing the node's device containers; without the metrics API the error wraps `labruntime.ErrMetricsUnavailable` |\n3810: +| `PacketCapturer` | `CaptureInterfaces(ctx, NodeRequest) ([]CaptureInterface, error)` | the capturable link interfaces of nodes, with alias, peer node and peer interface |\n3811: +| `PacketCapturer` | `Capture(ctx, CaptureRequest, io.Writer) error` | one pcapng stream of the request's targets, for `Duration` (0: until ctx ends), `PacketLimit` and `SnapLength`; gaps go to `OnGap` |\n3812: +| `InterfaceInspector` | `InspectInterfaces(ctx, NodeRequest) ([]*types.ContainerInterfaces, error)` | the `inspect interfaces` view of the link interfaces |\n3813: +| `SupportChecker` | `CheckSupport(ctx, Identity) error` | the clabernetes release check |\n3814:  \n3815:  The `core` package wraps them per lab and node name, accepting the node name\n3816:  as the topology file spells it or as it was sanitized:\n3817:  `CLab.LocateLabRuntimeNodes`, `CLab.AttachLabRuntimeNode`,\n3818: -`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats` and\n3819: -`CLab.NodeLogs`, which also serves Docker and Podman.\n3820: +`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats`,\n3821: +`CLab.CaptureInterfaces`, `CLab.Capture`, `CLab.LabRuntimeInterfaces`,\n3822: +`CLab.CheckLabRuntimeSupport` and `CLab.NodeLogs`, which also serves Docker and\n3823: +Podman.\n3824:  \n3825:  ```go\n3826:  c, err := clabcore.NewContainerLab(\n3827:  \tclabcore.WithRuntime(\"c9s\", nil),\n3828:  \tclabcore.WithTopologyName(\"clos\"),\n3829: @@ -884,10 +976,18 @@ c, err := clabcore.NewContainerLab(\n3830:  if err != nil {\n3831:  \treturn err\n3832:  }\n3833:  \n3834:  conn, err := c.DialLabRuntimeNodePort(ctx, \"srl1\", 22)\n3835: +\n3836: +// stream pcapng to a websocket, a file or Wireshark until ctx ends\n3837: +err = c.Capture(ctx, clablabruntime.CaptureRequest{\n3838: +\tTargets: []clablabruntime.CaptureTarget{\n3839: +\t\t{Node: \"srl1\", Interface: \"ethernet-1/1\"},\n3840: +\t\t{Node: \"srl2\", Interface: \"e1-1\"},\n3841: +\t},\n3842: +}, w)\n3843:  ```\n3844:  \n3845:  ### Acting as a user\n3846:  \n3847:  A server that runs labs for many users acts as each user, so the cluster's RBAC\n3848: @@ -936,11 +1036,12 @@ to:\n3849:  - create, get, list, watch, and delete c9s `Link` and `NodeProfile` resources\n3850:  - get, list, watch, and delete `Topology` resources when Topology-based labs\n3851:    must remain manageable\n3852:  - list and watch Pods\n3853:  - create, get, list, update, and delete ConfigMaps used for local files\n3854: -- exec into device Pods with `pods/exec`\n3855: +- exec into device Pods with `pods/exec`, also for `capture` and `inspect\n3856: +  interfaces` (in the `clabwire` and device containers)\n3857:  - list and delete PersistentVolumeClaims for `destroy --cleanup`\n3858:  - read container logs with `pods/log` for `logs`\n3859:  - port-forward with `pods/portforward` for `NodePortForwarder`\n3860:  - list `pods.metrics.k8s.io` for `NodeStatsSampler`\n3861:  \n3862: @@ -1152,12 +1253,14 @@ Known command differences:\n3863:    `--export-template`, `--restore`, and `--restore-all` are rejected.\n3864:  - Destroy flags `--graceful` and `--keep-mgmt-net` are rejected. `--cleanup`\n3865:    also deletes the lab's persistent claims (saved device state) and removes\n3866:    the local lab directory; a plain destroy keeps the claims.\n3867:  - Local Docker commands on the outer host are not authoritative for c9s labs.\n3868: -- `inspect interfaces` is rejected. Host-side `tc` or netem operations do not\n3869: -  have the same local namespace access they have with Docker labs.\n3870: +- `inspect interfaces` lists only the lab link interfaces (those `capture`\n3871: +  accepts), not the management or pod interfaces. Host-side `tc` or netem\n3872: +  operations do not have the same local namespace access they have with Docker\n3873: +  labs.\n3874:  - `graph` renders from the topology file only: `--mermaid`, `--dot`, `--drawio`\n3875:    and `--offline` work, the default mode that reads running containers is\n3876:    rejected, and so is `--node-filter`. `--drawio` runs the clab-io-draw\n3877:    container, so it needs Docker or Podman on the outer host.\n3878:  - `tools` commands operate on local containers and host networking and are\n3879: diff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md\n3880: index b194b29..4654128 100644\n3881: --- a/docs/manual/wireshark.md\n3882: +++ b/docs/manual/wireshark.md\n3883: @@ -15,10 +15,16 @@ Every lab emulation software must provide its users with the packet capturing ab\n3884:  \n3885:  Containerlab offers a simple way to capture the packets from any interface of any node in the lab. This article will explain how to do that.\n3886:  \n3887:  ///tip\n3888:  \n3889: +The [`containerlab capture`](../cmd/capture.md) command captures one or more lab link interfaces, of one or more nodes, into one pcapng file or stream, with nothing to install in the nodes or on the host:\n3890: +\n3891: +```bash\n3892: +containerlab capture --name quickstart --target srl:e1-1 -w - | wireshark -k -i -\n3893: +```\n3894: +\n3895:  If you are looking for a free Web UI for packet capture with Wireshark, check out our [Edgeshark integration](#edgeshark-integration).\n3896:  ///\n3897:  \n3898:  Consider the following lab topology which highlights the typical points of packet capture.\n3899:  \n3900: diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go\n3901: new file mode 100644\n3902: index 0000000..69d4072\n3903: --- /dev/null\n3904: +++ b/labruntime/clabernetes/capture.go\n3905: @@ -0,0 +1,1202 @@\n3906: +package clabernetes\n3907: +\n3908: +import (\n3909: +\t\"bytes\"\n3910: +\t\"context\"\n3911: +\t\"encoding/json\"\n3912: +\t\"errors\"\n3913: +\t\"fmt\"\n3914: +\t\"hash/fnv\"\n3915: +\t\"io\"\n3916: +\t\"os\"\n3917: +\t\"sort\"\n3918: +\t\"strconv\"\n3919: +\t\"strings\"\n3920: +\t\"sync\"\n3921: +\t\"time\"\n3922: +\n3923: +\t\"github.com/charmbracelet/log\"\n3924: +\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n3925: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n3926: +\t\"golang.org/x/sync/errgroup\"\n3927: +)\n3928: +\n3929: +// The clabwire packet capture contract (clabernetes 0.11 or newer).\n3930: +const (\n3931: +\tclabwireContainer = \"clabwire\"\n3932: +\tclabwireManager   = \"/clabernetes/manager\"\n3933: +\t// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.\n3934: +\tcaptureAuditSchema = \"c9s.direct-packet-capture-audit/v1alpha1\"\n3935: +\n3936: +\tcaptureAuditStarted   = \"Started\"\n3937: +\tcaptureAuditSucceeded = \"Succeeded\"\n3938: +\tcaptureAuditFailed    = \"Failed\"\n3939: +\tcaptureAuditDenied    = \"Denied\"\n3940: +\n3941: +\t// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.\n3942: +\tmaxCaptureSegment = time.Hour\n3943: +\t// maxClabwirePackets is the packet limit of a single clabwire capture.\n3944: +\tmaxClabwirePackets = 1_000_000\n3945: +\t// maxCaptureOverlap is how long two chained segments run side by side.\n3946: +\tmaxCaptureOverlap = 10 * time.Second\n3947: +\t// maxCaptureCutWindow is the half-width of the window around the cut in which packets of\n3948: +\t// two segments are matched by content; it covers the difference between the timestamps\n3949: +\t// two clabwire processes give the same packet.\n3950: +\tmaxCaptureCutWindow = 500 * time.Millisecond\n3951: +\t// minCaptureSegment is the shortest segment the chain requests.\n3952: +\tminCaptureSegment = 100 * time.Millisecond\n3953: +\t// captureEndGrace is how long a capture with a duration waits for its last clabwire\n3954: +\t// process to end after the duration passed.\n3955: +\tcaptureEndGrace = 30 * time.Second\n3956: +\t// captureStartRetries bounds the attempts to start a follow-up segment.\n3957: +\tcaptureStartRetries = 3\n3958: +\t// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was\n3959: +\t// closed before the stream is cut.\n3960: +\tcaptureStdinCloseGrace = 3 * time.Second\n3961: +\t// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A\n3962: +\t// Kubernetes exec does not stop its process when the stream ends, but it closes the\n3963: +\t// process's stdin, so every capture runs with stdin attached and this flag.\n3964: +\tclabwireStopOnStdinClose = \"--stop-on-stdin-close\"\n3965: +\n3966: +\t// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests\n3967: +\t// without hour-long captures.\n3968: +\tenvCaptureSegment = \"CLAB_C9S_CAPTURE_SEGMENT\"\n3969: +\t// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets\n3970: +\t// of other nodes stamped earlier but delivered later still go out before it.\n3971: +\tdefaultCaptureReorderWindow = 250 * time.Millisecond\n3972: +\t// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.\n3973: +\t// It is an internal knob, not a supported setting.\n3974: +\tenvCaptureReorderWindow = \"CLAB_C9S_CAPTURE_REORDER_WINDOW\"\n3975: +)\n3976: +\n3977: +// podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns\n3978: +// a *labruntime.CommandExitError.\n3979: +type podExecFunc func(\n3980: +\tctx context.Context,\n3981: +\tnamespace, pod, container string,\n3982: +\tcommand []string,\n3983: +\tstdin io.Reader,\n3984: +\tstdout, stderr io.Writer,\n3985: +) error\n3986: +\n3987: +// clabwireInterface is one entry of `packet-capture --list-interfaces`.\n3988: +type clabwireInterface struct {\n3989: +\tNode          string `json:\"node\"`\n3990: +\tInterface     string `json:\"interface\"`\n3991: +\tAlias         string `json:\"alias,omitempty\"`\n3992: +\tPeerNode      string `json:\"peerNode\"`\n3993: +\tPeerInterface string `json:\"peerInterface\"`\n3994: +}\n3995: +\n3996: +// captureAudit is one clabwire audit line.\n3997: +type captureAudit struct {\n3998: +\tSchemaVersion string    `json:\"schemaVersion\"`\n3999: +\tTime          time.Time `json:\"time\"`\n4000: +\tStatus        string    `json:\"status\"`\n4001: +\tNodeName      string    `json:\"nodeName\"`\n4002: +\tFormat        string    `json:\"format\"`\n4003: +\tReason        string    `json:\"reason\"`\n4004: +\tPackets       int       `json:\"packets\"`\n4005: +\tInterfaces    []struct {\n4006: +\t\tName    string `json:\"name\"`\n4007: +\t\tID      string `json:\"id\"`\n4008: +\t\tPackets int    `json:\"packets\"`\n4009: +\t} `json:\"interfaces\"`\n4010: +}\n4011: +\n4012: +func (r *Runtime) execInPodContainer() podExecFunc {\n4013: +\tif r.podExec != nil {\n4014: +\t\treturn r.podExec\n4015: +\t}\n4016: +\n4017: +\treturn r.streamPodExec\n4018: +}\n4019: +\n4020: +// captureSegmentLength is the length of one clabwire capture before the next takes over.\n4021: +func (r *Runtime) captureSegmentLength() time.Duration {\n4022: +\tif r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {\n4023: +\t\treturn r.captureSegment\n4024: +\t}\n4025: +\n4026: +\treturn maxCaptureSegment\n4027: +}\n4028: +\n4029: +// captureReorderWindowLength is the reorder window of the merged stream; zero disables\n4030: +// reordering.\n4031: +func (r *Runtime) captureReorderWindowLength() time.Duration {\n4032: +\tswitch {\n4033: +\tcase r.captureReorderWindow < 0:\n4034: +\t\treturn 0\n4035: +\tcase r.captureReorderWindow > 0:\n4036: +\t\treturn r.captureReorderWindow\n4037: +\t}\n4038: +\n4039: +\treturn defaultCaptureReorderWindow\n4040: +}\n4041: +\n4042: +// captureReorderWindowFromEnv reads the reorder window knob: unset or invalid keeps the\n4043: +// default (0), \"0\" disables reordering (-1).\n4044: +func captureReorderWindowFromEnv() time.Duration {\n4045: +\tvalue, err := time.ParseDuration(os.Getenv(envCaptureReorderWindow))\n4046: +\tswitch {\n4047: +\tcase err != nil || value < 0:\n4048: +\t\treturn 0\n4049: +\tcase value == 0:\n4050: +\t\treturn -1\n4051: +\t}\n4052: +\n4053: +\treturn value\n4054: +}\n4055: +\n4056: +func captureSegmentFromEnv() time.Duration {\n4057: +\tvalue, err := time.ParseDuration(os.Getenv(envCaptureSegment))\n4058: +\tif err != nil || value <= 0 {\n4059: +\t\treturn 0\n4060: +\t}\n4061: +\n4062: +\treturn value\n4063: +}\n4064: +\n4065: +// CaptureInterfaces lists the capturable lab link interfaces of the requested nodes, or of every\n4066: +// node, as clabwire reports them, with their peers. Node names are reported as the topology\n4067: +// spells them.\n4068: +func (r *Runtime) CaptureInterfaces(\n4069: +\tctx context.Context,\n4070: +\treq clablabruntime.NodeRequest,\n4071: +) ([]clablabruntime.CaptureInterface, error) {\n4072: +\tr, err := r.connect(ctx, req.Identity)\n4073: +\tif err != nil {\n4074: +\t\treturn nil, err\n4075: +\t}\n4076: +\n4077: +\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n4078: +\t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n4079: +\t})\n4080: +\tif err != nil {\n4081: +\t\treturn nil, err\n4082: +\t}\n4083: +\tif len(req.Nodes) == 0 {\n4084: +\t\t// a lab-wide listing skips nodes that do not run\n4085: +\t\trunning := locations[:0]\n4086: +\t\tfor _, location := range locations {\n4087: +\t\t\tif location.Pod != \"\" {\n4088: +\t\t\t\trunning = append(running, location)\n4089: +\t\t\t}\n4090: +\t\t}\n4091: +\t\tlocations = running\n4092: +\t}\n4093: +\n4094: +\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n4095: +\tif err != nil {\n4096: +\t\treturn nil, err\n4097: +\t}\n4098: +\tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n4099: +\tif err != nil {\n4100: +\t\treturn nil, err\n4101: +\t}\n4102: +\n4103: +\tresult := make([]clablabruntime.CaptureInterface, 0)\n4104: +\tfor _, location := range locations {\n4105: +\t\tfor _, entry := range listed[location.NodeName] {\n4106: +\t\t\tresult = append(result, clablabruntime.CaptureInterface{\n4107: +\t\t\t\tNode:          names.display(entry.Node),\n4108: +\t\t\t\tInterface:     entry.Interface,\n4109: +\t\t\t\tAlias:         entry.Alias,\n4110: +\t\t\t\tPeerNode:      names.display(entry.PeerNode),\n4111: +\t\t\t\tPeerInterface: entry.PeerInterface,\n4112: +\t\t\t})\n4113: +\t\t}\n4114: +\t}\n4115: +\tsort.SliceStable(result, func(i, j int) bool {\n4116: +\t\tif result[i].Node != result[j].Node {\n4117: +\t\t\treturn result[i].Node < result[j].Node\n4118: +\t\t}\n4119: +\n4120: +\t\treturn result[i].Interface < result[j].Interface\n4121: +\t})\n4122: +\n4123: +\treturn result, nil\n4124: +}\n4125: +\n4126: +// listCaptureInterfaces runs one --list-interfaces per pod and returns the entries per Node.\n4127: +func (r *Runtime) listCaptureInterfaces(\n4128: +\tctx context.Context,\n4129: +\tlab string,\n4130: +\tlocations []clablabruntime.NodeLocation,\n4131: +) (map[string][]clabwireInterface, error) {\n4132: +\tpods := map[string]clablabruntime.NodeLocation{}\n4133: +\twanted := map[string]bool{}\n4134: +\tfor _, location := range locations {\n4135: +\t\tif location.Pod == \"\" {\n4136: +\t\t\treturn nil, fmt.Errorf(\"c9s node %s/%s/%s has no pod; is it running?\",\n4137: +\t\t\t\tlocation.Namespace, lab, location.NodeName)\n4138: +\t\t}\n4139: +\t\tpods[location.Namespace+\"/\"+location.Pod] = location\n4140: +\t\twanted[location.NodeName] = true\n4141: +\t}\n4142: +\n4143: +\tvar mu sync.Mutex\n4144: +\tresult := map[string][]clabwireInterface{}\n4145: +\tgroup, groupCtx := errgroup.WithContext(ctx)\n4146: +\tgroup.SetLimit(interfaceSampleWorkers)\n4147: +\texec := r.execInPodContainer()\n4148: +\tfor _, location := range pods {\n4149: +\t\tgroup.Go(func() error {\n4150: +\t\t\tvar stdout, stderr bytes.Buffer\n4151: +\t\t\terr := exec(groupCtx, location.Namespace, location.Pod, clabwireContainer,\n4152: +\t\t\t\t[]string{clabwireManager, \"node-runtime\", \"packet-capture\", \"--list-interfaces\"},\n4153: +\t\t\t\tnil, &stdout, &stderr)\n4154: +\t\t\tif err != nil {\n4155: +\t\t\t\treturn fmt.Errorf(\"failed to list the capturable interfaces of pod %s/%s: %w%s\",\n4156: +\t\t\t\t\tlocation.Namespace, location.Pod, err, stderrSuffix(stderr.Bytes()))\n4157: +\t\t\t}\n4158: +\n4159: +\t\t\tvar entries []clabwireInterface\n4160: +\t\t\tif err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {\n4161: +\t\t\t\treturn fmt.Errorf(\"failed to parse the capturable interfaces of pod %s/%s: %w\",\n4162: +\t\t\t\t\tlocation.Namespace, location.Pod, err)\n4163: +\t\t\t}\n4164: +\n4165: +\t\t\tmu.Lock()\n4166: +\t\t\tdefer mu.Unlock()\n4167: +\t\t\tfor _, entry := range entries {\n4168: +\t\t\t\tif wanted[entry.Node] {\n4169: +\t\t\t\t\tresult[entry.Node] = append(result[entry.Node], entry)\n4170: +\t\t\t\t}\n4171: +\t\t\t}\n4172: +\n4173: +\t\t\treturn nil\n4174: +\t\t})\n4175: +\t}\n4176: +\tif err := group.Wait(); err != nil {\n4177: +\t\treturn nil, err\n4178: +\t}\n4179: +\n4180: +\treturn result, nil\n4181: +}\n4182: +\n4183: +func stderrSuffix(stderr []byte) string {\n4184: +\ttext := strings.TrimSpace(string(stderr))\n4185: +\tif text == \"\" {\n4186: +\t\treturn \"\"\n4187: +\t}\n4188: +\n4189: +\treturn \": \" + text\n4190: +}\n4191: +\n4192: +// nodeNames maps the node names the cluster carries to the names the topology file uses.\n4193: +type nodeNames map[string]string\n4194: +\n4195: +func (n nodeNames) display(name string) string {\n4196: +\tif original := n[name]; original != \"\" {\n4197: +\t\treturn original\n4198: +\t}\n4199: +\n4200: +\treturn name\n4201: +}\n4202: +\n4203: +// nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the\n4204: +// lab's Nodes.\n4205: +func (r *Runtime) nodeDisplayNames(\n4206: +\tctx context.Context,\n4207: +\tlab string,\n4208: +\tlocations []clablabruntime.NodeLocation,\n4209: +) (nodeNames, error) {\n4210: +\tnames := nodeNames{}\n4211: +\tif len(locations) == 0 {\n4212: +\t\treturn names, nil\n4213: +\t}\n4214: +\n4215: +\tnodes, err := r.nodesForTopology(ctx, lab, locations[0].Namespace)\n4216: +\tif err != nil {\n4217: +\t\treturn nil, err\n4218: +\t}\n4219: +\tfor idx := range nodes.Items {\n4220: +\t\tif original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != \"\" {\n4221: +\t\t\tnames[nodes.Items[idx].GetName()] = original\n4222: +\t\t}\n4223: +\t}\n4224: +\n4225: +\treturn names, nil\n4226: +}\n4227: +\n4228: +// captureGroup is the part of a capture one clabwire process serves: the requested interfaces of\n4229: +// one node, in one pod.\n4230: +type captureGroup struct {\n4231: +\tlocation clablabruntime.NodeLocation\n4232: +\tdisplay  string\n4233: +\t// interfaces are the planned interface names, in the order the merged stream lists them.\n4234: +\tinterfaces []string\n4235: +\t// ids are the merged interface IDs of interfaces.\n4236: +\tids []uint32\n4237: +}\n4238: +\n4239: +// resolvedCapture is a validated capture request.\n4240: +type resolvedCapture struct {\n4241: +\tgroups []*captureGroup\n4242: +\t// names are the merged interface names (<node>:<interface>), indexed by merged ID.\n4243: +\tnames []string\n4244: +}\n4245: +\n4246: +// resolveCaptureTargets locates every target node, checks every interface against the\n4247: +// interfaces clabwire allows, and groups the targets per node.\n4248: +func (r *Runtime) resolveCaptureTargets(\n4249: +\tctx context.Context,\n4250: +\treq clablabruntime.CaptureRequest,\n4251: +) (*resolvedCapture, error) {\n4252: +\tnodeOrder := make([]string, 0, len(req.Targets))\n4253: +\tseenNodes := map[string]bool{}\n4254: +\tfor _, target := range req.Targets {\n4255: +\t\tif !seenNodes[target.Node] {\n4256: +\t\t\tseenNodes[target.Node] = true\n4257: +\t\t\tnodeOrder = append(nodeOrder, target.Node)\n4258: +\t\t}\n4259: +\t}\n4260: +\n4261: +\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n4262: +\t\tName: req.Name, Namespace: req.Namespace, Nodes: nodeOrder, Identity: req.Identity,\n4263: +\t})\n4264: +\tif err != nil {\n4265: +\t\treturn nil, err\n4266: +\t}\n4267: +\tbyRequest := make(map[string]clablabruntime.NodeLocation, len(nodeOrder))\n4268: +\tfor idx, name := range nodeOrder {\n4269: +\t\tbyRequest[name] = locations[idx]\n4270: +\t}\n4271: +\n4272: +\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n4273: +\tif err != nil {\n4274: +\t\treturn nil, err\n4275: +\t}\n4276: +\tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n4277: +\tif err != nil {\n4278: +\t\treturn nil, err\n4279: +\t}\n4280: +\n4281: +\tresolved := &resolvedCapture{}\n4282: +\tgroups := map[string]*captureGroup{}\n4283: +\tseen := map[string]bool{}\n4284: +\tfor _, target := range req.Targets {\n4285: +\t\tlocation := byRequest[target.Node]\n4286: +\t\tentry, ok := findCaptureInterface(listed[location.NodeName], target.Interface)\n4287: +\t\tif !ok {\n4288: +\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n4289: +\t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n4290: +\t\t\t\tdescribeCaptureInterfaces(listed[location.NodeName]))\n4291: +\t\t}\n4292: +\n4293: +\t\tkey := location.NodeName + \"\\x00\" + entry.Interface\n4294: +\t\tif seen[key] {\n4295: +\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n4296: +\t\t\t\tentry.Interface, target.Node)\n4297: +\t\t}\n4298: +\t\tseen[key] = true\n4299: +\n4300: +\t\tgroup := groups[location.NodeName]\n4301: +\t\tif group == nil {\n4302: +\t\t\tgroup = &captureGroup{\n4303: +\t\t\t\tlocation: location,\n4304: +\t\t\t\tdisplay:  names.display(location.NodeName),\n4305: +\t\t\t}\n4306: +\t\t\tgroups[location.NodeName] = group\n4307: +\t\t\tresolved.groups = append(resolved.groups, group)\n4308: +\t\t}\n4309: +\n4310: +\t\tid := uint32(len(resolved.names)) //nolint:gosec // bounded by the targets\n4311: +\t\tgroup.interfaces = append(group.interfaces, entry.Interface)\n4312: +\t\tgroup.ids = append(group.ids, id)\n4313: +\t\tresolved.names = append(resolved.names, group.display+\":\"+entry.Interface)\n4314: +\t}\n4315: +\n4316: +\treturn resolved, nil\n4317: +}\n4318: +\n4319: +// findCaptureInterface matches a requested interface by its planned name or its alias.\n4320: +func findCaptureInterface(entries []clabwireInterface, name string) (clabwireInterface, bool) {\n4321: +\tfor _, entry := range entries {\n4322: +\t\tif entry.Interface == name {\n4323: +\t\t\treturn entry, true\n4324: +\t\t}\n4325: +\t}\n4326: +\tfor _, entry := range entries {\n4327: +\t\tif entry.Alias != \"\" && entry.Alias == name {\n4328: +\t\t\treturn entry, true\n4329: +\t\t}\n4330: +\t}\n4331: +\n4332: +\treturn clabwireInterface{}, false\n4333: +}\n4334: +\n4335: +func describeCaptureInterfaces(entries []clabwireInterface) string {\n4336: +\tif len(entries) == 0 {\n4337: +\t\treturn \"none\"\n4338: +\t}\n4339: +\n4340: +\tnames := make([]string, 0, len(entries))\n4341: +\tfor _, entry := range entries {\n4342: +\t\tname := entry.Interface\n4343: +\t\tif entry.Alias != \"\" {\n4344: +\t\t\tname += \" (\" + entry.Alias + \")\"\n4345: +\t\t}\n4346: +\t\tnames = append(names, name)\n4347: +\t}\n4348: +\n4349: +\treturn strings.Join(names, \", \")\n4350: +}\n4351: +\n4352: +// Capture streams pcapng from lab link interfaces to w: one section, one Interface Description\n4353: +// Block per target in request order named <node>:<interface>, then the packets of every target.\n4354: +//\n4355: +// Each node's interfaces are captured by one clabwire process in the node's pod. clabwire limits\n4356: +// a capture to one hour, so a longer capture (or one without Duration) chains captures: the next\n4357: +// one starts before the current one ends, and the stream switches at a cut in the overlap. See\n4358: +// captureChain for how packets of the overlap are kept once.\n4359: +//\n4360: +// Packets go out in timestamp order across nodes, through a reorder buffer (captureReorder).\n4361: +//\n4362: +// Every clabwire process runs with stdin attached and --stop-on-stdin-close: a Kubernetes exec\n4363: +// does not stop its process when the stream closes, so containerlab closes stdin whenever a\n4364: +// segment ends (the capture ends, fails, its output fails, or a newer segment took over) and\n4365: +// clabwire ends the capture itself.\n4366: +//\n4367: +// Capture returns when Duration has passed, PacketLimit packets were written, or ctx ends; an\n4368: +// ended ctx is not an error. Every block reaches w in one write, so the stream is a valid capture\n4369: +// whenever it stops. A clabwire Denied or Failed audit record is returned as an error.\n4370: +func (r *Runtime) Capture(\n4371: +\tctx context.Context,\n4372: +\treq clablabruntime.CaptureRequest,\n4373: +\tw io.Writer,\n4374: +) error {\n4375: +\tif err := clabcapture.ValidateRequest(&req); err != nil {\n4376: +\t\treturn err\n4377: +\t}\n4378: +\n4379: +\tr, err := r.connect(ctx, req.Identity)\n4380: +\tif err != nil {\n4381: +\t\treturn err\n4382: +\t}\n4383: +\n4384: +\tresolved, err := r.resolveCaptureTargets(ctx, req)\n4385: +\tif err != nil {\n4386: +\t\treturn err\n4387: +\t}\n4388: +\n4389: +\tcaptureCtx, stop := context.WithCancel(ctx)\n4390: +\tdefer stop()\n4391: +\n4392: +\tout, err := clabcapture.NewOutput(w, resolved.names, req.SnapLength, req.PacketLimit,\n4393: +\t\tr.captureReorderWindowLength(), stop)\n4394: +\tif err != nil {\n4395: +\t\treturn err\n4396: +\t}\n4397: +\n4398: +\trun := &captureRun{\n4399: +\t\tr:       r,\n4400: +\t\treq:     req,\n4401: +\t\tout:     out,\n4402: +\t\tsegment: r.captureSegmentLength(),\n4403: +\t}\n4404: +\tif req.Duration > 0 {\n4405: +\t\trun.deadline = time.Now().Add(req.Duration)\n4406: +\t}\n4407: +\trun.overlap = min(maxCaptureOverlap, run.segment/3)\n4408: +\trun.window = min(maxCaptureCutWindow, run.overlap/4)\n4409: +\n4410: +\tif req.Duration > 0 {\n4411: +\t\t// a clabwire process that does not end on its own does not hold the capture open\n4412: +\t\tvar cancelTimeout context.CancelFunc\n4413: +\t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx,\n4414: +\t\t\treq.Duration+run.overlap+captureEndGrace)\n4415: +\t\tdefer cancelTimeout()\n4416: +\t}\n4417: +\n4418: +\tgroup, groupCtx := errgroup.WithContext(captureCtx)\n4419: +\tfor _, captureGroup := range resolved.groups {\n4420: +\t\tchain := &captureChain{capture: run, group: captureGroup}\n4421: +\t\tgroup.Go(func() error {\n4422: +\t\t\treturn chain.run(groupCtx)\n4423: +\t\t})\n4424: +\t}\n4425: +\n4426: +\terr = group.Wait()\n4427: +\tif writeErr := out.Close(); writeErr != nil {\n4428: +\t\treturn writeErr\n4429: +\t}\n4430: +\tif err != nil && !(errors.Is(err, context.Canceled) && captureCtx.Err() != nil) {\n4431: +\t\treturn err\n4432: +\t}\n4433: +\n4434: +\treturn nil\n4435: +}\n4436: +\n4437: +// captureRun is the state a capture's chains share.\n4438: +type captureRun struct {\n4439: +\tr   *Runtime\n4440: +\treq clablabruntime.CaptureRequest\n4441: +\t// out is the merged stream; it writes the packets of every chain in timestamp order and\n4442: +\t// stops every chain once the packet limit is reached.\n4443: +\tout *clabcapture.Output\n4444: +\n4445: +\tsegment  time.Duration\n4446: +\toverlap  time.Duration\n4447: +\twindow   time.Duration\n4448: +\tdeadline time.Time\n4449: +}\n4450: +\n4451: +// emit writes a packet under its merged interface ID. It reports false once the packet limit is\n4452: +// reached and the capture stops.\n4453: +func (run *captureRun) emit(id uint32, packet *clabcapture.Packet) (bool, error) {\n4454: +\treturn run.out.Emit(id, packet)\n4455: +}\n4456: +\n4457: +func (run *captureRun) reportGap(gap clablabruntime.CaptureGap) {\n4458: +\tclabcapture.ReportGap(run.req.OnGap, gap)\n4459: +}\n4460: +\n4461: +// captureSegment is one clabwire capture process of a chain.\n4462: +type captureSegment struct {\n4463: +\tindex      int\n4464: +\tlocalStart time.Time\n4465: +\tduration   time.Duration\n4466: +\tcancel     context.CancelFunc\n4467: +\t// closeStdin closes the stdin of the segment's clabwire process, which ends it; it may be\n4468: +\t// called any number of times.\n4469: +\tcloseStdin func()\n4470: +\t// stopTimer closes stdin once the segment is no longer needed after a switch-over.\n4471: +\tstopTimer *time.Timer\n4472: +\t// started and ended are the pod-clock times of the Started and Succeeded audit records.\n4473: +\tstarted time.Time\n4474: +\tended   time.Time\n4475: +\tdone    bool\n4476: +}\n4477: +\n4478: +func (s *captureSegment) plannedEnd() time.Time {\n4479: +\treturn s.started.Add(s.duration)\n4480: +}\n4481: +\n4482: +// segmentEvent is something a segment reported: a packet, an audit record, or its end.\n4483: +type segmentEvent struct {\n4484: +\tsegment *captureSegment\n4485: +\tpacket  *clabcapture.Packet\n4486: +\taudit   *captureAudit\n4487: +\tdone    bool\n4488: +\terr     error\n4489: +}\n4490: +\n4491: +// captureChain runs the chained clabwire captures of one group.\n4492: +//\n4493: +// Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both\n4494: +// capture the same packets for a while. clabwire stamps packets when it reads them, so two\n4495: +// processes give the same packet timestamps a few microseconds apart, and timestamps alone\n4496: +// cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by\n4497: +// content close to the cut:\n4498: +//\n4499: +//  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is\n4500: +//     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.\n4501: +//  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the\n4502: +//     content of what it wrote since segment k+1 started.\n4503: +//  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped\n4504: +//     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped\n4505: +//     when segment k wrote the same bytes on the same interface, and every other one is written.\n4506: +//     From then on segment k+1 streams live.\n4507: +//\n4508: +// Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its\n4509: +// planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other\n4510: +// nodes' later packets do not overtake them in the merged stream.\n4511: +//\n4512: +// W (500 ms, less for short test segments) covers the stamping difference. Identical frames on\n4513: +// the same interface within W of the cut can be paired with each other, which can drop a true\n4514: +// repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves\n4515: +// a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.\n4516: +type captureChain struct {\n4517: +\tcapture *captureRun\n4518: +\tgroup   *captureGroup\n4519: +\n4520: +\tevents chan segmentEvent\n4521: +\twg     sync.WaitGroup\n4522: +\n4523: +\tactive *captureSegment\n4524: +\tnext   *captureSegment\n4525: +\t// cut is the switch time between active and next, in nanoseconds; zero until known.\n4526: +\tcut int64\n4527: +\t// emitted remembers the content of the packets active wrote while next runs.\n4528: +\temitted map[uint64]int\n4529: +\t// held are the packets of next until active ends.\n4530: +\theld     []*clabcapture.Packet\n4531: +\tsegments int\n4532: +\tretries  int\n4533: +\t// final is set once no further segment is due.\n4534: +\tfinal bool\n4535: +\t// stopping is set once ctx ended: the segments are asked to end and what they still\n4536: +\t// deliver is written.\n4537: +\tstopping bool\n4538: +}\n4539: +\n4540: +// run runs the chain until its last segment ended. When ctx ends, it stops the segments and\n4541: +// keeps writing the packets they read until then; a segment that does not end within\n4542: +// captureStdinCloseGrace is cut.\n4543: +func (c *captureChain) run(ctx context.Context) error {\n4544: +\tc.events = make(chan segmentEvent, 256)\n4545: +\t// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them\n4546: +\tsegmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))\n4547: +\tvar abort *time.Timer\n4548: +\tdefer func() {\n4549: +\t\tif abort != nil {\n4550: +\t\t\tabort.Stop()\n4551: +\t\t}\n4552: +\t\tcancel()\n4553: +\t\tc.drain()\n4554: +\t\tc.capture.out.Release(c)\n4555: +\t}()\n4556: +\n4557: +\tc.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))\n4558: +\ttimer := time.NewTimer(c.nextStartIn())\n4559: +\tdefer timer.Stop()\n4560: +\n4561: +\tdone := ctx.Done()\n4562: +\tfor {\n4563: +\t\tselect {\n4564: +\t\tcase <-done:\n4565: +\t\t\tdone = nil\n4566: +\t\t\tc.stop(timer)\n4567: +\t\t\tabort = time.AfterFunc(captureStdinCloseGrace, cancel)\n4568: +\t\tcase <-segmentsCtx.Done():\n4569: +\t\t\treturn nil\n4570: +\t\tcase <-timer.C:\n4571: +\t\t\tif c.next == nil && !c.final {\n4572: +\t\t\t\tc.startNext(segmentsCtx)\n4573: +\t\t\t}\n4574: +\t\tcase event := <-c.events:\n4575: +\t\t\tstop, err := c.handle(segmentsCtx, event, timer)\n4576: +\t\t\tif err != nil || stop {\n4577: +\t\t\t\treturn err\n4578: +\t\t\t}\n4579: +\t\t}\n4580: +\t}\n4581: +}\n4582: +\n4583: +// stop ends the chain early, like a deadline would: no further segment starts and the running\n4584: +// ones are asked to end. The chain then writes what they deliver until they ended.\n4585: +func (c *captureChain) stop(timer *time.Timer) {\n4586: +\tc.stopping = true\n4587: +\tc.final = true\n4588: +\ttimer.Stop()\n4589: +\tc.active.closeStdin()\n4590: +\tif c.next != nil {\n4591: +\t\tc.next.closeStdin()\n4592: +\t}\n4593: +}\n4594: +\n4595: +// drain waits for the segment goroutines after the chain ended.\n4596: +func (c *captureChain) drain() {\n4597: +\tdone := make(chan struct{})\n4598: +\tgo func() {\n4599: +\t\tc.wg.Wait()\n4600: +\t\tclose(done)\n4601: +\t}()\n4602: +\tfor {\n4603: +\t\tselect {\n4604: +\t\tcase <-done:\n4605: +\t\t\treturn\n4606: +\t\tcase <-c.events:\n4607: +\t\t}\n4608: +\t}\n4609: +}\n4610: +\n4611: +// segmentDuration is the requested duration of a segment starting now.\n4612: +func (c *captureChain) segmentDuration(now time.Time) time.Duration {\n4613: +\tduration := c.capture.segment\n4614: +\tif !c.capture.deadline.IsZero() {\n4615: +\t\tduration = min(duration, c.capture.deadline.Sub(now))\n4616: +\t}\n4617: +\n4618: +\treturn max(duration, minCaptureSegment)\n4619: +}\n4620: +\n4621: +// nextStartIn is the time until the follow-up of the active segment is due. It marks the chain\n4622: +// final when none is due.\n4623: +func (c *captureChain) nextStartIn() time.Duration {\n4624: +\tif c.stopping {\n4625: +\t\tc.final = true\n4626: +\t\treturn maxCaptureSegment\n4627: +\t}\n4628: +\tactiveEnd := c.active.localStart.Add(c.active.duration)\n4629: +\tif !c.capture.deadline.IsZero() &&\n4630: +\t\t!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {\n4631: +\t\tc.final = true\n4632: +\t\treturn maxCaptureSegment\n4633: +\t}\n4634: +\tc.final = false\n4635: +\n4636: +\treturn max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)\n4637: +}\n4638: +\n4639: +func (c *captureChain) startNext(ctx context.Context) {\n4640: +\tc.next = c.start(ctx, c.segmentDuration(time.Now()))\n4641: +\tc.emitted = map[uint64]int{}\n4642: +\tc.held = nil\n4643: +\tc.cut = 0\n4644: +}\n4645: +\n4646: +func (c *captureChain) handle(\n4647: +\tctx context.Context,\n4648: +\tevent segmentEvent,\n4649: +\ttimer *time.Timer,\n4650: +) (bool, error) {\n4651: +\tsegment := event.segment\n4652: +\n4653: +\tswitch {\n4654: +\tcase event.audit != nil:\n4655: +\t\treturn false, c.handleAudit(segment, event.audit)\n4656: +\tcase event.packet != nil:\n4657: +\t\treturn c.handlePacket(segment, event.packet)\n4658: +\tcase event.done:\n4659: +\t\tsegment.done = true\n4660: +\t\tif segment.stopTimer != nil {\n4661: +\t\t\tsegment.stopTimer.Stop()\n4662: +\t\t}\n4663: +\t\tif event.err != nil && !c.stopping {\n4664: +\t\t\tif segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {\n4665: +\t\t\t\t// the follow-up did not start; try again while the active one still runs\n4666: +\t\t\t\tc.retries++\n4667: +\t\t\t\tlog.Warn(\"Capture follow-up segment failed to start, retrying\",\n4668: +\t\t\t\t\t\"node\", c.group.display, \"error\", event.err)\n4669: +\t\t\t\tc.next = nil\n4670: +\t\t\t\tresetTimer(timer, time.Second)\n4671: +\n4672: +\t\t\t\treturn false, nil\n4673: +\t\t\t}\n4674: +\n4675: +\t\t\treturn true, fmt.Errorf(\"capture on c9s node %s/%s/%s failed: %w\",\n4676: +\t\t\t\tc.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)\n4677: +\t\t}\n4678: +\t\tif segment != c.active {\n4679: +\t\t\treturn false, nil\n4680: +\t\t}\n4681: +\n4682: +\t\treturn c.switchSegments(ctx, timer)\n4683: +\t}\n4684: +\n4685: +\treturn false, nil\n4686: +}\n4687: +\n4688: +func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {\n4689: +\tswitch audit.Status {\n4690: +\tcase captureAuditStarted:\n4691: +\t\tsegment.started = audit.Time\n4692: +\t\tlog.Debug(\"Capture segment started\", \"node\", c.group.display, \"segment\", segment.index,\n4693: +\t\t\t\"interfaces\", strings.Join(c.group.interfaces, \",\"), \"duration\", segment.duration)\n4694: +\t\tif segment == c.next && !c.active.started.IsZero() {\n4695: +\t\t\tc.setCut()\n4696: +\t\t}\n4697: +\t\tif segment == c.next {\n4698: +\t\t\tc.retries = 0\n4699: +\t\t}\n4700: +\tcase captureAuditSucceeded:\n4701: +\t\tsegment.ended = audit.Time\n4702: +\t\tlog.Debug(\"Capture segment succeeded\", \"node\", c.group.display,\n4703: +\t\t\t\"segment\", segment.index, \"packets\", audit.Packets)\n4704: +\tcase captureAuditDenied, captureAuditFailed:\n4705: +\t\treturn captureAuditError(c.group.display, audit)\n4706: +\t}\n4707: +\n4708: +\treturn nil\n4709: +}\n4710: +\n4711: +// captureAuditError turns a Denied or Failed clabwire audit record into an error.\n4712: +func captureAuditError(node string, audit *captureAudit) error {\n4713: +\tverb := \"failed\"\n4714: +\tif audit.Status == captureAuditDenied {\n4715: +\t\tverb = \"was denied\"\n4716: +\t}\n4717: +\tinterfaces := make([]string, 0, len(audit.Interfaces))\n4718: +\tfor _, intf := range audit.Interfaces {\n4719: +\t\tinterfaces = append(interfaces, intf.Name)\n4720: +\t}\n4721: +\n4722: +\treturn fmt.Errorf(\"capture of %s on node %s %s by clabwire: %s\",\n4723: +\t\tstrings.Join(interfaces, \",\"), node, verb, audit.Reason)\n4724: +}\n4725: +\n4726: +// setCut places the cut in the middle of the overlap of the active and the next segment, both\n4727: +// measured on the pod clock.\n4728: +func (c *captureChain) setCut() {\n4729: +\toverlapStart := c.next.started\n4730: +\toverlapEnd := c.active.plannedEnd()\n4731: +\tif overlapEnd.Sub(overlapStart) < 2*c.capture.window {\n4732: +\t\t// the overlap is too short to match packets around a cut: the switch is reported as a\n4733: +\t\t// gap once the active segment ended\n4734: +\t\tc.cut = 0\n4735: +\t\treturn\n4736: +\t}\n4737: +\tc.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()\n4738: +\n4739: +\twindow := c.capture.window.Nanoseconds()\n4740: +\t// Packets the next segment holds back are stamped from T-W on: other chains' packets after\n4741: +\t// that wait in the reorder buffer until the switch, so the merged stream stays in order.\n4742: +\tc.capture.out.Hold(c, c.cut-window)\n4743: +\n4744: +\t// The active segment only matters for packets stamped before T. Once the pod clock passed\n4745: +\t// T+W, it is closed: packets it read until then are still delivered, and the ones it reads\n4746: +\t// later are stamped after T and dropped anyway. The next segment's Started record was\n4747: +\t// written on the pod clock no later than now, so the pod clock passes T+W no later than\n4748: +\t// (T - Started + W) from now.\n4749: +\tactive := c.active\n4750: +\tactive.stopTimer = time.AfterFunc(\n4751: +\t\ttime.Duration(c.cut-c.next.started.UnixNano()+window), active.closeStdin)\n4752: +}\n4753: +\n4754: +func (c *captureChain) handlePacket(\n4755: +\tsegment *captureSegment,\n4756: +\tpacket *clabcapture.Packet,\n4757: +) (bool, error) {\n4758: +\tswitch segment {\n4759: +\tcase c.active:\n4760: +\t\tif c.cut != 0 && packet.Timestamp >= c.cut {\n4761: +\t\t\treturn false, nil\n4762: +\t\t}\n4763: +\t\tif c.next != nil {\n4764: +\t\t\tc.emitted[packetKey(packet)]++\n4765: +\t\t}\n4766: +\n4767: +\t\treturn c.emit(packet)\n4768: +\tcase c.next:\n4769: +\t\tc.held = append(c.held, packet)\n4770: +\t}\n4771: +\n4772: +\treturn false, nil\n4773: +}\n4774: +\n4775: +func (c *captureChain) emit(packet *clabcapture.Packet) (bool, error) {\n4776: +\tif int(packet.InterfaceID) >= len(c.group.ids) {\n4777: +\t\treturn true, fmt.Errorf(\"clabwire wrote a packet for interface %d of %d\",\n4778: +\t\t\tpacket.InterfaceID, len(c.group.ids))\n4779: +\t}\n\n(Output capped at 50 KB. Showing lines 3478-4779. Use offset=4780 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+\t\tcase 6: // Enhanced Packet Block\n+\t\t\tid := binary.LittleEndian.Uint32(body[0:4])\n+\t\t\tframe := body[20 : 20+binary.LittleEndian.Uint32(body[12:16])]\n+\t\t\tif len(frame) > 23 && frame[12] == 0x08 && frame[13] == 0x00 && frame[23] == 1 {\n+\t\t\t\ticmp[id]++\n+\t\t\t}\n+\t\t}\n+\t\tdata = data[length:]\n+\t}\n+\n+\treturn names, icmp\n+}\ndiff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml\nnew file mode 100644\nindex 0000000..0422c22\n--- /dev/null\n+++ b/core/test_data/capture.clab.yml\n@@ -0,0 +1,15 @@\n+name: capture\n+topology:",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+\t\tcase 6: // Enhanced Packet Block\n+\t\t\tid := binary.LittleEndian.Uint32(body[0:4])\n+\t\t\tframe := body[20 : 20+binary.LittleEndian.Uint32(body[12:16])]\n+\t\t\tif len(frame) > 23 && frame[12] == 0x08 && frame[13] == 0x00 && frame[23] == 1 {\n+\t\t\t\ticmp[id]++\n+\t\t\t}\n+\t\t}\n+\t\tdata = data[length:]\n+\t}\n+\n+\treturn names, icmp\n+}\ndiff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml\nnew file mode 100644\nindex 0000000..0422c22\n--- /dev/null\n+++ b/core/test_data/capture.clab.yml\n@@ -0,0 +1,15 @@\n+name: capture\n+topology:\n+  nodes:\n+    srl1:\n+      kind: nokia_srlinux\n+    srl2:\n+      kind: nokia_srlinux\n+    client:\n+      kind: linux\n+      image: alpine:3\n+  links:\n+    - endpoints: [\"srl1:ethernet-1/1\", \"srl2:e1-1\"]\n+    - endpoints: [\"srl1:e1-2\", \"client:eth1\"]\n+    - endpoints: [\"client:eth2\", \"host:client-eth2\"]\n+    - endpoints: [\"client:eth3\", \"mgmt-net:client-eth3\"]\ndiff --git a/docs/cmd/capture.md b/docs/cmd/capture.md\nnew file mode 100644\nindex 0000000..15006ff\n--- /dev/null\n+++ b/docs/cmd/capture.md\n@@ -0,0 +1,134 @@\n+# capture command\n+\n+### Description\n+\n+The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.\n+\n+It works with every runtime:\n+\n+- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).\n+- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).\n+\n+The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.\n+\n+--8<-- \"docs/cmd/deploy.md:env-vars-flags\"\n+\n+### Usage\n+\n+`containerlab [global-flags] capture [local-flags]`\n+\n+### Flags\n+\n+#### topology | name\n+\n+Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.\n+\n+With Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.\n+\n+#### target\n+\n+The local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:\n+\n+```text\n+--target srl1:e1-1,e1-2 --target srl2:e1-1\n+```\n+\n+The node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.\n+\n+Only lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.\n+\n+#### duration\n+\n+The local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).\n+\n+#### packet-limit\n+\n+The local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.\n+\n+#### snap-length\n+\n+The local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.\n+\n+#### write\n+\n+The local `--write | -w` flag names the output file. The default `-` writes to stdout.\n+\n+#### list\n+\n+The local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.\n+\n+### Output\n+\n+The output is one pcapng section:\n+\n+- a Section Header Block with `shb_userappl` set to `containerlab`\n+- one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it\n+- Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes\n+\n+The interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.\n+\n+When the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.\n+\n+`--list -f json` prints an array:\n+\n+```json\n+[\n+  {\n+    \"node\": \"srl1\",\n+    \"interface\": \"e1-1\",\n+    \"alias\": \"ethernet-1/1\",\n+    \"peer_node\": \"srl2\",\n+    \"peer_interface\": \"ethernet-1/1\"\n+  }\n+]\n+```\n+\n+`alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.\n+\n+### How Docker and Podman captures work\n+\n+For each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.\n+\n+- Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.\n+- 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.\n+- Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.\n+- An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.\n+\n+The command needs root (to open packet sockets and enter network namespaces), as other lab commands do.\n+\n+### Long captures\n+\n+Docker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.\n+\n+### Examples\n+\n+#### Capture two nodes for 30 seconds into one file\n+\n+```bash\n+containerlab capture -t srl.clab.yml \\\n+  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n+```\n+\n+#### Watch a capture live in Wireshark\n+\n+```bash\n+containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n+```\n+\n+#### Capture the first 100 packets with tshark\n+\n+```bash\n+containerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -\n+```\n+\n+#### List the capturable interfaces\n+\n+```bash\n+containerlab capture --name srl --list\n+```\n+\n+#### Capture a c9s lab\n+\n+```bash\n+containerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng\n+```\ndiff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md\nindex 3dc8e27..2354dc1 100644\n--- a/docs/cmd/inspect/interfaces.md\n+++ b/docs/cmd/inspect/interfaces.md\n@@ -3,10 +3,12 @@\n ### Description\n \n The `inspect interfaces` subcommand provides information about the network interfaces of deployed nodes of a deployed lab.\n The subcommand gathers information directly from deployed containers, and displays information about their operational state, network interface type, and if applicable, the applied network interface alias.\n \n+With the [c9s runtime](../../manual/clabernetes/runtime.md#packet-capture), the listing covers the lab link interfaces of each running node, the ones [`capture`](../capture.md) accepts, with the alias the topology used, and the MAC address, index, MTU and operational state read in the node's device container. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields are the same as with Docker.\n+\n ### Usage\n \n `containerlab [global-flags] inspect interfaces [local-flags]`\n \n A shorthand can be used for this subcommand: `int` or `intf`.\ndiff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md\nindex 0ce708d..8174c98 100644\n--- a/docs/manual/clabernetes/runtime.md\n+++ b/docs/manual/clabernetes/runtime.md\n@@ -110,10 +110,13 @@ The c9s runtime currently supports the main lab lifecycle and node operations:\n | `start` | sets the node's `spec.runState` to `Running` |\n | `stop` | sets the node's `spec.runState` to `Stopped` |\n | `restart` | requests a Pod replacement with a `c9s.run/restart-requested` token |\n | `save` | runs the node's save lifecycle inside its device container |\n | `events` | watches Clabernetes resources and pods |\n+| `logs` | streams the device container log |\n+| `capture` | captures lab link interfaces through the `clabwire` sidecar into one pcapng stream |\n+| `inspect interfaces` | lists the capturable link interfaces with their sysfs state |\n | `validate` | checks c9s compatibility without creating Kubernetes resources |\n | `deploy --dry-run` | compiles and diffs Namespace, ConfigMap, NodeProfile, Link, and Node resources without changing them |\n | `deploy --emit-crs` | prints the Namespace, ConfigMap, and Topology (or NodeProfile, Link, and Node) manifests deploy would create, without contacting the cluster |\n \n ## Requirements\n@@ -141,11 +144,11 @@ Containerlab needs a clabernetes release that has:\n \n - Node run state: `nodes.c9s.run` `spec.runState` (`Running` | `Stopped`), the\n   `Stopped` condition, and restart requests through the\n   `c9s.run/restart-requested` annotation\n - the clabwire packet capture contract: `--nodeName`, repeated `--interface`,\n-  `--format pcapng` and `--list-interfaces`\n+  `--format pcapng`, `--list-interfaces` and `--stop-on-stdin-close`\n - the namespace-bindable `clabernetes-lab-viewer` and `clabernetes-lab-editor`\n   roles\n \n Both features ship in the same release, so containerlab checks one field: the\n published OpenAPI schema of `nodes.c9s.run` (`/openapi/v3/apis/c9s.run/v1alpha1`)\n@@ -159,10 +162,21 @@ an older release every other command fails like this:\n the clabernetes release on this cluster is not supported: nodes.c9s.run has no\n spec.runState (Node run state); the c9s runtime needs clabernetes with Node run\n state and the clabwire capture contract (0.11 or newer)\n ```\n \n+A cluster that passes this check but runs a `clabwire` without\n+`--stop-on-stdin-close` (a development build between the two features) fails\n+the first capture with the same kind of error, naming the pod:\n+\n+```text\n+the clabernetes release on this cluster is not supported: clabwire in pod\n+<namespace>/<pod> does not accept packet-capture --stop-on-stdin-close; the c9s\n+runtime needs clabernetes with Node run state and the clabwire capture contract\n+(0.11 or newer)\n+```\n+\n Library users can run the check up front with\n `(*core.CLab).CheckLabRuntimeSupport(ctx)` or the optional\n `labruntime.SupportChecker` interface; the error wraps\n `labruntime.ErrUnsupportedRuntimeVersion`.\n \n@@ -579,10 +593,82 @@ containerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timest\n \n It reads the `pods/log` subresource of the node's pod, so RBAC must allow\n `get` on `pods/log`. Kubernetes returns stdout and stderr as one stream. See\n the [`logs` command](../../cmd/logs.md) for the flags.\n \n+## Packet capture\n+\n+[`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of\n+one or more nodes into one pcapng stream. Each node's pod runs the `clabwire`\n+sidecar, which realized the node's links; containerlab execs its capture\n+command (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.\n+No capture service runs in the cluster, and nothing is captured outside the\n+lab's planned link interfaces.\n+\n+```bash\n+# both ends of a link, for 30 seconds\n+containerlab -r c9s capture -t clos.clab.yml \\\n+  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n+\n+# live in Wireshark until Wireshark or Ctrl+C ends it\n+containerlab -r c9s capture --name clos --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n+\n+# what can be captured, with the peer of each link\n+containerlab -r c9s capture --name clos --list\n+```\n+\n+How it works:\n+\n+- containerlab locates each target node's pod and runs one `clabwire` capture\n+  per node, with `--nodeName`, every requested interface of that node,\n+  `--format pcapng` and `--stop-on-stdin-close`, with stdin attached.\n+- The streams are merged into one section: one Interface Description Block per\n+  target named `<node>:<interface>` (the node as the topology spells it),\n+  written before the first packet, and the packets of every target with their\n+  interface IDs remapped.\n+- Packets are written in timestamp order. Each node's stream arrives over its\n+  own exec stream, so the merged stream holds every packet for 250 ms and\n+  writes the held packets ordered by timestamp. A packet that arrives later\n+  than that, stamped before a packet already written, is written as it comes;\n+  the number of such packets goes to the debug log.\n+- `clabwire` limits one capture to one hour. Longer captures, and captures\n+  without `--duration`, chain captures with a few seconds of overlap and switch\n+  in the middle of it; packets near the switch are matched by content so each\n+  is written once. A follow-up that does not start in time is reported as a\n+  gap, with its time span.\n+- `clabwire` audit records (JSON on its stderr, schema\n+  `c9s.direct-packet-capture-audit/v1alpha1`) with status `Denied` or `Failed`\n+  end the command with their reason. `Started` and `Succeeded` go to the debug\n+  log.\n+\n+Interface names are the names inside the node; targets may also use the alias\n+the topology used for an interface:\n+\n+| Kind | Interface | Alias |\n+| ---- | --------- | ----- |\n+| linux | `eth1` | |\n+| SR Linux | `e1-1` | `ethernet-1/1` |\n+| vr-sros / nokia_sros | `eth3` | `1/1/3` |\n+\n+The management interface and the pod's `c9s0` interface cannot be captured.\n+\n+Ctrl+C or SIGTERM ends a capture cleanly: the output stays a valid pcapng\n+file and the command exits with code 0. Kubernetes does not stop a command\n+when its exec stream closes, but it closes the command's stdin. containerlab\n+closes the stdin of every `clabwire` capture when the capture ends for any\n+reason (the duration or packet limit, Ctrl+C, an error, a failed write of the\n+output such as a closed Wireshark, or a newer segment taking over), and\n+`clabwire` then ends the capture within milliseconds. If the process does not\n+end within three seconds, containerlab cuts the exec stream. A killed\n+containerlab drops the connection, which closes stdin as well.\n+\n+Capturing needs `get` and `create` on `pods/exec` in the lab namespace, which\n+`clabernetes-lab-editor` grants. `inspect interfaces -r c9s` lists the same\n+interfaces, with the MAC address, index, MTU and operational state read from\n+sysfs in the device container (type `veth`, which is how `clabwire` realizes\n+lab links).\n+\n ## Start, stop, and restart\n \n Node lifecycle commands ask the clabernetes controllers for a run state; they\n never touch Deployments or Pods.\n \n@@ -863,16 +949,22 @@ implemented by the c9s runtime:\n | `NodeLocator` | `LocateNode(ctx, NodeRequest) ([]NodeLocation, error)` | the namespace, pod, primary device container, Node UID, exposed ports and LoadBalancer address of nodes |\n | `NodeAttacher` | `Attach(ctx, AttachRequest, AttachStreams) error` | an interactive exec with stdin, an optional TTY and a resize channel, in the device container or a chosen container |\n | `NodeLogStreamer` | `StreamLogs(ctx, LogRequest, io.Writer) error` | the device container log, with tail, follow and timestamps |\n | `NodePortForwarder` | `DialPort(ctx, NodeRequest, port) (net.Conn, error)` | a connection to a TCP port of the node's pod through `pods/portforward` (SSH, web UIs) |\n | `NodeStatsSampler` | `SampleStats(ctx, InspectRequest) ([]NodeStats, error)` | CPU and memory per node from `metrics.k8s.io` PodMetrics, summing the node's device containers; without the metrics API the error wraps `labruntime.ErrMetricsUnavailable` |\n+| `PacketCapturer` | `CaptureInterfaces(ctx, NodeRequest) ([]CaptureInterface, error)` | the capturable link interfaces of nodes, with alias, peer node and peer interface |\n+| `PacketCapturer` | `Capture(ctx, CaptureRequest, io.Writer) error` | one pcapng stream of the request's targets, for `Duration` (0: until ctx ends), `PacketLimit` and `SnapLength`; gaps go to `OnGap` |\n+| `InterfaceInspector` | `InspectInterfaces(ctx, NodeRequest) ([]*types.ContainerInterfaces, error)` | the `inspect interfaces` view of the link interfaces |\n+| `SupportChecker` | `CheckSupport(ctx, Identity) error` | the clabernetes release check |\n \n The `core` package wraps them per lab and node name, accepting the node name\n as the topology file spells it or as it was sanitized:\n `CLab.LocateLabRuntimeNodes`, `CLab.AttachLabRuntimeNode`,\n-`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats` and\n-`CLab.NodeLogs`, which also serves Docker and Podman.\n+`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats`,\n+`CLab.CaptureInterfaces`, `CLab.Capture`, `CLab.LabRuntimeInterfaces`,\n+`CLab.CheckLabRuntimeSupport` and `CLab.NodeLogs`, which also serves Docker and\n+Podman.\n \n ```go\n c, err := clabcore.NewContainerLab(\n \tclabcore.WithRuntime(\"c9s\", nil),\n \tclabcore.WithTopologyName(\"clos\"),\n@@ -884,10 +976,18 @@ c, err := clabcore.NewContainerLab(\n if err != nil {\n \treturn err\n }\n \n conn, err := c.DialLabRuntimeNodePort(ctx, \"srl1\", 22)\n+\n+// stream pcapng to a websocket, a file or Wireshark until ctx ends\n+err = c.Capture(ctx, clablabruntime.CaptureRequest{\n+\tTargets: []clablabruntime.CaptureTarget{\n+\t\t{Node: \"srl1\", Interface: \"ethernet-1/1\"},\n+\t\t{Node: \"srl2\", Interface: \"e1-1\"},\n+\t},\n+}, w)\n ```\n \n ### Acting as a user\n \n A server that runs labs for many users acts as each user, so the cluster's RBAC\n@@ -936,11 +1036,12 @@ to:\n - create, get, list, watch, and delete c9s `Link` and `NodeProfile` resources\n - get, list, watch, and delete `Topology` resources when Topology-based labs\n   must remain manageable\n - list and watch Pods\n - create, get, list, update, and delete ConfigMaps used for local files\n-- exec into device Pods with `pods/exec`\n+- exec into device Pods with `pods/exec`, also for `capture` and `inspect\n+  interfaces` (in the `clabwire` and device containers)\n - list and delete PersistentVolumeClaims for `destroy --cleanup`\n - read container logs with `pods/log` for `logs`\n - port-forward with `pods/portforward` for `NodePortForwarder`\n - list `pods.metrics.k8s.io` for `NodeStatsSampler`\n \n@@ -1152,12 +1253,14 @@ Known command differences:\n   `--export-template`, `--restore`, and `--restore-all` are rejected.\n - Destroy flags `--graceful` and `--keep-mgmt-net` are rejected. `--cleanup`\n   also deletes the lab's persistent claims (saved device state) and removes\n   the local lab directory; a plain destroy keeps the claims.\n - Local Docker commands on the outer host are not authoritative for c9s labs.\n-- `inspect interfaces` is rejected. Host-side `tc` or netem operations do not\n-  have the same local namespace access they have with Docker labs.\n+- `inspect interfaces` lists only the lab link interfaces (those `capture`\n+  accepts), not the management or pod interfaces. Host-side `tc` or netem\n+  operations do not have the same local namespace access they have with Docker\n+  labs.\n - `graph` renders from the topology file only: `--mermaid`, `--dot`, `--drawio`\n   and `--offline` work, the default mode that reads running containers is\n   rejected, and so is `--node-filter`. `--drawio` runs the clab-io-draw\n   container, so it needs Docker or Podman on the outer host.\n - `tools` commands operate on local containers and host networking and are\ndiff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md\nindex b194b29..4654128 100644\n--- a/docs/manual/wireshark.md\n+++ b/docs/manual/wireshark.md\n@@ -15,10 +15,16 @@ Every lab emulation software must provide its users with the packet capturing ab\n \n Containerlab offers a simple way to capture the packets from any interface of any node in the lab. This article will explain how to do that.\n \n ///tip\n \n+The [`containerlab capture`](../cmd/capture.md) command captures one or more lab link interfaces, of one or more nodes, into one pcapng file or stream, with nothing to install in the nodes or on the host:\n+\n+```bash\n+containerlab capture --name quickstart --target srl:e1-1 -w - | wireshark -k -i -\n+```\n+\n If you are looking for a free Web UI for packet capture with Wireshark, check out our [Edgeshark integration](#edgeshark-integration).\n ///\n \n Consider the following lab topology which highlights the typical points of packet capture.\n \ndiff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go\nnew file mode 100644\nindex 0000000..69d4072\n--- /dev/null\n+++ b/labruntime/clabernetes/capture.go\n@@ -0,0 +1,1202 @@\n+package clabernetes\n+\n+import (\n+\t\"bytes\"\n+\t\"context\"\n+\t\"encoding/json\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"hash/fnv\"\n+\t\"io\"\n+\t\"os\"\n+\t\"sort\"\n+\t\"strconv\"\n+\t\"strings\"\n+\t\"sync\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\t\"golang.org/x/sync/errgroup\"\n+)\n+\n+// The clabwire packet capture contract (clabernetes 0.11 or newer).\n+const (\n+\tclabwireContainer = \"clabwire\"\n+\tclabwireManager   = \"/clabernetes/manager\"\n+\t// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.\n+\tcaptureAuditSchema = \"c9s.direct-packet-capture-audit/v1alpha1\"\n+\n+\tcaptureAuditStarted   = \"Started\"\n+\tcaptureAuditSucceeded = \"Succeeded\"\n+\tcaptureAuditFailed    = \"Failed\"\n+\tcaptureAuditDenied    = \"Denied\"\n+\n+\t// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.\n+\tmaxCaptureSegment = time.Hour\n+\t// maxClabwirePackets is the packet limit of a single clabwire capture.\n+\tmaxClabwirePackets = 1_000_000\n+\t// maxCaptureOverlap is how long two chained segments run side by side.\n+\tmaxCaptureOverlap = 10 * time.Second\n+\t// maxCaptureCutWindow is the half-width of the window around the cut in which packets of\n+\t// two segments are matched by content; it covers the difference between the timestamps\n+\t// two clabwire processes give the same packet.\n+\tmaxCaptureCutWindow = 500 * time.Millisecond\n+\t// minCaptureSegment is the shortest segment the chain requests.\n+\tminCaptureSegment = 100 * time.Millisecond\n+\t// captureEndGrace is how long a capture with a duration waits for its last clabwire\n+\t// process to end after the duration passed.\n+\tcaptureEndGrace = 30 * time.Second\n+\t// captureStartRetries bounds the attempts to start a follow-up segment.\n+\tcaptureStartRetries = 3\n+\t// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was\n+\t// closed before the stream is cut.\n+\tcaptureStdinCloseGrace = 3 * time.Second\n+\t// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A\n+\t// Kubernetes exec does not stop its process when the stream ends, but it closes the\n+\t// process's stdin, so every capture runs with stdin attached and this flag.\n+\tclabwireStopOnStdinClose = \"--stop-on-stdin-close\"\n+\n+\t// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests\n+\t// without hour-long captures.\n+\tenvCaptureSegment = \"CLAB_C9S_CAPTURE_SEGMENT\"\n+\t// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets\n+\t// of other nodes stamped earlier but delivered later still go out before it.\n+\tdefaultCaptureReorderWindow = 250 * time.Millisecond\n+\t// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.\n+\t// It is an internal knob, not a supported setting.\n+\tenvCaptureReorderWindow = \"CLAB_C9S_CAPTURE_REORDER_WINDOW\"\n+)\n+\n+// podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns\n+// a *labruntime.CommandExitError.\n+type podExecFunc func(\n+\tctx context.Context,\n+\tnamespace, pod, container string,\n+\tcommand []string,\n+\tstdin io.Reader,\n+\tstdout, stderr io.Writer,\n+) error\n+\n+// clabwireInterface is one entry of `packet-capture --list-interfaces`.\n+type clabwireInterface struct {\n+\tNode          string `json:\"node\"`\n+\tInterface     string `json:\"interface\"`\n+\tAlias         string `json:\"alias,omitempty\"`\n+\tPeerNode      string `json:\"peerNode\"`\n+\tPeerInterface string `json:\"peerInterface\"`\n+}\n+\n+// captureAudit is one clabwire audit line.\n+type captureAudit struct {\n+\tSchemaVersion string    `json:\"schemaVersion\"`\n+\tTime          time.Time `json:\"time\"`\n+\tStatus        string    `json:\"status\"`\n+\tNodeName      string    `json:\"nodeName\"`\n+\tFormat        string    `json:\"format\"`\n+\tReason        string    `json:\"reason\"`\n+\tPackets       int       `json:\"packets\"`\n+\tInterfaces    []struct {\n+\t\tName    string `json:\"name\"`\n+\t\tID      string `json:\"id\"`\n+\t\tPackets int    `json:\"packets\"`\n+\t} `json:\"interfaces\"`\n+}\n+\n+func (r *Runtime) execInPodContainer() podExecFunc {\n+\tif r.podExec != nil {\n+\t\treturn r.podExec\n+\t}\n+\n+\treturn r.streamPodExec\n+}\n+\n+// captureSegmentLength is the length of one clabwire capture before the next takes over.\n+func (r *Runtime) captureSegmentLength() time.Duration {\n+\tif r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {\n+\t\treturn r.captureSegment\n+\t}\n+\n+\treturn maxCaptureSegment\n+}\n+\n+// captureReorderWindowLength is the reorder window of the merged stream; zero disables\n+// reordering.\n+func (r *Runtime) captureReorderWindowLength() time.Duration {\n+\tswitch {\n+\tcase r.captureReorderWindow < 0:\n+\t\treturn 0\n+\tcase r.captureReorderWindow > 0:\n+\t\treturn r.captureReorderWindow\n+\t}\n+\n+\treturn defaultCaptureReorderWindow\n+}\n+\n+// captureReorderWindowFromEnv reads the reorder window knob: unset or invalid keeps the\n+// default (0), \"0\" disables reordering (-1).\n+func captureReorderWindowFromEnv() time.Duration {\n+\tvalue, err := time.ParseDuration(os.Getenv(envCaptureReorderWindow))\n+\tswitch {\n+\tcase err != nil || value < 0:\n+\t\treturn 0\n+\tcase value == 0:\n+\t\treturn -1\n+\t}\n+\n+\treturn value\n+}\n+\n+func captureSegmentFromEnv() time.Duration {\n+\tvalue, err := time.ParseDuration(os.Getenv(envCaptureSegment))\n+\tif err != nil || value <= 0 {\n+\t\treturn 0\n+\t}\n+\n+\treturn value\n+}\n+\n+// CaptureInterfaces lists the capturable lab link interfaces of the requested nodes, or of every\n+// node, as clabwire reports them, with their peers. Node names are reported as the topology\n+// spells them.\n+func (r *Runtime) CaptureInterfaces(\n+\tctx context.Context,\n+\treq clablabruntime.NodeRequest,\n+) ([]clablabruntime.CaptureInterface, error) {\n+\tr, err := r.connect(ctx, req.Identity)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n+\t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n+\t})\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tif len(req.Nodes) == 0 {\n+\t\t// a lab-wide listing skips nodes that do not run\n+\t\trunning := locations[:0]\n+\t\tfor _, location := range locations {\n+\t\t\tif location.Pod != \"\" {\n+\t\t\t\trunning = append(running, location)\n+\t\t\t}\n+\t\t}\n+\t\tlocations = running\n+\t}\n+\n+\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\tresult := make([]clablabruntime.CaptureInterface, 0)\n+\tfor _, location := range locations {\n+\t\tfor _, entry := range listed[location.NodeName] {\n+\t\t\tresult = append(result, clablabruntime.CaptureInterface{\n+\t\t\t\tNode:          names.display(entry.Node),\n+\t\t\t\tInterface:     entry.Interface,\n+\t\t\t\tAlias:         entry.Alias,\n+\t\t\t\tPeerNode:      names.display(entry.PeerNode),\n+\t\t\t\tPeerInterface: entry.PeerInterface,\n+\t\t\t})\n+\t\t}\n+\t}\n+\tsort.SliceStable(result, func(i, j int) bool {\n+\t\tif result[i].Node != result[j].Node {\n+\t\t\treturn result[i].Node < result[j].Node\n+\t\t}\n+\n+\t\treturn result[i].Interface < result[j].Interface\n+\t})\n+\n+\treturn result, nil\n+}\n+\n+// listCaptureInterfaces runs one --list-interfaces per pod and returns the entries per Node.\n+func (r *Runtime) listCaptureInterfaces(\n+\tctx context.Context,\n+\tlab string,\n+\tlocations []clablabruntime.NodeLocation,\n+) (map[string][]clabwireInterface, error) {\n+\tpods := map[string]clablabruntime.NodeLocation{}\n+\twanted := map[string]bool{}\n+\tfor _, location := range locations {\n+\t\tif location.Pod == \"\" {\n+\t\t\treturn nil, fmt.Errorf(\"c9s node %s/%s/%s has no pod; is it running?\",\n+\t\t\t\tlocation.Namespace, lab, location.NodeName)\n+\t\t}\n+\t\tpods[location.Namespace+\"/\"+location.Pod] = location\n+\t\twanted[location.NodeName] = true\n+\t}\n+\n+\tvar mu sync.Mutex\n+\tresult := map[string][]clabwireInterface{}\n+\tgroup, groupCtx := errgroup.WithContext(ctx)\n+\tgroup.SetLimit(interfaceSampleWorkers)\n+\texec := r.execInPodContainer()\n+\tfor _, location := range pods {\n+\t\tgroup.Go(func() error {\n+\t\t\tvar stdout, stderr bytes.Buffer\n+\t\t\terr := exec(groupCtx, location.Namespace, location.Pod, clabwireContainer,\n+\t\t\t\t[]string{clabwireManager, \"node-runtime\", \"packet-capture\", \"--list-interfaces\"},\n+\t\t\t\tnil, &stdout, &stderr)\n+\t\t\tif err != nil {\n+\t\t\t\treturn fmt.Errorf(\"failed to list the capturable interfaces of pod %s/%s: %w%s\",\n+\t\t\t\t\tlocation.Namespace, location.Pod, err, stderrSuffix(stderr.Bytes()))\n+\t\t\t}\n+\n+\t\t\tvar entries []clabwireInterface\n+\t\t\tif err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {\n+\t\t\t\treturn fmt.Errorf(\"failed to parse the capturable interfaces of pod %s/%s: %w\",\n+\t\t\t\t\tlocation.Namespace, location.Pod, err)\n+\t\t\t}\n+\n+\t\t\tmu.Lock()\n+\t\t\tdefer mu.Unlock()\n+\t\t\tfor _, entry := range entries {\n+\t\t\t\tif wanted[entry.Node] {\n+\t\t\t\t\tresult[entry.Node] = append(result[entry.Node], entry)\n+\t\t\t\t}\n+\t\t\t}\n+\n+\t\t\treturn nil\n+\t\t})\n+\t}\n+\tif err := group.Wait(); err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treturn result, nil\n+}\n+\n+func stderrSuffix(stderr []byte) string {\n+\ttext := strings.TrimSpace(string(stderr))\n+\tif text == \"\" {\n+\t\treturn \"\"\n+\t}\n+\n+\treturn \": \" + text\n+}\n+\n+// nodeNames maps the node names the cluster carries to the names the topology file uses.\n+type nodeNames map[string]string\n+\n+func (n nodeNames) display(name string) string {\n+\tif original := n[name]; original != \"\" {\n+\t\treturn original\n+\t}\n+\n+\treturn name\n+}\n+\n+// nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the\n+// lab's Nodes.\n+func (r *Runtime) nodeDisplayNames(\n+\tctx context.Context,\n+\tlab string,\n+\tlocations []clablabruntime.NodeLocation,\n+) (nodeNames, error) {\n+\tnames := nodeNames{}\n+\tif len(locations) == 0 {\n+\t\treturn names, nil\n+\t}\n+\n+\tnodes, err := r.nodesForTopology(ctx, lab, locations[0].Namespace)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tfor idx := range nodes.Items {\n+\t\tif original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != \"\" {\n+\t\t\tnames[nodes.Items[idx].GetName()] = original\n+\t\t}\n+\t}\n+\n+\treturn names, nil\n+}\n+\n+// captureGroup is the part of a capture one clabwire process serves: the requested interfaces of\n+// one node, in one pod.\n+type captureGroup struct {\n+\tlocation clablabruntime.NodeLocation\n+\tdisplay  string\n+\t// interfaces are the planned interface names, in the order the merged stream lists them.\n+\tinterfaces []string\n+\t// ids are the merged interface IDs of interfaces.\n+\tids []uint32\n+}\n+\n+// resolvedCapture is a validated capture request.\n+type resolvedCapture struct {\n+\tgroups []*captureGroup\n+\t// names are the merged interface names (<node>:<interface>), indexed by merged ID.\n+\tnames []string\n+}\n+\n+// resolveCaptureTargets locates every target node, checks every interface against the\n+// interfaces clabwire allows, and groups the targets per node.\n+func (r *Runtime) resolveCaptureTargets(\n+\tctx context.Context,\n+\treq clablabruntime.CaptureRequest,\n+) (*resolvedCapture, error) {\n+\tnodeOrder := make([]string, 0, len(req.Targets))\n+\tseenNodes := map[string]bool{}\n+\tfor _, target := range req.Targets {\n+\t\tif !seenNodes[target.Node] {\n+\t\t\tseenNodes[target.Node] = true\n+\t\t\tnodeOrder = append(nodeOrder, target.Node)\n+\t\t}\n+\t}\n+\n+\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n+\t\tName: req.Name, Namespace: req.Namespace, Nodes: nodeOrder, Identity: req.Identity,\n+\t})\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tbyRequest := make(map[string]clablabruntime.NodeLocation, len(nodeOrder))\n+\tfor idx, name := range nodeOrder {\n+\t\tbyRequest[name] = locations[idx]\n+\t}\n+\n+\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\tresolved := &resolvedCapture{}\n+\tgroups := map[string]*captureGroup{}\n+\tseen := map[string]bool{}\n+\tfor _, target := range req.Targets {\n+\t\tlocation := byRequest[target.Node]\n+\t\tentry, ok := findCaptureInterface(listed[location.NodeName], target.Interface)\n+\t\tif !ok {\n+\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n+\t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n+\t\t\t\tdescribeCaptureInterfaces(listed[location.NodeName]))\n+\t\t}\n+\n+\t\tkey := location.NodeName + \"\\x00\" + entry.Interface\n+\t\tif seen[key] {\n+\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n+\t\t\t\tentry.Interface, target.Node)\n+\t\t}\n+\t\tseen[key] = true\n+\n+\t\tgroup := groups[location.NodeName]\n+\t\tif group == nil {\n+\t\t\tgroup = &captureGroup{\n+\t\t\t\tlocation: location,\n+\t\t\t\tdisplay:  names.display(location.NodeName),\n+\t\t\t}\n+\t\t\tgroups[location.NodeName] = group\n+\t\t\tresolved.groups = append(resolved.groups, group)\n+\t\t}\n+\n+\t\tid := uint32(len(resolved.names)) //nolint:gosec // bounded by the targets\n+\t\tgroup.interfaces = append(group.interfaces, entry.Interface)\n+\t\tgroup.ids = append(group.ids, id)\n+\t\tresolved.names = append(resolved.names, group.display+\":\"+entry.Interface)\n+\t}\n+\n+\treturn resolved, nil\n+}\n+\n+// findCaptureInterface matches a requested interface by its planned name or its alias.\n+func findCaptureInterface(entries []clabwireInterface, name string) (clabwireInterface, bool) {\n+\tfor _, entry := range entries {\n+\t\tif entry.Interface == name {\n+\t\t\treturn entry, true\n+\t\t}\n+\t}\n+\tfor _, entry := range entries {\n+\t\tif entry.Alias != \"\" && entry.Alias == name {\n+\t\t\treturn entry, true\n+\t\t}\n+\t}\n+\n+\treturn clabwireInterface{}, false\n+}\n+\n+func describeCaptureInterfaces(entries []clabwireInterface) string {\n+\tif len(entries) == 0 {\n+\t\treturn \"none\"\n+\t}\n+\n+\tnames := make([]string, 0, len(entries))\n+\tfor _, entry := range entries {\n+\t\tname := entry.Interface\n+\t\tif entry.Alias != \"\" {\n+\t\t\tname += \" (\" + entry.Alias + \")\"\n+\t\t}\n+\t\tnames = append(names, name)\n+\t}\n+\n+\treturn strings.Join(names, \", \")\n+}\n+\n+// Capture streams pcapng from lab link interfaces to w: one section, one Interface Description\n+// Block per target in request order named <node>:<interface>, then the packets of every target.\n+//\n+// Each node's interfaces are captured by one clabwire process in the node's pod. clabwire limits\n+// a capture to one hour, so a longer capture (or one without Duration) chains captures: the next\n+// one starts before the current one ends, and the stream switches at a cut in the overlap. See\n+// captureChain for how packets of the overlap are kept once.\n+//\n+// Packets go out in timestamp order across nodes, through a reorder buffer (captureReorder).\n+//\n+// Every clabwire process runs with stdin attached and --stop-on-stdin-close: a Kubernetes exec\n+// does not stop its process when the stream closes, so containerlab closes stdin whenever a\n+// segment ends (the capture ends, fails, its output fails, or a newer segment took over) and\n+// clabwire ends the capture itself.\n+//\n+// Capture returns when Duration has passed, PacketLimit packets were written, or ctx ends; an\n+// ended ctx is not an error. Every block reaches w in one write, so the stream is a valid capture\n+// whenever it stops. A clabwire Denied or Failed audit record is returned as an error.\n+func (r *Runtime) Capture(\n+\tctx context.Context,\n+\treq clablabruntime.CaptureRequest,\n+\tw io.Writer,\n+) error {\n+\tif err := clabcapture.ValidateRequest(&req); err != nil {\n+\t\treturn err\n+\t}\n+\n+\tr, err := r.connect(ctx, req.Identity)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tresolved, err := r.resolveCaptureTargets(ctx, req)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tcaptureCtx, stop := context.WithCancel(ctx)\n+\tdefer stop()\n+\n+\tout, err := clabcapture.NewOutput(w, resolved.names, req.SnapLength, req.PacketLimit,\n+\t\tr.captureReorderWindowLength(), stop)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\trun := &captureRun{\n+\t\tr:       r,\n+\t\treq:     req,\n+\t\tout:     out,\n+\t\tsegment: r.captureSegmentLength(),\n+\t}\n+\tif req.Duration > 0 {\n+\t\trun.deadline = time.Now().Add(req.Duration)\n+\t}\n+\trun.overlap = min(maxCaptureOverlap, run.segment/3)\n+\trun.window = min(maxCaptureCutWindow, run.overlap/4)\n+\n+\tif req.Duration > 0 {\n+\t\t// a clabwire process that does not end on its own does not hold the capture open\n+\t\tvar cancelTimeout context.CancelFunc\n+\t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx,\n+\t\t\treq.Duration+run.overlap+captureEndGrace)\n+\t\tdefer cancelTimeout()\n+\t}\n+\n+\tgroup, groupCtx := errgroup.WithContext(captureCtx)\n+\tfor _, captureGroup := range resolved.groups {\n+\t\tchain := &captureChain{capture: run, group: captureGroup}\n+\t\tgroup.Go(func() error {\n+\t\t\treturn chain.run(groupCtx)\n+\t\t})\n+\t}\n+\n+\terr = group.Wait()\n+\tif writeErr := out.Close(); writeErr != nil {\n+\t\treturn writeErr\n+\t}\n+\tif err != nil && !(errors.Is(err, context.Canceled) && captureCtx.Err() != nil) {\n+\t\treturn err\n+\t}\n+\n+\treturn nil\n+}\n+\n+// captureRun is the state a capture's chains share.\n+type captureRun struct {\n+\tr   *Runtime\n+\treq clablabruntime.CaptureRequest\n+\t// out is the merged stream; it writes the packets of every chain in timestamp order and\n+\t// stops every chain once the packet limit is reached.\n+\tout *clabcapture.Output\n+\n+\tsegment  time.Duration\n+\toverlap  time.Duration\n+\twindow   time.Duration\n+\tdeadline time.Time\n+}\n+\n+// emit writes a packet under its merged interface ID. It reports false once the packet limit is\n+// reached and the capture stops.\n+func (run *captureRun) emit(id uint32, packet *clabcapture.Packet) (bool, error) {\n+\treturn run.out.Emit(id, packet)\n+}\n+\n+func (run *captureRun) reportGap(gap clablabruntime.CaptureGap) {\n+\tclabcapture.ReportGap(run.req.OnGap, gap)\n+}\n+\n+// captureSegment is one clabwire capture process of a chain.\n+type captureSegment struct {\n+\tindex      int\n+\tlocalStart time.Time\n+\tduration   time.Duration\n+\tcancel     context.CancelFunc\n+\t// closeStdin closes the stdin of the segment's clabwire process, which ends it; it may be\n+\t// called any number of times.\n+\tcloseStdin func()\n+\t// stopTimer closes stdin once the segment is no longer needed after a switch-over.\n+\tstopTimer *time.Timer\n+\t// started and ended are the pod-clock times of the Started and Succeeded audit records.\n+\tstarted time.Time\n+\tended   time.Time\n+\tdone    bool\n+}\n+\n+func (s *captureSegment) plannedEnd() time.Time {\n+\treturn s.started.Add(s.duration)\n+}\n+\n+// segmentEvent is something a segment reported: a packet, an audit record, or its end.\n+type segmentEvent struct {\n+\tsegment *captureSegment\n+\tpacket  *clabcapture.Packet\n+\taudit   *captureAudit\n+\tdone    bool\n+\terr     error\n+}\n+\n+// captureChain runs the chained clabwire captures of one group.\n+//\n+// Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both\n+// capture the same packets for a while. clabwire stamps packets when it reads them, so two\n+// processes give the same packet timestamps a few microseconds apart, and timestamps alone\n+// cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by\n+// content close to the cut:\n+//\n+//  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is\n+//     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.\n+//  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the\n+//     content of what it wrote since segment k+1 started.\n+//  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped\n+//     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped\n+//     when segment k wrote the same bytes on the same interface, and every other one is written.\n+//     From then on segment k+1 streams live.\n+//\n+// Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its\n+// planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other\n+// nodes' later packets do not overtake them in the merged stream.\n+//\n+// W (500 ms, less for short test segments) covers the stamping difference. Identical frames on\n+// the same interface within W of the cut can be paired with each other, which can drop a true\n+// repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves\n+// a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.\n+type captureChain struct {\n+\tcapture *captureRun\n+\tgroup   *captureGroup\n+\n+\tevents chan segmentEvent\n+\twg     sync.WaitGroup\n+\n+\tactive *captureSegment\n+\tnext   *captureSegment\n+\t// cut is the switch time between active and next, in nanoseconds; zero until known.\n+\tcut int64\n+\t// emitted remembers the content of the packets active wrote while next runs.\n+\temitted map[uint64]int\n+\t// held are the packets of next until active ends.\n+\theld     []*clabcapture.Packet\n+\tsegments int\n+\tretries  int\n+\t// final is set once no further segment is due.\n+\tfinal bool\n+\t// stopping is set once ctx ended: the segments are asked to end and what they still\n+\t// deliver is written.\n+\tstopping bool\n+}\n+\n+// run runs the chain until its last segment ended. When ctx ends, it stops the segments and\n+// keeps writing the packets they read until then; a segment that does not end within\n+// captureStdinCloseGrace is cut.\n+func (c *captureChain) run(ctx context.Context) error {\n+\tc.events = make(chan segmentEvent, 256)\n+\t// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them\n+\tsegmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))\n+\tvar abort *time.Timer\n+\tdefer func() {\n+\t\tif abort != nil {\n+\t\t\tabort.Stop()\n+\t\t}\n+\t\tcancel()\n+\t\tc.drain()\n+\t\tc.capture.out.Release(c)\n+\t}()\n+\n+\tc.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))\n+\ttimer := time.NewTimer(c.nextStartIn())\n+\tdefer timer.Stop()\n+\n+\tdone := ctx.Done()\n+\tfor {\n+\t\tselect {\n+\t\tcase <-done:\n+\t\t\tdone = nil\n+\t\t\tc.stop(timer)\n+\t\t\tabort = time.AfterFunc(captureStdinCloseGrace, cancel)\n+\t\tcase <-segmentsCtx.Done():\n+\t\t\treturn nil\n+\t\tcase <-timer.C:\n+\t\t\tif c.next == nil && !c.final {\n+\t\t\t\tc.startNext(segmentsCtx)\n+\t\t\t}\n+\t\tcase event := <-c.events:\n+\t\t\tstop, err := c.handle(segmentsCtx, event, timer)\n+\t\t\tif err != nil || stop {\n+\t\t\t\treturn err\n+\t\t\t}\n+\t\t}\n+\t}\n+}\n+\n+// stop ends the chain early, like a deadline would: no further segment starts and the running\n+// ones are asked to end. The chain then writes what they deliver until they ended.\n+func (c *captureChain) stop(timer *time.Timer) {\n+\tc.stopping = true\n+\tc.final = true\n+\ttimer.Stop()\n+\tc.active.closeStdin()\n+\tif c.next != nil {\n+\t\tc.next.closeStdin()\n+\t}\n+}\n+\n+// drain waits for the segment goroutines after the chain ended.\n+func (c *captureChain) drain() {\n+\tdone := make(chan struct{})\n+\tgo func() {\n+\t\tc.wg.Wait()\n+\t\tclose(done)\n+\t}()\n+\tfor {\n+\t\tselect {\n+\t\tcase <-done:\n+\t\t\treturn\n+\t\tcase <-c.events:\n+\t\t}\n+\t}\n+}\n+\n+// segmentDuration is the requested duration of a segment starting now.\n+func (c *captureChain) segmentDuration(now time.Time) time.Duration {\n+\tduration := c.capture.segment\n+\tif !c.capture.deadline.IsZero() {\n+\t\tduration = min(duration, c.capture.deadline.Sub(now))\n+\t}\n+\n+\treturn max(duration, minCaptureSegment)\n+}\n+\n+// nextStartIn is the time until the follow-up of the active segment is due. It marks the chain\n+// final when none is due.\n+func (c *captureChain) nextStartIn() time.Duration {\n+\tif c.stopping {\n+\t\tc.final = true\n+\t\treturn maxCaptureSegment\n+\t}\n+\tactiveEnd := c.active.localStart.Add(c.active.duration)\n+\tif !c.capture.deadline.IsZero() &&\n+\t\t!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {\n+\t\tc.final = true\n+\t\treturn maxCaptureSegment\n+\t}\n+\tc.final = false\n+\n+\treturn max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)\n+}\n+\n+func (c *captureChain) startNext(ctx context.Context) {\n+\tc.next = c.start(ctx, c.segmentDuration(time.Now()))\n+\tc.emitted = map[uint64]int{}\n+\tc.held = nil\n+\tc.cut = 0\n+}\n+\n+func (c *captureChain) handle(\n+\tctx context.Context,\n+\tevent segmentEvent,\n+\ttimer *time.Timer,\n+) (bool, error) {\n+\tsegment := event.segment\n+\n+\tswitch {\n+\tcase event.audit != nil:\n+\t\treturn false, c.handleAudit(segment, event.audit)\n+\tcase event.packet != nil:\n+\t\treturn c.handlePacket(segment, event.packet)\n+\tcase event.done:\n+\t\tsegment.done = true\n+\t\tif segment.stopTimer != nil {\n+\t\t\tsegment.stopTimer.Stop()\n+\t\t}\n+\t\tif event.err != nil && !c.stopping {\n+\t\t\tif segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {\n+\t\t\t\t// the follow-up did not start; try again while the active one still runs\n+\t\t\t\tc.retries++\n+\t\t\t\tlog.Warn(\"Capture follow-up segment failed to start, retrying\",\n+\t\t\t\t\t\"node\", c.group.display, \"error\", event.err)\n+\t\t\t\tc.next = nil\n+\t\t\t\tresetTimer(timer, time.Second)\n+\n+\t\t\t\treturn false, nil\n+\t\t\t}\n+\n+\t\t\treturn true, fmt.Errorf(\"capture on c9s node %s/%s/%s failed: %w\",\n+\t\t\t\tc.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)\n+\t\t}\n+\t\tif segment != c.active {\n+\t\t\treturn false, nil\n+\t\t}\n+\n+\t\treturn c.switchSegments(ctx, timer)\n+\t}\n+\n+\treturn false, nil\n+}\n+\n+func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {\n+\tswitch audit.Status {\n+\tcase captureAuditStarted:\n+\t\tsegment.started = audit.Time\n+\t\tlog.Debug(\"Capture segment started\", \"node\", c.group.display, \"segment\", segment.index,\n+\t\t\t\"interfaces\", strings.Join(c.group.interfaces, \",\"), \"duration\", segment.duration)\n+\t\tif segment == c.next && !c.active.started.IsZero() {\n+\t\t\tc.setCut()\n+\t\t}\n+\t\tif segment == c.next {\n+\t\t\tc.retries = 0\n+\t\t}\n+\tcase captureAuditSucceeded:\n+\t\tsegment.ended = audit.Time\n+\t\tlog.Debug(\"Capture segment succeeded\", \"node\", c.group.display,\n+\t\t\t\"segment\", segment.index, \"packets\", audit.Packets)\n+\tcase captureAuditDenied, captureAuditFailed:\n+\t\treturn captureAuditError(c.group.display, audit)\n+\t}\n+\n+\treturn nil\n+}\n+\n+// captureAuditError turns a Denied or Failed clabwire audit record into an error.\n+func captureAuditError(node string, audit *captureAudit) error {\n+\tverb := \"failed\"\n+\tif audit.Status == captureAuditDenied {\n+\t\tverb = \"was denied\"\n+\t}\n+\tinterfaces := make([]string, 0, len(audit.Interfaces))\n+\tfor _, intf := range audit.Interfaces {\n+\t\tinterfaces = append(interfaces, intf.Name)\n+\t}\n+\n+\treturn fmt.Errorf(\"capture of %s on node %s %s by clabwire: %s\",\n+\t\tstrings.Join(interfaces, \",\"), node, verb, audit.Reason)\n+}\n+\n+// setCut places the cut in the middle of the overlap of the active and the next segment, both\n+// measured on the pod clock.\n+func (c *captureChain) setCut() {\n+\toverlapStart := c.next.started\n+\toverlapEnd := c.active.plannedEnd()\n+\tif overlapEnd.Sub(overlapStart) < 2*c.capture.window {\n+\t\t// the overlap is too short to match packets around a cut: the switch is reported as a\n+\t\t// gap once the active segment ended\n+\t\tc.cut = 0\n+\t\treturn\n+\t}\n+\tc.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()\n+\n+\twindow := c.capture.window.Nanoseconds()\n+\t// Packets the next segment holds back are stamped from T-W on: other chains' packets after\n+\t// that wait in the reorder buffer until the switch, so the merged stream stays in order.\n+\tc.capture.out.Hold(c, c.cut-window)\n+\n+\t// The active segment only matters for packets stamped before T. Once the pod clock passed\n+\t// T+W, it is closed: packets it read until then are still delivered, and the ones it reads\n+\t// later are stamped after T and dropped anyway. The next segment's Started record was\n+\t// written on the pod clock no later than now, so the pod clock passes T+W no later than\n+\t// (T - Started + W) from now.\n+\tactive := c.active\n+\tactive.stopTimer = time.AfterFunc(\n+\t\ttime.Duration(c.cut-c.next.started.UnixNano()+window), active.closeStdin)\n+}\n+\n+func (c *captureChain) handlePacket(\n+\tsegment *captureSegment,\n+\tpacket *clabcapture.Packet,\n+) (bool, error) {\n+\tswitch segment {\n+\tcase c.active:\n+\t\tif c.cut != 0 && packet.Timestamp >= c.cut {\n+\t\t\treturn false, nil\n+\t\t}\n+\t\tif c.next != nil {\n+\t\t\tc.emitted[packetKey(packet)]++\n+\t\t}\n+\n+\t\treturn c.emit(packet)\n+\tcase c.next:\n+\t\tc.held = append(c.held, packet)\n+\t}\n+\n+\treturn false, nil\n+}\n+\n+func (c *captureChain) emit(packet *clabcapture.Packet) (bool, error) {\n+\tif int(packet.InterfaceID) >= len(c.group.ids) {\n+\t\treturn true, fmt.Errorf(\"clabwire wrote a packet for interface %d of %d\",\n+\t\t\tpacket.InterfaceID, len(c.group.ids))\n+\t}",
        "lineStart": 3478,
        "lineEnd": 4779,
        "totalLines": 4780,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523233527,
      "end": 1793523233547
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19650b30f001fEyR2ZmuhvZ2VY",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650a855001ooGiCUj8bm23MA",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 47928,
    "input": 22434,
    "output": 21,
    "reasoning": 1,
    "cache": {
      "read": 25472,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19650a855001ooGiCUj8bm23MA",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523230805,
    "completed": 1793523233554
  },
  "parentID": "msg_196508bbe001tLsHPkKW57hw60",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 47928,
    "input": 22434,
    "output": 21,
    "reasoning": 1,
    "cache": {
      "read": 25472,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 7
step-start
{
  "type": "step-start",
  "id": "prt_19650be2d001kXVIYjg6EPUaeo",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650b315001ndmMoYOP5TaOov"
}
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "offset": 4780
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
4780: +	more, err := c.capture.emit(c.group.ids[packet.InterfaceID], packet)
4781: +
4782: +	return !more, err
4783: +}
4784: +
4785: +// switchSegments makes the next segment the active one after the active one ended, writing the
4786: +// held packets of the next one that the active one did not write.
4787: +func (c *captureChain) switchSegments(ctx context.Context, timer *time.Timer) (bool, error) {
4788: +	// the held packets are in the reorder buffer once this returns
4789: +	defer c.capture.out.Release(c)
4790: +
4791: +	ended := c.active
4792: +	if c.stopping && c.next != nil && c.next.started.IsZero() {
4793: +		// the chain is stopping: a follow-up that has not started takes nothing over
4794: +		c.next, c.held, c.emitted, c.cut = nil, nil, nil, 0
4795: +	}
4796: +	if c.final && c.next == nil {
4797: +		return true, nil
4798: +	}
4799: +
4800: +	if c.next == nil || c.next.started.IsZero() || c.cut == 0 {
4801: +		from := ended.ended
4802: +		if from.IsZero() {
4803: +			from = ended.plannedEnd()
4804: +		}
4805: +		gap := clablabruntime.CaptureGap{
4806: +			Node: c.group.display, Interfaces: c.group.interfaces, From: from,
4807: +			Reason: "the follow-up capture did not overlap the previous one",
4808: +		}
4809: +		if c.next != nil && !c.next.started.IsZero() {
4810: +			gap.To = c.next.started
4811: +		}
4812: +		c.capture.reportGap(gap)
4813: +	}
4814: +
4815: +	if c.next != nil && c.next.done && !c.stopping {
4816: +		// the follow-up already ended (it started too late to take over): keep what it
4817: +		// captured and continue with a fresh segment
4818: +		for _, packet := range c.held {
4819: +			if stop, err := c.emit(packet); stop || err != nil {
4820: +				return true, err
4821: +			}
4822: +		}
4823: +		c.next, c.held, c.emitted, c.cut = nil, nil, nil, 0
4824: +	}
4825: +
4826: +	if c.next == nil {
4827: +		if !c.capture.deadline.IsZero() &&
4828: +			!time.Now().Before(c.capture.deadline.Add(-c.capture.window)) {
4829: +			return true, nil
4830: +		}
4831: +		c.active = c.start(ctx, c.segmentDuration(time.Now()))
4832: +		resetTimer(timer, c.nextStartIn())
4833: +
4834: +		return false, nil
4835: +	}
4836: +
4837: +	window := c.capture.window.Nanoseconds()
4838: +	for _, packet := range c.held {
4839: +		if c.cut != 0 {
4840: +			if packet.Timestamp < c.cut-window {
4841: +				continue
4842: +			}
4843: +			if packet.Timestamp < c.cut+window {
4844: +				key := packetKey(packet)
4845: +				if c.emitted[key] > 0 {
4846: +					c.emitted[key]--
4847: +					continue
4848: +				}
4849: +			}
4850: +		}
4851: +		if stop, err := c.emit(packet); stop || err != nil {
4852: +			return true, err
4853: +		}
4854: +	}
4855: +
4856: +	c.active, c.next = c.next, nil
4857: +	c.held, c.emitted, c.cut = nil, nil, 0
4858: +	if c.active.done {
4859: +		// the chain is stopping and the follow-up ended before the active one
4860: +		return true, nil
4861: +	}
4862: +	resetTimer(timer, c.nextStartIn())
4863: +
4864: +	return false, nil
4865: +}
4866: +
4867: +func resetTimer(timer *time.Timer, d time.Duration) {
4868: +	if !timer.Stop() {
4869: +		select {
4870: +		case <-timer.C:
4871: +		default:
4872: +		}
4873: +	}
4874: +	timer.Reset(d)
4875: +}
4876: +
4877: +// packetKey identifies a packet by its interface and content.
4878: +func packetKey(packet *clabcapture.Packet) uint64 {
4879: +	hash := fnv.New64a()
4880: +	var id [4]byte
4881: +	id[0] = byte(packet.InterfaceID)
4882: +	id[1] = byte(packet.InterfaceID >> 8)
4883: +	_, _ = hash.Write(id[:])
4884: +	_, _ = hash.Write(packet.Data)
4885: +
4886: +	return hash.Sum64()
4887: +}
4888: +
4889: +// start runs one clabwire capture and reports its packets, audit records and end as events.
4890: +func (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {
4891: +	segmentCtx, cancel := context.WithCancel(ctx)
4892: +	stdinReader, stdinWriter := io.Pipe()
4893: +	segment := &captureSegment{
4894: +		index: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,
4895: +		closeStdin: func() { _ = stdinWriter.Close() },
4896: +	}
4897: +	c.segments++
4898: +
4899: +	command := []string{
4900: +		clabwireManager, "node-runtime", "packet-capture",
4901: +		"--nodeName", c.group.location.NodeName,
4902: +		"--format", "pcapng",
4903: +		"--snapLength", strconv.Itoa(c.capture.req.SnapLength),
4904: +		"--duration", duration.String(),
4905: +		clabwireStopOnStdinClose,
4906: +	}
4907: +	for _, name := range c.group.interfaces {
4908: +		command = append(command, "--interface", name)
4909: +	}
4910: +	if c.capture.req.PacketLimit > 0 {
4911: +		remaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()
4912: +		command = append(command, "--packetLimit",
4913: +			strconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))
4914: +	}
4915: +
4916: +	send := func(event segmentEvent) {
4917: +		event.segment = segment
4918: +		select {
4919: +		case c.events <- event:
4920: +		case <-segmentCtx.Done():
4921: +		}
4922: +	}
4923: +
4924: +	stdoutReader, stdoutWriter := io.Pipe()
4925: +	stderr := &auditLineWriter{send: func(audit *captureAudit) { send(segmentEvent{audit: audit}) }}
4926: +
4927: +	// The exec outlives the segment's context by up to captureStdinCloseGrace: when the segment
4928: +	// ends for any reason (the capture is cancelled or failed, the output failed, or a newer
4929: +	// segment took over), its stdin is closed first so clabwire ends on its own, and the stream
4930: +	// is cut only if it does not.
4931: +	execCtx, cancelExec := context.WithCancel(context.WithoutCancel(segmentCtx))
4932: +	execDone := make(chan struct{})
4933: +
4934: +	c.wg.Add(3)
4935: +	readDone := make(chan error, 1)
4936: +	go func() {
4937: +		defer c.wg.Done()
4938: +		readDone <- c.readSegment(stdoutReader, func(packet *clabcapture.Packet) {
4939: +			send(segmentEvent{packet: packet})
4940: +		})
4941: +		_, _ = io.Copy(io.Discard, stdoutReader)
4942: +	}()
4943: +	go func() {
4944: +		defer c.wg.Done()
4945: +		select {
4946: +		case <-execDone:
4947: +			return
4948: +		case <-segmentCtx.Done():
4949: +		}
4950: +		segment.closeStdin()
4951: +		grace := time.NewTimer(captureStdinCloseGrace)
4952: +		defer grace.Stop()
4953: +		select {
4954: +		case <-execDone:
4955: +		case <-grace.C:
4956: +			log.Debug("Capture segment did not end after its stdin closed, cutting the stream",
4957: +				"node", c.group.display, "segment", segment.index)
4958: +			cancelExec()
4959: +		}
4960: +	}()
4961: +	go func() {
4962: +		defer c.wg.Done()
4963: +		defer cancel()
4964: +		defer cancelExec()
4965: +
4966: +		err := c.capture.r.execInPodContainer()(execCtx, c.group.location.Namespace,
4967: +			c.group.location.Pod, clabwireContainer, command, stdinReader, stdoutWriter, stderr)
4968: +		close(execDone)
4969: +		// the process ended: release the stdin copy of the exec stream
4970: +		segment.closeStdin()
4971: +		_ = stdoutWriter.Close()
4972: +		readErr := <-readDone
4973: +		stderr.flush()
4974: +		if err == nil && readErr != nil {
4975: +			err = readErr
4976: +		}
4977: +		if err != nil && stderr.text() != "" {
4978: +			if unsupported := unsupportedClabwire(
4979: +				c.group.location,
4980: +				stderr.text(),
4981: +			); unsupported != nil {
4982: +				err = unsupported
4983: +			} else {
4984: +				err = fmt.Errorf("%w: %s", err, stderr.text())
4985: +			}
4986: +		}
4987: +		send(segmentEvent{done: true, err: err})
4988: +	}()
4989: +
4990: +	return segment
4991: +}
4992: +
4993: +// unsupportedClabwire recognizes a clabwire that rejects --stop-on-stdin-close, which every
4994: +// capture passes: its release predates the capture contract the runtime needs.
4995: +func unsupportedClabwire(location clablabruntime.NodeLocation, stderr string) error {
4996: +	if !strings.Contains(stderr, "flag provided but not defined") ||
4997: +		!strings.Contains(stderr, strings.TrimPrefix(clabwireStopOnStdinClose, "-")) {
4998: +		return nil
4999: +	}
5000: +
5001: +	return &unsupportedClabernetesError{reason: fmt.Sprintf(
5002: +		"clabwire in pod %s/%s does not accept packet-capture %s",
5003: +		location.Namespace, location.Pod, clabwireStopOnStdinClose)}
5004: +}
5005: +
5006: +// readSegment checks that a segment's interfaces are the requested ones and passes its packets
5007: +// on with the segment's interface index.
5008: +func (c *captureChain) readSegment(stdout io.Reader, packet func(*clabcapture.Packet)) error {
5009: +	reader := clabcapture.NewReader(stdout)
5010: +	interfaces := 0
5011: +	for {
5012: +		event, err := reader.Next()
5013: +		if errors.Is(err, io.EOF) {
5014: +			return nil
5015: +		}
5016: +		if errors.Is(err, io.ErrUnexpectedEOF) {
5017: +			// the process was stopped inside a block
5018: +			return nil
5019: +		}
5020: +		if err != nil {
5021: +			return fmt.Errorf("failed to read the clabwire capture: %w", err)
5022: +		}
5023: +		if event.Interface != nil {
5024: +			if interfaces >= len(c.group.interfaces) ||
5025: +				event.Interface.Name != c.group.interfaces[interfaces] {
5026: +				return fmt.Errorf("clabwire described interface %q, want %s in order",
5027: +					event.Interface.Name, strings.Join(c.group.interfaces, ", "))
5028: +			}
5029: +			interfaces++
5030: +			continue
5031: +		}
5032: +		if event.Packet != nil {
5033: +			packet(event.Packet)
5034: +		}
5035: +	}
5036: +}
5037: +
5038: +// auditLineWriter parses clabwire's stderr: audit records go to send, other lines are kept for
5039: +// error messages.
5040: +type auditLineWriter struct {
5041: +	send func(*captureAudit)
5042: +
5043: +	mu      sync.Mutex
5044: +	partial []byte
5045: +	other   []string
5046: +}
5047: +
5048: +func (w *auditLineWriter) Write(data []byte) (int, error) {
5049: +	w.mu.Lock()
5050: +	w.partial = append(w.partial, data...)
5051: +	var lines [][]byte
5052: +	for {
5053: +		idx := bytes.IndexByte(w.partial, '\n')
5054: +		if idx < 0 {
5055: +			break
5056: +		}
5057: +		lines = append(lines, append([]byte(nil), w.partial[:idx]...))
5058: +		w.partial = w.partial[idx+1:]
5059: +	}
5060: +	w.mu.Unlock()
5061: +
5062: +	for _, line := range lines {
5063: +		w.line(line)
5064: +	}
5065: +
5066: +	return len(data), nil
5067: +}
5068: +
5069: +func (w *auditLineWriter) flush() {
5070: +	w.mu.Lock()
5071: +	line := w.partial
5072: +	w.partial = nil
5073: +	w.mu.Unlock()
5074: +	if len(bytes.TrimSpace(line)) != 0 {
5075: +		w.line(line)
5076: +	}
5077: +}
5078: +
5079: +func (w *auditLineWriter) line(line []byte) {
5080: +	line = bytes.TrimSpace(line)
5081: +	if len(line) == 0 {
5082: +		return
5083: +	}
5084: +
5085: +	var audit captureAudit
5086: +	if err := json.Unmarshal(
5087: +		line,
5088: +		&audit,
5089: +	); err == nil &&
5090: +		audit.SchemaVersion == captureAuditSchema {
5091: +		w.send(&audit)
5092: +		return
5093: +	}
5094: +
5095: +	w.mu.Lock()
5096: +	defer w.mu.Unlock()
5097: +	if len(w.other) < 20 {
5098: +		w.other = append(w.other, string(line))
5099: +	}
5100: +}
5101: +
5102: +func (w *auditLineWriter) text() string {
5103: +	w.mu.Lock()
5104: +	defer w.mu.Unlock()
5105: +
5106: +	return strings.Join(w.other, "; ")
5107: +}
5108: diff --git a/labruntime/clabernetes/capture_interfaces.go b/labruntime/clabernetes/capture_interfaces.go
5109: new file mode 100644
5110: index 0000000..21029ed
5111: --- /dev/null
5112: +++ b/labruntime/clabernetes/capture_interfaces.go
5113: @@ -0,0 +1,187 @@
5114: +package clabernetes
5115: +
5116: +import (
5117: +	"bytes"
5118: +	"context"
5119: +	"errors"
5120: +	"fmt"
5121: +	"io"
5122: +	"sort"
5123: +	"sync"
5124: +
5125: +	"github.com/charmbracelet/log"
5126: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
5127: +	clabtypes "github.com/srl-labs/containerlab/types"
5128: +	corev1 "k8s.io/api/core/v1"
5129: +	"k8s.io/client-go/kubernetes/scheme"
5130: +	"k8s.io/client-go/tools/remotecommand"
5131: +	kubeexec "k8s.io/client-go/util/exec"
5132: +)
5133: +
5134: +// streamPodExec runs a command in a pod container without a terminal and streams its stdout
5135: +// and stderr. A non-nil stdin is attached: when it ends, the process's stdin is closed (the
5136: +// websocket v5 close signal, or a half-closed SPDY stream). A nonzero exit returns a
5137: +// *labruntime.CommandExitError.
5138: +func (r *Runtime) streamPodExec(
5139: +	ctx context.Context,
5140: +	namespace, pod, container string,
5141: +	command []string,
5142: +	stdin io.Reader,
5143: +	stdout, stderr io.Writer,
5144: +) error {
5145: +	execURL := r.kubeClient.CoreV1().RESTClient().Post().
5146: +		Resource("pods").
5147: +		Name(pod).
5148: +		Namespace(namespace).
5149: +		SubResource("exec").
5150: +		VersionedParams(&corev1.PodExecOptions{
5151: +			Container: container,
5152: +			Command:   command,
5153: +			Stdin:     stdin != nil,
5154: +			Stdout:    stdout != nil,
5155: +			Stderr:    stderr != nil,
5156: +		}, scheme.ParameterCodec).URL()
5157: +
5158: +	executor, err := r.newExecutor(execURL)
5159: +	if err != nil {
5160: +		return err
5161: +	}
5162: +
5163: +	// client-go reports streams cut by a cancelled context through the context's logger; a
5164: +	// capture ends that way on purpose, so it goes to the debug log
5165: +	err = executor.StreamWithContext(withKubernetesClientDebugLogs(ctx),
5166: +		remotecommand.StreamOptions{
5167: +			Stdin:  stdin,
5168: +			Stdout: stdout,
5169: +			Stderr: stderr,
5170: +		})
5171: +
5172: +	var exitErr kubeexec.ExitError
5173: +	if errors.As(err, &exitErr) {
5174: +		return &clablabruntime.CommandExitError{Code: exitErr.ExitStatus()}
5175: +	}
5176: +	if err != nil {
5177: +		return fmt.Errorf("failed to execute command in pod %s/%s container %s: %w",
5178: +			namespace, pod, container, err)
5179: +	}
5180: +
5181: +	return nil
5182: +}
5183: +
5184: +// InspectInterfaces lists the capturable link interfaces of the requested nodes, or of every
5185: +// running node, in the shape of `inspect interfaces`: per node (named <lab>-<node> like in
5186: +// inspect), the interface and its alias as clabwire reports them, and the MAC address, index,
5187: +// MTU and operational state read from sysfs in the device container. A node whose device
5188: +// container has no shell reports its interfaces without these attributes.
5189: +func (r *Runtime) InspectInterfaces(
5190: +	ctx context.Context,
5191: +	req clablabruntime.NodeRequest,
5192: +) ([]*clabtypes.ContainerInterfaces, error) {
5193: +	r, err := r.connect(ctx, req.Identity)
5194: +	if err != nil {
5195: +		return nil, err
5196: +	}
5197: +
5198: +	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{
5199: +		Name: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,
5200: +	})
5201: +	if err != nil {
5202: +		return nil, err
5203: +	}
5204: +
5205: +	running := make([]clablabruntime.NodeLocation, 0, len(locations))
5206: +	for _, location := range locations {
5207: +		if location.Pod == "" {
5208: +			log.Warn("Skipping interface detection of a node that does not run",
5209: +				"node", location.NodeName)
5210: +			continue
5211: +		}
5212: +		running = append(running, location)
5213: +	}
5214: +
5215: +	listed, err := r.listCaptureInterfaces(ctx, req.Name, running)
5216: +	if err != nil {
5217: +		return nil, err
5218: +	}
5219: +	states := r.sampleInterfaceStates(ctx, running)
5220: +
5221: +	result := make([]*clabtypes.ContainerInterfaces, 0, len(running))
5222: +	for _, location := range running {
5223: +		container := &clabtypes.ContainerInterfaces{
5224: +			ContainerName: req.Name + "-" + location.NodeName,
5225: +			Interfaces:    []*clabtypes.ContainerInterfaceDetails{},
5226: +		}
5227: +		for _, entry := range listed[location.NodeName] {
5228: +			details := &clabtypes.ContainerInterfaceDetails{
5229: +				InterfaceName:  entry.Interface,
5230: +				InterfaceAlias: entry.Alias,
5231: +				// clabwire realizes every lab link interface as a veth pair
5232: +				InterfaceType: "veth",
5233: +			}
5234: +			if state, ok := states[location.NodeName][entry.Interface]; ok {
5235: +				details.InterfaceMAC = state.MAC
5236: +				details.InterfaceIndex = state.Index
5237: +				details.InterfaceMTU = state.MTU
5238: +				details.InterfaceState = state.OperState
5239: +			}
5240: +			container.Interfaces = append(container.Interfaces, details)
5241: +		}
5242: +		sort.Slice(container.Interfaces, func(i, j int) bool {
5243: +			return container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName
5244: +		})
5245: +		result = append(result, container)
5246: +	}
5247: +	sort.Slice(result, func(i, j int) bool {
5248: +		return result[i].ContainerName < result[j].ContainerName
5249: +	})
5250: +
5251: +	return result, nil
5252: +}
5253: +
5254: +// sampleInterfaceStates reads the sysfs interface attributes of every node's device container,
5255: +// one exec per node, with the script the interface events use.
5256: +func (r *Runtime) sampleInterfaceStates(
5257: +	ctx context.Context,
5258: +	locations []clablabruntime.NodeLocation,
5259: +) map[string]map[string]c9sIfaceState {
5260: +	var mu sync.Mutex
5261: +	result := map[string]map[string]c9sIfaceState{}
5262: +
5263: +	var wg sync.WaitGroup
5264: +	workers := make(chan struct{}, interfaceSampleWorkers)
5265: +	exec := r.execInPodContainer()
5266: +	for _, location := range locations {
5267: +		wg.Add(1)
5268: +		go func() {
5269: +			defer wg.Done()
5270: +			workers <- struct{}{}
5271: +			defer func() { <-workers }()
5272: +
5273: +			var stdout, stderr bytes.Buffer
5274: +			err := exec(ctx, location.Namespace, location.Pod, location.Container,
5275: +				[]string{"sh", "-c", interfaceSampleScript}, nil, &stdout, &stderr)
5276: +			if err != nil {
5277: +				log.Debug("Cannot read the interface state of a c9s node",
5278: +					"node", location.NodeName, "error", err)
5279: +				return
5280: +			}
5281: +			_, ifaces, _, err := parseInterfaceSample(stdout.Bytes())
5282: +			if err != nil {
5283: +				log.Debug("Cannot parse the interface state of a c9s node",
5284: +					"node", location.NodeName, "error", err)
5285: +				return
5286: +			}
5287: +
5288: +			byName := make(map[string]c9sIfaceState, len(ifaces))
5289: +			for _, iface := range ifaces {
5290: +				byName[iface.Name] = iface
5291: +			}
5292: +			mu.Lock()
5293: +			result[location.NodeName] = byName
5294: +			mu.Unlock()
5295: +		}()
5296: +	}
5297: +	wg.Wait()
5298: +
5299: +	return result
5300: +}
5301: diff --git a/labruntime/clabernetes/capture_test.go b/labruntime/clabernetes/capture_test.go
5302: new file mode 100644
5303: index 0000000..16628b5
5304: --- /dev/null
5305: +++ b/labruntime/clabernetes/capture_test.go
5306: @@ -0,0 +1,1050 @@
5307: +package clabernetes
5308: +
5309: +import (
5310: +	"bytes"
5311: +	"context"
5312: +	"encoding/binary"
5313: +	"encoding/json"
5314: +	"errors"
5315: +	"fmt"
5316: +	"io"
5317: +	"slices"
5318: +	"strings"
5319: +	"sync"
5320: +	"testing"
5321: +	"time"
5322: +
5323: +	clabcapture "github.com/srl-labs/containerlab/capture"
5324: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
5325: +	corev1 "k8s.io/api/core/v1"
5326: +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
5327: +	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
5328: +	k8sruntime "k8s.io/apimachinery/pkg/runtime"
5329: +)
5330: +
5331: +func captureTestNode(name, original, container string) *unstructured.Unstructured {
5332: +	labels := map[string]any{labelTopologyOwner: "lab1"}
5333: +	if original != "" {
5334: +		labels[labelOriginalNodeName] = original
5335: +	}
5336: +
5337: +	return &unstructured.Unstructured{Object: map[string]any{
5338: +		"apiVersion": c9sAPIVersion,
5339: +		"kind":       "Node",
5340: +		"metadata": map[string]any{
5341: +			"name": name, "namespace": "lab-ns", "uid": "uid-" + name, "labels": labels,
5342: +		},
5343: +		"spec": map[string]any{"kind": "srl", "runState": nodeRunStateRunning},
5344: +		"status": map[string]any{
5345: +			"readiness":        "ready",
5346: +			"directContainers": []any{map[string]any{"name": container, "id": name}},
5347: +		},
5348: +	}}
5349: +}
5350: +
5351: +func captureTestPod(name, node string) *corev1.Pod {
5352: +	return &corev1.Pod{
5353: +		ObjectMeta: metav1.ObjectMeta{
5354: +			Name: name, Namespace: "lab-ns",
5355: +			Labels: map[string]string{
5356: +				labelApp: clabernetesAppValue, labelTopologyOwner: "lab1", labelTopologyNode: node,
5357: +			},
5358: +		},
5359: +		Status: corev1.PodStatus{Phase: corev1.PodRunning},
5360: +	}
5361: +}
5362: +
5363: +// captureListing is the --list-interfaces output of each pod.
5364: +var captureListing = map[string][]clabwireInterface{ //nolint:gochecknoglobals
5365: +	"lab1-r1-abc": {
5366: +		{
5367: +			Node:          "r1",
5368: +			Interface:     "e1-1",
5369: +			Alias:         "ethernet-1/1",
5370: +			PeerNode:      "r2",
5371: +			PeerInterface: "ethernet-1/1",
5372: +		},
5373: +		{Node: "r1", Interface: "e1-2", PeerNode: "host", PeerInterface: "r1-e1-2"},
5374: +	},
5375: +	"lab1-r2-def": {
5376: +		{
5377: +			Node:          "r2",
5378: +			Interface:     "e1-1",
5379: +			Alias:         "ethernet-1/1",
5380: +			PeerNode:      "r1",
5381: +			PeerInterface: "ethernet-1/1",
5382: +		},
5383: +	},
5384: +}
5385: +
5386: +// fakeClabwire plays clabwire packet-capture and --list-interfaces in the fake pod exec. Every
5387: +// capture process sees the same traffic: one packet per tick on each requested interface,
5388: +// carrying the tick number, stamped with the tick time plus a per-process jitter (clabwire stamps
5389: +// packets when it reads them).
5390: +type fakeClabwire struct {
5391: +	t     *testing.T
5392: +	epoch time.Time
5393: +	tick  time.Duration
5394: +
5395: +	mu       sync.Mutex
5396: +	commands [][]string
5397: +	// processes counts the capture processes started per node
5398: +	processes map[string]int
5399: +
5400: +	// startDelay delays the Started record of the given process index (all nodes).
5401: +	startDelay map[int]time.Duration
5402: +	// firstStartDelay delays the Started record of a node's first process.
5403: +	firstStartDelay map[string]time.Duration
5404: +	// fail makes a process write this audit status and exit 1.
5405: +	fail string
5406: +	// stderrOnly makes a process write this text to stderr and exit 1, like a clabwire that
5407: +	// rejects a flag.
5408: +	stderrOnly string
5409: +	// stampSkew stamps the packets of a node this much earlier, as if its stream reached
5410: +	// containerlab this much later than the others.
5411: +	stampSkew map[string]time.Duration
5412: +	// stdinClosed counts the processes that ended because their stdin closed, per node.
5413: +	stdinClosed map[string]int
5414: +	// written counts the packets written to stdout, per node.
5415: +	written map[string]int
5416: +	// sysfs is the device container's interface sample.
5417: +	sysfs string
5418: +}
5419: +
5420: +func newFakeClabwire(t *testing.T, tick time.Duration) *fakeClabwire {
5421: +	t.Helper()
5422: +
5423: +	return &fakeClabwire{
5424: +		t: t, epoch: time.Now(), tick: tick, processes: map[string]int{},
5425: +		startDelay: map[int]time.Duration{}, stampSkew: map[string]time.Duration{},
5426: +		firstStartDelay: map[string]time.Duration{},
5427: +		stdinClosed:     map[string]int{},
5428: +		written:         map[string]int{},
5429: +	}
5430: +}
5431: +
5432: +func (f *fakeClabwire) exec(
5433: +	ctx context.Context,
5434: +	namespace, pod, container string,
5435: +	command []string,
5436: +	stdin io.Reader,
5437: +	stdout, stderr io.Writer,
5438: +) error {
5439: +	f.mu.Lock()
5440: +	f.commands = append(
5441: +		f.commands,
5442: +		append([]string{namespace + "/" + pod + "/" + container}, command...),
5443: +	)
5444: +	f.mu.Unlock()
5445: +
5446: +	if container != clabwireContainer {
5447: +		_, _ = io.WriteString(stdout, f.sysfs)
5448: +		return nil
5449: +	}
5450: +	if slices.Contains(command, "--list-interfaces") {
5451: +		return json.NewEncoder(stdout).Encode(captureListing[pod])
5452: +	}
5453: +
5454: +	return f.capture(ctx, command, stdin, stdout, stderr)
5455: +}
5456: +
5457: +func flagValues(command []string, name string) []string {
5458: +	var values []string
5459: +	for idx := 0; idx+1 < len(command); idx++ {
5460: +		if command[idx] == name {
5461: +			values = append(values, command[idx+1])
5462: +		}
5463: +	}
5464: +
5465: +	return values
5466: +}
5467: +
5468: +func (f *fakeClabwire) audit(
5469: +	stderr io.Writer,
5470: +	status, node string,
5471: +	interfaces []string,
5472: +	reason string,
5473: +) {
5474: +	record := map[string]any{
5475: +		"schemaVersion": captureAuditSchema, "time": time.Now().UTC(), "operation": "PacketCapture",
5476: +		"status": status, "nodeName": node, "format": "pcapng", "reason": reason,
5477: +	}
5478: +	entries := []map[string]any{}
5479: +	for _, name := range interfaces {
5480: +		entries = append(entries, map[string]any{"name": name})
5481: +	}
5482: +	record["interfaces"] = entries
5483: +	data, _ := json.Marshal(record)
5484: +	_, _ = stderr.Write(append(data, '\n'))
5485: +}
5486: +
5487: +func (f *fakeClabwire) capture(
5488: +	ctx context.Context,
5489: +	command []string,
5490: +	stdin io.Reader,
5491: +	stdout, stderr io.Writer,
5492: +) error {
5493: +	f.mu.Lock()
5494: +	rejected := f.stderrOnly
5495: +	f.mu.Unlock()
5496: +	if rejected != "" {
5497: +		_, _ = io.WriteString(stdout, "Incorrect Usage: "+rejected+"\n\nNAME:\n   manager\n")
5498: +		_, _ = io.WriteString(stderr, rejected+"\n")
5499: +		return &clablabruntime.CommandExitError{Code: 1}
5500: +	}
5501: +
5502: +	// clabwire ends the capture when stdin closes (--stop-on-stdin-close)
5503: +	if !slices.Contains(command, clabwireStopOnStdinClose) || stdin == nil {
5504: +		f.t.Errorf("capture without stdin and %s: %v", clabwireStopOnStdinClose, command)
5505: +		return fmt.Errorf("no stdin")
5506: +	}
5507: +	stdinClosed := make(chan struct{})
5508: +	go func() {
5509: +		_, _ = io.Copy(io.Discard, stdin)
5510: +		close(stdinClosed)
5511: +	}()
5512: +
5513: +	node := flagValues(command, "--nodeName")[0]
5514: +	interfaces := flagValues(command, "--interface")
5515: +	duration, err := time.ParseDuration(flagValues(command, "--duration")[0])
5516: +	if err != nil {
5517: +		f.t.Errorf("duration: %v", err)
5518: +	}
5519: +	if !slices.Equal(flagValues(command, "--format"), []string{"pcapng"}) {
5520: +		f.t.Errorf("capture without --format pcapng: %v", command)
5521: +	}
5522: +
5523: +	f.mu.Lock()
5524: +	index := f.processes[node]
5525: +	f.processes[node]++
5526: +	delay := f.startDelay[index]
5527: +	if index == 0 {
5528: +		delay += f.firstStartDelay[node]
5529: +	}
5530: +	failure := f.fail
5531: +	skew := f.stampSkew[node]
5532: +	f.mu.Unlock()
5533: +
5534: +	if failure != "" {
5535: +		f.audit(stderr, failure, node, interfaces, "interface \"eth9\" is not uniquely planned")
5536: +		return &clablabruntime.CommandExitError{Code: 1}
5537: +	}
5538: +
5539: +	select {
5540: +	case <-time.After(delay):
5541: +	case <-ctx.Done():
5542: +		return ctx.Err()
5543: +	case <-stdinClosed:
5544: +		f.audit(stderr, captureAuditStarted, node, interfaces, "")
5545: +		f.audit(stderr, captureAuditSucceeded, node, interfaces, "client closed: stdin reached EOF")
5546: +		return nil
5547: +	}
5548: +
5549: +	writer := clabcapture.NewWriter(stdout)
5550: +	f.audit(stderr, captureAuditStarted, node, interfaces, "")
5551: +	if err := writer.WriteHeader(interfaces, clabcapture.DefaultSnapLength); err != nil {
5552: +		return err
5553: +	}
5554: +
5555: +	// clabwire's own section header names it
5556: +	end := time.Now().Add(duration)
5557: +	jitter := time.Duration(index%3) * 7 * time.Microsecond
5558: +	next := time.Now().Sub(f.epoch)/f.tick + 1
5559: +	for {
5560: +		at := f.epoch.Add(next * f.tick)
5561: +		if at.After(end) {
5562: +			break
5563: +		}
5564: +		select {
5565: +		case <-ctx.Done():
5566: +			return ctx.Err()
5567: +		case <-stdinClosed:
5568: +			f.mu.Lock()
5569: +			f.stdinClosed[node]++
5570: +			f.mu.Unlock()
5571: +			f.audit(
5572: +				stderr,
5573: +				captureAuditSucceeded,
5574: +				node,
5575: +				interfaces,
5576: +				"client closed: stdin reached EOF",
5577: +			)
5578: +			return nil
5579: +		case <-time.After(time.Until(at)):
5580: +		}
5581: +		for id := range interfaces {
5582: +			data := make([]byte, 64)
5583: +			binary.BigEndian.PutUint64(data[0:], uint64(next))
5584: +			copy(data[8:], node+":"+interfaces[id])
5585: +			if err := writer.WritePacket(uint32(id), &clabcapture.Packet{ //nolint:gosec // small
5586: +				Timestamp: at.Add(jitter - skew).UnixNano(), OriginalLength: 64, Data: data,
5587: +			}); err != nil {
5588: +				return err
5589: +			}
5590: +			f.mu.Lock()
5591: +			f.written[node]++
5592: +			f.mu.Unlock()
5593: +		}
5594: +		next++
5595: +	}
5596: +	f.audit(stderr, captureAuditSucceeded, node, interfaces, "")
5597: +
5598: +	return nil
5599: +}
5600: +
5601: +func (f *fakeClabwire) captureCommands() [][]string {
5602: +	f.mu.Lock()
5603: +	defer f.mu.Unlock()
5604: +
5605: +	var result [][]string
5606: +	for _, command := range f.commands {
5607: +		if slices.Contains(command, "packet-capture") &&
5608: +			!slices.Contains(command, "--list-interfaces") {
5609: +			result = append(result, command)
5610: +		}
5611: +	}
5612: +
5613: +	return result
5614: +}
5615: +
5616: +// captureTestRuntime is lab1 in lab-ns with nodes r1 (topology name R1) and r2, each in its
5617: +// own pod, and a fake clabwire.
5618: +func captureTestRuntime(t *testing.T, tick time.Duration) (*Runtime, *fakeClabwire) {
5619: +	t.Helper()
5620: +
5621: +	r := newTestRuntimeWithKubeObjects(
5622: +		[]*unstructured.Unstructured{
5623: +			captureTestNode("r1", "R1", "node-r1-x"),
5624: +			captureTestNode("r2", "", "node-r2-x"),
5625: +		},
5626: +		[]k8sruntime.Object{
5627: +			captureTestPod("lab1-r1-abc", "r1"),
5628: +			captureTestPod("lab1-r2-def", "r2"),
5629: +		},
5630: +	)
5631: +	r.labNamespaceOverride = "lab-ns"
5632: +	clabwire := newFakeClabwire(t, tick)
5633: +	r.podExec = clabwire.exec
5634: +
5635: +	return r, clabwire
5636: +}
5637: +
5638: +// parsedCapture is a pcapng stream read back.
5639: +type parsedCapture struct {
5640: +	sections   int
5641: +	interfaces []string
5642: +	packets    []clabcapture.Packet
5643: +}
5644: +
5645: +func parseCapture(t *testing.T, data []byte) parsedCapture {
5646: +	t.Helper()
5647: +
5648: +	reader := clabcapture.NewReader(bytes.NewReader(data))
5649: +	var parsed parsedCapture
5650: +	for {
5651: +		event, err := reader.Next()
5652: +		if errors.Is(err, io.EOF) {
5653: +			break
5654: +		}
5655: +		if err != nil {
5656: +			t.Fatalf("invalid capture: %v", err)
5657: +		}
5658: +		if event.Interface != nil {
5659: +			if len(parsed.packets) != 0 {
5660: +				t.Fatal("interface description after the first packet")
5661: +			}
5662: +			if event.Interface.TSResol != 9 /* nanoseconds */ {
5663: +				t.Fatalf("interface %s tsresol = %d", event.Interface.Name, event.Interface.TSResol)
5664: +			}
5665: +			parsed.interfaces = append(parsed.interfaces, event.Interface.Name)
5666: +		}
5667: +		if event.Packet != nil {
5668: +			parsed.packets = append(parsed.packets, *event.Packet)
5669: +		}
5670: +	}
5671: +	parsed.sections = reader.Sections()
5672: +
5673: +	return parsed
5674: +}
5675: +
5676: +func packetSequence(packet clabcapture.Packet) uint64 {
5677: +	return binary.BigEndian.Uint64(packet.Data[0:8])
5678: +}
5679: +
5680: +func packetOrigin(packet clabcapture.Packet) string {
5681: +	return strings.TrimRight(string(packet.Data[8:]), "\x00")
5682: +}
5683: +
5684: +func TestCaptureInterfacesUsesTopologyNames(t *testing.T) {
5685: +	t.Parallel()
5686: +
5687: +	r, _ := captureTestRuntime(t, time.Millisecond)
5688: +	interfaces, err := r.CaptureInterfaces(
5689: +		context.Background(),
5690: +		clablabruntime.NodeRequest{Name: "lab1"},
5691: +	)
5692: +	if err != nil {
5693: +		t.Fatal(err)
5694: +	}
5695: +	want := []clablabruntime.CaptureInterface{
5696: +		{
5697: +			Node:          "R1",
5698: +			Interface:     "e1-1",
5699: +			Alias:         "ethernet-1/1",
5700: +			PeerNode:      "r2",
5701: +			PeerInterface: "ethernet-1/1",
5702: +		},
5703: +		{Node: "R1", Interface: "e1-2", PeerNode: "host", PeerInterface: "r1-e1-2"},
5704: +		{
5705: +			Node:          "r2",
5706: +			Interface:     "e1-1",
5707: +			Alias:         "ethernet-1/1",
5708: +			PeerNode:      "R1",
5709: +			PeerInterface: "ethernet-1/1",
5710: +		},
5711: +	}
5712: +	if !slices.Equal(interfaces, want) {
5713: +		t.Fatalf("interfaces = %+v\nwant %+v", interfaces, want)
5714: +	}
5715: +
5716: +	one, err := r.CaptureInterfaces(context.Background(), clablabruntime.NodeRequest{
5717: +		Name: "lab1", Nodes: []string{"r2"},
5718: +	})
5719: +	if err != nil || len(one) != 1 || one[0].Node != "r2" {
5720: +		t.Fatalf("r2 interfaces = %+v, %v", one, err)
5721: +	}
5722: +}
5723: +
5724: +func TestCaptureMergesNodesIntoOneSection(t *testing.T) {
5725: +	t.Parallel()
5726: +
5727: +	r, clabwire := captureTestRuntime(t, 10*time.Millisecond)
5728: +	var out bytes.Buffer
5729: +	err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
5730: +		Name: "lab1",
5731: +		// the topology name of r1, an alias, and a second node between two r1 interfaces
5732: +		Targets: []clablabruntime.CaptureTarget{
5733: +			{Node: "R1", Interface: "ethernet-1/1"},
5734: +			{Node: "r2", Interface: "e1-1"},
5735: +			{Node: "r1", Interface: "e1-2"},
5736: +		},
5737: +		Duration: 300 * time.Millisecond,
5738: +	}, &out)
5739: +	if err != nil {
5740: +		t.Fatal(err)
5741: +	}
5742: +
5743: +	parsed := parseCapture(t, out.Bytes())
5744: +	if parsed.sections != 1 {
5745: +		t.Fatalf("sections = %d, want one merged section", parsed.sections)
5746: +	}
5747: +	wantNames := []string{"R1:e1-1", "r2:e1-1", "R1:e1-2"}
5748: +	if !slices.Equal(parsed.interfaces, wantNames) {
5749: +		t.Fatalf("interfaces = %v, want %v", parsed.interfaces, wantNames)
5750: +	}
5751: +
5752: +	// one clabwire process per node, with all of the node's interfaces in request order
5753: +	commands := clabwire.captureCommands()
5754: +	if len(commands) != 2 {
5755: +		t.Fatalf("capture processes = %d, want one per node: %v", len(commands), commands)
5756: +	}
5757: +	for _, command := range commands {
5758: +		node := flagValues(command, "--nodeName")[0]
5759: +		want := map[string][]string{"r1": {"e1-1", "e1-2"}, "r2": {"e1-1"}}[node]
5760: +		if got := flagValues(command, "--interface"); !slices.Equal(got, want) {
5761: +			t.Fatalf("%s interfaces = %v, want %v", node, got, want)
5762: +		}
5763: +		if !strings.HasSuffix(command[0], "/"+clabwireContainer) {
5764: +			t.Fatalf("capture ran in %s, want the clabwire container", command[0])
5765: +		}
5766: +	}
5767: +
5768: +	// every packet carries the merged ID of its interface
5769: +	wantOrigin := map[uint32]string{0: "r1:e1-1", 1: "r2:e1-1", 2: "r1:e1-2"}
5770: +	perInterface := map[uint32]int{}
5771: +	for _, packet := range parsed.packets {
5772: +		if packetOrigin(packet) != wantOrigin[packet.InterfaceID] {
5773: +			t.Fatalf("packet from %s has interface ID %d", packetOrigin(packet), packet.InterfaceID)
5774: +		}
5775: +		perInterface[packet.InterfaceID]++
5776: +	}
5777: +	for id := range uint32(3) {
5778: +		if perInterface[id] == 0 {
5779: +			t.Fatalf("no packets on %s: %v", wantNames[id], perInterface)
5780: +		}
5781: +	}
5782: +}
5783: +
5784: +// TestCaptureChainsSegmentsWithoutDuplicatesOrGaps runs captures longer than one segment: every
5785: +// tick must appear exactly once per interface, across every switch.
5786: +func TestCaptureChainsSegmentsWithoutDuplicatesOrGaps(t *testing.T) {
5787: +	t.Parallel()
5788: +
5789: +	r, clabwire := captureTestRuntime(t, 4*time.Millisecond)
5790: +	r.captureSegment = 300 * time.Millisecond
5791: +
5792: +	var gaps []clablabruntime.CaptureGap
5793: +	var out bytes.Buffer
5794: +	err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
5795: +		Name: "lab1",
5796: +		Targets: []clablabruntime.CaptureTarget{
5797: +			{Node: "r1", Interface: "e1-1"},
5798: +			{Node: "r1", Interface: "e1-2"},
5799: +		},
5800: +		Duration: 1300 * time.Millisecond,
5801: +		OnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },
5802: +	}, &out)
5803: +	if err != nil {
5804: +		t.Fatal(err)
5805: +	}
5806: +	if len(gaps) != 0 {
5807: +		t.Fatalf("gaps = %+v", gaps)
5808: +	}
5809: +	if processes := len(clabwire.captureCommands()); processes < 4 {
5810: +		t.Fatalf("capture processes = %d, want a chain of at least 4 segments", processes)
5811: +	}
5812: +
5813: +	parsed := parseCapture(t, out.Bytes())
5814: +	if parsed.sections != 1 || len(parsed.interfaces) != 2 {
5815: +		t.Fatalf("sections = %d, interfaces = %v; want the follow-up headers dropped",
5816: +			parsed.sections, parsed.interfaces)
5817: +	}
5818: +	for id := range uint32(2) {
5819: +		var sequence []uint64
5820: +		for _, packet := range parsed.packets {
5821: +			if packet.InterfaceID == id {
5822: +				sequence = append(sequence, packetSequence(packet))
5823: +			}
5824: +		}
5825: +		if len(sequence) < 200 {
5826: +			t.Fatalf("interface %d has %d packets", id, len(sequence))
5827: +		}
5828: +		slices.Sort(sequence)
5829: +		for idx := 1; idx < len(sequence); idx++ {
5830: +			switch {
5831: +			case sequence[idx] == sequence[idx-1]:
5832: +				t.Fatalf("interface %d: tick %d written twice", id, sequence[idx])
5833: +			case sequence[idx] != sequence[idx-1]+1:
5834: +				t.Fatalf(
5835: +					"interface %d: ticks %d to %d missing",
5836: +					id,
5837: +					sequence[idx-1]+1,
5838: +					sequence[idx]-1,
5839: +				)
5840: +			}
5841: +		}
5842: +	}
5843: +}
5844: +
5845: +func TestCaptureReportsAGapWhenTheFollowUpStartsLate(t *testing.T) {
5846: +	t.Parallel()
5847: +
5848: +	r, clabwire := captureTestRuntime(t, 5*time.Millisecond)
5849: +	r.captureSegment = 300 * time.Millisecond
5850: +	// the second process starts long after the first one ended
5851: +	clabwire.startDelay[1] = 400 * time.Millisecond
5852: +
5853: +	var gaps []clablabruntime.CaptureGap
5854: +	var out bytes.Buffer
5855: +	err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
5856: +		Name:     "lab1",
5857: +		Targets:  []clablabruntime.CaptureTarget{{Node: "r2", Interface: "e1-1"}},
5858: +		Duration: 800 * time.Millisecond,
5859: +		OnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },
5860: +	}, &out)
5861: +	if err != nil {
5862: +		t.Fatal(err)
5863: +	}
5864: +	if len(gaps) == 0 || gaps[0].Node != "r2" ||
5865: +		!slices.Equal(gaps[0].Interfaces, []string{"e1-1"}) ||
5866: +		gaps[0].From.IsZero() ||
5867: +		gaps[0].Reason == "" {
5868: +		t.Fatalf("gaps = %+v, want the late follow-up reported", gaps)
5869: +	}
5870: +	if !gaps[0].To.IsZero() && !gaps[0].To.After(gaps[0].From) {
5871: +		t.Fatalf("gap ends before it starts: %+v", gaps[0])
5872: +	}
5873: +	parseCapture(t, out.Bytes())
5874: +}
5875: +
5876: +func TestCaptureMapsDeniedAndFailedAuditsToErrors(t *testing.T) {
5877: +	t.Parallel()
5878: +
5879: +	for _, status := range []string{captureAuditDenied, captureAuditFailed} {
5880: +		r, clabwire := captureTestRuntime(t, time.Millisecond)
5881: +		clabwire.fail = status
5882: +
5883: +		var out bytes.Buffer
5884: +		err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
5885: +			Name:     "lab1",
5886: +			Targets:  []clablabruntime.CaptureTarget{{Node: "r2", Interface: "e1-1"}},
5887: +			Duration: time.Second,
5888: +		}, &out)
5889: +		if err == nil || !strings.Contains(err.Error(), "is not uniquely planned") ||
5890: +			!strings.Contains(err.Error(), "node r2") {
5891: +			t.Fatalf("%s: error = %v, want the audit reason", status, err)
5892: +		}
5893: +		if status == captureAuditDenied && !strings.Contains(err.Error(), "was denied") {
5894: +			t.Fatalf("Denied error = %v", err)
5895: +		}
5896: +		// the header is written before the capture starts, so the output stays a valid file
5897: +		parseCapture(t, out.Bytes())
5898: +	}
5899: +}
5900: +
5901: +func TestCaptureAuditLineWriter(t *testing.T) {
5902: +	t.Parallel()
5903: +
5904: +	var audits []*captureAudit
5905: +	writer := &auditLineWriter{send: func(audit *captureAudit) { audits = append(audits, audit) }}
5906: +	started := fmt.Sprintf(`{"schemaVersion":%q,"time":"2026-10-27T10:00:00.123456789Z",`+
5907: +		`"status":"Started","nodeName":"r1","interfaces":[{"name":"e1-1","id":"if1"}]}`,
5908: +		captureAuditSchema)
5909: +	// lines arrive split across writes
5910: +	_, _ = writer.Write([]byte(started[:20]))
5911: +	_, _ = writer.Write([]byte(started[20:] + "\nnot json\n{\"status\":\"Started\"}\n"))
5912: +	_, _ = writer.Write(
5913: +		[]byte(`{"schemaVersion":"` + captureAuditSchema + `","status":"Succeeded","packets":3}`),
5914: +	)
5915: +	writer.flush()
5916: +
5917: +	if len(audits) != 2 || audits[0].Status != captureAuditStarted || audits[1].Packets != 3 ||
5918: +		audits[0].Time.Nanosecond() != 123456789 || audits[0].Interfaces[0].Name != "e1-1" {
5919: +		t.Fatalf("audits = %+v", audits)
5920: +	}
5921: +	if writer.text() != `not json; {"status":"Started"}` {
5922: +		t.Fatalf("other stderr = %q", writer.text())
5923: +	}
5924: +
5925: +	err := captureAuditError("r1", &captureAudit{
5926: +		Status: captureAuditDenied, Reason: "nope",
5927: +		Interfaces: []struct {
5928: +			Name    string `json:"name"`
5929: +			ID      string `json:"id"`
5930: +			Packets int    `json:"packets"`
5931: +		}{{Name: "e1-1"}, {Name: "eth0"}},
5932: +	})
5933: +	if err.Error() != "capture of e1-1,eth0 on node r1 was denied by clabwire: nope" {
5934: +		t.Fatalf("audit error = %q", err)
5935: +	}
5936: +}
5937: +
5938: +func TestCaptureStopsAtThePacketLimit(t *testing.T) {
5939: +	t.Parallel()
5940: +
5941: +	r, clabwire := captureTestRuntime(t, 2*time.Millisecond)
5942: +	var out bytes.Buffer
5943: +	err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
5944: +		Name: "lab1",
5945: +		Targets: []clablabruntime.CaptureTarget{
5946: +			{Node: "r1", Interface: "e1-1"},
5947: +			{Node: "r2", Interface: "e1-1"},
5948: +		},
5949: +		PacketLimit: 7,
5950: +	}, &out)
5951: +	if err != nil {
5952: +		t.Fatal(err)
5953: +	}
5954: +	if got := len(parseCapture(t, out.Bytes()).packets); got != 7 {
5955: +		t.Fatalf("packets = %d, want 7", got)
5956: +	}
5957: +	// each clabwire process gets the limit that remained when it started
5958: +	for _, command := range clabwire.captureCommands() {
5959: +		limit := flagValues(command, "--packetLimit")
5960: +		if len(limit) != 1 || limit[0] < "1" || limit[0] > "7" || len(limit[0]) != 1 {
5961: +			t.Fatalf("clabwire packet limit = %v, want at most 7", limit)
5962: +		}
5963: +	}
5964: +}
5965: +
5966: +func TestCaptureEndsCleanlyWhenTheContextEnds(t *testing.T) {
5967: +	t.Parallel()
5968: +
5969: +	r, _ := captureTestRuntime(t, 2*time.Millisecond)
5970: +	ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
5971: +	defer cancel()
5972: +
5973: +	var out bytes.Buffer
5974: +	if err := r.Capture(ctx, clablabruntime.CaptureRequest{
5975: +		Name:    "lab1",
5976: +		Targets: []clablabruntime.CaptureTarget{{Node: "r1", Interface: "e1-1"}},
5977: +	}, &out); err != nil {
5978: +		t.Fatalf("Capture() after the context ended = %v, want nil", err)
5979: +	}
5980: +	if len(parseCapture(t, out.Bytes()).packets) == 0 {
5981: +		t.Fatal("no packets before the context ended")
5982: +	}
5983: +}
5984: +
5985: +func TestCaptureValidatesTargets(t *testing.T) {
5986: +	t.Parallel()
5987: +
5988: +	r, clabwire := captureTestRuntime(t, time.Millisecond)
5989: +	ctx := context.Background()
5990: +	cases := map[string]clablabruntime.CaptureRequest{
5991: +		"is not a capturable link interface; capturable: e1-1 (ethernet-1/1), e1-2": {
5992: +			Targets: []clablabruntime.CaptureTarget{{Node: "r1", Interface: "eth0"}},
5993: +		},
5994: +		"requested more than once": {
5995: +			Targets: []clablabruntime.CaptureTarget{
5996: +				{Node: "r1", Interface: "e1-1"}, {Node: "R1", Interface: "ethernet-1/1"},
5997: +			},
5998: +		},
5999: +		`node "missing" was not found`: {
6000: +			Targets: []clablabruntime.CaptureTarget{{Node: "missing", Interface: "e1-1"}},
6001: +		},
6002: +		"at least one capture target": {},
6003: +		"snap length 10 is outside": {
6004: +			Targets:    []clablabruntime.CaptureTarget{{Node: "r1", Interface: "e1-1"}},
6005: +			SnapLength: 10,
6006: +		},
6007: +		"duration must not be negative": {
6008: +			Targets:  []clablabruntime.CaptureTarget{{Node: "r1", Interface: "e1-1"}},
6009: +			Duration: -time.Second,
6010: +		},
6011: +	}
6012: +	for want, req := range cases {
6013: +		req.Name = "lab1"
6014: +		err := r.Capture(ctx, req, io.Discard)
6015: +		if err == nil || !strings.Contains(err.Error(), want) {
6016: +			t.Errorf("error = %v, want %q", err, want)
6017: +		}
6018: +	}
6019: +	if commands := clabwire.captureCommands(); len(commands) != 0 {
6020: +		t.Fatalf("invalid requests started captures: %v", commands)
6021: +	}
6022: +}
6023: +
6024: +func TestInspectInterfacesReportsStateFromSysfs(t *testing.T) {
6025: +	t.Parallel()
6026: +
6027: +	r, clabwire := captureTestRuntime(t, time.Millisecond)
6028: +	clabwire.sysfs = "Inter-|   Receive\n face |bytes\n" + interfaceSysfsMarker + "\n" +
6029: +		"e1-1\t12\t9500\taa:c1:ab:00:00:01\tup\t0x1003\t\n" +
6030: +		"e1-2\t13\t1500\taa:c1:ab:00:00:02\tlowerlayerdown\t0x1003\t\n"
6031: +
6032: +	interfaces, err := r.InspectInterfaces(context.Background(), clablabruntime.NodeRequest{
6033: +		Name: "lab1", Nodes: []string{"R1"},
6034: +	})
6035: +	if err != nil {
6036: +		t.Fatal(err)
6037: +	}
6038: +	if len(interfaces) != 1 || interfaces[0].ContainerName != "lab1-r1" ||
6039: +		len(interfaces[0].Interfaces) != 2 {
6040: +		t.Fatalf("interfaces = %+v", interfaces)
6041: +	}
6042: +	first := interfaces[0].Interfaces[0]
6043: +	if first.InterfaceName != "e1-1" || first.InterfaceAlias != "ethernet-1/1" ||
6044: +		first.InterfaceMAC != "aa:c1:ab:00:00:01" || first.InterfaceIndex != 12 ||
6045: +		first.InterfaceMTU != 9500 || first.InterfaceState != "up" {
6046: +		t.Fatalf("e1-1 = %+v", first)
6047: +	}
6048: +	if second := interfaces[0].Interfaces[1]; second.InterfaceState != "lowerlayerdown" {
6049: +		t.Fatalf("e1-2 = %+v", second)
6050: +	}
6051: +}
6052: +
6053: +// TestCaptureClosesStdinWhenItEnds ends every clabwire process through its stdin, whether the
6054: +// caller cancels the capture or the output fails, so no capture is left running in the pod.
6055: +// TestCaptureWritesWhatItReadWhenTheContextEnds stops a capture while the output is slow and
6056: +// the chains have packets queued: every packet clabwire wrote before it ended is in the file.
6057: +func TestCaptureWritesWhatItReadWhenTheContextEnds(t *testing.T) {
6058: +	t.Parallel()
6059: +
6060: +	r, clabwire := captureTestRuntime(t, time.Millisecond)
6061: +	// without a reorder window, a blocked output blocks the chains
6062: +	r.captureReorderWindow = -1
6063: +	ctx, cancel := context.WithCancel(context.Background())
6064: +	defer cancel()
6065: +
6066: +	out := &gatedWriter{open: make(chan struct{})}
6067: +	go func() {
6068: +		time.Sleep(50 * time.Millisecond)
6069: +		out.block()
6070: +		// the segments keep reading while the chains wait for the output
6071: +		time.Sleep(400 * time.Millisecond)
6072: +		cancel()
6073: +		close(out.open)
6074: +	}()
6075: +
6076: +	if err := r.Capture(ctx, clablabruntime.CaptureRequest{
6077: +		Name: "lab1",
6078: +		Targets: []clablabruntime.CaptureTarget{
6079: +			{Node: "r1", Interface: "e1-1"},
6080: +			{Node: "r2", Interface: "e1-1"},
6081: +		},
6082: +	}, out); err != nil {
6083: +		t.Fatal(err)
6084: +	}
6085: +
6086: +	parsed := parseCapture(t, out.bytes())
6087: +	got := map[string]int{}
6088: +	for _, packet := range parsed.packets {
6089: +		node, _, _ := strings.Cut(packetOrigin(packet), ":")
6090: +		got[node]++
6091: +	}
6092: +	clabwire.mu.Lock()
6093: +	defer clabwire.mu.Unlock()
6094: +	for _, node := range []string{"r1", "r2"} {
6095: +		if clabwire.written[node] < 300 || got[node] != clabwire.written[node] {
6096: +			t.Fatalf("%s: clabwire wrote %d packets, the capture has %d", node,
6097: +				clabwire.written[node], got[node])
6098: +		}
6099: +	}
6100: +}
6101: +
6102: +// gatedWriter collects writes; once blocked, writes wait until open is closed.
6103: +type gatedWriter struct {
6104: +	open chan struct{}
6105: +
6106: +	mu      sync.Mutex
6107: +	blocked bool
6108: +	data    bytes.Buffer
6109: +}
6110: +
6111: +func (w *gatedWriter) block() {
6112: +	w.mu.Lock()
6113: +	w.blocked = true
6114: +	w.mu.Unlock()
6115: +}
6116: +
6117: +func (w *gatedWriter) Write(data []byte) (int, error) {
6118: +	w.mu.Lock()
6119: +	blocked := w.blocked
6120: +	w.mu.Unlock()
6121: +	if blocked {
6122: +		<-w.open
6123: +	}
6124: +	w.mu.Lock()
6125: +	defer w.mu.Unlock()
6126: +
6127: +	return w.data.Write(data)
6128: +}
6129: +
6130: +func (w *gatedWriter) bytes() []byte {
6131: +	w.mu.Lock()
6132: +	defer w.mu.Unlock()
6133: +
6134: +	return w.data.Bytes()
6135: +}
6136: +
6137: +func TestCaptureClosesStdinWhenItEnds(t *testing.T) {
6138: +	t.Parallel()
6139: +
6140: +	targets := []clablabruntime.CaptureTarget{
6141: +		{Node: "r1", Interface: "e1-1"},
6142: +		{Node: "r2", Interface: "e1-1"},
6143: +	}
6144: +
6145: +	t.Run("cancel", func(t *testing.T) {
6146: +		t.Parallel()
6147: +
6148: +		r, clabwire := captureTestRuntime(t, 2*time.Millisecond)
6149: +		ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
6150: +		defer cancel()
6151: +
6152: +		if err := r.Capture(ctx, clablabruntime.CaptureRequest{Name: "lab1", Targets: targets},
6153: +			io.Discard); err != nil {
6154: +			t.Fatal(err)
6155: +		}
6156: +		requireStdinClosedEverywhere(t, clabwire)
6157: +	})
6158: +
6159: +	t.Run("output fails", func(t *testing.T) {
6160: +		t.Parallel()
6161: +
6162: +		r, clabwire := captureTestRuntime(t, 2*time.Millisecond)
6163: +		output := &failingWriter{accept: 3}
6164: +		err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
6165: +			Name: "lab1", Targets: targets, Duration: time.Hour,
6166: +		}, output)
6167: +		if err == nil || !strings.Contains(err.Error(), "broken pipe") {
6168: +			t.Fatalf("Capture() = %v, want the write error", err)
6169: +		}
6170: +		requireStdinClosedEverywhere(t, clabwire)
6171: +	})
6172: +}
6173: +
6174: +// failingWriter accepts some writes, then fails like a closed pipe.
6175: +type failingWriter struct {
6176: +	mu     sync.Mutex
6177: +	accept int
6178: +}
6179: +
6180: +func (w *failingWriter) Write(data []byte) (int, error) {
6181: +	w.mu.Lock()
6182: +	defer w.mu.Unlock()
6183: +	if w.accept == 0 {
6184: +		return 0, errors.New("write |1: broken pipe")
6185: +	}
6186: +	w.accept--
6187: +
6188: +	return len(data), nil
6189: +}
6190: +
6191: +func requireStdinClosedEverywhere(t *testing.T, clabwire *fakeClabwire) {
6192: +	t.Helper()
6193: +
6194: +	clabwire.mu.Lock()
6195: +	defer clabwire.mu.Unlock()
6196: +	for _, node := range []string{"r1", "r2"} {
6197: +		if clabwire.processes[node] == 0 || clabwire.stdinClosed[node] != clabwire.processes[node] {
6198: +			t.Fatalf("%s: %d processes, %d ended through stdin", node,
6199: +				clabwire.processes[node], clabwire.stdinClosed[node])
6200: +		}
6201: +	}
6202: +}
6203: +
6204: +// TestCaptureRejectsAClabwireWithoutStopOnStdinClose turns the usage error of an older clabwire
6205: +// into the release error.
6206: +func TestCaptureRejectsAClabwireWithoutStopOnStdinClose(t *testing.T) {
6207: +	t.Parallel()
6208: +
6209: +	r, clabwire := captureTestRuntime(t, time.Millisecond)
6210: +	clabwire.stderrOnly = "flag provided but not defined: -stop-on-stdin-close"
6211: +
6212: +	err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
6213: +		Name: "lab1", Targets: []clablabruntime.CaptureTarget{{Node: "r2", Interface: "e1-1"}},
6214: +		Duration: time.Second,
6215: +	}, io.Discard)
6216: +	if !errors.Is(err, clablabruntime.ErrUnsupportedRuntimeVersion) ||
6217: +		!strings.Contains(err.Error(), "clabwire in pod lab-ns/lab1-r2-def does not accept "+
6218: +			"packet-capture --stop-on-stdin-close") ||
6219: +		!strings.Contains(err.Error(), "(0.11 or newer)") {
6220: +		t.Fatalf("Capture() = %v, want the release error", err)
6221: +	}
6222: +}
6223: +
6224: +// requireTimeOrdered checks that the merged stream's timestamps never decrease.
6225: +func requireTimeOrdered(t *testing.T, packets []clabcapture.Packet) {
6226: +	t.Helper()
6227: +
6228: +	for idx := 1; idx < len(packets); idx++ {
6229: +		if packets[idx].Timestamp < packets[idx-1].Timestamp {
6230: +			t.Fatalf("packet %d (%s) at %d precedes packet %d (%s) at %d", idx,
6231: +				packetOrigin(packets[idx]), packets[idx].Timestamp, idx-1,
6232: +				packetOrigin(packets[idx-1]), packets[idx-1].Timestamp)
6233: +		}
6234: +	}
6235: +}
6236: +
6237: +// TestCaptureMergesNodesInTimestampOrder merges two nodes whose streams arrive with different
6238: +// delays: r2's packets are stamped 60 ms before they reach containerlab. The reorder window puts
6239: +// them in order; without it they are not.
6240: +func TestCaptureMergesNodesInTimestampOrder(t *testing.T) {
6241: +	t.Parallel()
6242: +
6243: +	for _, reorder := range []bool{true, false} {
6244: +		t.Run(fmt.Sprintf("reorder=%v", reorder), func(t *testing.T) {
6245: +			t.Parallel()
6246: +
6247: +			r, clabwire := captureTestRuntime(t, 5*time.Millisecond)
6248: +			clabwire.stampSkew["r2"] = 60 * time.Millisecond
6249: +			if !reorder {
6250: +				r.captureReorderWindow = -1
6251: +			}
6252: +
6253: +			var out bytes.Buffer
6254: +			err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
6255: +				Name: "lab1",
6256: +				Targets: []clablabruntime.CaptureTarget{
6257: +					{Node: "r1", Interface: "e1-1"},
6258: +					{Node: "r2", Interface: "e1-1"},
6259: +				},
6260: +				Duration: 500 * time.Millisecond,
6261: +			}, &out)
6262: +			if err != nil {
6263: +				t.Fatal(err)
6264: +			}
6265: +
6266: +			packets := parseCapture(t, out.Bytes()).packets
6267: +			ordered := slices.IsSortedFunc(packets, func(a, b clabcapture.Packet) int {
6268: +				return int(a.Timestamp - b.Timestamp)
6269: +			})
6270: +			if reorder {
6271: +				requireTimeOrdered(t, packets)
6272: +			} else if ordered {
6273: +				t.Fatal("the skewed streams came out ordered without the reorder window")
6274: +			}
6275: +		})
6276: +	}
6277: +}
6278: +
6279: +// TestCaptureChainsSeveralNodesInOrderWithoutDuplicates chains two nodes with skewed streams and a
6280: +// reorder window shorter than a segment switch:
6281: +// every tick appears exactly once per interface and the merged stream stays in timestamp order
6282: +// across every segment switch, while old segments are ended through stdin at the switch.
6283: +func TestCaptureChainsSeveralNodesInOrderWithoutDuplicates(t *testing.T) {
6284: +	t.Parallel()
6285: +
6286: +	r, clabwire := captureTestRuntime(t, 4*time.Millisecond)
6287: +	r.captureSegment = 300 * time.Millisecond
6288: +	// a window shorter than a switch: the chains' holds keep the order across the switches
6289: +	r.captureReorderWindow = 15 * time.Millisecond
6290: +	clabwire.stampSkew["r2"] = 5 * time.Millisecond
6291: +	// r2 switches segments 120 ms after r1, so one chain streams live while the other holds
6292: +	clabwire.firstStartDelay["r2"] = 120 * time.Millisecond
6293: +
6294: +	var gaps []clablabruntime.CaptureGap
6295: +	var out bytes.Buffer
6296: +	err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
6297: +		Name: "lab1",
6298: +		Targets: []clablabruntime.CaptureTarget{
6299: +			{Node: "r1", Interface: "e1-1"},
6300: +			{Node: "r2", Interface: "e1-1"},
6301: +		},
6302: +		Duration: 1300 * time.Millisecond,
6303: +		OnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },
6304: +	}, &out)
6305: +	if err != nil {
6306: +		t.Fatal(err)
6307: +	}
6308: +	if len(gaps) != 0 {
6309: +		t.Fatalf("gaps = %+v", gaps)
6310: +	}
6311: +
6312: +	parsed := parseCapture(t, out.Bytes())
6313: +	requireTimeOrdered(t, parsed.packets)
6314: +	for id := range uint32(2) {
6315: +		var sequence []uint64
6316: +		for _, packet := range parsed.packets {
6317: +			if packet.InterfaceID == id {
6318: +				sequence = append(sequence, packetSequence(packet))
6319: +			}
6320: +		}
6321: +		slices.Sort(sequence)
6322: +		if len(sequence) < 200 {
6323: +			t.Fatalf("interface %d has %d packets", id, len(sequence))
6324: +		}
6325: +		for idx := 1; idx < len(sequence); idx++ {
6326: +			if sequence[idx] != sequence[idx-1]+1 {
6327: +				t.Fatalf("interface %d: tick %d followed by %d", id, sequence[idx-1], sequence[idx])
6328: +			}
6329: +		}
6330: +	}
6331: +
6332: +	clabwire.mu.Lock()
6333: +	defer clabwire.mu.Unlock()
6334: +	for _, node := range []string{"r1", "r2"} {
6335: +		if clabwire.processes[node] < 4 || clabwire.stdinClosed[node] == 0 {
6336: +			t.Fatalf("%s: %d processes, %d stopped through stdin at a switch", node,
6337: +				clabwire.processes[node], clabwire.stdinClosed[node])
6338: +		}
6339: +	}
6340: +}
6341: +
6342: +func TestCaptureReorderWindowKnob(t *testing.T) {
6343: +	cases := map[string]time.Duration{
6344: +		"":      250 * time.Millisecond,
6345: +		"0":     0,
6346: +		"75ms":  75 * time.Millisecond,
6347: +		"bogus": 250 * time.Millisecond,
6348: +	}
6349: +	for value, want := range cases {
6350: +		t.Setenv(envCaptureReorderWindow, value)
6351: +		r := &Runtime{captureReorderWindow: captureReorderWindowFromEnv()}
6352: +		if got := r.captureReorderWindowLength(); got != want {
6353: +			t.Errorf("%s=%q: window %s, want %s", envCaptureReorderWindow, value, got, want)
6354: +		}
6355: +	}
6356: +}
6357: diff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go
6358: index 3c556e7..e869191 100644
6359: --- a/labruntime/clabernetes/clabernetes.go
6360: +++ b/labruntime/clabernetes/clabernetes.go
6361: @@ -84,10 +84,18 @@ type Runtime struct {
6362:  	// identity is the configured identity of calls without one; in a connected view it is the
6363:  	// identity the clients impersonate.
6364:  	identity clablabruntime.Identity
6365:  	// pollInterval overrides how often waits poll the cluster (tests).
6366:  	pollInterval time.Duration
6367: +	// podExec overrides how commands run in pod containers (tests).
6368: +	podExec podExecFunc
6369: +	// captureSegment is the length of one chained packet capture; zero uses the clabwire
6370: +	// maximum of one hour.
6371: +	captureSegment time.Duration
6372: +	// captureReorderWindow is how long the merged capture stream holds packets back to write
6373: +	// them in timestamp order: zero uses the default, a negative value disables reordering.
6374: +	captureReorderWindow time.Duration
6375:  	// support checks once per runtime instance, before the first cluster call, that the
6376:  	// cluster runs a clabernetes release with the contract this runtime needs. Every view
6377:  	// shares it. It is nil when the clients were injected (tests).
6378:  	support *supportCheck
6379:  }
6380: @@ -253,7 +261,9 @@ func New(cfg clablabruntime.Config) (clablabruntime.LabRuntime, error) {
6381:  		timeout:              cfg.Timeout,
6382:  		kindLinkApplyMode:    cfg.KindLinkApplyMode,
6383:  		identity:             cfg.Identity,
6384:  		clients:              newClientLoader(),
6385:  		support:              &supportCheck{},
6386: +		captureSegment:       captureSegmentFromEnv(),
6387: +		captureReorderWindow: captureReorderWindowFromEnv(),
6388:  	}, nil
6389:  }
6390: diff --git a/labruntime/runtime.go b/labruntime/runtime.go
6391: index 76e651c..367565d 100644
6392: --- a/labruntime/runtime.go
6393: +++ b/labruntime/runtime.go
6394: @@ -387,10 +387,80 @@ type NodeLogStreamer interface {
6395:  // exactly one node. Closing the connection closes the stream.
6396:  type NodePortForwarder interface {
6397:  	DialPort(ctx context.Context, req NodeRequest, port int) (net.Conn, error)
6398:  }
6399:  
6400: +// CaptureInterface is a lab link interface packet capture accepts, with the far end of its link.
6401: +type CaptureInterface struct {
6402: +	// Node is the node name as the topology spells it.
6403: +	Node string `json:"node"`
6404: +	// Interface is the interface name inside the node, which capture output carries.
6405: +	Interface string `json:"interface"`
6406: +	// Alias is the name the topology used for the interface when the node kind maps it (for
6407: +	// example ethernet-1/1 for SR Linux e1-1). Capture targets accept either name.
6408: +	Alias string `json:"alias,omitempty"`
6409: +	// PeerNode is the node at the other end of the link, "host" for a host endpoint, or empty

(Output capped at 50 KB. Showing lines 4780-6409. Use offset=6410 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19650be59001Q0jP5lrZrsobav",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650b315001ndmMoYOP5TaOov",
  "callID": "call_ed625a13bc8c48cbab77c4cd",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "offset": 4780
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n4780: +\tmore, err := c.capture.emit(c.group.ids[packet.InterfaceID], packet)\n4781: +\n4782: +\treturn !more, err\n4783: +}\n4784: +\n4785: +// switchSegments makes the next segment the active one after the active one ended, writing the\n4786: +// held packets of the next one that the active one did not write.\n4787: +func (c *captureChain) switchSegments(ctx context.Context, timer *time.Timer) (bool, error) {\n4788: +\t// the held packets are in the reorder buffer once this returns\n4789: +\tdefer c.capture.out.Release(c)\n4790: +\n4791: +\tended := c.active\n4792: +\tif c.stopping && c.next != nil && c.next.started.IsZero() {\n4793: +\t\t// the chain is stopping: a follow-up that has not started takes nothing over\n4794: +\t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n4795: +\t}\n4796: +\tif c.final && c.next == nil {\n4797: +\t\treturn true, nil\n4798: +\t}\n4799: +\n4800: +\tif c.next == nil || c.next.started.IsZero() || c.cut == 0 {\n4801: +\t\tfrom := ended.ended\n4802: +\t\tif from.IsZero() {\n4803: +\t\t\tfrom = ended.plannedEnd()\n4804: +\t\t}\n4805: +\t\tgap := clablabruntime.CaptureGap{\n4806: +\t\t\tNode: c.group.display, Interfaces: c.group.interfaces, From: from,\n4807: +\t\t\tReason: \"the follow-up capture did not overlap the previous one\",\n4808: +\t\t}\n4809: +\t\tif c.next != nil && !c.next.started.IsZero() {\n4810: +\t\t\tgap.To = c.next.started\n4811: +\t\t}\n4812: +\t\tc.capture.reportGap(gap)\n4813: +\t}\n4814: +\n4815: +\tif c.next != nil && c.next.done && !c.stopping {\n4816: +\t\t// the follow-up already ended (it started too late to take over): keep what it\n4817: +\t\t// captured and continue with a fresh segment\n4818: +\t\tfor _, packet := range c.held {\n4819: +\t\t\tif stop, err := c.emit(packet); stop || err != nil {\n4820: +\t\t\t\treturn true, err\n4821: +\t\t\t}\n4822: +\t\t}\n4823: +\t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n4824: +\t}\n4825: +\n4826: +\tif c.next == nil {\n4827: +\t\tif !c.capture.deadline.IsZero() &&\n4828: +\t\t\t!time.Now().Before(c.capture.deadline.Add(-c.capture.window)) {\n4829: +\t\t\treturn true, nil\n4830: +\t\t}\n4831: +\t\tc.active = c.start(ctx, c.segmentDuration(time.Now()))\n4832: +\t\tresetTimer(timer, c.nextStartIn())\n4833: +\n4834: +\t\treturn false, nil\n4835: +\t}\n4836: +\n4837: +\twindow := c.capture.window.Nanoseconds()\n4838: +\tfor _, packet := range c.held {\n4839: +\t\tif c.cut != 0 {\n4840: +\t\t\tif packet.Timestamp < c.cut-window {\n4841: +\t\t\t\tcontinue\n4842: +\t\t\t}\n4843: +\t\t\tif packet.Timestamp < c.cut+window {\n4844: +\t\t\t\tkey := packetKey(packet)\n4845: +\t\t\t\tif c.emitted[key] > 0 {\n4846: +\t\t\t\t\tc.emitted[key]--\n4847: +\t\t\t\t\tcontinue\n4848: +\t\t\t\t}\n4849: +\t\t\t}\n4850: +\t\t}\n4851: +\t\tif stop, err := c.emit(packet); stop || err != nil {\n4852: +\t\t\treturn true, err\n4853: +\t\t}\n4854: +\t}\n4855: +\n4856: +\tc.active, c.next = c.next, nil\n4857: +\tc.held, c.emitted, c.cut = nil, nil, 0\n4858: +\tif c.active.done {\n4859: +\t\t// the chain is stopping and the follow-up ended before the active one\n4860: +\t\treturn true, nil\n4861: +\t}\n4862: +\tresetTimer(timer, c.nextStartIn())\n4863: +\n4864: +\treturn false, nil\n4865: +}\n4866: +\n4867: +func resetTimer(timer *time.Timer, d time.Duration) {\n4868: +\tif !timer.Stop() {\n4869: +\t\tselect {\n4870: +\t\tcase <-timer.C:\n4871: +\t\tdefault:\n4872: +\t\t}\n4873: +\t}\n4874: +\ttimer.Reset(d)\n4875: +}\n4876: +\n4877: +// packetKey identifies a packet by its interface and content.\n4878: +func packetKey(packet *clabcapture.Packet) uint64 {\n4879: +\thash := fnv.New64a()\n4880: +\tvar id [4]byte\n4881: +\tid[0] = byte(packet.InterfaceID)\n4882: +\tid[1] = byte(packet.InterfaceID >> 8)\n4883: +\t_, _ = hash.Write(id[:])\n4884: +\t_, _ = hash.Write(packet.Data)\n4885: +\n4886: +\treturn hash.Sum64()\n4887: +}\n4888: +\n4889: +// start runs one clabwire capture and reports its packets, audit records and end as events.\n4890: +func (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {\n4891: +\tsegmentCtx, cancel := context.WithCancel(ctx)\n4892: +\tstdinReader, stdinWriter := io.Pipe()\n4893: +\tsegment := &captureSegment{\n4894: +\t\tindex: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,\n4895: +\t\tcloseStdin: func() { _ = stdinWriter.Close() },\n4896: +\t}\n4897: +\tc.segments++\n4898: +\n4899: +\tcommand := []string{\n4900: +\t\tclabwireManager, \"node-runtime\", \"packet-capture\",\n4901: +\t\t\"--nodeName\", c.group.location.NodeName,\n4902: +\t\t\"--format\", \"pcapng\",\n4903: +\t\t\"--snapLength\", strconv.Itoa(c.capture.req.SnapLength),\n4904: +\t\t\"--duration\", duration.String(),\n4905: +\t\tclabwireStopOnStdinClose,\n4906: +\t}\n4907: +\tfor _, name := range c.group.interfaces {\n4908: +\t\tcommand = append(command, \"--interface\", name)\n4909: +\t}\n4910: +\tif c.capture.req.PacketLimit > 0 {\n4911: +\t\tremaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()\n4912: +\t\tcommand = append(command, \"--packetLimit\",\n4913: +\t\t\tstrconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))\n4914: +\t}\n4915: +\n4916: +\tsend := func(event segmentEvent) {\n4917: +\t\tevent.segment = segment\n4918: +\t\tselect {\n4919: +\t\tcase c.events <- event:\n4920: +\t\tcase <-segmentCtx.Done():\n4921: +\t\t}\n4922: +\t}\n4923: +\n4924: +\tstdoutReader, stdoutWriter := io.Pipe()\n4925: +\tstderr := &auditLineWriter{send: func(audit *captureAudit) { send(segmentEvent{audit: audit}) }}\n4926: +\n4927: +\t// The exec outlives the segment's context by up to captureStdinCloseGrace: when the segment\n4928: +\t// ends for any reason (the capture is cancelled or failed, the output failed, or a newer\n4929: +\t// segment took over), its stdin is closed first so clabwire ends on its own, and the stream\n4930: +\t// is cut only if it does not.\n4931: +\texecCtx, cancelExec := context.WithCancel(context.WithoutCancel(segmentCtx))\n4932: +\texecDone := make(chan struct{})\n4933: +\n4934: +\tc.wg.Add(3)\n4935: +\treadDone := make(chan error, 1)\n4936: +\tgo func() {\n4937: +\t\tdefer c.wg.Done()\n4938: +\t\treadDone <- c.readSegment(stdoutReader, func(packet *clabcapture.Packet) {\n4939: +\t\t\tsend(segmentEvent{packet: packet})\n4940: +\t\t})\n4941: +\t\t_, _ = io.Copy(io.Discard, stdoutReader)\n4942: +\t}()\n4943: +\tgo func() {\n4944: +\t\tdefer c.wg.Done()\n4945: +\t\tselect {\n4946: +\t\tcase <-execDone:\n4947: +\t\t\treturn\n4948: +\t\tcase <-segmentCtx.Done():\n4949: +\t\t}\n4950: +\t\tsegment.closeStdin()\n4951: +\t\tgrace := time.NewTimer(captureStdinCloseGrace)\n4952: +\t\tdefer grace.Stop()\n4953: +\t\tselect {\n4954: +\t\tcase <-execDone:\n4955: +\t\tcase <-grace.C:\n4956: +\t\t\tlog.Debug(\"Capture segment did not end after its stdin closed, cutting the stream\",\n4957: +\t\t\t\t\"node\", c.group.display, \"segment\", segment.index)\n4958: +\t\t\tcancelExec()\n4959: +\t\t}\n4960: +\t}()\n4961: +\tgo func() {\n4962: +\t\tdefer c.wg.Done()\n4963: +\t\tdefer cancel()\n4964: +\t\tdefer cancelExec()\n4965: +\n4966: +\t\terr := c.capture.r.execInPodContainer()(execCtx, c.group.location.Namespace,\n4967: +\t\t\tc.group.location.Pod, clabwireContainer, command, stdinReader, stdoutWriter, stderr)\n4968: +\t\tclose(execDone)\n4969: +\t\t// the process ended: release the stdin copy of the exec stream\n4970: +\t\tsegment.closeStdin()\n4971: +\t\t_ = stdoutWriter.Close()\n4972: +\t\treadErr := <-readDone\n4973: +\t\tstderr.flush()\n4974: +\t\tif err == nil && readErr != nil {\n4975: +\t\t\terr = readErr\n4976: +\t\t}\n4977: +\t\tif err != nil && stderr.text() != \"\" {\n4978: +\t\t\tif unsupported := unsupportedClabwire(\n4979: +\t\t\t\tc.group.location,\n4980: +\t\t\t\tstderr.text(),\n4981: +\t\t\t); unsupported != nil {\n4982: +\t\t\t\terr = unsupported\n4983: +\t\t\t} else {\n4984: +\t\t\t\terr = fmt.Errorf(\"%w: %s\", err, stderr.text())\n4985: +\t\t\t}\n4986: +\t\t}\n4987: +\t\tsend(segmentEvent{done: true, err: err})\n4988: +\t}()\n4989: +\n4990: +\treturn segment\n4991: +}\n4992: +\n4993: +// unsupportedClabwire recognizes a clabwire that rejects --stop-on-stdin-close, which every\n4994: +// capture passes: its release predates the capture contract the runtime needs.\n4995: +func unsupportedClabwire(location clablabruntime.NodeLocation, stderr string) error {\n4996: +\tif !strings.Contains(stderr, \"flag provided but not defined\") ||\n4997: +\t\t!strings.Contains(stderr, strings.TrimPrefix(clabwireStopOnStdinClose, \"-\")) {\n4998: +\t\treturn nil\n4999: +\t}\n5000: +\n5001: +\treturn &unsupportedClabernetesError{reason: fmt.Sprintf(\n5002: +\t\t\"clabwire in pod %s/%s does not accept packet-capture %s\",\n5003: +\t\tlocation.Namespace, location.Pod, clabwireStopOnStdinClose)}\n5004: +}\n5005: +\n5006: +// readSegment checks that a segment's interfaces are the requested ones and passes its packets\n5007: +// on with the segment's interface index.\n5008: +func (c *captureChain) readSegment(stdout io.Reader, packet func(*clabcapture.Packet)) error {\n5009: +\treader := clabcapture.NewReader(stdout)\n5010: +\tinterfaces := 0\n5011: +\tfor {\n5012: +\t\tevent, err := reader.Next()\n5013: +\t\tif errors.Is(err, io.EOF) {\n5014: +\t\t\treturn nil\n5015: +\t\t}\n5016: +\t\tif errors.Is(err, io.ErrUnexpectedEOF) {\n5017: +\t\t\t// the process was stopped inside a block\n5018: +\t\t\treturn nil\n5019: +\t\t}\n5020: +\t\tif err != nil {\n5021: +\t\t\treturn fmt.Errorf(\"failed to read the clabwire capture: %w\", err)\n5022: +\t\t}\n5023: +\t\tif event.Interface != nil {\n5024: +\t\t\tif interfaces >= len(c.group.interfaces) ||\n5025: +\t\t\t\tevent.Interface.Name != c.group.interfaces[interfaces] {\n5026: +\t\t\t\treturn fmt.Errorf(\"clabwire described interface %q, want %s in order\",\n5027: +\t\t\t\t\tevent.Interface.Name, strings.Join(c.group.interfaces, \", \"))\n5028: +\t\t\t}\n5029: +\t\t\tinterfaces++\n5030: +\t\t\tcontinue\n5031: +\t\t}\n5032: +\t\tif event.Packet != nil {\n5033: +\t\t\tpacket(event.Packet)\n5034: +\t\t}\n5035: +\t}\n5036: +}\n5037: +\n5038: +// auditLineWriter parses clabwire's stderr: audit records go to send, other lines are kept for\n5039: +// error messages.\n5040: +type auditLineWriter struct {\n5041: +\tsend func(*captureAudit)\n5042: +\n5043: +\tmu      sync.Mutex\n5044: +\tpartial []byte\n5045: +\tother   []string\n5046: +}\n5047: +\n5048: +func (w *auditLineWriter) Write(data []byte) (int, error) {\n5049: +\tw.mu.Lock()\n5050: +\tw.partial = append(w.partial, data...)\n5051: +\tvar lines [][]byte\n5052: +\tfor {\n5053: +\t\tidx := bytes.IndexByte(w.partial, '\\n')\n5054: +\t\tif idx < 0 {\n5055: +\t\t\tbreak\n5056: +\t\t}\n5057: +\t\tlines = append(lines, append([]byte(nil), w.partial[:idx]...))\n5058: +\t\tw.partial = w.partial[idx+1:]\n5059: +\t}\n5060: +\tw.mu.Unlock()\n5061: +\n5062: +\tfor _, line := range lines {\n5063: +\t\tw.line(line)\n5064: +\t}\n5065: +\n5066: +\treturn len(data), nil\n5067: +}\n5068: +\n5069: +func (w *auditLineWriter) flush() {\n5070: +\tw.mu.Lock()\n5071: +\tline := w.partial\n5072: +\tw.partial = nil\n5073: +\tw.mu.Unlock()\n5074: +\tif len(bytes.TrimSpace(line)) != 0 {\n5075: +\t\tw.line(line)\n5076: +\t}\n5077: +}\n5078: +\n5079: +func (w *auditLineWriter) line(line []byte) {\n5080: +\tline = bytes.TrimSpace(line)\n5081: +\tif len(line) == 0 {\n5082: +\t\treturn\n5083: +\t}\n5084: +\n5085: +\tvar audit captureAudit\n5086: +\tif err := json.Unmarshal(\n5087: +\t\tline,\n5088: +\t\t&audit,\n5089: +\t); err == nil &&\n5090: +\t\taudit.SchemaVersion == captureAuditSchema {\n5091: +\t\tw.send(&audit)\n5092: +\t\treturn\n5093: +\t}\n5094: +\n5095: +\tw.mu.Lock()\n5096: +\tdefer w.mu.Unlock()\n5097: +\tif len(w.other) < 20 {\n5098: +\t\tw.other = append(w.other, string(line))\n5099: +\t}\n5100: +}\n5101: +\n5102: +func (w *auditLineWriter) text() string {\n5103: +\tw.mu.Lock()\n5104: +\tdefer w.mu.Unlock()\n5105: +\n5106: +\treturn strings.Join(w.other, \"; \")\n5107: +}\n5108: diff --git a/labruntime/clabernetes/capture_interfaces.go b/labruntime/clabernetes/capture_interfaces.go\n5109: new file mode 100644\n5110: index 0000000..21029ed\n5111: --- /dev/null\n5112: +++ b/labruntime/clabernetes/capture_interfaces.go\n5113: @@ -0,0 +1,187 @@\n5114: +package clabernetes\n5115: +\n5116: +import (\n5117: +\t\"bytes\"\n5118: +\t\"context\"\n5119: +\t\"errors\"\n5120: +\t\"fmt\"\n5121: +\t\"io\"\n5122: +\t\"sort\"\n5123: +\t\"sync\"\n5124: +\n5125: +\t\"github.com/charmbracelet/log\"\n5126: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n5127: +\tclabtypes \"github.com/srl-labs/containerlab/types\"\n5128: +\tcorev1 \"k8s.io/api/core/v1\"\n5129: +\t\"k8s.io/client-go/kubernetes/scheme\"\n5130: +\t\"k8s.io/client-go/tools/remotecommand\"\n5131: +\tkubeexec \"k8s.io/client-go/util/exec\"\n5132: +)\n5133: +\n5134: +// streamPodExec runs a command in a pod container without a terminal and streams its stdout\n5135: +// and stderr. A non-nil stdin is attached: when it ends, the process's stdin is closed (the\n5136: +// websocket v5 close signal, or a half-closed SPDY stream). A nonzero exit returns a\n5137: +// *labruntime.CommandExitError.\n5138: +func (r *Runtime) streamPodExec(\n5139: +\tctx context.Context,\n5140: +\tnamespace, pod, container string,\n5141: +\tcommand []string,\n5142: +\tstdin io.Reader,\n5143: +\tstdout, stderr io.Writer,\n5144: +) error {\n5145: +\texecURL := r.kubeClient.CoreV1().RESTClient().Post().\n5146: +\t\tResource(\"pods\").\n5147: +\t\tName(pod).\n5148: +\t\tNamespace(namespace).\n5149: +\t\tSubResource(\"exec\").\n5150: +\t\tVersionedParams(&corev1.PodExecOptions{\n5151: +\t\t\tContainer: container,\n5152: +\t\t\tCommand:   command,\n5153: +\t\t\tStdin:     stdin != nil,\n5154: +\t\t\tStdout:    stdout != nil,\n5155: +\t\t\tStderr:    stderr != nil,\n5156: +\t\t}, scheme.ParameterCodec).URL()\n5157: +\n5158: +\texecutor, err := r.newExecutor(execURL)\n5159: +\tif err != nil {\n5160: +\t\treturn err\n5161: +\t}\n5162: +\n5163: +\t// client-go reports streams cut by a cancelled context through the context's logger; a\n5164: +\t// capture ends that way on purpose, so it goes to the debug log\n5165: +\terr = executor.StreamWithContext(withKubernetesClientDebugLogs(ctx),\n5166: +\t\tremotecommand.StreamOptions{\n5167: +\t\t\tStdin:  stdin,\n5168: +\t\t\tStdout: stdout,\n5169: +\t\t\tStderr: stderr,\n5170: +\t\t})\n5171: +\n5172: +\tvar exitErr kubeexec.ExitError\n5173: +\tif errors.As(err, &exitErr) {\n5174: +\t\treturn &clablabruntime.CommandExitError{Code: exitErr.ExitStatus()}\n5175: +\t}\n5176: +\tif err != nil {\n5177: +\t\treturn fmt.Errorf(\"failed to execute command in pod %s/%s container %s: %w\",\n5178: +\t\t\tnamespace, pod, container, err)\n5179: +\t}\n5180: +\n5181: +\treturn nil\n5182: +}\n5183: +\n5184: +// InspectInterfaces lists the capturable link interfaces of the requested nodes, or of every\n5185: +// running node, in the shape of `inspect interfaces`: per node (named <lab>-<node> like in\n5186: +// inspect), the interface and its alias as clabwire reports them, and the MAC address, index,\n5187: +// MTU and operational state read from sysfs in the device container. A node whose device\n5188: +// container has no shell reports its interfaces without these attributes.\n5189: +func (r *Runtime) InspectInterfaces(\n5190: +\tctx context.Context,\n5191: +\treq clablabruntime.NodeRequest,\n5192: +) ([]*clabtypes.ContainerInterfaces, error) {\n5193: +\tr, err := r.connect(ctx, req.Identity)\n5194: +\tif err != nil {\n5195: +\t\treturn nil, err\n5196: +\t}\n5197: +\n5198: +\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n5199: +\t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n5200: +\t})\n5201: +\tif err != nil {\n5202: +\t\treturn nil, err\n5203: +\t}\n5204: +\n5205: +\trunning := make([]clablabruntime.NodeLocation, 0, len(locations))\n5206: +\tfor _, location := range locations {\n5207: +\t\tif location.Pod == \"\" {\n5208: +\t\t\tlog.Warn(\"Skipping interface detection of a node that does not run\",\n5209: +\t\t\t\t\"node\", location.NodeName)\n5210: +\t\t\tcontinue\n5211: +\t\t}\n5212: +\t\trunning = append(running, location)\n5213: +\t}\n5214: +\n5215: +\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, running)\n5216: +\tif err != nil {\n5217: +\t\treturn nil, err\n5218: +\t}\n5219: +\tstates := r.sampleInterfaceStates(ctx, running)\n5220: +\n5221: +\tresult := make([]*clabtypes.ContainerInterfaces, 0, len(running))\n5222: +\tfor _, location := range running {\n5223: +\t\tcontainer := &clabtypes.ContainerInterfaces{\n5224: +\t\t\tContainerName: req.Name + \"-\" + location.NodeName,\n5225: +\t\t\tInterfaces:    []*clabtypes.ContainerInterfaceDetails{},\n5226: +\t\t}\n5227: +\t\tfor _, entry := range listed[location.NodeName] {\n5228: +\t\t\tdetails := &clabtypes.ContainerInterfaceDetails{\n5229: +\t\t\t\tInterfaceName:  entry.Interface,\n5230: +\t\t\t\tInterfaceAlias: entry.Alias,\n5231: +\t\t\t\t// clabwire realizes every lab link interface as a veth pair\n5232: +\t\t\t\tInterfaceType: \"veth\",\n5233: +\t\t\t}\n5234: +\t\t\tif state, ok := states[location.NodeName][entry.Interface]; ok {\n5235: +\t\t\t\tdetails.InterfaceMAC = state.MAC\n5236: +\t\t\t\tdetails.InterfaceIndex = state.Index\n5237: +\t\t\t\tdetails.InterfaceMTU = state.MTU\n5238: +\t\t\t\tdetails.InterfaceState = state.OperState\n5239: +\t\t\t}\n5240: +\t\t\tcontainer.Interfaces = append(container.Interfaces, details)\n5241: +\t\t}\n5242: +\t\tsort.Slice(container.Interfaces, func(i, j int) bool {\n5243: +\t\t\treturn container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName\n5244: +\t\t})\n5245: +\t\tresult = append(result, container)\n5246: +\t}\n5247: +\tsort.Slice(result, func(i, j int) bool {\n5248: +\t\treturn result[i].ContainerName < result[j].ContainerName\n5249: +\t})\n5250: +\n5251: +\treturn result, nil\n5252: +}\n5253: +\n5254: +// sampleInterfaceStates reads the sysfs interface attributes of every node's device container,\n5255: +// one exec per node, with the script the interface events use.\n5256: +func (r *Runtime) sampleInterfaceStates(\n5257: +\tctx context.Context,\n5258: +\tlocations []clablabruntime.NodeLocation,\n5259: +) map[string]map[string]c9sIfaceState {\n5260: +\tvar mu sync.Mutex\n5261: +\tresult := map[string]map[string]c9sIfaceState{}\n5262: +\n5263: +\tvar wg sync.WaitGroup\n5264: +\tworkers := make(chan struct{}, interfaceSampleWorkers)\n5265: +\texec := r.execInPodContainer()\n5266: +\tfor _, location := range locations {\n5267: +\t\twg.Add(1)\n5268: +\t\tgo func() {\n5269: +\t\t\tdefer wg.Done()\n5270: +\t\t\tworkers <- struct{}{}\n5271: +\t\t\tdefer func() { <-workers }()\n5272: +\n5273: +\t\t\tvar stdout, stderr bytes.Buffer\n5274: +\t\t\terr := exec(ctx, location.Namespace, location.Pod, location.Container,\n5275: +\t\t\t\t[]string{\"sh\", \"-c\", interfaceSampleScript}, nil, &stdout, &stderr)\n5276: +\t\t\tif err != nil {\n5277: +\t\t\t\tlog.Debug(\"Cannot read the interface state of a c9s node\",\n5278: +\t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n5279: +\t\t\t\treturn\n5280: +\t\t\t}\n5281: +\t\t\t_, ifaces, _, err := parseInterfaceSample(stdout.Bytes())\n5282: +\t\t\tif err != nil {\n5283: +\t\t\t\tlog.Debug(\"Cannot parse the interface state of a c9s node\",\n5284: +\t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n5285: +\t\t\t\treturn\n5286: +\t\t\t}\n5287: +\n5288: +\t\t\tbyName := make(map[string]c9sIfaceState, len(ifaces))\n5289: +\t\t\tfor _, iface := range ifaces {\n5290: +\t\t\t\tbyName[iface.Name] = iface\n5291: +\t\t\t}\n5292: +\t\t\tmu.Lock()\n5293: +\t\t\tresult[location.NodeName] = byName\n5294: +\t\t\tmu.Unlock()\n5295: +\t\t}()\n5296: +\t}\n5297: +\twg.Wait()\n5298: +\n5299: +\treturn result\n5300: +}\n5301: diff --git a/labruntime/clabernetes/capture_test.go b/labruntime/clabernetes/capture_test.go\n5302: new file mode 100644\n5303: index 0000000..16628b5\n5304: --- /dev/null\n5305: +++ b/labruntime/clabernetes/capture_test.go\n5306: @@ -0,0 +1,1050 @@\n5307: +package clabernetes\n5308: +\n5309: +import (\n5310: +\t\"bytes\"\n5311: +\t\"context\"\n5312: +\t\"encoding/binary\"\n5313: +\t\"encoding/json\"\n5314: +\t\"errors\"\n5315: +\t\"fmt\"\n5316: +\t\"io\"\n5317: +\t\"slices\"\n5318: +\t\"strings\"\n5319: +\t\"sync\"\n5320: +\t\"testing\"\n5321: +\t\"time\"\n5322: +\n5323: +\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n5324: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n5325: +\tcorev1 \"k8s.io/api/core/v1\"\n5326: +\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n5327: +\t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n5328: +\tk8sruntime \"k8s.io/apimachinery/pkg/runtime\"\n5329: +)\n5330: +\n5331: +func captureTestNode(name, original, container string) *unstructured.Unstructured {\n5332: +\tlabels := map[string]any{labelTopologyOwner: \"lab1\"}\n5333: +\tif original != \"\" {\n5334: +\t\tlabels[labelOriginalNodeName] = original\n5335: +\t}\n5336: +\n5337: +\treturn &unstructured.Unstructured{Object: map[string]any{\n5338: +\t\t\"apiVersion\": c9sAPIVersion,\n5339: +\t\t\"kind\":       \"Node\",\n5340: +\t\t\"metadata\": map[string]any{\n5341: +\t\t\t\"name\": name, \"namespace\": \"lab-ns\", \"uid\": \"uid-\" + name, \"labels\": labels,\n5342: +\t\t},\n5343: +\t\t\"spec\": map[string]any{\"kind\": \"srl\", \"runState\": nodeRunStateRunning},\n5344: +\t\t\"status\": map[string]any{\n5345: +\t\t\t\"readiness\":        \"ready\",\n5346: +\t\t\t\"directContainers\": []any{map[string]any{\"name\": container, \"id\": name}},\n5347: +\t\t},\n5348: +\t}}\n5349: +}\n5350: +\n5351: +func captureTestPod(name, node string) *corev1.Pod {\n5352: +\treturn &corev1.Pod{\n5353: +\t\tObjectMeta: metav1.ObjectMeta{\n5354: +\t\t\tName: name, Namespace: \"lab-ns\",\n5355: +\t\t\tLabels: map[string]string{\n5356: +\t\t\t\tlabelApp: clabernetesAppValue, labelTopologyOwner: \"lab1\", labelTopologyNode: node,\n5357: +\t\t\t},\n5358: +\t\t},\n5359: +\t\tStatus: corev1.PodStatus{Phase: corev1.PodRunning},\n5360: +\t}\n5361: +}\n5362: +\n5363: +// captureListing is the --list-interfaces output of each pod.\n5364: +var captureListing = map[string][]clabwireInterface{ //nolint:gochecknoglobals\n5365: +\t\"lab1-r1-abc\": {\n5366: +\t\t{\n5367: +\t\t\tNode:          \"r1\",\n5368: +\t\t\tInterface:     \"e1-1\",\n5369: +\t\t\tAlias:         \"ethernet-1/1\",\n5370: +\t\t\tPeerNode:      \"r2\",\n5371: +\t\t\tPeerInterface: \"ethernet-1/1\",\n5372: +\t\t},\n5373: +\t\t{Node: \"r1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"r1-e1-2\"},\n5374: +\t},\n5375: +\t\"lab1-r2-def\": {\n5376: +\t\t{\n5377: +\t\t\tNode:          \"r2\",\n5378: +\t\t\tInterface:     \"e1-1\",\n5379: +\t\t\tAlias:         \"ethernet-1/1\",\n5380: +\t\t\tPeerNode:      \"r1\",\n5381: +\t\t\tPeerInterface: \"ethernet-1/1\",\n5382: +\t\t},\n5383: +\t},\n5384: +}\n5385: +\n5386: +// fakeClabwire plays clabwire packet-capture and --list-interfaces in the fake pod exec. Every\n5387: +// capture process sees the same traffic: one packet per tick on each requested interface,\n5388: +// carrying the tick number, stamped with the tick time plus a per-process jitter (clabwire stamps\n5389: +// packets when it reads them).\n5390: +type fakeClabwire struct {\n5391: +\tt     *testing.T\n5392: +\tepoch time.Time\n5393: +\ttick  time.Duration\n5394: +\n5395: +\tmu       sync.Mutex\n5396: +\tcommands [][]string\n5397: +\t// processes counts the capture processes started per node\n5398: +\tprocesses map[string]int\n5399: +\n5400: +\t// startDelay delays the Started record of the given process index (all nodes).\n5401: +\tstartDelay map[int]time.Duration\n5402: +\t// firstStartDelay delays the Started record of a node's first process.\n5403: +\tfirstStartDelay map[string]time.Duration\n5404: +\t// fail makes a process write this audit status and exit 1.\n5405: +\tfail string\n5406: +\t// stderrOnly makes a process write this text to stderr and exit 1, like a clabwire that\n5407: +\t// rejects a flag.\n5408: +\tstderrOnly string\n5409: +\t// stampSkew stamps the packets of a node this much earlier, as if its stream reached\n5410: +\t// containerlab this much later than the others.\n5411: +\tstampSkew map[string]time.Duration\n5412: +\t// stdinClosed counts the processes that ended because their stdin closed, per node.\n5413: +\tstdinClosed map[string]int\n5414: +\t// written counts the packets written to stdout, per node.\n5415: +\twritten map[string]int\n5416: +\t// sysfs is the device container's interface sample.\n5417: +\tsysfs string\n5418: +}\n5419: +\n5420: +func newFakeClabwire(t *testing.T, tick time.Duration) *fakeClabwire {\n5421: +\tt.Helper()\n5422: +\n5423: +\treturn &fakeClabwire{\n5424: +\t\tt: t, epoch: time.Now(), tick: tick, processes: map[string]int{},\n5425: +\t\tstartDelay: map[int]time.Duration{}, stampSkew: map[string]time.Duration{},\n5426: +\t\tfirstStartDelay: map[string]time.Duration{},\n5427: +\t\tstdinClosed:     map[string]int{},\n5428: +\t\twritten:         map[string]int{},\n5429: +\t}\n5430: +}\n5431: +\n5432: +func (f *fakeClabwire) exec(\n5433: +\tctx context.Context,\n5434: +\tnamespace, pod, container string,\n5435: +\tcommand []string,\n5436: +\tstdin io.Reader,\n5437: +\tstdout, stderr io.Writer,\n5438: +) error {\n5439: +\tf.mu.Lock()\n5440: +\tf.commands = append(\n5441: +\t\tf.commands,\n5442: +\t\tappend([]string{namespace + \"/\" + pod + \"/\" + container}, command...),\n5443: +\t)\n5444: +\tf.mu.Unlock()\n5445: +\n5446: +\tif container != clabwireContainer {\n5447: +\t\t_, _ = io.WriteString(stdout, f.sysfs)\n5448: +\t\treturn nil\n5449: +\t}\n5450: +\tif slices.Contains(command, \"--list-interfaces\") {\n5451: +\t\treturn json.NewEncoder(stdout).Encode(captureListing[pod])\n5452: +\t}\n5453: +\n5454: +\treturn f.capture(ctx, command, stdin, stdout, stderr)\n5455: +}\n5456: +\n5457: +func flagValues(command []string, name string) []string {\n5458: +\tvar values []string\n5459: +\tfor idx := 0; idx+1 < len(command); idx++ {\n5460: +\t\tif command[idx] == name {\n5461: +\t\t\tvalues = append(values, command[idx+1])\n5462: +\t\t}\n5463: +\t}\n5464: +\n5465: +\treturn values\n5466: +}\n5467: +\n5468: +func (f *fakeClabwire) audit(\n5469: +\tstderr io.Writer,\n5470: +\tstatus, node string,\n5471: +\tinterfaces []string,\n5472: +\treason string,\n5473: +) {\n5474: +\trecord := map[string]any{\n5475: +\t\t\"schemaVersion\": captureAuditSchema, \"time\": time.Now().UTC(), \"operation\": \"PacketCapture\",\n5476: +\t\t\"status\": status, \"nodeName\": node, \"format\": \"pcapng\", \"reason\": reason,\n5477: +\t}\n5478: +\tentries := []map[string]any{}\n5479: +\tfor _, name := range interfaces {\n5480: +\t\tentries = append(entries, map[string]any{\"name\": name})\n5481: +\t}\n5482: +\trecord[\"interfaces\"] = entries\n5483: +\tdata, _ := json.Marshal(record)\n5484: +\t_, _ = stderr.Write(append(data, '\\n'))\n5485: +}\n5486: +\n5487: +func (f *fakeClabwire) capture(\n5488: +\tctx context.Context,\n5489: +\tcommand []string,\n5490: +\tstdin io.Reader,\n5491: +\tstdout, stderr io.Writer,\n5492: +) error {\n5493: +\tf.mu.Lock()\n5494: +\trejected := f.stderrOnly\n5495: +\tf.mu.Unlock()\n5496: +\tif rejected != \"\" {\n5497: +\t\t_, _ = io.WriteString(stdout, \"Incorrect Usage: \"+rejected+\"\\n\\nNAME:\\n   manager\\n\")\n5498: +\t\t_, _ = io.WriteString(stderr, rejected+\"\\n\")\n5499: +\t\treturn &clablabruntime.CommandExitError{Code: 1}\n5500: +\t}\n5501: +\n5502: +\t// clabwire ends the capture when stdin closes (--stop-on-stdin-close)\n5503: +\tif !slices.Contains(command, clabwireStopOnStdinClose) || stdin == nil {\n5504: +\t\tf.t.Errorf(\"capture without stdin and %s: %v\", clabwireStopOnStdinClose, command)\n5505: +\t\treturn fmt.Errorf(\"no stdin\")\n5506: +\t}\n5507: +\tstdinClosed := make(chan struct{})\n5508: +\tgo func() {\n5509: +\t\t_, _ = io.Copy(io.Discard, stdin)\n5510: +\t\tclose(stdinClosed)\n5511: +\t}()\n5512: +\n5513: +\tnode := flagValues(command, \"--nodeName\")[0]\n5514: +\tinterfaces := flagValues(command, \"--interface\")\n5515: +\tduration, err := time.ParseDuration(flagValues(command, \"--duration\")[0])\n5516: +\tif err != nil {\n5517: +\t\tf.t.Errorf(\"duration: %v\", err)\n5518: +\t}\n5519: +\tif !slices.Equal(flagValues(command, \"--format\"), []string{\"pcapng\"}) {\n5520: +\t\tf.t.Errorf(\"capture without --format pcapng: %v\", command)\n5521: +\t}\n5522: +\n5523: +\tf.mu.Lock()\n5524: +\tindex := f.processes[node]\n5525: +\tf.processes[node]++\n5526: +\tdelay := f.startDelay[index]\n5527: +\tif index == 0 {\n5528: +\t\tdelay += f.firstStartDelay[node]\n5529: +\t}\n5530: +\tfailure := f.fail\n5531: +\tskew := f.stampSkew[node]\n5532: +\tf.mu.Unlock()\n5533: +\n5534: +\tif failure != \"\" {\n5535: +\t\tf.audit(stderr, failure, node, interfaces, \"interface \\\"eth9\\\" is not uniquely planned\")\n5536: +\t\treturn &clablabruntime.CommandExitError{Code: 1}\n5537: +\t}\n5538: +\n5539: +\tselect {\n5540: +\tcase <-time.After(delay):\n5541: +\tcase <-ctx.Done():\n5542: +\t\treturn ctx.Err()\n5543: +\tcase <-stdinClosed:\n5544: +\t\tf.audit(stderr, captureAuditStarted, node, interfaces, \"\")\n5545: +\t\tf.audit(stderr, captureAuditSucceeded, node, interfaces, \"client closed: stdin reached EOF\")\n5546: +\t\treturn nil\n5547: +\t}\n5548: +\n5549: +\twriter := clabcapture.NewWriter(stdout)\n5550: +\tf.audit(stderr, captureAuditStarted, node, interfaces, \"\")\n5551: +\tif err := writer.WriteHeader(interfaces, clabcapture.DefaultSnapLength); err != nil {\n5552: +\t\treturn err\n5553: +\t}\n5554: +\n5555: +\t// clabwire's own section header names it\n5556: +\tend := time.Now().Add(duration)\n5557: +\tjitter := time.Duration(index%3) * 7 * time.Microsecond\n5558: +\tnext := time.Now().Sub(f.epoch)/f.tick + 1\n5559: +\tfor {\n5560: +\t\tat := f.epoch.Add(next * f.tick)\n5561: +\t\tif at.After(end) {\n5562: +\t\t\tbreak\n5563: +\t\t}\n5564: +\t\tselect {\n5565: +\t\tcase <-ctx.Done():\n5566: +\t\t\treturn ctx.Err()\n5567: +\t\tcase <-stdinClosed:\n5568: +\t\t\tf.mu.Lock()\n5569: +\t\t\tf.stdinClosed[node]++\n5570: +\t\t\tf.mu.Unlock()\n5571: +\t\t\tf.audit(\n5572: +\t\t\t\tstderr,\n5573: +\t\t\t\tcaptureAuditSucceeded,\n5574: +\t\t\t\tnode,\n5575: +\t\t\t\tinterfaces,\n5576: +\t\t\t\t\"client closed: stdin reached EOF\",\n5577: +\t\t\t)\n5578: +\t\t\treturn nil\n5579: +\t\tcase <-time.After(time.Until(at)):\n5580: +\t\t}\n5581: +\t\tfor id := range interfaces {\n5582: +\t\t\tdata := make([]byte, 64)\n5583: +\t\t\tbinary.BigEndian.PutUint64(data[0:], uint64(next))\n5584: +\t\t\tcopy(data[8:], node+\":\"+interfaces[id])\n5585: +\t\t\tif err := writer.WritePacket(uint32(id), &clabcapture.Packet{ //nolint:gosec // small\n5586: +\t\t\t\tTimestamp: at.Add(jitter - skew).UnixNano(), OriginalLength: 64, Data: data,\n5587: +\t\t\t}); err != nil {\n5588: +\t\t\t\treturn err\n5589: +\t\t\t}\n5590: +\t\t\tf.mu.Lock()\n5591: +\t\t\tf.written[node]++\n5592: +\t\t\tf.mu.Unlock()\n5593: +\t\t}\n5594: +\t\tnext++\n5595: +\t}\n5596: +\tf.audit(stderr, captureAuditSucceeded, node, interfaces, \"\")\n5597: +\n5598: +\treturn nil\n5599: +}\n5600: +\n5601: +func (f *fakeClabwire) captureCommands() [][]string {\n5602: +\tf.mu.Lock()\n5603: +\tdefer f.mu.Unlock()\n5604: +\n5605: +\tvar result [][]string\n5606: +\tfor _, command := range f.commands {\n5607: +\t\tif slices.Contains(command, \"packet-capture\") &&\n5608: +\t\t\t!slices.Contains(command, \"--list-interfaces\") {\n5609: +\t\t\tresult = append(result, command)\n5610: +\t\t}\n5611: +\t}\n5612: +\n5613: +\treturn result\n5614: +}\n5615: +\n5616: +// captureTestRuntime is lab1 in lab-ns with nodes r1 (topology name R1) and r2, each in its\n5617: +// own pod, and a fake clabwire.\n5618: +func captureTestRuntime(t *testing.T, tick time.Duration) (*Runtime, *fakeClabwire) {\n5619: +\tt.Helper()\n5620: +\n5621: +\tr := newTestRuntimeWithKubeObjects(\n5622: +\t\t[]*unstructured.Unstructured{\n5623: +\t\t\tcaptureTestNode(\"r1\", \"R1\", \"node-r1-x\"),\n5624: +\t\t\tcaptureTestNode(\"r2\", \"\", \"node-r2-x\"),\n5625: +\t\t},\n5626: +\t\t[]k8sruntime.Object{\n5627: +\t\t\tcaptureTestPod(\"lab1-r1-abc\", \"r1\"),\n5628: +\t\t\tcaptureTestPod(\"lab1-r2-def\", \"r2\"),\n5629: +\t\t},\n5630: +\t)\n5631: +\tr.labNamespaceOverride = \"lab-ns\"\n5632: +\tclabwire := newFakeClabwire(t, tick)\n5633: +\tr.podExec = clabwire.exec\n5634: +\n5635: +\treturn r, clabwire\n5636: +}\n5637: +\n5638: +// parsedCapture is a pcapng stream read back.\n5639: +type parsedCapture struct {\n5640: +\tsections   int\n5641: +\tinterfaces []string\n5642: +\tpackets    []clabcapture.Packet\n5643: +}\n5644: +\n5645: +func parseCapture(t *testing.T, data []byte) parsedCapture {\n5646: +\tt.Helper()\n5647: +\n5648: +\treader := clabcapture.NewReader(bytes.NewReader(data))\n5649: +\tvar parsed parsedCapture\n5650: +\tfor {\n5651: +\t\tevent, err := reader.Next()\n5652: +\t\tif errors.Is(err, io.EOF) {\n5653: +\t\t\tbreak\n5654: +\t\t}\n5655: +\t\tif err != nil {\n5656: +\t\t\tt.Fatalf(\"invalid capture: %v\", err)\n5657: +\t\t}\n5658: +\t\tif event.Interface != nil {\n5659: +\t\t\tif len(parsed.packets) != 0 {\n5660: +\t\t\t\tt.Fatal(\"interface description after the first packet\")\n5661: +\t\t\t}\n5662: +\t\t\tif event.Interface.TSResol != 9 /* nanoseconds */ {\n5663: +\t\t\t\tt.Fatalf(\"interface %s tsresol = %d\", event.Interface.Name, event.Interface.TSResol)\n5664: +\t\t\t}\n5665: +\t\t\tparsed.interfaces = append(parsed.interfaces, event.Interface.Name)\n5666: +\t\t}\n5667: +\t\tif event.Packet != nil {\n5668: +\t\t\tparsed.packets = append(parsed.packets, *event.Packet)\n5669: +\t\t}\n5670: +\t}\n5671: +\tparsed.sections = reader.Sections()\n5672: +\n5673: +\treturn parsed\n5674: +}\n5675: +\n5676: +func packetSequence(packet clabcapture.Packet) uint64 {\n5677: +\treturn binary.BigEndian.Uint64(packet.Data[0:8])\n5678: +}\n5679: +\n5680: +func packetOrigin(packet clabcapture.Packet) string {\n5681: +\treturn strings.TrimRight(string(packet.Data[8:]), \"\\x00\")\n5682: +}\n5683: +\n5684: +func TestCaptureInterfacesUsesTopologyNames(t *testing.T) {\n5685: +\tt.Parallel()\n5686: +\n5687: +\tr, _ := captureTestRuntime(t, time.Millisecond)\n5688: +\tinterfaces, err := r.CaptureInterfaces(\n5689: +\t\tcontext.Background(),\n5690: +\t\tclablabruntime.NodeRequest{Name: \"lab1\"},\n5691: +\t)\n5692: +\tif err != nil {\n5693: +\t\tt.Fatal(err)\n5694: +\t}\n5695: +\twant := []clablabruntime.CaptureInterface{\n5696: +\t\t{\n5697: +\t\t\tNode:          \"R1\",\n5698: +\t\t\tInterface:     \"e1-1\",\n5699: +\t\t\tAlias:         \"ethernet-1/1\",\n5700: +\t\t\tPeerNode:      \"r2\",\n5701: +\t\t\tPeerInterface: \"ethernet-1/1\",\n5702: +\t\t},\n5703: +\t\t{Node: \"R1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"r1-e1-2\"},\n5704: +\t\t{\n5705: +\t\t\tNode:          \"r2\",\n5706: +\t\t\tInterface:     \"e1-1\",\n5707: +\t\t\tAlias:         \"ethernet-1/1\",\n5708: +\t\t\tPeerNode:      \"R1\",\n5709: +\t\t\tPeerInterface: \"ethernet-1/1\",\n5710: +\t\t},\n5711: +\t}\n5712: +\tif !slices.Equal(interfaces, want) {\n5713: +\t\tt.Fatalf(\"interfaces = %+v\\nwant %+v\", interfaces, want)\n5714: +\t}\n5715: +\n5716: +\tone, err := r.CaptureInterfaces(context.Background(), clablabruntime.NodeRequest{\n5717: +\t\tName: \"lab1\", Nodes: []string{\"r2\"},\n5718: +\t})\n5719: +\tif err != nil || len(one) != 1 || one[0].Node != \"r2\" {\n5720: +\t\tt.Fatalf(\"r2 interfaces = %+v, %v\", one, err)\n5721: +\t}\n5722: +}\n5723: +\n5724: +func TestCaptureMergesNodesIntoOneSection(t *testing.T) {\n5725: +\tt.Parallel()\n5726: +\n5727: +\tr, clabwire := captureTestRuntime(t, 10*time.Millisecond)\n5728: +\tvar out bytes.Buffer\n5729: +\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n5730: +\t\tName: \"lab1\",\n5731: +\t\t// the topology name of r1, an alias, and a second node between two r1 interfaces\n5732: +\t\tTargets: []clablabruntime.CaptureTarget{\n5733: +\t\t\t{Node: \"R1\", Interface: \"ethernet-1/1\"},\n5734: +\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n5735: +\t\t\t{Node: \"r1\", Interface: \"e1-2\"},\n5736: +\t\t},\n5737: +\t\tDuration: 300 * time.Millisecond,\n5738: +\t}, &out)\n5739: +\tif err != nil {\n5740: +\t\tt.Fatal(err)\n5741: +\t}\n5742: +\n5743: +\tparsed := parseCapture(t, out.Bytes())\n5744: +\tif parsed.sections != 1 {\n5745: +\t\tt.Fatalf(\"sections = %d, want one merged section\", parsed.sections)\n5746: +\t}\n5747: +\twantNames := []string{\"R1:e1-1\", \"r2:e1-1\", \"R1:e1-2\"}\n5748: +\tif !slices.Equal(parsed.interfaces, wantNames) {\n5749: +\t\tt.Fatalf(\"interfaces = %v, want %v\", parsed.interfaces, wantNames)\n5750: +\t}\n5751: +\n5752: +\t// one clabwire process per node, with all of the node's interfaces in request order\n5753: +\tcommands := clabwire.captureCommands()\n5754: +\tif len(commands) != 2 {\n5755: +\t\tt.Fatalf(\"capture processes = %d, want one per node: %v\", len(commands), commands)\n5756: +\t}\n5757: +\tfor _, command := range commands {\n5758: +\t\tnode := flagValues(command, \"--nodeName\")[0]\n5759: +\t\twant := map[string][]string{\"r1\": {\"e1-1\", \"e1-2\"}, \"r2\": {\"e1-1\"}}[node]\n5760: +\t\tif got := flagValues(command, \"--interface\"); !slices.Equal(got, want) {\n5761: +\t\t\tt.Fatalf(\"%s interfaces = %v, want %v\", node, got, want)\n5762: +\t\t}\n5763: +\t\tif !strings.HasSuffix(command[0], \"/\"+clabwireContainer) {\n5764: +\t\t\tt.Fatalf(\"capture ran in %s, want the clabwire container\", command[0])\n5765: +\t\t}\n5766: +\t}\n5767: +\n5768: +\t// every packet carries the merged ID of its interface\n5769: +\twantOrigin := map[uint32]string{0: \"r1:e1-1\", 1: \"r2:e1-1\", 2: \"r1:e1-2\"}\n5770: +\tperInterface := map[uint32]int{}\n5771: +\tfor _, packet := range parsed.packets {\n5772: +\t\tif packetOrigin(packet) != wantOrigin[packet.InterfaceID] {\n5773: +\t\t\tt.Fatalf(\"packet from %s has interface ID %d\", packetOrigin(packet), packet.InterfaceID)\n5774: +\t\t}\n5775: +\t\tperInterface[packet.InterfaceID]++\n5776: +\t}\n5777: +\tfor id := range uint32(3) {\n5778: +\t\tif perInterface[id] == 0 {\n5779: +\t\t\tt.Fatalf(\"no packets on %s: %v\", wantNames[id], perInterface)\n5780: +\t\t}\n5781: +\t}\n5782: +}\n5783: +\n5784: +// TestCaptureChainsSegmentsWithoutDuplicatesOrGaps runs captures longer than one segment: every\n5785: +// tick must appear exactly once per interface, across every switch.\n5786: +func TestCaptureChainsSegmentsWithoutDuplicatesOrGaps(t *testing.T) {\n5787: +\tt.Parallel()\n5788: +\n5789: +\tr, clabwire := captureTestRuntime(t, 4*time.Millisecond)\n5790: +\tr.captureSegment = 300 * time.Millisecond\n5791: +\n5792: +\tvar gaps []clablabruntime.CaptureGap\n5793: +\tvar out bytes.Buffer\n5794: +\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n5795: +\t\tName: \"lab1\",\n5796: +\t\tTargets: []clablabruntime.CaptureTarget{\n5797: +\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n5798: +\t\t\t{Node: \"r1\", Interface: \"e1-2\"},\n5799: +\t\t},\n5800: +\t\tDuration: 1300 * time.Millisecond,\n5801: +\t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n5802: +\t}, &out)\n5803: +\tif err != nil {\n5804: +\t\tt.Fatal(err)\n5805: +\t}\n5806: +\tif len(gaps) != 0 {\n5807: +\t\tt.Fatalf(\"gaps = %+v\", gaps)\n5808: +\t}\n5809: +\tif processes := len(clabwire.captureCommands()); processes < 4 {\n5810: +\t\tt.Fatalf(\"capture processes = %d, want a chain of at least 4 segments\", processes)\n5811: +\t}\n5812: +\n5813: +\tparsed := parseCapture(t, out.Bytes())\n5814: +\tif parsed.sections != 1 || len(parsed.interfaces) != 2 {\n5815: +\t\tt.Fatalf(\"sections = %d, interfaces = %v; want the follow-up headers dropped\",\n5816: +\t\t\tparsed.sections, parsed.interfaces)\n5817: +\t}\n5818: +\tfor id := range uint32(2) {\n5819: +\t\tvar sequence []uint64\n5820: +\t\tfor _, packet := range parsed.packets {\n5821: +\t\t\tif packet.InterfaceID == id {\n5822: +\t\t\t\tsequence = append(sequence, packetSequence(packet))\n5823: +\t\t\t}\n5824: +\t\t}\n5825: +\t\tif len(sequence) < 200 {\n5826: +\t\t\tt.Fatalf(\"interface %d has %d packets\", id, len(sequence))\n5827: +\t\t}\n5828: +\t\tslices.Sort(sequence)\n5829: +\t\tfor idx := 1; idx < len(sequence); idx++ {\n5830: +\t\t\tswitch {\n5831: +\t\t\tcase sequence[idx] == sequence[idx-1]:\n5832: +\t\t\t\tt.Fatalf(\"interface %d: tick %d written twice\", id, sequence[idx])\n5833: +\t\t\tcase sequence[idx] != sequence[idx-1]+1:\n5834: +\t\t\t\tt.Fatalf(\n5835: +\t\t\t\t\t\"interface %d: ticks %d to %d missing\",\n5836: +\t\t\t\t\tid,\n5837: +\t\t\t\t\tsequence[idx-1]+1,\n5838: +\t\t\t\t\tsequence[idx]-1,\n5839: +\t\t\t\t)\n5840: +\t\t\t}\n5841: +\t\t}\n5842: +\t}\n5843: +}\n5844: +\n5845: +func TestCaptureReportsAGapWhenTheFollowUpStartsLate(t *testing.T) {\n5846: +\tt.Parallel()\n5847: +\n5848: +\tr, clabwire := captureTestRuntime(t, 5*time.Millisecond)\n5849: +\tr.captureSegment = 300 * time.Millisecond\n5850: +\t// the second process starts long after the first one ended\n5851: +\tclabwire.startDelay[1] = 400 * time.Millisecond\n5852: +\n5853: +\tvar gaps []clablabruntime.CaptureGap\n5854: +\tvar out bytes.Buffer\n5855: +\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n5856: +\t\tName:     \"lab1\",\n5857: +\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"r2\", Interface: \"e1-1\"}},\n5858: +\t\tDuration: 800 * time.Millisecond,\n5859: +\t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n5860: +\t}, &out)\n5861: +\tif err != nil {\n5862: +\t\tt.Fatal(err)\n5863: +\t}\n5864: +\tif len(gaps) == 0 || gaps[0].Node != \"r2\" ||\n5865: +\t\t!slices.Equal(gaps[0].Interfaces, []string{\"e1-1\"}) ||\n5866: +\t\tgaps[0].From.IsZero() ||\n5867: +\t\tgaps[0].Reason == \"\" {\n5868: +\t\tt.Fatalf(\"gaps = %+v, want the late follow-up reported\", gaps)\n5869: +\t}\n5870: +\tif !gaps[0].To.IsZero() && !gaps[0].To.After(gaps[0].From) {\n5871: +\t\tt.Fatalf(\"gap ends before it starts: %+v\", gaps[0])\n5872: +\t}\n5873: +\tparseCapture(t, out.Bytes())\n5874: +}\n5875: +\n5876: +func TestCaptureMapsDeniedAndFailedAuditsToErrors(t *testing.T) {\n5877: +\tt.Parallel()\n5878: +\n5879: +\tfor _, status := range []string{captureAuditDenied, captureAuditFailed} {\n5880: +\t\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n5881: +\t\tclabwire.fail = status\n5882: +\n5883: +\t\tvar out bytes.Buffer\n5884: +\t\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n5885: +\t\t\tName:     \"lab1\",\n5886: +\t\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"r2\", Interface: \"e1-1\"}},\n5887: +\t\t\tDuration: time.Second,\n5888: +\t\t}, &out)\n5889: +\t\tif err == nil || !strings.Contains(err.Error(), \"is not uniquely planned\") ||\n5890: +\t\t\t!strings.Contains(err.Error(), \"node r2\") {\n5891: +\t\t\tt.Fatalf(\"%s: error = %v, want the audit reason\", status, err)\n5892: +\t\t}\n5893: +\t\tif status == captureAuditDenied && !strings.Contains(err.Error(), \"was denied\") {\n5894: +\t\t\tt.Fatalf(\"Denied error = %v\", err)\n5895: +\t\t}\n5896: +\t\t// the header is written before the capture starts, so the output stays a valid file\n5897: +\t\tparseCapture(t, out.Bytes())\n5898: +\t}\n5899: +}\n5900: +\n5901: +func TestCaptureAuditLineWriter(t *testing.T) {\n5902: +\tt.Parallel()\n5903: +\n5904: +\tvar audits []*captureAudit\n5905: +\twriter := &auditLineWriter{send: func(audit *captureAudit) { audits = append(audits, audit) }}\n5906: +\tstarted := fmt.Sprintf(`{\"schemaVersion\":%q,\"time\":\"2026-10-27T10:00:00.123456789Z\",`+\n5907: +\t\t`\"status\":\"Started\",\"nodeName\":\"r1\",\"interfaces\":[{\"name\":\"e1-1\",\"id\":\"if1\"}]}`,\n5908: +\t\tcaptureAuditSchema)\n5909: +\t// lines arrive split across writes\n5910: +\t_, _ = writer.Write([]byte(started[:20]))\n5911: +\t_, _ = writer.Write([]byte(started[20:] + \"\\nnot json\\n{\\\"status\\\":\\\"Started\\\"}\\n\"))\n5912: +\t_, _ = writer.Write(\n5913: +\t\t[]byte(`{\"schemaVersion\":\"` + captureAuditSchema + `\",\"status\":\"Succeeded\",\"packets\":3}`),\n5914: +\t)\n5915: +\twriter.flush()\n5916: +\n5917: +\tif len(audits) != 2 || audits[0].Status != captureAuditStarted || audits[1].Packets != 3 ||\n5918: +\t\taudits[0].Time.Nanosecond() != 123456789 || audits[0].Interfaces[0].Name != \"e1-1\" {\n5919: +\t\tt.Fatalf(\"audits = %+v\", audits)\n5920: +\t}\n5921: +\tif writer.text() != `not json; {\"status\":\"Started\"}` {\n5922: +\t\tt.Fatalf(\"other stderr = %q\", writer.text())\n5923: +\t}\n5924: +\n5925: +\terr := captureAuditError(\"r1\", &captureAudit{\n5926: +\t\tStatus: captureAuditDenied, Reason: \"nope\",\n5927: +\t\tInterfaces: []struct {\n5928: +\t\t\tName    string `json:\"name\"`\n5929: +\t\t\tID      string `json:\"id\"`\n5930: +\t\t\tPackets int    `json:\"packets\"`\n5931: +\t\t}{{Name: \"e1-1\"}, {Name: \"eth0\"}},\n5932: +\t})\n5933: +\tif err.Error() != \"capture of e1-1,eth0 on node r1 was denied by clabwire: nope\" {\n5934: +\t\tt.Fatalf(\"audit error = %q\", err)\n5935: +\t}\n5936: +}\n5937: +\n5938: +func TestCaptureStopsAtThePacketLimit(t *testing.T) {\n5939: +\tt.Parallel()\n5940: +\n5941: +\tr, clabwire := captureTestRuntime(t, 2*time.Millisecond)\n5942: +\tvar out bytes.Buffer\n5943: +\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n5944: +\t\tName: \"lab1\",\n5945: +\t\tTargets: []clablabruntime.CaptureTarget{\n5946: +\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n5947: +\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n5948: +\t\t},\n5949: +\t\tPacketLimit: 7,\n5950: +\t}, &out)\n5951: +\tif err != nil {\n5952: +\t\tt.Fatal(err)\n5953: +\t}\n5954: +\tif got := len(parseCapture(t, out.Bytes()).packets); got != 7 {\n5955: +\t\tt.Fatalf(\"packets = %d, want 7\", got)\n5956: +\t}\n5957: +\t// each clabwire process gets the limit that remained when it started\n5958: +\tfor _, command := range clabwire.captureCommands() {\n5959: +\t\tlimit := flagValues(command, \"--packetLimit\")\n5960: +\t\tif len(limit) != 1 || limit[0] < \"1\" || limit[0] > \"7\" || len(limit[0]) != 1 {\n5961: +\t\t\tt.Fatalf(\"clabwire packet limit = %v, want at most 7\", limit)\n5962: +\t\t}\n5963: +\t}\n5964: +}\n5965: +\n5966: +func TestCaptureEndsCleanlyWhenTheContextEnds(t *testing.T) {\n5967: +\tt.Parallel()\n5968: +\n5969: +\tr, _ := captureTestRuntime(t, 2*time.Millisecond)\n5970: +\tctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)\n5971: +\tdefer cancel()\n5972: +\n5973: +\tvar out bytes.Buffer\n5974: +\tif err := r.Capture(ctx, clablabruntime.CaptureRequest{\n5975: +\t\tName:    \"lab1\",\n5976: +\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"e1-1\"}},\n5977: +\t}, &out); err != nil {\n5978: +\t\tt.Fatalf(\"Capture() after the context ended = %v, want nil\", err)\n5979: +\t}\n5980: +\tif len(parseCapture(t, out.Bytes()).packets) == 0 {\n5981: +\t\tt.Fatal(\"no packets before the context ended\")\n5982: +\t}\n5983: +}\n5984: +\n5985: +func TestCaptureValidatesTargets(t *testing.T) {\n5986: +\tt.Parallel()\n5987: +\n5988: +\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n5989: +\tctx := context.Background()\n5990: +\tcases := map[string]clablabruntime.CaptureRequest{\n5991: +\t\t\"is not a capturable link interface; capturable: e1-1 (ethernet-1/1), e1-2\": {\n5992: +\t\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth0\"}},\n5993: +\t\t},\n5994: +\t\t\"requested more than once\": {\n5995: +\t\t\tTargets: []clablabruntime.CaptureTarget{\n5996: +\t\t\t\t{Node: \"r1\", Interface: \"e1-1\"}, {Node: \"R1\", Interface: \"ethernet-1/1\"},\n5997: +\t\t\t},\n5998: +\t\t},\n5999: +\t\t`node \"missing\" was not found`: {\n6000: +\t\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"missing\", Interface: \"e1-1\"}},\n6001: +\t\t},\n6002: +\t\t\"at least one capture target\": {},\n6003: +\t\t\"snap length 10 is outside\": {\n6004: +\t\t\tTargets:    []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"e1-1\"}},\n6005: +\t\t\tSnapLength: 10,\n6006: +\t\t},\n6007: +\t\t\"duration must not be negative\": {\n6008: +\t\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"e1-1\"}},\n6009: +\t\t\tDuration: -time.Second,\n6010: +\t\t},\n6011: +\t}\n6012: +\tfor want, req := range cases {\n6013: +\t\treq.Name = \"lab1\"\n6014: +\t\terr := r.Capture(ctx, req, io.Discard)\n6015: +\t\tif err == nil || !strings.Contains(err.Error(), want) {\n6016: +\t\t\tt.Errorf(\"error = %v, want %q\", err, want)\n6017: +\t\t}\n6018: +\t}\n6019: +\tif commands := clabwire.captureCommands(); len(commands) != 0 {\n6020: +\t\tt.Fatalf(\"invalid requests started captures: %v\", commands)\n6021: +\t}\n6022: +}\n6023: +\n6024: +func TestInspectInterfacesReportsStateFromSysfs(t *testing.T) {\n6025: +\tt.Parallel()\n6026: +\n6027: +\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n6028: +\tclabwire.sysfs = \"Inter-|   Receive\\n face |bytes\\n\" + interfaceSysfsMarker + \"\\n\" +\n6029: +\t\t\"e1-1\\t12\\t9500\\taa:c1:ab:00:00:01\\tup\\t0x1003\\t\\n\" +\n6030: +\t\t\"e1-2\\t13\\t1500\\taa:c1:ab:00:00:02\\tlowerlayerdown\\t0x1003\\t\\n\"\n6031: +\n6032: +\tinterfaces, err := r.InspectInterfaces(context.Background(), clablabruntime.NodeRequest{\n6033: +\t\tName: \"lab1\", Nodes: []string{\"R1\"},\n6034: +\t})\n6035: +\tif err != nil {\n6036: +\t\tt.Fatal(err)\n6037: +\t}\n6038: +\tif len(interfaces) != 1 || interfaces[0].ContainerName != \"lab1-r1\" ||\n6039: +\t\tlen(interfaces[0].Interfaces) != 2 {\n6040: +\t\tt.Fatalf(\"interfaces = %+v\", interfaces)\n6041: +\t}\n6042: +\tfirst := interfaces[0].Interfaces[0]\n6043: +\tif first.InterfaceName != \"e1-1\" || first.InterfaceAlias != \"ethernet-1/1\" ||\n6044: +\t\tfirst.InterfaceMAC != \"aa:c1:ab:00:00:01\" || first.InterfaceIndex != 12 ||\n6045: +\t\tfirst.InterfaceMTU != 9500 || first.InterfaceState != \"up\" {\n6046: +\t\tt.Fatalf(\"e1-1 = %+v\", first)\n6047: +\t}\n6048: +\tif second := interfaces[0].Interfaces[1]; second.InterfaceState != \"lowerlayerdown\" {\n6049: +\t\tt.Fatalf(\"e1-2 = %+v\", second)\n6050: +\t}\n6051: +}\n6052: +\n6053: +// TestCaptureClosesStdinWhenItEnds ends every clabwire process through its stdin, whether the\n6054: +// caller cancels the capture or the output fails, so no capture is left running in the pod.\n6055: +// TestCaptureWritesWhatItReadWhenTheContextEnds stops a capture while the output is slow and\n6056: +// the chains have packets queued: every packet clabwire wrote before it ended is in the file.\n6057: +func TestCaptureWritesWhatItReadWhenTheContextEnds(t *testing.T) {\n6058: +\tt.Parallel()\n6059: +\n6060: +\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n6061: +\t// without a reorder window, a blocked output blocks the chains\n6062: +\tr.captureReorderWindow = -1\n6063: +\tctx, cancel := context.WithCancel(context.Background())\n6064: +\tdefer cancel()\n6065: +\n6066: +\tout := &gatedWriter{open: make(chan struct{})}\n6067: +\tgo func() {\n6068: +\t\ttime.Sleep(50 * time.Millisecond)\n6069: +\t\tout.block()\n6070: +\t\t// the segments keep reading while the chains wait for the output\n6071: +\t\ttime.Sleep(400 * time.Millisecond)\n6072: +\t\tcancel()\n6073: +\t\tclose(out.open)\n6074: +\t}()\n6075: +\n6076: +\tif err := r.Capture(ctx, clablabruntime.CaptureRequest{\n6077: +\t\tName: \"lab1\",\n6078: +\t\tTargets: []clablabruntime.CaptureTarget{\n6079: +\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n6080: +\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n6081: +\t\t},\n6082: +\t}, out); err != nil {\n6083: +\t\tt.Fatal(err)\n6084: +\t}\n6085: +\n6086: +\tparsed := parseCapture(t, out.bytes())\n6087: +\tgot := map[string]int{}\n6088: +\tfor _, packet := range parsed.packets {\n6089: +\t\tnode, _, _ := strings.Cut(packetOrigin(packet), \":\")\n6090: +\t\tgot[node]++\n6091: +\t}\n6092: +\tclabwire.mu.Lock()\n6093: +\tdefer clabwire.mu.Unlock()\n6094: +\tfor _, node := range []string{\"r1\", \"r2\"} {\n6095: +\t\tif clabwire.written[node] < 300 || got[node] != clabwire.written[node] {\n6096: +\t\t\tt.Fatalf(\"%s: clabwire wrote %d packets, the capture has %d\", node,\n6097: +\t\t\t\tclabwire.written[node], got[node])\n6098: +\t\t}\n6099: +\t}\n6100: +}\n6101: +\n6102: +// gatedWriter collects writes; once blocked, writes wait until open is closed.\n6103: +type gatedWriter struct {\n6104: +\topen chan struct{}\n6105: +\n6106: +\tmu      sync.Mutex\n6107: +\tblocked bool\n6108: +\tdata    bytes.Buffer\n6109: +}\n6110: +\n6111: +func (w *gatedWriter) block() {\n6112: +\tw.mu.Lock()\n6113: +\tw.blocked = true\n6114: +\tw.mu.Unlock()\n6115: +}\n6116: +\n6117: +func (w *gatedWriter) Write(data []byte) (int, error) {\n6118: +\tw.mu.Lock()\n6119: +\tblocked := w.blocked\n6120: +\tw.mu.Unlock()\n6121: +\tif blocked {\n6122: +\t\t<-w.open\n6123: +\t}\n6124: +\tw.mu.Lock()\n6125: +\tdefer w.mu.Unlock()\n6126: +\n6127: +\treturn w.data.Write(data)\n6128: +}\n6129: +\n6130: +func (w *gatedWriter) bytes() []byte {\n6131: +\tw.mu.Lock()\n6132: +\tdefer w.mu.Unlock()\n6133: +\n6134: +\treturn w.data.Bytes()\n6135: +}\n6136: +\n6137: +func TestCaptureClosesStdinWhenItEnds(t *testing.T) {\n6138: +\tt.Parallel()\n6139: +\n6140: +\ttargets := []clablabruntime.CaptureTarget{\n6141: +\t\t{Node: \"r1\", Interface: \"e1-1\"},\n6142: +\t\t{Node: \"r2\", Interface: \"e1-1\"},\n6143: +\t}\n6144: +\n6145: +\tt.Run(\"cancel\", func(t *testing.T) {\n6146: +\t\tt.Parallel()\n6147: +\n6148: +\t\tr, clabwire := captureTestRuntime(t, 2*time.Millisecond)\n6149: +\t\tctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)\n6150: +\t\tdefer cancel()\n6151: +\n6152: +\t\tif err := r.Capture(ctx, clablabruntime.CaptureRequest{Name: \"lab1\", Targets: targets},\n6153: +\t\t\tio.Discard); err != nil {\n6154: +\t\t\tt.Fatal(err)\n6155: +\t\t}\n6156: +\t\trequireStdinClosedEverywhere(t, clabwire)\n6157: +\t})\n6158: +\n6159: +\tt.Run(\"output fails\", func(t *testing.T) {\n6160: +\t\tt.Parallel()\n6161: +\n6162: +\t\tr, clabwire := captureTestRuntime(t, 2*time.Millisecond)\n6163: +\t\toutput := &failingWriter{accept: 3}\n6164: +\t\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n6165: +\t\t\tName: \"lab1\", Targets: targets, Duration: time.Hour,\n6166: +\t\t}, output)\n6167: +\t\tif err == nil || !strings.Contains(err.Error(), \"broken pipe\") {\n6168: +\t\t\tt.Fatalf(\"Capture() = %v, want the write error\", err)\n6169: +\t\t}\n6170: +\t\trequireStdinClosedEverywhere(t, clabwire)\n6171: +\t})\n6172: +}\n6173: +\n6174: +// failingWriter accepts some writes, then fails like a closed pipe.\n6175: +type failingWriter struct {\n6176: +\tmu     sync.Mutex\n6177: +\taccept int\n6178: +}\n6179: +\n6180: +func (w *failingWriter) Write(data []byte) (int, error) {\n6181: +\tw.mu.Lock()\n6182: +\tdefer w.mu.Unlock()\n6183: +\tif w.accept == 0 {\n6184: +\t\treturn 0, errors.New(\"write |1: broken pipe\")\n6185: +\t}\n6186: +\tw.accept--\n6187: +\n6188: +\treturn len(data), nil\n6189: +}\n6190: +\n6191: +func requireStdinClosedEverywhere(t *testing.T, clabwire *fakeClabwire) {\n6192: +\tt.Helper()\n6193: +\n6194: +\tclabwire.mu.Lock()\n6195: +\tdefer clabwire.mu.Unlock()\n6196: +\tfor _, node := range []string{\"r1\", \"r2\"} {\n6197: +\t\tif clabwire.processes[node] == 0 || clabwire.stdinClosed[node] != clabwire.processes[node] {\n6198: +\t\t\tt.Fatalf(\"%s: %d processes, %d ended through stdin\", node,\n6199: +\t\t\t\tclabwire.processes[node], clabwire.stdinClosed[node])\n6200: +\t\t}\n6201: +\t}\n6202: +}\n6203: +\n6204: +// TestCaptureRejectsAClabwireWithoutStopOnStdinClose turns the usage error of an older clabwire\n6205: +// into the release error.\n6206: +func TestCaptureRejectsAClabwireWithoutStopOnStdinClose(t *testing.T) {\n6207: +\tt.Parallel()\n6208: +\n6209: +\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n6210: +\tclabwire.stderrOnly = \"flag provided but not defined: -stop-on-stdin-close\"\n6211: +\n6212: +\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n6213: +\t\tName: \"lab1\", Targets: []clablabruntime.CaptureTarget{{Node: \"r2\", Interface: \"e1-1\"}},\n6214: +\t\tDuration: time.Second,\n6215: +\t}, io.Discard)\n6216: +\tif !errors.Is(err, clablabruntime.ErrUnsupportedRuntimeVersion) ||\n6217: +\t\t!strings.Contains(err.Error(), \"clabwire in pod lab-ns/lab1-r2-def does not accept \"+\n6218: +\t\t\t\"packet-capture --stop-on-stdin-close\") ||\n6219: +\t\t!strings.Contains(err.Error(), \"(0.11 or newer)\") {\n6220: +\t\tt.Fatalf(\"Capture() = %v, want the release error\", err)\n6221: +\t}\n6222: +}\n6223: +\n6224: +// requireTimeOrdered checks that the merged stream's timestamps never decrease.\n6225: +func requireTimeOrdered(t *testing.T, packets []clabcapture.Packet) {\n6226: +\tt.Helper()\n6227: +\n6228: +\tfor idx := 1; idx < len(packets); idx++ {\n6229: +\t\tif packets[idx].Timestamp < packets[idx-1].Timestamp {\n6230: +\t\t\tt.Fatalf(\"packet %d (%s) at %d precedes packet %d (%s) at %d\", idx,\n6231: +\t\t\t\tpacketOrigin(packets[idx]), packets[idx].Timestamp, idx-1,\n6232: +\t\t\t\tpacketOrigin(packets[idx-1]), packets[idx-1].Timestamp)\n6233: +\t\t}\n6234: +\t}\n6235: +}\n6236: +\n6237: +// TestCaptureMergesNodesInTimestampOrder merges two nodes whose streams arrive with different\n6238: +// delays: r2's packets are stamped 60 ms before they reach containerlab. The reorder window puts\n6239: +// them in order; without it they are not.\n6240: +func TestCaptureMergesNodesInTimestampOrder(t *testing.T) {\n6241: +\tt.Parallel()\n6242: +\n6243: +\tfor _, reorder := range []bool{true, false} {\n6244: +\t\tt.Run(fmt.Sprintf(\"reorder=%v\", reorder), func(t *testing.T) {\n6245: +\t\t\tt.Parallel()\n6246: +\n6247: +\t\t\tr, clabwire := captureTestRuntime(t, 5*time.Millisecond)\n6248: +\t\t\tclabwire.stampSkew[\"r2\"] = 60 * time.Millisecond\n6249: +\t\t\tif !reorder {\n6250: +\t\t\t\tr.captureReorderWindow = -1\n6251: +\t\t\t}\n6252: +\n6253: +\t\t\tvar out bytes.Buffer\n6254: +\t\t\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n6255: +\t\t\t\tName: \"lab1\",\n6256: +\t\t\t\tTargets: []clablabruntime.CaptureTarget{\n6257: +\t\t\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n6258: +\t\t\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n6259: +\t\t\t\t},\n6260: +\t\t\t\tDuration: 500 * time.Millisecond,\n6261: +\t\t\t}, &out)\n6262: +\t\t\tif err != nil {\n6263: +\t\t\t\tt.Fatal(err)\n6264: +\t\t\t}\n6265: +\n6266: +\t\t\tpackets := parseCapture(t, out.Bytes()).packets\n6267: +\t\t\tordered := slices.IsSortedFunc(packets, func(a, b clabcapture.Packet) int {\n6268: +\t\t\t\treturn int(a.Timestamp - b.Timestamp)\n6269: +\t\t\t})\n6270: +\t\t\tif reorder {\n6271: +\t\t\t\trequireTimeOrdered(t, packets)\n6272: +\t\t\t} else if ordered {\n6273: +\t\t\t\tt.Fatal(\"the skewed streams came out ordered without the reorder window\")\n6274: +\t\t\t}\n6275: +\t\t})\n6276: +\t}\n6277: +}\n6278: +\n6279: +// TestCaptureChainsSeveralNodesInOrderWithoutDuplicates chains two nodes with skewed streams and a\n6280: +// reorder window shorter than a segment switch:\n6281: +// every tick appears exactly once per interface and the merged stream stays in timestamp order\n6282: +// across every segment switch, while old segments are ended through stdin at the switch.\n6283: +func TestCaptureChainsSeveralNodesInOrderWithoutDuplicates(t *testing.T) {\n6284: +\tt.Parallel()\n6285: +\n6286: +\tr, clabwire := captureTestRuntime(t, 4*time.Millisecond)\n6287: +\tr.captureSegment = 300 * time.Millisecond\n6288: +\t// a window shorter than a switch: the chains' holds keep the order across the switches\n6289: +\tr.captureReorderWindow = 15 * time.Millisecond\n6290: +\tclabwire.stampSkew[\"r2\"] = 5 * time.Millisecond\n6291: +\t// r2 switches segments 120 ms after r1, so one chain streams live while the other holds\n6292: +\tclabwire.firstStartDelay[\"r2\"] = 120 * time.Millisecond\n6293: +\n6294: +\tvar gaps []clablabruntime.CaptureGap\n6295: +\tvar out bytes.Buffer\n6296: +\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n6297: +\t\tName: \"lab1\",\n6298: +\t\tTargets: []clablabruntime.CaptureTarget{\n6299: +\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n6300: +\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n6301: +\t\t},\n6302: +\t\tDuration: 1300 * time.Millisecond,\n6303: +\t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n6304: +\t}, &out)\n6305: +\tif err != nil {\n6306: +\t\tt.Fatal(err)\n6307: +\t}\n6308: +\tif len(gaps) != 0 {\n6309: +\t\tt.Fatalf(\"gaps = %+v\", gaps)\n6310: +\t}\n6311: +\n6312: +\tparsed := parseCapture(t, out.Bytes())\n6313: +\trequireTimeOrdered(t, parsed.packets)\n6314: +\tfor id := range uint32(2) {\n6315: +\t\tvar sequence []uint64\n6316: +\t\tfor _, packet := range parsed.packets {\n6317: +\t\t\tif packet.InterfaceID == id {\n6318: +\t\t\t\tsequence = append(sequence, packetSequence(packet))\n6319: +\t\t\t}\n6320: +\t\t}\n6321: +\t\tslices.Sort(sequence)\n6322: +\t\tif len(sequence) < 200 {\n6323: +\t\t\tt.Fatalf(\"interface %d has %d packets\", id, len(sequence))\n6324: +\t\t}\n6325: +\t\tfor idx := 1; idx < len(sequence); idx++ {\n6326: +\t\t\tif sequence[idx] != sequence[idx-1]+1 {\n6327: +\t\t\t\tt.Fatalf(\"interface %d: tick %d followed by %d\", id, sequence[idx-1], sequence[idx])\n6328: +\t\t\t}\n6329: +\t\t}\n6330: +\t}\n6331: +\n6332: +\tclabwire.mu.Lock()\n6333: +\tdefer clabwire.mu.Unlock()\n6334: +\tfor _, node := range []string{\"r1\", \"r2\"} {\n6335: +\t\tif clabwire.processes[node] < 4 || clabwire.stdinClosed[node] == 0 {\n6336: +\t\t\tt.Fatalf(\"%s: %d processes, %d stopped through stdin at a switch\", node,\n6337: +\t\t\t\tclabwire.processes[node], clabwire.stdinClosed[node])\n6338: +\t\t}\n6339: +\t}\n6340: +}\n6341: +\n6342: +func TestCaptureReorderWindowKnob(t *testing.T) {\n6343: +\tcases := map[string]time.Duration{\n6344: +\t\t\"\":      250 * time.Millisecond,\n6345: +\t\t\"0\":     0,\n6346: +\t\t\"75ms\":  75 * time.Millisecond,\n6347: +\t\t\"bogus\": 250 * time.Millisecond,\n6348: +\t}\n6349: +\tfor value, want := range cases {\n6350: +\t\tt.Setenv(envCaptureReorderWindow, value)\n6351: +\t\tr := &Runtime{captureReorderWindow: captureReorderWindowFromEnv()}\n6352: +\t\tif got := r.captureReorderWindowLength(); got != want {\n6353: +\t\t\tt.Errorf(\"%s=%q: window %s, want %s\", envCaptureReorderWindow, value, got, want)\n6354: +\t\t}\n6355: +\t}\n6356: +}\n6357: diff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go\n6358: index 3c556e7..e869191 100644\n6359: --- a/labruntime/clabernetes/clabernetes.go\n6360: +++ b/labruntime/clabernetes/clabernetes.go\n6361: @@ -84,10 +84,18 @@ type Runtime struct {\n6362:  \t// identity is the configured identity of calls without one; in a connected view it is the\n6363:  \t// identity the clients impersonate.\n6364:  \tidentity clablabruntime.Identity\n6365:  \t// pollInterval overrides how often waits poll the cluster (tests).\n6366:  \tpollInterval time.Duration\n6367: +\t// podExec overrides how commands run in pod containers (tests).\n6368: +\tpodExec podExecFunc\n6369: +\t// captureSegment is the length of one chained packet capture; zero uses the clabwire\n6370: +\t// maximum of one hour.\n6371: +\tcaptureSegment time.Duration\n6372: +\t// captureReorderWindow is how long the merged capture stream holds packets back to write\n6373: +\t// them in timestamp order: zero uses the default, a negative value disables reordering.\n6374: +\tcaptureReorderWindow time.Duration\n6375:  \t// support checks once per runtime instance, before the first cluster call, that the\n6376:  \t// cluster runs a clabernetes release with the contract this runtime needs. Every view\n6377:  \t// shares it. It is nil when the clients were injected (tests).\n6378:  \tsupport *supportCheck\n6379:  }\n6380: @@ -253,7 +261,9 @@ func New(cfg clablabruntime.Config) (clablabruntime.LabRuntime, error) {\n6381:  \t\ttimeout:              cfg.Timeout,\n6382:  \t\tkindLinkApplyMode:    cfg.KindLinkApplyMode,\n6383:  \t\tidentity:             cfg.Identity,\n6384:  \t\tclients:              newClientLoader(),\n6385:  \t\tsupport:              &supportCheck{},\n6386: +\t\tcaptureSegment:       captureSegmentFromEnv(),\n6387: +\t\tcaptureReorderWindow: captureReorderWindowFromEnv(),\n6388:  \t}, nil\n6389:  }\n6390: diff --git a/labruntime/runtime.go b/labruntime/runtime.go\n6391: index 76e651c..367565d 100644\n6392: --- a/labruntime/runtime.go\n6393: +++ b/labruntime/runtime.go\n6394: @@ -387,10 +387,80 @@ type NodeLogStreamer interface {\n6395:  // exactly one node. Closing the connection closes the stream.\n6396:  type NodePortForwarder interface {\n6397:  \tDialPort(ctx context.Context, req NodeRequest, port int) (net.Conn, error)\n6398:  }\n6399:  \n6400: +// CaptureInterface is a lab link interface packet capture accepts, with the far end of its link.\n6401: +type CaptureInterface struct {\n6402: +\t// Node is the node name as the topology spells it.\n6403: +\tNode string `json:\"node\"`\n6404: +\t// Interface is the interface name inside the node, which capture output carries.\n6405: +\tInterface string `json:\"interface\"`\n6406: +\t// Alias is the name the topology used for the interface when the node kind maps it (for\n6407: +\t// example ethernet-1/1 for SR Linux e1-1). Capture targets accept either name.\n6408: +\tAlias string `json:\"alias,omitempty\"`\n6409: +\t// PeerNode is the node at the other end of the link, \"host\" for a host endpoint, or empty\n\n(Output capped at 50 KB. Showing lines 4780-6409. Use offset=6410 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+\tmore, err := c.capture.emit(c.group.ids[packet.InterfaceID], packet)\n+\n+\treturn !more, err\n+}\n+\n+// switchSegments makes the next segment the active one after the active one ended, writing the\n+// held packets of the next one that the active one did not write.\n+func (c *captureChain) switchSegments(ctx context.Context, timer *time.Timer) (bool, error) {\n+\t// the held packets are in the reorder buffer once this returns\n+\tdefer c.capture.out.Release(c)\n+\n+\tended := c.active\n+\tif c.stopping && c.next != nil && c.next.started.IsZero() {\n+\t\t// the chain is stopping: a follow-up that has not started takes nothing over\n+\t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n+\t}\n+\tif c.final && c.next == nil {\n+\t\treturn true, nil\n+\t}\n+",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+\tmore, err := c.capture.emit(c.group.ids[packet.InterfaceID], packet)\n+\n+\treturn !more, err\n+}\n+\n+// switchSegments makes the next segment the active one after the active one ended, writing the\n+// held packets of the next one that the active one did not write.\n+func (c *captureChain) switchSegments(ctx context.Context, timer *time.Timer) (bool, error) {\n+\t// the held packets are in the reorder buffer once this returns\n+\tdefer c.capture.out.Release(c)\n+\n+\tended := c.active\n+\tif c.stopping && c.next != nil && c.next.started.IsZero() {\n+\t\t// the chain is stopping: a follow-up that has not started takes nothing over\n+\t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n+\t}\n+\tif c.final && c.next == nil {\n+\t\treturn true, nil\n+\t}\n+\n+\tif c.next == nil || c.next.started.IsZero() || c.cut == 0 {\n+\t\tfrom := ended.ended\n+\t\tif from.IsZero() {\n+\t\t\tfrom = ended.plannedEnd()\n+\t\t}\n+\t\tgap := clablabruntime.CaptureGap{\n+\t\t\tNode: c.group.display, Interfaces: c.group.interfaces, From: from,\n+\t\t\tReason: \"the follow-up capture did not overlap the previous one\",\n+\t\t}\n+\t\tif c.next != nil && !c.next.started.IsZero() {\n+\t\t\tgap.To = c.next.started\n+\t\t}\n+\t\tc.capture.reportGap(gap)\n+\t}\n+\n+\tif c.next != nil && c.next.done && !c.stopping {\n+\t\t// the follow-up already ended (it started too late to take over): keep what it\n+\t\t// captured and continue with a fresh segment\n+\t\tfor _, packet := range c.held {\n+\t\t\tif stop, err := c.emit(packet); stop || err != nil {\n+\t\t\t\treturn true, err\n+\t\t\t}\n+\t\t}\n+\t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n+\t}\n+\n+\tif c.next == nil {\n+\t\tif !c.capture.deadline.IsZero() &&\n+\t\t\t!time.Now().Before(c.capture.deadline.Add(-c.capture.window)) {\n+\t\t\treturn true, nil\n+\t\t}\n+\t\tc.active = c.start(ctx, c.segmentDuration(time.Now()))\n+\t\tresetTimer(timer, c.nextStartIn())\n+\n+\t\treturn false, nil\n+\t}\n+\n+\twindow := c.capture.window.Nanoseconds()\n+\tfor _, packet := range c.held {\n+\t\tif c.cut != 0 {\n+\t\t\tif packet.Timestamp < c.cut-window {\n+\t\t\t\tcontinue\n+\t\t\t}\n+\t\t\tif packet.Timestamp < c.cut+window {\n+\t\t\t\tkey := packetKey(packet)\n+\t\t\t\tif c.emitted[key] > 0 {\n+\t\t\t\t\tc.emitted[key]--\n+\t\t\t\t\tcontinue\n+\t\t\t\t}\n+\t\t\t}\n+\t\t}\n+\t\tif stop, err := c.emit(packet); stop || err != nil {\n+\t\t\treturn true, err\n+\t\t}\n+\t}\n+\n+\tc.active, c.next = c.next, nil\n+\tc.held, c.emitted, c.cut = nil, nil, 0\n+\tif c.active.done {\n+\t\t// the chain is stopping and the follow-up ended before the active one\n+\t\treturn true, nil\n+\t}\n+\tresetTimer(timer, c.nextStartIn())\n+\n+\treturn false, nil\n+}\n+\n+func resetTimer(timer *time.Timer, d time.Duration) {\n+\tif !timer.Stop() {\n+\t\tselect {\n+\t\tcase <-timer.C:\n+\t\tdefault:\n+\t\t}\n+\t}\n+\ttimer.Reset(d)\n+}\n+\n+// packetKey identifies a packet by its interface and content.\n+func packetKey(packet *clabcapture.Packet) uint64 {\n+\thash := fnv.New64a()\n+\tvar id [4]byte\n+\tid[0] = byte(packet.InterfaceID)\n+\tid[1] = byte(packet.InterfaceID >> 8)\n+\t_, _ = hash.Write(id[:])\n+\t_, _ = hash.Write(packet.Data)\n+\n+\treturn hash.Sum64()\n+}\n+\n+// start runs one clabwire capture and reports its packets, audit records and end as events.\n+func (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {\n+\tsegmentCtx, cancel := context.WithCancel(ctx)\n+\tstdinReader, stdinWriter := io.Pipe()\n+\tsegment := &captureSegment{\n+\t\tindex: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,\n+\t\tcloseStdin: func() { _ = stdinWriter.Close() },\n+\t}\n+\tc.segments++\n+\n+\tcommand := []string{\n+\t\tclabwireManager, \"node-runtime\", \"packet-capture\",\n+\t\t\"--nodeName\", c.group.location.NodeName,\n+\t\t\"--format\", \"pcapng\",\n+\t\t\"--snapLength\", strconv.Itoa(c.capture.req.SnapLength),\n+\t\t\"--duration\", duration.String(),\n+\t\tclabwireStopOnStdinClose,\n+\t}\n+\tfor _, name := range c.group.interfaces {\n+\t\tcommand = append(command, \"--interface\", name)\n+\t}\n+\tif c.capture.req.PacketLimit > 0 {\n+\t\tremaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()\n+\t\tcommand = append(command, \"--packetLimit\",\n+\t\t\tstrconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))\n+\t}\n+\n+\tsend := func(event segmentEvent) {\n+\t\tevent.segment = segment\n+\t\tselect {\n+\t\tcase c.events <- event:\n+\t\tcase <-segmentCtx.Done():\n+\t\t}\n+\t}\n+\n+\tstdoutReader, stdoutWriter := io.Pipe()\n+\tstderr := &auditLineWriter{send: func(audit *captureAudit) { send(segmentEvent{audit: audit}) }}\n+\n+\t// The exec outlives the segment's context by up to captureStdinCloseGrace: when the segment\n+\t// ends for any reason (the capture is cancelled or failed, the output failed, or a newer\n+\t// segment took over), its stdin is closed first so clabwire ends on its own, and the stream\n+\t// is cut only if it does not.\n+\texecCtx, cancelExec := context.WithCancel(context.WithoutCancel(segmentCtx))\n+\texecDone := make(chan struct{})\n+\n+\tc.wg.Add(3)\n+\treadDone := make(chan error, 1)\n+\tgo func() {\n+\t\tdefer c.wg.Done()\n+\t\treadDone <- c.readSegment(stdoutReader, func(packet *clabcapture.Packet) {\n+\t\t\tsend(segmentEvent{packet: packet})\n+\t\t})\n+\t\t_, _ = io.Copy(io.Discard, stdoutReader)\n+\t}()\n+\tgo func() {\n+\t\tdefer c.wg.Done()\n+\t\tselect {\n+\t\tcase <-execDone:\n+\t\t\treturn\n+\t\tcase <-segmentCtx.Done():\n+\t\t}\n+\t\tsegment.closeStdin()\n+\t\tgrace := time.NewTimer(captureStdinCloseGrace)\n+\t\tdefer grace.Stop()\n+\t\tselect {\n+\t\tcase <-execDone:\n+\t\tcase <-grace.C:\n+\t\t\tlog.Debug(\"Capture segment did not end after its stdin closed, cutting the stream\",\n+\t\t\t\t\"node\", c.group.display, \"segment\", segment.index)\n+\t\t\tcancelExec()\n+\t\t}\n+\t}()\n+\tgo func() {\n+\t\tdefer c.wg.Done()\n+\t\tdefer cancel()\n+\t\tdefer cancelExec()\n+\n+\t\terr := c.capture.r.execInPodContainer()(execCtx, c.group.location.Namespace,\n+\t\t\tc.group.location.Pod, clabwireContainer, command, stdinReader, stdoutWriter, stderr)\n+\t\tclose(execDone)\n+\t\t// the process ended: release the stdin copy of the exec stream\n+\t\tsegment.closeStdin()\n+\t\t_ = stdoutWriter.Close()\n+\t\treadErr := <-readDone\n+\t\tstderr.flush()\n+\t\tif err == nil && readErr != nil {\n+\t\t\terr = readErr\n+\t\t}\n+\t\tif err != nil && stderr.text() != \"\" {\n+\t\t\tif unsupported := unsupportedClabwire(\n+\t\t\t\tc.group.location,\n+\t\t\t\tstderr.text(),\n+\t\t\t); unsupported != nil {\n+\t\t\t\terr = unsupported\n+\t\t\t} else {\n+\t\t\t\terr = fmt.Errorf(\"%w: %s\", err, stderr.text())\n+\t\t\t}\n+\t\t}\n+\t\tsend(segmentEvent{done: true, err: err})\n+\t}()\n+\n+\treturn segment\n+}\n+\n+// unsupportedClabwire recognizes a clabwire that rejects --stop-on-stdin-close, which every\n+// capture passes: its release predates the capture contract the runtime needs.\n+func unsupportedClabwire(location clablabruntime.NodeLocation, stderr string) error {\n+\tif !strings.Contains(stderr, \"flag provided but not defined\") ||\n+\t\t!strings.Contains(stderr, strings.TrimPrefix(clabwireStopOnStdinClose, \"-\")) {\n+\t\treturn nil\n+\t}\n+\n+\treturn &unsupportedClabernetesError{reason: fmt.Sprintf(\n+\t\t\"clabwire in pod %s/%s does not accept packet-capture %s\",\n+\t\tlocation.Namespace, location.Pod, clabwireStopOnStdinClose)}\n+}\n+\n+// readSegment checks that a segment's interfaces are the requested ones and passes its packets\n+// on with the segment's interface index.\n+func (c *captureChain) readSegment(stdout io.Reader, packet func(*clabcapture.Packet)) error {\n+\treader := clabcapture.NewReader(stdout)\n+\tinterfaces := 0\n+\tfor {\n+\t\tevent, err := reader.Next()\n+\t\tif errors.Is(err, io.EOF) {\n+\t\t\treturn nil\n+\t\t}\n+\t\tif errors.Is(err, io.ErrUnexpectedEOF) {\n+\t\t\t// the process was stopped inside a block\n+\t\t\treturn nil\n+\t\t}\n+\t\tif err != nil {\n+\t\t\treturn fmt.Errorf(\"failed to read the clabwire capture: %w\", err)\n+\t\t}\n+\t\tif event.Interface != nil {\n+\t\t\tif interfaces >= len(c.group.interfaces) ||\n+\t\t\t\tevent.Interface.Name != c.group.interfaces[interfaces] {\n+\t\t\t\treturn fmt.Errorf(\"clabwire described interface %q, want %s in order\",\n+\t\t\t\t\tevent.Interface.Name, strings.Join(c.group.interfaces, \", \"))\n+\t\t\t}\n+\t\t\tinterfaces++\n+\t\t\tcontinue\n+\t\t}\n+\t\tif event.Packet != nil {\n+\t\t\tpacket(event.Packet)\n+\t\t}\n+\t}\n+}\n+\n+// auditLineWriter parses clabwire's stderr: audit records go to send, other lines are kept for\n+// error messages.\n+type auditLineWriter struct {\n+\tsend func(*captureAudit)\n+\n+\tmu      sync.Mutex\n+\tpartial []byte\n+\tother   []string\n+}\n+\n+func (w *auditLineWriter) Write(data []byte) (int, error) {\n+\tw.mu.Lock()\n+\tw.partial = append(w.partial, data...)\n+\tvar lines [][]byte\n+\tfor {\n+\t\tidx := bytes.IndexByte(w.partial, '\\n')\n+\t\tif idx < 0 {\n+\t\t\tbreak\n+\t\t}\n+\t\tlines = append(lines, append([]byte(nil), w.partial[:idx]...))\n+\t\tw.partial = w.partial[idx+1:]\n+\t}\n+\tw.mu.Unlock()\n+\n+\tfor _, line := range lines {\n+\t\tw.line(line)\n+\t}\n+\n+\treturn len(data), nil\n+}\n+\n+func (w *auditLineWriter) flush() {\n+\tw.mu.Lock()\n+\tline := w.partial\n+\tw.partial = nil\n+\tw.mu.Unlock()\n+\tif len(bytes.TrimSpace(line)) != 0 {\n+\t\tw.line(line)\n+\t}\n+}\n+\n+func (w *auditLineWriter) line(line []byte) {\n+\tline = bytes.TrimSpace(line)\n+\tif len(line) == 0 {\n+\t\treturn\n+\t}\n+\n+\tvar audit captureAudit\n+\tif err := json.Unmarshal(\n+\t\tline,\n+\t\t&audit,\n+\t); err == nil &&\n+\t\taudit.SchemaVersion == captureAuditSchema {\n+\t\tw.send(&audit)\n+\t\treturn\n+\t}\n+\n+\tw.mu.Lock()\n+\tdefer w.mu.Unlock()\n+\tif len(w.other) < 20 {\n+\t\tw.other = append(w.other, string(line))\n+\t}\n+}\n+\n+func (w *auditLineWriter) text() string {\n+\tw.mu.Lock()\n+\tdefer w.mu.Unlock()\n+\n+\treturn strings.Join(w.other, \"; \")\n+}\ndiff --git a/labruntime/clabernetes/capture_interfaces.go b/labruntime/clabernetes/capture_interfaces.go\nnew file mode 100644\nindex 0000000..21029ed\n--- /dev/null\n+++ b/labruntime/clabernetes/capture_interfaces.go\n@@ -0,0 +1,187 @@\n+package clabernetes\n+\n+import (\n+\t\"bytes\"\n+\t\"context\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"sort\"\n+\t\"sync\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tclabtypes \"github.com/srl-labs/containerlab/types\"\n+\tcorev1 \"k8s.io/api/core/v1\"\n+\t\"k8s.io/client-go/kubernetes/scheme\"\n+\t\"k8s.io/client-go/tools/remotecommand\"\n+\tkubeexec \"k8s.io/client-go/util/exec\"\n+)\n+\n+// streamPodExec runs a command in a pod container without a terminal and streams its stdout\n+// and stderr. A non-nil stdin is attached: when it ends, the process's stdin is closed (the\n+// websocket v5 close signal, or a half-closed SPDY stream). A nonzero exit returns a\n+// *labruntime.CommandExitError.\n+func (r *Runtime) streamPodExec(\n+\tctx context.Context,\n+\tnamespace, pod, container string,\n+\tcommand []string,\n+\tstdin io.Reader,\n+\tstdout, stderr io.Writer,\n+) error {\n+\texecURL := r.kubeClient.CoreV1().RESTClient().Post().\n+\t\tResource(\"pods\").\n+\t\tName(pod).\n+\t\tNamespace(namespace).\n+\t\tSubResource(\"exec\").\n+\t\tVersionedParams(&corev1.PodExecOptions{\n+\t\t\tContainer: container,\n+\t\t\tCommand:   command,\n+\t\t\tStdin:     stdin != nil,\n+\t\t\tStdout:    stdout != nil,\n+\t\t\tStderr:    stderr != nil,\n+\t\t}, scheme.ParameterCodec).URL()\n+\n+\texecutor, err := r.newExecutor(execURL)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\t// client-go reports streams cut by a cancelled context through the context's logger; a\n+\t// capture ends that way on purpose, so it goes to the debug log\n+\terr = executor.StreamWithContext(withKubernetesClientDebugLogs(ctx),\n+\t\tremotecommand.StreamOptions{\n+\t\t\tStdin:  stdin,\n+\t\t\tStdout: stdout,\n+\t\t\tStderr: stderr,\n+\t\t})\n+\n+\tvar exitErr kubeexec.ExitError\n+\tif errors.As(err, &exitErr) {\n+\t\treturn &clablabruntime.CommandExitError{Code: exitErr.ExitStatus()}\n+\t}\n+\tif err != nil {\n+\t\treturn fmt.Errorf(\"failed to execute command in pod %s/%s container %s: %w\",\n+\t\t\tnamespace, pod, container, err)\n+\t}\n+\n+\treturn nil\n+}\n+\n+// InspectInterfaces lists the capturable link interfaces of the requested nodes, or of every\n+// running node, in the shape of `inspect interfaces`: per node (named <lab>-<node> like in\n+// inspect), the interface and its alias as clabwire reports them, and the MAC address, index,\n+// MTU and operational state read from sysfs in the device container. A node whose device\n+// container has no shell reports its interfaces without these attributes.\n+func (r *Runtime) InspectInterfaces(\n+\tctx context.Context,\n+\treq clablabruntime.NodeRequest,\n+) ([]*clabtypes.ContainerInterfaces, error) {\n+\tr, err := r.connect(ctx, req.Identity)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n+\t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n+\t})\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\trunning := make([]clablabruntime.NodeLocation, 0, len(locations))\n+\tfor _, location := range locations {\n+\t\tif location.Pod == \"\" {\n+\t\t\tlog.Warn(\"Skipping interface detection of a node that does not run\",\n+\t\t\t\t\"node\", location.NodeName)\n+\t\t\tcontinue\n+\t\t}\n+\t\trunning = append(running, location)\n+\t}\n+\n+\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, running)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tstates := r.sampleInterfaceStates(ctx, running)\n+\n+\tresult := make([]*clabtypes.ContainerInterfaces, 0, len(running))\n+\tfor _, location := range running {\n+\t\tcontainer := &clabtypes.ContainerInterfaces{\n+\t\t\tContainerName: req.Name + \"-\" + location.NodeName,\n+\t\t\tInterfaces:    []*clabtypes.ContainerInterfaceDetails{},\n+\t\t}\n+\t\tfor _, entry := range listed[location.NodeName] {\n+\t\t\tdetails := &clabtypes.ContainerInterfaceDetails{\n+\t\t\t\tInterfaceName:  entry.Interface,\n+\t\t\t\tInterfaceAlias: entry.Alias,\n+\t\t\t\t// clabwire realizes every lab link interface as a veth pair\n+\t\t\t\tInterfaceType: \"veth\",\n+\t\t\t}\n+\t\t\tif state, ok := states[location.NodeName][entry.Interface]; ok {\n+\t\t\t\tdetails.InterfaceMAC = state.MAC\n+\t\t\t\tdetails.InterfaceIndex = state.Index\n+\t\t\t\tdetails.InterfaceMTU = state.MTU\n+\t\t\t\tdetails.InterfaceState = state.OperState\n+\t\t\t}\n+\t\t\tcontainer.Interfaces = append(container.Interfaces, details)\n+\t\t}\n+\t\tsort.Slice(container.Interfaces, func(i, j int) bool {\n+\t\t\treturn container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName\n+\t\t})\n+\t\tresult = append(result, container)\n+\t}\n+\tsort.Slice(result, func(i, j int) bool {\n+\t\treturn result[i].ContainerName < result[j].ContainerName\n+\t})\n+\n+\treturn result, nil\n+}\n+\n+// sampleInterfaceStates reads the sysfs interface attributes of every node's device container,\n+// one exec per node, with the script the interface events use.\n+func (r *Runtime) sampleInterfaceStates(\n+\tctx context.Context,\n+\tlocations []clablabruntime.NodeLocation,\n+) map[string]map[string]c9sIfaceState {\n+\tvar mu sync.Mutex\n+\tresult := map[string]map[string]c9sIfaceState{}\n+\n+\tvar wg sync.WaitGroup\n+\tworkers := make(chan struct{}, interfaceSampleWorkers)\n+\texec := r.execInPodContainer()\n+\tfor _, location := range locations {\n+\t\twg.Add(1)\n+\t\tgo func() {\n+\t\t\tdefer wg.Done()\n+\t\t\tworkers <- struct{}{}\n+\t\t\tdefer func() { <-workers }()\n+\n+\t\t\tvar stdout, stderr bytes.Buffer\n+\t\t\terr := exec(ctx, location.Namespace, location.Pod, location.Container,\n+\t\t\t\t[]string{\"sh\", \"-c\", interfaceSampleScript}, nil, &stdout, &stderr)\n+\t\t\tif err != nil {\n+\t\t\t\tlog.Debug(\"Cannot read the interface state of a c9s node\",\n+\t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n+\t\t\t\treturn\n+\t\t\t}\n+\t\t\t_, ifaces, _, err := parseInterfaceSample(stdout.Bytes())\n+\t\t\tif err != nil {\n+\t\t\t\tlog.Debug(\"Cannot parse the interface state of a c9s node\",\n+\t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n+\t\t\t\treturn\n+\t\t\t}\n+\n+\t\t\tbyName := make(map[string]c9sIfaceState, len(ifaces))\n+\t\t\tfor _, iface := range ifaces {\n+\t\t\t\tbyName[iface.Name] = iface\n+\t\t\t}\n+\t\t\tmu.Lock()\n+\t\t\tresult[location.NodeName] = byName\n+\t\t\tmu.Unlock()\n+\t\t}()\n+\t}\n+\twg.Wait()\n+\n+\treturn result\n+}\ndiff --git a/labruntime/clabernetes/capture_test.go b/labruntime/clabernetes/capture_test.go\nnew file mode 100644\nindex 0000000..16628b5\n--- /dev/null\n+++ b/labruntime/clabernetes/capture_test.go\n@@ -0,0 +1,1050 @@\n+package clabernetes\n+\n+import (\n+\t\"bytes\"\n+\t\"context\"\n+\t\"encoding/binary\"\n+\t\"encoding/json\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"slices\"\n+\t\"strings\"\n+\t\"sync\"\n+\t\"testing\"\n+\t\"time\"\n+\n+\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tcorev1 \"k8s.io/api/core/v1\"\n+\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n+\t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n+\tk8sruntime \"k8s.io/apimachinery/pkg/runtime\"\n+)\n+\n+func captureTestNode(name, original, container string) *unstructured.Unstructured {\n+\tlabels := map[string]any{labelTopologyOwner: \"lab1\"}\n+\tif original != \"\" {\n+\t\tlabels[labelOriginalNodeName] = original\n+\t}\n+\n+\treturn &unstructured.Unstructured{Object: map[string]any{\n+\t\t\"apiVersion\": c9sAPIVersion,\n+\t\t\"kind\":       \"Node\",\n+\t\t\"metadata\": map[string]any{\n+\t\t\t\"name\": name, \"namespace\": \"lab-ns\", \"uid\": \"uid-\" + name, \"labels\": labels,\n+\t\t},\n+\t\t\"spec\": map[string]any{\"kind\": \"srl\", \"runState\": nodeRunStateRunning},\n+\t\t\"status\": map[string]any{\n+\t\t\t\"readiness\":        \"ready\",\n+\t\t\t\"directContainers\": []any{map[string]any{\"name\": container, \"id\": name}},\n+\t\t},\n+\t}}\n+}\n+\n+func captureTestPod(name, node string) *corev1.Pod {\n+\treturn &corev1.Pod{\n+\t\tObjectMeta: metav1.ObjectMeta{\n+\t\t\tName: name, Namespace: \"lab-ns\",\n+\t\t\tLabels: map[string]string{\n+\t\t\t\tlabelApp: clabernetesAppValue, labelTopologyOwner: \"lab1\", labelTopologyNode: node,\n+\t\t\t},\n+\t\t},\n+\t\tStatus: corev1.PodStatus{Phase: corev1.PodRunning},\n+\t}\n+}\n+\n+// captureListing is the --list-interfaces output of each pod.\n+var captureListing = map[string][]clabwireInterface{ //nolint:gochecknoglobals\n+\t\"lab1-r1-abc\": {\n+\t\t{\n+\t\t\tNode:          \"r1\",\n+\t\t\tInterface:     \"e1-1\",\n+\t\t\tAlias:         \"ethernet-1/1\",\n+\t\t\tPeerNode:      \"r2\",\n+\t\t\tPeerInterface: \"ethernet-1/1\",\n+\t\t},\n+\t\t{Node: \"r1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"r1-e1-2\"},\n+\t},\n+\t\"lab1-r2-def\": {\n+\t\t{\n+\t\t\tNode:          \"r2\",\n+\t\t\tInterface:     \"e1-1\",\n+\t\t\tAlias:         \"ethernet-1/1\",\n+\t\t\tPeerNode:      \"r1\",\n+\t\t\tPeerInterface: \"ethernet-1/1\",\n+\t\t},\n+\t},\n+}\n+\n+// fakeClabwire plays clabwire packet-capture and --list-interfaces in the fake pod exec. Every\n+// capture process sees the same traffic: one packet per tick on each requested interface,\n+// carrying the tick number, stamped with the tick time plus a per-process jitter (clabwire stamps\n+// packets when it reads them).\n+type fakeClabwire struct {\n+\tt     *testing.T\n+\tepoch time.Time\n+\ttick  time.Duration\n+\n+\tmu       sync.Mutex\n+\tcommands [][]string\n+\t// processes counts the capture processes started per node\n+\tprocesses map[string]int\n+\n+\t// startDelay delays the Started record of the given process index (all nodes).\n+\tstartDelay map[int]time.Duration\n+\t// firstStartDelay delays the Started record of a node's first process.\n+\tfirstStartDelay map[string]time.Duration\n+\t// fail makes a process write this audit status and exit 1.\n+\tfail string\n+\t// stderrOnly makes a process write this text to stderr and exit 1, like a clabwire that\n+\t// rejects a flag.\n+\tstderrOnly string\n+\t// stampSkew stamps the packets of a node this much earlier, as if its stream reached\n+\t// containerlab this much later than the others.\n+\tstampSkew map[string]time.Duration\n+\t// stdinClosed counts the processes that ended because their stdin closed, per node.\n+\tstdinClosed map[string]int\n+\t// written counts the packets written to stdout, per node.\n+\twritten map[string]int\n+\t// sysfs is the device container's interface sample.\n+\tsysfs string\n+}\n+\n+func newFakeClabwire(t *testing.T, tick time.Duration) *fakeClabwire {\n+\tt.Helper()\n+\n+\treturn &fakeClabwire{\n+\t\tt: t, epoch: time.Now(), tick: tick, processes: map[string]int{},\n+\t\tstartDelay: map[int]time.Duration{}, stampSkew: map[string]time.Duration{},\n+\t\tfirstStartDelay: map[string]time.Duration{},\n+\t\tstdinClosed:     map[string]int{},\n+\t\twritten:         map[string]int{},\n+\t}\n+}\n+\n+func (f *fakeClabwire) exec(\n+\tctx context.Context,\n+\tnamespace, pod, container string,\n+\tcommand []string,\n+\tstdin io.Reader,\n+\tstdout, stderr io.Writer,\n+) error {\n+\tf.mu.Lock()\n+\tf.commands = append(\n+\t\tf.commands,\n+\t\tappend([]string{namespace + \"/\" + pod + \"/\" + container}, command...),\n+\t)\n+\tf.mu.Unlock()\n+\n+\tif container != clabwireContainer {\n+\t\t_, _ = io.WriteString(stdout, f.sysfs)\n+\t\treturn nil\n+\t}\n+\tif slices.Contains(command, \"--list-interfaces\") {\n+\t\treturn json.NewEncoder(stdout).Encode(captureListing[pod])\n+\t}\n+\n+\treturn f.capture(ctx, command, stdin, stdout, stderr)\n+}\n+\n+func flagValues(command []string, name string) []string {\n+\tvar values []string\n+\tfor idx := 0; idx+1 < len(command); idx++ {\n+\t\tif command[idx] == name {\n+\t\t\tvalues = append(values, command[idx+1])\n+\t\t}\n+\t}\n+\n+\treturn values\n+}\n+\n+func (f *fakeClabwire) audit(\n+\tstderr io.Writer,\n+\tstatus, node string,\n+\tinterfaces []string,\n+\treason string,\n+) {\n+\trecord := map[string]any{\n+\t\t\"schemaVersion\": captureAuditSchema, \"time\": time.Now().UTC(), \"operation\": \"PacketCapture\",\n+\t\t\"status\": status, \"nodeName\": node, \"format\": \"pcapng\", \"reason\": reason,\n+\t}\n+\tentries := []map[string]any{}\n+\tfor _, name := range interfaces {\n+\t\tentries = append(entries, map[string]any{\"name\": name})\n+\t}\n+\trecord[\"interfaces\"] = entries\n+\tdata, _ := json.Marshal(record)\n+\t_, _ = stderr.Write(append(data, '\\n'))\n+}\n+\n+func (f *fakeClabwire) capture(\n+\tctx context.Context,\n+\tcommand []string,\n+\tstdin io.Reader,\n+\tstdout, stderr io.Writer,\n+) error {\n+\tf.mu.Lock()\n+\trejected := f.stderrOnly\n+\tf.mu.Unlock()\n+\tif rejected != \"\" {\n+\t\t_, _ = io.WriteString(stdout, \"Incorrect Usage: \"+rejected+\"\\n\\nNAME:\\n   manager\\n\")\n+\t\t_, _ = io.WriteString(stderr, rejected+\"\\n\")\n+\t\treturn &clablabruntime.CommandExitError{Code: 1}\n+\t}\n+\n+\t// clabwire ends the capture when stdin closes (--stop-on-stdin-close)\n+\tif !slices.Contains(command, clabwireStopOnStdinClose) || stdin == nil {\n+\t\tf.t.Errorf(\"capture without stdin and %s: %v\", clabwireStopOnStdinClose, command)\n+\t\treturn fmt.Errorf(\"no stdin\")\n+\t}\n+\tstdinClosed := make(chan struct{})\n+\tgo func() {\n+\t\t_, _ = io.Copy(io.Discard, stdin)\n+\t\tclose(stdinClosed)\n+\t}()\n+\n+\tnode := flagValues(command, \"--nodeName\")[0]\n+\tinterfaces := flagValues(command, \"--interface\")\n+\tduration, err := time.ParseDuration(flagValues(command, \"--duration\")[0])\n+\tif err != nil {\n+\t\tf.t.Errorf(\"duration: %v\", err)\n+\t}\n+\tif !slices.Equal(flagValues(command, \"--format\"), []string{\"pcapng\"}) {\n+\t\tf.t.Errorf(\"capture without --format pcapng: %v\", command)\n+\t}\n+\n+\tf.mu.Lock()\n+\tindex := f.processes[node]\n+\tf.processes[node]++\n+\tdelay := f.startDelay[index]\n+\tif index == 0 {\n+\t\tdelay += f.firstStartDelay[node]\n+\t}\n+\tfailure := f.fail\n+\tskew := f.stampSkew[node]\n+\tf.mu.Unlock()\n+\n+\tif failure != \"\" {\n+\t\tf.audit(stderr, failure, node, interfaces, \"interface \\\"eth9\\\" is not uniquely planned\")\n+\t\treturn &clablabruntime.CommandExitError{Code: 1}\n+\t}\n+\n+\tselect {\n+\tcase <-time.After(delay):\n+\tcase <-ctx.Done():\n+\t\treturn ctx.Err()\n+\tcase <-stdinClosed:\n+\t\tf.audit(stderr, captureAuditStarted, node, interfaces, \"\")\n+\t\tf.audit(stderr, captureAuditSucceeded, node, interfaces, \"client closed: stdin reached EOF\")\n+\t\treturn nil\n+\t}\n+\n+\twriter := clabcapture.NewWriter(stdout)\n+\tf.audit(stderr, captureAuditStarted, node, interfaces, \"\")\n+\tif err := writer.WriteHeader(interfaces, clabcapture.DefaultSnapLength); err != nil {\n+\t\treturn err\n+\t}\n+\n+\t// clabwire's own section header names it\n+\tend := time.Now().Add(duration)\n+\tjitter := time.Duration(index%3) * 7 * time.Microsecond\n+\tnext := time.Now().Sub(f.epoch)/f.tick + 1\n+\tfor {\n+\t\tat := f.epoch.Add(next * f.tick)\n+\t\tif at.After(end) {\n+\t\t\tbreak\n+\t\t}\n+\t\tselect {\n+\t\tcase <-ctx.Done():\n+\t\t\treturn ctx.Err()\n+\t\tcase <-stdinClosed:\n+\t\t\tf.mu.Lock()\n+\t\t\tf.stdinClosed[node]++\n+\t\t\tf.mu.Unlock()\n+\t\t\tf.audit(\n+\t\t\t\tstderr,\n+\t\t\t\tcaptureAuditSucceeded,\n+\t\t\t\tnode,\n+\t\t\t\tinterfaces,\n+\t\t\t\t\"client closed: stdin reached EOF\",\n+\t\t\t)\n+\t\t\treturn nil\n+\t\tcase <-time.After(time.Until(at)):\n+\t\t}\n+\t\tfor id := range interfaces {\n+\t\t\tdata := make([]byte, 64)\n+\t\t\tbinary.BigEndian.PutUint64(data[0:], uint64(next))\n+\t\t\tcopy(data[8:], node+\":\"+interfaces[id])\n+\t\t\tif err := writer.WritePacket(uint32(id), &clabcapture.Packet{ //nolint:gosec // small\n+\t\t\t\tTimestamp: at.Add(jitter - skew).UnixNano(), OriginalLength: 64, Data: data,\n+\t\t\t}); err != nil {\n+\t\t\t\treturn err\n+\t\t\t}\n+\t\t\tf.mu.Lock()\n+\t\t\tf.written[node]++\n+\t\t\tf.mu.Unlock()\n+\t\t}\n+\t\tnext++\n+\t}\n+\tf.audit(stderr, captureAuditSucceeded, node, interfaces, \"\")\n+\n+\treturn nil\n+}\n+\n+func (f *fakeClabwire) captureCommands() [][]string {\n+\tf.mu.Lock()\n+\tdefer f.mu.Unlock()\n+\n+\tvar result [][]string\n+\tfor _, command := range f.commands {\n+\t\tif slices.Contains(command, \"packet-capture\") &&\n+\t\t\t!slices.Contains(command, \"--list-interfaces\") {\n+\t\t\tresult = append(result, command)\n+\t\t}\n+\t}\n+\n+\treturn result\n+}\n+\n+// captureTestRuntime is lab1 in lab-ns with nodes r1 (topology name R1) and r2, each in its\n+// own pod, and a fake clabwire.\n+func captureTestRuntime(t *testing.T, tick time.Duration) (*Runtime, *fakeClabwire) {\n+\tt.Helper()\n+\n+\tr := newTestRuntimeWithKubeObjects(\n+\t\t[]*unstructured.Unstructured{\n+\t\t\tcaptureTestNode(\"r1\", \"R1\", \"node-r1-x\"),\n+\t\t\tcaptureTestNode(\"r2\", \"\", \"node-r2-x\"),\n+\t\t},\n+\t\t[]k8sruntime.Object{\n+\t\t\tcaptureTestPod(\"lab1-r1-abc\", \"r1\"),\n+\t\t\tcaptureTestPod(\"lab1-r2-def\", \"r2\"),\n+\t\t},\n+\t)\n+\tr.labNamespaceOverride = \"lab-ns\"\n+\tclabwire := newFakeClabwire(t, tick)\n+\tr.podExec = clabwire.exec\n+\n+\treturn r, clabwire\n+}\n+\n+// parsedCapture is a pcapng stream read back.\n+type parsedCapture struct {\n+\tsections   int\n+\tinterfaces []string\n+\tpackets    []clabcapture.Packet\n+}\n+\n+func parseCapture(t *testing.T, data []byte) parsedCapture {\n+\tt.Helper()\n+\n+\treader := clabcapture.NewReader(bytes.NewReader(data))\n+\tvar parsed parsedCapture\n+\tfor {\n+\t\tevent, err := reader.Next()\n+\t\tif errors.Is(err, io.EOF) {\n+\t\t\tbreak\n+\t\t}\n+\t\tif err != nil {\n+\t\t\tt.Fatalf(\"invalid capture: %v\", err)\n+\t\t}\n+\t\tif event.Interface != nil {\n+\t\t\tif len(parsed.packets) != 0 {\n+\t\t\t\tt.Fatal(\"interface description after the first packet\")\n+\t\t\t}\n+\t\t\tif event.Interface.TSResol != 9 /* nanoseconds */ {\n+\t\t\t\tt.Fatalf(\"interface %s tsresol = %d\", event.Interface.Name, event.Interface.TSResol)\n+\t\t\t}\n+\t\t\tparsed.interfaces = append(parsed.interfaces, event.Interface.Name)\n+\t\t}\n+\t\tif event.Packet != nil {\n+\t\t\tparsed.packets = append(parsed.packets, *event.Packet)\n+\t\t}\n+\t}\n+\tparsed.sections = reader.Sections()\n+\n+\treturn parsed\n+}\n+\n+func packetSequence(packet clabcapture.Packet) uint64 {\n+\treturn binary.BigEndian.Uint64(packet.Data[0:8])\n+}\n+\n+func packetOrigin(packet clabcapture.Packet) string {\n+\treturn strings.TrimRight(string(packet.Data[8:]), \"\\x00\")\n+}\n+\n+func TestCaptureInterfacesUsesTopologyNames(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, _ := captureTestRuntime(t, time.Millisecond)\n+\tinterfaces, err := r.CaptureInterfaces(\n+\t\tcontext.Background(),\n+\t\tclablabruntime.NodeRequest{Name: \"lab1\"},\n+\t)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\twant := []clablabruntime.CaptureInterface{\n+\t\t{\n+\t\t\tNode:          \"R1\",\n+\t\t\tInterface:     \"e1-1\",\n+\t\t\tAlias:         \"ethernet-1/1\",\n+\t\t\tPeerNode:      \"r2\",\n+\t\t\tPeerInterface: \"ethernet-1/1\",\n+\t\t},\n+\t\t{Node: \"R1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"r1-e1-2\"},\n+\t\t{\n+\t\t\tNode:          \"r2\",\n+\t\t\tInterface:     \"e1-1\",\n+\t\t\tAlias:         \"ethernet-1/1\",\n+\t\t\tPeerNode:      \"R1\",\n+\t\t\tPeerInterface: \"ethernet-1/1\",\n+\t\t},\n+\t}\n+\tif !slices.Equal(interfaces, want) {\n+\t\tt.Fatalf(\"interfaces = %+v\\nwant %+v\", interfaces, want)\n+\t}\n+\n+\tone, err := r.CaptureInterfaces(context.Background(), clablabruntime.NodeRequest{\n+\t\tName: \"lab1\", Nodes: []string{\"r2\"},\n+\t})\n+\tif err != nil || len(one) != 1 || one[0].Node != \"r2\" {\n+\t\tt.Fatalf(\"r2 interfaces = %+v, %v\", one, err)\n+\t}\n+}\n+\n+func TestCaptureMergesNodesIntoOneSection(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, 10*time.Millisecond)\n+\tvar out bytes.Buffer\n+\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tName: \"lab1\",\n+\t\t// the topology name of r1, an alias, and a second node between two r1 interfaces\n+\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t{Node: \"R1\", Interface: \"ethernet-1/1\"},\n+\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n+\t\t\t{Node: \"r1\", Interface: \"e1-2\"},\n+\t\t},\n+\t\tDuration: 300 * time.Millisecond,\n+\t}, &out)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\n+\tparsed := parseCapture(t, out.Bytes())\n+\tif parsed.sections != 1 {\n+\t\tt.Fatalf(\"sections = %d, want one merged section\", parsed.sections)\n+\t}\n+\twantNames := []string{\"R1:e1-1\", \"r2:e1-1\", \"R1:e1-2\"}\n+\tif !slices.Equal(parsed.interfaces, wantNames) {\n+\t\tt.Fatalf(\"interfaces = %v, want %v\", parsed.interfaces, wantNames)\n+\t}\n+\n+\t// one clabwire process per node, with all of the node's interfaces in request order\n+\tcommands := clabwire.captureCommands()\n+\tif len(commands) != 2 {\n+\t\tt.Fatalf(\"capture processes = %d, want one per node: %v\", len(commands), commands)\n+\t}\n+\tfor _, command := range commands {\n+\t\tnode := flagValues(command, \"--nodeName\")[0]\n+\t\twant := map[string][]string{\"r1\": {\"e1-1\", \"e1-2\"}, \"r2\": {\"e1-1\"}}[node]\n+\t\tif got := flagValues(command, \"--interface\"); !slices.Equal(got, want) {\n+\t\t\tt.Fatalf(\"%s interfaces = %v, want %v\", node, got, want)\n+\t\t}\n+\t\tif !strings.HasSuffix(command[0], \"/\"+clabwireContainer) {\n+\t\t\tt.Fatalf(\"capture ran in %s, want the clabwire container\", command[0])\n+\t\t}\n+\t}\n+\n+\t// every packet carries the merged ID of its interface\n+\twantOrigin := map[uint32]string{0: \"r1:e1-1\", 1: \"r2:e1-1\", 2: \"r1:e1-2\"}\n+\tperInterface := map[uint32]int{}\n+\tfor _, packet := range parsed.packets {\n+\t\tif packetOrigin(packet) != wantOrigin[packet.InterfaceID] {\n+\t\t\tt.Fatalf(\"packet from %s has interface ID %d\", packetOrigin(packet), packet.InterfaceID)\n+\t\t}\n+\t\tperInterface[packet.InterfaceID]++\n+\t}\n+\tfor id := range uint32(3) {\n+\t\tif perInterface[id] == 0 {\n+\t\t\tt.Fatalf(\"no packets on %s: %v\", wantNames[id], perInterface)\n+\t\t}\n+\t}\n+}\n+\n+// TestCaptureChainsSegmentsWithoutDuplicatesOrGaps runs captures longer than one segment: every\n+// tick must appear exactly once per interface, across every switch.\n+func TestCaptureChainsSegmentsWithoutDuplicatesOrGaps(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, 4*time.Millisecond)\n+\tr.captureSegment = 300 * time.Millisecond\n+\n+\tvar gaps []clablabruntime.CaptureGap\n+\tvar out bytes.Buffer\n+\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tName: \"lab1\",\n+\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n+\t\t\t{Node: \"r1\", Interface: \"e1-2\"},\n+\t\t},\n+\t\tDuration: 1300 * time.Millisecond,\n+\t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n+\t}, &out)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif len(gaps) != 0 {\n+\t\tt.Fatalf(\"gaps = %+v\", gaps)\n+\t}\n+\tif processes := len(clabwire.captureCommands()); processes < 4 {\n+\t\tt.Fatalf(\"capture processes = %d, want a chain of at least 4 segments\", processes)\n+\t}\n+\n+\tparsed := parseCapture(t, out.Bytes())\n+\tif parsed.sections != 1 || len(parsed.interfaces) != 2 {\n+\t\tt.Fatalf(\"sections = %d, interfaces = %v; want the follow-up headers dropped\",\n+\t\t\tparsed.sections, parsed.interfaces)\n+\t}\n+\tfor id := range uint32(2) {\n+\t\tvar sequence []uint64\n+\t\tfor _, packet := range parsed.packets {\n+\t\t\tif packet.InterfaceID == id {\n+\t\t\t\tsequence = append(sequence, packetSequence(packet))\n+\t\t\t}\n+\t\t}\n+\t\tif len(sequence) < 200 {\n+\t\t\tt.Fatalf(\"interface %d has %d packets\", id, len(sequence))\n+\t\t}\n+\t\tslices.Sort(sequence)\n+\t\tfor idx := 1; idx < len(sequence); idx++ {\n+\t\t\tswitch {\n+\t\t\tcase sequence[idx] == sequence[idx-1]:\n+\t\t\t\tt.Fatalf(\"interface %d: tick %d written twice\", id, sequence[idx])\n+\t\t\tcase sequence[idx] != sequence[idx-1]+1:\n+\t\t\t\tt.Fatalf(\n+\t\t\t\t\t\"interface %d: ticks %d to %d missing\",\n+\t\t\t\t\tid,\n+\t\t\t\t\tsequence[idx-1]+1,\n+\t\t\t\t\tsequence[idx]-1,\n+\t\t\t\t)\n+\t\t\t}\n+\t\t}\n+\t}\n+}\n+\n+func TestCaptureReportsAGapWhenTheFollowUpStartsLate(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, 5*time.Millisecond)\n+\tr.captureSegment = 300 * time.Millisecond\n+\t// the second process starts long after the first one ended\n+\tclabwire.startDelay[1] = 400 * time.Millisecond\n+\n+\tvar gaps []clablabruntime.CaptureGap\n+\tvar out bytes.Buffer\n+\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tName:     \"lab1\",\n+\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"r2\", Interface: \"e1-1\"}},\n+\t\tDuration: 800 * time.Millisecond,\n+\t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n+\t}, &out)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif len(gaps) == 0 || gaps[0].Node != \"r2\" ||\n+\t\t!slices.Equal(gaps[0].Interfaces, []string{\"e1-1\"}) ||\n+\t\tgaps[0].From.IsZero() ||\n+\t\tgaps[0].Reason == \"\" {\n+\t\tt.Fatalf(\"gaps = %+v, want the late follow-up reported\", gaps)\n+\t}\n+\tif !gaps[0].To.IsZero() && !gaps[0].To.After(gaps[0].From) {\n+\t\tt.Fatalf(\"gap ends before it starts: %+v\", gaps[0])\n+\t}\n+\tparseCapture(t, out.Bytes())\n+}\n+\n+func TestCaptureMapsDeniedAndFailedAuditsToErrors(t *testing.T) {\n+\tt.Parallel()\n+\n+\tfor _, status := range []string{captureAuditDenied, captureAuditFailed} {\n+\t\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n+\t\tclabwire.fail = status\n+\n+\t\tvar out bytes.Buffer\n+\t\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\t\tName:     \"lab1\",\n+\t\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"r2\", Interface: \"e1-1\"}},\n+\t\t\tDuration: time.Second,\n+\t\t}, &out)\n+\t\tif err == nil || !strings.Contains(err.Error(), \"is not uniquely planned\") ||\n+\t\t\t!strings.Contains(err.Error(), \"node r2\") {\n+\t\t\tt.Fatalf(\"%s: error = %v, want the audit reason\", status, err)\n+\t\t}\n+\t\tif status == captureAuditDenied && !strings.Contains(err.Error(), \"was denied\") {\n+\t\t\tt.Fatalf(\"Denied error = %v\", err)\n+\t\t}\n+\t\t// the header is written before the capture starts, so the output stays a valid file\n+\t\tparseCapture(t, out.Bytes())\n+\t}\n+}\n+\n+func TestCaptureAuditLineWriter(t *testing.T) {\n+\tt.Parallel()\n+\n+\tvar audits []*captureAudit\n+\twriter := &auditLineWriter{send: func(audit *captureAudit) { audits = append(audits, audit) }}\n+\tstarted := fmt.Sprintf(`{\"schemaVersion\":%q,\"time\":\"2026-10-27T10:00:00.123456789Z\",`+\n+\t\t`\"status\":\"Started\",\"nodeName\":\"r1\",\"interfaces\":[{\"name\":\"e1-1\",\"id\":\"if1\"}]}`,\n+\t\tcaptureAuditSchema)\n+\t// lines arrive split across writes\n+\t_, _ = writer.Write([]byte(started[:20]))\n+\t_, _ = writer.Write([]byte(started[20:] + \"\\nnot json\\n{\\\"status\\\":\\\"Started\\\"}\\n\"))\n+\t_, _ = writer.Write(\n+\t\t[]byte(`{\"schemaVersion\":\"` + captureAuditSchema + `\",\"status\":\"Succeeded\",\"packets\":3}`),\n+\t)\n+\twriter.flush()\n+\n+\tif len(audits) != 2 || audits[0].Status != captureAuditStarted || audits[1].Packets != 3 ||\n+\t\taudits[0].Time.Nanosecond() != 123456789 || audits[0].Interfaces[0].Name != \"e1-1\" {\n+\t\tt.Fatalf(\"audits = %+v\", audits)\n+\t}\n+\tif writer.text() != `not json; {\"status\":\"Started\"}` {\n+\t\tt.Fatalf(\"other stderr = %q\", writer.text())\n+\t}\n+\n+\terr := captureAuditError(\"r1\", &captureAudit{\n+\t\tStatus: captureAuditDenied, Reason: \"nope\",\n+\t\tInterfaces: []struct {\n+\t\t\tName    string `json:\"name\"`\n+\t\t\tID      string `json:\"id\"`\n+\t\t\tPackets int    `json:\"packets\"`\n+\t\t}{{Name: \"e1-1\"}, {Name: \"eth0\"}},\n+\t})\n+\tif err.Error() != \"capture of e1-1,eth0 on node r1 was denied by clabwire: nope\" {\n+\t\tt.Fatalf(\"audit error = %q\", err)\n+\t}\n+}\n+\n+func TestCaptureStopsAtThePacketLimit(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, 2*time.Millisecond)\n+\tvar out bytes.Buffer\n+\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tName: \"lab1\",\n+\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n+\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n+\t\t},\n+\t\tPacketLimit: 7,\n+\t}, &out)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif got := len(parseCapture(t, out.Bytes()).packets); got != 7 {\n+\t\tt.Fatalf(\"packets = %d, want 7\", got)\n+\t}\n+\t// each clabwire process gets the limit that remained when it started\n+\tfor _, command := range clabwire.captureCommands() {\n+\t\tlimit := flagValues(command, \"--packetLimit\")\n+\t\tif len(limit) != 1 || limit[0] < \"1\" || limit[0] > \"7\" || len(limit[0]) != 1 {\n+\t\t\tt.Fatalf(\"clabwire packet limit = %v, want at most 7\", limit)\n+\t\t}\n+\t}\n+}\n+\n+func TestCaptureEndsCleanlyWhenTheContextEnds(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, _ := captureTestRuntime(t, 2*time.Millisecond)\n+\tctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)\n+\tdefer cancel()\n+\n+\tvar out bytes.Buffer\n+\tif err := r.Capture(ctx, clablabruntime.CaptureRequest{\n+\t\tName:    \"lab1\",\n+\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"e1-1\"}},\n+\t}, &out); err != nil {\n+\t\tt.Fatalf(\"Capture() after the context ended = %v, want nil\", err)\n+\t}\n+\tif len(parseCapture(t, out.Bytes()).packets) == 0 {\n+\t\tt.Fatal(\"no packets before the context ended\")\n+\t}\n+}\n+\n+func TestCaptureValidatesTargets(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n+\tctx := context.Background()\n+\tcases := map[string]clablabruntime.CaptureRequest{\n+\t\t\"is not a capturable link interface; capturable: e1-1 (ethernet-1/1), e1-2\": {\n+\t\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth0\"}},\n+\t\t},\n+\t\t\"requested more than once\": {\n+\t\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t\t{Node: \"r1\", Interface: \"e1-1\"}, {Node: \"R1\", Interface: \"ethernet-1/1\"},\n+\t\t\t},\n+\t\t},\n+\t\t`node \"missing\" was not found`: {\n+\t\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"missing\", Interface: \"e1-1\"}},\n+\t\t},\n+\t\t\"at least one capture target\": {},\n+\t\t\"snap length 10 is outside\": {\n+\t\t\tTargets:    []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"e1-1\"}},\n+\t\t\tSnapLength: 10,\n+\t\t},\n+\t\t\"duration must not be negative\": {\n+\t\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"e1-1\"}},\n+\t\t\tDuration: -time.Second,\n+\t\t},\n+\t}\n+\tfor want, req := range cases {\n+\t\treq.Name = \"lab1\"\n+\t\terr := r.Capture(ctx, req, io.Discard)\n+\t\tif err == nil || !strings.Contains(err.Error(), want) {\n+\t\t\tt.Errorf(\"error = %v, want %q\", err, want)\n+\t\t}\n+\t}\n+\tif commands := clabwire.captureCommands(); len(commands) != 0 {\n+\t\tt.Fatalf(\"invalid requests started captures: %v\", commands)\n+\t}\n+}\n+\n+func TestInspectInterfacesReportsStateFromSysfs(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n+\tclabwire.sysfs = \"Inter-|   Receive\\n face |bytes\\n\" + interfaceSysfsMarker + \"\\n\" +\n+\t\t\"e1-1\\t12\\t9500\\taa:c1:ab:00:00:01\\tup\\t0x1003\\t\\n\" +\n+\t\t\"e1-2\\t13\\t1500\\taa:c1:ab:00:00:02\\tlowerlayerdown\\t0x1003\\t\\n\"\n+\n+\tinterfaces, err := r.InspectInterfaces(context.Background(), clablabruntime.NodeRequest{\n+\t\tName: \"lab1\", Nodes: []string{\"R1\"},\n+\t})\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif len(interfaces) != 1 || interfaces[0].ContainerName != \"lab1-r1\" ||\n+\t\tlen(interfaces[0].Interfaces) != 2 {\n+\t\tt.Fatalf(\"interfaces = %+v\", interfaces)\n+\t}\n+\tfirst := interfaces[0].Interfaces[0]\n+\tif first.InterfaceName != \"e1-1\" || first.InterfaceAlias != \"ethernet-1/1\" ||\n+\t\tfirst.InterfaceMAC != \"aa:c1:ab:00:00:01\" || first.InterfaceIndex != 12 ||\n+\t\tfirst.InterfaceMTU != 9500 || first.InterfaceState != \"up\" {\n+\t\tt.Fatalf(\"e1-1 = %+v\", first)\n+\t}\n+\tif second := interfaces[0].Interfaces[1]; second.InterfaceState != \"lowerlayerdown\" {\n+\t\tt.Fatalf(\"e1-2 = %+v\", second)\n+\t}\n+}\n+\n+// TestCaptureClosesStdinWhenItEnds ends every clabwire process through its stdin, whether the\n+// caller cancels the capture or the output fails, so no capture is left running in the pod.\n+// TestCaptureWritesWhatItReadWhenTheContextEnds stops a capture while the output is slow and\n+// the chains have packets queued: every packet clabwire wrote before it ended is in the file.\n+func TestCaptureWritesWhatItReadWhenTheContextEnds(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n+\t// without a reorder window, a blocked output blocks the chains\n+\tr.captureReorderWindow = -1\n+\tctx, cancel := context.WithCancel(context.Background())\n+\tdefer cancel()\n+\n+\tout := &gatedWriter{open: make(chan struct{})}\n+\tgo func() {\n+\t\ttime.Sleep(50 * time.Millisecond)\n+\t\tout.block()\n+\t\t// the segments keep reading while the chains wait for the output\n+\t\ttime.Sleep(400 * time.Millisecond)\n+\t\tcancel()\n+\t\tclose(out.open)\n+\t}()\n+\n+\tif err := r.Capture(ctx, clablabruntime.CaptureRequest{\n+\t\tName: \"lab1\",\n+\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n+\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n+\t\t},\n+\t}, out); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\n+\tparsed := parseCapture(t, out.bytes())\n+\tgot := map[string]int{}\n+\tfor _, packet := range parsed.packets {\n+\t\tnode, _, _ := strings.Cut(packetOrigin(packet), \":\")\n+\t\tgot[node]++\n+\t}\n+\tclabwire.mu.Lock()\n+\tdefer clabwire.mu.Unlock()\n+\tfor _, node := range []string{\"r1\", \"r2\"} {\n+\t\tif clabwire.written[node] < 300 || got[node] != clabwire.written[node] {\n+\t\t\tt.Fatalf(\"%s: clabwire wrote %d packets, the capture has %d\", node,\n+\t\t\t\tclabwire.written[node], got[node])\n+\t\t}\n+\t}\n+}\n+\n+// gatedWriter collects writes; once blocked, writes wait until open is closed.\n+type gatedWriter struct {\n+\topen chan struct{}\n+\n+\tmu      sync.Mutex\n+\tblocked bool\n+\tdata    bytes.Buffer\n+}\n+\n+func (w *gatedWriter) block() {\n+\tw.mu.Lock()\n+\tw.blocked = true\n+\tw.mu.Unlock()\n+}\n+\n+func (w *gatedWriter) Write(data []byte) (int, error) {\n+\tw.mu.Lock()\n+\tblocked := w.blocked\n+\tw.mu.Unlock()\n+\tif blocked {\n+\t\t<-w.open\n+\t}\n+\tw.mu.Lock()\n+\tdefer w.mu.Unlock()\n+\n+\treturn w.data.Write(data)\n+}\n+\n+func (w *gatedWriter) bytes() []byte {\n+\tw.mu.Lock()\n+\tdefer w.mu.Unlock()\n+\n+\treturn w.data.Bytes()\n+}\n+\n+func TestCaptureClosesStdinWhenItEnds(t *testing.T) {\n+\tt.Parallel()\n+\n+\ttargets := []clablabruntime.CaptureTarget{\n+\t\t{Node: \"r1\", Interface: \"e1-1\"},\n+\t\t{Node: \"r2\", Interface: \"e1-1\"},\n+\t}\n+\n+\tt.Run(\"cancel\", func(t *testing.T) {\n+\t\tt.Parallel()\n+\n+\t\tr, clabwire := captureTestRuntime(t, 2*time.Millisecond)\n+\t\tctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)\n+\t\tdefer cancel()\n+\n+\t\tif err := r.Capture(ctx, clablabruntime.CaptureRequest{Name: \"lab1\", Targets: targets},\n+\t\t\tio.Discard); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\trequireStdinClosedEverywhere(t, clabwire)\n+\t})\n+\n+\tt.Run(\"output fails\", func(t *testing.T) {\n+\t\tt.Parallel()\n+\n+\t\tr, clabwire := captureTestRuntime(t, 2*time.Millisecond)\n+\t\toutput := &failingWriter{accept: 3}\n+\t\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\t\tName: \"lab1\", Targets: targets, Duration: time.Hour,\n+\t\t}, output)\n+\t\tif err == nil || !strings.Contains(err.Error(), \"broken pipe\") {\n+\t\t\tt.Fatalf(\"Capture() = %v, want the write error\", err)\n+\t\t}\n+\t\trequireStdinClosedEverywhere(t, clabwire)\n+\t})\n+}\n+\n+// failingWriter accepts some writes, then fails like a closed pipe.\n+type failingWriter struct {\n+\tmu     sync.Mutex\n+\taccept int\n+}\n+\n+func (w *failingWriter) Write(data []byte) (int, error) {\n+\tw.mu.Lock()\n+\tdefer w.mu.Unlock()\n+\tif w.accept == 0 {\n+\t\treturn 0, errors.New(\"write |1: broken pipe\")\n+\t}\n+\tw.accept--\n+\n+\treturn len(data), nil\n+}\n+\n+func requireStdinClosedEverywhere(t *testing.T, clabwire *fakeClabwire) {\n+\tt.Helper()\n+\n+\tclabwire.mu.Lock()\n+\tdefer clabwire.mu.Unlock()\n+\tfor _, node := range []string{\"r1\", \"r2\"} {\n+\t\tif clabwire.processes[node] == 0 || clabwire.stdinClosed[node] != clabwire.processes[node] {\n+\t\t\tt.Fatalf(\"%s: %d processes, %d ended through stdin\", node,\n+\t\t\t\tclabwire.processes[node], clabwire.stdinClosed[node])\n+\t\t}\n+\t}\n+}\n+\n+// TestCaptureRejectsAClabwireWithoutStopOnStdinClose turns the usage error of an older clabwire\n+// into the release error.\n+func TestCaptureRejectsAClabwireWithoutStopOnStdinClose(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n+\tclabwire.stderrOnly = \"flag provided but not defined: -stop-on-stdin-close\"\n+\n+\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tName: \"lab1\", Targets: []clablabruntime.CaptureTarget{{Node: \"r2\", Interface: \"e1-1\"}},\n+\t\tDuration: time.Second,\n+\t}, io.Discard)\n+\tif !errors.Is(err, clablabruntime.ErrUnsupportedRuntimeVersion) ||\n+\t\t!strings.Contains(err.Error(), \"clabwire in pod lab-ns/lab1-r2-def does not accept \"+\n+\t\t\t\"packet-capture --stop-on-stdin-close\") ||\n+\t\t!strings.Contains(err.Error(), \"(0.11 or newer)\") {\n+\t\tt.Fatalf(\"Capture() = %v, want the release error\", err)\n+\t}\n+}\n+\n+// requireTimeOrdered checks that the merged stream's timestamps never decrease.\n+func requireTimeOrdered(t *testing.T, packets []clabcapture.Packet) {\n+\tt.Helper()\n+\n+\tfor idx := 1; idx < len(packets); idx++ {\n+\t\tif packets[idx].Timestamp < packets[idx-1].Timestamp {\n+\t\t\tt.Fatalf(\"packet %d (%s) at %d precedes packet %d (%s) at %d\", idx,\n+\t\t\t\tpacketOrigin(packets[idx]), packets[idx].Timestamp, idx-1,\n+\t\t\t\tpacketOrigin(packets[idx-1]), packets[idx-1].Timestamp)\n+\t\t}\n+\t}\n+}\n+\n+// TestCaptureMergesNodesInTimestampOrder merges two nodes whose streams arrive with different\n+// delays: r2's packets are stamped 60 ms before they reach containerlab. The reorder window puts\n+// them in order; without it they are not.\n+func TestCaptureMergesNodesInTimestampOrder(t *testing.T) {\n+\tt.Parallel()\n+\n+\tfor _, reorder := range []bool{true, false} {\n+\t\tt.Run(fmt.Sprintf(\"reorder=%v\", reorder), func(t *testing.T) {\n+\t\t\tt.Parallel()\n+\n+\t\t\tr, clabwire := captureTestRuntime(t, 5*time.Millisecond)\n+\t\t\tclabwire.stampSkew[\"r2\"] = 60 * time.Millisecond\n+\t\t\tif !reorder {\n+\t\t\t\tr.captureReorderWindow = -1\n+\t\t\t}\n+\n+\t\t\tvar out bytes.Buffer\n+\t\t\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\t\t\tName: \"lab1\",\n+\t\t\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n+\t\t\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n+\t\t\t\t},\n+\t\t\t\tDuration: 500 * time.Millisecond,\n+\t\t\t}, &out)\n+\t\t\tif err != nil {\n+\t\t\t\tt.Fatal(err)\n+\t\t\t}\n+\n+\t\t\tpackets := parseCapture(t, out.Bytes()).packets\n+\t\t\tordered := slices.IsSortedFunc(packets, func(a, b clabcapture.Packet) int {\n+\t\t\t\treturn int(a.Timestamp - b.Timestamp)\n+\t\t\t})\n+\t\t\tif reorder {\n+\t\t\t\trequireTimeOrdered(t, packets)\n+\t\t\t} else if ordered {\n+\t\t\t\tt.Fatal(\"the skewed streams came out ordered without the reorder window\")\n+\t\t\t}\n+\t\t})\n+\t}\n+}\n+\n+// TestCaptureChainsSeveralNodesInOrderWithoutDuplicates chains two nodes with skewed streams and a\n+// reorder window shorter than a segment switch:\n+// every tick appears exactly once per interface and the merged stream stays in timestamp order\n+// across every segment switch, while old segments are ended through stdin at the switch.\n+func TestCaptureChainsSeveralNodesInOrderWithoutDuplicates(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, 4*time.Millisecond)\n+\tr.captureSegment = 300 * time.Millisecond\n+\t// a window shorter than a switch: the chains' holds keep the order across the switches\n+\tr.captureReorderWindow = 15 * time.Millisecond\n+\tclabwire.stampSkew[\"r2\"] = 5 * time.Millisecond\n+\t// r2 switches segments 120 ms after r1, so one chain streams live while the other holds\n+\tclabwire.firstStartDelay[\"r2\"] = 120 * time.Millisecond\n+\n+\tvar gaps []clablabruntime.CaptureGap\n+\tvar out bytes.Buffer\n+\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tName: \"lab1\",\n+\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n+\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n+\t\t},\n+\t\tDuration: 1300 * time.Millisecond,\n+\t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n+\t}, &out)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif len(gaps) != 0 {\n+\t\tt.Fatalf(\"gaps = %+v\", gaps)\n+\t}\n+\n+\tparsed := parseCapture(t, out.Bytes())\n+\trequireTimeOrdered(t, parsed.packets)\n+\tfor id := range uint32(2) {\n+\t\tvar sequence []uint64\n+\t\tfor _, packet := range parsed.packets {\n+\t\t\tif packet.InterfaceID == id {\n+\t\t\t\tsequence = append(sequence, packetSequence(packet))\n+\t\t\t}\n+\t\t}\n+\t\tslices.Sort(sequence)\n+\t\tif len(sequence) < 200 {\n+\t\t\tt.Fatalf(\"interface %d has %d packets\", id, len(sequence))\n+\t\t}\n+\t\tfor idx := 1; idx < len(sequence); idx++ {\n+\t\t\tif sequence[idx] != sequence[idx-1]+1 {\n+\t\t\t\tt.Fatalf(\"interface %d: tick %d followed by %d\", id, sequence[idx-1], sequence[idx])\n+\t\t\t}\n+\t\t}\n+\t}\n+\n+\tclabwire.mu.Lock()\n+\tdefer clabwire.mu.Unlock()\n+\tfor _, node := range []string{\"r1\", \"r2\"} {\n+\t\tif clabwire.processes[node] < 4 || clabwire.stdinClosed[node] == 0 {\n+\t\t\tt.Fatalf(\"%s: %d processes, %d stopped through stdin at a switch\", node,\n+\t\t\t\tclabwire.processes[node], clabwire.stdinClosed[node])\n+\t\t}\n+\t}\n+}\n+\n+func TestCaptureReorderWindowKnob(t *testing.T) {\n+\tcases := map[string]time.Duration{\n+\t\t\"\":      250 * time.Millisecond,\n+\t\t\"0\":     0,\n+\t\t\"75ms\":  75 * time.Millisecond,\n+\t\t\"bogus\": 250 * time.Millisecond,\n+\t}\n+\tfor value, want := range cases {\n+\t\tt.Setenv(envCaptureReorderWindow, value)\n+\t\tr := &Runtime{captureReorderWindow: captureReorderWindowFromEnv()}\n+\t\tif got := r.captureReorderWindowLength(); got != want {\n+\t\t\tt.Errorf(\"%s=%q: window %s, want %s\", envCaptureReorderWindow, value, got, want)\n+\t\t}\n+\t}\n+}\ndiff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go\nindex 3c556e7..e869191 100644\n--- a/labruntime/clabernetes/clabernetes.go\n+++ b/labruntime/clabernetes/clabernetes.go\n@@ -84,10 +84,18 @@ type Runtime struct {\n \t// identity is the configured identity of calls without one; in a connected view it is the\n \t// identity the clients impersonate.\n \tidentity clablabruntime.Identity\n \t// pollInterval overrides how often waits poll the cluster (tests).\n \tpollInterval time.Duration\n+\t// podExec overrides how commands run in pod containers (tests).\n+\tpodExec podExecFunc\n+\t// captureSegment is the length of one chained packet capture; zero uses the clabwire\n+\t// maximum of one hour.\n+\tcaptureSegment time.Duration\n+\t// captureReorderWindow is how long the merged capture stream holds packets back to write\n+\t// them in timestamp order: zero uses the default, a negative value disables reordering.\n+\tcaptureReorderWindow time.Duration\n \t// support checks once per runtime instance, before the first cluster call, that the\n \t// cluster runs a clabernetes release with the contract this runtime needs. Every view\n \t// shares it. It is nil when the clients were injected (tests).\n \tsupport *supportCheck\n }\n@@ -253,7 +261,9 @@ func New(cfg clablabruntime.Config) (clablabruntime.LabRuntime, error) {\n \t\ttimeout:              cfg.Timeout,\n \t\tkindLinkApplyMode:    cfg.KindLinkApplyMode,\n \t\tidentity:             cfg.Identity,\n \t\tclients:              newClientLoader(),\n \t\tsupport:              &supportCheck{},\n+\t\tcaptureSegment:       captureSegmentFromEnv(),\n+\t\tcaptureReorderWindow: captureReorderWindowFromEnv(),\n \t}, nil\n }\ndiff --git a/labruntime/runtime.go b/labruntime/runtime.go\nindex 76e651c..367565d 100644\n--- a/labruntime/runtime.go\n+++ b/labruntime/runtime.go\n@@ -387,10 +387,80 @@ type NodeLogStreamer interface {\n // exactly one node. Closing the connection closes the stream.\n type NodePortForwarder interface {\n \tDialPort(ctx context.Context, req NodeRequest, port int) (net.Conn, error)\n }\n \n+// CaptureInterface is a lab link interface packet capture accepts, with the far end of its link.\n+type CaptureInterface struct {\n+\t// Node is the node name as the topology spells it.\n+\tNode string `json:\"node\"`\n+\t// Interface is the interface name inside the node, which capture output carries.\n+\tInterface string `json:\"interface\"`\n+\t// Alias is the name the topology used for the interface when the node kind maps it (for\n+\t// example ethernet-1/1 for SR Linux e1-1). Capture targets accept either name.\n+\tAlias string `json:\"alias,omitempty\"`\n+\t// PeerNode is the node at the other end of the link, \"host\" for a host endpoint, or empty",
        "lineStart": 4780,
        "lineEnd": 6409,
        "totalLines": 6410,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523236447,
      "end": 1793523236475
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19650be7e001Y5y9dItN7gQ1Qr",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650b315001ndmMoYOP5TaOov",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 67192,
    "input": 19298,
    "output": 21,
    "reasoning": 1,
    "cache": {
      "read": 47872,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19650b315001ndmMoYOP5TaOov",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523233557,
    "completed": 1793523236481
  },
  "parentID": "msg_196508bbe001tLsHPkKW57hw60",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 67192,
    "input": 19298,
    "output": 21,
    "reasoning": 1,
    "cache": {
      "read": 47872,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 8
step-start
{
  "type": "step-start",
  "id": "prt_19650ca460014LGH6kgJV9DwwX",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650be85001Eha5NBjsp4KX8c"
}
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "offset": 6410
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
6410: +	// when the runtime cannot name it.
6411: +	PeerNode string `json:"peer_node"`
6412: +	// PeerInterface is the peer's interface as the topology wrote it.
6413: +	PeerInterface string `json:"peer_interface"`
6414: +}
6415: +
6416: +// CaptureTarget is one interface of one node to capture. Node takes the name the topology or
6417: +// the runtime uses, Interface the interface name or its alias.
6418: +type CaptureTarget struct {
6419: +	Node      string
6420: +	Interface string
6421: +}
6422: +
6423: +// CaptureRequest selects what Capture streams.
6424: +type CaptureRequest struct {
6425: +	// Name is the lab name.
6426: +	Name      string
6427: +	Namespace string
6428: +	Targets   []CaptureTarget
6429: +	// Duration ends the capture; zero captures until the context ends.
6430: +	Duration time.Duration
6431: +	// PacketLimit ends the capture after that many packets across all targets; zero means no
6432: +	// limit.
6433: +	PacketLimit int
6434: +	// SnapLength is the number of bytes kept of each packet; zero uses the runtime default.
6435: +	SnapLength int
6436: +	// OnGap is called when the capture missed traffic, for example because a chained capture
6437: +	// did not start in time. Without it, gaps are logged as warnings.
6438: +	OnGap    func(CaptureGap)
6439: +	Identity Identity
6440: +}
6441: +
6442: +// CaptureGap is a time span a capture has no packets for, although it was running.
6443: +type CaptureGap struct {
6444: +	Node       string
6445: +	Interfaces []string
6446: +	// From and To bound the gap on the node's clock; To is zero when it is unknown.
6447: +	From   time.Time
6448: +	To     time.Time
6449: +	Reason string
6450: +}
6451: +
6452: +// PacketCapturer streams pcapng from lab link interfaces. Capture writes one section with one
6453: +// Interface Description Block per target, named <node>:<interface>, before any packet. It
6454: +// returns when Duration passed, PacketLimit packets were written, or the context ended (which
6455: +// is not an error); the output is a valid capture whenever it stops.
6456: +type PacketCapturer interface {
6457: +	CaptureInterfaces(ctx context.Context, req NodeRequest) ([]CaptureInterface, error)
6458: +	Capture(ctx context.Context, req CaptureRequest, w io.Writer) error
6459: +}
6460: +
6461: +// InterfaceInspector lists the link interfaces of a lab's nodes with their current state, in the
6462: +// shape of `inspect interfaces`.
6463: +type InterfaceInspector interface {
6464: +	InspectInterfaces(
6465: +		ctx context.Context,
6466: +		req NodeRequest,
6467: +	) ([]*clabtypes.ContainerInterfaces, error)
6468: +}
6469: +
6470:  // NodeStatsSampler reports the resource usage of a lab's nodes. It returns an error wrapping
6471:  // ErrMetricsUnavailable when the cluster serves no resource metrics.
6472:  type NodeStatsSampler interface {
6473:  	SampleStats(ctx context.Context, req InspectRequest) ([]NodeStats, error)
6474:  }
6475: diff --git a/mkdocs.yml b/mkdocs.yml
6476: index 0285ad6..8dc17bd 100644
6477: --- a/mkdocs.yml
6478: +++ b/mkdocs.yml
6479: @@ -117,10 +117,11 @@ nav:
6480:        - inspect:
6481:            - cmd/inspect/index.md
6482:            - interfaces: cmd/inspect/interfaces.md
6483:        - events: cmd/events.md
6484:        - logs: cmd/logs.md
6485: +      - capture: cmd/capture.md
6486:        - save: cmd/save.md
6487:        - exec: cmd/exec.md
6488:        - generate: cmd/generate.md
6489:        - graph: cmd/graph.md
6490:        - validate: cmd/validate.md
6491: diff --git a/tests/01-smoke/33-capture-summary.py b/tests/01-smoke/33-capture-summary.py
6492: new file mode 100755
6493: index 0000000..d49014c
6494: --- /dev/null
6495: +++ b/tests/01-smoke/33-capture-summary.py
6496: @@ -0,0 +1,69 @@
6497: +#!/usr/bin/env python3
6498: +# Copyright 2020 Nokia
6499: +# Licensed under the BSD 3-Clause License.
6500: +# SPDX-License-Identifier: BSD-3-Clause
6501: +"""Summarize a little-endian pcapng file as containerlab capture writes it, as JSON.
6502: +
6503: +Prints the number of sections, the interface names in order, the packet count per interface,
6504: +whether packets are in timestamp order, the number of 802.1Q tagged frames and the number of
6505: +ICMP echo requests and replies (untagged or tagged).
6506: +"""
6507: +
6508: +import json
6509: +import struct
6510: +import sys
6511: +
6512: +SHB, IDB, EPB = 0x0A0D0D0A, 0x00000001, 0x00000006
6513: +
6514: +
6515: +def main(path):
6516: +    with open(path, "rb") as f:
6517: +        data = f.read()
6518: +
6519: +    sections, names, counts, stamps = 0, [], {}, []
6520: +    vlan, echo = 0, 0
6521: +    offset = 0
6522: +    while offset < len(data):
6523: +        block_type, length = struct.unpack_from("<II", data, offset)
6524: +        body = data[offset + 8 : offset + length - 4]
6525: +        if block_type == SHB:
6526: +            sections += 1
6527: +        elif block_type == IDB:
6528: +            options, name = body[8:], ""
6529: +            while len(options) >= 4:
6530: +                code, size = struct.unpack_from("<HH", options)
6531: +                if code == 0:
6532: +                    break
6533: +                if code == 2:
6534: +                    name = options[4 : 4 + size].decode()
6535: +                options = options[4 + size + (4 - size % 4) % 4 :]
6536: +            names.append(name)
6537: +        elif block_type == EPB:
6538: +            iface, high, low, captured = struct.unpack_from("<IIII", body)
6539: +            frame = body[20 : 20 + captured]
6540: +            counts[names[iface]] = counts.get(names[iface], 0) + 1
6541: +            stamps.append(high << 32 | low)
6542: +            ethertype, l3 = struct.unpack_from(">H", frame, 12)[0], 14
6543: +            if ethertype == 0x8100:
6544: +                vlan += 1
6545: +                ethertype, l3 = struct.unpack_from(">H", frame, 16)[0], 18
6546: +            if ethertype == 0x0800 and frame[l3 + 9] == 1 and frame[l3 + 20] in (0, 8):
6547: +                echo += 1
6548: +        offset += length
6549: +
6550: +    print(
6551: +        json.dumps(
6552: +            {
6553: +                "sections": sections,
6554: +                "interfaces": names,
6555: +                "packets": counts,
6556: +                "ordered": stamps == sorted(stamps),
6557: +                "vlan_frames": vlan,
6558: +                "icmp_echo": echo,
6559: +            }
6560: +        )
6561: +    )
6562: +
6563: +
6564: +if __name__ == "__main__":
6565: +    main(sys.argv[1])
6566: diff --git a/tests/01-smoke/33-capture.clab.yml b/tests/01-smoke/33-capture.clab.yml
6567: new file mode 100644
6568: index 0000000..3f70288
6569: --- /dev/null
6570: +++ b/tests/01-smoke/33-capture.clab.yml
6571: @@ -0,0 +1,29 @@
6572: +# yaml-language-server: $schema=../../schemas/clab.schema.json
6573: +name: capture
6574: +
6575: +topology:
6576: +  nodes:
6577: +    l1:
6578: +      kind: linux
6579: +      image: alpine:3
6580: +      exec:
6581: +        - ip addr add 10.0.0.1/24 dev eth1
6582: +        - ip link add link eth1 name eth1.10 type vlan id 10
6583: +        - ip addr add 10.10.0.1/24 dev eth1.10
6584: +        - ip link set eth1.10 up
6585: +    l2:
6586: +      kind: linux
6587: +      image: alpine:3
6588: +      exec:
6589: +        - ip addr add 10.0.0.2/24 dev eth1
6590: +        - ip link add link eth1 name eth1.10 type vlan id 10
6591: +        - ip addr add 10.10.0.2/24 dev eth1.10
6592: +        - ip link set eth1.10 up
6593: +
6594: +  links:
6595: +    - endpoints: ["l1:eth1", "l2:eth1"]
6596: +    - type: host
6597: +      host-interface: capl2eth2
6598: +      endpoint:
6599: +        node: l2
6600: +        interface: eth2
6601: diff --git a/tests/01-smoke/33-capture.robot b/tests/01-smoke/33-capture.robot
6602: new file mode 100644
6603: index 0000000..9502a8e
6604: --- /dev/null
6605: +++ b/tests/01-smoke/33-capture.robot
6606: @@ -0,0 +1,161 @@
6607: +*** Comments ***
6608: +This suite tests the capture command with the local container runtimes: containerlab reads the
6609: +lab link interfaces through packet sockets in the nodes' network namespaces.
6610: +
6611: +
6612: +*** Settings ***
6613: +Library             OperatingSystem
6614: +Library             Process
6615: +Library             String
6616: +Library             Collections
6617: +Resource            ../common.robot
6618: +
6619: +Suite Setup         Run    ${CLAB_BIN} --runtime ${runtime} destroy -t ${topo} --cleanup
6620: +Suite Teardown      Cleanup
6621: +
6622: +
6623: +*** Variables ***
6624: +${lab-name}         capture
6625: +${topo}             ${CURDIR}/33-capture.clab.yml
6626: +${runtime}          docker
6627: +${summary-script}   ${CURDIR}/33-capture-summary.py
6628: +${pcap}             /tmp/clab-capture.pcapng
6629: +${stdout-pcap}      /tmp/clab-capture-stdout.pcapng
6630: +${interrupt-pcap}   /tmp/clab-capture-interrupt.pcapng
6631: +${restart-pcap}     /tmp/clab-capture-restart.pcapng
6632: +
6633: +
6634: +*** Test Cases ***
6635: +Deploy ${lab-name} lab
6636: +    ${rc}    ${output} =    Run And Return Rc And Output
6637: +    ...    ${CLAB_BIN} --runtime ${runtime} deploy -t ${topo}
6638: +    Log    ${output}
6639: +    Should Be Equal As Integers    ${rc}    0
6640: +
6641: +List the capturable interfaces
6642: +    ${result} =    Run Capture    --name ${lab-name} --list -f json
6643: +    Should Be Equal As Integers    ${result.rc}    0
6644: +    ${interfaces} =    Evaluate    json.loads($result.stdout)    modules=json
6645: +    Length Should Be    ${interfaces}    3
6646: +    Should Be Equal    ${interfaces}[0][node]    l1
6647: +    Should Be Equal    ${interfaces}[0][interface]    eth1
6648: +    Should Be Equal    ${interfaces}[0][peer_node]    l2
6649: +    Should Be Equal    ${interfaces}[2][node]    l2
6650: +    Should Be Equal    ${interfaces}[2][interface]    eth2
6651: +    Should Be Equal    ${interfaces}[2][peer_node]    host
6652: +    Should Be Equal    ${interfaces}[2][peer_interface]    capl2eth2
6653: +
6654: +Capture both ends of a link with VLAN traffic
6655: +    Start Process
6656: +    ...    ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l1:eth1 --target l2:eth1 --duration 8s -w ${pcap}
6657: +    ...    shell=True
6658: +    ...    alias=both-ends
6659: +    Sleep    2s
6660: +    Ping From L1    10.0.0.2
6661: +    Ping From L1    10.10.0.2
6662: +    ${result} =    Wait For Process    both-ends    timeout=30s    on_timeout=kill
6663: +    Log    ${result.stderr}
6664: +    Should Be Equal As Integers    ${result.rc}    0
6665: +    ${summary} =    Capture Summary    ${pcap}
6666: +    Should Be Equal As Integers    ${summary}[sections]    1
6667: +    ${want} =    Create List    l1:eth1    l2:eth1
6668: +    Lists Should Be Equal    ${summary}[interfaces]    ${want}
6669: +    Should Be True    ${summary}[ordered]
6670: +    # 6 pings, each request and reply seen on both ends
6671: +    Should Be True    ${summary}[icmp_echo] >= 24
6672: +    # the VLAN 10 pings keep their 802.1Q tag
6673: +    Should Be True    ${summary}[vlan_frames] >= 12
6674: +
6675: +Capture to stdout stops at the packet limit
6676: +    Start Process
6677: +    ...    sleep 1 && sudo ${runtime} exec clab-${lab-name}-l1 ping -c 20 -i 0.2 10.0.0.2
6678: +    ...    shell=True
6679: +    ...    alias=background-ping
6680: +    ${result} =    Process.Run Process
6681: +    ...    ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l2:eth1 --packet-limit 6 -w - > ${stdout-pcap}
6682: +    ...    shell=True
6683: +    ...    timeout=30s
6684: +    ...    on_timeout=kill
6685: +    Log    ${result.stderr}
6686: +    Should Be Equal As Integers    ${result.rc}    0
6687: +    ${summary} =    Capture Summary    ${stdout-pcap}
6688: +    Should Be Equal As Integers    ${summary}[packets][l2:eth1]    6
6689: +    [Teardown]    Terminate Process    background-ping    kill=True
6690: +
6691: +An interrupt ends the capture with a valid file
6692: +    Start Process
6693: +    ...    exec ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l1:eth1 -w ${interrupt-pcap}
6694: +    ...    shell=True
6695: +    ...    alias=interrupted
6696: +    Sleep    2s
6697: +    Ping From L1    10.0.0.2
6698: +    Send Signal To Process    SIGINT    interrupted
6699: +    ${result} =    Wait For Process    interrupted    timeout=15s    on_timeout=kill
6700: +    Log    ${result.stderr}
6701: +    Should Be Equal As Integers    ${result.rc}    0
6702: +    ${summary} =    Capture Summary    ${interrupt-pcap}
6703: +    Should Be True    ${summary}[icmp_echo] >= 6
6704: +
6705: +The capture reattaches an interface after its node restarts
6706: +    Start Process
6707: +    ...    exec ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l2:eth1 -w ${restart-pcap}
6708: +    ...    shell=True
6709: +    ...    alias=restarted
6710: +    Sleep    2s
6711: +    Ping From L1    10.0.0.2
6712: +    ${rc}    ${output} =    Run And Return Rc And Output
6713: +    ...    ${CLAB_BIN} --runtime ${runtime} restart -t ${topo} --node l2
6714: +    Log    ${output}
6715: +    Should Be Equal As Integers    ${rc}    0
6716: +    ${rc}    ${output} =    Run And Return Rc And Output
6717: +    ...    sudo ${runtime} exec clab-${lab-name}-l2 ip addr replace 10.0.0.2/24 dev eth1
6718: +    Log    ${output}
6719: +    Wait Until Keyword Succeeds    20s    1s    Ping From L1    10.0.0.2
6720: +    # the capture reattaches within a fraction of a second after the link is back
6721: +    Sleep    1s
6722: +    Ping From L1    10.0.0.2
6723: +    Send Signal To Process    SIGINT    restarted
6724: +    ${result} =    Wait For Process    restarted    timeout=15s    on_timeout=kill
6725: +    Log    ${result.stderr}
6726: +    Should Be Equal As Integers    ${result.rc}    0
6727: +    Should Contain    ${result.stderr}    Capture has a gap
6728: +    ${summary} =    Capture Summary    ${restart-pcap}
6729: +    # 3 pings before and 3 after the reattach, request and reply each
6730: +    Should Be True    ${summary}[icmp_echo] >= 12
6731: +
6732: +The capture rejects the management interface
6733: +    ${result} =    Run Capture    --name ${lab-name} --target l1:eth0 -w /dev/null
6734: +    Should Not Be Equal As Integers    ${result.rc}    0
6735: +    Should Contain    ${result.stderr}    not a capturable link interface; capturable: eth1
6736: +
6737: +
6738: +*** Keywords ***
6739: +Run Capture
6740: +    [Arguments]    ${args}
6741: +    ${result} =    Process.Run Process
6742: +    ...    ${CLAB_BIN} --runtime ${runtime} capture ${args}
6743: +    ...    shell=True
6744: +    ...    timeout=60s
6745: +    ...    on_timeout=kill
6746: +    Log    stdout:${\n}${result.stdout}
6747: +    Log    stderr:${\n}${result.stderr}
6748: +    RETURN    ${result}
6749: +
6750: +Ping From L1
6751: +    [Arguments]    ${address}
6752: +    ${rc}    ${output} =    Run And Return Rc And Output
6753: +    ...    sudo ${runtime} exec clab-${lab-name}-l1 ping -c 3 -i 0.2 -W 1 ${address}
6754: +    Log    ${output}
6755: +    Should Be Equal As Integers    ${rc}    0
6756: +
6757: +Capture Summary
6758: +    [Arguments]    ${file}
6759: +    ${rc}    ${output} =    Run And Return Rc And Output    python3 ${summary-script} ${file}
6760: +    Log    ${output}
6761: +    Should Be Equal As Integers    ${rc}    0
6762: +    ${summary} =    Evaluate    json.loads($output)    modules=json
6763: +    RETURN    ${summary}
6764: +
6765: +Cleanup
6766: +    Run    ${CLAB_BIN} --runtime ${runtime} destroy -t ${topo} --cleanup
6767: +    Run    sudo rm -f ${pcap} ${stdout-pcap} ${interrupt-pcap} ${restart-pcap}
6768: diff --git a/tests/14-clabernetes/01-linux-lifecycle.robot b/tests/14-clabernetes/01-linux-lifecycle.robot
6769: index 1896ae4..f45a3ff 100644
6770: --- a/tests/14-clabernetes/01-linux-lifecycle.robot
6771: +++ b/tests/14-clabernetes/01-linux-lifecycle.robot
6772: @@ -23,10 +23,14 @@ ${events-err}           /tmp/clab-c9s-events.err
6773:  ${iface-events-log}     /tmp/clab-c9s-iface-events.log
6774:  ${iface-events-err}     /tmp/clab-c9s-iface-events.err
6775:  ${offline-env}          env CLAB_KUBECONFIG\=/nonexistent/kubeconfig KUBECONFIG\=/nonexistent/kubeconfig
6776:  ${recovery-timeout}     180s
6777:  ${retry-interval}       5s
6778: +${capture-file}         /tmp/clab-c9s-capture.pcapng
6779: +${chain-file}           /tmp/clab-c9s-capture-chain.pcapng
6780: +${stop-file}            /tmp/clab-c9s-capture-stop.pcapng
6781: +${stop-err}             /tmp/clab-c9s-capture-stop.err
6782:  
6783:  
6784:  *** Test Cases ***
6785:  Deploy c9s linux lab
6786:      ${output} =    Run Clab Command    deploy -t ${topo}
6787: @@ -130,10 +134,157 @@ Graph renders from the topology file without a cluster
6788:  
6789:  Exec into client and verify dataplane
6790:      Wait Until Keyword Succeeds    60s    ${retry-interval}    Client Eth1 Should Be Visible
6791:      Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Succeed
6792:  
6793: +Inspect interfaces lists the link interfaces with their state
6794: +    ${output} =    Run Clab Command    inspect interfaces -t ${topo} -f json
6795: +    Should Be Equal As Integers    ${output.rc}    0
6796: +    ${containers} =    Evaluate    json.loads($output.stdout)    modules=json
6797: +    Length Should Be    ${containers}    2
6798: +    FOR    ${container}    IN    @{containers}
6799: +        Should Match Regexp    ${container}[name]    ^${lab-name}-(client|server)$
6800: +        Length Should Be    ${container}[interfaces]    1
6801: +        ${iface} =    Set Variable    ${container}[interfaces][0]
6802: +        Should Be Equal    ${iface}[name]    eth1
6803: +        Should Be Equal    ${iface}[type]    veth
6804: +        Should Be Equal    ${iface}[state]    up
6805: +        Should Match Regexp    ${iface}[mac]    ^([0-9a-f]{2}:){5}[0-9a-f]{2}$
6806: +        Should Be True    ${iface}[ifindex] > 0 and ${iface}[mtu] > 0
6807: +    END
6808: +
6809: +    ${one} =    Run Clab Command    inspect interfaces --name ${lab-name} -n client -f json
6810: +    Should Be Equal As Integers    ${one.rc}    0
6811: +    ${only} =    Evaluate    [c["name"] for c in json.loads($one.stdout)]    modules=json
6812: +    Should Be Equal    ${only}    ${{["${lab-name}-client"]}}
6813: +
6814: +Capture lists the capturable interfaces with their peers
6815: +    ${output} =    Run Clab Command    capture -t ${topo} --list -f json
6816: +    Should Be Equal As Integers    ${output.rc}    0
6817: +    ${interfaces} =    Evaluate    json.loads($output.stdout)    modules=json
6818: +    ${want} =    Evaluate
6819: +    ...    [{"node": "client", "interface": "eth1", "peer_node": "server", "peer_interface": "eth1"}, {"node": "server", "interface": "eth1", "peer_node": "client", "peer_interface": "eth1"}]
6820: +    Should Be Equal    ${interfaces}    ${want}
6821: +
6822: +Capture both ends of a link into one pcapng stream
6823: +    Skip If    not shutil.which("tshark")    tshark is not installed
6824: +    Remove File If Exists    ${capture-file}
6825: +    Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 10 -i 0.3 10.10.10.2'
6826: +    ...    shell=True    alias=c9s_ping
6827: +    ${output} =    Run Clab Command
6828: +    ...    capture -t ${topo} --target client:eth1 --target server:eth1 --duration 5s -w ${capture-file}
6829: +    Wait For Process    c9s_ping    timeout=30s
6830: +    Should Be Equal As Integers    ${output.rc}    0
6831: +
6832: +    ${idbs} =    Process.Run Process    capinfos -T -m -I ${capture-file}    shell=True
6833: +    Log    ${idbs.stdout}
6834: +    ${names} =    Process.Run Process
6835: +    ...    tshark -r ${capture-file} -T fields -e frame.interface_name -Y icmp | sort | uniq -c
6836: +    ...    shell=True
6837: +    Log    ${names.stdout}
6838: +    Should Be Equal As Integers    ${names.rc}    0
6839: +    ${counts} =    Evaluate
6840: +    ...    {l.split()[1]: int(l.split()[0]) for l in $names.stdout.splitlines() if l.strip()}
6841: +    Should Be Equal    ${{sorted($counts)}}    ${{["client:eth1", "server:eth1"]}}
6842: +    Should Be True    ${counts}[client:eth1] >= 10 and ${counts}[server:eth1] >= 10
6843: +
6844: +    ${info} =    Process.Run Process    capinfos ${capture-file}    shell=True
6845: +    Log    ${info.stdout}
6846: +    Should Contain    ${info.stdout}    Number of interfaces in file: 2
6847: +    Should Contain    ${info.stdout}    Capture application: containerlab
6848: +    Should Contain    ${info.stdout}    nanoseconds
6849: +
6850: +    # the packets of both nodes are merged in timestamp order
6851: +    ${times} =    Process.Run Process
6852: +    ...    tshark -r ${capture-file} -T fields -e frame.time_epoch
6853: +    ...    shell=True
6854: +    Should Be Equal As Integers    ${times.rc}    0
6855: +    ${epochs} =    Evaluate    [decimal.Decimal(x) for x in $times.stdout.split()]    modules=decimal
6856: +    ${count} =    Get Length    ${epochs}
6857: +    Should Be True    ${count} >= 20    only ${count} packets
6858: +    ${inversions} =    Evaluate
6859: +    ...    [(i, str($epochs[i - 1]), str($epochs[i])) for i in range(1, len($epochs)) if $epochs[i] < $epochs[i - 1]]
6860: +    Should Be Empty    ${inversions}    frame.time_epoch decreases
6861: +    [Teardown]    Remove File If Exists    ${capture-file}
6862: +
6863: +Stopping a capture leaves no capture process in clabwire
6864: +    Skip If    not shutil.which("docker")    docker is needed to list the processes of a KinD worker
6865: +    Skip If    not shutil.which("capinfos")    capinfos is not installed
6866: +    Remove File If Exists    ${stop-file}
6867: +    Start Process    ${CLAB_BIN}    --runtime    ${runtime}    capture    -t    ${topo}
6868: +    ...    --target    client:eth1    --target    server:eth1    -w    ${stop-file}
6869: +    ...    alias=c9s_capture    stderr=${stop-err}
6870: +    Wait Until Keyword Succeeds    60s    1s    Capture Process Should Run In Clabwire    client
6871: +    Wait Until Keyword Succeeds    10s    1s    Capture Process Should Run In Clabwire    server
6872: +
6873: +    Send Signal To Process    SIGINT    c9s_capture
6874: +    ${result} =    Wait For Process    c9s_capture    timeout=30s    on_timeout=kill
6875: +    Log    ${result.stderr}
6876: +    Should Be Equal As Integers    ${result.rc}    0
6877: +    # Kubernetes does not stop an exec'd process when its stream closes; clabwire ends the
6878: +    # capture when containerlab closes its stdin
6879: +    Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    client
6880: +    Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    server
6881: +
6882: +    ${info} =    Process.Run Process    capinfos ${stop-file}    shell=True
6883: +    Should Be Equal As Integers    ${info.rc}    0
6884: +    Should Contain    ${info.stdout}    Number of interfaces in file: 2
6885: +    [Teardown]    Run Keywords    Remove File If Exists    ${stop-file}
6886: +    ...    AND    Remove File If Exists    ${stop-err}
6887: +
6888: +Capture chains segments without duplicates or gaps
6889: +    Skip If    not shutil.which("tshark")    tshark is not installed
6890: +    Remove File If Exists    ${chain-file}
6891: +    Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 130 -i 0.2 10.10.10.2'
6892: +    ...    shell=True    alias=c9s_ping
6893: +    Sleep    1s
6894: +    # a 6 s segment length forces four switches in 20 s
6895: +    ${output} =    Process.Run Process
6896: +    ...    ${CLAB_BIN} --runtime ${runtime} --log-level debug capture -t ${topo} --target client:eth1 --duration 20s -w ${chain-file}
6897: +    ...    shell=True
6898: +    ...    env:CLAB_C9S_CAPTURE_SEGMENT=6s
6899: +    Log    ${output.stderr}
6900: +    Wait For Process    c9s_ping    timeout=60s
6901: +    Should Be Equal As Integers    ${output.rc}    0
6902: +    Should Contain    ${output.stderr}    segment=4
6903: +    Should Not Contain    ${output.stderr}    gap
6904: +
6905: +    ${seqs} =    Process.Run Process
6906: +    ...    tshark -r ${chain-file} -Y 'icmp.type \=\= 8' -T fields -e icmp.seq
6907: +    ...    shell=True
6908: +    Should Be Equal As Integers    ${seqs.rc}    0
6909: +    ${numbers} =    Evaluate    [int(x) for x in $seqs.stdout.split()]
6910: +    ${count} =    Get Length    ${numbers}
6911: +    Should Be True    ${count} >= 90    only ${count} echo requests
6912: +    ${unique} =    Evaluate    len(set($numbers))
6913: +    Should Be Equal As Integers    ${unique}    ${count}    duplicate echo requests
6914: +    ${span} =    Evaluate    max($numbers) - min($numbers) + 1
6915: +    Should Be Equal As Integers    ${span}    ${count}    missing echo requests
6916: +    [Teardown]    Remove File If Exists    ${chain-file}
6917: +
6918: +Capture works for a lab editor and is forbidden without a binding
6919: +    ${rbac} =    Process.Run Process
6920: +    ...    kubectl -n ${lab-namespace} create serviceaccount capture-editor && kubectl -n ${lab-namespace} create rolebinding capture-editor --clusterrole\=clabernetes-lab-editor --serviceaccount\=${lab-namespace}:capture-editor
6921: +    ...    shell=True
6922: +    Log    ${rbac.stdout}${\n}${rbac.stderr}
6923: +    Should Be Equal As Integers    ${rbac.rc}    0
6924: +
6925: +    ${result} =    Process.Run Process
6926: +    ...    go test ./core/ -run TestC9sClusterCapture -count\=1 -v
6927: +    ...    shell=True
6928: +    ...    cwd=${CURDIR}/../..
6929: +    ...    env:CLAB_C9S_TEST_LAB=${lab-name}
6930: +    ...    env:CLAB_C9S_TEST_CAPTURE_USER=system:serviceaccount:${lab-namespace}:capture-editor
6931: +    ...    env:CLAB_C9S_TEST_FORBIDDEN_USER=system:serviceaccount:${lab-namespace}:nobody
6932: +    Log    ${result.stdout}${\n}${result.stderr}    console=${True}
6933: +    Should Be Equal As Integers    ${result.rc}    0
6934: +    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/capture_both_ends_of_a_link
6935: +    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/restart_as_lab_editor
6936: +    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/forbidden_identity
6937: +    Should Not Contain    ${result.stdout}    SKIP
6938: +    Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed
6939: +
6940:  Logs shows the device container log
6941:      ${result} =    Run Clab Command    logs -t ${topo} -n client --tail 2 --timestamps
6942:      Should Be Equal As Integers    ${result.rc}    0
6943:      ${lines} =    Split To Lines    ${result.stdout}
6944:      ${count} =    Get Length    ${lines}
6945: @@ -411,10 +562,32 @@ Run Clab Command
6946:      ...    shell=True
6947:      Log    stdout:${\n}${output.stdout}    console=${True}
6948:      Log    stderr:${\n}${output.stderr}    console=${True}
6949:      RETURN    ${output}
6950:  
6951: +Clabwire Capture Processes
6952: +    [Arguments]    ${node}
6953: +    ${result} =    Process.Run Process
6954: +    ...    ${CURDIR}/clabwire-captures.sh ${lab-namespace} ${node}
6955: +    ...    shell=True
6956: +    Log    ${result.stdout}${\n}${result.stderr}
6957: +    Should Be Equal As Integers    ${result.rc}    0
6958: +    ${lines} =    Get Lines Containing String    ${result.stdout}    packet-capture
6959: +    ${count} =    Get Line Count    ${lines}
6960: +    RETURN    ${count}
6961: +
6962: +Capture Process Should Run In Clabwire
6963: +    [Arguments]    ${node}
6964: +    ${count} =    Clabwire Capture Processes    ${node}
6965: +    Should Be True    ${count} > 0    no packet-capture process in the clabwire container of ${node}
6966: +
6967: +No Capture Process Should Run In Clabwire
6968: +    [Arguments]    ${node}
6969: +    ${count} =    Clabwire Capture Processes    ${node}
6970: +    Should Be Equal As Integers    ${count}    0
6971: +    ...    ${count} packet-capture processes still run in the clabwire container of ${node}
6972: +
6973:  Ping From Client Should Succeed
6974:      ${output} =    Run Clab Command
6975:      ...    exec -t ${topo} --label ${client-label} --cmd 'ping -c 1 -W 2 10.10.10.2'
6976:      ${combined} =    Catenate    SEPARATOR=\n    ${output.stdout}    ${output.stderr}
6977:      Should Be Equal As Integers    ${output.rc}    0
6978: diff --git a/tests/14-clabernetes/clabwire-captures.sh b/tests/14-clabernetes/clabwire-captures.sh
6979: new file mode 100755
6980: index 0000000..14833b3
6981: --- /dev/null
6982: +++ b/tests/14-clabernetes/clabwire-captures.sh
6983: @@ -0,0 +1,35 @@
6984: +#!/bin/sh
6985: +# Prints the packet-capture processes running in the clabwire container of a c9s node's pod.
6986: +# usage: clabwire-captures.sh <namespace> <node>
6987: +#
6988: +# A process of a Kubernetes exec is not visible through the API, so this looks at the worker
6989: +# that runs the pod: a KinD node, which is a Docker container. It lists the processes whose
6990: +# cgroup belongs to the clabwire container. Exits 2 when the worker is not a Docker container.
6991: +set -eu
6992: +
6993: +namespace=$1
6994: +node=$2
6995: +
6996: +pod=$(kubectl -n "$namespace" get pod -l "c9s.run/topologyNode=$node" \
6997: +  -o jsonpath='{.items[0].metadata.name}')
6998: +worker=$(kubectl -n "$namespace" get pod "$pod" -o jsonpath='{.spec.nodeName}')
6999: +# clabwire is a sidecar (an init container that keeps running)
7000: +container=$(kubectl -n "$namespace" get pod "$pod" -o jsonpath=\
7001: +'{.status.initContainerStatuses[?(@.name=="clabwire")].containerID}{.status.containerStatuses[?(@.name=="clabwire")].containerID}')
7002: +container=${container#*://}
7003: +
7004: +if ! docker inspect --type container "$worker" >/dev/null 2>&1; then
7005: +  echo "worker $worker of pod $namespace/$pod is not a Docker container (KinD)" >&2
7006: +  exit 2
7007: +fi
7008: +if [ -z "$container" ]; then
7009: +  echo "pod $namespace/$pod has no running clabwire container" >&2
7010: +  exit 1
7011: +fi
7012: +
7013: +docker exec "$worker" sh -c "
7014: +  for proc in /proc/[0-9]*; do
7015: +    if grep -qs '$container' \"\$proc/cgroup\"; then
7016: +      tr '\\0' ' ' < \"\$proc/cmdline\" 2>/dev/null && echo
7017: +    fi
7018: +  done" | grep 'packet-capture' || true

(End of file - total 7018 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19650ca73001VQBe8E937D7U6V",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650be85001Eha5NBjsp4KX8c",
  "callID": "call_03dccb7e27a343d4a75df172",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "offset": 6410
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n6410: +\t// when the runtime cannot name it.\n6411: +\tPeerNode string `json:\"peer_node\"`\n6412: +\t// PeerInterface is the peer's interface as the topology wrote it.\n6413: +\tPeerInterface string `json:\"peer_interface\"`\n6414: +}\n6415: +\n6416: +// CaptureTarget is one interface of one node to capture. Node takes the name the topology or\n6417: +// the runtime uses, Interface the interface name or its alias.\n6418: +type CaptureTarget struct {\n6419: +\tNode      string\n6420: +\tInterface string\n6421: +}\n6422: +\n6423: +// CaptureRequest selects what Capture streams.\n6424: +type CaptureRequest struct {\n6425: +\t// Name is the lab name.\n6426: +\tName      string\n6427: +\tNamespace string\n6428: +\tTargets   []CaptureTarget\n6429: +\t// Duration ends the capture; zero captures until the context ends.\n6430: +\tDuration time.Duration\n6431: +\t// PacketLimit ends the capture after that many packets across all targets; zero means no\n6432: +\t// limit.\n6433: +\tPacketLimit int\n6434: +\t// SnapLength is the number of bytes kept of each packet; zero uses the runtime default.\n6435: +\tSnapLength int\n6436: +\t// OnGap is called when the capture missed traffic, for example because a chained capture\n6437: +\t// did not start in time. Without it, gaps are logged as warnings.\n6438: +\tOnGap    func(CaptureGap)\n6439: +\tIdentity Identity\n6440: +}\n6441: +\n6442: +// CaptureGap is a time span a capture has no packets for, although it was running.\n6443: +type CaptureGap struct {\n6444: +\tNode       string\n6445: +\tInterfaces []string\n6446: +\t// From and To bound the gap on the node's clock; To is zero when it is unknown.\n6447: +\tFrom   time.Time\n6448: +\tTo     time.Time\n6449: +\tReason string\n6450: +}\n6451: +\n6452: +// PacketCapturer streams pcapng from lab link interfaces. Capture writes one section with one\n6453: +// Interface Description Block per target, named <node>:<interface>, before any packet. It\n6454: +// returns when Duration passed, PacketLimit packets were written, or the context ended (which\n6455: +// is not an error); the output is a valid capture whenever it stops.\n6456: +type PacketCapturer interface {\n6457: +\tCaptureInterfaces(ctx context.Context, req NodeRequest) ([]CaptureInterface, error)\n6458: +\tCapture(ctx context.Context, req CaptureRequest, w io.Writer) error\n6459: +}\n6460: +\n6461: +// InterfaceInspector lists the link interfaces of a lab's nodes with their current state, in the\n6462: +// shape of `inspect interfaces`.\n6463: +type InterfaceInspector interface {\n6464: +\tInspectInterfaces(\n6465: +\t\tctx context.Context,\n6466: +\t\treq NodeRequest,\n6467: +\t) ([]*clabtypes.ContainerInterfaces, error)\n6468: +}\n6469: +\n6470:  // NodeStatsSampler reports the resource usage of a lab's nodes. It returns an error wrapping\n6471:  // ErrMetricsUnavailable when the cluster serves no resource metrics.\n6472:  type NodeStatsSampler interface {\n6473:  \tSampleStats(ctx context.Context, req InspectRequest) ([]NodeStats, error)\n6474:  }\n6475: diff --git a/mkdocs.yml b/mkdocs.yml\n6476: index 0285ad6..8dc17bd 100644\n6477: --- a/mkdocs.yml\n6478: +++ b/mkdocs.yml\n6479: @@ -117,10 +117,11 @@ nav:\n6480:        - inspect:\n6481:            - cmd/inspect/index.md\n6482:            - interfaces: cmd/inspect/interfaces.md\n6483:        - events: cmd/events.md\n6484:        - logs: cmd/logs.md\n6485: +      - capture: cmd/capture.md\n6486:        - save: cmd/save.md\n6487:        - exec: cmd/exec.md\n6488:        - generate: cmd/generate.md\n6489:        - graph: cmd/graph.md\n6490:        - validate: cmd/validate.md\n6491: diff --git a/tests/01-smoke/33-capture-summary.py b/tests/01-smoke/33-capture-summary.py\n6492: new file mode 100755\n6493: index 0000000..d49014c\n6494: --- /dev/null\n6495: +++ b/tests/01-smoke/33-capture-summary.py\n6496: @@ -0,0 +1,69 @@\n6497: +#!/usr/bin/env python3\n6498: +# Copyright 2020 Nokia\n6499: +# Licensed under the BSD 3-Clause License.\n6500: +# SPDX-License-Identifier: BSD-3-Clause\n6501: +\"\"\"Summarize a little-endian pcapng file as containerlab capture writes it, as JSON.\n6502: +\n6503: +Prints the number of sections, the interface names in order, the packet count per interface,\n6504: +whether packets are in timestamp order, the number of 802.1Q tagged frames and the number of\n6505: +ICMP echo requests and replies (untagged or tagged).\n6506: +\"\"\"\n6507: +\n6508: +import json\n6509: +import struct\n6510: +import sys\n6511: +\n6512: +SHB, IDB, EPB = 0x0A0D0D0A, 0x00000001, 0x00000006\n6513: +\n6514: +\n6515: +def main(path):\n6516: +    with open(path, \"rb\") as f:\n6517: +        data = f.read()\n6518: +\n6519: +    sections, names, counts, stamps = 0, [], {}, []\n6520: +    vlan, echo = 0, 0\n6521: +    offset = 0\n6522: +    while offset < len(data):\n6523: +        block_type, length = struct.unpack_from(\"<II\", data, offset)\n6524: +        body = data[offset + 8 : offset + length - 4]\n6525: +        if block_type == SHB:\n6526: +            sections += 1\n6527: +        elif block_type == IDB:\n6528: +            options, name = body[8:], \"\"\n6529: +            while len(options) >= 4:\n6530: +                code, size = struct.unpack_from(\"<HH\", options)\n6531: +                if code == 0:\n6532: +                    break\n6533: +                if code == 2:\n6534: +                    name = options[4 : 4 + size].decode()\n6535: +                options = options[4 + size + (4 - size % 4) % 4 :]\n6536: +            names.append(name)\n6537: +        elif block_type == EPB:\n6538: +            iface, high, low, captured = struct.unpack_from(\"<IIII\", body)\n6539: +            frame = body[20 : 20 + captured]\n6540: +            counts[names[iface]] = counts.get(names[iface], 0) + 1\n6541: +            stamps.append(high << 32 | low)\n6542: +            ethertype, l3 = struct.unpack_from(\">H\", frame, 12)[0], 14\n6543: +            if ethertype == 0x8100:\n6544: +                vlan += 1\n6545: +                ethertype, l3 = struct.unpack_from(\">H\", frame, 16)[0], 18\n6546: +            if ethertype == 0x0800 and frame[l3 + 9] == 1 and frame[l3 + 20] in (0, 8):\n6547: +                echo += 1\n6548: +        offset += length\n6549: +\n6550: +    print(\n6551: +        json.dumps(\n6552: +            {\n6553: +                \"sections\": sections,\n6554: +                \"interfaces\": names,\n6555: +                \"packets\": counts,\n6556: +                \"ordered\": stamps == sorted(stamps),\n6557: +                \"vlan_frames\": vlan,\n6558: +                \"icmp_echo\": echo,\n6559: +            }\n6560: +        )\n6561: +    )\n6562: +\n6563: +\n6564: +if __name__ == \"__main__\":\n6565: +    main(sys.argv[1])\n6566: diff --git a/tests/01-smoke/33-capture.clab.yml b/tests/01-smoke/33-capture.clab.yml\n6567: new file mode 100644\n6568: index 0000000..3f70288\n6569: --- /dev/null\n6570: +++ b/tests/01-smoke/33-capture.clab.yml\n6571: @@ -0,0 +1,29 @@\n6572: +# yaml-language-server: $schema=../../schemas/clab.schema.json\n6573: +name: capture\n6574: +\n6575: +topology:\n6576: +  nodes:\n6577: +    l1:\n6578: +      kind: linux\n6579: +      image: alpine:3\n6580: +      exec:\n6581: +        - ip addr add 10.0.0.1/24 dev eth1\n6582: +        - ip link add link eth1 name eth1.10 type vlan id 10\n6583: +        - ip addr add 10.10.0.1/24 dev eth1.10\n6584: +        - ip link set eth1.10 up\n6585: +    l2:\n6586: +      kind: linux\n6587: +      image: alpine:3\n6588: +      exec:\n6589: +        - ip addr add 10.0.0.2/24 dev eth1\n6590: +        - ip link add link eth1 name eth1.10 type vlan id 10\n6591: +        - ip addr add 10.10.0.2/24 dev eth1.10\n6592: +        - ip link set eth1.10 up\n6593: +\n6594: +  links:\n6595: +    - endpoints: [\"l1:eth1\", \"l2:eth1\"]\n6596: +    - type: host\n6597: +      host-interface: capl2eth2\n6598: +      endpoint:\n6599: +        node: l2\n6600: +        interface: eth2\n6601: diff --git a/tests/01-smoke/33-capture.robot b/tests/01-smoke/33-capture.robot\n6602: new file mode 100644\n6603: index 0000000..9502a8e\n6604: --- /dev/null\n6605: +++ b/tests/01-smoke/33-capture.robot\n6606: @@ -0,0 +1,161 @@\n6607: +*** Comments ***\n6608: +This suite tests the capture command with the local container runtimes: containerlab reads the\n6609: +lab link interfaces through packet sockets in the nodes' network namespaces.\n6610: +\n6611: +\n6612: +*** Settings ***\n6613: +Library             OperatingSystem\n6614: +Library             Process\n6615: +Library             String\n6616: +Library             Collections\n6617: +Resource            ../common.robot\n6618: +\n6619: +Suite Setup         Run    ${CLAB_BIN} --runtime ${runtime} destroy -t ${topo} --cleanup\n6620: +Suite Teardown      Cleanup\n6621: +\n6622: +\n6623: +*** Variables ***\n6624: +${lab-name}         capture\n6625: +${topo}             ${CURDIR}/33-capture.clab.yml\n6626: +${runtime}          docker\n6627: +${summary-script}   ${CURDIR}/33-capture-summary.py\n6628: +${pcap}             /tmp/clab-capture.pcapng\n6629: +${stdout-pcap}      /tmp/clab-capture-stdout.pcapng\n6630: +${interrupt-pcap}   /tmp/clab-capture-interrupt.pcapng\n6631: +${restart-pcap}     /tmp/clab-capture-restart.pcapng\n6632: +\n6633: +\n6634: +*** Test Cases ***\n6635: +Deploy ${lab-name} lab\n6636: +    ${rc}    ${output} =    Run And Return Rc And Output\n6637: +    ...    ${CLAB_BIN} --runtime ${runtime} deploy -t ${topo}\n6638: +    Log    ${output}\n6639: +    Should Be Equal As Integers    ${rc}    0\n6640: +\n6641: +List the capturable interfaces\n6642: +    ${result} =    Run Capture    --name ${lab-name} --list -f json\n6643: +    Should Be Equal As Integers    ${result.rc}    0\n6644: +    ${interfaces} =    Evaluate    json.loads($result.stdout)    modules=json\n6645: +    Length Should Be    ${interfaces}    3\n6646: +    Should Be Equal    ${interfaces}[0][node]    l1\n6647: +    Should Be Equal    ${interfaces}[0][interface]    eth1\n6648: +    Should Be Equal    ${interfaces}[0][peer_node]    l2\n6649: +    Should Be Equal    ${interfaces}[2][node]    l2\n6650: +    Should Be Equal    ${interfaces}[2][interface]    eth2\n6651: +    Should Be Equal    ${interfaces}[2][peer_node]    host\n6652: +    Should Be Equal    ${interfaces}[2][peer_interface]    capl2eth2\n6653: +\n6654: +Capture both ends of a link with VLAN traffic\n6655: +    Start Process\n6656: +    ...    ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l1:eth1 --target l2:eth1 --duration 8s -w ${pcap}\n6657: +    ...    shell=True\n6658: +    ...    alias=both-ends\n6659: +    Sleep    2s\n6660: +    Ping From L1    10.0.0.2\n6661: +    Ping From L1    10.10.0.2\n6662: +    ${result} =    Wait For Process    both-ends    timeout=30s    on_timeout=kill\n6663: +    Log    ${result.stderr}\n6664: +    Should Be Equal As Integers    ${result.rc}    0\n6665: +    ${summary} =    Capture Summary    ${pcap}\n6666: +    Should Be Equal As Integers    ${summary}[sections]    1\n6667: +    ${want} =    Create List    l1:eth1    l2:eth1\n6668: +    Lists Should Be Equal    ${summary}[interfaces]    ${want}\n6669: +    Should Be True    ${summary}[ordered]\n6670: +    # 6 pings, each request and reply seen on both ends\n6671: +    Should Be True    ${summary}[icmp_echo] >= 24\n6672: +    # the VLAN 10 pings keep their 802.1Q tag\n6673: +    Should Be True    ${summary}[vlan_frames] >= 12\n6674: +\n6675: +Capture to stdout stops at the packet limit\n6676: +    Start Process\n6677: +    ...    sleep 1 && sudo ${runtime} exec clab-${lab-name}-l1 ping -c 20 -i 0.2 10.0.0.2\n6678: +    ...    shell=True\n6679: +    ...    alias=background-ping\n6680: +    ${result} =    Process.Run Process\n6681: +    ...    ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l2:eth1 --packet-limit 6 -w - > ${stdout-pcap}\n6682: +    ...    shell=True\n6683: +    ...    timeout=30s\n6684: +    ...    on_timeout=kill\n6685: +    Log    ${result.stderr}\n6686: +    Should Be Equal As Integers    ${result.rc}    0\n6687: +    ${summary} =    Capture Summary    ${stdout-pcap}\n6688: +    Should Be Equal As Integers    ${summary}[packets][l2:eth1]    6\n6689: +    [Teardown]    Terminate Process    background-ping    kill=True\n6690: +\n6691: +An interrupt ends the capture with a valid file\n6692: +    Start Process\n6693: +    ...    exec ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l1:eth1 -w ${interrupt-pcap}\n6694: +    ...    shell=True\n6695: +    ...    alias=interrupted\n6696: +    Sleep    2s\n6697: +    Ping From L1    10.0.0.2\n6698: +    Send Signal To Process    SIGINT    interrupted\n6699: +    ${result} =    Wait For Process    interrupted    timeout=15s    on_timeout=kill\n6700: +    Log    ${result.stderr}\n6701: +    Should Be Equal As Integers    ${result.rc}    0\n6702: +    ${summary} =    Capture Summary    ${interrupt-pcap}\n6703: +    Should Be True    ${summary}[icmp_echo] >= 6\n6704: +\n6705: +The capture reattaches an interface after its node restarts\n6706: +    Start Process\n6707: +    ...    exec ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l2:eth1 -w ${restart-pcap}\n6708: +    ...    shell=True\n6709: +    ...    alias=restarted\n6710: +    Sleep    2s\n6711: +    Ping From L1    10.0.0.2\n6712: +    ${rc}    ${output} =    Run And Return Rc And Output\n6713: +    ...    ${CLAB_BIN} --runtime ${runtime} restart -t ${topo} --node l2\n6714: +    Log    ${output}\n6715: +    Should Be Equal As Integers    ${rc}    0\n6716: +    ${rc}    ${output} =    Run And Return Rc And Output\n6717: +    ...    sudo ${runtime} exec clab-${lab-name}-l2 ip addr replace 10.0.0.2/24 dev eth1\n6718: +    Log    ${output}\n6719: +    Wait Until Keyword Succeeds    20s    1s    Ping From L1    10.0.0.2\n6720: +    # the capture reattaches within a fraction of a second after the link is back\n6721: +    Sleep    1s\n6722: +    Ping From L1    10.0.0.2\n6723: +    Send Signal To Process    SIGINT    restarted\n6724: +    ${result} =    Wait For Process    restarted    timeout=15s    on_timeout=kill\n6725: +    Log    ${result.stderr}\n6726: +    Should Be Equal As Integers    ${result.rc}    0\n6727: +    Should Contain    ${result.stderr}    Capture has a gap\n6728: +    ${summary} =    Capture Summary    ${restart-pcap}\n6729: +    # 3 pings before and 3 after the reattach, request and reply each\n6730: +    Should Be True    ${summary}[icmp_echo] >= 12\n6731: +\n6732: +The capture rejects the management interface\n6733: +    ${result} =    Run Capture    --name ${lab-name} --target l1:eth0 -w /dev/null\n6734: +    Should Not Be Equal As Integers    ${result.rc}    0\n6735: +    Should Contain    ${result.stderr}    not a capturable link interface; capturable: eth1\n6736: +\n6737: +\n6738: +*** Keywords ***\n6739: +Run Capture\n6740: +    [Arguments]    ${args}\n6741: +    ${result} =    Process.Run Process\n6742: +    ...    ${CLAB_BIN} --runtime ${runtime} capture ${args}\n6743: +    ...    shell=True\n6744: +    ...    timeout=60s\n6745: +    ...    on_timeout=kill\n6746: +    Log    stdout:${\\n}${result.stdout}\n6747: +    Log    stderr:${\\n}${result.stderr}\n6748: +    RETURN    ${result}\n6749: +\n6750: +Ping From L1\n6751: +    [Arguments]    ${address}\n6752: +    ${rc}    ${output} =    Run And Return Rc And Output\n6753: +    ...    sudo ${runtime} exec clab-${lab-name}-l1 ping -c 3 -i 0.2 -W 1 ${address}\n6754: +    Log    ${output}\n6755: +    Should Be Equal As Integers    ${rc}    0\n6756: +\n6757: +Capture Summary\n6758: +    [Arguments]    ${file}\n6759: +    ${rc}    ${output} =    Run And Return Rc And Output    python3 ${summary-script} ${file}\n6760: +    Log    ${output}\n6761: +    Should Be Equal As Integers    ${rc}    0\n6762: +    ${summary} =    Evaluate    json.loads($output)    modules=json\n6763: +    RETURN    ${summary}\n6764: +\n6765: +Cleanup\n6766: +    Run    ${CLAB_BIN} --runtime ${runtime} destroy -t ${topo} --cleanup\n6767: +    Run    sudo rm -f ${pcap} ${stdout-pcap} ${interrupt-pcap} ${restart-pcap}\n6768: diff --git a/tests/14-clabernetes/01-linux-lifecycle.robot b/tests/14-clabernetes/01-linux-lifecycle.robot\n6769: index 1896ae4..f45a3ff 100644\n6770: --- a/tests/14-clabernetes/01-linux-lifecycle.robot\n6771: +++ b/tests/14-clabernetes/01-linux-lifecycle.robot\n6772: @@ -23,10 +23,14 @@ ${events-err}           /tmp/clab-c9s-events.err\n6773:  ${iface-events-log}     /tmp/clab-c9s-iface-events.log\n6774:  ${iface-events-err}     /tmp/clab-c9s-iface-events.err\n6775:  ${offline-env}          env CLAB_KUBECONFIG\\=/nonexistent/kubeconfig KUBECONFIG\\=/nonexistent/kubeconfig\n6776:  ${recovery-timeout}     180s\n6777:  ${retry-interval}       5s\n6778: +${capture-file}         /tmp/clab-c9s-capture.pcapng\n6779: +${chain-file}           /tmp/clab-c9s-capture-chain.pcapng\n6780: +${stop-file}            /tmp/clab-c9s-capture-stop.pcapng\n6781: +${stop-err}             /tmp/clab-c9s-capture-stop.err\n6782:  \n6783:  \n6784:  *** Test Cases ***\n6785:  Deploy c9s linux lab\n6786:      ${output} =    Run Clab Command    deploy -t ${topo}\n6787: @@ -130,10 +134,157 @@ Graph renders from the topology file without a cluster\n6788:  \n6789:  Exec into client and verify dataplane\n6790:      Wait Until Keyword Succeeds    60s    ${retry-interval}    Client Eth1 Should Be Visible\n6791:      Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Succeed\n6792:  \n6793: +Inspect interfaces lists the link interfaces with their state\n6794: +    ${output} =    Run Clab Command    inspect interfaces -t ${topo} -f json\n6795: +    Should Be Equal As Integers    ${output.rc}    0\n6796: +    ${containers} =    Evaluate    json.loads($output.stdout)    modules=json\n6797: +    Length Should Be    ${containers}    2\n6798: +    FOR    ${container}    IN    @{containers}\n6799: +        Should Match Regexp    ${container}[name]    ^${lab-name}-(client|server)$\n6800: +        Length Should Be    ${container}[interfaces]    1\n6801: +        ${iface} =    Set Variable    ${container}[interfaces][0]\n6802: +        Should Be Equal    ${iface}[name]    eth1\n6803: +        Should Be Equal    ${iface}[type]    veth\n6804: +        Should Be Equal    ${iface}[state]    up\n6805: +        Should Match Regexp    ${iface}[mac]    ^([0-9a-f]{2}:){5}[0-9a-f]{2}$\n6806: +        Should Be True    ${iface}[ifindex] > 0 and ${iface}[mtu] > 0\n6807: +    END\n6808: +\n6809: +    ${one} =    Run Clab Command    inspect interfaces --name ${lab-name} -n client -f json\n6810: +    Should Be Equal As Integers    ${one.rc}    0\n6811: +    ${only} =    Evaluate    [c[\"name\"] for c in json.loads($one.stdout)]    modules=json\n6812: +    Should Be Equal    ${only}    ${{[\"${lab-name}-client\"]}}\n6813: +\n6814: +Capture lists the capturable interfaces with their peers\n6815: +    ${output} =    Run Clab Command    capture -t ${topo} --list -f json\n6816: +    Should Be Equal As Integers    ${output.rc}    0\n6817: +    ${interfaces} =    Evaluate    json.loads($output.stdout)    modules=json\n6818: +    ${want} =    Evaluate\n6819: +    ...    [{\"node\": \"client\", \"interface\": \"eth1\", \"peer_node\": \"server\", \"peer_interface\": \"eth1\"}, {\"node\": \"server\", \"interface\": \"eth1\", \"peer_node\": \"client\", \"peer_interface\": \"eth1\"}]\n6820: +    Should Be Equal    ${interfaces}    ${want}\n6821: +\n6822: +Capture both ends of a link into one pcapng stream\n6823: +    Skip If    not shutil.which(\"tshark\")    tshark is not installed\n6824: +    Remove File If Exists    ${capture-file}\n6825: +    Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 10 -i 0.3 10.10.10.2'\n6826: +    ...    shell=True    alias=c9s_ping\n6827: +    ${output} =    Run Clab Command\n6828: +    ...    capture -t ${topo} --target client:eth1 --target server:eth1 --duration 5s -w ${capture-file}\n6829: +    Wait For Process    c9s_ping    timeout=30s\n6830: +    Should Be Equal As Integers    ${output.rc}    0\n6831: +\n6832: +    ${idbs} =    Process.Run Process    capinfos -T -m -I ${capture-file}    shell=True\n6833: +    Log    ${idbs.stdout}\n6834: +    ${names} =    Process.Run Process\n6835: +    ...    tshark -r ${capture-file} -T fields -e frame.interface_name -Y icmp | sort | uniq -c\n6836: +    ...    shell=True\n6837: +    Log    ${names.stdout}\n6838: +    Should Be Equal As Integers    ${names.rc}    0\n6839: +    ${counts} =    Evaluate\n6840: +    ...    {l.split()[1]: int(l.split()[0]) for l in $names.stdout.splitlines() if l.strip()}\n6841: +    Should Be Equal    ${{sorted($counts)}}    ${{[\"client:eth1\", \"server:eth1\"]}}\n6842: +    Should Be True    ${counts}[client:eth1] >= 10 and ${counts}[server:eth1] >= 10\n6843: +\n6844: +    ${info} =    Process.Run Process    capinfos ${capture-file}    shell=True\n6845: +    Log    ${info.stdout}\n6846: +    Should Contain    ${info.stdout}    Number of interfaces in file: 2\n6847: +    Should Contain    ${info.stdout}    Capture application: containerlab\n6848: +    Should Contain    ${info.stdout}    nanoseconds\n6849: +\n6850: +    # the packets of both nodes are merged in timestamp order\n6851: +    ${times} =    Process.Run Process\n6852: +    ...    tshark -r ${capture-file} -T fields -e frame.time_epoch\n6853: +    ...    shell=True\n6854: +    Should Be Equal As Integers    ${times.rc}    0\n6855: +    ${epochs} =    Evaluate    [decimal.Decimal(x) for x in $times.stdout.split()]    modules=decimal\n6856: +    ${count} =    Get Length    ${epochs}\n6857: +    Should Be True    ${count} >= 20    only ${count} packets\n6858: +    ${inversions} =    Evaluate\n6859: +    ...    [(i, str($epochs[i - 1]), str($epochs[i])) for i in range(1, len($epochs)) if $epochs[i] < $epochs[i - 1]]\n6860: +    Should Be Empty    ${inversions}    frame.time_epoch decreases\n6861: +    [Teardown]    Remove File If Exists    ${capture-file}\n6862: +\n6863: +Stopping a capture leaves no capture process in clabwire\n6864: +    Skip If    not shutil.which(\"docker\")    docker is needed to list the processes of a KinD worker\n6865: +    Skip If    not shutil.which(\"capinfos\")    capinfos is not installed\n6866: +    Remove File If Exists    ${stop-file}\n6867: +    Start Process    ${CLAB_BIN}    --runtime    ${runtime}    capture    -t    ${topo}\n6868: +    ...    --target    client:eth1    --target    server:eth1    -w    ${stop-file}\n6869: +    ...    alias=c9s_capture    stderr=${stop-err}\n6870: +    Wait Until Keyword Succeeds    60s    1s    Capture Process Should Run In Clabwire    client\n6871: +    Wait Until Keyword Succeeds    10s    1s    Capture Process Should Run In Clabwire    server\n6872: +\n6873: +    Send Signal To Process    SIGINT    c9s_capture\n6874: +    ${result} =    Wait For Process    c9s_capture    timeout=30s    on_timeout=kill\n6875: +    Log    ${result.stderr}\n6876: +    Should Be Equal As Integers    ${result.rc}    0\n6877: +    # Kubernetes does not stop an exec'd process when its stream closes; clabwire ends the\n6878: +    # capture when containerlab closes its stdin\n6879: +    Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    client\n6880: +    Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    server\n6881: +\n6882: +    ${info} =    Process.Run Process    capinfos ${stop-file}    shell=True\n6883: +    Should Be Equal As Integers    ${info.rc}    0\n6884: +    Should Contain    ${info.stdout}    Number of interfaces in file: 2\n6885: +    [Teardown]    Run Keywords    Remove File If Exists    ${stop-file}\n6886: +    ...    AND    Remove File If Exists    ${stop-err}\n6887: +\n6888: +Capture chains segments without duplicates or gaps\n6889: +    Skip If    not shutil.which(\"tshark\")    tshark is not installed\n6890: +    Remove File If Exists    ${chain-file}\n6891: +    Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 130 -i 0.2 10.10.10.2'\n6892: +    ...    shell=True    alias=c9s_ping\n6893: +    Sleep    1s\n6894: +    # a 6 s segment length forces four switches in 20 s\n6895: +    ${output} =    Process.Run Process\n6896: +    ...    ${CLAB_BIN} --runtime ${runtime} --log-level debug capture -t ${topo} --target client:eth1 --duration 20s -w ${chain-file}\n6897: +    ...    shell=True\n6898: +    ...    env:CLAB_C9S_CAPTURE_SEGMENT=6s\n6899: +    Log    ${output.stderr}\n6900: +    Wait For Process    c9s_ping    timeout=60s\n6901: +    Should Be Equal As Integers    ${output.rc}    0\n6902: +    Should Contain    ${output.stderr}    segment=4\n6903: +    Should Not Contain    ${output.stderr}    gap\n6904: +\n6905: +    ${seqs} =    Process.Run Process\n6906: +    ...    tshark -r ${chain-file} -Y 'icmp.type \\=\\= 8' -T fields -e icmp.seq\n6907: +    ...    shell=True\n6908: +    Should Be Equal As Integers    ${seqs.rc}    0\n6909: +    ${numbers} =    Evaluate    [int(x) for x in $seqs.stdout.split()]\n6910: +    ${count} =    Get Length    ${numbers}\n6911: +    Should Be True    ${count} >= 90    only ${count} echo requests\n6912: +    ${unique} =    Evaluate    len(set($numbers))\n6913: +    Should Be Equal As Integers    ${unique}    ${count}    duplicate echo requests\n6914: +    ${span} =    Evaluate    max($numbers) - min($numbers) + 1\n6915: +    Should Be Equal As Integers    ${span}    ${count}    missing echo requests\n6916: +    [Teardown]    Remove File If Exists    ${chain-file}\n6917: +\n6918: +Capture works for a lab editor and is forbidden without a binding\n6919: +    ${rbac} =    Process.Run Process\n6920: +    ...    kubectl -n ${lab-namespace} create serviceaccount capture-editor && kubectl -n ${lab-namespace} create rolebinding capture-editor --clusterrole\\=clabernetes-lab-editor --serviceaccount\\=${lab-namespace}:capture-editor\n6921: +    ...    shell=True\n6922: +    Log    ${rbac.stdout}${\\n}${rbac.stderr}\n6923: +    Should Be Equal As Integers    ${rbac.rc}    0\n6924: +\n6925: +    ${result} =    Process.Run Process\n6926: +    ...    go test ./core/ -run TestC9sClusterCapture -count\\=1 -v\n6927: +    ...    shell=True\n6928: +    ...    cwd=${CURDIR}/../..\n6929: +    ...    env:CLAB_C9S_TEST_LAB=${lab-name}\n6930: +    ...    env:CLAB_C9S_TEST_CAPTURE_USER=system:serviceaccount:${lab-namespace}:capture-editor\n6931: +    ...    env:CLAB_C9S_TEST_FORBIDDEN_USER=system:serviceaccount:${lab-namespace}:nobody\n6932: +    Log    ${result.stdout}${\\n}${result.stderr}    console=${True}\n6933: +    Should Be Equal As Integers    ${result.rc}    0\n6934: +    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/capture_both_ends_of_a_link\n6935: +    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/restart_as_lab_editor\n6936: +    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/forbidden_identity\n6937: +    Should Not Contain    ${result.stdout}    SKIP\n6938: +    Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n6939: +\n6940:  Logs shows the device container log\n6941:      ${result} =    Run Clab Command    logs -t ${topo} -n client --tail 2 --timestamps\n6942:      Should Be Equal As Integers    ${result.rc}    0\n6943:      ${lines} =    Split To Lines    ${result.stdout}\n6944:      ${count} =    Get Length    ${lines}\n6945: @@ -411,10 +562,32 @@ Run Clab Command\n6946:      ...    shell=True\n6947:      Log    stdout:${\\n}${output.stdout}    console=${True}\n6948:      Log    stderr:${\\n}${output.stderr}    console=${True}\n6949:      RETURN    ${output}\n6950:  \n6951: +Clabwire Capture Processes\n6952: +    [Arguments]    ${node}\n6953: +    ${result} =    Process.Run Process\n6954: +    ...    ${CURDIR}/clabwire-captures.sh ${lab-namespace} ${node}\n6955: +    ...    shell=True\n6956: +    Log    ${result.stdout}${\\n}${result.stderr}\n6957: +    Should Be Equal As Integers    ${result.rc}    0\n6958: +    ${lines} =    Get Lines Containing String    ${result.stdout}    packet-capture\n6959: +    ${count} =    Get Line Count    ${lines}\n6960: +    RETURN    ${count}\n6961: +\n6962: +Capture Process Should Run In Clabwire\n6963: +    [Arguments]    ${node}\n6964: +    ${count} =    Clabwire Capture Processes    ${node}\n6965: +    Should Be True    ${count} > 0    no packet-capture process in the clabwire container of ${node}\n6966: +\n6967: +No Capture Process Should Run In Clabwire\n6968: +    [Arguments]    ${node}\n6969: +    ${count} =    Clabwire Capture Processes    ${node}\n6970: +    Should Be Equal As Integers    ${count}    0\n6971: +    ...    ${count} packet-capture processes still run in the clabwire container of ${node}\n6972: +\n6973:  Ping From Client Should Succeed\n6974:      ${output} =    Run Clab Command\n6975:      ...    exec -t ${topo} --label ${client-label} --cmd 'ping -c 1 -W 2 10.10.10.2'\n6976:      ${combined} =    Catenate    SEPARATOR=\\n    ${output.stdout}    ${output.stderr}\n6977:      Should Be Equal As Integers    ${output.rc}    0\n6978: diff --git a/tests/14-clabernetes/clabwire-captures.sh b/tests/14-clabernetes/clabwire-captures.sh\n6979: new file mode 100755\n6980: index 0000000..14833b3\n6981: --- /dev/null\n6982: +++ b/tests/14-clabernetes/clabwire-captures.sh\n6983: @@ -0,0 +1,35 @@\n6984: +#!/bin/sh\n6985: +# Prints the packet-capture processes running in the clabwire container of a c9s node's pod.\n6986: +# usage: clabwire-captures.sh <namespace> <node>\n6987: +#\n6988: +# A process of a Kubernetes exec is not visible through the API, so this looks at the worker\n6989: +# that runs the pod: a KinD node, which is a Docker container. It lists the processes whose\n6990: +# cgroup belongs to the clabwire container. Exits 2 when the worker is not a Docker container.\n6991: +set -eu\n6992: +\n6993: +namespace=$1\n6994: +node=$2\n6995: +\n6996: +pod=$(kubectl -n \"$namespace\" get pod -l \"c9s.run/topologyNode=$node\" \\\n6997: +  -o jsonpath='{.items[0].metadata.name}')\n6998: +worker=$(kubectl -n \"$namespace\" get pod \"$pod\" -o jsonpath='{.spec.nodeName}')\n6999: +# clabwire is a sidecar (an init container that keeps running)\n7000: +container=$(kubectl -n \"$namespace\" get pod \"$pod\" -o jsonpath=\\\n7001: +'{.status.initContainerStatuses[?(@.name==\"clabwire\")].containerID}{.status.containerStatuses[?(@.name==\"clabwire\")].containerID}')\n7002: +container=${container#*://}\n7003: +\n7004: +if ! docker inspect --type container \"$worker\" >/dev/null 2>&1; then\n7005: +  echo \"worker $worker of pod $namespace/$pod is not a Docker container (KinD)\" >&2\n7006: +  exit 2\n7007: +fi\n7008: +if [ -z \"$container\" ]; then\n7009: +  echo \"pod $namespace/$pod has no running clabwire container\" >&2\n7010: +  exit 1\n7011: +fi\n7012: +\n7013: +docker exec \"$worker\" sh -c \"\n7014: +  for proc in /proc/[0-9]*; do\n7015: +    if grep -qs '$container' \\\"\\$proc/cgroup\\\"; then\n7016: +      tr '\\\\0' ' ' < \\\"\\$proc/cmdline\\\" 2>/dev/null && echo\n7017: +    fi\n7018: +  done\" | grep 'packet-capture' || true\n\n(End of file - total 7018 lines)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+\t// when the runtime cannot name it.\n+\tPeerNode string `json:\"peer_node\"`\n+\t// PeerInterface is the peer's interface as the topology wrote it.\n+\tPeerInterface string `json:\"peer_interface\"`\n+}\n+\n+// CaptureTarget is one interface of one node to capture. Node takes the name the topology or\n+// the runtime uses, Interface the interface name or its alias.\n+type CaptureTarget struct {\n+\tNode      string\n+\tInterface string\n+}\n+\n+// CaptureRequest selects what Capture streams.\n+type CaptureRequest struct {\n+\t// Name is the lab name.\n+\tName      string\n+\tNamespace string\n+\tTargets   []CaptureTarget\n+\t// Duration ends the capture; zero captures until the context ends.",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+\t// when the runtime cannot name it.\n+\tPeerNode string `json:\"peer_node\"`\n+\t// PeerInterface is the peer's interface as the topology wrote it.\n+\tPeerInterface string `json:\"peer_interface\"`\n+}\n+\n+// CaptureTarget is one interface of one node to capture. Node takes the name the topology or\n+// the runtime uses, Interface the interface name or its alias.\n+type CaptureTarget struct {\n+\tNode      string\n+\tInterface string\n+}\n+\n+// CaptureRequest selects what Capture streams.\n+type CaptureRequest struct {\n+\t// Name is the lab name.\n+\tName      string\n+\tNamespace string\n+\tTargets   []CaptureTarget\n+\t// Duration ends the capture; zero captures until the context ends.\n+\tDuration time.Duration\n+\t// PacketLimit ends the capture after that many packets across all targets; zero means no\n+\t// limit.\n+\tPacketLimit int\n+\t// SnapLength is the number of bytes kept of each packet; zero uses the runtime default.\n+\tSnapLength int\n+\t// OnGap is called when the capture missed traffic, for example because a chained capture\n+\t// did not start in time. Without it, gaps are logged as warnings.\n+\tOnGap    func(CaptureGap)\n+\tIdentity Identity\n+}\n+\n+// CaptureGap is a time span a capture has no packets for, although it was running.\n+type CaptureGap struct {\n+\tNode       string\n+\tInterfaces []string\n+\t// From and To bound the gap on the node's clock; To is zero when it is unknown.\n+\tFrom   time.Time\n+\tTo     time.Time\n+\tReason string\n+}\n+\n+// PacketCapturer streams pcapng from lab link interfaces. Capture writes one section with one\n+// Interface Description Block per target, named <node>:<interface>, before any packet. It\n+// returns when Duration passed, PacketLimit packets were written, or the context ended (which\n+// is not an error); the output is a valid capture whenever it stops.\n+type PacketCapturer interface {\n+\tCaptureInterfaces(ctx context.Context, req NodeRequest) ([]CaptureInterface, error)\n+\tCapture(ctx context.Context, req CaptureRequest, w io.Writer) error\n+}\n+\n+// InterfaceInspector lists the link interfaces of a lab's nodes with their current state, in the\n+// shape of `inspect interfaces`.\n+type InterfaceInspector interface {\n+\tInspectInterfaces(\n+\t\tctx context.Context,\n+\t\treq NodeRequest,\n+\t) ([]*clabtypes.ContainerInterfaces, error)\n+}\n+\n // NodeStatsSampler reports the resource usage of a lab's nodes. It returns an error wrapping\n // ErrMetricsUnavailable when the cluster serves no resource metrics.\n type NodeStatsSampler interface {\n \tSampleStats(ctx context.Context, req InspectRequest) ([]NodeStats, error)\n }\ndiff --git a/mkdocs.yml b/mkdocs.yml\nindex 0285ad6..8dc17bd 100644\n--- a/mkdocs.yml\n+++ b/mkdocs.yml\n@@ -117,10 +117,11 @@ nav:\n       - inspect:\n           - cmd/inspect/index.md\n           - interfaces: cmd/inspect/interfaces.md\n       - events: cmd/events.md\n       - logs: cmd/logs.md\n+      - capture: cmd/capture.md\n       - save: cmd/save.md\n       - exec: cmd/exec.md\n       - generate: cmd/generate.md\n       - graph: cmd/graph.md\n       - validate: cmd/validate.md\ndiff --git a/tests/01-smoke/33-capture-summary.py b/tests/01-smoke/33-capture-summary.py\nnew file mode 100755\nindex 0000000..d49014c\n--- /dev/null\n+++ b/tests/01-smoke/33-capture-summary.py\n@@ -0,0 +1,69 @@\n+#!/usr/bin/env python3\n+# Copyright 2020 Nokia\n+# Licensed under the BSD 3-Clause License.\n+# SPDX-License-Identifier: BSD-3-Clause\n+\"\"\"Summarize a little-endian pcapng file as containerlab capture writes it, as JSON.\n+\n+Prints the number of sections, the interface names in order, the packet count per interface,\n+whether packets are in timestamp order, the number of 802.1Q tagged frames and the number of\n+ICMP echo requests and replies (untagged or tagged).\n+\"\"\"\n+\n+import json\n+import struct\n+import sys\n+\n+SHB, IDB, EPB = 0x0A0D0D0A, 0x00000001, 0x00000006\n+\n+\n+def main(path):\n+    with open(path, \"rb\") as f:\n+        data = f.read()\n+\n+    sections, names, counts, stamps = 0, [], {}, []\n+    vlan, echo = 0, 0\n+    offset = 0\n+    while offset < len(data):\n+        block_type, length = struct.unpack_from(\"<II\", data, offset)\n+        body = data[offset + 8 : offset + length - 4]\n+        if block_type == SHB:\n+            sections += 1\n+        elif block_type == IDB:\n+            options, name = body[8:], \"\"\n+            while len(options) >= 4:\n+                code, size = struct.unpack_from(\"<HH\", options)\n+                if code == 0:\n+                    break\n+                if code == 2:\n+                    name = options[4 : 4 + size].decode()\n+                options = options[4 + size + (4 - size % 4) % 4 :]\n+            names.append(name)\n+        elif block_type == EPB:\n+            iface, high, low, captured = struct.unpack_from(\"<IIII\", body)\n+            frame = body[20 : 20 + captured]\n+            counts[names[iface]] = counts.get(names[iface], 0) + 1\n+            stamps.append(high << 32 | low)\n+            ethertype, l3 = struct.unpack_from(\">H\", frame, 12)[0], 14\n+            if ethertype == 0x8100:\n+                vlan += 1\n+                ethertype, l3 = struct.unpack_from(\">H\", frame, 16)[0], 18\n+            if ethertype == 0x0800 and frame[l3 + 9] == 1 and frame[l3 + 20] in (0, 8):\n+                echo += 1\n+        offset += length\n+\n+    print(\n+        json.dumps(\n+            {\n+                \"sections\": sections,\n+                \"interfaces\": names,\n+                \"packets\": counts,\n+                \"ordered\": stamps == sorted(stamps),\n+                \"vlan_frames\": vlan,\n+                \"icmp_echo\": echo,\n+            }\n+        )\n+    )\n+\n+\n+if __name__ == \"__main__\":\n+    main(sys.argv[1])\ndiff --git a/tests/01-smoke/33-capture.clab.yml b/tests/01-smoke/33-capture.clab.yml\nnew file mode 100644\nindex 0000000..3f70288\n--- /dev/null\n+++ b/tests/01-smoke/33-capture.clab.yml\n@@ -0,0 +1,29 @@\n+# yaml-language-server: $schema=../../schemas/clab.schema.json\n+name: capture\n+\n+topology:\n+  nodes:\n+    l1:\n+      kind: linux\n+      image: alpine:3\n+      exec:\n+        - ip addr add 10.0.0.1/24 dev eth1\n+        - ip link add link eth1 name eth1.10 type vlan id 10\n+        - ip addr add 10.10.0.1/24 dev eth1.10\n+        - ip link set eth1.10 up\n+    l2:\n+      kind: linux\n+      image: alpine:3\n+      exec:\n+        - ip addr add 10.0.0.2/24 dev eth1\n+        - ip link add link eth1 name eth1.10 type vlan id 10\n+        - ip addr add 10.10.0.2/24 dev eth1.10\n+        - ip link set eth1.10 up\n+\n+  links:\n+    - endpoints: [\"l1:eth1\", \"l2:eth1\"]\n+    - type: host\n+      host-interface: capl2eth2\n+      endpoint:\n+        node: l2\n+        interface: eth2\ndiff --git a/tests/01-smoke/33-capture.robot b/tests/01-smoke/33-capture.robot\nnew file mode 100644\nindex 0000000..9502a8e\n--- /dev/null\n+++ b/tests/01-smoke/33-capture.robot\n@@ -0,0 +1,161 @@\n+*** Comments ***\n+This suite tests the capture command with the local container runtimes: containerlab reads the\n+lab link interfaces through packet sockets in the nodes' network namespaces.\n+\n+\n+*** Settings ***\n+Library             OperatingSystem\n+Library             Process\n+Library             String\n+Library             Collections\n+Resource            ../common.robot\n+\n+Suite Setup         Run    ${CLAB_BIN} --runtime ${runtime} destroy -t ${topo} --cleanup\n+Suite Teardown      Cleanup\n+\n+\n+*** Variables ***\n+${lab-name}         capture\n+${topo}             ${CURDIR}/33-capture.clab.yml\n+${runtime}          docker\n+${summary-script}   ${CURDIR}/33-capture-summary.py\n+${pcap}             /tmp/clab-capture.pcapng\n+${stdout-pcap}      /tmp/clab-capture-stdout.pcapng\n+${interrupt-pcap}   /tmp/clab-capture-interrupt.pcapng\n+${restart-pcap}     /tmp/clab-capture-restart.pcapng\n+\n+\n+*** Test Cases ***\n+Deploy ${lab-name} lab\n+    ${rc}    ${output} =    Run And Return Rc And Output\n+    ...    ${CLAB_BIN} --runtime ${runtime} deploy -t ${topo}\n+    Log    ${output}\n+    Should Be Equal As Integers    ${rc}    0\n+\n+List the capturable interfaces\n+    ${result} =    Run Capture    --name ${lab-name} --list -f json\n+    Should Be Equal As Integers    ${result.rc}    0\n+    ${interfaces} =    Evaluate    json.loads($result.stdout)    modules=json\n+    Length Should Be    ${interfaces}    3\n+    Should Be Equal    ${interfaces}[0][node]    l1\n+    Should Be Equal    ${interfaces}[0][interface]    eth1\n+    Should Be Equal    ${interfaces}[0][peer_node]    l2\n+    Should Be Equal    ${interfaces}[2][node]    l2\n+    Should Be Equal    ${interfaces}[2][interface]    eth2\n+    Should Be Equal    ${interfaces}[2][peer_node]    host\n+    Should Be Equal    ${interfaces}[2][peer_interface]    capl2eth2\n+\n+Capture both ends of a link with VLAN traffic\n+    Start Process\n+    ...    ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l1:eth1 --target l2:eth1 --duration 8s -w ${pcap}\n+    ...    shell=True\n+    ...    alias=both-ends\n+    Sleep    2s\n+    Ping From L1    10.0.0.2\n+    Ping From L1    10.10.0.2\n+    ${result} =    Wait For Process    both-ends    timeout=30s    on_timeout=kill\n+    Log    ${result.stderr}\n+    Should Be Equal As Integers    ${result.rc}    0\n+    ${summary} =    Capture Summary    ${pcap}\n+    Should Be Equal As Integers    ${summary}[sections]    1\n+    ${want} =    Create List    l1:eth1    l2:eth1\n+    Lists Should Be Equal    ${summary}[interfaces]    ${want}\n+    Should Be True    ${summary}[ordered]\n+    # 6 pings, each request and reply seen on both ends\n+    Should Be True    ${summary}[icmp_echo] >= 24\n+    # the VLAN 10 pings keep their 802.1Q tag\n+    Should Be True    ${summary}[vlan_frames] >= 12\n+\n+Capture to stdout stops at the packet limit\n+    Start Process\n+    ...    sleep 1 && sudo ${runtime} exec clab-${lab-name}-l1 ping -c 20 -i 0.2 10.0.0.2\n+    ...    shell=True\n+    ...    alias=background-ping\n+    ${result} =    Process.Run Process\n+    ...    ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l2:eth1 --packet-limit 6 -w - > ${stdout-pcap}\n+    ...    shell=True\n+    ...    timeout=30s\n+    ...    on_timeout=kill\n+    Log    ${result.stderr}\n+    Should Be Equal As Integers    ${result.rc}    0\n+    ${summary} =    Capture Summary    ${stdout-pcap}\n+    Should Be Equal As Integers    ${summary}[packets][l2:eth1]    6\n+    [Teardown]    Terminate Process    background-ping    kill=True\n+\n+An interrupt ends the capture with a valid file\n+    Start Process\n+    ...    exec ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l1:eth1 -w ${interrupt-pcap}\n+    ...    shell=True\n+    ...    alias=interrupted\n+    Sleep    2s\n+    Ping From L1    10.0.0.2\n+    Send Signal To Process    SIGINT    interrupted\n+    ${result} =    Wait For Process    interrupted    timeout=15s    on_timeout=kill\n+    Log    ${result.stderr}\n+    Should Be Equal As Integers    ${result.rc}    0\n+    ${summary} =    Capture Summary    ${interrupt-pcap}\n+    Should Be True    ${summary}[icmp_echo] >= 6\n+\n+The capture reattaches an interface after its node restarts\n+    Start Process\n+    ...    exec ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l2:eth1 -w ${restart-pcap}\n+    ...    shell=True\n+    ...    alias=restarted\n+    Sleep    2s\n+    Ping From L1    10.0.0.2\n+    ${rc}    ${output} =    Run And Return Rc And Output\n+    ...    ${CLAB_BIN} --runtime ${runtime} restart -t ${topo} --node l2\n+    Log    ${output}\n+    Should Be Equal As Integers    ${rc}    0\n+    ${rc}    ${output} =    Run And Return Rc And Output\n+    ...    sudo ${runtime} exec clab-${lab-name}-l2 ip addr replace 10.0.0.2/24 dev eth1\n+    Log    ${output}\n+    Wait Until Keyword Succeeds    20s    1s    Ping From L1    10.0.0.2\n+    # the capture reattaches within a fraction of a second after the link is back\n+    Sleep    1s\n+    Ping From L1    10.0.0.2\n+    Send Signal To Process    SIGINT    restarted\n+    ${result} =    Wait For Process    restarted    timeout=15s    on_timeout=kill\n+    Log    ${result.stderr}\n+    Should Be Equal As Integers    ${result.rc}    0\n+    Should Contain    ${result.stderr}    Capture has a gap\n+    ${summary} =    Capture Summary    ${restart-pcap}\n+    # 3 pings before and 3 after the reattach, request and reply each\n+    Should Be True    ${summary}[icmp_echo] >= 12\n+\n+The capture rejects the management interface\n+    ${result} =    Run Capture    --name ${lab-name} --target l1:eth0 -w /dev/null\n+    Should Not Be Equal As Integers    ${result.rc}    0\n+    Should Contain    ${result.stderr}    not a capturable link interface; capturable: eth1\n+\n+\n+*** Keywords ***\n+Run Capture\n+    [Arguments]    ${args}\n+    ${result} =    Process.Run Process\n+    ...    ${CLAB_BIN} --runtime ${runtime} capture ${args}\n+    ...    shell=True\n+    ...    timeout=60s\n+    ...    on_timeout=kill\n+    Log    stdout:${\\n}${result.stdout}\n+    Log    stderr:${\\n}${result.stderr}\n+    RETURN    ${result}\n+\n+Ping From L1\n+    [Arguments]    ${address}\n+    ${rc}    ${output} =    Run And Return Rc And Output\n+    ...    sudo ${runtime} exec clab-${lab-name}-l1 ping -c 3 -i 0.2 -W 1 ${address}\n+    Log    ${output}\n+    Should Be Equal As Integers    ${rc}    0\n+\n+Capture Summary\n+    [Arguments]    ${file}\n+    ${rc}    ${output} =    Run And Return Rc And Output    python3 ${summary-script} ${file}\n+    Log    ${output}\n+    Should Be Equal As Integers    ${rc}    0\n+    ${summary} =    Evaluate    json.loads($output)    modules=json\n+    RETURN    ${summary}\n+\n+Cleanup\n+    Run    ${CLAB_BIN} --runtime ${runtime} destroy -t ${topo} --cleanup\n+    Run    sudo rm -f ${pcap} ${stdout-pcap} ${interrupt-pcap} ${restart-pcap}\ndiff --git a/tests/14-clabernetes/01-linux-lifecycle.robot b/tests/14-clabernetes/01-linux-lifecycle.robot\nindex 1896ae4..f45a3ff 100644\n--- a/tests/14-clabernetes/01-linux-lifecycle.robot\n+++ b/tests/14-clabernetes/01-linux-lifecycle.robot\n@@ -23,10 +23,14 @@ ${events-err}           /tmp/clab-c9s-events.err\n ${iface-events-log}     /tmp/clab-c9s-iface-events.log\n ${iface-events-err}     /tmp/clab-c9s-iface-events.err\n ${offline-env}          env CLAB_KUBECONFIG\\=/nonexistent/kubeconfig KUBECONFIG\\=/nonexistent/kubeconfig\n ${recovery-timeout}     180s\n ${retry-interval}       5s\n+${capture-file}         /tmp/clab-c9s-capture.pcapng\n+${chain-file}           /tmp/clab-c9s-capture-chain.pcapng\n+${stop-file}            /tmp/clab-c9s-capture-stop.pcapng\n+${stop-err}             /tmp/clab-c9s-capture-stop.err\n \n \n *** Test Cases ***\n Deploy c9s linux lab\n     ${output} =    Run Clab Command    deploy -t ${topo}\n@@ -130,10 +134,157 @@ Graph renders from the topology file without a cluster\n \n Exec into client and verify dataplane\n     Wait Until Keyword Succeeds    60s    ${retry-interval}    Client Eth1 Should Be Visible\n     Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Succeed\n \n+Inspect interfaces lists the link interfaces with their state\n+    ${output} =    Run Clab Command    inspect interfaces -t ${topo} -f json\n+    Should Be Equal As Integers    ${output.rc}    0\n+    ${containers} =    Evaluate    json.loads($output.stdout)    modules=json\n+    Length Should Be    ${containers}    2\n+    FOR    ${container}    IN    @{containers}\n+        Should Match Regexp    ${container}[name]    ^${lab-name}-(client|server)$\n+        Length Should Be    ${container}[interfaces]    1\n+        ${iface} =    Set Variable    ${container}[interfaces][0]\n+        Should Be Equal    ${iface}[name]    eth1\n+        Should Be Equal    ${iface}[type]    veth\n+        Should Be Equal    ${iface}[state]    up\n+        Should Match Regexp    ${iface}[mac]    ^([0-9a-f]{2}:){5}[0-9a-f]{2}$\n+        Should Be True    ${iface}[ifindex] > 0 and ${iface}[mtu] > 0\n+    END\n+\n+    ${one} =    Run Clab Command    inspect interfaces --name ${lab-name} -n client -f json\n+    Should Be Equal As Integers    ${one.rc}    0\n+    ${only} =    Evaluate    [c[\"name\"] for c in json.loads($one.stdout)]    modules=json\n+    Should Be Equal    ${only}    ${{[\"${lab-name}-client\"]}}\n+\n+Capture lists the capturable interfaces with their peers\n+    ${output} =    Run Clab Command    capture -t ${topo} --list -f json\n+    Should Be Equal As Integers    ${output.rc}    0\n+    ${interfaces} =    Evaluate    json.loads($output.stdout)    modules=json\n+    ${want} =    Evaluate\n+    ...    [{\"node\": \"client\", \"interface\": \"eth1\", \"peer_node\": \"server\", \"peer_interface\": \"eth1\"}, {\"node\": \"server\", \"interface\": \"eth1\", \"peer_node\": \"client\", \"peer_interface\": \"eth1\"}]\n+    Should Be Equal    ${interfaces}    ${want}\n+\n+Capture both ends of a link into one pcapng stream\n+    Skip If    not shutil.which(\"tshark\")    tshark is not installed\n+    Remove File If Exists    ${capture-file}\n+    Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 10 -i 0.3 10.10.10.2'\n+    ...    shell=True    alias=c9s_ping\n+    ${output} =    Run Clab Command\n+    ...    capture -t ${topo} --target client:eth1 --target server:eth1 --duration 5s -w ${capture-file}\n+    Wait For Process    c9s_ping    timeout=30s\n+    Should Be Equal As Integers    ${output.rc}    0\n+\n+    ${idbs} =    Process.Run Process    capinfos -T -m -I ${capture-file}    shell=True\n+    Log    ${idbs.stdout}\n+    ${names} =    Process.Run Process\n+    ...    tshark -r ${capture-file} -T fields -e frame.interface_name -Y icmp | sort | uniq -c\n+    ...    shell=True\n+    Log    ${names.stdout}\n+    Should Be Equal As Integers    ${names.rc}    0\n+    ${counts} =    Evaluate\n+    ...    {l.split()[1]: int(l.split()[0]) for l in $names.stdout.splitlines() if l.strip()}\n+    Should Be Equal    ${{sorted($counts)}}    ${{[\"client:eth1\", \"server:eth1\"]}}\n+    Should Be True    ${counts}[client:eth1] >= 10 and ${counts}[server:eth1] >= 10\n+\n+    ${info} =    Process.Run Process    capinfos ${capture-file}    shell=True\n+    Log    ${info.stdout}\n+    Should Contain    ${info.stdout}    Number of interfaces in file: 2\n+    Should Contain    ${info.stdout}    Capture application: containerlab\n+    Should Contain    ${info.stdout}    nanoseconds\n+\n+    # the packets of both nodes are merged in timestamp order\n+    ${times} =    Process.Run Process\n+    ...    tshark -r ${capture-file} -T fields -e frame.time_epoch\n+    ...    shell=True\n+    Should Be Equal As Integers    ${times.rc}    0\n+    ${epochs} =    Evaluate    [decimal.Decimal(x) for x in $times.stdout.split()]    modules=decimal\n+    ${count} =    Get Length    ${epochs}\n+    Should Be True    ${count} >= 20    only ${count} packets\n+    ${inversions} =    Evaluate\n+    ...    [(i, str($epochs[i - 1]), str($epochs[i])) for i in range(1, len($epochs)) if $epochs[i] < $epochs[i - 1]]\n+    Should Be Empty    ${inversions}    frame.time_epoch decreases\n+    [Teardown]    Remove File If Exists    ${capture-file}\n+\n+Stopping a capture leaves no capture process in clabwire\n+    Skip If    not shutil.which(\"docker\")    docker is needed to list the processes of a KinD worker\n+    Skip If    not shutil.which(\"capinfos\")    capinfos is not installed\n+    Remove File If Exists    ${stop-file}\n+    Start Process    ${CLAB_BIN}    --runtime    ${runtime}    capture    -t    ${topo}\n+    ...    --target    client:eth1    --target    server:eth1    -w    ${stop-file}\n+    ...    alias=c9s_capture    stderr=${stop-err}\n+    Wait Until Keyword Succeeds    60s    1s    Capture Process Should Run In Clabwire    client\n+    Wait Until Keyword Succeeds    10s    1s    Capture Process Should Run In Clabwire    server\n+\n+    Send Signal To Process    SIGINT    c9s_capture\n+    ${result} =    Wait For Process    c9s_capture    timeout=30s    on_timeout=kill\n+    Log    ${result.stderr}\n+    Should Be Equal As Integers    ${result.rc}    0\n+    # Kubernetes does not stop an exec'd process when its stream closes; clabwire ends the\n+    # capture when containerlab closes its stdin\n+    Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    client\n+    Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    server\n+\n+    ${info} =    Process.Run Process    capinfos ${stop-file}    shell=True\n+    Should Be Equal As Integers    ${info.rc}    0\n+    Should Contain    ${info.stdout}    Number of interfaces in file: 2\n+    [Teardown]    Run Keywords    Remove File If Exists    ${stop-file}\n+    ...    AND    Remove File If Exists    ${stop-err}\n+\n+Capture chains segments without duplicates or gaps\n+    Skip If    not shutil.which(\"tshark\")    tshark is not installed\n+    Remove File If Exists    ${chain-file}\n+    Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 130 -i 0.2 10.10.10.2'\n+    ...    shell=True    alias=c9s_ping\n+    Sleep    1s\n+    # a 6 s segment length forces four switches in 20 s\n+    ${output} =    Process.Run Process\n+    ...    ${CLAB_BIN} --runtime ${runtime} --log-level debug capture -t ${topo} --target client:eth1 --duration 20s -w ${chain-file}\n+    ...    shell=True\n+    ...    env:CLAB_C9S_CAPTURE_SEGMENT=6s\n+    Log    ${output.stderr}\n+    Wait For Process    c9s_ping    timeout=60s\n+    Should Be Equal As Integers    ${output.rc}    0\n+    Should Contain    ${output.stderr}    segment=4\n+    Should Not Contain    ${output.stderr}    gap\n+\n+    ${seqs} =    Process.Run Process\n+    ...    tshark -r ${chain-file} -Y 'icmp.type \\=\\= 8' -T fields -e icmp.seq\n+    ...    shell=True\n+    Should Be Equal As Integers    ${seqs.rc}    0\n+    ${numbers} =    Evaluate    [int(x) for x in $seqs.stdout.split()]\n+    ${count} =    Get Length    ${numbers}\n+    Should Be True    ${count} >= 90    only ${count} echo requests\n+    ${unique} =    Evaluate    len(set($numbers))\n+    Should Be Equal As Integers    ${unique}    ${count}    duplicate echo requests\n+    ${span} =    Evaluate    max($numbers) - min($numbers) + 1\n+    Should Be Equal As Integers    ${span}    ${count}    missing echo requests\n+    [Teardown]    Remove File If Exists    ${chain-file}\n+\n+Capture works for a lab editor and is forbidden without a binding\n+    ${rbac} =    Process.Run Process\n+    ...    kubectl -n ${lab-namespace} create serviceaccount capture-editor && kubectl -n ${lab-namespace} create rolebinding capture-editor --clusterrole\\=clabernetes-lab-editor --serviceaccount\\=${lab-namespace}:capture-editor\n+    ...    shell=True\n+    Log    ${rbac.stdout}${\\n}${rbac.stderr}\n+    Should Be Equal As Integers    ${rbac.rc}    0\n+\n+    ${result} =    Process.Run Process\n+    ...    go test ./core/ -run TestC9sClusterCapture -count\\=1 -v\n+    ...    shell=True\n+    ...    cwd=${CURDIR}/../..\n+    ...    env:CLAB_C9S_TEST_LAB=${lab-name}\n+    ...    env:CLAB_C9S_TEST_CAPTURE_USER=system:serviceaccount:${lab-namespace}:capture-editor\n+    ...    env:CLAB_C9S_TEST_FORBIDDEN_USER=system:serviceaccount:${lab-namespace}:nobody\n+    Log    ${result.stdout}${\\n}${result.stderr}    console=${True}\n+    Should Be Equal As Integers    ${result.rc}    0\n+    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/capture_both_ends_of_a_link\n+    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/restart_as_lab_editor\n+    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/forbidden_identity\n+    Should Not Contain    ${result.stdout}    SKIP\n+    Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n+\n Logs shows the device container log\n     ${result} =    Run Clab Command    logs -t ${topo} -n client --tail 2 --timestamps\n     Should Be Equal As Integers    ${result.rc}    0\n     ${lines} =    Split To Lines    ${result.stdout}\n     ${count} =    Get Length    ${lines}\n@@ -411,10 +562,32 @@ Run Clab Command\n     ...    shell=True\n     Log    stdout:${\\n}${output.stdout}    console=${True}\n     Log    stderr:${\\n}${output.stderr}    console=${True}\n     RETURN    ${output}\n \n+Clabwire Capture Processes\n+    [Arguments]    ${node}\n+    ${result} =    Process.Run Process\n+    ...    ${CURDIR}/clabwire-captures.sh ${lab-namespace} ${node}\n+    ...    shell=True\n+    Log    ${result.stdout}${\\n}${result.stderr}\n+    Should Be Equal As Integers    ${result.rc}    0\n+    ${lines} =    Get Lines Containing String    ${result.stdout}    packet-capture\n+    ${count} =    Get Line Count    ${lines}\n+    RETURN    ${count}\n+\n+Capture Process Should Run In Clabwire\n+    [Arguments]    ${node}\n+    ${count} =    Clabwire Capture Processes    ${node}\n+    Should Be True    ${count} > 0    no packet-capture process in the clabwire container of ${node}\n+\n+No Capture Process Should Run In Clabwire\n+    [Arguments]    ${node}\n+    ${count} =    Clabwire Capture Processes    ${node}\n+    Should Be Equal As Integers    ${count}    0\n+    ...    ${count} packet-capture processes still run in the clabwire container of ${node}\n+\n Ping From Client Should Succeed\n     ${output} =    Run Clab Command\n     ...    exec -t ${topo} --label ${client-label} --cmd 'ping -c 1 -W 2 10.10.10.2'\n     ${combined} =    Catenate    SEPARATOR=\\n    ${output.stdout}    ${output.stderr}\n     Should Be Equal As Integers    ${output.rc}    0\ndiff --git a/tests/14-clabernetes/clabwire-captures.sh b/tests/14-clabernetes/clabwire-captures.sh\nnew file mode 100755\nindex 0000000..14833b3\n--- /dev/null\n+++ b/tests/14-clabernetes/clabwire-captures.sh\n@@ -0,0 +1,35 @@\n+#!/bin/sh\n+# Prints the packet-capture processes running in the clabwire container of a c9s node's pod.\n+# usage: clabwire-captures.sh <namespace> <node>\n+#\n+# A process of a Kubernetes exec is not visible through the API, so this looks at the worker\n+# that runs the pod: a KinD node, which is a Docker container. It lists the processes whose\n+# cgroup belongs to the clabwire container. Exits 2 when the worker is not a Docker container.\n+set -eu\n+\n+namespace=$1\n+node=$2\n+\n+pod=$(kubectl -n \"$namespace\" get pod -l \"c9s.run/topologyNode=$node\" \\\n+  -o jsonpath='{.items[0].metadata.name}')\n+worker=$(kubectl -n \"$namespace\" get pod \"$pod\" -o jsonpath='{.spec.nodeName}')\n+# clabwire is a sidecar (an init container that keeps running)\n+container=$(kubectl -n \"$namespace\" get pod \"$pod\" -o jsonpath=\\\n+'{.status.initContainerStatuses[?(@.name==\"clabwire\")].containerID}{.status.containerStatuses[?(@.name==\"clabwire\")].containerID}')\n+container=${container#*://}\n+\n+if ! docker inspect --type container \"$worker\" >/dev/null 2>&1; then\n+  echo \"worker $worker of pod $namespace/$pod is not a Docker container (KinD)\" >&2\n+  exit 2\n+fi\n+if [ -z \"$container\" ]; then\n+  echo \"pod $namespace/$pod has no running clabwire container\" >&2\n+  exit 1\n+fi\n+\n+docker exec \"$worker\" sh -c \"\n+  for proc in /proc/[0-9]*; do\n+    if grep -qs '$container' \\\"\\$proc/cgroup\\\"; then\n+      tr '\\\\0' ' ' < \\\"\\$proc/cmdline\\\" 2>/dev/null && echo\n+    fi\n+  done\" | grep 'packet-capture' || true",
        "lineStart": 6410,
        "lineEnd": 7018,
        "totalLines": 7018,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523239544,
      "end": 1793523239576
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19650ca9a001p605m2O3Up56sl",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650be85001Eha5NBjsp4KX8c",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 89428,
    "input": 22270,
    "output": 21,
    "reasoning": 1,
    "cache": {
      "read": 67136,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19650be85001Eha5NBjsp4KX8c",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523236485,
    "completed": 1793523239581
  },
  "parentID": "msg_196508bbe001tLsHPkKW57hw60",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 89428,
    "input": 22270,
    "output": 21,
    "reasoning": 1,
    "cache": {
      "read": 67136,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
User · 9
compaction
{
  "type": "compaction",
  "id": "prt_19650ca9f001ldxkWnALzGGr2C",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650ca9e001IiM7d0o0iQV8Vc",
  "auto": true,
  "overflow": false,
  "tail_start_id": "msg_19650be85001Eha5NBjsp4KX8c"
}
Message metadata
{
  "role": "user",
  "id": "msg_19650ca9e001IiM7d0o0iQV8Vc",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523239582
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 10
step-start
{
  "type": "step-start",
  "id": "prt_19650ced0001VEwWcmIG7H7ogG",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650caae001bNbVQhE16Qm2EW"
}
Reasoning
Create the summary. Review of PR snapshot at /source, containerlab repo, capture feature PR. 37 changed paths. Read standards.json, rules, diff.txt partially (offsets 1, 1702, 3478, 4780). Key files seen: .github/workflows/clabernetes-tests.yml, smoke-tests.yml, capture/local.go (new), capture reorder code, core/test_data/capture.clab.yml, docs/cmd/capture.md. Need to continue tracking all 37 changed paths.

Head: 657b1700664a99c5e12c60b4cfd179eb11889bae, base: 00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4.
## Objective
- Review the read-only PR snapshot at `/source` (containerlab repo, srl-labs/containerlab): read `standards.json` and its referenced rules, then `diff.txt` and relevant head/base files; track all 37 changed paths and complete checks per path (including callers, tests, docs, schema) before producing a trusted result schema.

## Important Details
- Head commit: `657b1700664a99c5e12c60b4cfd179eb11889bae`; comparison base and target base: `00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4`.
- GitHub permalink roots: head=`https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/`; base=`https://github.com/srl-labs/containerlab/blob/00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4/`.
- Snapshot incomplete: false; full inventory/omission details are in `/source/manifest.json` (consult when needed).
- Source-only review is acceptable without executing tests; limitation must be disclosed in the final result.
- Use read offsets for truncated outputs; group independent tool calls; use glob/grep for surrounding code.
- `standards.json` references two always-apply rule files: `.cursor/rules/karpathy-guidelines.mdc` (surgical changes, simplicity first, no speculative abstractions) and `.cursor/rules/ponytail.mdc` (YAGNI, reuse existing helpers, shortest working diff).
- Direct `read` of `/source` directory itself is denied by permission rules; read individual files under `/source/*` instead.
- The diff introduces a new `capture` feature: `capture` package (e.g., `capture/local.go`, ~430 lines; a `Reorder` buffer with min-heap `reorderQueue`, holds/releases, `reorderStats`, late/forced packet counters), a c9s (clabernetes) runtime with chained capture segments and `CaptureGap` reporting (`clablabruntime.CaptureGap`), plus workflow/test/doc changes.

## Work State
### Completed
- Read `/source/standards.json` (lists the two rule files).
- Read `/source/standards/karpathy-guidelines.mdc` and `/source/standards/ponytail.mdc` (behavioral standards for the review).
- Read `/source/diff.txt` from start (lines 1–~1700) covering: `.github/workflows/clabernetes-tests.yml` (adds tshark install step: `sudo DEBIAN_FRONTEND=noninteractive apt-get install -y tshark`), `.github/workflows/smoke-tests.yml` (adds `"33*.robot"` to robot test glob list), and start of new file `capture/local.go`.
- Read diff.txt at offsets 1702 (Reorder buffer internals: `Reorder` struct, `reorderQueue` heap, `reorderedPacket`, `reorderStats`) and 3478 (pcapng Enhanced Packet Block parsing; end of some file before `core/test_data/capture.clab.yml`) and 4780 (`captureChain.switchSegments` logic, `CaptureGap` reporting, held-packet emission).
- Identified changed files so far from diff: `.github/workflows/clabernetes-tests.yml`, `.github/workflows/smoke-tests.yml`, `capture/local.go` (new), `core/test_data/capture.clab.yml` (new — 2x nokia_srlinux + alpine:3 client, 4 links incl. host and mgmt-net), `docs/cmd/capture.md` (new, ~134 lines documenting pcapng capture command).

### Active
- Reading through `diff.txt` progressively via offsets; diff.txt is large (~4800+ lines) and more changed files remain unreviewed.
- Must enumerate and track all 37 changed paths from the diff (only ~5 confirmed so far); remaining paths need to be discovered by continuing to read diff.txt and cross-checking with `manifest.json`.
- After diff review: examine head/base files for callers, tests, docs, and schema impact per changed path.

### Blocked
- Diff output truncation requires sequential offset reads; large diff not yet fully traversed.
- No changes to code are possible (read-only snapshot review); tests cannot be executed — must be disclosed in final result.

## Next Move
1. Continue reading `/source/diff.txt` at successive offsets (e.g., beyond ~5000) to enumerate all remaining changed paths out of the 37, noting new/modified files and key symbols.
2. Consult `/source/manifest.json` for the full changed-path inventory to ensure all 37 paths are tracked; then review head/base files, callers, tests, docs, and schema for each path and assemble the trusted result schema with the test-execution limitation disclosed.

## Relevant Files
- `/source/standards.json` — maps rule files to apply (karpathy-guidelines, ponytail).
- `/source/standards/karpathy-guidelines.mdc` — review standard: surgical changes, simplicity.
- `/source/standards/ponytail.mdc` — review standard: YAGNI, reuse, shortest diff.
- `/source/diff.txt` — full PR diff; large, needs offset-based sequential reading.
- `/source/manifest.json` — full inventory and omission details for the snapshot.
- `/source/capture/local.go` — new capture implementation file (review target).
- `/source/core/test_data/capture.clab.yml` — new test topology for capture feature.
- `/source/docs/cmd/capture.md` — new docs for `capture` command.
- `/source/.github/workflows/clabernetes-tests.yml` — adds tshark install step.
- `/source/.github/workflows/smoke-tests.yml` — adds `33*.robot` test glob.
step-finish
{
  "type": "step-finish",
  "id": "prt_19650e891001E5mKD59VqqyIit",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650caae001bNbVQhE16Qm2EW",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 6598,
    "input": 5139,
    "output": 1287,
    "reasoning": 172,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19650caae001bNbVQhE16Qm2EW",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523239598,
    "completed": 1793523247254
  },
  "parentID": "msg_19650ca9e001IiM7d0o0iQV8Vc",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "compaction",
  "agent": "compaction",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "summary": true,
  "cost": 0,
  "tokens": {
    "total": 6598,
    "input": 5139,
    "output": 1287,
    "reasoning": 172,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "stop"
}
User · 11
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_19650e899001051OTPpm7MOch6",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523247257
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 12
step-start
{
  "type": "step-start",
  "id": "prt_19650efd7001XnUvq9cd0HnVqy",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650e8a200111L08HO3uUnqfB"
}
Reasoning
I need to continue reviewing. The diff is 7018 lines; I've read the end (6410-7018) and offsets 1, 1702, 3478, 4780. I need to enumerate the full changed-path inventory from manifest.json and fill in diff gaps I haven't seen: between 1-1702 I saw workflows and capture/local.go start; 1702-3478 reorder buffer internals; 3478-4780 pcapng parsing + core/test_data/capture.clab.yml + docs/cmd/capture.md; 4780-6410 captureChain switchSegments + runtime interfaces. There's a gap I haven't read: roughly lines ~500-1702 (I read 1 and 1702, so chunk 2-1701 partially seen at first read? The summary says read offsets 1, 1702, 3478, 4780 — each read likely covered 2000 lines, so 1-1702 covered, 1702-3702 covered, 3478-5478 covered, 4780-7018 covered now). Actually 4780+2000 = 6780, so 6780-7018 covered by the latest read. So full diff has been traversed via overlapping reads.

Now I should get the manifest.json to enumerate all 37 changed paths, then examine key head files for issues. Let me read manifest.json and list the diff's file headers.
grep · completed

Input

{
  "pattern": "^diff --git",
  "path": "/source/diff.txt"
}

Output

Found 37 matches
/source/diff.txt:
  Line 1: diff --git a/.github/workflows/clabernetes-tests.yml b/.github/workflows/clabernetes-tests.yml

  Line 21: diff --git a/.github/workflows/smoke-tests.yml b/.github/workflows/smoke-tests.yml

  Line 37: diff --git a/capture/local.go b/capture/local.go

  Line 473: diff --git a/capture/local_test.go b/capture/local_test.go

  Line 955: diff --git a/capture/output.go b/capture/output.go

  Line 1164: diff --git a/capture/pcapng.go b/capture/pcapng.go

  Line 1503: diff --git a/capture/pcapng_test.go b/capture/pcapng_test.go

  Line 1676: diff --git a/capture/reorder.go b/capture/reorder.go

  Line 1953: diff --git a/capture/reorder_test.go b/capture/reorder_test.go

  Line 2161: diff --git a/cmd/capture.go b/cmd/capture.go

  Line 2429: diff --git a/cmd/capture_test.go b/cmd/capture_test.go

  Line 2544: diff --git a/cmd/context.go b/cmd/context.go

  Line 2569: diff --git a/cmd/inspect.go b/cmd/inspect.go

  Line 2588: diff --git a/cmd/inspect_interfaces.go b/cmd/inspect_interfaces.go

  Line 2618: diff --git a/cmd/options.go b/cmd/options.go

  Line 2665: diff --git a/cmd/root.go b/cmd/root.go

  Line 2709: diff --git a/cmd/root_test.go b/cmd/root_test.go

  Line 2744: diff --git a/core/capture.go b/core/capture.go

  Line 2843: diff --git a/core/capture_local.go b/core/capture_local.go

  Line 3104: diff --git a/core/capture_test.go b/core/capture_test.go

  Line 3320: diff --git a/core/labruntime_cluster_test.go b/core/labruntime_cluster_test.go

  Line 3490: diff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml

  Line 3511: diff --git a/docs/cmd/capture.md b/docs/cmd/capture.md

  Line 3651: diff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md

  Line 3668: diff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md

  Line 3879: diff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md

  Line 3900: diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go

  Line 5108: diff --git a/labruntime/clabernetes/capture_interfaces.go b/labruntime/clabernetes/capture_interfaces.go

  Line 5301: diff --git a/labruntime/clabernetes/capture_test.go b/labruntime/clabernetes/capture_test.go

  Line 6357: diff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go

  Line 6390: diff --git a/labruntime/runtime.go b/labruntime/runtime.go

  Line 6475: diff --git a/mkdocs.yml b/mkdocs.yml

  Line 6491: diff --git a/tests/01-smoke/33-capture-summary.py b/tests/01-smoke/33-capture-summary.py

  Line 6566: diff --git a/tests/01-smoke/33-capture.clab.yml b/tests/01-smoke/33-capture.clab.yml

  Line 6601: diff --git a/tests/01-smoke/33-capture.robot b/tests/01-smoke/33-capture.robot

  Line 6768: diff --git a/tests/14-clabernetes/01-linux-lifecycle.robot b/tests/14-clabernetes/01-linux-lifecycle.robot

  Line 6978: diff --git a/tests/14-clabernetes/clabwire-captures.sh b/tests/14-clabernetes/clabwire-captures.sh
Tool metadata
{
  "type": "tool",
  "id": "prt_19650f7db0010WKcKdyxri7Aw0",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650e8a200111L08HO3uUnqfB",
  "callID": "call_f5263ced5973453da978c248",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "pattern": "^diff --git",
      "path": "/source/diff.txt"
    },
    "output": "Found 37 matches\n/source/diff.txt:\n  Line 1: diff --git a/.github/workflows/clabernetes-tests.yml b/.github/workflows/clabernetes-tests.yml\n\n  Line 21: diff --git a/.github/workflows/smoke-tests.yml b/.github/workflows/smoke-tests.yml\n\n  Line 37: diff --git a/capture/local.go b/capture/local.go\n\n  Line 473: diff --git a/capture/local_test.go b/capture/local_test.go\n\n  Line 955: diff --git a/capture/output.go b/capture/output.go\n\n  Line 1164: diff --git a/capture/pcapng.go b/capture/pcapng.go\n\n  Line 1503: diff --git a/capture/pcapng_test.go b/capture/pcapng_test.go\n\n  Line 1676: diff --git a/capture/reorder.go b/capture/reorder.go\n\n  Line 1953: diff --git a/capture/reorder_test.go b/capture/reorder_test.go\n\n  Line 2161: diff --git a/cmd/capture.go b/cmd/capture.go\n\n  Line 2429: diff --git a/cmd/capture_test.go b/cmd/capture_test.go\n\n  Line 2544: diff --git a/cmd/context.go b/cmd/context.go\n\n  Line 2569: diff --git a/cmd/inspect.go b/cmd/inspect.go\n\n  Line 2588: diff --git a/cmd/inspect_interfaces.go b/cmd/inspect_interfaces.go\n\n  Line 2618: diff --git a/cmd/options.go b/cmd/options.go\n\n  Line 2665: diff --git a/cmd/root.go b/cmd/root.go\n\n  Line 2709: diff --git a/cmd/root_test.go b/cmd/root_test.go\n\n  Line 2744: diff --git a/core/capture.go b/core/capture.go\n\n  Line 2843: diff --git a/core/capture_local.go b/core/capture_local.go\n\n  Line 3104: diff --git a/core/capture_test.go b/core/capture_test.go\n\n  Line 3320: diff --git a/core/labruntime_cluster_test.go b/core/labruntime_cluster_test.go\n\n  Line 3490: diff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml\n\n  Line 3511: diff --git a/docs/cmd/capture.md b/docs/cmd/capture.md\n\n  Line 3651: diff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md\n\n  Line 3668: diff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md\n\n  Line 3879: diff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md\n\n  Line 3900: diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go\n\n  Line 5108: diff --git a/labruntime/clabernetes/capture_interfaces.go b/labruntime/clabernetes/capture_interfaces.go\n\n  Line 5301: diff --git a/labruntime/clabernetes/capture_test.go b/labruntime/clabernetes/capture_test.go\n\n  Line 6357: diff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go\n\n  Line 6390: diff --git a/labruntime/runtime.go b/labruntime/runtime.go\n\n  Line 6475: diff --git a/mkdocs.yml b/mkdocs.yml\n\n  Line 6491: diff --git a/tests/01-smoke/33-capture-summary.py b/tests/01-smoke/33-capture-summary.py\n\n  Line 6566: diff --git a/tests/01-smoke/33-capture.clab.yml b/tests/01-smoke/33-capture.clab.yml\n\n  Line 6601: diff --git a/tests/01-smoke/33-capture.robot b/tests/01-smoke/33-capture.robot\n\n  Line 6768: diff --git a/tests/14-clabernetes/01-linux-lifecycle.robot b/tests/14-clabernetes/01-linux-lifecycle.robot\n\n  Line 6978: diff --git a/tests/14-clabernetes/clabwire-captures.sh b/tests/14-clabernetes/clabwire-captures.sh\n",
    "title": "^diff --git",
    "metadata": {
      "matches": 37,
      "truncated": false
    },
    "time": {
      "start": 1793523251179,
      "end": 1793523251253
    }
  }
}
read · completed

Input

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

Output

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

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

Now the task is detailed review. Rather than re-reading the entire diff, I should now examine the head files for the most substantial new code: capture/local.go, capture/reorder.go, capture/pcapng.go, capture/output.go, cmd/capture.go, core/capture.go, core/capture_local.go, labruntime/clabernetes/capture.go (1202 lines), capture_interfaces.go, clabernetes.go, runtime.go changes.

Given context budget, I should focus on the most likely-defect areas. Let me read the key files. Start with capture/local.go and capture/reorder.go, capture/pcapng.go, capture/output.go.
The full diff has now been traversed (offsets 1, 1702, 3478, 4780, 6410 with overlaps covering all 7018 lines), and `manifest.json` confirms the complete 37-path inventory. Next I will examine the key head files in detail, starting with the new `capture` package.
read · error

Input

{
  "filePath": "/source/capture/local.go"
}

Output

File not found: /source/capture/local.go
Tool metadata
{
  "type": "tool",
  "id": "prt_196510bba001YTzQX9B21vCPBI",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650f8770016P9cVjb21SKWei",
  "callID": "call_e6ef2cf6b57a4fe88604c876",
  "tool": "read",
  "state": {
    "status": "error",
    "input": {
      "filePath": "/source/capture/local.go"
    },
    "error": "File not found: /source/capture/local.go",
    "time": {
      "start": 1793523256254,
      "end": 1793523256258
    }
  }
}
read · error

Input

{
  "filePath": "/source/capture/reorder.go"
}

Output

File not found: /source/capture/reorder.go
Tool metadata
{
  "type": "tool",
  "id": "prt_196510bdb0010b6whPqXRI3uAH",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650f8770016P9cVjb21SKWei",
  "callID": "call_8e2e517ec22547b395a76b8b",
  "tool": "read",
  "state": {
    "status": "error",
    "input": {
      "filePath": "/source/capture/reorder.go"
    },
    "error": "File not found: /source/capture/reorder.go",
    "time": {
      "start": 1793523256286,
      "end": 1793523256289
    }
  }
}
read · error

Input

{
  "filePath": "/source/capture/pcapng.go"
}

Output

File not found: /source/capture/pcapng.go
Tool metadata
{
  "type": "tool",
  "id": "prt_196510bfe001pwSk66zQTkJTaO",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650f8770016P9cVjb21SKWei",
  "callID": "call_6fee1c7b784a4209a62e3494",
  "tool": "read",
  "state": {
    "status": "error",
    "input": {
      "filePath": "/source/capture/pcapng.go"
    },
    "error": "File not found: /source/capture/pcapng.go",
    "time": {
      "start": 1793523256320,
      "end": 1793523256323
    }
  }
}
read · error

Input

{
  "filePath": "/source/capture/output.go"
}

Output

File not found: /source/capture/output.go
Tool metadata
{
  "type": "tool",
  "id": "prt_196510c22001Gsi4z1b1fqaXmH",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650f8770016P9cVjb21SKWei",
  "callID": "call_eb45659ce11d45999de12176",
  "tool": "read",
  "state": {
    "status": "error",
    "input": {
      "filePath": "/source/capture/output.go"
    },
    "error": "File not found: /source/capture/output.go",
    "time": {
      "start": 1793523256358,
      "end": 1793523256368
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196510c32001ey2z70nCDSKnyU",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19650f8770016P9cVjb21SKWei",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 36031,
    "input": 20426,
    "output": 132,
    "reasoning": 369,
    "cache": {
      "read": 15104,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19650f8770016P9cVjb21SKWei",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523251319,
    "completed": 1793523256373
  },
  "parentID": "msg_19650e899001051OTPpm7MOch6",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 36031,
    "input": 20426,
    "output": 132,
    "reasoning": 369,
    "cache": {
      "read": 15104,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 14
step-start
{
  "type": "step-start",
  "id": "prt_1965113510018g53CW8w6hHHuQ",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196510c3a001TWXRc4E0bury6D"
}
Reasoning
The files may be organized differently. Let me list the snapshot directory contents.
glob · completed

Input

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

Output

/source/head/main.go
/source/head/errors/errors.go
/source/head/types/bind.go
/source/head/types/types.go
/source/head/types/topo_diff.go
/source/head/types/hostentry.go
/source/head/types/host_requirements.go
/source/head/types/hostentry_test.go
/source/head/types/license_policy_value.go
/source/head/types/bind_test.go
/source/head/types/volume.go
/source/head/types/volume_test.go
/source/head/types/ipversion.go
/source/head/types/mgmt.go
/source/head/types/mgmt_test.go
/source/head/types/stages_test.go
/source/head/types/node_definition_test.go
/source/head/types/ssh_config.go
/source/head/types/ipam.go
/source/head/types/tailscale_ports.go
/source/head/types/stages.go
/source/head/types/topology_test.go
/source/head/types/settings.go
/source/head/types/node_definition.go
/source/head/types/topo_diff_test.go
/source/head/types/tailscale_ports_test.go
/source/head/types/mgmt_networks_test.go
/source/head/types/topology.go
/source/head/types/topo_paths.go
/source/head/exec/exec_test.go
/source/head/exec/exec.go
/source/head/virt/virt.go
/source/head/virt/memory.go
/source/head/constants/env.go
/source/head/constants/containerlab.go
/source/head/constants/labels.go
/source/head/constants/os.go
/source/head/capture/output.go
/source/head/capture/local_test.go
/source/head/cert/local_dir_cert_storage.go
/source/head/capture/reorder.go
/source/head/cert/cert.go
/source/head/capture/reorder_test.go
/source/head/cert/csr_input.go
/source/head/capture/pcapng.go
/source/head/capture/pcapng_test.go
/source/head/capture/local.go
/source/head/cert/certificate.go
/source/head/cert/ca.go
/source/head/netconf/netconf.go
/source/head/nodes/bridge/bridge.go
/source/head/nodes/xrd/xrd.go
/source/head/nodes/ciena_saos/ciena_saos_test.go
/source/head/nodes/ciena_saos/ciena_saos.go
/source/head/nodes/rare/rare.go
/source/head/nodes/vyosnetworks_vyos/vyos.go
/source/head/nodes/vyosnetworks_vyos/helpers.go
/source/head/nodes/ipinfusion_ocnos/ipinfusion_ocnos.go
/source/head/nodes/vr_csr/vr-csr.go
/source/head/nodes/vr_csr/vr-csr_test.go
/source/head/nodes/cisco_vios/cisco-vios.go
/source/head/nodes/cisco_vios/cisco-vios_test.go
/source/head/nodes/kind_specific_config.go
/source/head/nodes/vr_pan/vr-pan.go
/source/head/nodes/vr_pan/vr-pan_test.go
/source/head/nodes/default_node_test.go
/source/head/nodes/sonic/sonic.go
/source/head/nodes/sonic/sonic_test.go
/source/head/nodes/cjunosevolved/cjunosevolved.go
/source/head/nodes/vr_sros/vr-sros_test.go
/source/head/nodes/vr_sros/vr-sros.go
/source/head/nodes/vr_sros/interface_map.go
/source/head/nodes/vr_ros/vr-ros_test.go
/source/head/nodes/vr_ros/vr-ros.go
/source/head/nodes/vr_sros/interface_map_test.go
/source/head/nodes/vr_sros/variant_test.go
/source/head/nodes/vr_sros/sshKey.go
/source/head/nodes/vr_sros/sshKey_test.go
/source/head/nodes/vr_sros/variant.go
/source/head/nodes/6wind_vsr/6wind_vsr.go
/source/head/nodes/host/host.go
/source/head/nodes/host/host_test.go
/source/head/nodes/qemu_resource_env_test.go
/source/head/nodes/iol/iol_test.go
/source/head/nodes/ceos/ceos.go
/source/head/nodes/iol/iol.go
/source/head/nodes/ceos/ceos_test.go
/source/head/nodes/ssh_export_test.go
/source/head/nodes/vr_node_test.go
/source/head/nodes/arrcus_arcos/arcos.go
/source/head/nodes/plvision_sonic/plvision_sonic.go
/source/head/nodes/cisco_sdwan/cisco_sdwan.go
/source/head/nodes/spirent_stc/stc.go
/source/head/nodes/vr_freebsd/vr-freebsd.go
/source/head/nodes/ovs/ovs.go
/source/head/nodes/vr_freebsd/vr-freebsd_test.go
/source/head/nodes/huawei_vrp/huawei_vrp.go
/source/head/nodes/generic_vm/generic_vm.go
/source/head/nodes/node_registry_linkapplymode_test.go
/source/head/nodes/vr_veos/vr-veos_test.go

(Results are truncated: showing first 100 results. Consider using a more specific path or pattern.)
Tool metadata
{
  "type": "tool",
  "id": "prt_1965114590015k3f2bJDZ2qSZX",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196510c3a001TWXRc4E0bury6D",
  "callID": "call_83d7848fa7d94cf18534558a",
  "tool": "glob",
  "state": {
    "status": "completed",
    "input": {
      "pattern": "**/*.go",
      "path": "/source"
    },
    "output": "/source/head/main.go\n/source/head/errors/errors.go\n/source/head/types/bind.go\n/source/head/types/types.go\n/source/head/types/topo_diff.go\n/source/head/types/hostentry.go\n/source/head/types/host_requirements.go\n/source/head/types/hostentry_test.go\n/source/head/types/license_policy_value.go\n/source/head/types/bind_test.go\n/source/head/types/volume.go\n/source/head/types/volume_test.go\n/source/head/types/ipversion.go\n/source/head/types/mgmt.go\n/source/head/types/mgmt_test.go\n/source/head/types/stages_test.go\n/source/head/types/node_definition_test.go\n/source/head/types/ssh_config.go\n/source/head/types/ipam.go\n/source/head/types/tailscale_ports.go\n/source/head/types/stages.go\n/source/head/types/topology_test.go\n/source/head/types/settings.go\n/source/head/types/node_definition.go\n/source/head/types/topo_diff_test.go\n/source/head/types/tailscale_ports_test.go\n/source/head/types/mgmt_networks_test.go\n/source/head/types/topology.go\n/source/head/types/topo_paths.go\n/source/head/exec/exec_test.go\n/source/head/exec/exec.go\n/source/head/virt/virt.go\n/source/head/virt/memory.go\n/source/head/constants/env.go\n/source/head/constants/containerlab.go\n/source/head/constants/labels.go\n/source/head/constants/os.go\n/source/head/capture/output.go\n/source/head/capture/local_test.go\n/source/head/cert/local_dir_cert_storage.go\n/source/head/capture/reorder.go\n/source/head/cert/cert.go\n/source/head/capture/reorder_test.go\n/source/head/cert/csr_input.go\n/source/head/capture/pcapng.go\n/source/head/capture/pcapng_test.go\n/source/head/capture/local.go\n/source/head/cert/certificate.go\n/source/head/cert/ca.go\n/source/head/netconf/netconf.go\n/source/head/nodes/bridge/bridge.go\n/source/head/nodes/xrd/xrd.go\n/source/head/nodes/ciena_saos/ciena_saos_test.go\n/source/head/nodes/ciena_saos/ciena_saos.go\n/source/head/nodes/rare/rare.go\n/source/head/nodes/vyosnetworks_vyos/vyos.go\n/source/head/nodes/vyosnetworks_vyos/helpers.go\n/source/head/nodes/ipinfusion_ocnos/ipinfusion_ocnos.go\n/source/head/nodes/vr_csr/vr-csr.go\n/source/head/nodes/vr_csr/vr-csr_test.go\n/source/head/nodes/cisco_vios/cisco-vios.go\n/source/head/nodes/cisco_vios/cisco-vios_test.go\n/source/head/nodes/kind_specific_config.go\n/source/head/nodes/vr_pan/vr-pan.go\n/source/head/nodes/vr_pan/vr-pan_test.go\n/source/head/nodes/default_node_test.go\n/source/head/nodes/sonic/sonic.go\n/source/head/nodes/sonic/sonic_test.go\n/source/head/nodes/cjunosevolved/cjunosevolved.go\n/source/head/nodes/vr_sros/vr-sros_test.go\n/source/head/nodes/vr_sros/vr-sros.go\n/source/head/nodes/vr_sros/interface_map.go\n/source/head/nodes/vr_ros/vr-ros_test.go\n/source/head/nodes/vr_ros/vr-ros.go\n/source/head/nodes/vr_sros/interface_map_test.go\n/source/head/nodes/vr_sros/variant_test.go\n/source/head/nodes/vr_sros/sshKey.go\n/source/head/nodes/vr_sros/sshKey_test.go\n/source/head/nodes/vr_sros/variant.go\n/source/head/nodes/6wind_vsr/6wind_vsr.go\n/source/head/nodes/host/host.go\n/source/head/nodes/host/host_test.go\n/source/head/nodes/qemu_resource_env_test.go\n/source/head/nodes/iol/iol_test.go\n/source/head/nodes/ceos/ceos.go\n/source/head/nodes/iol/iol.go\n/source/head/nodes/ceos/ceos_test.go\n/source/head/nodes/ssh_export_test.go\n/source/head/nodes/vr_node_test.go\n/source/head/nodes/arrcus_arcos/arcos.go\n/source/head/nodes/plvision_sonic/plvision_sonic.go\n/source/head/nodes/cisco_sdwan/cisco_sdwan.go\n/source/head/nodes/spirent_stc/stc.go\n/source/head/nodes/vr_freebsd/vr-freebsd.go\n/source/head/nodes/ovs/ovs.go\n/source/head/nodes/vr_freebsd/vr-freebsd_test.go\n/source/head/nodes/huawei_vrp/huawei_vrp.go\n/source/head/nodes/generic_vm/generic_vm.go\n/source/head/nodes/node_registry_linkapplymode_test.go\n/source/head/nodes/vr_veos/vr-veos_test.go\n\n(Results are truncated: showing first 100 results. Consider using a more specific path or pattern.)",
    "title": "source",
    "metadata": {
      "count": 100,
      "truncated": true
    },
    "time": {
      "start": 1793523258461,
      "end": 1793523258473
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19651146b001d7a0V4xN7iffqL",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196510c3a001TWXRc4E0bury6D",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 36119,
    "input": 245,
    "output": 18,
    "reasoning": 16,
    "cache": {
      "read": 35840,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196510c3a001TWXRc4E0bury6D",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523256378,
    "completed": 1793523258478
  },
  "parentID": "msg_19650e899001051OTPpm7MOch6",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 36119,
    "input": 245,
    "output": 18,
    "reasoning": 16,
    "cache": {
      "read": 35840,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 15
step-start
{
  "type": "step-start",
  "id": "prt_196511f55001joHw3UBL1uuRNU",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196511473001Mcyul0Xt2XB0L4"
}
read · completed

Input

{
  "filePath": "/source/head/capture/local.go"
}

Output

<path>/source/head/capture/local.go</path>
<type>file</type>
<content>
1: package capture
2: 
3: import (
4: 	"context"
5: 	"errors"
6: 	"fmt"
7: 	"io"
8: 	"os"
9: 	"sync"
10: 	"time"
11: 
12: 	"github.com/charmbracelet/log"
13: 	"github.com/containernetworking/plugins/pkg/ns"
14: 	"github.com/gopacket/gopacket"
15: 	"github.com/gopacket/gopacket/afpacket"
16: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
17: )
18: 
19: const (
20: 	// localReorderWindow is how long the merged stream holds packets of local sockets back to
21: 	// write them in timestamp order. Each socket hands over its packets within
22: 	// localBlockTimeout, so a few times that covers the delivery skew between sockets.
23: 	localReorderWindow = 100 * time.Millisecond
24: 	// localBlockTimeout is how long the kernel fills a ring block before it hands it over.
25: 	localBlockTimeout = 10 * time.Millisecond
26: 	// localPollTimeout is how often a socket reader checks whether the capture ended.
27: 	localPollTimeout = 100 * time.Millisecond
28: 	// localReopenInterval is how often a reader tries to reopen the socket of an interface
29: 	// that went down or disappeared.
30: 	localReopenInterval = 200 * time.Millisecond
31: 	// localDrainQuiet is how long after the end of a capture a reader keeps waiting for packets
32: 	// still in the socket's ring: the kernel hands over a block within two block timeouts.
33: 	localDrainQuiet = 5 * localBlockTimeout
34: 	// localDrainTimeout bounds the drain while packets keep arriving.
35: 	localDrainTimeout = 250 * time.Millisecond
36: 	// localRingBlocks and localMinBlockSize size the receive ring of each socket: eight blocks
37: 	// of at least 1 MiB, each larger than the snap length.
38: 	localRingBlocks   = 8
39: 	localMinBlockSize = 1 << 20
40: 	// vlanHeaderLength is the length of the 802.1Q tag put back into frames whose tag the
41: 	// kernel moved out of band.
42: 	vlanHeaderLength = 4
43: )
44: 
45: // errReadTimeout is returned by a packet source that has no packet within the poll timeout.
46: var errReadTimeout = errors.New("no packet within the poll timeout")
47: 
48: // ExecFunc runs f in the network namespace of a node.
49: type ExecFunc func(ctx context.Context, f func(ns.NetNS) error) error
50: 
51: // LocalTarget is one interface of a node on this machine (Docker or Podman) to capture.
52: type LocalTarget struct {
53: 	// Node is the node name as the topology spells it.
54: 	Node string
55: 	// Interface is the interface name inside the node.
56: 	Interface string
57: 	// Exec runs a function in the node's network namespace.
58: 	Exec ExecFunc
59: }
60: 
61: // packetSource reads the packets of one interface.
62: type packetSource interface {
63: 	// ReadPacket returns the next packet; the data is only valid until the next call. It
64: 	// returns errReadTimeout when no packet arrived within the poll timeout.
65: 	ReadPacket() ([]byte, gopacket.CaptureInfo, error)
66: 	Close()
67: }
68: 
69: // openSourcesFunc opens one packet source per interface in the network namespace exec enters.
70: type openSourcesFunc func(
71: 	ctx context.Context,
72: 	exec ExecFunc,
73: 	interfaces []string,
74: 	snapLength int,
75: ) ([]packetSource, error)
76: 
77: // CaptureLocal streams pcapng from interfaces of nodes on this machine to w, with the same
78: // output and end conditions as labruntime.PacketCapturer.Capture: one section, one Interface
79: // Description Block per target named <node>:<interface>, then the packets of every target in
80: // timestamp order. targets lists the interfaces of req.Targets, resolved, in the same order.
81: //
82: // Each interface is read through a packet socket opened in the node's network namespace, so
83: // nothing runs in the node and the node image needs no capture tools; it needs CAP_NET_RAW and
84: // the right to enter the namespace, so root. An interface that goes down is reopened once it is
85: // up again; one that disappears (its node stopped or was recreated) is reattached when it is
86: // back, and the time it was gone is reported as a gap through req.OnGap (or logged).
87: func CaptureLocal(
88: 	ctx context.Context,
89: 	req clablabruntime.CaptureRequest,
90: 	targets []LocalTarget,
91: 	w io.Writer,
92: ) error {
93: 	return localCapture{
94: 		open:           openPacketSockets,
95: 		window:         localReorderWindow,
96: 		reopenInterval: localReopenInterval,
97: 	}.run(ctx, req, targets, w)
98: }
99: 
100: // localCapture is a local capture with its socket opener and timings, which tests replace.
101: type localCapture struct {
102: 	open           openSourcesFunc
103: 	window         time.Duration
104: 	reopenInterval time.Duration
105: }
106: 
107: func (l localCapture) run(
108: 	ctx context.Context,
109: 	req clablabruntime.CaptureRequest,
110: 	targets []LocalTarget,
111: 	w io.Writer,
112: ) error {
113: 	if err := ValidateRequest(&req); err != nil {
114: 		return err
115: 	}
116: 	if len(targets) != len(req.Targets) {
117: 		return fmt.Errorf("capture has %d resolved targets for %d requested ones",
118: 			len(targets), len(req.Targets))
119: 	}
120: 
121: 	sources, err := l.openAll(ctx, targets, req.SnapLength)
122: 	if err != nil {
123: 		return err
124: 	}
125: 
126: 	names := make([]string, len(targets))
127: 	for idx, target := range targets {
128: 		names[idx] = target.Node + ":" + target.Interface
129: 	}
130: 
131: 	captureCtx, stop := context.WithCancel(ctx)
132: 	defer stop()
133: 	if req.Duration > 0 {
134: 		var cancelTimeout context.CancelFunc
135: 		captureCtx, cancelTimeout = context.WithTimeout(captureCtx, req.Duration)
136: 		defer cancelTimeout()
137: 	}
138: 
139: 	out, err := NewOutput(w, names, req.SnapLength, req.PacketLimit, l.window, stop)
140: 	if err != nil {
141: 		for _, source := range sources {
142: 			source.Close()
143: 		}
144: 
145: 		return err
146: 	}
147: 
148: 	var wg sync.WaitGroup
149: 	for idx, source := range sources {
150: 		reader := &localReader{
151: 			capture: l,
152: 			out:     out,
153: 			id:      uint32(idx), //nolint:gosec // bounded by the targets
154: 			target:  targets[idx],
155: 			snap:    req.SnapLength,
156: 			onGap:   req.OnGap,
157: 		}
158: 		wg.Go(func() {
159: 			reader.run(captureCtx, source)
160: 		})
161: 	}
162: 	wg.Wait()
163: 
164: 	return out.Close()
165: }
166: 
167: // openAll opens the sockets of every target before anything is written, one namespace entry
168: // per node, so a capture that cannot start fails without output.
169: func (l localCapture) openAll(
170: 	ctx context.Context,
171: 	targets []LocalTarget,
172: 	snapLength int,
173: ) ([]packetSource, error) {
174: 	type nodeTargets struct {
175: 		exec    ExecFunc
176: 		indexes []int
177: 		names   []string
178: 	}
179: 	var order []string
180: 	byNode := map[string]*nodeTargets{}
181: 	for idx, target := range targets {
182: 		group := byNode[target.Node]
183: 		if group == nil {
184: 			group = &nodeTargets{exec: target.Exec}
185: 			byNode[target.Node] = group
186: 			order = append(order, target.Node)
187: 		}
188: 		group.indexes = append(group.indexes, idx)
189: 		group.names = append(group.names, target.Interface)
190: 	}
191: 
192: 	sources := make([]packetSource, len(targets))
193: 	closeAll := func() {
194: 		for _, source := range sources {
195: 			if source != nil {
196: 				source.Close()
197: 			}
198: 		}
199: 	}
200: 	for _, node := range order {
201: 		group := byNode[node]
202: 		opened, err := l.open(ctx, group.exec, group.names, snapLength)
203: 		if err != nil {
204: 			closeAll()
205: 			return nil, fmt.Errorf("failed to start the capture on node %q: %w", node, err)
206: 		}
207: 		for idx, source := range opened {
208: 			sources[group.indexes[idx]] = source
209: 		}
210: 	}
211: 
212: 	return sources, nil
213: }
214: 
215: // localReader reads one interface into the merged stream.
216: type localReader struct {
217: 	capture localCapture
218: 	out     *Output
219: 	id      uint32
220: 	target  LocalTarget
221: 	snap    int
222: 	onGap   func(clablabruntime.CaptureGap)
223: }
224: 
225: func (r *localReader) run(ctx context.Context, source packetSource) {
226: 	defer func() {
227: 		if source != nil {
228: 			source.Close()
229: 		}
230: 	}()
231: 
232: 	for {
233: 		if ctx.Err() != nil {
234: 			r.drain(source, time.Now())
235: 			return
236: 		}
237: 
238: 		data, info, err := source.ReadPacket()
239: 		if errors.Is(err, errReadTimeout) {
240: 			continue
241: 		}
242: 		if err != nil {
243: 			// The socket reports an error once its interface went down or was removed, and
244: 			// keeps reporting it: it is reopened.
245: 			log.Debug("Capture socket failed, reopening it", "node", r.target.Node,
246: 				"interface", r.target.Interface, "error", err)
247: 			source.Close()
248: 			source = r.reopen(ctx)
249: 			if source == nil {
250: 				return
251: 			}
252: 
253: 			continue
254: 		}
255: 
256: 		if more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {
257: 			return
258: 		}
259: 	}
260: }
261: 
262: // drain writes the packets that arrived before end but were still in the socket's ring: the
263: // kernel hands over a ring block once it is full or its block timeout passed, so the last
264: // packets before a capture ended may not have been read yet.
265: func (r *localReader) drain(source packetSource, end time.Time) {
266: 	deadline := end.Add(localDrainTimeout)
267: 	for time.Now().Before(deadline) {
268: 		data, info, err := source.ReadPacket()
269: 		if errors.Is(err, errReadTimeout) && time.Since(end) < localDrainQuiet {
270: 			continue
271: 		}
272: 		if err != nil || info.Timestamp.After(end) {
273: 			return
274: 		}
275: 		if more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {
276: 			return
277: 		}
278: 	}
279: }
280: 
281: // packet copies a packet out of the socket's ring, cut to the snap length.
282: func (r *localReader) packet(data []byte, info gopacket.CaptureInfo) *Packet {
283: 	length := info.Length
284: 	for _, ancillary := range info.AncillaryData {
285: 		if _, ok := ancillary.(afpacket.AncillaryVLAN); ok {
286: 			// the tag was put back into the data and counts toward the frame length
287: 			length += vlanHeaderLength
288: 			break
289: 		}
290: 	}
291: 	length = max(length, len(data))
292: 
293: 	captured := make([]byte, min(len(data), r.snap))
294: 	copy(captured, data)
295: 
296: 	return &Packet{
297: 		Timestamp:      info.Timestamp.UnixNano(),
298: 		OriginalLength: uint32(length), //nolint:gosec // bounded by the interface MTU
299: 		Data:           captured,
300: 	}
301: }
302: 
303: // reopen opens the interface's socket again once its node and interface are back. It returns
304: // nil when the capture ended first. Time the interface could not be opened is reported as a gap;
305: // an interface that only went down is not, as it has no traffic while down.
306: func (r *localReader) reopen(ctx context.Context) packetSource {
307: 	from := time.Now()
308: 	var unavailable error
309: 
310: 	timer := time.NewTimer(r.capture.reopenInterval)
311: 	defer timer.Stop()
312: 
313: 	for {
314: 		select {
315: 		case <-ctx.Done():
316: 			if unavailable != nil {
317: 				r.reportGap(from, time.Time{}, unavailable)
318: 			}
319: 
320: 			return nil
321: 		case <-timer.C:
322: 		}
323: 
324: 		opened, err := r.capture.open(ctx, r.target.Exec, []string{r.target.Interface}, r.snap)
325: 		if err != nil {
326: 			if unavailable == nil {
327: 				log.Debug("Capture interface is not available, waiting for it",
328: 					"node", r.target.Node, "interface", r.target.Interface, "error", err)
329: 			}
330: 			unavailable = err
331: 			resetTimer(timer, r.capture.reopenInterval)
332: 
333: 			continue
334: 		}
335: 		if unavailable != nil {
336: 			r.reportGap(from, time.Now(), unavailable)
337: 		}
338: 
339: 		return opened[0]
340: 	}
341: }
342: 
343: func (r *localReader) reportGap(from, to time.Time, cause error) {
344: 	ReportGap(r.onGap, clablabruntime.CaptureGap{
345: 		Node:       r.target.Node,
346: 		Interfaces: []string{r.target.Interface},
347: 		From:       from,
348: 		To:         to,
349: 		Reason:     fmt.Sprintf("the interface was not available: %v", cause),
350: 	})
351: }
352: 
353: // openPacketSockets opens one packet socket per interface in the namespace exec enters. A socket
354: // stays bound to its interface after the thread left the namespace.
355: func openPacketSockets(
356: 	ctx context.Context,
357: 	exec ExecFunc,
358: 	interfaces []string,
359: 	snapLength int,
360: ) ([]packetSource, error) {
361: 	sources := make([]packetSource, 0, len(interfaces))
362: 	err := exec(ctx, func(ns.NetNS) error {
363: 		for _, name := range interfaces {
364: 			source, err := openPacketSocket(name, snapLength)
365: 			if err != nil {
366: 				return fmt.Errorf("interface %q: %w", name, err)
367: 			}
368: 			sources = append(sources, source)
369: 		}
370: 
371: 		return nil
372: 	})
373: 	if err != nil {
374: 		for _, source := range sources {
375: 			source.Close()
376: 		}
377: 
378: 		return nil, err
379: 	}
380: 
381: 	return sources, nil
382: }
383: 
384: // afpacketSource is a TPACKET_V3 receive ring on one interface.
385: type afpacketSource struct {
386: 	handle *afpacket.TPacket
387: }
388: 
389: func openPacketSocket(name string, snapLength int) (*afpacketSource, error) {
390: 	// A TPACKET_V3 block holds whole frames: it must be larger than the snap length, plus the
391: 	// block and frame headers, and a multiple of the page size.
392: 	pageSize := os.Getpagesize()
393: 	blockSize := max(localMinBlockSize, snapLength+pageSize)
394: 	blockSize = (blockSize + pageSize - 1) / pageSize * pageSize
395: 
396: 	handle, err := afpacket.NewTPacket(
397: 		afpacket.OptInterface(name),
398: 		afpacket.OptTPacketVersion(afpacket.TPacketVersion3),
399: 		afpacket.OptFrameSize(blockSize),
400: 		afpacket.OptBlockSize(blockSize),
401: 		afpacket.OptNumBlocks(localRingBlocks),
402: 		afpacket.OptBlockTimeout(localBlockTimeout),
403: 		afpacket.OptPollTimeout(localPollTimeout),
404: 		// the kernel moves 802.1Q tags out of the frame; captures show them in place
405: 		afpacket.OptAddVLANHeader(true),
406: 	)
407: 	if err != nil {
408: 		return nil, err
409: 	}
410: 	// promiscuous mode is a membership of this socket and ends with it
411: 	if err := handle.SetPromiscuous(true); err != nil {
412: 		handle.Close()
413: 		return nil, fmt.Errorf("failed to enable promiscuous mode: %w", err)
414: 	}
415: 
416: 	return &afpacketSource{handle: handle}, nil
417: }
418: 
419: func (s *afpacketSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {
420: 	data, info, err := s.handle.ZeroCopyReadPacketData()
421: 	if errors.Is(err, afpacket.ErrTimeout) {
422: 		return nil, info, errReadTimeout
423: 	}
424: 
425: 	return data, info, err
426: }
427: 
428: func (s *afpacketSource) Close() {
429: 	s.handle.Close()
430: }

(End of file - total 430 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196511f7d0011hyoPJN4GQjCS6",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196511473001Mcyul0Xt2XB0L4",
  "callID": "call_d84420cfe05c4caab74c1191",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/capture/local.go"
    },
    "output": "<path>/source/head/capture/local.go</path>\n<type>file</type>\n<content>\n1: package capture\n2: \n3: import (\n4: \t\"context\"\n5: \t\"errors\"\n6: \t\"fmt\"\n7: \t\"io\"\n8: \t\"os\"\n9: \t\"sync\"\n10: \t\"time\"\n11: \n12: \t\"github.com/charmbracelet/log\"\n13: \t\"github.com/containernetworking/plugins/pkg/ns\"\n14: \t\"github.com/gopacket/gopacket\"\n15: \t\"github.com/gopacket/gopacket/afpacket\"\n16: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n17: )\n18: \n19: const (\n20: \t// localReorderWindow is how long the merged stream holds packets of local sockets back to\n21: \t// write them in timestamp order. Each socket hands over its packets within\n22: \t// localBlockTimeout, so a few times that covers the delivery skew between sockets.\n23: \tlocalReorderWindow = 100 * time.Millisecond\n24: \t// localBlockTimeout is how long the kernel fills a ring block before it hands it over.\n25: \tlocalBlockTimeout = 10 * time.Millisecond\n26: \t// localPollTimeout is how often a socket reader checks whether the capture ended.\n27: \tlocalPollTimeout = 100 * time.Millisecond\n28: \t// localReopenInterval is how often a reader tries to reopen the socket of an interface\n29: \t// that went down or disappeared.\n30: \tlocalReopenInterval = 200 * time.Millisecond\n31: \t// localDrainQuiet is how long after the end of a capture a reader keeps waiting for packets\n32: \t// still in the socket's ring: the kernel hands over a block within two block timeouts.\n33: \tlocalDrainQuiet = 5 * localBlockTimeout\n34: \t// localDrainTimeout bounds the drain while packets keep arriving.\n35: \tlocalDrainTimeout = 250 * time.Millisecond\n36: \t// localRingBlocks and localMinBlockSize size the receive ring of each socket: eight blocks\n37: \t// of at least 1 MiB, each larger than the snap length.\n38: \tlocalRingBlocks   = 8\n39: \tlocalMinBlockSize = 1 << 20\n40: \t// vlanHeaderLength is the length of the 802.1Q tag put back into frames whose tag the\n41: \t// kernel moved out of band.\n42: \tvlanHeaderLength = 4\n43: )\n44: \n45: // errReadTimeout is returned by a packet source that has no packet within the poll timeout.\n46: var errReadTimeout = errors.New(\"no packet within the poll timeout\")\n47: \n48: // ExecFunc runs f in the network namespace of a node.\n49: type ExecFunc func(ctx context.Context, f func(ns.NetNS) error) error\n50: \n51: // LocalTarget is one interface of a node on this machine (Docker or Podman) to capture.\n52: type LocalTarget struct {\n53: \t// Node is the node name as the topology spells it.\n54: \tNode string\n55: \t// Interface is the interface name inside the node.\n56: \tInterface string\n57: \t// Exec runs a function in the node's network namespace.\n58: \tExec ExecFunc\n59: }\n60: \n61: // packetSource reads the packets of one interface.\n62: type packetSource interface {\n63: \t// ReadPacket returns the next packet; the data is only valid until the next call. It\n64: \t// returns errReadTimeout when no packet arrived within the poll timeout.\n65: \tReadPacket() ([]byte, gopacket.CaptureInfo, error)\n66: \tClose()\n67: }\n68: \n69: // openSourcesFunc opens one packet source per interface in the network namespace exec enters.\n70: type openSourcesFunc func(\n71: \tctx context.Context,\n72: \texec ExecFunc,\n73: \tinterfaces []string,\n74: \tsnapLength int,\n75: ) ([]packetSource, error)\n76: \n77: // CaptureLocal streams pcapng from interfaces of nodes on this machine to w, with the same\n78: // output and end conditions as labruntime.PacketCapturer.Capture: one section, one Interface\n79: // Description Block per target named <node>:<interface>, then the packets of every target in\n80: // timestamp order. targets lists the interfaces of req.Targets, resolved, in the same order.\n81: //\n82: // Each interface is read through a packet socket opened in the node's network namespace, so\n83: // nothing runs in the node and the node image needs no capture tools; it needs CAP_NET_RAW and\n84: // the right to enter the namespace, so root. An interface that goes down is reopened once it is\n85: // up again; one that disappears (its node stopped or was recreated) is reattached when it is\n86: // back, and the time it was gone is reported as a gap through req.OnGap (or logged).\n87: func CaptureLocal(\n88: \tctx context.Context,\n89: \treq clablabruntime.CaptureRequest,\n90: \ttargets []LocalTarget,\n91: \tw io.Writer,\n92: ) error {\n93: \treturn localCapture{\n94: \t\topen:           openPacketSockets,\n95: \t\twindow:         localReorderWindow,\n96: \t\treopenInterval: localReopenInterval,\n97: \t}.run(ctx, req, targets, w)\n98: }\n99: \n100: // localCapture is a local capture with its socket opener and timings, which tests replace.\n101: type localCapture struct {\n102: \topen           openSourcesFunc\n103: \twindow         time.Duration\n104: \treopenInterval time.Duration\n105: }\n106: \n107: func (l localCapture) run(\n108: \tctx context.Context,\n109: \treq clablabruntime.CaptureRequest,\n110: \ttargets []LocalTarget,\n111: \tw io.Writer,\n112: ) error {\n113: \tif err := ValidateRequest(&req); err != nil {\n114: \t\treturn err\n115: \t}\n116: \tif len(targets) != len(req.Targets) {\n117: \t\treturn fmt.Errorf(\"capture has %d resolved targets for %d requested ones\",\n118: \t\t\tlen(targets), len(req.Targets))\n119: \t}\n120: \n121: \tsources, err := l.openAll(ctx, targets, req.SnapLength)\n122: \tif err != nil {\n123: \t\treturn err\n124: \t}\n125: \n126: \tnames := make([]string, len(targets))\n127: \tfor idx, target := range targets {\n128: \t\tnames[idx] = target.Node + \":\" + target.Interface\n129: \t}\n130: \n131: \tcaptureCtx, stop := context.WithCancel(ctx)\n132: \tdefer stop()\n133: \tif req.Duration > 0 {\n134: \t\tvar cancelTimeout context.CancelFunc\n135: \t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx, req.Duration)\n136: \t\tdefer cancelTimeout()\n137: \t}\n138: \n139: \tout, err := NewOutput(w, names, req.SnapLength, req.PacketLimit, l.window, stop)\n140: \tif err != nil {\n141: \t\tfor _, source := range sources {\n142: \t\t\tsource.Close()\n143: \t\t}\n144: \n145: \t\treturn err\n146: \t}\n147: \n148: \tvar wg sync.WaitGroup\n149: \tfor idx, source := range sources {\n150: \t\treader := &localReader{\n151: \t\t\tcapture: l,\n152: \t\t\tout:     out,\n153: \t\t\tid:      uint32(idx), //nolint:gosec // bounded by the targets\n154: \t\t\ttarget:  targets[idx],\n155: \t\t\tsnap:    req.SnapLength,\n156: \t\t\tonGap:   req.OnGap,\n157: \t\t}\n158: \t\twg.Go(func() {\n159: \t\t\treader.run(captureCtx, source)\n160: \t\t})\n161: \t}\n162: \twg.Wait()\n163: \n164: \treturn out.Close()\n165: }\n166: \n167: // openAll opens the sockets of every target before anything is written, one namespace entry\n168: // per node, so a capture that cannot start fails without output.\n169: func (l localCapture) openAll(\n170: \tctx context.Context,\n171: \ttargets []LocalTarget,\n172: \tsnapLength int,\n173: ) ([]packetSource, error) {\n174: \ttype nodeTargets struct {\n175: \t\texec    ExecFunc\n176: \t\tindexes []int\n177: \t\tnames   []string\n178: \t}\n179: \tvar order []string\n180: \tbyNode := map[string]*nodeTargets{}\n181: \tfor idx, target := range targets {\n182: \t\tgroup := byNode[target.Node]\n183: \t\tif group == nil {\n184: \t\t\tgroup = &nodeTargets{exec: target.Exec}\n185: \t\t\tbyNode[target.Node] = group\n186: \t\t\torder = append(order, target.Node)\n187: \t\t}\n188: \t\tgroup.indexes = append(group.indexes, idx)\n189: \t\tgroup.names = append(group.names, target.Interface)\n190: \t}\n191: \n192: \tsources := make([]packetSource, len(targets))\n193: \tcloseAll := func() {\n194: \t\tfor _, source := range sources {\n195: \t\t\tif source != nil {\n196: \t\t\t\tsource.Close()\n197: \t\t\t}\n198: \t\t}\n199: \t}\n200: \tfor _, node := range order {\n201: \t\tgroup := byNode[node]\n202: \t\topened, err := l.open(ctx, group.exec, group.names, snapLength)\n203: \t\tif err != nil {\n204: \t\t\tcloseAll()\n205: \t\t\treturn nil, fmt.Errorf(\"failed to start the capture on node %q: %w\", node, err)\n206: \t\t}\n207: \t\tfor idx, source := range opened {\n208: \t\t\tsources[group.indexes[idx]] = source\n209: \t\t}\n210: \t}\n211: \n212: \treturn sources, nil\n213: }\n214: \n215: // localReader reads one interface into the merged stream.\n216: type localReader struct {\n217: \tcapture localCapture\n218: \tout     *Output\n219: \tid      uint32\n220: \ttarget  LocalTarget\n221: \tsnap    int\n222: \tonGap   func(clablabruntime.CaptureGap)\n223: }\n224: \n225: func (r *localReader) run(ctx context.Context, source packetSource) {\n226: \tdefer func() {\n227: \t\tif source != nil {\n228: \t\t\tsource.Close()\n229: \t\t}\n230: \t}()\n231: \n232: \tfor {\n233: \t\tif ctx.Err() != nil {\n234: \t\t\tr.drain(source, time.Now())\n235: \t\t\treturn\n236: \t\t}\n237: \n238: \t\tdata, info, err := source.ReadPacket()\n239: \t\tif errors.Is(err, errReadTimeout) {\n240: \t\t\tcontinue\n241: \t\t}\n242: \t\tif err != nil {\n243: \t\t\t// The socket reports an error once its interface went down or was removed, and\n244: \t\t\t// keeps reporting it: it is reopened.\n245: \t\t\tlog.Debug(\"Capture socket failed, reopening it\", \"node\", r.target.Node,\n246: \t\t\t\t\"interface\", r.target.Interface, \"error\", err)\n247: \t\t\tsource.Close()\n248: \t\t\tsource = r.reopen(ctx)\n249: \t\t\tif source == nil {\n250: \t\t\t\treturn\n251: \t\t\t}\n252: \n253: \t\t\tcontinue\n254: \t\t}\n255: \n256: \t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n257: \t\t\treturn\n258: \t\t}\n259: \t}\n260: }\n261: \n262: // drain writes the packets that arrived before end but were still in the socket's ring: the\n263: // kernel hands over a ring block once it is full or its block timeout passed, so the last\n264: // packets before a capture ended may not have been read yet.\n265: func (r *localReader) drain(source packetSource, end time.Time) {\n266: \tdeadline := end.Add(localDrainTimeout)\n267: \tfor time.Now().Before(deadline) {\n268: \t\tdata, info, err := source.ReadPacket()\n269: \t\tif errors.Is(err, errReadTimeout) && time.Since(end) < localDrainQuiet {\n270: \t\t\tcontinue\n271: \t\t}\n272: \t\tif err != nil || info.Timestamp.After(end) {\n273: \t\t\treturn\n274: \t\t}\n275: \t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n276: \t\t\treturn\n277: \t\t}\n278: \t}\n279: }\n280: \n281: // packet copies a packet out of the socket's ring, cut to the snap length.\n282: func (r *localReader) packet(data []byte, info gopacket.CaptureInfo) *Packet {\n283: \tlength := info.Length\n284: \tfor _, ancillary := range info.AncillaryData {\n285: \t\tif _, ok := ancillary.(afpacket.AncillaryVLAN); ok {\n286: \t\t\t// the tag was put back into the data and counts toward the frame length\n287: \t\t\tlength += vlanHeaderLength\n288: \t\t\tbreak\n289: \t\t}\n290: \t}\n291: \tlength = max(length, len(data))\n292: \n293: \tcaptured := make([]byte, min(len(data), r.snap))\n294: \tcopy(captured, data)\n295: \n296: \treturn &Packet{\n297: \t\tTimestamp:      info.Timestamp.UnixNano(),\n298: \t\tOriginalLength: uint32(length), //nolint:gosec // bounded by the interface MTU\n299: \t\tData:           captured,\n300: \t}\n301: }\n302: \n303: // reopen opens the interface's socket again once its node and interface are back. It returns\n304: // nil when the capture ended first. Time the interface could not be opened is reported as a gap;\n305: // an interface that only went down is not, as it has no traffic while down.\n306: func (r *localReader) reopen(ctx context.Context) packetSource {\n307: \tfrom := time.Now()\n308: \tvar unavailable error\n309: \n310: \ttimer := time.NewTimer(r.capture.reopenInterval)\n311: \tdefer timer.Stop()\n312: \n313: \tfor {\n314: \t\tselect {\n315: \t\tcase <-ctx.Done():\n316: \t\t\tif unavailable != nil {\n317: \t\t\t\tr.reportGap(from, time.Time{}, unavailable)\n318: \t\t\t}\n319: \n320: \t\t\treturn nil\n321: \t\tcase <-timer.C:\n322: \t\t}\n323: \n324: \t\topened, err := r.capture.open(ctx, r.target.Exec, []string{r.target.Interface}, r.snap)\n325: \t\tif err != nil {\n326: \t\t\tif unavailable == nil {\n327: \t\t\t\tlog.Debug(\"Capture interface is not available, waiting for it\",\n328: \t\t\t\t\t\"node\", r.target.Node, \"interface\", r.target.Interface, \"error\", err)\n329: \t\t\t}\n330: \t\t\tunavailable = err\n331: \t\t\tresetTimer(timer, r.capture.reopenInterval)\n332: \n333: \t\t\tcontinue\n334: \t\t}\n335: \t\tif unavailable != nil {\n336: \t\t\tr.reportGap(from, time.Now(), unavailable)\n337: \t\t}\n338: \n339: \t\treturn opened[0]\n340: \t}\n341: }\n342: \n343: func (r *localReader) reportGap(from, to time.Time, cause error) {\n344: \tReportGap(r.onGap, clablabruntime.CaptureGap{\n345: \t\tNode:       r.target.Node,\n346: \t\tInterfaces: []string{r.target.Interface},\n347: \t\tFrom:       from,\n348: \t\tTo:         to,\n349: \t\tReason:     fmt.Sprintf(\"the interface was not available: %v\", cause),\n350: \t})\n351: }\n352: \n353: // openPacketSockets opens one packet socket per interface in the namespace exec enters. A socket\n354: // stays bound to its interface after the thread left the namespace.\n355: func openPacketSockets(\n356: \tctx context.Context,\n357: \texec ExecFunc,\n358: \tinterfaces []string,\n359: \tsnapLength int,\n360: ) ([]packetSource, error) {\n361: \tsources := make([]packetSource, 0, len(interfaces))\n362: \terr := exec(ctx, func(ns.NetNS) error {\n363: \t\tfor _, name := range interfaces {\n364: \t\t\tsource, err := openPacketSocket(name, snapLength)\n365: \t\t\tif err != nil {\n366: \t\t\t\treturn fmt.Errorf(\"interface %q: %w\", name, err)\n367: \t\t\t}\n368: \t\t\tsources = append(sources, source)\n369: \t\t}\n370: \n371: \t\treturn nil\n372: \t})\n373: \tif err != nil {\n374: \t\tfor _, source := range sources {\n375: \t\t\tsource.Close()\n376: \t\t}\n377: \n378: \t\treturn nil, err\n379: \t}\n380: \n381: \treturn sources, nil\n382: }\n383: \n384: // afpacketSource is a TPACKET_V3 receive ring on one interface.\n385: type afpacketSource struct {\n386: \thandle *afpacket.TPacket\n387: }\n388: \n389: func openPacketSocket(name string, snapLength int) (*afpacketSource, error) {\n390: \t// A TPACKET_V3 block holds whole frames: it must be larger than the snap length, plus the\n391: \t// block and frame headers, and a multiple of the page size.\n392: \tpageSize := os.Getpagesize()\n393: \tblockSize := max(localMinBlockSize, snapLength+pageSize)\n394: \tblockSize = (blockSize + pageSize - 1) / pageSize * pageSize\n395: \n396: \thandle, err := afpacket.NewTPacket(\n397: \t\tafpacket.OptInterface(name),\n398: \t\tafpacket.OptTPacketVersion(afpacket.TPacketVersion3),\n399: \t\tafpacket.OptFrameSize(blockSize),\n400: \t\tafpacket.OptBlockSize(blockSize),\n401: \t\tafpacket.OptNumBlocks(localRingBlocks),\n402: \t\tafpacket.OptBlockTimeout(localBlockTimeout),\n403: \t\tafpacket.OptPollTimeout(localPollTimeout),\n404: \t\t// the kernel moves 802.1Q tags out of the frame; captures show them in place\n405: \t\tafpacket.OptAddVLANHeader(true),\n406: \t)\n407: \tif err != nil {\n408: \t\treturn nil, err\n409: \t}\n410: \t// promiscuous mode is a membership of this socket and ends with it\n411: \tif err := handle.SetPromiscuous(true); err != nil {\n412: \t\thandle.Close()\n413: \t\treturn nil, fmt.Errorf(\"failed to enable promiscuous mode: %w\", err)\n414: \t}\n415: \n416: \treturn &afpacketSource{handle: handle}, nil\n417: }\n418: \n419: func (s *afpacketSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {\n420: \tdata, info, err := s.handle.ZeroCopyReadPacketData()\n421: \tif errors.Is(err, afpacket.ErrTimeout) {\n422: \t\treturn nil, info, errReadTimeout\n423: \t}\n424: \n425: \treturn data, info, err\n426: }\n427: \n428: func (s *afpacketSource) Close() {\n429: \ts.handle.Close()\n430: }\n\n(End of file - total 430 lines)\n</content>",
    "title": "source/head/capture/local.go",
    "metadata": {
      "preview": "package capture\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\t\"github.com/containernetworking/plugins/pkg/ns\"\n\t\"github.com/gopacket/gopacket\"\n\t\"github.com/gopacket/gopacket/afpacket\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\nconst (\n\t// localReorderWindow is how long the merged stream holds packets of local sockets back to",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/capture/local.go",
        "text": "package capture\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\t\"github.com/containernetworking/plugins/pkg/ns\"\n\t\"github.com/gopacket/gopacket\"\n\t\"github.com/gopacket/gopacket/afpacket\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\nconst (\n\t// localReorderWindow is how long the merged stream holds packets of local sockets back to\n\t// write them in timestamp order. Each socket hands over its packets within\n\t// localBlockTimeout, so a few times that covers the delivery skew between sockets.\n\tlocalReorderWindow = 100 * time.Millisecond\n\t// localBlockTimeout is how long the kernel fills a ring block before it hands it over.\n\tlocalBlockTimeout = 10 * time.Millisecond\n\t// localPollTimeout is how often a socket reader checks whether the capture ended.\n\tlocalPollTimeout = 100 * time.Millisecond\n\t// localReopenInterval is how often a reader tries to reopen the socket of an interface\n\t// that went down or disappeared.\n\tlocalReopenInterval = 200 * time.Millisecond\n\t// localDrainQuiet is how long after the end of a capture a reader keeps waiting for packets\n\t// still in the socket's ring: the kernel hands over a block within two block timeouts.\n\tlocalDrainQuiet = 5 * localBlockTimeout\n\t// localDrainTimeout bounds the drain while packets keep arriving.\n\tlocalDrainTimeout = 250 * time.Millisecond\n\t// localRingBlocks and localMinBlockSize size the receive ring of each socket: eight blocks\n\t// of at least 1 MiB, each larger than the snap length.\n\tlocalRingBlocks   = 8\n\tlocalMinBlockSize = 1 << 20\n\t// vlanHeaderLength is the length of the 802.1Q tag put back into frames whose tag the\n\t// kernel moved out of band.\n\tvlanHeaderLength = 4\n)\n\n// errReadTimeout is returned by a packet source that has no packet within the poll timeout.\nvar errReadTimeout = errors.New(\"no packet within the poll timeout\")\n\n// ExecFunc runs f in the network namespace of a node.\ntype ExecFunc func(ctx context.Context, f func(ns.NetNS) error) error\n\n// LocalTarget is one interface of a node on this machine (Docker or Podman) to capture.\ntype LocalTarget struct {\n\t// Node is the node name as the topology spells it.\n\tNode string\n\t// Interface is the interface name inside the node.\n\tInterface string\n\t// Exec runs a function in the node's network namespace.\n\tExec ExecFunc\n}\n\n// packetSource reads the packets of one interface.\ntype packetSource interface {\n\t// ReadPacket returns the next packet; the data is only valid until the next call. It\n\t// returns errReadTimeout when no packet arrived within the poll timeout.\n\tReadPacket() ([]byte, gopacket.CaptureInfo, error)\n\tClose()\n}\n\n// openSourcesFunc opens one packet source per interface in the network namespace exec enters.\ntype openSourcesFunc func(\n\tctx context.Context,\n\texec ExecFunc,\n\tinterfaces []string,\n\tsnapLength int,\n) ([]packetSource, error)\n\n// CaptureLocal streams pcapng from interfaces of nodes on this machine to w, with the same\n// output and end conditions as labruntime.PacketCapturer.Capture: one section, one Interface\n// Description Block per target named <node>:<interface>, then the packets of every target in\n// timestamp order. targets lists the interfaces of req.Targets, resolved, in the same order.\n//\n// Each interface is read through a packet socket opened in the node's network namespace, so\n// nothing runs in the node and the node image needs no capture tools; it needs CAP_NET_RAW and\n// the right to enter the namespace, so root. An interface that goes down is reopened once it is\n// up again; one that disappears (its node stopped or was recreated) is reattached when it is\n// back, and the time it was gone is reported as a gap through req.OnGap (or logged).\nfunc CaptureLocal(\n\tctx context.Context,\n\treq clablabruntime.CaptureRequest,\n\ttargets []LocalTarget,\n\tw io.Writer,\n) error {\n\treturn localCapture{\n\t\topen:           openPacketSockets,\n\t\twindow:         localReorderWindow,\n\t\treopenInterval: localReopenInterval,\n\t}.run(ctx, req, targets, w)\n}\n\n// localCapture is a local capture with its socket opener and timings, which tests replace.\ntype localCapture struct {\n\topen           openSourcesFunc\n\twindow         time.Duration\n\treopenInterval time.Duration\n}\n\nfunc (l localCapture) run(\n\tctx context.Context,\n\treq clablabruntime.CaptureRequest,\n\ttargets []LocalTarget,\n\tw io.Writer,\n) error {\n\tif err := ValidateRequest(&req); err != nil {\n\t\treturn err\n\t}\n\tif len(targets) != len(req.Targets) {\n\t\treturn fmt.Errorf(\"capture has %d resolved targets for %d requested ones\",\n\t\t\tlen(targets), len(req.Targets))\n\t}\n\n\tsources, err := l.openAll(ctx, targets, req.SnapLength)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnames := make([]string, len(targets))\n\tfor idx, target := range targets {\n\t\tnames[idx] = target.Node + \":\" + target.Interface\n\t}\n\n\tcaptureCtx, stop := context.WithCancel(ctx)\n\tdefer stop()\n\tif req.Duration > 0 {\n\t\tvar cancelTimeout context.CancelFunc\n\t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx, req.Duration)\n\t\tdefer cancelTimeout()\n\t}\n\n\tout, err := NewOutput(w, names, req.SnapLength, req.PacketLimit, l.window, stop)\n\tif err != nil {\n\t\tfor _, source := range sources {\n\t\t\tsource.Close()\n\t\t}\n\n\t\treturn err\n\t}\n\n\tvar wg sync.WaitGroup\n\tfor idx, source := range sources {\n\t\treader := &localReader{\n\t\t\tcapture: l,\n\t\t\tout:     out,\n\t\t\tid:      uint32(idx), //nolint:gosec // bounded by the targets\n\t\t\ttarget:  targets[idx],\n\t\t\tsnap:    req.SnapLength,\n\t\t\tonGap:   req.OnGap,\n\t\t}\n\t\twg.Go(func() {\n\t\t\treader.run(captureCtx, source)\n\t\t})\n\t}\n\twg.Wait()\n\n\treturn out.Close()\n}\n\n// openAll opens the sockets of every target before anything is written, one namespace entry\n// per node, so a capture that cannot start fails without output.\nfunc (l localCapture) openAll(\n\tctx context.Context,\n\ttargets []LocalTarget,\n\tsnapLength int,\n) ([]packetSource, error) {\n\ttype nodeTargets struct {\n\t\texec    ExecFunc\n\t\tindexes []int\n\t\tnames   []string\n\t}\n\tvar order []string\n\tbyNode := map[string]*nodeTargets{}\n\tfor idx, target := range targets {\n\t\tgroup := byNode[target.Node]\n\t\tif group == nil {\n\t\t\tgroup = &nodeTargets{exec: target.Exec}\n\t\t\tbyNode[target.Node] = group\n\t\t\torder = append(order, target.Node)\n\t\t}\n\t\tgroup.indexes = append(group.indexes, idx)\n\t\tgroup.names = append(group.names, target.Interface)\n\t}\n\n\tsources := make([]packetSource, len(targets))\n\tcloseAll := func() {\n\t\tfor _, source := range sources {\n\t\t\tif source != nil {\n\t\t\t\tsource.Close()\n\t\t\t}\n\t\t}\n\t}\n\tfor _, node := range order {\n\t\tgroup := byNode[node]\n\t\topened, err := l.open(ctx, group.exec, group.names, snapLength)\n\t\tif err != nil {\n\t\t\tcloseAll()\n\t\t\treturn nil, fmt.Errorf(\"failed to start the capture on node %q: %w\", node, err)\n\t\t}\n\t\tfor idx, source := range opened {\n\t\t\tsources[group.indexes[idx]] = source\n\t\t}\n\t}\n\n\treturn sources, nil\n}\n\n// localReader reads one interface into the merged stream.\ntype localReader struct {\n\tcapture localCapture\n\tout     *Output\n\tid      uint32\n\ttarget  LocalTarget\n\tsnap    int\n\tonGap   func(clablabruntime.CaptureGap)\n}\n\nfunc (r *localReader) run(ctx context.Context, source packetSource) {\n\tdefer func() {\n\t\tif source != nil {\n\t\t\tsource.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tif ctx.Err() != nil {\n\t\t\tr.drain(source, time.Now())\n\t\t\treturn\n\t\t}\n\n\t\tdata, info, err := source.ReadPacket()\n\t\tif errors.Is(err, errReadTimeout) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\t// The socket reports an error once its interface went down or was removed, and\n\t\t\t// keeps reporting it: it is reopened.\n\t\t\tlog.Debug(\"Capture socket failed, reopening it\", \"node\", r.target.Node,\n\t\t\t\t\"interface\", r.target.Interface, \"error\", err)\n\t\t\tsource.Close()\n\t\t\tsource = r.reopen(ctx)\n\t\t\tif source == nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// drain writes the packets that arrived before end but were still in the socket's ring: the\n// kernel hands over a ring block once it is full or its block timeout passed, so the last\n// packets before a capture ended may not have been read yet.\nfunc (r *localReader) drain(source packetSource, end time.Time) {\n\tdeadline := end.Add(localDrainTimeout)\n\tfor time.Now().Before(deadline) {\n\t\tdata, info, err := source.ReadPacket()\n\t\tif errors.Is(err, errReadTimeout) && time.Since(end) < localDrainQuiet {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil || info.Timestamp.After(end) {\n\t\t\treturn\n\t\t}\n\t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// packet copies a packet out of the socket's ring, cut to the snap length.\nfunc (r *localReader) packet(data []byte, info gopacket.CaptureInfo) *Packet {\n\tlength := info.Length\n\tfor _, ancillary := range info.AncillaryData {\n\t\tif _, ok := ancillary.(afpacket.AncillaryVLAN); ok {\n\t\t\t// the tag was put back into the data and counts toward the frame length\n\t\t\tlength += vlanHeaderLength\n\t\t\tbreak\n\t\t}\n\t}\n\tlength = max(length, len(data))\n\n\tcaptured := make([]byte, min(len(data), r.snap))\n\tcopy(captured, data)\n\n\treturn &Packet{\n\t\tTimestamp:      info.Timestamp.UnixNano(),\n\t\tOriginalLength: uint32(length), //nolint:gosec // bounded by the interface MTU\n\t\tData:           captured,\n\t}\n}\n\n// reopen opens the interface's socket again once its node and interface are back. It returns\n// nil when the capture ended first. Time the interface could not be opened is reported as a gap;\n// an interface that only went down is not, as it has no traffic while down.\nfunc (r *localReader) reopen(ctx context.Context) packetSource {\n\tfrom := time.Now()\n\tvar unavailable error\n\n\ttimer := time.NewTimer(r.capture.reopenInterval)\n\tdefer timer.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tif unavailable != nil {\n\t\t\t\tr.reportGap(from, time.Time{}, unavailable)\n\t\t\t}\n\n\t\t\treturn nil\n\t\tcase <-timer.C:\n\t\t}\n\n\t\topened, err := r.capture.open(ctx, r.target.Exec, []string{r.target.Interface}, r.snap)\n\t\tif err != nil {\n\t\t\tif unavailable == nil {\n\t\t\t\tlog.Debug(\"Capture interface is not available, waiting for it\",\n\t\t\t\t\t\"node\", r.target.Node, \"interface\", r.target.Interface, \"error\", err)\n\t\t\t}\n\t\t\tunavailable = err\n\t\t\tresetTimer(timer, r.capture.reopenInterval)\n\n\t\t\tcontinue\n\t\t}\n\t\tif unavailable != nil {\n\t\t\tr.reportGap(from, time.Now(), unavailable)\n\t\t}\n\n\t\treturn opened[0]\n\t}\n}\n\nfunc (r *localReader) reportGap(from, to time.Time, cause error) {\n\tReportGap(r.onGap, clablabruntime.CaptureGap{\n\t\tNode:       r.target.Node,\n\t\tInterfaces: []string{r.target.Interface},\n\t\tFrom:       from,\n\t\tTo:         to,\n\t\tReason:     fmt.Sprintf(\"the interface was not available: %v\", cause),\n\t})\n}\n\n// openPacketSockets opens one packet socket per interface in the namespace exec enters. A socket\n// stays bound to its interface after the thread left the namespace.\nfunc openPacketSockets(\n\tctx context.Context,\n\texec ExecFunc,\n\tinterfaces []string,\n\tsnapLength int,\n) ([]packetSource, error) {\n\tsources := make([]packetSource, 0, len(interfaces))\n\terr := exec(ctx, func(ns.NetNS) error {\n\t\tfor _, name := range interfaces {\n\t\t\tsource, err := openPacketSocket(name, snapLength)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"interface %q: %w\", name, err)\n\t\t\t}\n\t\t\tsources = append(sources, source)\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tfor _, source := range sources {\n\t\t\tsource.Close()\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn sources, nil\n}\n\n// afpacketSource is a TPACKET_V3 receive ring on one interface.\ntype afpacketSource struct {\n\thandle *afpacket.TPacket\n}\n\nfunc openPacketSocket(name string, snapLength int) (*afpacketSource, error) {\n\t// A TPACKET_V3 block holds whole frames: it must be larger than the snap length, plus the\n\t// block and frame headers, and a multiple of the page size.\n\tpageSize := os.Getpagesize()\n\tblockSize := max(localMinBlockSize, snapLength+pageSize)\n\tblockSize = (blockSize + pageSize - 1) / pageSize * pageSize\n\n\thandle, err := afpacket.NewTPacket(\n\t\tafpacket.OptInterface(name),\n\t\tafpacket.OptTPacketVersion(afpacket.TPacketVersion3),\n\t\tafpacket.OptFrameSize(blockSize),\n\t\tafpacket.OptBlockSize(blockSize),\n\t\tafpacket.OptNumBlocks(localRingBlocks),\n\t\tafpacket.OptBlockTimeout(localBlockTimeout),\n\t\tafpacket.OptPollTimeout(localPollTimeout),\n\t\t// the kernel moves 802.1Q tags out of the frame; captures show them in place\n\t\tafpacket.OptAddVLANHeader(true),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// promiscuous mode is a membership of this socket and ends with it\n\tif err := handle.SetPromiscuous(true); err != nil {\n\t\thandle.Close()\n\t\treturn nil, fmt.Errorf(\"failed to enable promiscuous mode: %w\", err)\n\t}\n\n\treturn &afpacketSource{handle: handle}, nil\n}\n\nfunc (s *afpacketSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {\n\tdata, info, err := s.handle.ZeroCopyReadPacketData()\n\tif errors.Is(err, afpacket.ErrTimeout) {\n\t\treturn nil, info, errReadTimeout\n\t}\n\n\treturn data, info, err\n}\n\nfunc (s *afpacketSource) Close() {\n\ts.handle.Close()\n}",
        "lineStart": 1,
        "lineEnd": 430,
        "totalLines": 430,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523261313,
      "end": 1793523261319
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/capture/reorder.go"
}

Output

<path>/source/head/capture/reorder.go</path>
<type>file</type>
<content>
1: package capture
2: 
3: import (
4: 	"container/heap"
5: 	"context"
6: 	"sync"
7: 	"time"
8: 
9: 	"github.com/charmbracelet/log"
10: )
11: 
12: // maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets
13: // are written early, which can put them out of order.
14: const maxReorderBytes = 64 << 20
15: 
16: // Reorder writes the packets of several capture sources in timestamp order.
17: //
18: // Each source (a node's capture stream, or a local interface socket) delivers its packets with
19: // its own delay. The buffer holds every packet for `window` after it arrived and writes the held
20: // packets in timestamp order, so a packet that was stamped earlier but delivered up to `window`
21: // later still goes out first. A packet stamped before the last packet written arrived too late
22: // to be ordered: it is written as it comes and counted, and the count goes to the debug log when
23: // the capture ends.
24: //
25: // A source can place a hold at the earliest timestamp it may still write (Hold); packets stamped
26: // after a hold wait for it to be released (Release). The c9s runtime holds while it switches
27: // between chained capture segments.
28: type Reorder struct {
29: 	write  func(id uint32, packet *Packet) error
30: 	onFail func()
31: 	window time.Duration
32: 	now    func() time.Time
33: 
34: 	mu     sync.Mutex
35: 	queue  reorderQueue
36: 	bytes  int
37: 	seq    uint64
38: 	holds  map[any]int64
39: 	err    error
40: 	wake   chan struct{}
41: 	stats  reorderStats
42: 	cursor int64 // timestamp of the latest packet written in order
43: }
44: 
45: type reorderStats struct {
46: 	late    int
47: 	maxLate time.Duration
48: 	forced  int
49: }
50: 
51: // reorderedPacket is a packet waiting in the buffer.
52: type reorderedPacket struct {
53: 	id      uint32
54: 	packet  *Packet
55: 	arrived time.Time
56: 	seq     uint64
57: }
58: 
59: // reorderQueue is a min-heap by timestamp, then arrival.
60: type reorderQueue []reorderedPacket
61: 
62: func (q reorderQueue) Len() int { return len(q) }
63: 
64: func (q reorderQueue) Less(i, j int) bool {
65: 	if q[i].packet.Timestamp != q[j].packet.Timestamp {
66: 		return q[i].packet.Timestamp < q[j].packet.Timestamp
67: 	}
68: 
69: 	return q[i].seq < q[j].seq
70: }
71: 
72: func (q reorderQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
73: 
74: func (q *reorderQueue) Push(
75: 	x any,
76: ) {
77: 	*q = append(*q, x.(reorderedPacket))
78: } //nolint:forcetypeassert // heap contract
79: 
80: func (q *reorderQueue) Pop() any {
81: 	old := *q
82: 	item := old[len(old)-1]
83: 	*q = old[:len(old)-1]
84: 
85: 	return item
86: }
87: 
88: // NewReorder returns a buffer that writes through write; onFail is called once a write
89: // failed. A window of zero or less writes every packet as it arrives.
90: func NewReorder(
91: 	window time.Duration,
92: 	write func(id uint32, packet *Packet) error,
93: 	onFail func(),
94: ) *Reorder {
95: 	return &Reorder{
96: 		write: write, onFail: onFail, window: window, now: time.Now,
97: 		holds: map[any]int64{}, wake: make(chan struct{}, 1),
98: 	}
99: }
100: 
101: // push hands a packet to the buffer. It returns the error of a failed write.
102: func (q *Reorder) Push(id uint32, packet *Packet) error {
103: 	q.mu.Lock()
104: 	defer q.mu.Unlock()
105: 
106: 	if q.err != nil {
107: 		return q.err
108: 	}
109: 	if q.window <= 0 {
110: 		return q.writeLocked(id, packet)
111: 	}
112: 	if q.cursor != 0 && packet.Timestamp < q.cursor {
113: 		q.stats.late++
114: 		q.stats.maxLate = max(q.stats.maxLate, time.Duration(q.cursor-packet.Timestamp))
115: 		if q.stats.late == 1 {
116: 			log.Debug("Capture packet arrived after the reorder window, writing it out of order",
117: 				"late_by", time.Duration(q.cursor-packet.Timestamp), "window", q.window)
118: 		}
119: 
120: 		return q.writeLocked(id, packet)
121: 	}
122: 
123: 	q.seq++
124: 	heap.Push(&q.queue, reorderedPacket{id: id, packet: packet, arrived: q.now(), seq: q.seq})
125: 	q.bytes += len(packet.Data)
126: 	for q.bytes > maxReorderBytes && q.queue.Len() > 0 {
127: 		q.stats.forced++
128: 		if err := q.popLocked(); err != nil {
129: 			return err
130: 		}
131: 	}
132: 
133: 	select {
134: 	case q.wake <- struct{}{}:
135: 	default:
136: 	}
137: 
138: 	return nil
139: }
140: 
141: // hold keeps packets stamped after timestamp in the buffer until release(key).
142: func (q *Reorder) Hold(key any, timestamp int64) {
143: 	q.mu.Lock()
144: 	defer q.mu.Unlock()
145: 
146: 	q.holds[key] = timestamp
147: }
148: 
149: // release removes the hold of key.
150: func (q *Reorder) Release(key any) {
151: 	q.mu.Lock()
152: 	_, held := q.holds[key]
153: 	delete(q.holds, key)
154: 	q.mu.Unlock()
155: 
156: 	if held {
157: 		select {
158: 		case q.wake <- struct{}{}:
159: 		default:
160: 		}
161: 	}
162: }
163: 
164: // run writes due packets until ctx ends.
165: func (q *Reorder) Run(ctx context.Context) {
166: 	if q.window <= 0 {
167: 		return
168: 	}
169: 
170: 	timer := time.NewTimer(time.Hour)
171: 	defer timer.Stop()
172: 
173: 	for {
174: 		next := q.writeDue()
175: 		wait := time.Hour
176: 		if !next.IsZero() {
177: 			wait = max(next.Sub(q.now()), time.Millisecond)
178: 		}
179: 		resetTimer(timer, wait)
180: 
181: 		select {
182: 		case <-ctx.Done():
183: 			return
184: 		case <-q.wake:
185: 		case <-timer.C:
186: 		}
187: 	}
188: }
189: 
190: // writeDue writes the packets that waited for the window and are not behind a hold, in
191: // timestamp order. It returns when the next packet is due, or zero when that depends on a new
192: // packet or a released hold.
193: func (q *Reorder) writeDue() time.Time {
194: 	q.mu.Lock()
195: 	defer q.mu.Unlock()
196: 
197: 	held, limit := false, int64(0)
198: 	for _, timestamp := range q.holds {
199: 		if !held || timestamp < limit {
200: 			held, limit = true, timestamp
201: 		}
202: 	}
203: 
204: 	now := q.now()
205: 	for q.queue.Len() > 0 && q.err == nil {
206: 		head := q.queue[0]
207: 		if held && head.packet.Timestamp > limit {
208: 			return time.Time{}
209: 		}
210: 		if due := head.arrived.Add(q.window); due.After(now) {
211: 			return due
212: 		}
213: 		if q.popLocked() != nil {
214: 			return time.Time{}
215: 		}
216: 	}
217: 
218: 	return time.Time{}
219: }
220: 
221: // flush writes every remaining packet in timestamp order and logs what could not be ordered.
222: func (q *Reorder) Flush() {
223: 	q.mu.Lock()
224: 	defer q.mu.Unlock()
225: 
226: 	for q.queue.Len() > 0 && q.err == nil {
227: 		if q.popLocked() != nil {
228: 			break
229: 		}
230: 	}
231: 	q.queue, q.bytes = nil, 0
232: 
233: 	if q.stats.late > 0 || q.stats.forced > 0 {
234: 		log.Debug("Capture wrote packets out of timestamp order",
235: 			"late_packets", q.stats.late, "max_late_by", q.stats.maxLate,
236: 			"window", q.window, "buffer_overflow_packets", q.stats.forced)
237: 	}
238: }
239: 
240: func (q *Reorder) popLocked() error {
241: 	item := heap.Pop(&q.queue).(reorderedPacket) //nolint:forcetypeassert // heap contract
242: 	q.bytes -= len(item.packet.Data)
243: 	q.cursor = max(q.cursor, item.packet.Timestamp)
244: 
245: 	return q.writeLocked(item.id, item.packet)
246: }
247: 
248: func (q *Reorder) writeLocked(id uint32, packet *Packet) error {
249: 	if err := q.write(id, packet); err != nil {
250: 		if q.err == nil {
251: 			q.err = err
252: 			if q.onFail != nil {
253: 				q.onFail()
254: 			}
255: 		}
256: 
257: 		return err
258: 	}
259: 
260: 	return nil
261: }
262: 
263: func resetTimer(timer *time.Timer, d time.Duration) {
264: 	if !timer.Stop() {
265: 		select {
266: 		case <-timer.C:
267: 		default:
268: 		}
269: 	}
270: 	timer.Reset(d)
271: }

(End of file - total 271 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196511fbf00191URbIF2vHiTl2",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196511473001Mcyul0Xt2XB0L4",
  "callID": "call_4a94b2df70d5454aa3bea510",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/capture/reorder.go"
    },
    "output": "<path>/source/head/capture/reorder.go</path>\n<type>file</type>\n<content>\n1: package capture\n2: \n3: import (\n4: \t\"container/heap\"\n5: \t\"context\"\n6: \t\"sync\"\n7: \t\"time\"\n8: \n9: \t\"github.com/charmbracelet/log\"\n10: )\n11: \n12: // maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets\n13: // are written early, which can put them out of order.\n14: const maxReorderBytes = 64 << 20\n15: \n16: // Reorder writes the packets of several capture sources in timestamp order.\n17: //\n18: // Each source (a node's capture stream, or a local interface socket) delivers its packets with\n19: // its own delay. The buffer holds every packet for `window` after it arrived and writes the held\n20: // packets in timestamp order, so a packet that was stamped earlier but delivered up to `window`\n21: // later still goes out first. A packet stamped before the last packet written arrived too late\n22: // to be ordered: it is written as it comes and counted, and the count goes to the debug log when\n23: // the capture ends.\n24: //\n25: // A source can place a hold at the earliest timestamp it may still write (Hold); packets stamped\n26: // after a hold wait for it to be released (Release). The c9s runtime holds while it switches\n27: // between chained capture segments.\n28: type Reorder struct {\n29: \twrite  func(id uint32, packet *Packet) error\n30: \tonFail func()\n31: \twindow time.Duration\n32: \tnow    func() time.Time\n33: \n34: \tmu     sync.Mutex\n35: \tqueue  reorderQueue\n36: \tbytes  int\n37: \tseq    uint64\n38: \tholds  map[any]int64\n39: \terr    error\n40: \twake   chan struct{}\n41: \tstats  reorderStats\n42: \tcursor int64 // timestamp of the latest packet written in order\n43: }\n44: \n45: type reorderStats struct {\n46: \tlate    int\n47: \tmaxLate time.Duration\n48: \tforced  int\n49: }\n50: \n51: // reorderedPacket is a packet waiting in the buffer.\n52: type reorderedPacket struct {\n53: \tid      uint32\n54: \tpacket  *Packet\n55: \tarrived time.Time\n56: \tseq     uint64\n57: }\n58: \n59: // reorderQueue is a min-heap by timestamp, then arrival.\n60: type reorderQueue []reorderedPacket\n61: \n62: func (q reorderQueue) Len() int { return len(q) }\n63: \n64: func (q reorderQueue) Less(i, j int) bool {\n65: \tif q[i].packet.Timestamp != q[j].packet.Timestamp {\n66: \t\treturn q[i].packet.Timestamp < q[j].packet.Timestamp\n67: \t}\n68: \n69: \treturn q[i].seq < q[j].seq\n70: }\n71: \n72: func (q reorderQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }\n73: \n74: func (q *reorderQueue) Push(\n75: \tx any,\n76: ) {\n77: \t*q = append(*q, x.(reorderedPacket))\n78: } //nolint:forcetypeassert // heap contract\n79: \n80: func (q *reorderQueue) Pop() any {\n81: \told := *q\n82: \titem := old[len(old)-1]\n83: \t*q = old[:len(old)-1]\n84: \n85: \treturn item\n86: }\n87: \n88: // NewReorder returns a buffer that writes through write; onFail is called once a write\n89: // failed. A window of zero or less writes every packet as it arrives.\n90: func NewReorder(\n91: \twindow time.Duration,\n92: \twrite func(id uint32, packet *Packet) error,\n93: \tonFail func(),\n94: ) *Reorder {\n95: \treturn &Reorder{\n96: \t\twrite: write, onFail: onFail, window: window, now: time.Now,\n97: \t\tholds: map[any]int64{}, wake: make(chan struct{}, 1),\n98: \t}\n99: }\n100: \n101: // push hands a packet to the buffer. It returns the error of a failed write.\n102: func (q *Reorder) Push(id uint32, packet *Packet) error {\n103: \tq.mu.Lock()\n104: \tdefer q.mu.Unlock()\n105: \n106: \tif q.err != nil {\n107: \t\treturn q.err\n108: \t}\n109: \tif q.window <= 0 {\n110: \t\treturn q.writeLocked(id, packet)\n111: \t}\n112: \tif q.cursor != 0 && packet.Timestamp < q.cursor {\n113: \t\tq.stats.late++\n114: \t\tq.stats.maxLate = max(q.stats.maxLate, time.Duration(q.cursor-packet.Timestamp))\n115: \t\tif q.stats.late == 1 {\n116: \t\t\tlog.Debug(\"Capture packet arrived after the reorder window, writing it out of order\",\n117: \t\t\t\t\"late_by\", time.Duration(q.cursor-packet.Timestamp), \"window\", q.window)\n118: \t\t}\n119: \n120: \t\treturn q.writeLocked(id, packet)\n121: \t}\n122: \n123: \tq.seq++\n124: \theap.Push(&q.queue, reorderedPacket{id: id, packet: packet, arrived: q.now(), seq: q.seq})\n125: \tq.bytes += len(packet.Data)\n126: \tfor q.bytes > maxReorderBytes && q.queue.Len() > 0 {\n127: \t\tq.stats.forced++\n128: \t\tif err := q.popLocked(); err != nil {\n129: \t\t\treturn err\n130: \t\t}\n131: \t}\n132: \n133: \tselect {\n134: \tcase q.wake <- struct{}{}:\n135: \tdefault:\n136: \t}\n137: \n138: \treturn nil\n139: }\n140: \n141: // hold keeps packets stamped after timestamp in the buffer until release(key).\n142: func (q *Reorder) Hold(key any, timestamp int64) {\n143: \tq.mu.Lock()\n144: \tdefer q.mu.Unlock()\n145: \n146: \tq.holds[key] = timestamp\n147: }\n148: \n149: // release removes the hold of key.\n150: func (q *Reorder) Release(key any) {\n151: \tq.mu.Lock()\n152: \t_, held := q.holds[key]\n153: \tdelete(q.holds, key)\n154: \tq.mu.Unlock()\n155: \n156: \tif held {\n157: \t\tselect {\n158: \t\tcase q.wake <- struct{}{}:\n159: \t\tdefault:\n160: \t\t}\n161: \t}\n162: }\n163: \n164: // run writes due packets until ctx ends.\n165: func (q *Reorder) Run(ctx context.Context) {\n166: \tif q.window <= 0 {\n167: \t\treturn\n168: \t}\n169: \n170: \ttimer := time.NewTimer(time.Hour)\n171: \tdefer timer.Stop()\n172: \n173: \tfor {\n174: \t\tnext := q.writeDue()\n175: \t\twait := time.Hour\n176: \t\tif !next.IsZero() {\n177: \t\t\twait = max(next.Sub(q.now()), time.Millisecond)\n178: \t\t}\n179: \t\tresetTimer(timer, wait)\n180: \n181: \t\tselect {\n182: \t\tcase <-ctx.Done():\n183: \t\t\treturn\n184: \t\tcase <-q.wake:\n185: \t\tcase <-timer.C:\n186: \t\t}\n187: \t}\n188: }\n189: \n190: // writeDue writes the packets that waited for the window and are not behind a hold, in\n191: // timestamp order. It returns when the next packet is due, or zero when that depends on a new\n192: // packet or a released hold.\n193: func (q *Reorder) writeDue() time.Time {\n194: \tq.mu.Lock()\n195: \tdefer q.mu.Unlock()\n196: \n197: \theld, limit := false, int64(0)\n198: \tfor _, timestamp := range q.holds {\n199: \t\tif !held || timestamp < limit {\n200: \t\t\theld, limit = true, timestamp\n201: \t\t}\n202: \t}\n203: \n204: \tnow := q.now()\n205: \tfor q.queue.Len() > 0 && q.err == nil {\n206: \t\thead := q.queue[0]\n207: \t\tif held && head.packet.Timestamp > limit {\n208: \t\t\treturn time.Time{}\n209: \t\t}\n210: \t\tif due := head.arrived.Add(q.window); due.After(now) {\n211: \t\t\treturn due\n212: \t\t}\n213: \t\tif q.popLocked() != nil {\n214: \t\t\treturn time.Time{}\n215: \t\t}\n216: \t}\n217: \n218: \treturn time.Time{}\n219: }\n220: \n221: // flush writes every remaining packet in timestamp order and logs what could not be ordered.\n222: func (q *Reorder) Flush() {\n223: \tq.mu.Lock()\n224: \tdefer q.mu.Unlock()\n225: \n226: \tfor q.queue.Len() > 0 && q.err == nil {\n227: \t\tif q.popLocked() != nil {\n228: \t\t\tbreak\n229: \t\t}\n230: \t}\n231: \tq.queue, q.bytes = nil, 0\n232: \n233: \tif q.stats.late > 0 || q.stats.forced > 0 {\n234: \t\tlog.Debug(\"Capture wrote packets out of timestamp order\",\n235: \t\t\t\"late_packets\", q.stats.late, \"max_late_by\", q.stats.maxLate,\n236: \t\t\t\"window\", q.window, \"buffer_overflow_packets\", q.stats.forced)\n237: \t}\n238: }\n239: \n240: func (q *Reorder) popLocked() error {\n241: \titem := heap.Pop(&q.queue).(reorderedPacket) //nolint:forcetypeassert // heap contract\n242: \tq.bytes -= len(item.packet.Data)\n243: \tq.cursor = max(q.cursor, item.packet.Timestamp)\n244: \n245: \treturn q.writeLocked(item.id, item.packet)\n246: }\n247: \n248: func (q *Reorder) writeLocked(id uint32, packet *Packet) error {\n249: \tif err := q.write(id, packet); err != nil {\n250: \t\tif q.err == nil {\n251: \t\t\tq.err = err\n252: \t\t\tif q.onFail != nil {\n253: \t\t\t\tq.onFail()\n254: \t\t\t}\n255: \t\t}\n256: \n257: \t\treturn err\n258: \t}\n259: \n260: \treturn nil\n261: }\n262: \n263: func resetTimer(timer *time.Timer, d time.Duration) {\n264: \tif !timer.Stop() {\n265: \t\tselect {\n266: \t\tcase <-timer.C:\n267: \t\tdefault:\n268: \t\t}\n269: \t}\n270: \ttimer.Reset(d)\n271: }\n\n(End of file - total 271 lines)\n</content>",
    "title": "source/head/capture/reorder.go",
    "metadata": {
      "preview": "package capture\n\nimport (\n\t\"container/heap\"\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n)\n\n// maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets\n// are written early, which can put them out of order.\nconst maxReorderBytes = 64 << 20\n\n// Reorder writes the packets of several capture sources in timestamp order.\n//\n// Each source (a node's capture stream, or a local interface socket) delivers its packets with\n// its own delay. The buffer holds every packet for `window` after it arrived and writes the held\n// packets in timestamp order, so a packet that was stamped earlier but delivered up to `window`",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/capture/reorder.go",
        "text": "package capture\n\nimport (\n\t\"container/heap\"\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n)\n\n// maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets\n// are written early, which can put them out of order.\nconst maxReorderBytes = 64 << 20\n\n// Reorder writes the packets of several capture sources in timestamp order.\n//\n// Each source (a node's capture stream, or a local interface socket) delivers its packets with\n// its own delay. The buffer holds every packet for `window` after it arrived and writes the held\n// packets in timestamp order, so a packet that was stamped earlier but delivered up to `window`\n// later still goes out first. A packet stamped before the last packet written arrived too late\n// to be ordered: it is written as it comes and counted, and the count goes to the debug log when\n// the capture ends.\n//\n// A source can place a hold at the earliest timestamp it may still write (Hold); packets stamped\n// after a hold wait for it to be released (Release). The c9s runtime holds while it switches\n// between chained capture segments.\ntype Reorder struct {\n\twrite  func(id uint32, packet *Packet) error\n\tonFail func()\n\twindow time.Duration\n\tnow    func() time.Time\n\n\tmu     sync.Mutex\n\tqueue  reorderQueue\n\tbytes  int\n\tseq    uint64\n\tholds  map[any]int64\n\terr    error\n\twake   chan struct{}\n\tstats  reorderStats\n\tcursor int64 // timestamp of the latest packet written in order\n}\n\ntype reorderStats struct {\n\tlate    int\n\tmaxLate time.Duration\n\tforced  int\n}\n\n// reorderedPacket is a packet waiting in the buffer.\ntype reorderedPacket struct {\n\tid      uint32\n\tpacket  *Packet\n\tarrived time.Time\n\tseq     uint64\n}\n\n// reorderQueue is a min-heap by timestamp, then arrival.\ntype reorderQueue []reorderedPacket\n\nfunc (q reorderQueue) Len() int { return len(q) }\n\nfunc (q reorderQueue) Less(i, j int) bool {\n\tif q[i].packet.Timestamp != q[j].packet.Timestamp {\n\t\treturn q[i].packet.Timestamp < q[j].packet.Timestamp\n\t}\n\n\treturn q[i].seq < q[j].seq\n}\n\nfunc (q reorderQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }\n\nfunc (q *reorderQueue) Push(\n\tx any,\n) {\n\t*q = append(*q, x.(reorderedPacket))\n} //nolint:forcetypeassert // heap contract\n\nfunc (q *reorderQueue) Pop() any {\n\told := *q\n\titem := old[len(old)-1]\n\t*q = old[:len(old)-1]\n\n\treturn item\n}\n\n// NewReorder returns a buffer that writes through write; onFail is called once a write\n// failed. A window of zero or less writes every packet as it arrives.\nfunc NewReorder(\n\twindow time.Duration,\n\twrite func(id uint32, packet *Packet) error,\n\tonFail func(),\n) *Reorder {\n\treturn &Reorder{\n\t\twrite: write, onFail: onFail, window: window, now: time.Now,\n\t\tholds: map[any]int64{}, wake: make(chan struct{}, 1),\n\t}\n}\n\n// push hands a packet to the buffer. It returns the error of a failed write.\nfunc (q *Reorder) Push(id uint32, packet *Packet) error {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\tif q.err != nil {\n\t\treturn q.err\n\t}\n\tif q.window <= 0 {\n\t\treturn q.writeLocked(id, packet)\n\t}\n\tif q.cursor != 0 && packet.Timestamp < q.cursor {\n\t\tq.stats.late++\n\t\tq.stats.maxLate = max(q.stats.maxLate, time.Duration(q.cursor-packet.Timestamp))\n\t\tif q.stats.late == 1 {\n\t\t\tlog.Debug(\"Capture packet arrived after the reorder window, writing it out of order\",\n\t\t\t\t\"late_by\", time.Duration(q.cursor-packet.Timestamp), \"window\", q.window)\n\t\t}\n\n\t\treturn q.writeLocked(id, packet)\n\t}\n\n\tq.seq++\n\theap.Push(&q.queue, reorderedPacket{id: id, packet: packet, arrived: q.now(), seq: q.seq})\n\tq.bytes += len(packet.Data)\n\tfor q.bytes > maxReorderBytes && q.queue.Len() > 0 {\n\t\tq.stats.forced++\n\t\tif err := q.popLocked(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tselect {\n\tcase q.wake <- struct{}{}:\n\tdefault:\n\t}\n\n\treturn nil\n}\n\n// hold keeps packets stamped after timestamp in the buffer until release(key).\nfunc (q *Reorder) Hold(key any, timestamp int64) {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\tq.holds[key] = timestamp\n}\n\n// release removes the hold of key.\nfunc (q *Reorder) Release(key any) {\n\tq.mu.Lock()\n\t_, held := q.holds[key]\n\tdelete(q.holds, key)\n\tq.mu.Unlock()\n\n\tif held {\n\t\tselect {\n\t\tcase q.wake <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n}\n\n// run writes due packets until ctx ends.\nfunc (q *Reorder) Run(ctx context.Context) {\n\tif q.window <= 0 {\n\t\treturn\n\t}\n\n\ttimer := time.NewTimer(time.Hour)\n\tdefer timer.Stop()\n\n\tfor {\n\t\tnext := q.writeDue()\n\t\twait := time.Hour\n\t\tif !next.IsZero() {\n\t\t\twait = max(next.Sub(q.now()), time.Millisecond)\n\t\t}\n\t\tresetTimer(timer, wait)\n\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-q.wake:\n\t\tcase <-timer.C:\n\t\t}\n\t}\n}\n\n// writeDue writes the packets that waited for the window and are not behind a hold, in\n// timestamp order. It returns when the next packet is due, or zero when that depends on a new\n// packet or a released hold.\nfunc (q *Reorder) writeDue() time.Time {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\theld, limit := false, int64(0)\n\tfor _, timestamp := range q.holds {\n\t\tif !held || timestamp < limit {\n\t\t\theld, limit = true, timestamp\n\t\t}\n\t}\n\n\tnow := q.now()\n\tfor q.queue.Len() > 0 && q.err == nil {\n\t\thead := q.queue[0]\n\t\tif held && head.packet.Timestamp > limit {\n\t\t\treturn time.Time{}\n\t\t}\n\t\tif due := head.arrived.Add(q.window); due.After(now) {\n\t\t\treturn due\n\t\t}\n\t\tif q.popLocked() != nil {\n\t\t\treturn time.Time{}\n\t\t}\n\t}\n\n\treturn time.Time{}\n}\n\n// flush writes every remaining packet in timestamp order and logs what could not be ordered.\nfunc (q *Reorder) Flush() {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\tfor q.queue.Len() > 0 && q.err == nil {\n\t\tif q.popLocked() != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tq.queue, q.bytes = nil, 0\n\n\tif q.stats.late > 0 || q.stats.forced > 0 {\n\t\tlog.Debug(\"Capture wrote packets out of timestamp order\",\n\t\t\t\"late_packets\", q.stats.late, \"max_late_by\", q.stats.maxLate,\n\t\t\t\"window\", q.window, \"buffer_overflow_packets\", q.stats.forced)\n\t}\n}\n\nfunc (q *Reorder) popLocked() error {\n\titem := heap.Pop(&q.queue).(reorderedPacket) //nolint:forcetypeassert // heap contract\n\tq.bytes -= len(item.packet.Data)\n\tq.cursor = max(q.cursor, item.packet.Timestamp)\n\n\treturn q.writeLocked(item.id, item.packet)\n}\n\nfunc (q *Reorder) writeLocked(id uint32, packet *Packet) error {\n\tif err := q.write(id, packet); err != nil {\n\t\tif q.err == nil {\n\t\t\tq.err = err\n\t\t\tif q.onFail != nil {\n\t\t\t\tq.onFail()\n\t\t\t}\n\t\t}\n\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc resetTimer(timer *time.Timer, d time.Duration) {\n\tif !timer.Stop() {\n\t\tselect {\n\t\tcase <-timer.C:\n\t\tdefault:\n\t\t}\n\t}\n\ttimer.Reset(d)\n}",
        "lineStart": 1,
        "lineEnd": 271,
        "totalLines": 271,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523261378,
      "end": 1793523261384
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196511fca001790oFnvEg7261N",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196511473001Mcyul0Xt2XB0L4",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 37195,
    "input": 34284,
    "output": 30,
    "reasoning": 1,
    "cache": {
      "read": 2880,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196511473001Mcyul0Xt2XB0L4",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523258483,
    "completed": 1793523261389
  },
  "parentID": "msg_19650e899001051OTPpm7MOch6",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 37195,
    "input": 34284,
    "output": 30,
    "reasoning": 1,
    "cache": {
      "read": 2880,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 16
step-start
{
  "type": "step-start",
  "id": "prt_1965126e5001idIaKvEjIZJhQl",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196511fd2001AsYcbxyXFxM3HK"
}
read · completed

Input

{
  "filePath": "/source/head/capture/pcapng.go"
}

Output

<path>/source/head/capture/pcapng.go</path>
<type>file</type>
<content>
1: // Package capture writes the pcapng streams of `containerlab capture`: one section with one
2: // interface per capture target, packets merged across targets in timestamp order. The local
3: // capturer reads lab link interfaces of Docker and Podman nodes through packet sockets; the c9s
4: // lab runtime feeds the same writer from clabwire streams.
5: package capture
6: 
7: import (
8: 	"bufio"
9: 	"encoding/binary"
10: 	"errors"
11: 	"fmt"
12: 	"io"
13: 	"math"
14: 	"sync"
15: )
16: 
17: // pcapng block layout (https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html). clabwire
18: // writes little-endian sections, and so does the merged stream containerlab writes.
19: const (
20: 	pcapngSectionHeaderType  = 0x0a0d0d0a
21: 	pcapngInterfaceType      = 0x00000001
22: 	pcapngEnhancedPacketType = 0x00000006
23: 	pcapngByteOrderMagic     = 0x1a2b3c4d
24: 	pcapngOptionEnd          = 0
25: 	pcapngOptionUserAppl     = 4
26: 	pcapngOptionIfName       = 2
27: 	pcapngOptionIfTSResol    = 9
28: 	pcapngLinkTypeEthernet   = 1
29: 	// pcapngNanoseconds is the if_tsresol value for 10^-9 s resolution.
30: 	pcapngNanoseconds = 9
31: 	// pcapngMaxBlockLength bounds a block read from a capture stream: a packet of the largest
32: 	// clabwire snap length (1 MiB) plus framing.
33: 	pcapngMaxBlockLength = 1<<20 + 1024
34: 	// captureUserApplication names the writer in the merged section header.
35: 	captureUserApplication = "containerlab"
36: )
37: 
38: var errPCAPNGByteOrder = errors.New("pcapng section is not little-endian")
39: 
40: // InterfaceDescription is an Interface Description Block.
41: type InterfaceDescription struct {
42: 	LinkType   uint16
43: 	SnapLength uint32
44: 	Name       string
45: 	// TSResol is the raw if_tsresol value; 6 (microseconds) when the block has none.
46: 	TSResol byte
47: }
48: 
49: // Packet is an Enhanced Packet Block with its timestamp in nanoseconds.
50: type Packet struct {
51: 	InterfaceID    uint32
52: 	Timestamp      int64
53: 	OriginalLength uint32
54: 	Data           []byte
55: }
56: 
57: // Reader reads the blocks of a pcapng stream as clabwire writes it: one or more
58: // little-endian sections, each with its Interface Description Blocks before its packets.
59: type Reader struct {
60: 	r          *bufio.Reader
61: 	interfaces []InterfaceDescription
62: 	// sections counts the Section Header Blocks read so far.
63: 	sections int
64: }
65: 
66: // NewReader returns a reader of the pcapng stream r.
67: func NewReader(r io.Reader) *Reader {
68: 	return &Reader{r: bufio.NewReaderSize(r, 64<<10)}
69: }
70: 
71: // Sections returns the number of Section Header Blocks read so far.
72: func (p *Reader) Sections() int {
73: 	return p.sections
74: }
75: 
76: // Event is one block of interest: a new interface or a packet.
77: type Event struct {
78: 	Interface *InterfaceDescription
79: 	Packet    *Packet
80: }
81: 
82: // Next returns the next interface or packet, skipping other block types. It returns io.EOF at
83: // the clean end of the stream, and io.ErrUnexpectedEOF for a stream cut inside a block.
84: func (p *Reader) Next() (Event, error) {
85: 	for {
86: 		var header [8]byte
87: 		if _, err := io.ReadFull(p.r, header[:]); err != nil {
88: 			if errors.Is(err, io.EOF) {
89: 				return Event{}, io.EOF
90: 			}
91: 
92: 			return Event{}, io.ErrUnexpectedEOF
93: 		}
94: 
95: 		blockType := binary.LittleEndian.Uint32(header[0:4])
96: 		length := binary.LittleEndian.Uint32(header[4:8])
97: 		if blockType == pcapngSectionHeaderType {
98: 			// the byte-order magic tells a big-endian section apart before its length is
99: 			// trusted: that length reads byte swapped
100: 			magic, err := p.r.Peek(4)
101: 			if err != nil {
102: 				return Event{}, io.ErrUnexpectedEOF
103: 			}
104: 			if binary.BigEndian.Uint32(magic) == pcapngByteOrderMagic {
105: 				return Event{}, errPCAPNGByteOrder
106: 			}
107: 		}
108: 		if length < 12 || length%4 != 0 || length > pcapngMaxBlockLength {
109: 			return Event{}, fmt.Errorf("invalid pcapng block length %d (at most %d)", length,
110: 				pcapngMaxBlockLength)
111: 		}
112: 
113: 		body := make([]byte, length-8)
114: 		if _, err := io.ReadFull(p.r, body); err != nil {
115: 			return Event{}, io.ErrUnexpectedEOF
116: 		}
117: 		if binary.LittleEndian.Uint32(body[len(body)-4:]) != length {
118: 			return Event{}, fmt.Errorf("pcapng block lengths do not match")
119: 		}
120: 		body = body[:len(body)-4]
121: 
122: 		switch blockType {
123: 		case pcapngSectionHeaderType:
124: 			if len(body) < 16 {
125: 				return Event{}, fmt.Errorf("short pcapng section header")
126: 			}
127: 			if binary.LittleEndian.Uint32(body[0:4]) != pcapngByteOrderMagic {
128: 				return Event{}, errPCAPNGByteOrder
129: 			}
130: 			p.sections++
131: 			p.interfaces = nil
132: 		case pcapngInterfaceType:
133: 			if p.sections == 0 {
134: 				return Event{}, fmt.Errorf("pcapng interface before a section header")
135: 			}
136: 			intf, err := parsePCAPNGInterface(body)
137: 			if err != nil {
138: 				return Event{}, err
139: 			}
140: 			p.interfaces = append(p.interfaces, intf)
141: 
142: 			return Event{Interface: &p.interfaces[len(p.interfaces)-1]}, nil
143: 		case pcapngEnhancedPacketType:
144: 			packet, err := p.parsePacket(body)
145: 			if err != nil {
146: 				return Event{}, err
147: 			}
148: 
149: 			return Event{Packet: &packet}, nil
150: 		}
151: 	}
152: }
153: 
154: func parsePCAPNGInterface(body []byte) (InterfaceDescription, error) {
155: 	if len(body) < 8 {
156: 		return InterfaceDescription{}, fmt.Errorf("short pcapng interface description")
157: 	}
158: 	intf := InterfaceDescription{
159: 		LinkType:   binary.LittleEndian.Uint16(body[0:2]),
160: 		SnapLength: binary.LittleEndian.Uint32(body[4:8]),
161: 		TSResol:    6,
162: 	}
163: 
164: 	options := body[8:]
165: 	for len(options) >= 4 {
166: 		code := binary.LittleEndian.Uint16(options[0:2])
167: 		size := int(binary.LittleEndian.Uint16(options[2:4]))
168: 		if code == pcapngOptionEnd {
169: 			break
170: 		}
171: 		padded := size + pcapngPadding(size)
172: 		if 4+padded > len(options) {
173: 			return InterfaceDescription{}, fmt.Errorf("truncated pcapng interface option")
174: 		}
175: 		value := options[4 : 4+size]
176: 		switch code {
177: 		case pcapngOptionIfName:
178: 			intf.Name = string(value)
179: 		case pcapngOptionIfTSResol:
180: 			if size == 1 {
181: 				intf.TSResol = value[0]
182: 			}
183: 		}
184: 		options = options[4+padded:]
185: 	}
186: 
187: 	return intf, nil
188: }
189: 
190: func (p *Reader) parsePacket(body []byte) (Packet, error) {
191: 	if len(body) < 20 {
192: 		return Packet{}, fmt.Errorf("short pcapng enhanced packet")
193: 	}
194: 	packet := Packet{
195: 		InterfaceID:    binary.LittleEndian.Uint32(body[0:4]),
196: 		OriginalLength: binary.LittleEndian.Uint32(body[16:20]),
197: 	}
198: 	if int(packet.InterfaceID) >= len(p.interfaces) {
199: 		return Packet{}, fmt.Errorf("pcapng packet for undeclared interface %d",
200: 			packet.InterfaceID)
201: 	}
202: 	captured := binary.LittleEndian.Uint32(body[12:16])
203: 	if int(captured) > len(body)-20 {
204: 		return Packet{}, fmt.Errorf("pcapng packet data exceeds its block")
205: 	}
206: 	packet.Data = body[20 : 20+captured]
207: 
208: 	raw := uint64(binary.LittleEndian.Uint32(body[4:8]))<<32 |
209: 		uint64(binary.LittleEndian.Uint32(body[8:12]))
210: 	timestamp, err := pcapngNanosecondsFrom(raw, p.interfaces[packet.InterfaceID].TSResol)
211: 	if err != nil {
212: 		return Packet{}, err
213: 	}
214: 	packet.Timestamp = timestamp
215: 
216: 	return packet, nil
217: }
218: 
219: // pcapngNanosecondsFrom converts a timestamp in an interface's resolution to nanoseconds.
220: // Only decimal resolutions up to nanoseconds occur in clabwire streams.
221: func pcapngNanosecondsFrom(raw uint64, tsresol byte) (int64, error) {
222: 	if tsresol&0x80 != 0 || tsresol > pcapngNanoseconds {
223: 		return 0, fmt.Errorf("unsupported pcapng timestamp resolution %#x", tsresol)
224: 	}
225: 	scale := uint64(1)
226: 	for range pcapngNanoseconds - int(tsresol) {
227: 		scale *= 10
228: 	}
229: 	if raw > math.MaxInt64/scale {
230: 		return 0, fmt.Errorf("pcapng timestamp out of range")
231: 	}
232: 
233: 	return int64(raw * scale), nil //nolint:gosec // bounded above
234: }
235: 
236: // Writer writes one little-endian section with nanosecond timestamps. Every block goes out
237: // in one Write under a lock, so concurrent writers never interleave blocks and a stream cut
238: // between writes is still a valid capture.
239: type Writer struct {
240: 	mu  sync.Mutex
241: 	w   io.Writer
242: 	err error
243: }
244: 
245: // NewWriter returns a writer of one pcapng section to w.
246: func NewWriter(w io.Writer) *Writer {
247: 	return &Writer{w: w}
248: }
249: 
250: // WriteHeader writes the Section Header Block and one Interface Description Block per name, in
251: // order; packets refer to the interfaces by that index.
252: func (p *Writer) WriteHeader(names []string, snapLength uint32) error {
253: 	section := make([]byte, 16)
254: 	binary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)
255: 	binary.LittleEndian.PutUint16(section[4:], 1)
256: 	binary.LittleEndian.PutUint16(section[6:], 0)
257: 	binary.LittleEndian.PutUint64(section[8:], math.MaxUint64)
258: 	section = appendPCAPNGOption(section, pcapngOptionUserAppl, []byte(captureUserApplication))
259: 	section = appendPCAPNGOption(section, pcapngOptionEnd, nil)
260: 
261: 	header := pcapngBlock(pcapngSectionHeaderType, section)
262: 	for _, name := range names {
263: 		description := make([]byte, 8)
264: 		binary.LittleEndian.PutUint16(description[0:], pcapngLinkTypeEthernet)
265: 		binary.LittleEndian.PutUint32(description[4:], snapLength)
266: 		description = appendPCAPNGOption(description, pcapngOptionIfName, []byte(name))
267: 		description = appendPCAPNGOption(description, pcapngOptionIfTSResol,
268: 			[]byte{pcapngNanoseconds})
269: 		description = appendPCAPNGOption(description, pcapngOptionEnd, nil)
270: 		header = append(header, pcapngBlock(pcapngInterfaceType, description)...)
271: 	}
272: 
273: 	return p.write(header)
274: }
275: 
276: // WritePacket writes an Enhanced Packet Block for the interface with the given index.
277: func (p *Writer) WritePacket(interfaceID uint32, packet *Packet) error {
278: 	timestamp := uint64(packet.Timestamp) //nolint:gosec // capture timestamps are positive
279: 	body := make([]byte, 20, 20+len(packet.Data)+3)
280: 	binary.LittleEndian.PutUint32(body[0:], interfaceID)
281: 	binary.LittleEndian.PutUint32(body[4:], uint32(timestamp>>32))
282: 	binary.LittleEndian.PutUint32(body[8:], uint32(timestamp)) //nolint:gosec // low 32 bits
283: 	binary.LittleEndian.PutUint32(body[12:], uint32(len(packet.Data)))
284: 	binary.LittleEndian.PutUint32(body[16:], packet.OriginalLength)
285: 	body = append(body, packet.Data...)
286: 	body = append(body, make([]byte, pcapngPadding(len(packet.Data)))...)
287: 
288: 	return p.write(pcapngBlock(pcapngEnhancedPacketType, body))
289: }
290: 
291: // Err returns the first write error, or nil.
292: func (p *Writer) Err() error {
293: 	p.mu.Lock()
294: 	defer p.mu.Unlock()
295: 
296: 	return p.err
297: }
298: 
299: func (p *Writer) write(block []byte) error {
300: 	p.mu.Lock()
301: 	defer p.mu.Unlock()
302: 
303: 	if p.err != nil {
304: 		return p.err
305: 	}
306: 	if _, err := p.w.Write(block); err != nil {
307: 		p.err = fmt.Errorf("failed to write the capture: %w", err)
308: 	}
309: 
310: 	return p.err
311: }
312: 
313: func pcapngBlock(blockType uint32, body []byte) []byte {
314: 	total := uint32(12 + len(body)) //nolint:gosec // bounded by the snap length
315: 	block := make([]byte, 8, total)
316: 	binary.LittleEndian.PutUint32(block[0:], blockType)
317: 	binary.LittleEndian.PutUint32(block[4:], total)
318: 	block = append(block, body...)
319: 
320: 	return binary.LittleEndian.AppendUint32(block, total)
321: }
322: 
323: func appendPCAPNGOption(body []byte, code uint16, value []byte) []byte {
324: 	body = binary.LittleEndian.AppendUint16(body, code)
325: 	body = binary.LittleEndian.AppendUint16(body, uint16(len(value))) //nolint:gosec // short
326: 	body = append(body, value...)
327: 
328: 	return append(body, make([]byte, pcapngPadding(len(value)))...)
329: }
330: 
331: func pcapngPadding(length int) int {
332: 	return (4 - length%4) % 4
333: }

(End of file - total 333 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196512723001R69qfoJkZcFeir",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196511fd2001AsYcbxyXFxM3HK",
  "callID": "call_f11fb4a69875416b9416e37b",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/capture/pcapng.go"
    },
    "output": "<path>/source/head/capture/pcapng.go</path>\n<type>file</type>\n<content>\n1: // Package capture writes the pcapng streams of `containerlab capture`: one section with one\n2: // interface per capture target, packets merged across targets in timestamp order. The local\n3: // capturer reads lab link interfaces of Docker and Podman nodes through packet sockets; the c9s\n4: // lab runtime feeds the same writer from clabwire streams.\n5: package capture\n6: \n7: import (\n8: \t\"bufio\"\n9: \t\"encoding/binary\"\n10: \t\"errors\"\n11: \t\"fmt\"\n12: \t\"io\"\n13: \t\"math\"\n14: \t\"sync\"\n15: )\n16: \n17: // pcapng block layout (https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html). clabwire\n18: // writes little-endian sections, and so does the merged stream containerlab writes.\n19: const (\n20: \tpcapngSectionHeaderType  = 0x0a0d0d0a\n21: \tpcapngInterfaceType      = 0x00000001\n22: \tpcapngEnhancedPacketType = 0x00000006\n23: \tpcapngByteOrderMagic     = 0x1a2b3c4d\n24: \tpcapngOptionEnd          = 0\n25: \tpcapngOptionUserAppl     = 4\n26: \tpcapngOptionIfName       = 2\n27: \tpcapngOptionIfTSResol    = 9\n28: \tpcapngLinkTypeEthernet   = 1\n29: \t// pcapngNanoseconds is the if_tsresol value for 10^-9 s resolution.\n30: \tpcapngNanoseconds = 9\n31: \t// pcapngMaxBlockLength bounds a block read from a capture stream: a packet of the largest\n32: \t// clabwire snap length (1 MiB) plus framing.\n33: \tpcapngMaxBlockLength = 1<<20 + 1024\n34: \t// captureUserApplication names the writer in the merged section header.\n35: \tcaptureUserApplication = \"containerlab\"\n36: )\n37: \n38: var errPCAPNGByteOrder = errors.New(\"pcapng section is not little-endian\")\n39: \n40: // InterfaceDescription is an Interface Description Block.\n41: type InterfaceDescription struct {\n42: \tLinkType   uint16\n43: \tSnapLength uint32\n44: \tName       string\n45: \t// TSResol is the raw if_tsresol value; 6 (microseconds) when the block has none.\n46: \tTSResol byte\n47: }\n48: \n49: // Packet is an Enhanced Packet Block with its timestamp in nanoseconds.\n50: type Packet struct {\n51: \tInterfaceID    uint32\n52: \tTimestamp      int64\n53: \tOriginalLength uint32\n54: \tData           []byte\n55: }\n56: \n57: // Reader reads the blocks of a pcapng stream as clabwire writes it: one or more\n58: // little-endian sections, each with its Interface Description Blocks before its packets.\n59: type Reader struct {\n60: \tr          *bufio.Reader\n61: \tinterfaces []InterfaceDescription\n62: \t// sections counts the Section Header Blocks read so far.\n63: \tsections int\n64: }\n65: \n66: // NewReader returns a reader of the pcapng stream r.\n67: func NewReader(r io.Reader) *Reader {\n68: \treturn &Reader{r: bufio.NewReaderSize(r, 64<<10)}\n69: }\n70: \n71: // Sections returns the number of Section Header Blocks read so far.\n72: func (p *Reader) Sections() int {\n73: \treturn p.sections\n74: }\n75: \n76: // Event is one block of interest: a new interface or a packet.\n77: type Event struct {\n78: \tInterface *InterfaceDescription\n79: \tPacket    *Packet\n80: }\n81: \n82: // Next returns the next interface or packet, skipping other block types. It returns io.EOF at\n83: // the clean end of the stream, and io.ErrUnexpectedEOF for a stream cut inside a block.\n84: func (p *Reader) Next() (Event, error) {\n85: \tfor {\n86: \t\tvar header [8]byte\n87: \t\tif _, err := io.ReadFull(p.r, header[:]); err != nil {\n88: \t\t\tif errors.Is(err, io.EOF) {\n89: \t\t\t\treturn Event{}, io.EOF\n90: \t\t\t}\n91: \n92: \t\t\treturn Event{}, io.ErrUnexpectedEOF\n93: \t\t}\n94: \n95: \t\tblockType := binary.LittleEndian.Uint32(header[0:4])\n96: \t\tlength := binary.LittleEndian.Uint32(header[4:8])\n97: \t\tif blockType == pcapngSectionHeaderType {\n98: \t\t\t// the byte-order magic tells a big-endian section apart before its length is\n99: \t\t\t// trusted: that length reads byte swapped\n100: \t\t\tmagic, err := p.r.Peek(4)\n101: \t\t\tif err != nil {\n102: \t\t\t\treturn Event{}, io.ErrUnexpectedEOF\n103: \t\t\t}\n104: \t\t\tif binary.BigEndian.Uint32(magic) == pcapngByteOrderMagic {\n105: \t\t\t\treturn Event{}, errPCAPNGByteOrder\n106: \t\t\t}\n107: \t\t}\n108: \t\tif length < 12 || length%4 != 0 || length > pcapngMaxBlockLength {\n109: \t\t\treturn Event{}, fmt.Errorf(\"invalid pcapng block length %d (at most %d)\", length,\n110: \t\t\t\tpcapngMaxBlockLength)\n111: \t\t}\n112: \n113: \t\tbody := make([]byte, length-8)\n114: \t\tif _, err := io.ReadFull(p.r, body); err != nil {\n115: \t\t\treturn Event{}, io.ErrUnexpectedEOF\n116: \t\t}\n117: \t\tif binary.LittleEndian.Uint32(body[len(body)-4:]) != length {\n118: \t\t\treturn Event{}, fmt.Errorf(\"pcapng block lengths do not match\")\n119: \t\t}\n120: \t\tbody = body[:len(body)-4]\n121: \n122: \t\tswitch blockType {\n123: \t\tcase pcapngSectionHeaderType:\n124: \t\t\tif len(body) < 16 {\n125: \t\t\t\treturn Event{}, fmt.Errorf(\"short pcapng section header\")\n126: \t\t\t}\n127: \t\t\tif binary.LittleEndian.Uint32(body[0:4]) != pcapngByteOrderMagic {\n128: \t\t\t\treturn Event{}, errPCAPNGByteOrder\n129: \t\t\t}\n130: \t\t\tp.sections++\n131: \t\t\tp.interfaces = nil\n132: \t\tcase pcapngInterfaceType:\n133: \t\t\tif p.sections == 0 {\n134: \t\t\t\treturn Event{}, fmt.Errorf(\"pcapng interface before a section header\")\n135: \t\t\t}\n136: \t\t\tintf, err := parsePCAPNGInterface(body)\n137: \t\t\tif err != nil {\n138: \t\t\t\treturn Event{}, err\n139: \t\t\t}\n140: \t\t\tp.interfaces = append(p.interfaces, intf)\n141: \n142: \t\t\treturn Event{Interface: &p.interfaces[len(p.interfaces)-1]}, nil\n143: \t\tcase pcapngEnhancedPacketType:\n144: \t\t\tpacket, err := p.parsePacket(body)\n145: \t\t\tif err != nil {\n146: \t\t\t\treturn Event{}, err\n147: \t\t\t}\n148: \n149: \t\t\treturn Event{Packet: &packet}, nil\n150: \t\t}\n151: \t}\n152: }\n153: \n154: func parsePCAPNGInterface(body []byte) (InterfaceDescription, error) {\n155: \tif len(body) < 8 {\n156: \t\treturn InterfaceDescription{}, fmt.Errorf(\"short pcapng interface description\")\n157: \t}\n158: \tintf := InterfaceDescription{\n159: \t\tLinkType:   binary.LittleEndian.Uint16(body[0:2]),\n160: \t\tSnapLength: binary.LittleEndian.Uint32(body[4:8]),\n161: \t\tTSResol:    6,\n162: \t}\n163: \n164: \toptions := body[8:]\n165: \tfor len(options) >= 4 {\n166: \t\tcode := binary.LittleEndian.Uint16(options[0:2])\n167: \t\tsize := int(binary.LittleEndian.Uint16(options[2:4]))\n168: \t\tif code == pcapngOptionEnd {\n169: \t\t\tbreak\n170: \t\t}\n171: \t\tpadded := size + pcapngPadding(size)\n172: \t\tif 4+padded > len(options) {\n173: \t\t\treturn InterfaceDescription{}, fmt.Errorf(\"truncated pcapng interface option\")\n174: \t\t}\n175: \t\tvalue := options[4 : 4+size]\n176: \t\tswitch code {\n177: \t\tcase pcapngOptionIfName:\n178: \t\t\tintf.Name = string(value)\n179: \t\tcase pcapngOptionIfTSResol:\n180: \t\t\tif size == 1 {\n181: \t\t\t\tintf.TSResol = value[0]\n182: \t\t\t}\n183: \t\t}\n184: \t\toptions = options[4+padded:]\n185: \t}\n186: \n187: \treturn intf, nil\n188: }\n189: \n190: func (p *Reader) parsePacket(body []byte) (Packet, error) {\n191: \tif len(body) < 20 {\n192: \t\treturn Packet{}, fmt.Errorf(\"short pcapng enhanced packet\")\n193: \t}\n194: \tpacket := Packet{\n195: \t\tInterfaceID:    binary.LittleEndian.Uint32(body[0:4]),\n196: \t\tOriginalLength: binary.LittleEndian.Uint32(body[16:20]),\n197: \t}\n198: \tif int(packet.InterfaceID) >= len(p.interfaces) {\n199: \t\treturn Packet{}, fmt.Errorf(\"pcapng packet for undeclared interface %d\",\n200: \t\t\tpacket.InterfaceID)\n201: \t}\n202: \tcaptured := binary.LittleEndian.Uint32(body[12:16])\n203: \tif int(captured) > len(body)-20 {\n204: \t\treturn Packet{}, fmt.Errorf(\"pcapng packet data exceeds its block\")\n205: \t}\n206: \tpacket.Data = body[20 : 20+captured]\n207: \n208: \traw := uint64(binary.LittleEndian.Uint32(body[4:8]))<<32 |\n209: \t\tuint64(binary.LittleEndian.Uint32(body[8:12]))\n210: \ttimestamp, err := pcapngNanosecondsFrom(raw, p.interfaces[packet.InterfaceID].TSResol)\n211: \tif err != nil {\n212: \t\treturn Packet{}, err\n213: \t}\n214: \tpacket.Timestamp = timestamp\n215: \n216: \treturn packet, nil\n217: }\n218: \n219: // pcapngNanosecondsFrom converts a timestamp in an interface's resolution to nanoseconds.\n220: // Only decimal resolutions up to nanoseconds occur in clabwire streams.\n221: func pcapngNanosecondsFrom(raw uint64, tsresol byte) (int64, error) {\n222: \tif tsresol&0x80 != 0 || tsresol > pcapngNanoseconds {\n223: \t\treturn 0, fmt.Errorf(\"unsupported pcapng timestamp resolution %#x\", tsresol)\n224: \t}\n225: \tscale := uint64(1)\n226: \tfor range pcapngNanoseconds - int(tsresol) {\n227: \t\tscale *= 10\n228: \t}\n229: \tif raw > math.MaxInt64/scale {\n230: \t\treturn 0, fmt.Errorf(\"pcapng timestamp out of range\")\n231: \t}\n232: \n233: \treturn int64(raw * scale), nil //nolint:gosec // bounded above\n234: }\n235: \n236: // Writer writes one little-endian section with nanosecond timestamps. Every block goes out\n237: // in one Write under a lock, so concurrent writers never interleave blocks and a stream cut\n238: // between writes is still a valid capture.\n239: type Writer struct {\n240: \tmu  sync.Mutex\n241: \tw   io.Writer\n242: \terr error\n243: }\n244: \n245: // NewWriter returns a writer of one pcapng section to w.\n246: func NewWriter(w io.Writer) *Writer {\n247: \treturn &Writer{w: w}\n248: }\n249: \n250: // WriteHeader writes the Section Header Block and one Interface Description Block per name, in\n251: // order; packets refer to the interfaces by that index.\n252: func (p *Writer) WriteHeader(names []string, snapLength uint32) error {\n253: \tsection := make([]byte, 16)\n254: \tbinary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)\n255: \tbinary.LittleEndian.PutUint16(section[4:], 1)\n256: \tbinary.LittleEndian.PutUint16(section[6:], 0)\n257: \tbinary.LittleEndian.PutUint64(section[8:], math.MaxUint64)\n258: \tsection = appendPCAPNGOption(section, pcapngOptionUserAppl, []byte(captureUserApplication))\n259: \tsection = appendPCAPNGOption(section, pcapngOptionEnd, nil)\n260: \n261: \theader := pcapngBlock(pcapngSectionHeaderType, section)\n262: \tfor _, name := range names {\n263: \t\tdescription := make([]byte, 8)\n264: \t\tbinary.LittleEndian.PutUint16(description[0:], pcapngLinkTypeEthernet)\n265: \t\tbinary.LittleEndian.PutUint32(description[4:], snapLength)\n266: \t\tdescription = appendPCAPNGOption(description, pcapngOptionIfName, []byte(name))\n267: \t\tdescription = appendPCAPNGOption(description, pcapngOptionIfTSResol,\n268: \t\t\t[]byte{pcapngNanoseconds})\n269: \t\tdescription = appendPCAPNGOption(description, pcapngOptionEnd, nil)\n270: \t\theader = append(header, pcapngBlock(pcapngInterfaceType, description)...)\n271: \t}\n272: \n273: \treturn p.write(header)\n274: }\n275: \n276: // WritePacket writes an Enhanced Packet Block for the interface with the given index.\n277: func (p *Writer) WritePacket(interfaceID uint32, packet *Packet) error {\n278: \ttimestamp := uint64(packet.Timestamp) //nolint:gosec // capture timestamps are positive\n279: \tbody := make([]byte, 20, 20+len(packet.Data)+3)\n280: \tbinary.LittleEndian.PutUint32(body[0:], interfaceID)\n281: \tbinary.LittleEndian.PutUint32(body[4:], uint32(timestamp>>32))\n282: \tbinary.LittleEndian.PutUint32(body[8:], uint32(timestamp)) //nolint:gosec // low 32 bits\n283: \tbinary.LittleEndian.PutUint32(body[12:], uint32(len(packet.Data)))\n284: \tbinary.LittleEndian.PutUint32(body[16:], packet.OriginalLength)\n285: \tbody = append(body, packet.Data...)\n286: \tbody = append(body, make([]byte, pcapngPadding(len(packet.Data)))...)\n287: \n288: \treturn p.write(pcapngBlock(pcapngEnhancedPacketType, body))\n289: }\n290: \n291: // Err returns the first write error, or nil.\n292: func (p *Writer) Err() error {\n293: \tp.mu.Lock()\n294: \tdefer p.mu.Unlock()\n295: \n296: \treturn p.err\n297: }\n298: \n299: func (p *Writer) write(block []byte) error {\n300: \tp.mu.Lock()\n301: \tdefer p.mu.Unlock()\n302: \n303: \tif p.err != nil {\n304: \t\treturn p.err\n305: \t}\n306: \tif _, err := p.w.Write(block); err != nil {\n307: \t\tp.err = fmt.Errorf(\"failed to write the capture: %w\", err)\n308: \t}\n309: \n310: \treturn p.err\n311: }\n312: \n313: func pcapngBlock(blockType uint32, body []byte) []byte {\n314: \ttotal := uint32(12 + len(body)) //nolint:gosec // bounded by the snap length\n315: \tblock := make([]byte, 8, total)\n316: \tbinary.LittleEndian.PutUint32(block[0:], blockType)\n317: \tbinary.LittleEndian.PutUint32(block[4:], total)\n318: \tblock = append(block, body...)\n319: \n320: \treturn binary.LittleEndian.AppendUint32(block, total)\n321: }\n322: \n323: func appendPCAPNGOption(body []byte, code uint16, value []byte) []byte {\n324: \tbody = binary.LittleEndian.AppendUint16(body, code)\n325: \tbody = binary.LittleEndian.AppendUint16(body, uint16(len(value))) //nolint:gosec // short\n326: \tbody = append(body, value...)\n327: \n328: \treturn append(body, make([]byte, pcapngPadding(len(value)))...)\n329: }\n330: \n331: func pcapngPadding(length int) int {\n332: \treturn (4 - length%4) % 4\n333: }\n\n(End of file - total 333 lines)\n</content>",
    "title": "source/head/capture/pcapng.go",
    "metadata": {
      "preview": "// Package capture writes the pcapng streams of `containerlab capture`: one section with one\n// interface per capture target, packets merged across targets in timestamp order. The local\n// capturer reads lab link interfaces of Docker and Podman nodes through packet sockets; the c9s\n// lab runtime feeds the same writer from clabwire streams.\npackage capture\n\nimport (\n\t\"bufio\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"sync\"\n)\n\n// pcapng block layout (https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html). clabwire\n// writes little-endian sections, and so does the merged stream containerlab writes.\nconst (\n\tpcapngSectionHeaderType  = 0x0a0d0d0a",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/capture/pcapng.go",
        "text": "// Package capture writes the pcapng streams of `containerlab capture`: one section with one\n// interface per capture target, packets merged across targets in timestamp order. The local\n// capturer reads lab link interfaces of Docker and Podman nodes through packet sockets; the c9s\n// lab runtime feeds the same writer from clabwire streams.\npackage capture\n\nimport (\n\t\"bufio\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"sync\"\n)\n\n// pcapng block layout (https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html). clabwire\n// writes little-endian sections, and so does the merged stream containerlab writes.\nconst (\n\tpcapngSectionHeaderType  = 0x0a0d0d0a\n\tpcapngInterfaceType      = 0x00000001\n\tpcapngEnhancedPacketType = 0x00000006\n\tpcapngByteOrderMagic     = 0x1a2b3c4d\n\tpcapngOptionEnd          = 0\n\tpcapngOptionUserAppl     = 4\n\tpcapngOptionIfName       = 2\n\tpcapngOptionIfTSResol    = 9\n\tpcapngLinkTypeEthernet   = 1\n\t// pcapngNanoseconds is the if_tsresol value for 10^-9 s resolution.\n\tpcapngNanoseconds = 9\n\t// pcapngMaxBlockLength bounds a block read from a capture stream: a packet of the largest\n\t// clabwire snap length (1 MiB) plus framing.\n\tpcapngMaxBlockLength = 1<<20 + 1024\n\t// captureUserApplication names the writer in the merged section header.\n\tcaptureUserApplication = \"containerlab\"\n)\n\nvar errPCAPNGByteOrder = errors.New(\"pcapng section is not little-endian\")\n\n// InterfaceDescription is an Interface Description Block.\ntype InterfaceDescription struct {\n\tLinkType   uint16\n\tSnapLength uint32\n\tName       string\n\t// TSResol is the raw if_tsresol value; 6 (microseconds) when the block has none.\n\tTSResol byte\n}\n\n// Packet is an Enhanced Packet Block with its timestamp in nanoseconds.\ntype Packet struct {\n\tInterfaceID    uint32\n\tTimestamp      int64\n\tOriginalLength uint32\n\tData           []byte\n}\n\n// Reader reads the blocks of a pcapng stream as clabwire writes it: one or more\n// little-endian sections, each with its Interface Description Blocks before its packets.\ntype Reader struct {\n\tr          *bufio.Reader\n\tinterfaces []InterfaceDescription\n\t// sections counts the Section Header Blocks read so far.\n\tsections int\n}\n\n// NewReader returns a reader of the pcapng stream r.\nfunc NewReader(r io.Reader) *Reader {\n\treturn &Reader{r: bufio.NewReaderSize(r, 64<<10)}\n}\n\n// Sections returns the number of Section Header Blocks read so far.\nfunc (p *Reader) Sections() int {\n\treturn p.sections\n}\n\n// Event is one block of interest: a new interface or a packet.\ntype Event struct {\n\tInterface *InterfaceDescription\n\tPacket    *Packet\n}\n\n// Next returns the next interface or packet, skipping other block types. It returns io.EOF at\n// the clean end of the stream, and io.ErrUnexpectedEOF for a stream cut inside a block.\nfunc (p *Reader) Next() (Event, error) {\n\tfor {\n\t\tvar header [8]byte\n\t\tif _, err := io.ReadFull(p.r, header[:]); err != nil {\n\t\t\tif errors.Is(err, io.EOF) {\n\t\t\t\treturn Event{}, io.EOF\n\t\t\t}\n\n\t\t\treturn Event{}, io.ErrUnexpectedEOF\n\t\t}\n\n\t\tblockType := binary.LittleEndian.Uint32(header[0:4])\n\t\tlength := binary.LittleEndian.Uint32(header[4:8])\n\t\tif blockType == pcapngSectionHeaderType {\n\t\t\t// the byte-order magic tells a big-endian section apart before its length is\n\t\t\t// trusted: that length reads byte swapped\n\t\t\tmagic, err := p.r.Peek(4)\n\t\t\tif err != nil {\n\t\t\t\treturn Event{}, io.ErrUnexpectedEOF\n\t\t\t}\n\t\t\tif binary.BigEndian.Uint32(magic) == pcapngByteOrderMagic {\n\t\t\t\treturn Event{}, errPCAPNGByteOrder\n\t\t\t}\n\t\t}\n\t\tif length < 12 || length%4 != 0 || length > pcapngMaxBlockLength {\n\t\t\treturn Event{}, fmt.Errorf(\"invalid pcapng block length %d (at most %d)\", length,\n\t\t\t\tpcapngMaxBlockLength)\n\t\t}\n\n\t\tbody := make([]byte, length-8)\n\t\tif _, err := io.ReadFull(p.r, body); err != nil {\n\t\t\treturn Event{}, io.ErrUnexpectedEOF\n\t\t}\n\t\tif binary.LittleEndian.Uint32(body[len(body)-4:]) != length {\n\t\t\treturn Event{}, fmt.Errorf(\"pcapng block lengths do not match\")\n\t\t}\n\t\tbody = body[:len(body)-4]\n\n\t\tswitch blockType {\n\t\tcase pcapngSectionHeaderType:\n\t\t\tif len(body) < 16 {\n\t\t\t\treturn Event{}, fmt.Errorf(\"short pcapng section header\")\n\t\t\t}\n\t\t\tif binary.LittleEndian.Uint32(body[0:4]) != pcapngByteOrderMagic {\n\t\t\t\treturn Event{}, errPCAPNGByteOrder\n\t\t\t}\n\t\t\tp.sections++\n\t\t\tp.interfaces = nil\n\t\tcase pcapngInterfaceType:\n\t\t\tif p.sections == 0 {\n\t\t\t\treturn Event{}, fmt.Errorf(\"pcapng interface before a section header\")\n\t\t\t}\n\t\t\tintf, err := parsePCAPNGInterface(body)\n\t\t\tif err != nil {\n\t\t\t\treturn Event{}, err\n\t\t\t}\n\t\t\tp.interfaces = append(p.interfaces, intf)\n\n\t\t\treturn Event{Interface: &p.interfaces[len(p.interfaces)-1]}, nil\n\t\tcase pcapngEnhancedPacketType:\n\t\t\tpacket, err := p.parsePacket(body)\n\t\t\tif err != nil {\n\t\t\t\treturn Event{}, err\n\t\t\t}\n\n\t\t\treturn Event{Packet: &packet}, nil\n\t\t}\n\t}\n}\n\nfunc parsePCAPNGInterface(body []byte) (InterfaceDescription, error) {\n\tif len(body) < 8 {\n\t\treturn InterfaceDescription{}, fmt.Errorf(\"short pcapng interface description\")\n\t}\n\tintf := InterfaceDescription{\n\t\tLinkType:   binary.LittleEndian.Uint16(body[0:2]),\n\t\tSnapLength: binary.LittleEndian.Uint32(body[4:8]),\n\t\tTSResol:    6,\n\t}\n\n\toptions := body[8:]\n\tfor len(options) >= 4 {\n\t\tcode := binary.LittleEndian.Uint16(options[0:2])\n\t\tsize := int(binary.LittleEndian.Uint16(options[2:4]))\n\t\tif code == pcapngOptionEnd {\n\t\t\tbreak\n\t\t}\n\t\tpadded := size + pcapngPadding(size)\n\t\tif 4+padded > len(options) {\n\t\t\treturn InterfaceDescription{}, fmt.Errorf(\"truncated pcapng interface option\")\n\t\t}\n\t\tvalue := options[4 : 4+size]\n\t\tswitch code {\n\t\tcase pcapngOptionIfName:\n\t\t\tintf.Name = string(value)\n\t\tcase pcapngOptionIfTSResol:\n\t\t\tif size == 1 {\n\t\t\t\tintf.TSResol = value[0]\n\t\t\t}\n\t\t}\n\t\toptions = options[4+padded:]\n\t}\n\n\treturn intf, nil\n}\n\nfunc (p *Reader) parsePacket(body []byte) (Packet, error) {\n\tif len(body) < 20 {\n\t\treturn Packet{}, fmt.Errorf(\"short pcapng enhanced packet\")\n\t}\n\tpacket := Packet{\n\t\tInterfaceID:    binary.LittleEndian.Uint32(body[0:4]),\n\t\tOriginalLength: binary.LittleEndian.Uint32(body[16:20]),\n\t}\n\tif int(packet.InterfaceID) >= len(p.interfaces) {\n\t\treturn Packet{}, fmt.Errorf(\"pcapng packet for undeclared interface %d\",\n\t\t\tpacket.InterfaceID)\n\t}\n\tcaptured := binary.LittleEndian.Uint32(body[12:16])\n\tif int(captured) > len(body)-20 {\n\t\treturn Packet{}, fmt.Errorf(\"pcapng packet data exceeds its block\")\n\t}\n\tpacket.Data = body[20 : 20+captured]\n\n\traw := uint64(binary.LittleEndian.Uint32(body[4:8]))<<32 |\n\t\tuint64(binary.LittleEndian.Uint32(body[8:12]))\n\ttimestamp, err := pcapngNanosecondsFrom(raw, p.interfaces[packet.InterfaceID].TSResol)\n\tif err != nil {\n\t\treturn Packet{}, err\n\t}\n\tpacket.Timestamp = timestamp\n\n\treturn packet, nil\n}\n\n// pcapngNanosecondsFrom converts a timestamp in an interface's resolution to nanoseconds.\n// Only decimal resolutions up to nanoseconds occur in clabwire streams.\nfunc pcapngNanosecondsFrom(raw uint64, tsresol byte) (int64, error) {\n\tif tsresol&0x80 != 0 || tsresol > pcapngNanoseconds {\n\t\treturn 0, fmt.Errorf(\"unsupported pcapng timestamp resolution %#x\", tsresol)\n\t}\n\tscale := uint64(1)\n\tfor range pcapngNanoseconds - int(tsresol) {\n\t\tscale *= 10\n\t}\n\tif raw > math.MaxInt64/scale {\n\t\treturn 0, fmt.Errorf(\"pcapng timestamp out of range\")\n\t}\n\n\treturn int64(raw * scale), nil //nolint:gosec // bounded above\n}\n\n// Writer writes one little-endian section with nanosecond timestamps. Every block goes out\n// in one Write under a lock, so concurrent writers never interleave blocks and a stream cut\n// between writes is still a valid capture.\ntype Writer struct {\n\tmu  sync.Mutex\n\tw   io.Writer\n\terr error\n}\n\n// NewWriter returns a writer of one pcapng section to w.\nfunc NewWriter(w io.Writer) *Writer {\n\treturn &Writer{w: w}\n}\n\n// WriteHeader writes the Section Header Block and one Interface Description Block per name, in\n// order; packets refer to the interfaces by that index.\nfunc (p *Writer) WriteHeader(names []string, snapLength uint32) error {\n\tsection := make([]byte, 16)\n\tbinary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)\n\tbinary.LittleEndian.PutUint16(section[4:], 1)\n\tbinary.LittleEndian.PutUint16(section[6:], 0)\n\tbinary.LittleEndian.PutUint64(section[8:], math.MaxUint64)\n\tsection = appendPCAPNGOption(section, pcapngOptionUserAppl, []byte(captureUserApplication))\n\tsection = appendPCAPNGOption(section, pcapngOptionEnd, nil)\n\n\theader := pcapngBlock(pcapngSectionHeaderType, section)\n\tfor _, name := range names {\n\t\tdescription := make([]byte, 8)\n\t\tbinary.LittleEndian.PutUint16(description[0:], pcapngLinkTypeEthernet)\n\t\tbinary.LittleEndian.PutUint32(description[4:], snapLength)\n\t\tdescription = appendPCAPNGOption(description, pcapngOptionIfName, []byte(name))\n\t\tdescription = appendPCAPNGOption(description, pcapngOptionIfTSResol,\n\t\t\t[]byte{pcapngNanoseconds})\n\t\tdescription = appendPCAPNGOption(description, pcapngOptionEnd, nil)\n\t\theader = append(header, pcapngBlock(pcapngInterfaceType, description)...)\n\t}\n\n\treturn p.write(header)\n}\n\n// WritePacket writes an Enhanced Packet Block for the interface with the given index.\nfunc (p *Writer) WritePacket(interfaceID uint32, packet *Packet) error {\n\ttimestamp := uint64(packet.Timestamp) //nolint:gosec // capture timestamps are positive\n\tbody := make([]byte, 20, 20+len(packet.Data)+3)\n\tbinary.LittleEndian.PutUint32(body[0:], interfaceID)\n\tbinary.LittleEndian.PutUint32(body[4:], uint32(timestamp>>32))\n\tbinary.LittleEndian.PutUint32(body[8:], uint32(timestamp)) //nolint:gosec // low 32 bits\n\tbinary.LittleEndian.PutUint32(body[12:], uint32(len(packet.Data)))\n\tbinary.LittleEndian.PutUint32(body[16:], packet.OriginalLength)\n\tbody = append(body, packet.Data...)\n\tbody = append(body, make([]byte, pcapngPadding(len(packet.Data)))...)\n\n\treturn p.write(pcapngBlock(pcapngEnhancedPacketType, body))\n}\n\n// Err returns the first write error, or nil.\nfunc (p *Writer) Err() error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\treturn p.err\n}\n\nfunc (p *Writer) write(block []byte) error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\tif p.err != nil {\n\t\treturn p.err\n\t}\n\tif _, err := p.w.Write(block); err != nil {\n\t\tp.err = fmt.Errorf(\"failed to write the capture: %w\", err)\n\t}\n\n\treturn p.err\n}\n\nfunc pcapngBlock(blockType uint32, body []byte) []byte {\n\ttotal := uint32(12 + len(body)) //nolint:gosec // bounded by the snap length\n\tblock := make([]byte, 8, total)\n\tbinary.LittleEndian.PutUint32(block[0:], blockType)\n\tbinary.LittleEndian.PutUint32(block[4:], total)\n\tblock = append(block, body...)\n\n\treturn binary.LittleEndian.AppendUint32(block, total)\n}\n\nfunc appendPCAPNGOption(body []byte, code uint16, value []byte) []byte {\n\tbody = binary.LittleEndian.AppendUint16(body, code)\n\tbody = binary.LittleEndian.AppendUint16(body, uint16(len(value))) //nolint:gosec // short\n\tbody = append(body, value...)\n\n\treturn append(body, make([]byte, pcapngPadding(len(value)))...)\n}\n\nfunc pcapngPadding(length int) int {\n\treturn (4 - length%4) % 4\n}",
        "lineStart": 1,
        "lineEnd": 333,
        "totalLines": 333,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523263271,
      "end": 1793523263277
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/capture/output.go"
}

Output

<path>/source/head/capture/output.go</path>
<type>file</type>
<content>
1: package capture
2: 
3: import (
4: 	"context"
5: 	"fmt"
6: 	"io"
7: 	"strings"
8: 	"sync/atomic"
9: 	"time"
10: 
11: 	"github.com/charmbracelet/log"
12: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
13: )
14: 
15: // Snap length bounds of a capture.
16: const (
17: 	// DefaultSnapLength is the snap length of a request without one.
18: 	DefaultSnapLength = 256 << 10
19: 	MinSnapLength     = 64
20: 	MaxSnapLength     = 1 << 20
21: )
22: 
23: // ValidateRequest checks the bounds of a capture request and fills the default snap length.
24: func ValidateRequest(req *clablabruntime.CaptureRequest) error {
25: 	if req.Name == "" {
26: 		return fmt.Errorf("topology name is required")
27: 	}
28: 	if len(req.Targets) == 0 {
29: 		return fmt.Errorf("at least one capture target (node and interface) is required")
30: 	}
31: 	for _, target := range req.Targets {
32: 		if target.Node == "" || target.Interface == "" {
33: 			return fmt.Errorf("capture target %+v needs a node and an interface", target)
34: 		}
35: 	}
36: 	if req.Duration < 0 {
37: 		return fmt.Errorf("capture duration must not be negative")
38: 	}
39: 	if req.PacketLimit < 0 {
40: 		return fmt.Errorf("capture packet limit must not be negative")
41: 	}
42: 	if req.SnapLength == 0 {
43: 		req.SnapLength = DefaultSnapLength
44: 	}
45: 	if req.SnapLength < MinSnapLength || req.SnapLength > MaxSnapLength {
46: 		return fmt.Errorf("capture snap length %d is outside %d to %d bytes", req.SnapLength,
47: 			MinSnapLength, MaxSnapLength)
48: 	}
49: 
50: 	return nil
51: }
52: 
53: // FindInterface matches a requested interface by its name, then by its alias.
54: func FindInterface(
55: 	entries []clablabruntime.CaptureInterface,
56: 	name string,
57: ) (clablabruntime.CaptureInterface, bool) {
58: 	for _, entry := range entries {
59: 		if entry.Interface == name {
60: 			return entry, true
61: 		}
62: 	}
63: 	for _, entry := range entries {
64: 		if entry.Alias != "" && entry.Alias == name {
65: 			return entry, true
66: 		}
67: 	}
68: 
69: 	return clablabruntime.CaptureInterface{}, false
70: }
71: 
72: // DescribeInterfaces lists interfaces for an error message: name (alias), ...
73: func DescribeInterfaces(entries []clablabruntime.CaptureInterface) string {
74: 	if len(entries) == 0 {
75: 		return "none"
76: 	}
77: 
78: 	names := make([]string, 0, len(entries))
79: 	for _, entry := range entries {
80: 		name := entry.Interface
81: 		if entry.Alias != "" {
82: 			name += " (" + entry.Alias + ")"
83: 		}
84: 		names = append(names, name)
85: 	}
86: 
87: 	return strings.Join(names, ", ")
88: }
89: 
90: // ReportGap hands a gap to onGap, or logs it as a warning when onGap is nil.
91: func ReportGap(onGap func(clablabruntime.CaptureGap), gap clablabruntime.CaptureGap) {
92: 	if onGap != nil {
93: 		onGap(gap)
94: 		return
95: 	}
96: 
97: 	to := "unknown"
98: 	if !gap.To.IsZero() {
99: 		to = gap.To.Format(time.RFC3339Nano)
100: 	}
101: 	log.Warn("Capture has a gap", "node", gap.Node, "interfaces", strings.Join(gap.Interfaces, ","),
102: 		"from", gap.From.Format(time.RFC3339Nano), "to", to, "reason", gap.Reason)
103: }
104: 
105: // Output is the merged pcapng stream of one capture: the section header with one interface per
106: // capture target, then the packets of every target in timestamp order (through a Reorder), up
107: // to an optional packet limit.
108: type Output struct {
109: 	writer  *Writer
110: 	reorder *Reorder
111: 	limit   int64
112: 	written atomic.Int64
113: 	stop    func()
114: 
115: 	cancelRun context.CancelFunc
116: 	runDone   chan struct{}
117: }
118: 
119: // NewOutput writes the section header and one Interface Description Block per name to w, then
120: // starts the reorder buffer with the given window (zero or less writes packets as they come).
121: // stop is called once the packet limit is reached or a write failed. Close must be called.
122: func NewOutput(
123: 	w io.Writer,
124: 	names []string,
125: 	snapLength, packetLimit int,
126: 	window time.Duration,
127: 	stop func(),
128: ) (*Output, error) {
129: 	writer := NewWriter(w)
130: 	if err := writer.WriteHeader(
131: 		names,
132: 		uint32(snapLength),
133: 	); err != nil { //nolint:gosec // validated
134: 		return nil, err
135: 	}
136: 
137: 	out := &Output{
138: 		writer:  writer,
139: 		reorder: NewReorder(window, writer.WritePacket, stop),
140: 		limit:   int64(packetLimit),
141: 		stop:    stop,
142: 		runDone: make(chan struct{}),
143: 	}
144: 
145: 	var runCtx context.Context
146: 	runCtx, out.cancelRun = context.WithCancel(context.Background())
147: 	go func() {
148: 		defer close(out.runDone)
149: 		out.reorder.Run(runCtx)
150: 	}()
151: 
152: 	return out, nil
153: }
154: 
155: // Emit hands a packet of the interface with the given index to the stream. It reports false
156: // once the packet limit is reached and the capture stops, and returns the error of a failed
157: // write.
158: func (o *Output) Emit(id uint32, packet *Packet) (bool, error) {
159: 	if o.limit > 0 {
160: 		count := o.written.Add(1)
161: 		if count > o.limit {
162: 			o.stop()
163: 			return false, nil
164: 		}
165: 		if err := o.reorder.Push(id, packet); err != nil {
166: 			return false, err
167: 		}
168: 		if count == o.limit {
169: 			o.stop()
170: 			return false, nil
171: 		}
172: 
173: 		return true, nil
174: 	}
175: 
176: 	o.written.Add(1)
177: 
178: 	return true, o.reorder.Push(id, packet)
179: }
180: 
181: // Written returns the number of packets handed to the stream so far.
182: func (o *Output) Written() int64 {
183: 	return o.written.Load()
184: }
185: 
186: // Hold keeps packets stamped after timestamp back until Release(key).
187: func (o *Output) Hold(key any, timestamp int64) {
188: 	o.reorder.Hold(key, timestamp)
189: }
190: 
191: // Release removes the hold of key.
192: func (o *Output) Release(key any) {
193: 	o.reorder.Release(key)
194: }
195: 
196: // Close writes the packets still held back and returns the first write error.
197: func (o *Output) Close() error {
198: 	o.cancelRun()
199: 	<-o.runDone
200: 	o.reorder.Flush()
201: 
202: 	return o.writer.Err()
203: }

(End of file - total 203 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196512750001LzaRHygnxafDGs",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196511fd2001AsYcbxyXFxM3HK",
  "callID": "call_992eee12df8f4f13a4a45bba",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/capture/output.go"
    },
    "output": "<path>/source/head/capture/output.go</path>\n<type>file</type>\n<content>\n1: package capture\n2: \n3: import (\n4: \t\"context\"\n5: \t\"fmt\"\n6: \t\"io\"\n7: \t\"strings\"\n8: \t\"sync/atomic\"\n9: \t\"time\"\n10: \n11: \t\"github.com/charmbracelet/log\"\n12: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n13: )\n14: \n15: // Snap length bounds of a capture.\n16: const (\n17: \t// DefaultSnapLength is the snap length of a request without one.\n18: \tDefaultSnapLength = 256 << 10\n19: \tMinSnapLength     = 64\n20: \tMaxSnapLength     = 1 << 20\n21: )\n22: \n23: // ValidateRequest checks the bounds of a capture request and fills the default snap length.\n24: func ValidateRequest(req *clablabruntime.CaptureRequest) error {\n25: \tif req.Name == \"\" {\n26: \t\treturn fmt.Errorf(\"topology name is required\")\n27: \t}\n28: \tif len(req.Targets) == 0 {\n29: \t\treturn fmt.Errorf(\"at least one capture target (node and interface) is required\")\n30: \t}\n31: \tfor _, target := range req.Targets {\n32: \t\tif target.Node == \"\" || target.Interface == \"\" {\n33: \t\t\treturn fmt.Errorf(\"capture target %+v needs a node and an interface\", target)\n34: \t\t}\n35: \t}\n36: \tif req.Duration < 0 {\n37: \t\treturn fmt.Errorf(\"capture duration must not be negative\")\n38: \t}\n39: \tif req.PacketLimit < 0 {\n40: \t\treturn fmt.Errorf(\"capture packet limit must not be negative\")\n41: \t}\n42: \tif req.SnapLength == 0 {\n43: \t\treq.SnapLength = DefaultSnapLength\n44: \t}\n45: \tif req.SnapLength < MinSnapLength || req.SnapLength > MaxSnapLength {\n46: \t\treturn fmt.Errorf(\"capture snap length %d is outside %d to %d bytes\", req.SnapLength,\n47: \t\t\tMinSnapLength, MaxSnapLength)\n48: \t}\n49: \n50: \treturn nil\n51: }\n52: \n53: // FindInterface matches a requested interface by its name, then by its alias.\n54: func FindInterface(\n55: \tentries []clablabruntime.CaptureInterface,\n56: \tname string,\n57: ) (clablabruntime.CaptureInterface, bool) {\n58: \tfor _, entry := range entries {\n59: \t\tif entry.Interface == name {\n60: \t\t\treturn entry, true\n61: \t\t}\n62: \t}\n63: \tfor _, entry := range entries {\n64: \t\tif entry.Alias != \"\" && entry.Alias == name {\n65: \t\t\treturn entry, true\n66: \t\t}\n67: \t}\n68: \n69: \treturn clablabruntime.CaptureInterface{}, false\n70: }\n71: \n72: // DescribeInterfaces lists interfaces for an error message: name (alias), ...\n73: func DescribeInterfaces(entries []clablabruntime.CaptureInterface) string {\n74: \tif len(entries) == 0 {\n75: \t\treturn \"none\"\n76: \t}\n77: \n78: \tnames := make([]string, 0, len(entries))\n79: \tfor _, entry := range entries {\n80: \t\tname := entry.Interface\n81: \t\tif entry.Alias != \"\" {\n82: \t\t\tname += \" (\" + entry.Alias + \")\"\n83: \t\t}\n84: \t\tnames = append(names, name)\n85: \t}\n86: \n87: \treturn strings.Join(names, \", \")\n88: }\n89: \n90: // ReportGap hands a gap to onGap, or logs it as a warning when onGap is nil.\n91: func ReportGap(onGap func(clablabruntime.CaptureGap), gap clablabruntime.CaptureGap) {\n92: \tif onGap != nil {\n93: \t\tonGap(gap)\n94: \t\treturn\n95: \t}\n96: \n97: \tto := \"unknown\"\n98: \tif !gap.To.IsZero() {\n99: \t\tto = gap.To.Format(time.RFC3339Nano)\n100: \t}\n101: \tlog.Warn(\"Capture has a gap\", \"node\", gap.Node, \"interfaces\", strings.Join(gap.Interfaces, \",\"),\n102: \t\t\"from\", gap.From.Format(time.RFC3339Nano), \"to\", to, \"reason\", gap.Reason)\n103: }\n104: \n105: // Output is the merged pcapng stream of one capture: the section header with one interface per\n106: // capture target, then the packets of every target in timestamp order (through a Reorder), up\n107: // to an optional packet limit.\n108: type Output struct {\n109: \twriter  *Writer\n110: \treorder *Reorder\n111: \tlimit   int64\n112: \twritten atomic.Int64\n113: \tstop    func()\n114: \n115: \tcancelRun context.CancelFunc\n116: \trunDone   chan struct{}\n117: }\n118: \n119: // NewOutput writes the section header and one Interface Description Block per name to w, then\n120: // starts the reorder buffer with the given window (zero or less writes packets as they come).\n121: // stop is called once the packet limit is reached or a write failed. Close must be called.\n122: func NewOutput(\n123: \tw io.Writer,\n124: \tnames []string,\n125: \tsnapLength, packetLimit int,\n126: \twindow time.Duration,\n127: \tstop func(),\n128: ) (*Output, error) {\n129: \twriter := NewWriter(w)\n130: \tif err := writer.WriteHeader(\n131: \t\tnames,\n132: \t\tuint32(snapLength),\n133: \t); err != nil { //nolint:gosec // validated\n134: \t\treturn nil, err\n135: \t}\n136: \n137: \tout := &Output{\n138: \t\twriter:  writer,\n139: \t\treorder: NewReorder(window, writer.WritePacket, stop),\n140: \t\tlimit:   int64(packetLimit),\n141: \t\tstop:    stop,\n142: \t\trunDone: make(chan struct{}),\n143: \t}\n144: \n145: \tvar runCtx context.Context\n146: \trunCtx, out.cancelRun = context.WithCancel(context.Background())\n147: \tgo func() {\n148: \t\tdefer close(out.runDone)\n149: \t\tout.reorder.Run(runCtx)\n150: \t}()\n151: \n152: \treturn out, nil\n153: }\n154: \n155: // Emit hands a packet of the interface with the given index to the stream. It reports false\n156: // once the packet limit is reached and the capture stops, and returns the error of a failed\n157: // write.\n158: func (o *Output) Emit(id uint32, packet *Packet) (bool, error) {\n159: \tif o.limit > 0 {\n160: \t\tcount := o.written.Add(1)\n161: \t\tif count > o.limit {\n162: \t\t\to.stop()\n163: \t\t\treturn false, nil\n164: \t\t}\n165: \t\tif err := o.reorder.Push(id, packet); err != nil {\n166: \t\t\treturn false, err\n167: \t\t}\n168: \t\tif count == o.limit {\n169: \t\t\to.stop()\n170: \t\t\treturn false, nil\n171: \t\t}\n172: \n173: \t\treturn true, nil\n174: \t}\n175: \n176: \to.written.Add(1)\n177: \n178: \treturn true, o.reorder.Push(id, packet)\n179: }\n180: \n181: // Written returns the number of packets handed to the stream so far.\n182: func (o *Output) Written() int64 {\n183: \treturn o.written.Load()\n184: }\n185: \n186: // Hold keeps packets stamped after timestamp back until Release(key).\n187: func (o *Output) Hold(key any, timestamp int64) {\n188: \to.reorder.Hold(key, timestamp)\n189: }\n190: \n191: // Release removes the hold of key.\n192: func (o *Output) Release(key any) {\n193: \to.reorder.Release(key)\n194: }\n195: \n196: // Close writes the packets still held back and returns the first write error.\n197: func (o *Output) Close() error {\n198: \to.cancelRun()\n199: \t<-o.runDone\n200: \to.reorder.Flush()\n201: \n202: \treturn o.writer.Err()\n203: }\n\n(End of file - total 203 lines)\n</content>",
    "title": "source/head/capture/output.go",
    "metadata": {
      "preview": "package capture\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\n// Snap length bounds of a capture.\nconst (\n\t// DefaultSnapLength is the snap length of a request without one.\n\tDefaultSnapLength = 256 << 10\n\tMinSnapLength     = 64\n\tMaxSnapLength     = 1 << 20",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/capture/output.go",
        "text": "package capture\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\n// Snap length bounds of a capture.\nconst (\n\t// DefaultSnapLength is the snap length of a request without one.\n\tDefaultSnapLength = 256 << 10\n\tMinSnapLength     = 64\n\tMaxSnapLength     = 1 << 20\n)\n\n// ValidateRequest checks the bounds of a capture request and fills the default snap length.\nfunc ValidateRequest(req *clablabruntime.CaptureRequest) error {\n\tif req.Name == \"\" {\n\t\treturn fmt.Errorf(\"topology name is required\")\n\t}\n\tif len(req.Targets) == 0 {\n\t\treturn fmt.Errorf(\"at least one capture target (node and interface) is required\")\n\t}\n\tfor _, target := range req.Targets {\n\t\tif target.Node == \"\" || target.Interface == \"\" {\n\t\t\treturn fmt.Errorf(\"capture target %+v needs a node and an interface\", target)\n\t\t}\n\t}\n\tif req.Duration < 0 {\n\t\treturn fmt.Errorf(\"capture duration must not be negative\")\n\t}\n\tif req.PacketLimit < 0 {\n\t\treturn fmt.Errorf(\"capture packet limit must not be negative\")\n\t}\n\tif req.SnapLength == 0 {\n\t\treq.SnapLength = DefaultSnapLength\n\t}\n\tif req.SnapLength < MinSnapLength || req.SnapLength > MaxSnapLength {\n\t\treturn fmt.Errorf(\"capture snap length %d is outside %d to %d bytes\", req.SnapLength,\n\t\t\tMinSnapLength, MaxSnapLength)\n\t}\n\n\treturn nil\n}\n\n// FindInterface matches a requested interface by its name, then by its alias.\nfunc FindInterface(\n\tentries []clablabruntime.CaptureInterface,\n\tname string,\n) (clablabruntime.CaptureInterface, bool) {\n\tfor _, entry := range entries {\n\t\tif entry.Interface == name {\n\t\t\treturn entry, true\n\t\t}\n\t}\n\tfor _, entry := range entries {\n\t\tif entry.Alias != \"\" && entry.Alias == name {\n\t\t\treturn entry, true\n\t\t}\n\t}\n\n\treturn clablabruntime.CaptureInterface{}, false\n}\n\n// DescribeInterfaces lists interfaces for an error message: name (alias), ...\nfunc DescribeInterfaces(entries []clablabruntime.CaptureInterface) string {\n\tif len(entries) == 0 {\n\t\treturn \"none\"\n\t}\n\n\tnames := make([]string, 0, len(entries))\n\tfor _, entry := range entries {\n\t\tname := entry.Interface\n\t\tif entry.Alias != \"\" {\n\t\t\tname += \" (\" + entry.Alias + \")\"\n\t\t}\n\t\tnames = append(names, name)\n\t}\n\n\treturn strings.Join(names, \", \")\n}\n\n// ReportGap hands a gap to onGap, or logs it as a warning when onGap is nil.\nfunc ReportGap(onGap func(clablabruntime.CaptureGap), gap clablabruntime.CaptureGap) {\n\tif onGap != nil {\n\t\tonGap(gap)\n\t\treturn\n\t}\n\n\tto := \"unknown\"\n\tif !gap.To.IsZero() {\n\t\tto = gap.To.Format(time.RFC3339Nano)\n\t}\n\tlog.Warn(\"Capture has a gap\", \"node\", gap.Node, \"interfaces\", strings.Join(gap.Interfaces, \",\"),\n\t\t\"from\", gap.From.Format(time.RFC3339Nano), \"to\", to, \"reason\", gap.Reason)\n}\n\n// Output is the merged pcapng stream of one capture: the section header with one interface per\n// capture target, then the packets of every target in timestamp order (through a Reorder), up\n// to an optional packet limit.\ntype Output struct {\n\twriter  *Writer\n\treorder *Reorder\n\tlimit   int64\n\twritten atomic.Int64\n\tstop    func()\n\n\tcancelRun context.CancelFunc\n\trunDone   chan struct{}\n}\n\n// NewOutput writes the section header and one Interface Description Block per name to w, then\n// starts the reorder buffer with the given window (zero or less writes packets as they come).\n// stop is called once the packet limit is reached or a write failed. Close must be called.\nfunc NewOutput(\n\tw io.Writer,\n\tnames []string,\n\tsnapLength, packetLimit int,\n\twindow time.Duration,\n\tstop func(),\n) (*Output, error) {\n\twriter := NewWriter(w)\n\tif err := writer.WriteHeader(\n\t\tnames,\n\t\tuint32(snapLength),\n\t); err != nil { //nolint:gosec // validated\n\t\treturn nil, err\n\t}\n\n\tout := &Output{\n\t\twriter:  writer,\n\t\treorder: NewReorder(window, writer.WritePacket, stop),\n\t\tlimit:   int64(packetLimit),\n\t\tstop:    stop,\n\t\trunDone: make(chan struct{}),\n\t}\n\n\tvar runCtx context.Context\n\trunCtx, out.cancelRun = context.WithCancel(context.Background())\n\tgo func() {\n\t\tdefer close(out.runDone)\n\t\tout.reorder.Run(runCtx)\n\t}()\n\n\treturn out, nil\n}\n\n// Emit hands a packet of the interface with the given index to the stream. It reports false\n// once the packet limit is reached and the capture stops, and returns the error of a failed\n// write.\nfunc (o *Output) Emit(id uint32, packet *Packet) (bool, error) {\n\tif o.limit > 0 {\n\t\tcount := o.written.Add(1)\n\t\tif count > o.limit {\n\t\t\to.stop()\n\t\t\treturn false, nil\n\t\t}\n\t\tif err := o.reorder.Push(id, packet); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif count == o.limit {\n\t\t\to.stop()\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t}\n\n\to.written.Add(1)\n\n\treturn true, o.reorder.Push(id, packet)\n}\n\n// Written returns the number of packets handed to the stream so far.\nfunc (o *Output) Written() int64 {\n\treturn o.written.Load()\n}\n\n// Hold keeps packets stamped after timestamp back until Release(key).\nfunc (o *Output) Hold(key any, timestamp int64) {\n\to.reorder.Hold(key, timestamp)\n}\n\n// Release removes the hold of key.\nfunc (o *Output) Release(key any) {\n\to.reorder.Release(key)\n}\n\n// Close writes the packets still held back and returns the first write error.\nfunc (o *Output) Close() error {\n\to.cancelRun()\n\t<-o.runDone\n\to.reorder.Flush()\n\n\treturn o.writer.Err()\n}",
        "lineStart": 1,
        "lineEnd": 203,
        "totalLines": 203,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523263316,
      "end": 1793523263322
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19651275c001e01dhOINpr9l3q",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196511fd2001AsYcbxyXFxM3HK",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 44340,
    "input": 8211,
    "output": 32,
    "reasoning": 1,
    "cache": {
      "read": 36096,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196511fd2001AsYcbxyXFxM3HK",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523261394,
    "completed": 1793523263328
  },
  "parentID": "msg_19650e899001051OTPpm7MOch6",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 44340,
    "input": 8211,
    "output": 32,
    "reasoning": 1,
    "cache": {
      "read": 36096,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 17
step-start
{
  "type": "step-start",
  "id": "prt_196512d7d001W8O2RkiSu7KY7l",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965127650017wFkuC8x5Fl7Gc"
}
Reasoning
Notable observations so far:

1. `capture/local.go` `drain()`: after ctx done, drain reads with `time.Now().Before(deadline)` — but ReadPacket can block up to localPollTimeout (100ms), deadline is end+250ms. Potential issue: `drain` loops calling `source.ReadPacket()` — if source returns errReadTimeout after `localDrainQuiet` it returns. OK.

2. `localReader.run`: on ctx done, drain; but note when `r.out.Emit` returns `!more` (packet limit reached), reader returns without drain — fine.

3. `Output.Emit`: increments `written` before push; if `reorder.Push` fails, count already added. Minor.

4. `Reorder.Push` with cursor: `q.cursor != 0 && packet.Timestamp < q.cursor` — late packets written out of order. Note `cursor` only updated in popLocked. `writeLocked` direct writes don't update cursor... Actually in Push, late packet writeLocked does not update cursor — but late packet is behind cursor already, fine.

5. `Reorder.writeDue` holds: computes min timestamp among holds; packets with Timestamp > limit wait. OK.

6. `Output.Close` calls cancelRun then waits, then Flush — but Flush writes remaining packets ignoring holds (flushes all). Good.

7. Potential deadlock in local.go `run`: readers exit when `Emit` returns false... after stop() called (packet limit), sources still open; readers return. wg.Wait. Fine.

8. `drain` deadline: `deadline := end.Add(localDrainTimeout)`; loop condition `time.Now().Before(deadline)`; inside, if errReadTimeout && time.Since(end) < localDrainQuiet → continue; but if time.Since(end) >= localDrainQuiet and errReadTimeout, falls to `if err != nil || ...` → return. OK.

9. In `drain`, `info.Timestamp.After(end)` returns, dropping packets stamped after end — reasonable.

10. capture/local.go reopen: after ctx done reports gap with To zero. OK.

Potential bug: In `localCapture.run`, when `NewOutput` fails, closes sources and returns — but the `captureCtx` cancel timers are deferred, fine.

Potential issue: `openAll` — if `l.open` returns fewer sources than `len(group.names)`? e.g., opened has len != len(names); mapping `sources[group.indexes[idx]]` would panic index out of range if opened shorter, or leave nil entries if longer. openPacketSockets appends one per interface, so equal in practice. Minor.

11. pcapng.go `Next`: peek of 4 bytes for byte-order magic at SHB — if the peek fails with EOF returns ErrUnexpectedEOF even when it's a clean EOF (truncated section header at end). Minor.

Also `if binary.BigEndian.Uint32(magic) == pcapngByteOrderMagic` — big-endian section detection. OK.

12. Writer.WriteHeader: section header block: `section := make([]byte, 16)`, puts magic at 0, major 4, minor 6, section length 8..16 math.MaxUint64. Correct per spec.

13. `pcapngBlock` — total = 12+len(body). Block = 4 type + 4 length + body + 4 total. Good.

14. appendPCAPNGOption padding: appends value then padding of len(value) — correct.

15. `WritePacket` timestamp: `uint64(packet.Timestamp)` — if Timestamp negative (pre-1970), wraps. nolint noted. Minor.

16. Reorder.Run wait computation: `next.Sub(q.now())` could be negative? It computes max(..., time.Millisecond). OK.

17. `resetTimer` — standard.

Now, the bigger files: cmd/capture.go, core/capture.go, core/capture_local.go, labruntime/clabernetes/capture.go (1202 lines), capture_interfaces.go, and diffs to cmd/* (context, inspect, options, root). Let me read cmd/capture.go and core/capture_local.go, core/capture.go.
The `capture` package looks well-structured. Now let me review the command layer and core integration.
read · completed

Input

{
  "filePath": "/source/head/cmd/capture.go"
}

Output

<path>/source/head/cmd/capture.go</path>
<type>file</type>
<content>
1: package cmd
2: 
3: import (
4: 	"encoding/json"
5: 	"fmt"
6: 	"io"
7: 	"os"
8: 	"strings"
9: 	"time"
10: 
11: 	"github.com/charmbracelet/log"
12: 	tableWriter "github.com/jedib0t/go-pretty/v6/table"
13: 	"github.com/jedib0t/go-pretty/v6/text"
14: 	"github.com/spf13/cobra"
15: 	clabconstants "github.com/srl-labs/containerlab/constants"
16: 	clabcore "github.com/srl-labs/containerlab/core"
17: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
18: 	clabutils "github.com/srl-labs/containerlab/utils"
19: )
20: 
21: // CaptureOptions are the flags of the capture command.
22: type CaptureOptions struct {
23: 	Targets     []string
24: 	Duration    time.Duration
25: 	PacketLimit int
26: 	SnapLength  int
27: 	Write       string
28: 	List        bool
29: 	Format      string
30: }
31: 
32: func captureCmd(o *Options) (*cobra.Command, error) {
33: 	c := &cobra.Command{
34: 		Use:   "capture",
35: 		Short: "capture packets on lab link interfaces",
36: 		Long: "capture packets on lab link interfaces of one or more nodes into one pcapng " +
37: 			"stream\nreference: https://containerlab.dev/cmd/capture/",
38: 		PreRunE: func(_ *cobra.Command, _ []string) error {
39: 			if commandSkipsRoot(o.Global.Runtime) {
40: 				return nil
41: 			}
42: 
43: 			// Docker and Podman captures open packet sockets in the nodes' namespaces
44: 			return clabutils.CheckAndGetRootPrivs()
45: 		},
46: 		SilenceUsage: true,
47: 		RunE: func(cmd *cobra.Command, _ []string) error {
48: 			return captureFn(cmd, o)
49: 		},
50: 	}
51: 
52: 	c.Flags().StringArrayVar(
53: 		&o.Capture.Targets,
54: 		"target",
55: 		o.Capture.Targets,
56: 		"node and interfaces to capture, as <node>:<interface>[,<interface>...]; repeatable",
57: 	)
58: 	c.Flags().DurationVar(
59: 		&o.Capture.Duration,
60: 		"duration",
61: 		o.Capture.Duration,
62: 		"stop after this duration; 0 captures until interrupted",
63: 	)
64: 	c.Flags().IntVar(
65: 		&o.Capture.PacketLimit,
66: 		"packet-limit",
67: 		o.Capture.PacketLimit,
68: 		"stop after this many packets across all targets; 0 means no limit",
69: 	)
70: 	c.Flags().IntVar(
71: 		&o.Capture.SnapLength,
72: 		"snap-length",
73: 		o.Capture.SnapLength,
74: 		"bytes kept of each packet (64 to 1048576); 0 uses the runtime default",
75: 	)
76: 	c.Flags().StringVarP(
77: 		&o.Capture.Write,
78: 		"write",
79: 		"w",
80: 		o.Capture.Write,
81: 		"pcapng output file; - writes to stdout",
82: 	)
83: 	c.Flags().BoolVar(
84: 		&o.Capture.List,
85: 		"list",
86: 		o.Capture.List,
87: 		"list the capturable interfaces instead of capturing",
88: 	)
89: 	c.Flags().StringVarP(
90: 		&o.Capture.Format,
91: 		"format",
92: 		"f",
93: 		o.Capture.Format,
94: 		"output format of --list: table or json",
95: 	)
96: 
97: 	c.Example = `# Capture e1-1 of srl1 and e1-1 of srl2 for 30 seconds into one file
98: containerlab capture -t srl.clab.yml --target srl1:e1-1 --target srl2:e1-1 \
99:   --duration 30s -w srl.pcapng
100: 
101: # Capture two interfaces of one node and watch them live in Wireshark
102: containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -
103: 
104: # List the interfaces capture accepts
105: containerlab capture --name srl --list -f json
106: 
107: # Capture a lab running on the c9s runtime
108: containerlab -r c9s capture --name srl --target srl1:e1-1 -w srl.pcapng`
109: 
110: 	return c, nil
111: }
112: 
113: func captureFn(cmd *cobra.Command, o *Options) error {
114: 	if o.Global.TopologyName == "" && o.Global.TopologyFile == "" {
115: 		return fmt.Errorf("provide either a lab name (--name) or a topology file path (--topo)")
116: 	}
117: 
118: 	if o.Capture.List {
119: 		return captureListFn(cmd, o)
120: 	}
121: 
122: 	targets, err := parseCaptureTargets(o.Capture.Targets)
123: 	if err != nil {
124: 		return err
125: 	}
126: 
127: 	c, err := clabcore.NewContainerLab(o.ToClabOptions()...)
128: 	if err != nil {
129: 		return err
130: 	}
131: 
132: 	// An interrupt ends the capture; the command still finishes the file and exits cleanly.
133: 	// Armed before the file is created, so an interrupt never leaves it empty.
134: 	o.Global.FinishOnCancel.Store(true)
135: 	defer o.Global.FinishOnCancel.Store(false)
136: 
137: 	output := cmd.OutOrStdout()
138: 	if o.Capture.Write != "" && o.Capture.Write != "-" {
139: 		file, err := os.Create(o.Capture.Write)
140: 		if err != nil {
141: 			return fmt.Errorf("failed to create the capture file: %w", err)
142: 		}
143: 		defer file.Close()
144: 		output = file
145: 
146: 		// the file belongs to the user who ran the command, also through sudo or setuid
147: 		if err := clabutils.SetUIDAndGID(o.Capture.Write); err != nil {
148: 			log.Debug("Cannot hand the capture file to the user", "file", o.Capture.Write,
149: 				"error", err)
150: 		}
151: 	}
152: 
153: 	err = c.Capture(cmd.Context(), clablabruntime.CaptureRequest{
154: 		Targets:     targets,
155: 		Duration:    o.Capture.Duration,
156: 		PacketLimit: o.Capture.PacketLimit,
157: 		SnapLength:  o.Capture.SnapLength,
158: 	}, output)
159: 	if err != nil {
160: 		return err
161: 	}
162: 
163: 	if file, ok := output.(*os.File); ok && output != cmd.OutOrStdout() {
164: 		if err := file.Sync(); err != nil {
165: 			return fmt.Errorf("failed to write the capture file: %w", err)
166: 		}
167: 	}
168: 
169: 	return nil
170: }
171: 
172: // parseCaptureTargets parses --target values: <node>:<interface>[,<interface>...]. The node name
173: // ends at the first colon, so interface names may contain colons or slashes.
174: func parseCaptureTargets(values []string) ([]clablabruntime.CaptureTarget, error) {
175: 	if len(values) == 0 {
176: 		return nil, fmt.Errorf("provide at least one --target <node>:<interface>[,<interface>...]")
177: 	}
178: 
179: 	targets := make([]clablabruntime.CaptureTarget, 0, len(values))
180: 	for _, value := range values {
181: 		node, interfaces, ok := strings.Cut(strings.TrimSpace(value), ":")
182: 		node = strings.TrimSpace(node)
183: 		if !ok || node == "" || strings.TrimSpace(interfaces) == "" {
184: 			return nil, fmt.Errorf("invalid --target %q: use <node>:<interface>[,<interface>...]",
185: 				value)
186: 		}
187: 
188: 		for _, name := range strings.Split(interfaces, ",") {
189: 			name = strings.TrimSpace(name)
190: 			if name == "" {
191: 				return nil, fmt.Errorf("invalid --target %q: empty interface name", value)
192: 			}
193: 			targets = append(targets, clablabruntime.CaptureTarget{Node: node, Interface: name})
194: 		}
195: 	}
196: 
197: 	return targets, nil
198: }
199: 
200: func captureListFn(cmd *cobra.Command, o *Options) error {
201: 	format := o.Capture.Format
202: 	if format == "" {
203: 		format = clabconstants.FormatTable
204: 	}
205: 	if format != clabconstants.FormatTable && format != clabconstants.FormatJSON {
206: 		return fmt.Errorf("output format %q is not supported, use 'table' or 'json'", format)
207: 	}
208: 	if len(o.Capture.Targets) != 0 {
209: 		return fmt.Errorf("--list lists every running node's interfaces; it takes no --target")
210: 	}
211: 
212: 	c, err := clabcore.NewContainerLab(o.ToClabOptions()...)
213: 	if err != nil {
214: 		return err
215: 	}
216: 
217: 	interfaces, err := c.CaptureInterfaces(cmd.Context())
218: 	if err != nil {
219: 		return err
220: 	}
221: 
222: 	return printCaptureInterfaces(cmd.OutOrStdout(), interfaces, format)
223: }
224: 
225: func printCaptureInterfaces(
226: 	w io.Writer,
227: 	interfaces []clablabruntime.CaptureInterface,
228: 	format string,
229: ) error {
230: 	if format == clabconstants.FormatJSON {
231: 		if interfaces == nil {
232: 			interfaces = []clablabruntime.CaptureInterface{}
233: 		}
234: 		data, err := json.MarshalIndent(interfaces, "", "  ")
235: 		if err != nil {
236: 			return err
237: 		}
238: 		_, err = fmt.Fprintln(w, string(data))
239: 
240: 		return err
241: 	}
242: 
243: 	table := tableWriter.NewWriter()
244: 	table.SetOutputMirror(w)
245: 	table.SetStyle(tableWriter.StyleRounded)
246: 	table.Style().Format.Header = text.FormatTitle
247: 	table.Style().Format.HeaderAlign = text.AlignCenter
248: 	table.AppendHeader(tableWriter.Row{"Node", "Interface", "Alias", "Peer Node", "Peer Interface"})
249: 	table.SetColumnConfigs([]tableWriter.ColumnConfig{{Number: 1, AutoMerge: true}})
250: 	for _, intf := range interfaces {
251: 		alias := intf.Alias
252: 		if alias == "" {
253: 			alias = clabconstants.NotApplicable
254: 		}
255: 		table.AppendRow(tableWriter.Row{
256: 			intf.Node, intf.Interface, alias, intf.PeerNode, intf.PeerInterface,
257: 		})
258: 	}
259: 	table.Render()
260: 
261: 	return nil
262: }

(End of file - total 262 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1965149c0001thIDN6AVHFb03R",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965127650017wFkuC8x5Fl7Gc",
  "callID": "call_f0100cecd2894ff4956416b1",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/cmd/capture.go"
    },
    "output": "<path>/source/head/cmd/capture.go</path>\n<type>file</type>\n<content>\n1: package cmd\n2: \n3: import (\n4: \t\"encoding/json\"\n5: \t\"fmt\"\n6: \t\"io\"\n7: \t\"os\"\n8: \t\"strings\"\n9: \t\"time\"\n10: \n11: \t\"github.com/charmbracelet/log\"\n12: \ttableWriter \"github.com/jedib0t/go-pretty/v6/table\"\n13: \t\"github.com/jedib0t/go-pretty/v6/text\"\n14: \t\"github.com/spf13/cobra\"\n15: \tclabconstants \"github.com/srl-labs/containerlab/constants\"\n16: \tclabcore \"github.com/srl-labs/containerlab/core\"\n17: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n18: \tclabutils \"github.com/srl-labs/containerlab/utils\"\n19: )\n20: \n21: // CaptureOptions are the flags of the capture command.\n22: type CaptureOptions struct {\n23: \tTargets     []string\n24: \tDuration    time.Duration\n25: \tPacketLimit int\n26: \tSnapLength  int\n27: \tWrite       string\n28: \tList        bool\n29: \tFormat      string\n30: }\n31: \n32: func captureCmd(o *Options) (*cobra.Command, error) {\n33: \tc := &cobra.Command{\n34: \t\tUse:   \"capture\",\n35: \t\tShort: \"capture packets on lab link interfaces\",\n36: \t\tLong: \"capture packets on lab link interfaces of one or more nodes into one pcapng \" +\n37: \t\t\t\"stream\\nreference: https://containerlab.dev/cmd/capture/\",\n38: \t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n39: \t\t\tif commandSkipsRoot(o.Global.Runtime) {\n40: \t\t\t\treturn nil\n41: \t\t\t}\n42: \n43: \t\t\t// Docker and Podman captures open packet sockets in the nodes' namespaces\n44: \t\t\treturn clabutils.CheckAndGetRootPrivs()\n45: \t\t},\n46: \t\tSilenceUsage: true,\n47: \t\tRunE: func(cmd *cobra.Command, _ []string) error {\n48: \t\t\treturn captureFn(cmd, o)\n49: \t\t},\n50: \t}\n51: \n52: \tc.Flags().StringArrayVar(\n53: \t\t&o.Capture.Targets,\n54: \t\t\"target\",\n55: \t\to.Capture.Targets,\n56: \t\t\"node and interfaces to capture, as <node>:<interface>[,<interface>...]; repeatable\",\n57: \t)\n58: \tc.Flags().DurationVar(\n59: \t\t&o.Capture.Duration,\n60: \t\t\"duration\",\n61: \t\to.Capture.Duration,\n62: \t\t\"stop after this duration; 0 captures until interrupted\",\n63: \t)\n64: \tc.Flags().IntVar(\n65: \t\t&o.Capture.PacketLimit,\n66: \t\t\"packet-limit\",\n67: \t\to.Capture.PacketLimit,\n68: \t\t\"stop after this many packets across all targets; 0 means no limit\",\n69: \t)\n70: \tc.Flags().IntVar(\n71: \t\t&o.Capture.SnapLength,\n72: \t\t\"snap-length\",\n73: \t\to.Capture.SnapLength,\n74: \t\t\"bytes kept of each packet (64 to 1048576); 0 uses the runtime default\",\n75: \t)\n76: \tc.Flags().StringVarP(\n77: \t\t&o.Capture.Write,\n78: \t\t\"write\",\n79: \t\t\"w\",\n80: \t\to.Capture.Write,\n81: \t\t\"pcapng output file; - writes to stdout\",\n82: \t)\n83: \tc.Flags().BoolVar(\n84: \t\t&o.Capture.List,\n85: \t\t\"list\",\n86: \t\to.Capture.List,\n87: \t\t\"list the capturable interfaces instead of capturing\",\n88: \t)\n89: \tc.Flags().StringVarP(\n90: \t\t&o.Capture.Format,\n91: \t\t\"format\",\n92: \t\t\"f\",\n93: \t\to.Capture.Format,\n94: \t\t\"output format of --list: table or json\",\n95: \t)\n96: \n97: \tc.Example = `# Capture e1-1 of srl1 and e1-1 of srl2 for 30 seconds into one file\n98: containerlab capture -t srl.clab.yml --target srl1:e1-1 --target srl2:e1-1 \\\n99:   --duration 30s -w srl.pcapng\n100: \n101: # Capture two interfaces of one node and watch them live in Wireshark\n102: containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n103: \n104: # List the interfaces capture accepts\n105: containerlab capture --name srl --list -f json\n106: \n107: # Capture a lab running on the c9s runtime\n108: containerlab -r c9s capture --name srl --target srl1:e1-1 -w srl.pcapng`\n109: \n110: \treturn c, nil\n111: }\n112: \n113: func captureFn(cmd *cobra.Command, o *Options) error {\n114: \tif o.Global.TopologyName == \"\" && o.Global.TopologyFile == \"\" {\n115: \t\treturn fmt.Errorf(\"provide either a lab name (--name) or a topology file path (--topo)\")\n116: \t}\n117: \n118: \tif o.Capture.List {\n119: \t\treturn captureListFn(cmd, o)\n120: \t}\n121: \n122: \ttargets, err := parseCaptureTargets(o.Capture.Targets)\n123: \tif err != nil {\n124: \t\treturn err\n125: \t}\n126: \n127: \tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n128: \tif err != nil {\n129: \t\treturn err\n130: \t}\n131: \n132: \t// An interrupt ends the capture; the command still finishes the file and exits cleanly.\n133: \t// Armed before the file is created, so an interrupt never leaves it empty.\n134: \to.Global.FinishOnCancel.Store(true)\n135: \tdefer o.Global.FinishOnCancel.Store(false)\n136: \n137: \toutput := cmd.OutOrStdout()\n138: \tif o.Capture.Write != \"\" && o.Capture.Write != \"-\" {\n139: \t\tfile, err := os.Create(o.Capture.Write)\n140: \t\tif err != nil {\n141: \t\t\treturn fmt.Errorf(\"failed to create the capture file: %w\", err)\n142: \t\t}\n143: \t\tdefer file.Close()\n144: \t\toutput = file\n145: \n146: \t\t// the file belongs to the user who ran the command, also through sudo or setuid\n147: \t\tif err := clabutils.SetUIDAndGID(o.Capture.Write); err != nil {\n148: \t\t\tlog.Debug(\"Cannot hand the capture file to the user\", \"file\", o.Capture.Write,\n149: \t\t\t\t\"error\", err)\n150: \t\t}\n151: \t}\n152: \n153: \terr = c.Capture(cmd.Context(), clablabruntime.CaptureRequest{\n154: \t\tTargets:     targets,\n155: \t\tDuration:    o.Capture.Duration,\n156: \t\tPacketLimit: o.Capture.PacketLimit,\n157: \t\tSnapLength:  o.Capture.SnapLength,\n158: \t}, output)\n159: \tif err != nil {\n160: \t\treturn err\n161: \t}\n162: \n163: \tif file, ok := output.(*os.File); ok && output != cmd.OutOrStdout() {\n164: \t\tif err := file.Sync(); err != nil {\n165: \t\t\treturn fmt.Errorf(\"failed to write the capture file: %w\", err)\n166: \t\t}\n167: \t}\n168: \n169: \treturn nil\n170: }\n171: \n172: // parseCaptureTargets parses --target values: <node>:<interface>[,<interface>...]. The node name\n173: // ends at the first colon, so interface names may contain colons or slashes.\n174: func parseCaptureTargets(values []string) ([]clablabruntime.CaptureTarget, error) {\n175: \tif len(values) == 0 {\n176: \t\treturn nil, fmt.Errorf(\"provide at least one --target <node>:<interface>[,<interface>...]\")\n177: \t}\n178: \n179: \ttargets := make([]clablabruntime.CaptureTarget, 0, len(values))\n180: \tfor _, value := range values {\n181: \t\tnode, interfaces, ok := strings.Cut(strings.TrimSpace(value), \":\")\n182: \t\tnode = strings.TrimSpace(node)\n183: \t\tif !ok || node == \"\" || strings.TrimSpace(interfaces) == \"\" {\n184: \t\t\treturn nil, fmt.Errorf(\"invalid --target %q: use <node>:<interface>[,<interface>...]\",\n185: \t\t\t\tvalue)\n186: \t\t}\n187: \n188: \t\tfor _, name := range strings.Split(interfaces, \",\") {\n189: \t\t\tname = strings.TrimSpace(name)\n190: \t\t\tif name == \"\" {\n191: \t\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: empty interface name\", value)\n192: \t\t\t}\n193: \t\t\ttargets = append(targets, clablabruntime.CaptureTarget{Node: node, Interface: name})\n194: \t\t}\n195: \t}\n196: \n197: \treturn targets, nil\n198: }\n199: \n200: func captureListFn(cmd *cobra.Command, o *Options) error {\n201: \tformat := o.Capture.Format\n202: \tif format == \"\" {\n203: \t\tformat = clabconstants.FormatTable\n204: \t}\n205: \tif format != clabconstants.FormatTable && format != clabconstants.FormatJSON {\n206: \t\treturn fmt.Errorf(\"output format %q is not supported, use 'table' or 'json'\", format)\n207: \t}\n208: \tif len(o.Capture.Targets) != 0 {\n209: \t\treturn fmt.Errorf(\"--list lists every running node's interfaces; it takes no --target\")\n210: \t}\n211: \n212: \tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n213: \tif err != nil {\n214: \t\treturn err\n215: \t}\n216: \n217: \tinterfaces, err := c.CaptureInterfaces(cmd.Context())\n218: \tif err != nil {\n219: \t\treturn err\n220: \t}\n221: \n222: \treturn printCaptureInterfaces(cmd.OutOrStdout(), interfaces, format)\n223: }\n224: \n225: func printCaptureInterfaces(\n226: \tw io.Writer,\n227: \tinterfaces []clablabruntime.CaptureInterface,\n228: \tformat string,\n229: ) error {\n230: \tif format == clabconstants.FormatJSON {\n231: \t\tif interfaces == nil {\n232: \t\t\tinterfaces = []clablabruntime.CaptureInterface{}\n233: \t\t}\n234: \t\tdata, err := json.MarshalIndent(interfaces, \"\", \"  \")\n235: \t\tif err != nil {\n236: \t\t\treturn err\n237: \t\t}\n238: \t\t_, err = fmt.Fprintln(w, string(data))\n239: \n240: \t\treturn err\n241: \t}\n242: \n243: \ttable := tableWriter.NewWriter()\n244: \ttable.SetOutputMirror(w)\n245: \ttable.SetStyle(tableWriter.StyleRounded)\n246: \ttable.Style().Format.Header = text.FormatTitle\n247: \ttable.Style().Format.HeaderAlign = text.AlignCenter\n248: \ttable.AppendHeader(tableWriter.Row{\"Node\", \"Interface\", \"Alias\", \"Peer Node\", \"Peer Interface\"})\n249: \ttable.SetColumnConfigs([]tableWriter.ColumnConfig{{Number: 1, AutoMerge: true}})\n250: \tfor _, intf := range interfaces {\n251: \t\talias := intf.Alias\n252: \t\tif alias == \"\" {\n253: \t\t\talias = clabconstants.NotApplicable\n254: \t\t}\n255: \t\ttable.AppendRow(tableWriter.Row{\n256: \t\t\tintf.Node, intf.Interface, alias, intf.PeerNode, intf.PeerInterface,\n257: \t\t})\n258: \t}\n259: \ttable.Render()\n260: \n261: \treturn nil\n262: }\n\n(End of file - total 262 lines)\n</content>",
    "title": "source/head/cmd/capture.go",
    "metadata": {
      "preview": "package cmd\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\ttableWriter \"github.com/jedib0t/go-pretty/v6/table\"\n\t\"github.com/jedib0t/go-pretty/v6/text\"\n\t\"github.com/spf13/cobra\"\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\tclabutils \"github.com/srl-labs/containerlab/utils\"\n)\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/cmd/capture.go",
        "text": "package cmd\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\ttableWriter \"github.com/jedib0t/go-pretty/v6/table\"\n\t\"github.com/jedib0t/go-pretty/v6/text\"\n\t\"github.com/spf13/cobra\"\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\tclabutils \"github.com/srl-labs/containerlab/utils\"\n)\n\n// CaptureOptions are the flags of the capture command.\ntype CaptureOptions struct {\n\tTargets     []string\n\tDuration    time.Duration\n\tPacketLimit int\n\tSnapLength  int\n\tWrite       string\n\tList        bool\n\tFormat      string\n}\n\nfunc captureCmd(o *Options) (*cobra.Command, error) {\n\tc := &cobra.Command{\n\t\tUse:   \"capture\",\n\t\tShort: \"capture packets on lab link interfaces\",\n\t\tLong: \"capture packets on lab link interfaces of one or more nodes into one pcapng \" +\n\t\t\t\"stream\\nreference: https://containerlab.dev/cmd/capture/\",\n\t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t// Docker and Podman captures open packet sockets in the nodes' namespaces\n\t\t\treturn clabutils.CheckAndGetRootPrivs()\n\t\t},\n\t\tSilenceUsage: true,\n\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n\t\t\treturn captureFn(cmd, o)\n\t\t},\n\t}\n\n\tc.Flags().StringArrayVar(\n\t\t&o.Capture.Targets,\n\t\t\"target\",\n\t\to.Capture.Targets,\n\t\t\"node and interfaces to capture, as <node>:<interface>[,<interface>...]; repeatable\",\n\t)\n\tc.Flags().DurationVar(\n\t\t&o.Capture.Duration,\n\t\t\"duration\",\n\t\to.Capture.Duration,\n\t\t\"stop after this duration; 0 captures until interrupted\",\n\t)\n\tc.Flags().IntVar(\n\t\t&o.Capture.PacketLimit,\n\t\t\"packet-limit\",\n\t\to.Capture.PacketLimit,\n\t\t\"stop after this many packets across all targets; 0 means no limit\",\n\t)\n\tc.Flags().IntVar(\n\t\t&o.Capture.SnapLength,\n\t\t\"snap-length\",\n\t\to.Capture.SnapLength,\n\t\t\"bytes kept of each packet (64 to 1048576); 0 uses the runtime default\",\n\t)\n\tc.Flags().StringVarP(\n\t\t&o.Capture.Write,\n\t\t\"write\",\n\t\t\"w\",\n\t\to.Capture.Write,\n\t\t\"pcapng output file; - writes to stdout\",\n\t)\n\tc.Flags().BoolVar(\n\t\t&o.Capture.List,\n\t\t\"list\",\n\t\to.Capture.List,\n\t\t\"list the capturable interfaces instead of capturing\",\n\t)\n\tc.Flags().StringVarP(\n\t\t&o.Capture.Format,\n\t\t\"format\",\n\t\t\"f\",\n\t\to.Capture.Format,\n\t\t\"output format of --list: table or json\",\n\t)\n\n\tc.Example = `# Capture e1-1 of srl1 and e1-1 of srl2 for 30 seconds into one file\ncontainerlab capture -t srl.clab.yml --target srl1:e1-1 --target srl2:e1-1 \\\n  --duration 30s -w srl.pcapng\n\n# Capture two interfaces of one node and watch them live in Wireshark\ncontainerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n\n# List the interfaces capture accepts\ncontainerlab capture --name srl --list -f json\n\n# Capture a lab running on the c9s runtime\ncontainerlab -r c9s capture --name srl --target srl1:e1-1 -w srl.pcapng`\n\n\treturn c, nil\n}\n\nfunc captureFn(cmd *cobra.Command, o *Options) error {\n\tif o.Global.TopologyName == \"\" && o.Global.TopologyFile == \"\" {\n\t\treturn fmt.Errorf(\"provide either a lab name (--name) or a topology file path (--topo)\")\n\t}\n\n\tif o.Capture.List {\n\t\treturn captureListFn(cmd, o)\n\t}\n\n\ttargets, err := parseCaptureTargets(o.Capture.Targets)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// An interrupt ends the capture; the command still finishes the file and exits cleanly.\n\t// Armed before the file is created, so an interrupt never leaves it empty.\n\to.Global.FinishOnCancel.Store(true)\n\tdefer o.Global.FinishOnCancel.Store(false)\n\n\toutput := cmd.OutOrStdout()\n\tif o.Capture.Write != \"\" && o.Capture.Write != \"-\" {\n\t\tfile, err := os.Create(o.Capture.Write)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create the capture file: %w\", err)\n\t\t}\n\t\tdefer file.Close()\n\t\toutput = file\n\n\t\t// the file belongs to the user who ran the command, also through sudo or setuid\n\t\tif err := clabutils.SetUIDAndGID(o.Capture.Write); err != nil {\n\t\t\tlog.Debug(\"Cannot hand the capture file to the user\", \"file\", o.Capture.Write,\n\t\t\t\t\"error\", err)\n\t\t}\n\t}\n\n\terr = c.Capture(cmd.Context(), clablabruntime.CaptureRequest{\n\t\tTargets:     targets,\n\t\tDuration:    o.Capture.Duration,\n\t\tPacketLimit: o.Capture.PacketLimit,\n\t\tSnapLength:  o.Capture.SnapLength,\n\t}, output)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif file, ok := output.(*os.File); ok && output != cmd.OutOrStdout() {\n\t\tif err := file.Sync(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to write the capture file: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// parseCaptureTargets parses --target values: <node>:<interface>[,<interface>...]. The node name\n// ends at the first colon, so interface names may contain colons or slashes.\nfunc parseCaptureTargets(values []string) ([]clablabruntime.CaptureTarget, error) {\n\tif len(values) == 0 {\n\t\treturn nil, fmt.Errorf(\"provide at least one --target <node>:<interface>[,<interface>...]\")\n\t}\n\n\ttargets := make([]clablabruntime.CaptureTarget, 0, len(values))\n\tfor _, value := range values {\n\t\tnode, interfaces, ok := strings.Cut(strings.TrimSpace(value), \":\")\n\t\tnode = strings.TrimSpace(node)\n\t\tif !ok || node == \"\" || strings.TrimSpace(interfaces) == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: use <node>:<interface>[,<interface>...]\",\n\t\t\t\tvalue)\n\t\t}\n\n\t\tfor _, name := range strings.Split(interfaces, \",\") {\n\t\t\tname = strings.TrimSpace(name)\n\t\t\tif name == \"\" {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: empty interface name\", value)\n\t\t\t}\n\t\t\ttargets = append(targets, clablabruntime.CaptureTarget{Node: node, Interface: name})\n\t\t}\n\t}\n\n\treturn targets, nil\n}\n\nfunc captureListFn(cmd *cobra.Command, o *Options) error {\n\tformat := o.Capture.Format\n\tif format == \"\" {\n\t\tformat = clabconstants.FormatTable\n\t}\n\tif format != clabconstants.FormatTable && format != clabconstants.FormatJSON {\n\t\treturn fmt.Errorf(\"output format %q is not supported, use 'table' or 'json'\", format)\n\t}\n\tif len(o.Capture.Targets) != 0 {\n\t\treturn fmt.Errorf(\"--list lists every running node's interfaces; it takes no --target\")\n\t}\n\n\tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinterfaces, err := c.CaptureInterfaces(cmd.Context())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn printCaptureInterfaces(cmd.OutOrStdout(), interfaces, format)\n}\n\nfunc printCaptureInterfaces(\n\tw io.Writer,\n\tinterfaces []clablabruntime.CaptureInterface,\n\tformat string,\n) error {\n\tif format == clabconstants.FormatJSON {\n\t\tif interfaces == nil {\n\t\t\tinterfaces = []clablabruntime.CaptureInterface{}\n\t\t}\n\t\tdata, err := json.MarshalIndent(interfaces, \"\", \"  \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = fmt.Fprintln(w, string(data))\n\n\t\treturn err\n\t}\n\n\ttable := tableWriter.NewWriter()\n\ttable.SetOutputMirror(w)\n\ttable.SetStyle(tableWriter.StyleRounded)\n\ttable.Style().Format.Header = text.FormatTitle\n\ttable.Style().Format.HeaderAlign = text.AlignCenter\n\ttable.AppendHeader(tableWriter.Row{\"Node\", \"Interface\", \"Alias\", \"Peer Node\", \"Peer Interface\"})\n\ttable.SetColumnConfigs([]tableWriter.ColumnConfig{{Number: 1, AutoMerge: true}})\n\tfor _, intf := range interfaces {\n\t\talias := intf.Alias\n\t\tif alias == \"\" {\n\t\t\talias = clabconstants.NotApplicable\n\t\t}\n\t\ttable.AppendRow(tableWriter.Row{\n\t\t\tintf.Node, intf.Interface, alias, intf.PeerNode, intf.PeerInterface,\n\t\t})\n\t}\n\ttable.Render()\n\n\treturn nil\n}",
        "lineStart": 1,
        "lineEnd": 262,
        "totalLines": 262,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523272133,
      "end": 1793523272139
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/core/capture.go"
}

Output

<path>/source/head/core/capture.go</path>
<type>file</type>
<content>
1: package core
2: 
3: import (
4: 	"context"
5: 	"io"
6: 
7: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
8: 	clabtypes "github.com/srl-labs/containerlab/types"
9: )
10: 
11: // CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for
12: // every running node, with the peer at the other end of each link. With Docker and Podman, the
13: // interfaces come from the topology's links; lab runtimes list them through their packet
14: // capturer.
15: func (c *CLab) CaptureInterfaces(
16: 	ctx context.Context,
17: 	nodeNames ...string,
18: ) ([]clablabruntime.CaptureInterface, error) {
19: 	if c.LabRuntime == nil {
20: 		return c.localCaptureInterfacesOf(ctx, nodeNames)
21: 	}
22: 
23: 	capturer, err := c.packetCapturer()
24: 	if err != nil {
25: 		return nil, err
26: 	}
27: 
28: 	return capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{
29: 		Name:     c.Config.Name,
30: 		Nodes:    nodeNames,
31: 		Identity: c.labRuntimeIdentity,
32: 	})
33: }
34: 
35: // Capture streams pcapng from lab link interfaces to w until req.Duration passed,
36: // req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name
37: // and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces
38: // itself through packet sockets in the nodes' network namespaces, which needs root; lab
39: // runtimes capture through their packet capturer.
40: func (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {
41: 	if c.LabRuntime == nil {
42: 		return c.captureLocal(ctx, req, w)
43: 	}
44: 
45: 	capturer, err := c.packetCapturer()
46: 	if err != nil {
47: 		return err
48: 	}
49: 
50: 	if req.Name == "" {
51: 		req.Name = c.Config.Name
52: 	}
53: 	if req.Identity.IsZero() {
54: 		req.Identity = c.labRuntimeIdentity
55: 	}
56: 
57: 	return capturer.Capture(ctx, req, w)
58: }
59: 
60: // LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their
61: // state, in the shape ListContainersInterfaces reports for local containers.
62: func (c *CLab) LabRuntimeInterfaces(
63: 	ctx context.Context,
64: 	nodeName string,
65: ) ([]*clabtypes.ContainerInterfaces, error) {
66: 	inspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](
67: 		c, "inspecting interfaces")
68: 	if err != nil {
69: 		return nil, err
70: 	}
71: 	if err := c.requireLabName(); err != nil {
72: 		return nil, err
73: 	}
74: 
75: 	req := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}
76: 	if nodeName != "" {
77: 		req.Nodes = []string{nodeName}
78: 	}
79: 
80: 	return inspector.InspectInterfaces(ctx, req)
81: }
82: 
83: func (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {
84: 	capturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, "packet capture")
85: 	if err != nil {
86: 		return nil, err
87: 	}
88: 	if err := c.requireLabName(); err != nil {
89: 		return nil, err
90: 	}
91: 
92: 	return capturer, nil
93: }

(End of file - total 93 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1965149de0011TO01T0g6xvEDd",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965127650017wFkuC8x5Fl7Gc",
  "callID": "call_7dff68a2c6fd46d396b56798",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/capture.go"
    },
    "output": "<path>/source/head/core/capture.go</path>\n<type>file</type>\n<content>\n1: package core\n2: \n3: import (\n4: \t\"context\"\n5: \t\"io\"\n6: \n7: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n8: \tclabtypes \"github.com/srl-labs/containerlab/types\"\n9: )\n10: \n11: // CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for\n12: // every running node, with the peer at the other end of each link. With Docker and Podman, the\n13: // interfaces come from the topology's links; lab runtimes list them through their packet\n14: // capturer.\n15: func (c *CLab) CaptureInterfaces(\n16: \tctx context.Context,\n17: \tnodeNames ...string,\n18: ) ([]clablabruntime.CaptureInterface, error) {\n19: \tif c.LabRuntime == nil {\n20: \t\treturn c.localCaptureInterfacesOf(ctx, nodeNames)\n21: \t}\n22: \n23: \tcapturer, err := c.packetCapturer()\n24: \tif err != nil {\n25: \t\treturn nil, err\n26: \t}\n27: \n28: \treturn capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{\n29: \t\tName:     c.Config.Name,\n30: \t\tNodes:    nodeNames,\n31: \t\tIdentity: c.labRuntimeIdentity,\n32: \t})\n33: }\n34: \n35: // Capture streams pcapng from lab link interfaces to w until req.Duration passed,\n36: // req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name\n37: // and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces\n38: // itself through packet sockets in the nodes' network namespaces, which needs root; lab\n39: // runtimes capture through their packet capturer.\n40: func (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {\n41: \tif c.LabRuntime == nil {\n42: \t\treturn c.captureLocal(ctx, req, w)\n43: \t}\n44: \n45: \tcapturer, err := c.packetCapturer()\n46: \tif err != nil {\n47: \t\treturn err\n48: \t}\n49: \n50: \tif req.Name == \"\" {\n51: \t\treq.Name = c.Config.Name\n52: \t}\n53: \tif req.Identity.IsZero() {\n54: \t\treq.Identity = c.labRuntimeIdentity\n55: \t}\n56: \n57: \treturn capturer.Capture(ctx, req, w)\n58: }\n59: \n60: // LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their\n61: // state, in the shape ListContainersInterfaces reports for local containers.\n62: func (c *CLab) LabRuntimeInterfaces(\n63: \tctx context.Context,\n64: \tnodeName string,\n65: ) ([]*clabtypes.ContainerInterfaces, error) {\n66: \tinspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](\n67: \t\tc, \"inspecting interfaces\")\n68: \tif err != nil {\n69: \t\treturn nil, err\n70: \t}\n71: \tif err := c.requireLabName(); err != nil {\n72: \t\treturn nil, err\n73: \t}\n74: \n75: \treq := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}\n76: \tif nodeName != \"\" {\n77: \t\treq.Nodes = []string{nodeName}\n78: \t}\n79: \n80: \treturn inspector.InspectInterfaces(ctx, req)\n81: }\n82: \n83: func (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {\n84: \tcapturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, \"packet capture\")\n85: \tif err != nil {\n86: \t\treturn nil, err\n87: \t}\n88: \tif err := c.requireLabName(); err != nil {\n89: \t\treturn nil, err\n90: \t}\n91: \n92: \treturn capturer, nil\n93: }\n\n(End of file - total 93 lines)\n</content>",
    "title": "source/head/core/capture.go",
    "metadata": {
      "preview": "package core\n\nimport (\n\t\"context\"\n\t\"io\"\n\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\tclabtypes \"github.com/srl-labs/containerlab/types\"\n)\n\n// CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for\n// every running node, with the peer at the other end of each link. With Docker and Podman, the\n// interfaces come from the topology's links; lab runtimes list them through their packet\n// capturer.\nfunc (c *CLab) CaptureInterfaces(\n\tctx context.Context,\n\tnodeNames ...string,\n) ([]clablabruntime.CaptureInterface, error) {\n\tif c.LabRuntime == nil {\n\t\treturn c.localCaptureInterfacesOf(ctx, nodeNames)",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/capture.go",
        "text": "package core\n\nimport (\n\t\"context\"\n\t\"io\"\n\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\tclabtypes \"github.com/srl-labs/containerlab/types\"\n)\n\n// CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for\n// every running node, with the peer at the other end of each link. With Docker and Podman, the\n// interfaces come from the topology's links; lab runtimes list them through their packet\n// capturer.\nfunc (c *CLab) CaptureInterfaces(\n\tctx context.Context,\n\tnodeNames ...string,\n) ([]clablabruntime.CaptureInterface, error) {\n\tif c.LabRuntime == nil {\n\t\treturn c.localCaptureInterfacesOf(ctx, nodeNames)\n\t}\n\n\tcapturer, err := c.packetCapturer()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{\n\t\tName:     c.Config.Name,\n\t\tNodes:    nodeNames,\n\t\tIdentity: c.labRuntimeIdentity,\n\t})\n}\n\n// Capture streams pcapng from lab link interfaces to w until req.Duration passed,\n// req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name\n// and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces\n// itself through packet sockets in the nodes' network namespaces, which needs root; lab\n// runtimes capture through their packet capturer.\nfunc (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {\n\tif c.LabRuntime == nil {\n\t\treturn c.captureLocal(ctx, req, w)\n\t}\n\n\tcapturer, err := c.packetCapturer()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif req.Name == \"\" {\n\t\treq.Name = c.Config.Name\n\t}\n\tif req.Identity.IsZero() {\n\t\treq.Identity = c.labRuntimeIdentity\n\t}\n\n\treturn capturer.Capture(ctx, req, w)\n}\n\n// LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their\n// state, in the shape ListContainersInterfaces reports for local containers.\nfunc (c *CLab) LabRuntimeInterfaces(\n\tctx context.Context,\n\tnodeName string,\n) ([]*clabtypes.ContainerInterfaces, error) {\n\tinspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](\n\t\tc, \"inspecting interfaces\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := c.requireLabName(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treq := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}\n\tif nodeName != \"\" {\n\t\treq.Nodes = []string{nodeName}\n\t}\n\n\treturn inspector.InspectInterfaces(ctx, req)\n}\n\nfunc (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {\n\tcapturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, \"packet capture\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := c.requireLabName(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn capturer, nil\n}",
        "lineStart": 1,
        "lineEnd": 93,
        "totalLines": 93,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523272162,
      "end": 1793523272167
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/core/capture_local.go"
}

Output

<path>/source/head/core/capture_local.go</path>
<type>file</type>
<content>
1: package core
2: 
3: import (
4: 	"context"
5: 	"fmt"
6: 	"io"
7: 	"slices"
8: 	"sort"
9: 	"strings"
10: 
11: 	clabcapture "github.com/srl-labs/containerlab/capture"
12: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
13: 	clablinks "github.com/srl-labs/containerlab/links"
14: 	clabnodes "github.com/srl-labs/containerlab/nodes"
15: 	clabruntime "github.com/srl-labs/containerlab/runtime"
16: )
17: 
18: // localCaptureInterface is a lab link interface of a node on this machine.
19: type localCaptureInterface struct {
20: 	node clabnodes.Node
21: 	info clablabruntime.CaptureInterface
22: }
23: 
24: // localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with
25: // the far end of each link, per node name. Host and management network endpoints are the far
26: // ends of links, not nodes to capture on.
27: func (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {
28: 	if len(c.Nodes) == 0 {
29: 		return nil, fmt.Errorf("the topology of lab %q is not available; capture reads the "+
30: 			"lab's links from it, pass it with --topo", c.Config.Name)
31: 	}
32: 	if len(c.Links) == 0 {
33: 		if err := c.ResolveLinks(); err != nil {
34: 			return nil, fmt.Errorf("failed to resolve the links of lab %q: %w", c.Config.Name, err)
35: 		}
36: 	}
37: 
38: 	indexes := make([]int, 0, len(c.Links))
39: 	for idx := range c.Links {
40: 		indexes = append(indexes, idx)
41: 	}
42: 	sort.Ints(indexes)
43: 
44: 	result := map[string][]localCaptureInterface{}
45: 	for _, idx := range indexes {
46: 		endpoints := c.Links[idx].GetEndpoints()
47: 		for epIdx, endpoint := range endpoints {
48: 			if endpoint.IsNodeless() || endpoint.IsRuntimeDiscovered() ||
49: 				endpoint.GetNode() == nil {
50: 				continue
51: 			}
52: 			name := endpoint.GetNode().GetShortName()
53: 			node, ok := c.Nodes[name]
54: 			if !ok {
55: 				continue
56: 			}
57: 
58: 			info := clablabruntime.CaptureInterface{
59: 				Node:      name,
60: 				Interface: endpoint.GetIfaceName(),
61: 			}
62: 			if alias := endpoint.GetIfaceAlias(); alias != info.Interface {
63: 				info.Alias = alias
64: 			}
65: 			if len(endpoints) == 2 {
66: 				peer := endpoints[1-epIdx]
67: 				info.PeerNode = capturePeerNode(peer)
68: 				info.PeerInterface = peer.GetIfaceDisplayName()
69: 			}
70: 
71: 			result[name] = append(result[name], localCaptureInterface{node: node, info: info})
72: 		}
73: 	}
74: 
75: 	return result, nil
76: }
77: 
78: // capturePeerNode names the node at the far end of a link: "host" for a host endpoint and
79: // "mgmt-net" for the management network, whose shared link nodes carry other names once a lab
80: // was deployed.
81: func capturePeerNode(peer clablinks.Endpoint) string {
82: 	if peer.IsNodeless() {
83: 		if _, ok := peer.(*clablinks.EndpointBridge); ok {
84: 			return string(clablinks.LinkTypeMgmtNet)
85: 		}
86: 
87: 		return string(clablinks.LinkTypeHost)
88: 	}
89: 	if peer.GetNode() == nil {
90: 		return ""
91: 	}
92: 
93: 	return peer.GetNode().GetShortName()
94: }
95: 
96: // lookupLocalNode finds a lab node by its topology name or its container name.
97: func (c *CLab) lookupLocalNode(name string) (clabnodes.Node, error) {
98: 	if node, ok := c.Nodes[name]; ok {
99: 		return node, nil
100: 	}
101: 	for _, node := range c.Nodes {
102: 		if node.Config().LongName == name {
103: 			return node, nil
104: 		}
105: 	}
106: 
107: 	names := make([]string, 0, len(c.Nodes))
108: 	for nodeName := range c.Nodes {
109: 		names = append(names, nodeName)
110: 	}
111: 	slices.Sort(names)
112: 
113: 	return nil, fmt.Errorf("node %q is not part of lab %q; nodes: %s", name, c.Config.Name,
114: 		strings.Join(names, ", "))
115: }
116: 
117: // nodeRuns reports whether a node's network namespace can be entered.
118: func nodeRuns(ctx context.Context, node clabnodes.Node) bool {
119: 	if node.Config().IsRootNamespaceBased {
120: 		return true
121: 	}
122: 
123: 	return clabruntime.ContainerHasJoinableNetns(node.GetContainerStatus(ctx))
124: }
125: 
126: // localCaptureInterfacesOf implements CaptureInterfaces for Docker and Podman: the requested
127: // nodes, or every running node.
128: func (c *CLab) localCaptureInterfacesOf(
129: 	ctx context.Context,
130: 	nodeNames []string,
131: ) ([]clablabruntime.CaptureInterface, error) {
132: 	if err := c.requireLabName(); err != nil {
133: 		return nil, err
134: 	}
135: 	byNode, err := c.localCaptureInterfaces()
136: 	if err != nil {
137: 		return nil, err
138: 	}
139: 
140: 	var nodes []clabnodes.Node
141: 	if len(nodeNames) == 0 {
142: 		for _, node := range c.Nodes {
143: 			if nodeRuns(ctx, node) {
144: 				nodes = append(nodes, node)
145: 			}
146: 		}
147: 	} else {
148: 		for _, name := range nodeNames {
149: 			node, err := c.lookupLocalNode(name)
150: 			if err != nil {
151: 				return nil, err
152: 			}
153: 			nodes = append(nodes, node)
154: 		}
155: 	}
156: 
157: 	result := make([]clablabruntime.CaptureInterface, 0)
158: 	seen := map[string]bool{}
159: 	for _, node := range nodes {
160: 		name := node.Config().ShortName
161: 		if seen[name] {
162: 			continue
163: 		}
164: 		seen[name] = true
165: 		for _, entry := range byNode[name] {
166: 			result = append(result, entry.info)
167: 		}
168: 	}
169: 	sortCaptureInterfaces(result)
170: 
171: 	return result, nil
172: }
173: 
174: func sortCaptureInterfaces(interfaces []clablabruntime.CaptureInterface) {
175: 	sort.SliceStable(interfaces, func(i, j int) bool {
176: 		if interfaces[i].Node != interfaces[j].Node {
177: 			return interfaces[i].Node < interfaces[j].Node
178: 		}
179: 
180: 		return interfaces[i].Interface < interfaces[j].Interface
181: 	})
182: }
183: 
184: // resolveLocalCaptureTargets checks every target against the node's link interfaces, by name or
185: // alias, and returns them in request order.
186: func (c *CLab) resolveLocalCaptureTargets(
187: 	targets []clablabruntime.CaptureTarget,
188: ) ([]clabcapture.LocalTarget, error) {
189: 	byNode, err := c.localCaptureInterfaces()
190: 	if err != nil {
191: 		return nil, err
192: 	}
193: 
194: 	resolved := make([]clabcapture.LocalTarget, 0, len(targets))
195: 	seen := map[string]bool{}
196: 	for _, target := range targets {
197: 		node, err := c.lookupLocalNode(target.Node)
198: 		if err != nil {
199: 			return nil, err
200: 		}
201: 		name := node.Config().ShortName
202: 
203: 		infos := make([]clablabruntime.CaptureInterface, 0, len(byNode[name]))
204: 		for _, entry := range byNode[name] {
205: 			infos = append(infos, entry.info)
206: 		}
207: 		sortCaptureInterfaces(infos)
208: 		info, ok := clabcapture.FindInterface(infos, target.Interface)
209: 		if !ok {
210: 			return nil, fmt.Errorf("interface %q of node %q is not a capturable link "+
211: 				"interface; capturable: %s", target.Interface, target.Node,
212: 				clabcapture.DescribeInterfaces(infos))
213: 		}
214: 
215: 		key := name + "\x00" + info.Interface
216: 		if seen[key] {
217: 			return nil, fmt.Errorf("interface %q of node %q is requested more than once",
218: 				info.Interface, target.Node)
219: 		}
220: 		seen[key] = true
221: 
222: 		resolved = append(resolved, clabcapture.LocalTarget{
223: 			Node:      name,
224: 			Interface: info.Interface,
225: 			Exec:      node.ExecFunction,
226: 		})
227: 	}
228: 
229: 	return resolved, nil
230: }
231: 
232: // captureLocal implements Capture for Docker and Podman through packet sockets in the nodes'
233: // network namespaces.
234: func (c *CLab) captureLocal(
235: 	ctx context.Context,
236: 	req clablabruntime.CaptureRequest,
237: 	w io.Writer,
238: ) error {
239: 	if err := c.requireLabName(); err != nil {
240: 		return err
241: 	}
242: 	if req.Name == "" {
243: 		req.Name = c.Config.Name
244: 	}
245: 	if err := clabcapture.ValidateRequest(&req); err != nil {
246: 		return err
247: 	}
248: 
249: 	targets, err := c.resolveLocalCaptureTargets(req.Targets)
250: 	if err != nil {
251: 		return err
252: 	}
253: 
254: 	return clabcapture.CaptureLocal(ctx, req, targets, w)
255: }

(End of file - total 255 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196514a02001nt9MlgzZgX1wbT",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965127650017wFkuC8x5Fl7Gc",
  "callID": "call_91b8a049ce8a42f08da1017c",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/capture_local.go"
    },
    "output": "<path>/source/head/core/capture_local.go</path>\n<type>file</type>\n<content>\n1: package core\n2: \n3: import (\n4: \t\"context\"\n5: \t\"fmt\"\n6: \t\"io\"\n7: \t\"slices\"\n8: \t\"sort\"\n9: \t\"strings\"\n10: \n11: \tclabcapture \"github.com/srl-labs/containerlab/capture\"\n12: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n13: \tclablinks \"github.com/srl-labs/containerlab/links\"\n14: \tclabnodes \"github.com/srl-labs/containerlab/nodes\"\n15: \tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n16: )\n17: \n18: // localCaptureInterface is a lab link interface of a node on this machine.\n19: type localCaptureInterface struct {\n20: \tnode clabnodes.Node\n21: \tinfo clablabruntime.CaptureInterface\n22: }\n23: \n24: // localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with\n25: // the far end of each link, per node name. Host and management network endpoints are the far\n26: // ends of links, not nodes to capture on.\n27: func (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {\n28: \tif len(c.Nodes) == 0 {\n29: \t\treturn nil, fmt.Errorf(\"the topology of lab %q is not available; capture reads the \"+\n30: \t\t\t\"lab's links from it, pass it with --topo\", c.Config.Name)\n31: \t}\n32: \tif len(c.Links) == 0 {\n33: \t\tif err := c.ResolveLinks(); err != nil {\n34: \t\t\treturn nil, fmt.Errorf(\"failed to resolve the links of lab %q: %w\", c.Config.Name, err)\n35: \t\t}\n36: \t}\n37: \n38: \tindexes := make([]int, 0, len(c.Links))\n39: \tfor idx := range c.Links {\n40: \t\tindexes = append(indexes, idx)\n41: \t}\n42: \tsort.Ints(indexes)\n43: \n44: \tresult := map[string][]localCaptureInterface{}\n45: \tfor _, idx := range indexes {\n46: \t\tendpoints := c.Links[idx].GetEndpoints()\n47: \t\tfor epIdx, endpoint := range endpoints {\n48: \t\t\tif endpoint.IsNodeless() || endpoint.IsRuntimeDiscovered() ||\n49: \t\t\t\tendpoint.GetNode() == nil {\n50: \t\t\t\tcontinue\n51: \t\t\t}\n52: \t\t\tname := endpoint.GetNode().GetShortName()\n53: \t\t\tnode, ok := c.Nodes[name]\n54: \t\t\tif !ok {\n55: \t\t\t\tcontinue\n56: \t\t\t}\n57: \n58: \t\t\tinfo := clablabruntime.CaptureInterface{\n59: \t\t\t\tNode:      name,\n60: \t\t\t\tInterface: endpoint.GetIfaceName(),\n61: \t\t\t}\n62: \t\t\tif alias := endpoint.GetIfaceAlias(); alias != info.Interface {\n63: \t\t\t\tinfo.Alias = alias\n64: \t\t\t}\n65: \t\t\tif len(endpoints) == 2 {\n66: \t\t\t\tpeer := endpoints[1-epIdx]\n67: \t\t\t\tinfo.PeerNode = capturePeerNode(peer)\n68: \t\t\t\tinfo.PeerInterface = peer.GetIfaceDisplayName()\n69: \t\t\t}\n70: \n71: \t\t\tresult[name] = append(result[name], localCaptureInterface{node: node, info: info})\n72: \t\t}\n73: \t}\n74: \n75: \treturn result, nil\n76: }\n77: \n78: // capturePeerNode names the node at the far end of a link: \"host\" for a host endpoint and\n79: // \"mgmt-net\" for the management network, whose shared link nodes carry other names once a lab\n80: // was deployed.\n81: func capturePeerNode(peer clablinks.Endpoint) string {\n82: \tif peer.IsNodeless() {\n83: \t\tif _, ok := peer.(*clablinks.EndpointBridge); ok {\n84: \t\t\treturn string(clablinks.LinkTypeMgmtNet)\n85: \t\t}\n86: \n87: \t\treturn string(clablinks.LinkTypeHost)\n88: \t}\n89: \tif peer.GetNode() == nil {\n90: \t\treturn \"\"\n91: \t}\n92: \n93: \treturn peer.GetNode().GetShortName()\n94: }\n95: \n96: // lookupLocalNode finds a lab node by its topology name or its container name.\n97: func (c *CLab) lookupLocalNode(name string) (clabnodes.Node, error) {\n98: \tif node, ok := c.Nodes[name]; ok {\n99: \t\treturn node, nil\n100: \t}\n101: \tfor _, node := range c.Nodes {\n102: \t\tif node.Config().LongName == name {\n103: \t\t\treturn node, nil\n104: \t\t}\n105: \t}\n106: \n107: \tnames := make([]string, 0, len(c.Nodes))\n108: \tfor nodeName := range c.Nodes {\n109: \t\tnames = append(names, nodeName)\n110: \t}\n111: \tslices.Sort(names)\n112: \n113: \treturn nil, fmt.Errorf(\"node %q is not part of lab %q; nodes: %s\", name, c.Config.Name,\n114: \t\tstrings.Join(names, \", \"))\n115: }\n116: \n117: // nodeRuns reports whether a node's network namespace can be entered.\n118: func nodeRuns(ctx context.Context, node clabnodes.Node) bool {\n119: \tif node.Config().IsRootNamespaceBased {\n120: \t\treturn true\n121: \t}\n122: \n123: \treturn clabruntime.ContainerHasJoinableNetns(node.GetContainerStatus(ctx))\n124: }\n125: \n126: // localCaptureInterfacesOf implements CaptureInterfaces for Docker and Podman: the requested\n127: // nodes, or every running node.\n128: func (c *CLab) localCaptureInterfacesOf(\n129: \tctx context.Context,\n130: \tnodeNames []string,\n131: ) ([]clablabruntime.CaptureInterface, error) {\n132: \tif err := c.requireLabName(); err != nil {\n133: \t\treturn nil, err\n134: \t}\n135: \tbyNode, err := c.localCaptureInterfaces()\n136: \tif err != nil {\n137: \t\treturn nil, err\n138: \t}\n139: \n140: \tvar nodes []clabnodes.Node\n141: \tif len(nodeNames) == 0 {\n142: \t\tfor _, node := range c.Nodes {\n143: \t\t\tif nodeRuns(ctx, node) {\n144: \t\t\t\tnodes = append(nodes, node)\n145: \t\t\t}\n146: \t\t}\n147: \t} else {\n148: \t\tfor _, name := range nodeNames {\n149: \t\t\tnode, err := c.lookupLocalNode(name)\n150: \t\t\tif err != nil {\n151: \t\t\t\treturn nil, err\n152: \t\t\t}\n153: \t\t\tnodes = append(nodes, node)\n154: \t\t}\n155: \t}\n156: \n157: \tresult := make([]clablabruntime.CaptureInterface, 0)\n158: \tseen := map[string]bool{}\n159: \tfor _, node := range nodes {\n160: \t\tname := node.Config().ShortName\n161: \t\tif seen[name] {\n162: \t\t\tcontinue\n163: \t\t}\n164: \t\tseen[name] = true\n165: \t\tfor _, entry := range byNode[name] {\n166: \t\t\tresult = append(result, entry.info)\n167: \t\t}\n168: \t}\n169: \tsortCaptureInterfaces(result)\n170: \n171: \treturn result, nil\n172: }\n173: \n174: func sortCaptureInterfaces(interfaces []clablabruntime.CaptureInterface) {\n175: \tsort.SliceStable(interfaces, func(i, j int) bool {\n176: \t\tif interfaces[i].Node != interfaces[j].Node {\n177: \t\t\treturn interfaces[i].Node < interfaces[j].Node\n178: \t\t}\n179: \n180: \t\treturn interfaces[i].Interface < interfaces[j].Interface\n181: \t})\n182: }\n183: \n184: // resolveLocalCaptureTargets checks every target against the node's link interfaces, by name or\n185: // alias, and returns them in request order.\n186: func (c *CLab) resolveLocalCaptureTargets(\n187: \ttargets []clablabruntime.CaptureTarget,\n188: ) ([]clabcapture.LocalTarget, error) {\n189: \tbyNode, err := c.localCaptureInterfaces()\n190: \tif err != nil {\n191: \t\treturn nil, err\n192: \t}\n193: \n194: \tresolved := make([]clabcapture.LocalTarget, 0, len(targets))\n195: \tseen := map[string]bool{}\n196: \tfor _, target := range targets {\n197: \t\tnode, err := c.lookupLocalNode(target.Node)\n198: \t\tif err != nil {\n199: \t\t\treturn nil, err\n200: \t\t}\n201: \t\tname := node.Config().ShortName\n202: \n203: \t\tinfos := make([]clablabruntime.CaptureInterface, 0, len(byNode[name]))\n204: \t\tfor _, entry := range byNode[name] {\n205: \t\t\tinfos = append(infos, entry.info)\n206: \t\t}\n207: \t\tsortCaptureInterfaces(infos)\n208: \t\tinfo, ok := clabcapture.FindInterface(infos, target.Interface)\n209: \t\tif !ok {\n210: \t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n211: \t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n212: \t\t\t\tclabcapture.DescribeInterfaces(infos))\n213: \t\t}\n214: \n215: \t\tkey := name + \"\\x00\" + info.Interface\n216: \t\tif seen[key] {\n217: \t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n218: \t\t\t\tinfo.Interface, target.Node)\n219: \t\t}\n220: \t\tseen[key] = true\n221: \n222: \t\tresolved = append(resolved, clabcapture.LocalTarget{\n223: \t\t\tNode:      name,\n224: \t\t\tInterface: info.Interface,\n225: \t\t\tExec:      node.ExecFunction,\n226: \t\t})\n227: \t}\n228: \n229: \treturn resolved, nil\n230: }\n231: \n232: // captureLocal implements Capture for Docker and Podman through packet sockets in the nodes'\n233: // network namespaces.\n234: func (c *CLab) captureLocal(\n235: \tctx context.Context,\n236: \treq clablabruntime.CaptureRequest,\n237: \tw io.Writer,\n238: ) error {\n239: \tif err := c.requireLabName(); err != nil {\n240: \t\treturn err\n241: \t}\n242: \tif req.Name == \"\" {\n243: \t\treq.Name = c.Config.Name\n244: \t}\n245: \tif err := clabcapture.ValidateRequest(&req); err != nil {\n246: \t\treturn err\n247: \t}\n248: \n249: \ttargets, err := c.resolveLocalCaptureTargets(req.Targets)\n250: \tif err != nil {\n251: \t\treturn err\n252: \t}\n253: \n254: \treturn clabcapture.CaptureLocal(ctx, req, targets, w)\n255: }\n\n(End of file - total 255 lines)\n</content>",
    "title": "source/head/core/capture_local.go",
    "metadata": {
      "preview": "package core\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"slices\"\n\t\"sort\"\n\t\"strings\"\n\n\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\tclablinks \"github.com/srl-labs/containerlab/links\"\n\tclabnodes \"github.com/srl-labs/containerlab/nodes\"\n\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n)\n\n// localCaptureInterface is a lab link interface of a node on this machine.\ntype localCaptureInterface struct {\n\tnode clabnodes.Node",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/capture_local.go",
        "text": "package core\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"slices\"\n\t\"sort\"\n\t\"strings\"\n\n\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\tclablinks \"github.com/srl-labs/containerlab/links\"\n\tclabnodes \"github.com/srl-labs/containerlab/nodes\"\n\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n)\n\n// localCaptureInterface is a lab link interface of a node on this machine.\ntype localCaptureInterface struct {\n\tnode clabnodes.Node\n\tinfo clablabruntime.CaptureInterface\n}\n\n// localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with\n// the far end of each link, per node name. Host and management network endpoints are the far\n// ends of links, not nodes to capture on.\nfunc (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {\n\tif len(c.Nodes) == 0 {\n\t\treturn nil, fmt.Errorf(\"the topology of lab %q is not available; capture reads the \"+\n\t\t\t\"lab's links from it, pass it with --topo\", c.Config.Name)\n\t}\n\tif len(c.Links) == 0 {\n\t\tif err := c.ResolveLinks(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to resolve the links of lab %q: %w\", c.Config.Name, err)\n\t\t}\n\t}\n\n\tindexes := make([]int, 0, len(c.Links))\n\tfor idx := range c.Links {\n\t\tindexes = append(indexes, idx)\n\t}\n\tsort.Ints(indexes)\n\n\tresult := map[string][]localCaptureInterface{}\n\tfor _, idx := range indexes {\n\t\tendpoints := c.Links[idx].GetEndpoints()\n\t\tfor epIdx, endpoint := range endpoints {\n\t\t\tif endpoint.IsNodeless() || endpoint.IsRuntimeDiscovered() ||\n\t\t\t\tendpoint.GetNode() == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tname := endpoint.GetNode().GetShortName()\n\t\t\tnode, ok := c.Nodes[name]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tinfo := clablabruntime.CaptureInterface{\n\t\t\t\tNode:      name,\n\t\t\t\tInterface: endpoint.GetIfaceName(),\n\t\t\t}\n\t\t\tif alias := endpoint.GetIfaceAlias(); alias != info.Interface {\n\t\t\t\tinfo.Alias = alias\n\t\t\t}\n\t\t\tif len(endpoints) == 2 {\n\t\t\t\tpeer := endpoints[1-epIdx]\n\t\t\t\tinfo.PeerNode = capturePeerNode(peer)\n\t\t\t\tinfo.PeerInterface = peer.GetIfaceDisplayName()\n\t\t\t}\n\n\t\t\tresult[name] = append(result[name], localCaptureInterface{node: node, info: info})\n\t\t}\n\t}\n\n\treturn result, nil\n}\n\n// capturePeerNode names the node at the far end of a link: \"host\" for a host endpoint and\n// \"mgmt-net\" for the management network, whose shared link nodes carry other names once a lab\n// was deployed.\nfunc capturePeerNode(peer clablinks.Endpoint) string {\n\tif peer.IsNodeless() {\n\t\tif _, ok := peer.(*clablinks.EndpointBridge); ok {\n\t\t\treturn string(clablinks.LinkTypeMgmtNet)\n\t\t}\n\n\t\treturn string(clablinks.LinkTypeHost)\n\t}\n\tif peer.GetNode() == nil {\n\t\treturn \"\"\n\t}\n\n\treturn peer.GetNode().GetShortName()\n}\n\n// lookupLocalNode finds a lab node by its topology name or its container name.\nfunc (c *CLab) lookupLocalNode(name string) (clabnodes.Node, error) {\n\tif node, ok := c.Nodes[name]; ok {\n\t\treturn node, nil\n\t}\n\tfor _, node := range c.Nodes {\n\t\tif node.Config().LongName == name {\n\t\t\treturn node, nil\n\t\t}\n\t}\n\n\tnames := make([]string, 0, len(c.Nodes))\n\tfor nodeName := range c.Nodes {\n\t\tnames = append(names, nodeName)\n\t}\n\tslices.Sort(names)\n\n\treturn nil, fmt.Errorf(\"node %q is not part of lab %q; nodes: %s\", name, c.Config.Name,\n\t\tstrings.Join(names, \", \"))\n}\n\n// nodeRuns reports whether a node's network namespace can be entered.\nfunc nodeRuns(ctx context.Context, node clabnodes.Node) bool {\n\tif node.Config().IsRootNamespaceBased {\n\t\treturn true\n\t}\n\n\treturn clabruntime.ContainerHasJoinableNetns(node.GetContainerStatus(ctx))\n}\n\n// localCaptureInterfacesOf implements CaptureInterfaces for Docker and Podman: the requested\n// nodes, or every running node.\nfunc (c *CLab) localCaptureInterfacesOf(\n\tctx context.Context,\n\tnodeNames []string,\n) ([]clablabruntime.CaptureInterface, error) {\n\tif err := c.requireLabName(); err != nil {\n\t\treturn nil, err\n\t}\n\tbyNode, err := c.localCaptureInterfaces()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar nodes []clabnodes.Node\n\tif len(nodeNames) == 0 {\n\t\tfor _, node := range c.Nodes {\n\t\t\tif nodeRuns(ctx, node) {\n\t\t\t\tnodes = append(nodes, node)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor _, name := range nodeNames {\n\t\t\tnode, err := c.lookupLocalNode(name)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tnodes = append(nodes, node)\n\t\t}\n\t}\n\n\tresult := make([]clablabruntime.CaptureInterface, 0)\n\tseen := map[string]bool{}\n\tfor _, node := range nodes {\n\t\tname := node.Config().ShortName\n\t\tif seen[name] {\n\t\t\tcontinue\n\t\t}\n\t\tseen[name] = true\n\t\tfor _, entry := range byNode[name] {\n\t\t\tresult = append(result, entry.info)\n\t\t}\n\t}\n\tsortCaptureInterfaces(result)\n\n\treturn result, nil\n}\n\nfunc sortCaptureInterfaces(interfaces []clablabruntime.CaptureInterface) {\n\tsort.SliceStable(interfaces, func(i, j int) bool {\n\t\tif interfaces[i].Node != interfaces[j].Node {\n\t\t\treturn interfaces[i].Node < interfaces[j].Node\n\t\t}\n\n\t\treturn interfaces[i].Interface < interfaces[j].Interface\n\t})\n}\n\n// resolveLocalCaptureTargets checks every target against the node's link interfaces, by name or\n// alias, and returns them in request order.\nfunc (c *CLab) resolveLocalCaptureTargets(\n\ttargets []clablabruntime.CaptureTarget,\n) ([]clabcapture.LocalTarget, error) {\n\tbyNode, err := c.localCaptureInterfaces()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresolved := make([]clabcapture.LocalTarget, 0, len(targets))\n\tseen := map[string]bool{}\n\tfor _, target := range targets {\n\t\tnode, err := c.lookupLocalNode(target.Node)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tname := node.Config().ShortName\n\n\t\tinfos := make([]clablabruntime.CaptureInterface, 0, len(byNode[name]))\n\t\tfor _, entry := range byNode[name] {\n\t\t\tinfos = append(infos, entry.info)\n\t\t}\n\t\tsortCaptureInterfaces(infos)\n\t\tinfo, ok := clabcapture.FindInterface(infos, target.Interface)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n\t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n\t\t\t\tclabcapture.DescribeInterfaces(infos))\n\t\t}\n\n\t\tkey := name + \"\\x00\" + info.Interface\n\t\tif seen[key] {\n\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n\t\t\t\tinfo.Interface, target.Node)\n\t\t}\n\t\tseen[key] = true\n\n\t\tresolved = append(resolved, clabcapture.LocalTarget{\n\t\t\tNode:      name,\n\t\t\tInterface: info.Interface,\n\t\t\tExec:      node.ExecFunction,\n\t\t})\n\t}\n\n\treturn resolved, nil\n}\n\n// captureLocal implements Capture for Docker and Podman through packet sockets in the nodes'\n// network namespaces.\nfunc (c *CLab) captureLocal(\n\tctx context.Context,\n\treq clablabruntime.CaptureRequest,\n\tw io.Writer,\n) error {\n\tif err := c.requireLabName(); err != nil {\n\t\treturn err\n\t}\n\tif req.Name == \"\" {\n\t\treq.Name = c.Config.Name\n\t}\n\tif err := clabcapture.ValidateRequest(&req); err != nil {\n\t\treturn err\n\t}\n\n\ttargets, err := c.resolveLocalCaptureTargets(req.Targets)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn clabcapture.CaptureLocal(ctx, req, targets, w)\n}",
        "lineStart": 1,
        "lineEnd": 255,
        "totalLines": 255,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523272197,
      "end": 1793523272214
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196514a18001sBbmcA2JKTzvlr",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965127650017wFkuC8x5Fl7Gc",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 51127,
    "input": 5897,
    "output": 65,
    "reasoning": 877,
    "cache": {
      "read": 44288,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1965127650017wFkuC8x5Fl7Gc",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523263333,
    "completed": 1793523272220
  },
  "parentID": "msg_19650e899001051OTPpm7MOch6",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 51127,
    "input": 5897,
    "output": 65,
    "reasoning": 877,
    "cache": {
      "read": 44288,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 18
step-start
{
  "type": "step-start",
  "id": "prt_1965152aa001BrOSpRqnuOmCRf",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196514a21001Ayu8dXKBiaV3GA"
}
Reasoning
Good. Now the biggest file: labruntime/clabernetes/capture.go (1202 lines). Let me read it. Also capture_interfaces.go and the diff in clabernetes.go and runtime.go.
Now the largest new file — the c9s runtime capture implementation.
read · completed

Input

{
  "filePath": "/source/head/labruntime/clabernetes/capture.go"
}

Output

<path>/source/head/labruntime/clabernetes/capture.go</path>
<type>file</type>
<content>
1: package clabernetes
2: 
3: import (
4: 	"bytes"
5: 	"context"
6: 	"encoding/json"
7: 	"errors"
8: 	"fmt"
9: 	"hash/fnv"
10: 	"io"
11: 	"os"
12: 	"sort"
13: 	"strconv"
14: 	"strings"
15: 	"sync"
16: 	"time"
17: 
18: 	"github.com/charmbracelet/log"
19: 	clabcapture "github.com/srl-labs/containerlab/capture"
20: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
21: 	"golang.org/x/sync/errgroup"
22: )
23: 
24: // The clabwire packet capture contract (clabernetes 0.11 or newer).
25: const (
26: 	clabwireContainer = "clabwire"
27: 	clabwireManager   = "/clabernetes/manager"
28: 	// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.
29: 	captureAuditSchema = "c9s.direct-packet-capture-audit/v1alpha1"
30: 
31: 	captureAuditStarted   = "Started"
32: 	captureAuditSucceeded = "Succeeded"
33: 	captureAuditFailed    = "Failed"
34: 	captureAuditDenied    = "Denied"
35: 
36: 	// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.
37: 	maxCaptureSegment = time.Hour
38: 	// maxClabwirePackets is the packet limit of a single clabwire capture.
39: 	maxClabwirePackets = 1_000_000
40: 	// maxCaptureOverlap is how long two chained segments run side by side.
41: 	maxCaptureOverlap = 10 * time.Second
42: 	// maxCaptureCutWindow is the half-width of the window around the cut in which packets of
43: 	// two segments are matched by content; it covers the difference between the timestamps
44: 	// two clabwire processes give the same packet.
45: 	maxCaptureCutWindow = 500 * time.Millisecond
46: 	// minCaptureSegment is the shortest segment the chain requests.
47: 	minCaptureSegment = 100 * time.Millisecond
48: 	// captureEndGrace is how long a capture with a duration waits for its last clabwire
49: 	// process to end after the duration passed.
50: 	captureEndGrace = 30 * time.Second
51: 	// captureStartRetries bounds the attempts to start a follow-up segment.
52: 	captureStartRetries = 3
53: 	// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was
54: 	// closed before the stream is cut.
55: 	captureStdinCloseGrace = 3 * time.Second
56: 	// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A
57: 	// Kubernetes exec does not stop its process when the stream ends, but it closes the
58: 	// process's stdin, so every capture runs with stdin attached and this flag.
59: 	clabwireStopOnStdinClose = "--stop-on-stdin-close"
60: 
61: 	// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests
62: 	// without hour-long captures.
63: 	envCaptureSegment = "CLAB_C9S_CAPTURE_SEGMENT"
64: 	// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets
65: 	// of other nodes stamped earlier but delivered later still go out before it.
66: 	defaultCaptureReorderWindow = 250 * time.Millisecond
67: 	// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.
68: 	// It is an internal knob, not a supported setting.
69: 	envCaptureReorderWindow = "CLAB_C9S_CAPTURE_REORDER_WINDOW"
70: )
71: 
72: // podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns
73: // a *labruntime.CommandExitError.
74: type podExecFunc func(
75: 	ctx context.Context,
76: 	namespace, pod, container string,
77: 	command []string,
78: 	stdin io.Reader,
79: 	stdout, stderr io.Writer,
80: ) error
81: 
82: // clabwireInterface is one entry of `packet-capture --list-interfaces`.
83: type clabwireInterface struct {
84: 	Node          string `json:"node"`
85: 	Interface     string `json:"interface"`
86: 	Alias         string `json:"alias,omitempty"`
87: 	PeerNode      string `json:"peerNode"`
88: 	PeerInterface string `json:"peerInterface"`
89: }
90: 
91: // captureAudit is one clabwire audit line.
92: type captureAudit struct {
93: 	SchemaVersion string    `json:"schemaVersion"`
94: 	Time          time.Time `json:"time"`
95: 	Status        string    `json:"status"`
96: 	NodeName      string    `json:"nodeName"`
97: 	Format        string    `json:"format"`
98: 	Reason        string    `json:"reason"`
99: 	Packets       int       `json:"packets"`
100: 	Interfaces    []struct {
101: 		Name    string `json:"name"`
102: 		ID      string `json:"id"`
103: 		Packets int    `json:"packets"`
104: 	} `json:"interfaces"`
105: }
106: 
107: func (r *Runtime) execInPodContainer() podExecFunc {
108: 	if r.podExec != nil {
109: 		return r.podExec
110: 	}
111: 
112: 	return r.streamPodExec
113: }
114: 
115: // captureSegmentLength is the length of one clabwire capture before the next takes over.
116: func (r *Runtime) captureSegmentLength() time.Duration {
117: 	if r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {
118: 		return r.captureSegment
119: 	}
120: 
121: 	return maxCaptureSegment
122: }
123: 
124: // captureReorderWindowLength is the reorder window of the merged stream; zero disables
125: // reordering.
126: func (r *Runtime) captureReorderWindowLength() time.Duration {
127: 	switch {
128: 	case r.captureReorderWindow < 0:
129: 		return 0
130: 	case r.captureReorderWindow > 0:
131: 		return r.captureReorderWindow
132: 	}
133: 
134: 	return defaultCaptureReorderWindow
135: }
136: 
137: // captureReorderWindowFromEnv reads the reorder window knob: unset or invalid keeps the
138: // default (0), "0" disables reordering (-1).
139: func captureReorderWindowFromEnv() time.Duration {
140: 	value, err := time.ParseDuration(os.Getenv(envCaptureReorderWindow))
141: 	switch {
142: 	case err != nil || value < 0:
143: 		return 0
144: 	case value == 0:
145: 		return -1
146: 	}
147: 
148: 	return value
149: }
150: 
151: func captureSegmentFromEnv() time.Duration {
152: 	value, err := time.ParseDuration(os.Getenv(envCaptureSegment))
153: 	if err != nil || value <= 0 {
154: 		return 0
155: 	}
156: 
157: 	return value
158: }
159: 
160: // CaptureInterfaces lists the capturable lab link interfaces of the requested nodes, or of every
161: // node, as clabwire reports them, with their peers. Node names are reported as the topology
162: // spells them.
163: func (r *Runtime) CaptureInterfaces(
164: 	ctx context.Context,
165: 	req clablabruntime.NodeRequest,
166: ) ([]clablabruntime.CaptureInterface, error) {
167: 	r, err := r.connect(ctx, req.Identity)
168: 	if err != nil {
169: 		return nil, err
170: 	}
171: 
172: 	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{
173: 		Name: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,
174: 	})
175: 	if err != nil {
176: 		return nil, err
177: 	}
178: 	if len(req.Nodes) == 0 {
179: 		// a lab-wide listing skips nodes that do not run
180: 		running := locations[:0]
181: 		for _, location := range locations {
182: 			if location.Pod != "" {
183: 				running = append(running, location)
184: 			}
185: 		}
186: 		locations = running
187: 	}
188: 
189: 	listed, err := r.listCaptureInterfaces(ctx, req.Name, locations)
190: 	if err != nil {
191: 		return nil, err
192: 	}
193: 	names, err := r.nodeDisplayNames(ctx, req.Name, locations)
194: 	if err != nil {
195: 		return nil, err
196: 	}
197: 
198: 	result := make([]clablabruntime.CaptureInterface, 0)
199: 	for _, location := range locations {
200: 		for _, entry := range listed[location.NodeName] {
201: 			result = append(result, clablabruntime.CaptureInterface{
202: 				Node:          names.display(entry.Node),
203: 				Interface:     entry.Interface,
204: 				Alias:         entry.Alias,
205: 				PeerNode:      names.display(entry.PeerNode),
206: 				PeerInterface: entry.PeerInterface,
207: 			})
208: 		}
209: 	}
210: 	sort.SliceStable(result, func(i, j int) bool {
211: 		if result[i].Node != result[j].Node {
212: 			return result[i].Node < result[j].Node
213: 		}
214: 
215: 		return result[i].Interface < result[j].Interface
216: 	})
217: 
218: 	return result, nil
219: }
220: 
221: // listCaptureInterfaces runs one --list-interfaces per pod and returns the entries per Node.
222: func (r *Runtime) listCaptureInterfaces(
223: 	ctx context.Context,
224: 	lab string,
225: 	locations []clablabruntime.NodeLocation,
226: ) (map[string][]clabwireInterface, error) {
227: 	pods := map[string]clablabruntime.NodeLocation{}
228: 	wanted := map[string]bool{}
229: 	for _, location := range locations {
230: 		if location.Pod == "" {
231: 			return nil, fmt.Errorf("c9s node %s/%s/%s has no pod; is it running?",
232: 				location.Namespace, lab, location.NodeName)
233: 		}
234: 		pods[location.Namespace+"/"+location.Pod] = location
235: 		wanted[location.NodeName] = true
236: 	}
237: 
238: 	var mu sync.Mutex
239: 	result := map[string][]clabwireInterface{}
240: 	group, groupCtx := errgroup.WithContext(ctx)
241: 	group.SetLimit(interfaceSampleWorkers)
242: 	exec := r.execInPodContainer()
243: 	for _, location := range pods {
244: 		group.Go(func() error {
245: 			var stdout, stderr bytes.Buffer
246: 			err := exec(groupCtx, location.Namespace, location.Pod, clabwireContainer,
247: 				[]string{clabwireManager, "node-runtime", "packet-capture", "--list-interfaces"},
248: 				nil, &stdout, &stderr)
249: 			if err != nil {
250: 				return fmt.Errorf("failed to list the capturable interfaces of pod %s/%s: %w%s",
251: 					location.Namespace, location.Pod, err, stderrSuffix(stderr.Bytes()))
252: 			}
253: 
254: 			var entries []clabwireInterface
255: 			if err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {
256: 				return fmt.Errorf("failed to parse the capturable interfaces of pod %s/%s: %w",
257: 					location.Namespace, location.Pod, err)
258: 			}
259: 
260: 			mu.Lock()
261: 			defer mu.Unlock()
262: 			for _, entry := range entries {
263: 				if wanted[entry.Node] {
264: 					result[entry.Node] = append(result[entry.Node], entry)
265: 				}
266: 			}
267: 
268: 			return nil
269: 		})
270: 	}
271: 	if err := group.Wait(); err != nil {
272: 		return nil, err
273: 	}
274: 
275: 	return result, nil
276: }
277: 
278: func stderrSuffix(stderr []byte) string {
279: 	text := strings.TrimSpace(string(stderr))
280: 	if text == "" {
281: 		return ""
282: 	}
283: 
284: 	return ": " + text
285: }
286: 
287: // nodeNames maps the node names the cluster carries to the names the topology file uses.
288: type nodeNames map[string]string
289: 
290: func (n nodeNames) display(name string) string {
291: 	if original := n[name]; original != "" {
292: 		return original
293: 	}
294: 
295: 	return name
296: }
297: 
298: // nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the
299: // lab's Nodes.
300: func (r *Runtime) nodeDisplayNames(
301: 	ctx context.Context,
302: 	lab string,
303: 	locations []clablabruntime.NodeLocation,
304: ) (nodeNames, error) {
305: 	names := nodeNames{}
306: 	if len(locations) == 0 {
307: 		return names, nil
308: 	}
309: 
310: 	nodes, err := r.nodesForTopology(ctx, lab, locations[0].Namespace)
311: 	if err != nil {
312: 		return nil, err
313: 	}
314: 	for idx := range nodes.Items {
315: 		if original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != "" {
316: 			names[nodes.Items[idx].GetName()] = original
317: 		}
318: 	}
319: 
320: 	return names, nil
321: }
322: 
323: // captureGroup is the part of a capture one clabwire process serves: the requested interfaces of
324: // one node, in one pod.
325: type captureGroup struct {
326: 	location clablabruntime.NodeLocation
327: 	display  string
328: 	// interfaces are the planned interface names, in the order the merged stream lists them.
329: 	interfaces []string
330: 	// ids are the merged interface IDs of interfaces.
331: 	ids []uint32
332: }
333: 
334: // resolvedCapture is a validated capture request.
335: type resolvedCapture struct {
336: 	groups []*captureGroup
337: 	// names are the merged interface names (<node>:<interface>), indexed by merged ID.
338: 	names []string
339: }
340: 
341: // resolveCaptureTargets locates every target node, checks every interface against the
342: // interfaces clabwire allows, and groups the targets per node.
343: func (r *Runtime) resolveCaptureTargets(
344: 	ctx context.Context,
345: 	req clablabruntime.CaptureRequest,
346: ) (*resolvedCapture, error) {
347: 	nodeOrder := make([]string, 0, len(req.Targets))
348: 	seenNodes := map[string]bool{}
349: 	for _, target := range req.Targets {
350: 		if !seenNodes[target.Node] {
351: 			seenNodes[target.Node] = true
352: 			nodeOrder = append(nodeOrder, target.Node)
353: 		}
354: 	}
355: 
356: 	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{
357: 		Name: req.Name, Namespace: req.Namespace, Nodes: nodeOrder, Identity: req.Identity,
358: 	})
359: 	if err != nil {
360: 		return nil, err
361: 	}
362: 	byRequest := make(map[string]clablabruntime.NodeLocation, len(nodeOrder))
363: 	for idx, name := range nodeOrder {
364: 		byRequest[name] = locations[idx]
365: 	}
366: 
367: 	listed, err := r.listCaptureInterfaces(ctx, req.Name, locations)
368: 	if err != nil {
369: 		return nil, err
370: 	}
371: 	names, err := r.nodeDisplayNames(ctx, req.Name, locations)
372: 	if err != nil {
373: 		return nil, err
374: 	}
375: 
376: 	resolved := &resolvedCapture{}
377: 	groups := map[string]*captureGroup{}
378: 	seen := map[string]bool{}
379: 	for _, target := range req.Targets {
380: 		location := byRequest[target.Node]
381: 		entry, ok := findCaptureInterface(listed[location.NodeName], target.Interface)
382: 		if !ok {
383: 			return nil, fmt.Errorf("interface %q of node %q is not a capturable link "+
384: 				"interface; capturable: %s", target.Interface, target.Node,
385: 				describeCaptureInterfaces(listed[location.NodeName]))
386: 		}
387: 
388: 		key := location.NodeName + "\x00" + entry.Interface
389: 		if seen[key] {
390: 			return nil, fmt.Errorf("interface %q of node %q is requested more than once",
391: 				entry.Interface, target.Node)
392: 		}
393: 		seen[key] = true
394: 
395: 		group := groups[location.NodeName]
396: 		if group == nil {
397: 			group = &captureGroup{
398: 				location: location,
399: 				display:  names.display(location.NodeName),
400: 			}
401: 			groups[location.NodeName] = group
402: 			resolved.groups = append(resolved.groups, group)
403: 		}
404: 
405: 		id := uint32(len(resolved.names)) //nolint:gosec // bounded by the targets
406: 		group.interfaces = append(group.interfaces, entry.Interface)
407: 		group.ids = append(group.ids, id)
408: 		resolved.names = append(resolved.names, group.display+":"+entry.Interface)
409: 	}
410: 
411: 	return resolved, nil
412: }
413: 
414: // findCaptureInterface matches a requested interface by its planned name or its alias.
415: func findCaptureInterface(entries []clabwireInterface, name string) (clabwireInterface, bool) {
416: 	for _, entry := range entries {
417: 		if entry.Interface == name {
418: 			return entry, true
419: 		}
420: 	}
421: 	for _, entry := range entries {
422: 		if entry.Alias != "" && entry.Alias == name {
423: 			return entry, true
424: 		}
425: 	}
426: 
427: 	return clabwireInterface{}, false
428: }
429: 
430: func describeCaptureInterfaces(entries []clabwireInterface) string {
431: 	if len(entries) == 0 {
432: 		return "none"
433: 	}
434: 
435: 	names := make([]string, 0, len(entries))
436: 	for _, entry := range entries {
437: 		name := entry.Interface
438: 		if entry.Alias != "" {
439: 			name += " (" + entry.Alias + ")"
440: 		}
441: 		names = append(names, name)
442: 	}
443: 
444: 	return strings.Join(names, ", ")
445: }
446: 
447: // Capture streams pcapng from lab link interfaces to w: one section, one Interface Description
448: // Block per target in request order named <node>:<interface>, then the packets of every target.
449: //
450: // Each node's interfaces are captured by one clabwire process in the node's pod. clabwire limits
451: // a capture to one hour, so a longer capture (or one without Duration) chains captures: the next
452: // one starts before the current one ends, and the stream switches at a cut in the overlap. See
453: // captureChain for how packets of the overlap are kept once.
454: //
455: // Packets go out in timestamp order across nodes, through a reorder buffer (captureReorder).
456: //
457: // Every clabwire process runs with stdin attached and --stop-on-stdin-close: a Kubernetes exec
458: // does not stop its process when the stream closes, so containerlab closes stdin whenever a
459: // segment ends (the capture ends, fails, its output fails, or a newer segment took over) and
460: // clabwire ends the capture itself.
461: //
462: // Capture returns when Duration has passed, PacketLimit packets were written, or ctx ends; an
463: // ended ctx is not an error. Every block reaches w in one write, so the stream is a valid capture
464: // whenever it stops. A clabwire Denied or Failed audit record is returned as an error.
465: func (r *Runtime) Capture(
466: 	ctx context.Context,
467: 	req clablabruntime.CaptureRequest,
468: 	w io.Writer,
469: ) error {
470: 	if err := clabcapture.ValidateRequest(&req); err != nil {
471: 		return err
472: 	}
473: 
474: 	r, err := r.connect(ctx, req.Identity)
475: 	if err != nil {
476: 		return err
477: 	}
478: 
479: 	resolved, err := r.resolveCaptureTargets(ctx, req)
480: 	if err != nil {
481: 		return err
482: 	}
483: 
484: 	captureCtx, stop := context.WithCancel(ctx)
485: 	defer stop()
486: 
487: 	out, err := clabcapture.NewOutput(w, resolved.names, req.SnapLength, req.PacketLimit,
488: 		r.captureReorderWindowLength(), stop)
489: 	if err != nil {
490: 		return err
491: 	}
492: 
493: 	run := &captureRun{
494: 		r:       r,
495: 		req:     req,
496: 		out:     out,
497: 		segment: r.captureSegmentLength(),
498: 	}
499: 	if req.Duration > 0 {
500: 		run.deadline = time.Now().Add(req.Duration)
501: 	}
502: 	run.overlap = min(maxCaptureOverlap, run.segment/3)
503: 	run.window = min(maxCaptureCutWindow, run.overlap/4)
504: 
505: 	if req.Duration > 0 {
506: 		// a clabwire process that does not end on its own does not hold the capture open
507: 		var cancelTimeout context.CancelFunc
508: 		captureCtx, cancelTimeout = context.WithTimeout(captureCtx,
509: 			req.Duration+run.overlap+captureEndGrace)
510: 		defer cancelTimeout()
511: 	}
512: 
513: 	group, groupCtx := errgroup.WithContext(captureCtx)
514: 	for _, captureGroup := range resolved.groups {
515: 		chain := &captureChain{capture: run, group: captureGroup}
516: 		group.Go(func() error {
517: 			return chain.run(groupCtx)
518: 		})
519: 	}
520: 
521: 	err = group.Wait()
522: 	if writeErr := out.Close(); writeErr != nil {
523: 		return writeErr
524: 	}
525: 	if err != nil && !(errors.Is(err, context.Canceled) && captureCtx.Err() != nil) {
526: 		return err
527: 	}
528: 
529: 	return nil
530: }
531: 
532: // captureRun is the state a capture's chains share.
533: type captureRun struct {
534: 	r   *Runtime
535: 	req clablabruntime.CaptureRequest
536: 	// out is the merged stream; it writes the packets of every chain in timestamp order and
537: 	// stops every chain once the packet limit is reached.
538: 	out *clabcapture.Output
539: 
540: 	segment  time.Duration
541: 	overlap  time.Duration
542: 	window   time.Duration
543: 	deadline time.Time
544: }
545: 
546: // emit writes a packet under its merged interface ID. It reports false once the packet limit is
547: // reached and the capture stops.
548: func (run *captureRun) emit(id uint32, packet *clabcapture.Packet) (bool, error) {
549: 	return run.out.Emit(id, packet)
550: }
551: 
552: func (run *captureRun) reportGap(gap clablabruntime.CaptureGap) {
553: 	clabcapture.ReportGap(run.req.OnGap, gap)
554: }
555: 
556: // captureSegment is one clabwire capture process of a chain.
557: type captureSegment struct {
558: 	index      int
559: 	localStart time.Time
560: 	duration   time.Duration
561: 	cancel     context.CancelFunc
562: 	// closeStdin closes the stdin of the segment's clabwire process, which ends it; it may be
563: 	// called any number of times.
564: 	closeStdin func()
565: 	// stopTimer closes stdin once the segment is no longer needed after a switch-over.
566: 	stopTimer *time.Timer
567: 	// started and ended are the pod-clock times of the Started and Succeeded audit records.
568: 	started time.Time
569: 	ended   time.Time
570: 	done    bool
571: }
572: 
573: func (s *captureSegment) plannedEnd() time.Time {
574: 	return s.started.Add(s.duration)
575: }
576: 
577: // segmentEvent is something a segment reported: a packet, an audit record, or its end.
578: type segmentEvent struct {
579: 	segment *captureSegment
580: 	packet  *clabcapture.Packet
581: 	audit   *captureAudit
582: 	done    bool
583: 	err     error
584: }
585: 
586: // captureChain runs the chained clabwire captures of one group.
587: //
588: // Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both
589: // capture the same packets for a while. clabwire stamps packets when it reads them, so two
590: // processes give the same packet timestamps a few microseconds apart, and timestamps alone
591: // cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by
592: // content close to the cut:
593: //
594: //  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is
595: //     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.
596: //  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the
597: //     content of what it wrote since segment k+1 started.
598: //  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped
599: //     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped
600: //     when segment k wrote the same bytes on the same interface, and every other one is written.
601: //     From then on segment k+1 streams live.
602: //
603: // Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its
604: // planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other
605: // nodes' later packets do not overtake them in the merged stream.
606: //
607: // W (500 ms, less for short test segments) covers the stamping difference. Identical frames on
608: // the same interface within W of the cut can be paired with each other, which can drop a true
609: // repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves
610: // a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.
611: type captureChain struct {
612: 	capture *captureRun
613: 	group   *captureGroup
614: 
615: 	events chan segmentEvent
616: 	wg     sync.WaitGroup
617: 
618: 	active *captureSegment
619: 	next   *captureSegment
620: 	// cut is the switch time between active and next, in nanoseconds; zero until known.
621: 	cut int64
622: 	// emitted remembers the content of the packets active wrote while next runs.
623: 	emitted map[uint64]int
624: 	// held are the packets of next until active ends.
625: 	held     []*clabcapture.Packet
626: 	segments int
627: 	retries  int
628: 	// final is set once no further segment is due.
629: 	final bool
630: 	// stopping is set once ctx ended: the segments are asked to end and what they still
631: 	// deliver is written.
632: 	stopping bool
633: }
634: 
635: // run runs the chain until its last segment ended. When ctx ends, it stops the segments and
636: // keeps writing the packets they read until then; a segment that does not end within
637: // captureStdinCloseGrace is cut.
638: func (c *captureChain) run(ctx context.Context) error {
639: 	c.events = make(chan segmentEvent, 256)
640: 	// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them
641: 	segmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
642: 	var abort *time.Timer
643: 	defer func() {
644: 		if abort != nil {
645: 			abort.Stop()
646: 		}
647: 		cancel()
648: 		c.drain()
649: 		c.capture.out.Release(c)
650: 	}()
651: 
652: 	c.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))
653: 	timer := time.NewTimer(c.nextStartIn())
654: 	defer timer.Stop()
655: 
656: 	done := ctx.Done()
657: 	for {
658: 		select {
659: 		case <-done:
660: 			done = nil
661: 			c.stop(timer)
662: 			abort = time.AfterFunc(captureStdinCloseGrace, cancel)
663: 		case <-segmentsCtx.Done():
664: 			return nil
665: 		case <-timer.C:
666: 			if c.next == nil && !c.final {
667: 				c.startNext(segmentsCtx)
668: 			}
669: 		case event := <-c.events:
670: 			stop, err := c.handle(segmentsCtx, event, timer)
671: 			if err != nil || stop {
672: 				return err
673: 			}
674: 		}
675: 	}
676: }
677: 
678: // stop ends the chain early, like a deadline would: no further segment starts and the running
679: // ones are asked to end. The chain then writes what they deliver until they ended.
680: func (c *captureChain) stop(timer *time.Timer) {
681: 	c.stopping = true
682: 	c.final = true
683: 	timer.Stop()
684: 	c.active.closeStdin()
685: 	if c.next != nil {
686: 		c.next.closeStdin()
687: 	}
688: }
689: 
690: // drain waits for the segment goroutines after the chain ended.
691: func (c *captureChain) drain() {
692: 	done := make(chan struct{})
693: 	go func() {
694: 		c.wg.Wait()
695: 		close(done)
696: 	}()
697: 	for {
698: 		select {
699: 		case <-done:
700: 			return
701: 		case <-c.events:
702: 		}
703: 	}
704: }
705: 
706: // segmentDuration is the requested duration of a segment starting now.
707: func (c *captureChain) segmentDuration(now time.Time) time.Duration {
708: 	duration := c.capture.segment
709: 	if !c.capture.deadline.IsZero() {
710: 		duration = min(duration, c.capture.deadline.Sub(now))
711: 	}
712: 
713: 	return max(duration, minCaptureSegment)
714: }
715: 
716: // nextStartIn is the time until the follow-up of the active segment is due. It marks the chain
717: // final when none is due.
718: func (c *captureChain) nextStartIn() time.Duration {
719: 	if c.stopping {
720: 		c.final = true
721: 		return maxCaptureSegment
722: 	}
723: 	activeEnd := c.active.localStart.Add(c.active.duration)
724: 	if !c.capture.deadline.IsZero() &&
725: 		!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {
726: 		c.final = true
727: 		return maxCaptureSegment
728: 	}
729: 	c.final = false
730: 
731: 	return max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)
732: }
733: 
734: func (c *captureChain) startNext(ctx context.Context) {
735: 	c.next = c.start(ctx, c.segmentDuration(time.Now()))
736: 	c.emitted = map[uint64]int{}
737: 	c.held = nil
738: 	c.cut = 0
739: }
740: 
741: func (c *captureChain) handle(
742: 	ctx context.Context,
743: 	event segmentEvent,
744: 	timer *time.Timer,
745: ) (bool, error) {
746: 	segment := event.segment
747: 
748: 	switch {
749: 	case event.audit != nil:
750: 		return false, c.handleAudit(segment, event.audit)
751: 	case event.packet != nil:
752: 		return c.handlePacket(segment, event.packet)
753: 	case event.done:
754: 		segment.done = true
755: 		if segment.stopTimer != nil {
756: 			segment.stopTimer.Stop()
757: 		}
758: 		if event.err != nil && !c.stopping {
759: 			if segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {
760: 				// the follow-up did not start; try again while the active one still runs
761: 				c.retries++
762: 				log.Warn("Capture follow-up segment failed to start, retrying",
763: 					"node", c.group.display, "error", event.err)
764: 				c.next = nil
765: 				resetTimer(timer, time.Second)
766: 
767: 				return false, nil
768: 			}
769: 
770: 			return true, fmt.Errorf("capture on c9s node %s/%s/%s failed: %w",
771: 				c.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)
772: 		}
773: 		if segment != c.active {
774: 			return false, nil
775: 		}
776: 
777: 		return c.switchSegments(ctx, timer)
778: 	}
779: 
780: 	return false, nil
781: }
782: 
783: func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {
784: 	switch audit.Status {
785: 	case captureAuditStarted:
786: 		segment.started = audit.Time
787: 		log.Debug("Capture segment started", "node", c.group.display, "segment", segment.index,
788: 			"interfaces", strings.Join(c.group.interfaces, ","), "duration", segment.duration)
789: 		if segment == c.next && !c.active.started.IsZero() {
790: 			c.setCut()
791: 		}
792: 		if segment == c.next {
793: 			c.retries = 0
794: 		}
795: 	case captureAuditSucceeded:
796: 		segment.ended = audit.Time
797: 		log.Debug("Capture segment succeeded", "node", c.group.display,
798: 			"segment", segment.index, "packets", audit.Packets)
799: 	case captureAuditDenied, captureAuditFailed:
800: 		return captureAuditError(c.group.display, audit)
801: 	}
802: 
803: 	return nil
804: }
805: 
806: // captureAuditError turns a Denied or Failed clabwire audit record into an error.
807: func captureAuditError(node string, audit *captureAudit) error {
808: 	verb := "failed"
809: 	if audit.Status == captureAuditDenied {
810: 		verb = "was denied"
811: 	}
812: 	interfaces := make([]string, 0, len(audit.Interfaces))
813: 	for _, intf := range audit.Interfaces {
814: 		interfaces = append(interfaces, intf.Name)
815: 	}
816: 
817: 	return fmt.Errorf("capture of %s on node %s %s by clabwire: %s",
818: 		strings.Join(interfaces, ","), node, verb, audit.Reason)
819: }
820: 
821: // setCut places the cut in the middle of the overlap of the active and the next segment, both
822: // measured on the pod clock.
823: func (c *captureChain) setCut() {
824: 	overlapStart := c.next.started
825: 	overlapEnd := c.active.plannedEnd()
826: 	if overlapEnd.Sub(overlapStart) < 2*c.capture.window {
827: 		// the overlap is too short to match packets around a cut: the switch is reported as a
828: 		// gap once the active segment ended
829: 		c.cut = 0
830: 		return
831: 	}
832: 	c.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()
833: 
834: 	window := c.capture.window.Nanoseconds()
835: 	// Packets the next segment holds back are stamped from T-W on: other chains' packets after
836: 	// that wait in the reorder buffer until the switch, so the merged stream stays in order.
837: 	c.capture.out.Hold(c, c.cut-window)
838: 
839: 	// The active segment only matters for packets stamped before T. Once the pod clock passed
840: 	// T+W, it is closed: packets it read until then are still delivered, and the ones it reads
841: 	// later are stamped after T and dropped anyway. The next segment's Started record was
842: 	// written on the pod clock no later than now, so the pod clock passes T+W no later than
843: 	// (T - Started + W) from now.
844: 	active := c.active
845: 	active.stopTimer = time.AfterFunc(
846: 		time.Duration(c.cut-c.next.started.UnixNano()+window), active.closeStdin)
847: }
848: 
849: func (c *captureChain) handlePacket(
850: 	segment *captureSegment,
851: 	packet *clabcapture.Packet,
852: ) (bool, error) {
853: 	switch segment {
854: 	case c.active:
855: 		if c.cut != 0 && packet.Timestamp >= c.cut {
856: 			return false, nil
857: 		}
858: 		if c.next != nil {
859: 			c.emitted[packetKey(packet)]++
860: 		}
861: 
862: 		return c.emit(packet)
863: 	case c.next:
864: 		c.held = append(c.held, packet)
865: 	}
866: 
867: 	return false, nil
868: }
869: 
870: func (c *captureChain) emit(packet *clabcapture.Packet) (bool, error) {
871: 	if int(packet.InterfaceID) >= len(c.group.ids) {
872: 		return true, fmt.Errorf("clabwire wrote a packet for interface %d of %d",
873: 			packet.InterfaceID, len(c.group.ids))
874: 	}
875: 	more, err := c.capture.emit(c.group.ids[packet.InterfaceID], packet)
876: 
877: 	return !more, err
878: }
879: 
880: // switchSegments makes the next segment the active one after the active one ended, writing the
881: // held packets of the next one that the active one did not write.
882: func (c *captureChain) switchSegments(ctx context.Context, timer *time.Timer) (bool, error) {
883: 	// the held packets are in the reorder buffer once this returns
884: 	defer c.capture.out.Release(c)
885: 
886: 	ended := c.active
887: 	if c.stopping && c.next != nil && c.next.started.IsZero() {
888: 		// the chain is stopping: a follow-up that has not started takes nothing over
889: 		c.next, c.held, c.emitted, c.cut = nil, nil, nil, 0
890: 	}
891: 	if c.final && c.next == nil {
892: 		return true, nil
893: 	}
894: 
895: 	if c.next == nil || c.next.started.IsZero() || c.cut == 0 {
896: 		from := ended.ended
897: 		if from.IsZero() {
898: 			from = ended.plannedEnd()
899: 		}
900: 		gap := clablabruntime.CaptureGap{
901: 			Node: c.group.display, Interfaces: c.group.interfaces, From: from,
902: 			Reason: "the follow-up capture did not overlap the previous one",
903: 		}
904: 		if c.next != nil && !c.next.started.IsZero() {
905: 			gap.To = c.next.started
906: 		}
907: 		c.capture.reportGap(gap)
908: 	}
909: 
910: 	if c.next != nil && c.next.done && !c.stopping {
911: 		// the follow-up already ended (it started too late to take over): keep what it
912: 		// captured and continue with a fresh segment
913: 		for _, packet := range c.held {
914: 			if stop, err := c.emit(packet); stop || err != nil {
915: 				return true, err
916: 			}
917: 		}
918: 		c.next, c.held, c.emitted, c.cut = nil, nil, nil, 0
919: 	}
920: 
921: 	if c.next == nil {
922: 		if !c.capture.deadline.IsZero() &&
923: 			!time.Now().Before(c.capture.deadline.Add(-c.capture.window)) {
924: 			return true, nil
925: 		}
926: 		c.active = c.start(ctx, c.segmentDuration(time.Now()))
927: 		resetTimer(timer, c.nextStartIn())
928: 
929: 		return false, nil
930: 	}
931: 
932: 	window := c.capture.window.Nanoseconds()
933: 	for _, packet := range c.held {
934: 		if c.cut != 0 {
935: 			if packet.Timestamp < c.cut-window {
936: 				continue
937: 			}
938: 			if packet.Timestamp < c.cut+window {
939: 				key := packetKey(packet)
940: 				if c.emitted[key] > 0 {
941: 					c.emitted[key]--
942: 					continue
943: 				}
944: 			}
945: 		}
946: 		if stop, err := c.emit(packet); stop || err != nil {
947: 			return true, err
948: 		}
949: 	}
950: 
951: 	c.active, c.next = c.next, nil
952: 	c.held, c.emitted, c.cut = nil, nil, 0
953: 	if c.active.done {
954: 		// the chain is stopping and the follow-up ended before the active one
955: 		return true, nil
956: 	}
957: 	resetTimer(timer, c.nextStartIn())
958: 
959: 	return false, nil
960: }
961: 
962: func resetTimer(timer *time.Timer, d time.Duration) {
963: 	if !timer.Stop() {
964: 		select {
965: 		case <-timer.C:
966: 		default:
967: 		}
968: 	}
969: 	timer.Reset(d)
970: }
971: 
972: // packetKey identifies a packet by its interface and content.
973: func packetKey(packet *clabcapture.Packet) uint64 {
974: 	hash := fnv.New64a()
975: 	var id [4]byte
976: 	id[0] = byte(packet.InterfaceID)
977: 	id[1] = byte(packet.InterfaceID >> 8)
978: 	_, _ = hash.Write(id[:])
979: 	_, _ = hash.Write(packet.Data)
980: 
981: 	return hash.Sum64()
982: }
983: 
984: // start runs one clabwire capture and reports its packets, audit records and end as events.
985: func (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {
986: 	segmentCtx, cancel := context.WithCancel(ctx)
987: 	stdinReader, stdinWriter := io.Pipe()
988: 	segment := &captureSegment{
989: 		index: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,
990: 		closeStdin: func() { _ = stdinWriter.Close() },
991: 	}
992: 	c.segments++
993: 
994: 	command := []string{
995: 		clabwireManager, "node-runtime", "packet-capture",
996: 		"--nodeName", c.group.location.NodeName,
997: 		"--format", "pcapng",
998: 		"--snapLength", strconv.Itoa(c.capture.req.SnapLength),
999: 		"--duration", duration.String(),
1000: 		clabwireStopOnStdinClose,
1001: 	}
1002: 	for _, name := range c.group.interfaces {
1003: 		command = append(command, "--interface", name)
1004: 	}
1005: 	if c.capture.req.PacketLimit > 0 {
1006: 		remaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()
1007: 		command = append(command, "--packetLimit",
1008: 			strconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))
1009: 	}
1010: 
1011: 	send := func(event segmentEvent) {
1012: 		event.segment = segment
1013: 		select {
1014: 		case c.events <- event:
1015: 		case <-segmentCtx.Done():
1016: 		}
1017: 	}
1018: 
1019: 	stdoutReader, stdoutWriter := io.Pipe()
1020: 	stderr := &auditLineWriter{send: func(audit *captureAudit) { send(segmentEvent{audit: audit}) }}
1021: 
1022: 	// The exec outlives the segment's context by up to captureStdinCloseGrace: when the segment
1023: 	// ends for any reason (the capture is cancelled or failed, the output failed, or a newer
1024: 	// segment took over), its stdin is closed first so clabwire ends on its own, and the stream
1025: 	// is cut only if it does not.
1026: 	execCtx, cancelExec := context.WithCancel(context.WithoutCancel(segmentCtx))
1027: 	execDone := make(chan struct{})
1028: 
1029: 	c.wg.Add(3)
1030: 	readDone := make(chan error, 1)
1031: 	go func() {
1032: 		defer c.wg.Done()
1033: 		readDone <- c.readSegment(stdoutReader, func(packet *clabcapture.Packet) {
1034: 			send(segmentEvent{packet: packet})
1035: 		})
1036: 		_, _ = io.Copy(io.Discard, stdoutReader)
1037: 	}()
1038: 	go func() {
1039: 		defer c.wg.Done()
1040: 		select {
1041: 		case <-execDone:
1042: 			return
1043: 		case <-segmentCtx.Done():
1044: 		}
1045: 		segment.closeStdin()
1046: 		grace := time.NewTimer(captureStdinCloseGrace)
1047: 		defer grace.Stop()
1048: 		select {
1049: 		case <-execDone:
1050: 		case <-grace.C:
1051: 			log.Debug("Capture segment did not end after its stdin closed, cutting the stream",
1052: 				"node", c.group.display, "segment", segment.index)
1053: 			cancelExec()
1054: 		}
1055: 	}()
1056: 	go func() {
1057: 		defer c.wg.Done()
1058: 		defer cancel()
1059: 		defer cancelExec()
1060: 
1061: 		err := c.capture.r.execInPodContainer()(execCtx, c.group.location.Namespace,
1062: 			c.group.location.Pod, clabwireContainer, command, stdinReader, stdoutWriter, stderr)
1063: 		close(execDone)
1064: 		// the process ended: release the stdin copy of the exec stream
1065: 		segment.closeStdin()
1066: 		_ = stdoutWriter.Close()
1067: 		readErr := <-readDone
1068: 		stderr.flush()
1069: 		if err == nil && readErr != nil {
1070: 			err = readErr
1071: 		}
1072: 		if err != nil && stderr.text() != "" {
1073: 			if unsupported := unsupportedClabwire(
1074: 				c.group.location,
1075: 				stderr.text(),
1076: 			); unsupported != nil {
1077: 				err = unsupported
1078: 			} else {
1079: 				err = fmt.Errorf("%w: %s", err, stderr.text())
1080: 			}
1081: 		}
1082: 		send(segmentEvent{done: true, err: err})
1083: 	}()
1084: 
1085: 	return segment
1086: }
1087: 
1088: // unsupportedClabwire recognizes a clabwire that rejects --stop-on-stdin-close, which every
1089: // capture passes: its release predates the capture contract the runtime needs.
1090: func unsupportedClabwire(location clablabruntime.NodeLocation, stderr string) error {
1091: 	if !strings.Contains(stderr, "flag provided but not defined") ||
1092: 		!strings.Contains(stderr, strings.TrimPrefix(clabwireStopOnStdinClose, "-")) {
1093: 		return nil
1094: 	}
1095: 
1096: 	return &unsupportedClabernetesError{reason: fmt.Sprintf(
1097: 		"clabwire in pod %s/%s does not accept packet-capture %s",
1098: 		location.Namespace, location.Pod, clabwireStopOnStdinClose)}
1099: }
1100: 
1101: // readSegment checks that a segment's interfaces are the requested ones and passes its packets
1102: // on with the segment's interface index.
1103: func (c *captureChain) readSegment(stdout io.Reader, packet func(*clabcapture.Packet)) error {
1104: 	reader := clabcapture.NewReader(stdout)
1105: 	interfaces := 0
1106: 	for {
1107: 		event, err := reader.Next()
1108: 		if errors.Is(err, io.EOF) {
1109: 			return nil
1110: 		}
1111: 		if errors.Is(err, io.ErrUnexpectedEOF) {
1112: 			// the process was stopped inside a block
1113: 			return nil
1114: 		}
1115: 		if err != nil {
1116: 			return fmt.Errorf("failed to read the clabwire capture: %w", err)
1117: 		}
1118: 		if event.Interface != nil {
1119: 			if interfaces >= len(c.group.interfaces) ||
1120: 				event.Interface.Name != c.group.interfaces[interfaces] {
1121: 				return fmt.Errorf("clabwire described interface %q, want %s in order",
1122: 					event.Interface.Name, strings.Join(c.group.interfaces, ", "))
1123: 			}
1124: 			interfaces++
1125: 			continue
1126: 		}
1127: 		if event.Packet != nil {
1128: 			packet(event.Packet)
1129: 		}
1130: 	}
1131: }
1132: 
1133: // auditLineWriter parses clabwire's stderr: audit records go to send, other lines are kept for
1134: // error messages.
1135: type auditLineWriter struct {
1136: 	send func(*captureAudit)
1137: 
1138: 	mu      sync.Mutex
1139: 	partial []byte
1140: 	other   []string
1141: }
1142: 
1143: func (w *auditLineWriter) Write(data []byte) (int, error) {
1144: 	w.mu.Lock()
1145: 	w.partial = append(w.partial, data...)
1146: 	var lines [][]byte
1147: 	for {
1148: 		idx := bytes.IndexByte(w.partial, '\n')
1149: 		if idx < 0 {
1150: 			break
1151: 		}
1152: 		lines = append(lines, append([]byte(nil), w.partial[:idx]...))
1153: 		w.partial = w.partial[idx+1:]
1154: 	}
1155: 	w.mu.Unlock()
1156: 
1157: 	for _, line := range lines {
1158: 		w.line(line)
1159: 	}
1160: 
1161: 	return len(data), nil
1162: }
1163: 
1164: func (w *auditLineWriter) flush() {
1165: 	w.mu.Lock()
1166: 	line := w.partial
1167: 	w.partial = nil
1168: 	w.mu.Unlock()
1169: 	if len(bytes.TrimSpace(line)) != 0 {
1170: 		w.line(line)
1171: 	}
1172: }
1173: 
1174: func (w *auditLineWriter) line(line []byte) {
1175: 	line = bytes.TrimSpace(line)
1176: 	if len(line) == 0 {
1177: 		return
1178: 	}
1179: 
1180: 	var audit captureAudit
1181: 	if err := json.Unmarshal(
1182: 		line,
1183: 		&audit,
1184: 	); err == nil &&
1185: 		audit.SchemaVersion == captureAuditSchema {
1186: 		w.send(&audit)
1187: 		return
1188: 	}
1189: 
1190: 	w.mu.Lock()
1191: 	defer w.mu.Unlock()
1192: 	if len(w.other) < 20 {
1193: 		w.other = append(w.other, string(line))
1194: 	}
1195: }
1196: 
1197: func (w *auditLineWriter) text() string {
1198: 	w.mu.Lock()
1199: 	defer w.mu.Unlock()
1200: 
1201: 	return strings.Join(w.other, "; ")
1202: }

(End of file - total 1202 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1965153da001yVkgd91qan4Kmn",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196514a21001Ayu8dXKBiaV3GA",
  "callID": "call_1a3f5bd7f65547008f4540b4",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/capture.go"
    },
    "output": "<path>/source/head/labruntime/clabernetes/capture.go</path>\n<type>file</type>\n<content>\n1: package clabernetes\n2: \n3: import (\n4: \t\"bytes\"\n5: \t\"context\"\n6: \t\"encoding/json\"\n7: \t\"errors\"\n8: \t\"fmt\"\n9: \t\"hash/fnv\"\n10: \t\"io\"\n11: \t\"os\"\n12: \t\"sort\"\n13: \t\"strconv\"\n14: \t\"strings\"\n15: \t\"sync\"\n16: \t\"time\"\n17: \n18: \t\"github.com/charmbracelet/log\"\n19: \tclabcapture \"github.com/srl-labs/containerlab/capture\"\n20: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n21: \t\"golang.org/x/sync/errgroup\"\n22: )\n23: \n24: // The clabwire packet capture contract (clabernetes 0.11 or newer).\n25: const (\n26: \tclabwireContainer = \"clabwire\"\n27: \tclabwireManager   = \"/clabernetes/manager\"\n28: \t// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.\n29: \tcaptureAuditSchema = \"c9s.direct-packet-capture-audit/v1alpha1\"\n30: \n31: \tcaptureAuditStarted   = \"Started\"\n32: \tcaptureAuditSucceeded = \"Succeeded\"\n33: \tcaptureAuditFailed    = \"Failed\"\n34: \tcaptureAuditDenied    = \"Denied\"\n35: \n36: \t// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.\n37: \tmaxCaptureSegment = time.Hour\n38: \t// maxClabwirePackets is the packet limit of a single clabwire capture.\n39: \tmaxClabwirePackets = 1_000_000\n40: \t// maxCaptureOverlap is how long two chained segments run side by side.\n41: \tmaxCaptureOverlap = 10 * time.Second\n42: \t// maxCaptureCutWindow is the half-width of the window around the cut in which packets of\n43: \t// two segments are matched by content; it covers the difference between the timestamps\n44: \t// two clabwire processes give the same packet.\n45: \tmaxCaptureCutWindow = 500 * time.Millisecond\n46: \t// minCaptureSegment is the shortest segment the chain requests.\n47: \tminCaptureSegment = 100 * time.Millisecond\n48: \t// captureEndGrace is how long a capture with a duration waits for its last clabwire\n49: \t// process to end after the duration passed.\n50: \tcaptureEndGrace = 30 * time.Second\n51: \t// captureStartRetries bounds the attempts to start a follow-up segment.\n52: \tcaptureStartRetries = 3\n53: \t// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was\n54: \t// closed before the stream is cut.\n55: \tcaptureStdinCloseGrace = 3 * time.Second\n56: \t// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A\n57: \t// Kubernetes exec does not stop its process when the stream ends, but it closes the\n58: \t// process's stdin, so every capture runs with stdin attached and this flag.\n59: \tclabwireStopOnStdinClose = \"--stop-on-stdin-close\"\n60: \n61: \t// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests\n62: \t// without hour-long captures.\n63: \tenvCaptureSegment = \"CLAB_C9S_CAPTURE_SEGMENT\"\n64: \t// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets\n65: \t// of other nodes stamped earlier but delivered later still go out before it.\n66: \tdefaultCaptureReorderWindow = 250 * time.Millisecond\n67: \t// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.\n68: \t// It is an internal knob, not a supported setting.\n69: \tenvCaptureReorderWindow = \"CLAB_C9S_CAPTURE_REORDER_WINDOW\"\n70: )\n71: \n72: // podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns\n73: // a *labruntime.CommandExitError.\n74: type podExecFunc func(\n75: \tctx context.Context,\n76: \tnamespace, pod, container string,\n77: \tcommand []string,\n78: \tstdin io.Reader,\n79: \tstdout, stderr io.Writer,\n80: ) error\n81: \n82: // clabwireInterface is one entry of `packet-capture --list-interfaces`.\n83: type clabwireInterface struct {\n84: \tNode          string `json:\"node\"`\n85: \tInterface     string `json:\"interface\"`\n86: \tAlias         string `json:\"alias,omitempty\"`\n87: \tPeerNode      string `json:\"peerNode\"`\n88: \tPeerInterface string `json:\"peerInterface\"`\n89: }\n90: \n91: // captureAudit is one clabwire audit line.\n92: type captureAudit struct {\n93: \tSchemaVersion string    `json:\"schemaVersion\"`\n94: \tTime          time.Time `json:\"time\"`\n95: \tStatus        string    `json:\"status\"`\n96: \tNodeName      string    `json:\"nodeName\"`\n97: \tFormat        string    `json:\"format\"`\n98: \tReason        string    `json:\"reason\"`\n99: \tPackets       int       `json:\"packets\"`\n100: \tInterfaces    []struct {\n101: \t\tName    string `json:\"name\"`\n102: \t\tID      string `json:\"id\"`\n103: \t\tPackets int    `json:\"packets\"`\n104: \t} `json:\"interfaces\"`\n105: }\n106: \n107: func (r *Runtime) execInPodContainer() podExecFunc {\n108: \tif r.podExec != nil {\n109: \t\treturn r.podExec\n110: \t}\n111: \n112: \treturn r.streamPodExec\n113: }\n114: \n115: // captureSegmentLength is the length of one clabwire capture before the next takes over.\n116: func (r *Runtime) captureSegmentLength() time.Duration {\n117: \tif r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {\n118: \t\treturn r.captureSegment\n119: \t}\n120: \n121: \treturn maxCaptureSegment\n122: }\n123: \n124: // captureReorderWindowLength is the reorder window of the merged stream; zero disables\n125: // reordering.\n126: func (r *Runtime) captureReorderWindowLength() time.Duration {\n127: \tswitch {\n128: \tcase r.captureReorderWindow < 0:\n129: \t\treturn 0\n130: \tcase r.captureReorderWindow > 0:\n131: \t\treturn r.captureReorderWindow\n132: \t}\n133: \n134: \treturn defaultCaptureReorderWindow\n135: }\n136: \n137: // captureReorderWindowFromEnv reads the reorder window knob: unset or invalid keeps the\n138: // default (0), \"0\" disables reordering (-1).\n139: func captureReorderWindowFromEnv() time.Duration {\n140: \tvalue, err := time.ParseDuration(os.Getenv(envCaptureReorderWindow))\n141: \tswitch {\n142: \tcase err != nil || value < 0:\n143: \t\treturn 0\n144: \tcase value == 0:\n145: \t\treturn -1\n146: \t}\n147: \n148: \treturn value\n149: }\n150: \n151: func captureSegmentFromEnv() time.Duration {\n152: \tvalue, err := time.ParseDuration(os.Getenv(envCaptureSegment))\n153: \tif err != nil || value <= 0 {\n154: \t\treturn 0\n155: \t}\n156: \n157: \treturn value\n158: }\n159: \n160: // CaptureInterfaces lists the capturable lab link interfaces of the requested nodes, or of every\n161: // node, as clabwire reports them, with their peers. Node names are reported as the topology\n162: // spells them.\n163: func (r *Runtime) CaptureInterfaces(\n164: \tctx context.Context,\n165: \treq clablabruntime.NodeRequest,\n166: ) ([]clablabruntime.CaptureInterface, error) {\n167: \tr, err := r.connect(ctx, req.Identity)\n168: \tif err != nil {\n169: \t\treturn nil, err\n170: \t}\n171: \n172: \tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n173: \t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n174: \t})\n175: \tif err != nil {\n176: \t\treturn nil, err\n177: \t}\n178: \tif len(req.Nodes) == 0 {\n179: \t\t// a lab-wide listing skips nodes that do not run\n180: \t\trunning := locations[:0]\n181: \t\tfor _, location := range locations {\n182: \t\t\tif location.Pod != \"\" {\n183: \t\t\t\trunning = append(running, location)\n184: \t\t\t}\n185: \t\t}\n186: \t\tlocations = running\n187: \t}\n188: \n189: \tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n190: \tif err != nil {\n191: \t\treturn nil, err\n192: \t}\n193: \tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n194: \tif err != nil {\n195: \t\treturn nil, err\n196: \t}\n197: \n198: \tresult := make([]clablabruntime.CaptureInterface, 0)\n199: \tfor _, location := range locations {\n200: \t\tfor _, entry := range listed[location.NodeName] {\n201: \t\t\tresult = append(result, clablabruntime.CaptureInterface{\n202: \t\t\t\tNode:          names.display(entry.Node),\n203: \t\t\t\tInterface:     entry.Interface,\n204: \t\t\t\tAlias:         entry.Alias,\n205: \t\t\t\tPeerNode:      names.display(entry.PeerNode),\n206: \t\t\t\tPeerInterface: entry.PeerInterface,\n207: \t\t\t})\n208: \t\t}\n209: \t}\n210: \tsort.SliceStable(result, func(i, j int) bool {\n211: \t\tif result[i].Node != result[j].Node {\n212: \t\t\treturn result[i].Node < result[j].Node\n213: \t\t}\n214: \n215: \t\treturn result[i].Interface < result[j].Interface\n216: \t})\n217: \n218: \treturn result, nil\n219: }\n220: \n221: // listCaptureInterfaces runs one --list-interfaces per pod and returns the entries per Node.\n222: func (r *Runtime) listCaptureInterfaces(\n223: \tctx context.Context,\n224: \tlab string,\n225: \tlocations []clablabruntime.NodeLocation,\n226: ) (map[string][]clabwireInterface, error) {\n227: \tpods := map[string]clablabruntime.NodeLocation{}\n228: \twanted := map[string]bool{}\n229: \tfor _, location := range locations {\n230: \t\tif location.Pod == \"\" {\n231: \t\t\treturn nil, fmt.Errorf(\"c9s node %s/%s/%s has no pod; is it running?\",\n232: \t\t\t\tlocation.Namespace, lab, location.NodeName)\n233: \t\t}\n234: \t\tpods[location.Namespace+\"/\"+location.Pod] = location\n235: \t\twanted[location.NodeName] = true\n236: \t}\n237: \n238: \tvar mu sync.Mutex\n239: \tresult := map[string][]clabwireInterface{}\n240: \tgroup, groupCtx := errgroup.WithContext(ctx)\n241: \tgroup.SetLimit(interfaceSampleWorkers)\n242: \texec := r.execInPodContainer()\n243: \tfor _, location := range pods {\n244: \t\tgroup.Go(func() error {\n245: \t\t\tvar stdout, stderr bytes.Buffer\n246: \t\t\terr := exec(groupCtx, location.Namespace, location.Pod, clabwireContainer,\n247: \t\t\t\t[]string{clabwireManager, \"node-runtime\", \"packet-capture\", \"--list-interfaces\"},\n248: \t\t\t\tnil, &stdout, &stderr)\n249: \t\t\tif err != nil {\n250: \t\t\t\treturn fmt.Errorf(\"failed to list the capturable interfaces of pod %s/%s: %w%s\",\n251: \t\t\t\t\tlocation.Namespace, location.Pod, err, stderrSuffix(stderr.Bytes()))\n252: \t\t\t}\n253: \n254: \t\t\tvar entries []clabwireInterface\n255: \t\t\tif err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {\n256: \t\t\t\treturn fmt.Errorf(\"failed to parse the capturable interfaces of pod %s/%s: %w\",\n257: \t\t\t\t\tlocation.Namespace, location.Pod, err)\n258: \t\t\t}\n259: \n260: \t\t\tmu.Lock()\n261: \t\t\tdefer mu.Unlock()\n262: \t\t\tfor _, entry := range entries {\n263: \t\t\t\tif wanted[entry.Node] {\n264: \t\t\t\t\tresult[entry.Node] = append(result[entry.Node], entry)\n265: \t\t\t\t}\n266: \t\t\t}\n267: \n268: \t\t\treturn nil\n269: \t\t})\n270: \t}\n271: \tif err := group.Wait(); err != nil {\n272: \t\treturn nil, err\n273: \t}\n274: \n275: \treturn result, nil\n276: }\n277: \n278: func stderrSuffix(stderr []byte) string {\n279: \ttext := strings.TrimSpace(string(stderr))\n280: \tif text == \"\" {\n281: \t\treturn \"\"\n282: \t}\n283: \n284: \treturn \": \" + text\n285: }\n286: \n287: // nodeNames maps the node names the cluster carries to the names the topology file uses.\n288: type nodeNames map[string]string\n289: \n290: func (n nodeNames) display(name string) string {\n291: \tif original := n[name]; original != \"\" {\n292: \t\treturn original\n293: \t}\n294: \n295: \treturn name\n296: }\n297: \n298: // nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the\n299: // lab's Nodes.\n300: func (r *Runtime) nodeDisplayNames(\n301: \tctx context.Context,\n302: \tlab string,\n303: \tlocations []clablabruntime.NodeLocation,\n304: ) (nodeNames, error) {\n305: \tnames := nodeNames{}\n306: \tif len(locations) == 0 {\n307: \t\treturn names, nil\n308: \t}\n309: \n310: \tnodes, err := r.nodesForTopology(ctx, lab, locations[0].Namespace)\n311: \tif err != nil {\n312: \t\treturn nil, err\n313: \t}\n314: \tfor idx := range nodes.Items {\n315: \t\tif original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != \"\" {\n316: \t\t\tnames[nodes.Items[idx].GetName()] = original\n317: \t\t}\n318: \t}\n319: \n320: \treturn names, nil\n321: }\n322: \n323: // captureGroup is the part of a capture one clabwire process serves: the requested interfaces of\n324: // one node, in one pod.\n325: type captureGroup struct {\n326: \tlocation clablabruntime.NodeLocation\n327: \tdisplay  string\n328: \t// interfaces are the planned interface names, in the order the merged stream lists them.\n329: \tinterfaces []string\n330: \t// ids are the merged interface IDs of interfaces.\n331: \tids []uint32\n332: }\n333: \n334: // resolvedCapture is a validated capture request.\n335: type resolvedCapture struct {\n336: \tgroups []*captureGroup\n337: \t// names are the merged interface names (<node>:<interface>), indexed by merged ID.\n338: \tnames []string\n339: }\n340: \n341: // resolveCaptureTargets locates every target node, checks every interface against the\n342: // interfaces clabwire allows, and groups the targets per node.\n343: func (r *Runtime) resolveCaptureTargets(\n344: \tctx context.Context,\n345: \treq clablabruntime.CaptureRequest,\n346: ) (*resolvedCapture, error) {\n347: \tnodeOrder := make([]string, 0, len(req.Targets))\n348: \tseenNodes := map[string]bool{}\n349: \tfor _, target := range req.Targets {\n350: \t\tif !seenNodes[target.Node] {\n351: \t\t\tseenNodes[target.Node] = true\n352: \t\t\tnodeOrder = append(nodeOrder, target.Node)\n353: \t\t}\n354: \t}\n355: \n356: \tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n357: \t\tName: req.Name, Namespace: req.Namespace, Nodes: nodeOrder, Identity: req.Identity,\n358: \t})\n359: \tif err != nil {\n360: \t\treturn nil, err\n361: \t}\n362: \tbyRequest := make(map[string]clablabruntime.NodeLocation, len(nodeOrder))\n363: \tfor idx, name := range nodeOrder {\n364: \t\tbyRequest[name] = locations[idx]\n365: \t}\n366: \n367: \tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n368: \tif err != nil {\n369: \t\treturn nil, err\n370: \t}\n371: \tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n372: \tif err != nil {\n373: \t\treturn nil, err\n374: \t}\n375: \n376: \tresolved := &resolvedCapture{}\n377: \tgroups := map[string]*captureGroup{}\n378: \tseen := map[string]bool{}\n379: \tfor _, target := range req.Targets {\n380: \t\tlocation := byRequest[target.Node]\n381: \t\tentry, ok := findCaptureInterface(listed[location.NodeName], target.Interface)\n382: \t\tif !ok {\n383: \t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n384: \t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n385: \t\t\t\tdescribeCaptureInterfaces(listed[location.NodeName]))\n386: \t\t}\n387: \n388: \t\tkey := location.NodeName + \"\\x00\" + entry.Interface\n389: \t\tif seen[key] {\n390: \t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n391: \t\t\t\tentry.Interface, target.Node)\n392: \t\t}\n393: \t\tseen[key] = true\n394: \n395: \t\tgroup := groups[location.NodeName]\n396: \t\tif group == nil {\n397: \t\t\tgroup = &captureGroup{\n398: \t\t\t\tlocation: location,\n399: \t\t\t\tdisplay:  names.display(location.NodeName),\n400: \t\t\t}\n401: \t\t\tgroups[location.NodeName] = group\n402: \t\t\tresolved.groups = append(resolved.groups, group)\n403: \t\t}\n404: \n405: \t\tid := uint32(len(resolved.names)) //nolint:gosec // bounded by the targets\n406: \t\tgroup.interfaces = append(group.interfaces, entry.Interface)\n407: \t\tgroup.ids = append(group.ids, id)\n408: \t\tresolved.names = append(resolved.names, group.display+\":\"+entry.Interface)\n409: \t}\n410: \n411: \treturn resolved, nil\n412: }\n413: \n414: // findCaptureInterface matches a requested interface by its planned name or its alias.\n415: func findCaptureInterface(entries []clabwireInterface, name string) (clabwireInterface, bool) {\n416: \tfor _, entry := range entries {\n417: \t\tif entry.Interface == name {\n418: \t\t\treturn entry, true\n419: \t\t}\n420: \t}\n421: \tfor _, entry := range entries {\n422: \t\tif entry.Alias != \"\" && entry.Alias == name {\n423: \t\t\treturn entry, true\n424: \t\t}\n425: \t}\n426: \n427: \treturn clabwireInterface{}, false\n428: }\n429: \n430: func describeCaptureInterfaces(entries []clabwireInterface) string {\n431: \tif len(entries) == 0 {\n432: \t\treturn \"none\"\n433: \t}\n434: \n435: \tnames := make([]string, 0, len(entries))\n436: \tfor _, entry := range entries {\n437: \t\tname := entry.Interface\n438: \t\tif entry.Alias != \"\" {\n439: \t\t\tname += \" (\" + entry.Alias + \")\"\n440: \t\t}\n441: \t\tnames = append(names, name)\n442: \t}\n443: \n444: \treturn strings.Join(names, \", \")\n445: }\n446: \n447: // Capture streams pcapng from lab link interfaces to w: one section, one Interface Description\n448: // Block per target in request order named <node>:<interface>, then the packets of every target.\n449: //\n450: // Each node's interfaces are captured by one clabwire process in the node's pod. clabwire limits\n451: // a capture to one hour, so a longer capture (or one without Duration) chains captures: the next\n452: // one starts before the current one ends, and the stream switches at a cut in the overlap. See\n453: // captureChain for how packets of the overlap are kept once.\n454: //\n455: // Packets go out in timestamp order across nodes, through a reorder buffer (captureReorder).\n456: //\n457: // Every clabwire process runs with stdin attached and --stop-on-stdin-close: a Kubernetes exec\n458: // does not stop its process when the stream closes, so containerlab closes stdin whenever a\n459: // segment ends (the capture ends, fails, its output fails, or a newer segment took over) and\n460: // clabwire ends the capture itself.\n461: //\n462: // Capture returns when Duration has passed, PacketLimit packets were written, or ctx ends; an\n463: // ended ctx is not an error. Every block reaches w in one write, so the stream is a valid capture\n464: // whenever it stops. A clabwire Denied or Failed audit record is returned as an error.\n465: func (r *Runtime) Capture(\n466: \tctx context.Context,\n467: \treq clablabruntime.CaptureRequest,\n468: \tw io.Writer,\n469: ) error {\n470: \tif err := clabcapture.ValidateRequest(&req); err != nil {\n471: \t\treturn err\n472: \t}\n473: \n474: \tr, err := r.connect(ctx, req.Identity)\n475: \tif err != nil {\n476: \t\treturn err\n477: \t}\n478: \n479: \tresolved, err := r.resolveCaptureTargets(ctx, req)\n480: \tif err != nil {\n481: \t\treturn err\n482: \t}\n483: \n484: \tcaptureCtx, stop := context.WithCancel(ctx)\n485: \tdefer stop()\n486: \n487: \tout, err := clabcapture.NewOutput(w, resolved.names, req.SnapLength, req.PacketLimit,\n488: \t\tr.captureReorderWindowLength(), stop)\n489: \tif err != nil {\n490: \t\treturn err\n491: \t}\n492: \n493: \trun := &captureRun{\n494: \t\tr:       r,\n495: \t\treq:     req,\n496: \t\tout:     out,\n497: \t\tsegment: r.captureSegmentLength(),\n498: \t}\n499: \tif req.Duration > 0 {\n500: \t\trun.deadline = time.Now().Add(req.Duration)\n501: \t}\n502: \trun.overlap = min(maxCaptureOverlap, run.segment/3)\n503: \trun.window = min(maxCaptureCutWindow, run.overlap/4)\n504: \n505: \tif req.Duration > 0 {\n506: \t\t// a clabwire process that does not end on its own does not hold the capture open\n507: \t\tvar cancelTimeout context.CancelFunc\n508: \t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx,\n509: \t\t\treq.Duration+run.overlap+captureEndGrace)\n510: \t\tdefer cancelTimeout()\n511: \t}\n512: \n513: \tgroup, groupCtx := errgroup.WithContext(captureCtx)\n514: \tfor _, captureGroup := range resolved.groups {\n515: \t\tchain := &captureChain{capture: run, group: captureGroup}\n516: \t\tgroup.Go(func() error {\n517: \t\t\treturn chain.run(groupCtx)\n518: \t\t})\n519: \t}\n520: \n521: \terr = group.Wait()\n522: \tif writeErr := out.Close(); writeErr != nil {\n523: \t\treturn writeErr\n524: \t}\n525: \tif err != nil && !(errors.Is(err, context.Canceled) && captureCtx.Err() != nil) {\n526: \t\treturn err\n527: \t}\n528: \n529: \treturn nil\n530: }\n531: \n532: // captureRun is the state a capture's chains share.\n533: type captureRun struct {\n534: \tr   *Runtime\n535: \treq clablabruntime.CaptureRequest\n536: \t// out is the merged stream; it writes the packets of every chain in timestamp order and\n537: \t// stops every chain once the packet limit is reached.\n538: \tout *clabcapture.Output\n539: \n540: \tsegment  time.Duration\n541: \toverlap  time.Duration\n542: \twindow   time.Duration\n543: \tdeadline time.Time\n544: }\n545: \n546: // emit writes a packet under its merged interface ID. It reports false once the packet limit is\n547: // reached and the capture stops.\n548: func (run *captureRun) emit(id uint32, packet *clabcapture.Packet) (bool, error) {\n549: \treturn run.out.Emit(id, packet)\n550: }\n551: \n552: func (run *captureRun) reportGap(gap clablabruntime.CaptureGap) {\n553: \tclabcapture.ReportGap(run.req.OnGap, gap)\n554: }\n555: \n556: // captureSegment is one clabwire capture process of a chain.\n557: type captureSegment struct {\n558: \tindex      int\n559: \tlocalStart time.Time\n560: \tduration   time.Duration\n561: \tcancel     context.CancelFunc\n562: \t// closeStdin closes the stdin of the segment's clabwire process, which ends it; it may be\n563: \t// called any number of times.\n564: \tcloseStdin func()\n565: \t// stopTimer closes stdin once the segment is no longer needed after a switch-over.\n566: \tstopTimer *time.Timer\n567: \t// started and ended are the pod-clock times of the Started and Succeeded audit records.\n568: \tstarted time.Time\n569: \tended   time.Time\n570: \tdone    bool\n571: }\n572: \n573: func (s *captureSegment) plannedEnd() time.Time {\n574: \treturn s.started.Add(s.duration)\n575: }\n576: \n577: // segmentEvent is something a segment reported: a packet, an audit record, or its end.\n578: type segmentEvent struct {\n579: \tsegment *captureSegment\n580: \tpacket  *clabcapture.Packet\n581: \taudit   *captureAudit\n582: \tdone    bool\n583: \terr     error\n584: }\n585: \n586: // captureChain runs the chained clabwire captures of one group.\n587: //\n588: // Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both\n589: // capture the same packets for a while. clabwire stamps packets when it reads them, so two\n590: // processes give the same packet timestamps a few microseconds apart, and timestamps alone\n591: // cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by\n592: // content close to the cut:\n593: //\n594: //  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is\n595: //     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.\n596: //  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the\n597: //     content of what it wrote since segment k+1 started.\n598: //  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped\n599: //     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped\n600: //     when segment k wrote the same bytes on the same interface, and every other one is written.\n601: //     From then on segment k+1 streams live.\n602: //\n603: // Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its\n604: // planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other\n605: // nodes' later packets do not overtake them in the merged stream.\n606: //\n607: // W (500 ms, less for short test segments) covers the stamping difference. Identical frames on\n608: // the same interface within W of the cut can be paired with each other, which can drop a true\n609: // repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves\n610: // a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.\n611: type captureChain struct {\n612: \tcapture *captureRun\n613: \tgroup   *captureGroup\n614: \n615: \tevents chan segmentEvent\n616: \twg     sync.WaitGroup\n617: \n618: \tactive *captureSegment\n619: \tnext   *captureSegment\n620: \t// cut is the switch time between active and next, in nanoseconds; zero until known.\n621: \tcut int64\n622: \t// emitted remembers the content of the packets active wrote while next runs.\n623: \temitted map[uint64]int\n624: \t// held are the packets of next until active ends.\n625: \theld     []*clabcapture.Packet\n626: \tsegments int\n627: \tretries  int\n628: \t// final is set once no further segment is due.\n629: \tfinal bool\n630: \t// stopping is set once ctx ended: the segments are asked to end and what they still\n631: \t// deliver is written.\n632: \tstopping bool\n633: }\n634: \n635: // run runs the chain until its last segment ended. When ctx ends, it stops the segments and\n636: // keeps writing the packets they read until then; a segment that does not end within\n637: // captureStdinCloseGrace is cut.\n638: func (c *captureChain) run(ctx context.Context) error {\n639: \tc.events = make(chan segmentEvent, 256)\n640: \t// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them\n641: \tsegmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))\n642: \tvar abort *time.Timer\n643: \tdefer func() {\n644: \t\tif abort != nil {\n645: \t\t\tabort.Stop()\n646: \t\t}\n647: \t\tcancel()\n648: \t\tc.drain()\n649: \t\tc.capture.out.Release(c)\n650: \t}()\n651: \n652: \tc.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))\n653: \ttimer := time.NewTimer(c.nextStartIn())\n654: \tdefer timer.Stop()\n655: \n656: \tdone := ctx.Done()\n657: \tfor {\n658: \t\tselect {\n659: \t\tcase <-done:\n660: \t\t\tdone = nil\n661: \t\t\tc.stop(timer)\n662: \t\t\tabort = time.AfterFunc(captureStdinCloseGrace, cancel)\n663: \t\tcase <-segmentsCtx.Done():\n664: \t\t\treturn nil\n665: \t\tcase <-timer.C:\n666: \t\t\tif c.next == nil && !c.final {\n667: \t\t\t\tc.startNext(segmentsCtx)\n668: \t\t\t}\n669: \t\tcase event := <-c.events:\n670: \t\t\tstop, err := c.handle(segmentsCtx, event, timer)\n671: \t\t\tif err != nil || stop {\n672: \t\t\t\treturn err\n673: \t\t\t}\n674: \t\t}\n675: \t}\n676: }\n677: \n678: // stop ends the chain early, like a deadline would: no further segment starts and the running\n679: // ones are asked to end. The chain then writes what they deliver until they ended.\n680: func (c *captureChain) stop(timer *time.Timer) {\n681: \tc.stopping = true\n682: \tc.final = true\n683: \ttimer.Stop()\n684: \tc.active.closeStdin()\n685: \tif c.next != nil {\n686: \t\tc.next.closeStdin()\n687: \t}\n688: }\n689: \n690: // drain waits for the segment goroutines after the chain ended.\n691: func (c *captureChain) drain() {\n692: \tdone := make(chan struct{})\n693: \tgo func() {\n694: \t\tc.wg.Wait()\n695: \t\tclose(done)\n696: \t}()\n697: \tfor {\n698: \t\tselect {\n699: \t\tcase <-done:\n700: \t\t\treturn\n701: \t\tcase <-c.events:\n702: \t\t}\n703: \t}\n704: }\n705: \n706: // segmentDuration is the requested duration of a segment starting now.\n707: func (c *captureChain) segmentDuration(now time.Time) time.Duration {\n708: \tduration := c.capture.segment\n709: \tif !c.capture.deadline.IsZero() {\n710: \t\tduration = min(duration, c.capture.deadline.Sub(now))\n711: \t}\n712: \n713: \treturn max(duration, minCaptureSegment)\n714: }\n715: \n716: // nextStartIn is the time until the follow-up of the active segment is due. It marks the chain\n717: // final when none is due.\n718: func (c *captureChain) nextStartIn() time.Duration {\n719: \tif c.stopping {\n720: \t\tc.final = true\n721: \t\treturn maxCaptureSegment\n722: \t}\n723: \tactiveEnd := c.active.localStart.Add(c.active.duration)\n724: \tif !c.capture.deadline.IsZero() &&\n725: \t\t!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {\n726: \t\tc.final = true\n727: \t\treturn maxCaptureSegment\n728: \t}\n729: \tc.final = false\n730: \n731: \treturn max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)\n732: }\n733: \n734: func (c *captureChain) startNext(ctx context.Context) {\n735: \tc.next = c.start(ctx, c.segmentDuration(time.Now()))\n736: \tc.emitted = map[uint64]int{}\n737: \tc.held = nil\n738: \tc.cut = 0\n739: }\n740: \n741: func (c *captureChain) handle(\n742: \tctx context.Context,\n743: \tevent segmentEvent,\n744: \ttimer *time.Timer,\n745: ) (bool, error) {\n746: \tsegment := event.segment\n747: \n748: \tswitch {\n749: \tcase event.audit != nil:\n750: \t\treturn false, c.handleAudit(segment, event.audit)\n751: \tcase event.packet != nil:\n752: \t\treturn c.handlePacket(segment, event.packet)\n753: \tcase event.done:\n754: \t\tsegment.done = true\n755: \t\tif segment.stopTimer != nil {\n756: \t\t\tsegment.stopTimer.Stop()\n757: \t\t}\n758: \t\tif event.err != nil && !c.stopping {\n759: \t\t\tif segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {\n760: \t\t\t\t// the follow-up did not start; try again while the active one still runs\n761: \t\t\t\tc.retries++\n762: \t\t\t\tlog.Warn(\"Capture follow-up segment failed to start, retrying\",\n763: \t\t\t\t\t\"node\", c.group.display, \"error\", event.err)\n764: \t\t\t\tc.next = nil\n765: \t\t\t\tresetTimer(timer, time.Second)\n766: \n767: \t\t\t\treturn false, nil\n768: \t\t\t}\n769: \n770: \t\t\treturn true, fmt.Errorf(\"capture on c9s node %s/%s/%s failed: %w\",\n771: \t\t\t\tc.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)\n772: \t\t}\n773: \t\tif segment != c.active {\n774: \t\t\treturn false, nil\n775: \t\t}\n776: \n777: \t\treturn c.switchSegments(ctx, timer)\n778: \t}\n779: \n780: \treturn false, nil\n781: }\n782: \n783: func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {\n784: \tswitch audit.Status {\n785: \tcase captureAuditStarted:\n786: \t\tsegment.started = audit.Time\n787: \t\tlog.Debug(\"Capture segment started\", \"node\", c.group.display, \"segment\", segment.index,\n788: \t\t\t\"interfaces\", strings.Join(c.group.interfaces, \",\"), \"duration\", segment.duration)\n789: \t\tif segment == c.next && !c.active.started.IsZero() {\n790: \t\t\tc.setCut()\n791: \t\t}\n792: \t\tif segment == c.next {\n793: \t\t\tc.retries = 0\n794: \t\t}\n795: \tcase captureAuditSucceeded:\n796: \t\tsegment.ended = audit.Time\n797: \t\tlog.Debug(\"Capture segment succeeded\", \"node\", c.group.display,\n798: \t\t\t\"segment\", segment.index, \"packets\", audit.Packets)\n799: \tcase captureAuditDenied, captureAuditFailed:\n800: \t\treturn captureAuditError(c.group.display, audit)\n801: \t}\n802: \n803: \treturn nil\n804: }\n805: \n806: // captureAuditError turns a Denied or Failed clabwire audit record into an error.\n807: func captureAuditError(node string, audit *captureAudit) error {\n808: \tverb := \"failed\"\n809: \tif audit.Status == captureAuditDenied {\n810: \t\tverb = \"was denied\"\n811: \t}\n812: \tinterfaces := make([]string, 0, len(audit.Interfaces))\n813: \tfor _, intf := range audit.Interfaces {\n814: \t\tinterfaces = append(interfaces, intf.Name)\n815: \t}\n816: \n817: \treturn fmt.Errorf(\"capture of %s on node %s %s by clabwire: %s\",\n818: \t\tstrings.Join(interfaces, \",\"), node, verb, audit.Reason)\n819: }\n820: \n821: // setCut places the cut in the middle of the overlap of the active and the next segment, both\n822: // measured on the pod clock.\n823: func (c *captureChain) setCut() {\n824: \toverlapStart := c.next.started\n825: \toverlapEnd := c.active.plannedEnd()\n826: \tif overlapEnd.Sub(overlapStart) < 2*c.capture.window {\n827: \t\t// the overlap is too short to match packets around a cut: the switch is reported as a\n828: \t\t// gap once the active segment ended\n829: \t\tc.cut = 0\n830: \t\treturn\n831: \t}\n832: \tc.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()\n833: \n834: \twindow := c.capture.window.Nanoseconds()\n835: \t// Packets the next segment holds back are stamped from T-W on: other chains' packets after\n836: \t// that wait in the reorder buffer until the switch, so the merged stream stays in order.\n837: \tc.capture.out.Hold(c, c.cut-window)\n838: \n839: \t// The active segment only matters for packets stamped before T. Once the pod clock passed\n840: \t// T+W, it is closed: packets it read until then are still delivered, and the ones it reads\n841: \t// later are stamped after T and dropped anyway. The next segment's Started record was\n842: \t// written on the pod clock no later than now, so the pod clock passes T+W no later than\n843: \t// (T - Started + W) from now.\n844: \tactive := c.active\n845: \tactive.stopTimer = time.AfterFunc(\n846: \t\ttime.Duration(c.cut-c.next.started.UnixNano()+window), active.closeStdin)\n847: }\n848: \n849: func (c *captureChain) handlePacket(\n850: \tsegment *captureSegment,\n851: \tpacket *clabcapture.Packet,\n852: ) (bool, error) {\n853: \tswitch segment {\n854: \tcase c.active:\n855: \t\tif c.cut != 0 && packet.Timestamp >= c.cut {\n856: \t\t\treturn false, nil\n857: \t\t}\n858: \t\tif c.next != nil {\n859: \t\t\tc.emitted[packetKey(packet)]++\n860: \t\t}\n861: \n862: \t\treturn c.emit(packet)\n863: \tcase c.next:\n864: \t\tc.held = append(c.held, packet)\n865: \t}\n866: \n867: \treturn false, nil\n868: }\n869: \n870: func (c *captureChain) emit(packet *clabcapture.Packet) (bool, error) {\n871: \tif int(packet.InterfaceID) >= len(c.group.ids) {\n872: \t\treturn true, fmt.Errorf(\"clabwire wrote a packet for interface %d of %d\",\n873: \t\t\tpacket.InterfaceID, len(c.group.ids))\n874: \t}\n875: \tmore, err := c.capture.emit(c.group.ids[packet.InterfaceID], packet)\n876: \n877: \treturn !more, err\n878: }\n879: \n880: // switchSegments makes the next segment the active one after the active one ended, writing the\n881: // held packets of the next one that the active one did not write.\n882: func (c *captureChain) switchSegments(ctx context.Context, timer *time.Timer) (bool, error) {\n883: \t// the held packets are in the reorder buffer once this returns\n884: \tdefer c.capture.out.Release(c)\n885: \n886: \tended := c.active\n887: \tif c.stopping && c.next != nil && c.next.started.IsZero() {\n888: \t\t// the chain is stopping: a follow-up that has not started takes nothing over\n889: \t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n890: \t}\n891: \tif c.final && c.next == nil {\n892: \t\treturn true, nil\n893: \t}\n894: \n895: \tif c.next == nil || c.next.started.IsZero() || c.cut == 0 {\n896: \t\tfrom := ended.ended\n897: \t\tif from.IsZero() {\n898: \t\t\tfrom = ended.plannedEnd()\n899: \t\t}\n900: \t\tgap := clablabruntime.CaptureGap{\n901: \t\t\tNode: c.group.display, Interfaces: c.group.interfaces, From: from,\n902: \t\t\tReason: \"the follow-up capture did not overlap the previous one\",\n903: \t\t}\n904: \t\tif c.next != nil && !c.next.started.IsZero() {\n905: \t\t\tgap.To = c.next.started\n906: \t\t}\n907: \t\tc.capture.reportGap(gap)\n908: \t}\n909: \n910: \tif c.next != nil && c.next.done && !c.stopping {\n911: \t\t// the follow-up already ended (it started too late to take over): keep what it\n912: \t\t// captured and continue with a fresh segment\n913: \t\tfor _, packet := range c.held {\n914: \t\t\tif stop, err := c.emit(packet); stop || err != nil {\n915: \t\t\t\treturn true, err\n916: \t\t\t}\n917: \t\t}\n918: \t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n919: \t}\n920: \n921: \tif c.next == nil {\n922: \t\tif !c.capture.deadline.IsZero() &&\n923: \t\t\t!time.Now().Before(c.capture.deadline.Add(-c.capture.window)) {\n924: \t\t\treturn true, nil\n925: \t\t}\n926: \t\tc.active = c.start(ctx, c.segmentDuration(time.Now()))\n927: \t\tresetTimer(timer, c.nextStartIn())\n928: \n929: \t\treturn false, nil\n930: \t}\n931: \n932: \twindow := c.capture.window.Nanoseconds()\n933: \tfor _, packet := range c.held {\n934: \t\tif c.cut != 0 {\n935: \t\t\tif packet.Timestamp < c.cut-window {\n936: \t\t\t\tcontinue\n937: \t\t\t}\n938: \t\t\tif packet.Timestamp < c.cut+window {\n939: \t\t\t\tkey := packetKey(packet)\n940: \t\t\t\tif c.emitted[key] > 0 {\n941: \t\t\t\t\tc.emitted[key]--\n942: \t\t\t\t\tcontinue\n943: \t\t\t\t}\n944: \t\t\t}\n945: \t\t}\n946: \t\tif stop, err := c.emit(packet); stop || err != nil {\n947: \t\t\treturn true, err\n948: \t\t}\n949: \t}\n950: \n951: \tc.active, c.next = c.next, nil\n952: \tc.held, c.emitted, c.cut = nil, nil, 0\n953: \tif c.active.done {\n954: \t\t// the chain is stopping and the follow-up ended before the active one\n955: \t\treturn true, nil\n956: \t}\n957: \tresetTimer(timer, c.nextStartIn())\n958: \n959: \treturn false, nil\n960: }\n961: \n962: func resetTimer(timer *time.Timer, d time.Duration) {\n963: \tif !timer.Stop() {\n964: \t\tselect {\n965: \t\tcase <-timer.C:\n966: \t\tdefault:\n967: \t\t}\n968: \t}\n969: \ttimer.Reset(d)\n970: }\n971: \n972: // packetKey identifies a packet by its interface and content.\n973: func packetKey(packet *clabcapture.Packet) uint64 {\n974: \thash := fnv.New64a()\n975: \tvar id [4]byte\n976: \tid[0] = byte(packet.InterfaceID)\n977: \tid[1] = byte(packet.InterfaceID >> 8)\n978: \t_, _ = hash.Write(id[:])\n979: \t_, _ = hash.Write(packet.Data)\n980: \n981: \treturn hash.Sum64()\n982: }\n983: \n984: // start runs one clabwire capture and reports its packets, audit records and end as events.\n985: func (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {\n986: \tsegmentCtx, cancel := context.WithCancel(ctx)\n987: \tstdinReader, stdinWriter := io.Pipe()\n988: \tsegment := &captureSegment{\n989: \t\tindex: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,\n990: \t\tcloseStdin: func() { _ = stdinWriter.Close() },\n991: \t}\n992: \tc.segments++\n993: \n994: \tcommand := []string{\n995: \t\tclabwireManager, \"node-runtime\", \"packet-capture\",\n996: \t\t\"--nodeName\", c.group.location.NodeName,\n997: \t\t\"--format\", \"pcapng\",\n998: \t\t\"--snapLength\", strconv.Itoa(c.capture.req.SnapLength),\n999: \t\t\"--duration\", duration.String(),\n1000: \t\tclabwireStopOnStdinClose,\n1001: \t}\n1002: \tfor _, name := range c.group.interfaces {\n1003: \t\tcommand = append(command, \"--interface\", name)\n1004: \t}\n1005: \tif c.capture.req.PacketLimit > 0 {\n1006: \t\tremaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()\n1007: \t\tcommand = append(command, \"--packetLimit\",\n1008: \t\t\tstrconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))\n1009: \t}\n1010: \n1011: \tsend := func(event segmentEvent) {\n1012: \t\tevent.segment = segment\n1013: \t\tselect {\n1014: \t\tcase c.events <- event:\n1015: \t\tcase <-segmentCtx.Done():\n1016: \t\t}\n1017: \t}\n1018: \n1019: \tstdoutReader, stdoutWriter := io.Pipe()\n1020: \tstderr := &auditLineWriter{send: func(audit *captureAudit) { send(segmentEvent{audit: audit}) }}\n1021: \n1022: \t// The exec outlives the segment's context by up to captureStdinCloseGrace: when the segment\n1023: \t// ends for any reason (the capture is cancelled or failed, the output failed, or a newer\n1024: \t// segment took over), its stdin is closed first so clabwire ends on its own, and the stream\n1025: \t// is cut only if it does not.\n1026: \texecCtx, cancelExec := context.WithCancel(context.WithoutCancel(segmentCtx))\n1027: \texecDone := make(chan struct{})\n1028: \n1029: \tc.wg.Add(3)\n1030: \treadDone := make(chan error, 1)\n1031: \tgo func() {\n1032: \t\tdefer c.wg.Done()\n1033: \t\treadDone <- c.readSegment(stdoutReader, func(packet *clabcapture.Packet) {\n1034: \t\t\tsend(segmentEvent{packet: packet})\n1035: \t\t})\n1036: \t\t_, _ = io.Copy(io.Discard, stdoutReader)\n1037: \t}()\n1038: \tgo func() {\n1039: \t\tdefer c.wg.Done()\n1040: \t\tselect {\n1041: \t\tcase <-execDone:\n1042: \t\t\treturn\n1043: \t\tcase <-segmentCtx.Done():\n1044: \t\t}\n1045: \t\tsegment.closeStdin()\n1046: \t\tgrace := time.NewTimer(captureStdinCloseGrace)\n1047: \t\tdefer grace.Stop()\n1048: \t\tselect {\n1049: \t\tcase <-execDone:\n1050: \t\tcase <-grace.C:\n1051: \t\t\tlog.Debug(\"Capture segment did not end after its stdin closed, cutting the stream\",\n1052: \t\t\t\t\"node\", c.group.display, \"segment\", segment.index)\n1053: \t\t\tcancelExec()\n1054: \t\t}\n1055: \t}()\n1056: \tgo func() {\n1057: \t\tdefer c.wg.Done()\n1058: \t\tdefer cancel()\n1059: \t\tdefer cancelExec()\n1060: \n1061: \t\terr := c.capture.r.execInPodContainer()(execCtx, c.group.location.Namespace,\n1062: \t\t\tc.group.location.Pod, clabwireContainer, command, stdinReader, stdoutWriter, stderr)\n1063: \t\tclose(execDone)\n1064: \t\t// the process ended: release the stdin copy of the exec stream\n1065: \t\tsegment.closeStdin()\n1066: \t\t_ = stdoutWriter.Close()\n1067: \t\treadErr := <-readDone\n1068: \t\tstderr.flush()\n1069: \t\tif err == nil && readErr != nil {\n1070: \t\t\terr = readErr\n1071: \t\t}\n1072: \t\tif err != nil && stderr.text() != \"\" {\n1073: \t\t\tif unsupported := unsupportedClabwire(\n1074: \t\t\t\tc.group.location,\n1075: \t\t\t\tstderr.text(),\n1076: \t\t\t); unsupported != nil {\n1077: \t\t\t\terr = unsupported\n1078: \t\t\t} else {\n1079: \t\t\t\terr = fmt.Errorf(\"%w: %s\", err, stderr.text())\n1080: \t\t\t}\n1081: \t\t}\n1082: \t\tsend(segmentEvent{done: true, err: err})\n1083: \t}()\n1084: \n1085: \treturn segment\n1086: }\n1087: \n1088: // unsupportedClabwire recognizes a clabwire that rejects --stop-on-stdin-close, which every\n1089: // capture passes: its release predates the capture contract the runtime needs.\n1090: func unsupportedClabwire(location clablabruntime.NodeLocation, stderr string) error {\n1091: \tif !strings.Contains(stderr, \"flag provided but not defined\") ||\n1092: \t\t!strings.Contains(stderr, strings.TrimPrefix(clabwireStopOnStdinClose, \"-\")) {\n1093: \t\treturn nil\n1094: \t}\n1095: \n1096: \treturn &unsupportedClabernetesError{reason: fmt.Sprintf(\n1097: \t\t\"clabwire in pod %s/%s does not accept packet-capture %s\",\n1098: \t\tlocation.Namespace, location.Pod, clabwireStopOnStdinClose)}\n1099: }\n1100: \n1101: // readSegment checks that a segment's interfaces are the requested ones and passes its packets\n1102: // on with the segment's interface index.\n1103: func (c *captureChain) readSegment(stdout io.Reader, packet func(*clabcapture.Packet)) error {\n1104: \treader := clabcapture.NewReader(stdout)\n1105: \tinterfaces := 0\n1106: \tfor {\n1107: \t\tevent, err := reader.Next()\n1108: \t\tif errors.Is(err, io.EOF) {\n1109: \t\t\treturn nil\n1110: \t\t}\n1111: \t\tif errors.Is(err, io.ErrUnexpectedEOF) {\n1112: \t\t\t// the process was stopped inside a block\n1113: \t\t\treturn nil\n1114: \t\t}\n1115: \t\tif err != nil {\n1116: \t\t\treturn fmt.Errorf(\"failed to read the clabwire capture: %w\", err)\n1117: \t\t}\n1118: \t\tif event.Interface != nil {\n1119: \t\t\tif interfaces >= len(c.group.interfaces) ||\n1120: \t\t\t\tevent.Interface.Name != c.group.interfaces[interfaces] {\n1121: \t\t\t\treturn fmt.Errorf(\"clabwire described interface %q, want %s in order\",\n1122: \t\t\t\t\tevent.Interface.Name, strings.Join(c.group.interfaces, \", \"))\n1123: \t\t\t}\n1124: \t\t\tinterfaces++\n1125: \t\t\tcontinue\n1126: \t\t}\n1127: \t\tif event.Packet != nil {\n1128: \t\t\tpacket(event.Packet)\n1129: \t\t}\n1130: \t}\n1131: }\n1132: \n1133: // auditLineWriter parses clabwire's stderr: audit records go to send, other lines are kept for\n1134: // error messages.\n1135: type auditLineWriter struct {\n1136: \tsend func(*captureAudit)\n1137: \n1138: \tmu      sync.Mutex\n1139: \tpartial []byte\n1140: \tother   []string\n1141: }\n1142: \n1143: func (w *auditLineWriter) Write(data []byte) (int, error) {\n1144: \tw.mu.Lock()\n1145: \tw.partial = append(w.partial, data...)\n1146: \tvar lines [][]byte\n1147: \tfor {\n1148: \t\tidx := bytes.IndexByte(w.partial, '\\n')\n1149: \t\tif idx < 0 {\n1150: \t\t\tbreak\n1151: \t\t}\n1152: \t\tlines = append(lines, append([]byte(nil), w.partial[:idx]...))\n1153: \t\tw.partial = w.partial[idx+1:]\n1154: \t}\n1155: \tw.mu.Unlock()\n1156: \n1157: \tfor _, line := range lines {\n1158: \t\tw.line(line)\n1159: \t}\n1160: \n1161: \treturn len(data), nil\n1162: }\n1163: \n1164: func (w *auditLineWriter) flush() {\n1165: \tw.mu.Lock()\n1166: \tline := w.partial\n1167: \tw.partial = nil\n1168: \tw.mu.Unlock()\n1169: \tif len(bytes.TrimSpace(line)) != 0 {\n1170: \t\tw.line(line)\n1171: \t}\n1172: }\n1173: \n1174: func (w *auditLineWriter) line(line []byte) {\n1175: \tline = bytes.TrimSpace(line)\n1176: \tif len(line) == 0 {\n1177: \t\treturn\n1178: \t}\n1179: \n1180: \tvar audit captureAudit\n1181: \tif err := json.Unmarshal(\n1182: \t\tline,\n1183: \t\t&audit,\n1184: \t); err == nil &&\n1185: \t\taudit.SchemaVersion == captureAuditSchema {\n1186: \t\tw.send(&audit)\n1187: \t\treturn\n1188: \t}\n1189: \n1190: \tw.mu.Lock()\n1191: \tdefer w.mu.Unlock()\n1192: \tif len(w.other) < 20 {\n1193: \t\tw.other = append(w.other, string(line))\n1194: \t}\n1195: }\n1196: \n1197: func (w *auditLineWriter) text() string {\n1198: \tw.mu.Lock()\n1199: \tdefer w.mu.Unlock()\n1200: \n1201: \treturn strings.Join(w.other, \"; \")\n1202: }\n\n(End of file - total 1202 lines)\n</content>",
    "title": "source/head/labruntime/clabernetes/capture.go",
    "metadata": {
      "preview": "package clabernetes\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"hash/fnv\"\n\t\"io\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/capture.go",
        "text": "package clabernetes\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"hash/fnv\"\n\t\"io\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\t\"golang.org/x/sync/errgroup\"\n)\n\n// The clabwire packet capture contract (clabernetes 0.11 or newer).\nconst (\n\tclabwireContainer = \"clabwire\"\n\tclabwireManager   = \"/clabernetes/manager\"\n\t// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.\n\tcaptureAuditSchema = \"c9s.direct-packet-capture-audit/v1alpha1\"\n\n\tcaptureAuditStarted   = \"Started\"\n\tcaptureAuditSucceeded = \"Succeeded\"\n\tcaptureAuditFailed    = \"Failed\"\n\tcaptureAuditDenied    = \"Denied\"\n\n\t// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.\n\tmaxCaptureSegment = time.Hour\n\t// maxClabwirePackets is the packet limit of a single clabwire capture.\n\tmaxClabwirePackets = 1_000_000\n\t// maxCaptureOverlap is how long two chained segments run side by side.\n\tmaxCaptureOverlap = 10 * time.Second\n\t// maxCaptureCutWindow is the half-width of the window around the cut in which packets of\n\t// two segments are matched by content; it covers the difference between the timestamps\n\t// two clabwire processes give the same packet.\n\tmaxCaptureCutWindow = 500 * time.Millisecond\n\t// minCaptureSegment is the shortest segment the chain requests.\n\tminCaptureSegment = 100 * time.Millisecond\n\t// captureEndGrace is how long a capture with a duration waits for its last clabwire\n\t// process to end after the duration passed.\n\tcaptureEndGrace = 30 * time.Second\n\t// captureStartRetries bounds the attempts to start a follow-up segment.\n\tcaptureStartRetries = 3\n\t// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was\n\t// closed before the stream is cut.\n\tcaptureStdinCloseGrace = 3 * time.Second\n\t// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A\n\t// Kubernetes exec does not stop its process when the stream ends, but it closes the\n\t// process's stdin, so every capture runs with stdin attached and this flag.\n\tclabwireStopOnStdinClose = \"--stop-on-stdin-close\"\n\n\t// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests\n\t// without hour-long captures.\n\tenvCaptureSegment = \"CLAB_C9S_CAPTURE_SEGMENT\"\n\t// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets\n\t// of other nodes stamped earlier but delivered later still go out before it.\n\tdefaultCaptureReorderWindow = 250 * time.Millisecond\n\t// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.\n\t// It is an internal knob, not a supported setting.\n\tenvCaptureReorderWindow = \"CLAB_C9S_CAPTURE_REORDER_WINDOW\"\n)\n\n// podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns\n// a *labruntime.CommandExitError.\ntype podExecFunc func(\n\tctx context.Context,\n\tnamespace, pod, container string,\n\tcommand []string,\n\tstdin io.Reader,\n\tstdout, stderr io.Writer,\n) error\n\n// clabwireInterface is one entry of `packet-capture --list-interfaces`.\ntype clabwireInterface struct {\n\tNode          string `json:\"node\"`\n\tInterface     string `json:\"interface\"`\n\tAlias         string `json:\"alias,omitempty\"`\n\tPeerNode      string `json:\"peerNode\"`\n\tPeerInterface string `json:\"peerInterface\"`\n}\n\n// captureAudit is one clabwire audit line.\ntype captureAudit struct {\n\tSchemaVersion string    `json:\"schemaVersion\"`\n\tTime          time.Time `json:\"time\"`\n\tStatus        string    `json:\"status\"`\n\tNodeName      string    `json:\"nodeName\"`\n\tFormat        string    `json:\"format\"`\n\tReason        string    `json:\"reason\"`\n\tPackets       int       `json:\"packets\"`\n\tInterfaces    []struct {\n\t\tName    string `json:\"name\"`\n\t\tID      string `json:\"id\"`\n\t\tPackets int    `json:\"packets\"`\n\t} `json:\"interfaces\"`\n}\n\nfunc (r *Runtime) execInPodContainer() podExecFunc {\n\tif r.podExec != nil {\n\t\treturn r.podExec\n\t}\n\n\treturn r.streamPodExec\n}\n\n// captureSegmentLength is the length of one clabwire capture before the next takes over.\nfunc (r *Runtime) captureSegmentLength() time.Duration {\n\tif r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {\n\t\treturn r.captureSegment\n\t}\n\n\treturn maxCaptureSegment\n}\n\n// captureReorderWindowLength is the reorder window of the merged stream; zero disables\n// reordering.\nfunc (r *Runtime) captureReorderWindowLength() time.Duration {\n\tswitch {\n\tcase r.captureReorderWindow < 0:\n\t\treturn 0\n\tcase r.captureReorderWindow > 0:\n\t\treturn r.captureReorderWindow\n\t}\n\n\treturn defaultCaptureReorderWindow\n}\n\n// captureReorderWindowFromEnv reads the reorder window knob: unset or invalid keeps the\n// default (0), \"0\" disables reordering (-1).\nfunc captureReorderWindowFromEnv() time.Duration {\n\tvalue, err := time.ParseDuration(os.Getenv(envCaptureReorderWindow))\n\tswitch {\n\tcase err != nil || value < 0:\n\t\treturn 0\n\tcase value == 0:\n\t\treturn -1\n\t}\n\n\treturn value\n}\n\nfunc captureSegmentFromEnv() time.Duration {\n\tvalue, err := time.ParseDuration(os.Getenv(envCaptureSegment))\n\tif err != nil || value <= 0 {\n\t\treturn 0\n\t}\n\n\treturn value\n}\n\n// CaptureInterfaces lists the capturable lab link interfaces of the requested nodes, or of every\n// node, as clabwire reports them, with their peers. Node names are reported as the topology\n// spells them.\nfunc (r *Runtime) CaptureInterfaces(\n\tctx context.Context,\n\treq clablabruntime.NodeRequest,\n) ([]clablabruntime.CaptureInterface, error) {\n\tr, err := r.connect(ctx, req.Identity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n\t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(req.Nodes) == 0 {\n\t\t// a lab-wide listing skips nodes that do not run\n\t\trunning := locations[:0]\n\t\tfor _, location := range locations {\n\t\t\tif location.Pod != \"\" {\n\t\t\t\trunning = append(running, location)\n\t\t\t}\n\t\t}\n\t\tlocations = running\n\t}\n\n\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := make([]clablabruntime.CaptureInterface, 0)\n\tfor _, location := range locations {\n\t\tfor _, entry := range listed[location.NodeName] {\n\t\t\tresult = append(result, clablabruntime.CaptureInterface{\n\t\t\t\tNode:          names.display(entry.Node),\n\t\t\t\tInterface:     entry.Interface,\n\t\t\t\tAlias:         entry.Alias,\n\t\t\t\tPeerNode:      names.display(entry.PeerNode),\n\t\t\t\tPeerInterface: entry.PeerInterface,\n\t\t\t})\n\t\t}\n\t}\n\tsort.SliceStable(result, func(i, j int) bool {\n\t\tif result[i].Node != result[j].Node {\n\t\t\treturn result[i].Node < result[j].Node\n\t\t}\n\n\t\treturn result[i].Interface < result[j].Interface\n\t})\n\n\treturn result, nil\n}\n\n// listCaptureInterfaces runs one --list-interfaces per pod and returns the entries per Node.\nfunc (r *Runtime) listCaptureInterfaces(\n\tctx context.Context,\n\tlab string,\n\tlocations []clablabruntime.NodeLocation,\n) (map[string][]clabwireInterface, error) {\n\tpods := map[string]clablabruntime.NodeLocation{}\n\twanted := map[string]bool{}\n\tfor _, location := range locations {\n\t\tif location.Pod == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"c9s node %s/%s/%s has no pod; is it running?\",\n\t\t\t\tlocation.Namespace, lab, location.NodeName)\n\t\t}\n\t\tpods[location.Namespace+\"/\"+location.Pod] = location\n\t\twanted[location.NodeName] = true\n\t}\n\n\tvar mu sync.Mutex\n\tresult := map[string][]clabwireInterface{}\n\tgroup, groupCtx := errgroup.WithContext(ctx)\n\tgroup.SetLimit(interfaceSampleWorkers)\n\texec := r.execInPodContainer()\n\tfor _, location := range pods {\n\t\tgroup.Go(func() error {\n\t\t\tvar stdout, stderr bytes.Buffer\n\t\t\terr := exec(groupCtx, location.Namespace, location.Pod, clabwireContainer,\n\t\t\t\t[]string{clabwireManager, \"node-runtime\", \"packet-capture\", \"--list-interfaces\"},\n\t\t\t\tnil, &stdout, &stderr)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to list the capturable interfaces of pod %s/%s: %w%s\",\n\t\t\t\t\tlocation.Namespace, location.Pod, err, stderrSuffix(stderr.Bytes()))\n\t\t\t}\n\n\t\t\tvar entries []clabwireInterface\n\t\t\tif err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to parse the capturable interfaces of pod %s/%s: %w\",\n\t\t\t\t\tlocation.Namespace, location.Pod, err)\n\t\t\t}\n\n\t\t\tmu.Lock()\n\t\t\tdefer mu.Unlock()\n\t\t\tfor _, entry := range entries {\n\t\t\t\tif wanted[entry.Node] {\n\t\t\t\t\tresult[entry.Node] = append(result[entry.Node], entry)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err := group.Wait(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\nfunc stderrSuffix(stderr []byte) string {\n\ttext := strings.TrimSpace(string(stderr))\n\tif text == \"\" {\n\t\treturn \"\"\n\t}\n\n\treturn \": \" + text\n}\n\n// nodeNames maps the node names the cluster carries to the names the topology file uses.\ntype nodeNames map[string]string\n\nfunc (n nodeNames) display(name string) string {\n\tif original := n[name]; original != \"\" {\n\t\treturn original\n\t}\n\n\treturn name\n}\n\n// nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the\n// lab's Nodes.\nfunc (r *Runtime) nodeDisplayNames(\n\tctx context.Context,\n\tlab string,\n\tlocations []clablabruntime.NodeLocation,\n) (nodeNames, error) {\n\tnames := nodeNames{}\n\tif len(locations) == 0 {\n\t\treturn names, nil\n\t}\n\n\tnodes, err := r.nodesForTopology(ctx, lab, locations[0].Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor idx := range nodes.Items {\n\t\tif original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != \"\" {\n\t\t\tnames[nodes.Items[idx].GetName()] = original\n\t\t}\n\t}\n\n\treturn names, nil\n}\n\n// captureGroup is the part of a capture one clabwire process serves: the requested interfaces of\n// one node, in one pod.\ntype captureGroup struct {\n\tlocation clablabruntime.NodeLocation\n\tdisplay  string\n\t// interfaces are the planned interface names, in the order the merged stream lists them.\n\tinterfaces []string\n\t// ids are the merged interface IDs of interfaces.\n\tids []uint32\n}\n\n// resolvedCapture is a validated capture request.\ntype resolvedCapture struct {\n\tgroups []*captureGroup\n\t// names are the merged interface names (<node>:<interface>), indexed by merged ID.\n\tnames []string\n}\n\n// resolveCaptureTargets locates every target node, checks every interface against the\n// interfaces clabwire allows, and groups the targets per node.\nfunc (r *Runtime) resolveCaptureTargets(\n\tctx context.Context,\n\treq clablabruntime.CaptureRequest,\n) (*resolvedCapture, error) {\n\tnodeOrder := make([]string, 0, len(req.Targets))\n\tseenNodes := map[string]bool{}\n\tfor _, target := range req.Targets {\n\t\tif !seenNodes[target.Node] {\n\t\t\tseenNodes[target.Node] = true\n\t\t\tnodeOrder = append(nodeOrder, target.Node)\n\t\t}\n\t}\n\n\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n\t\tName: req.Name, Namespace: req.Namespace, Nodes: nodeOrder, Identity: req.Identity,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbyRequest := make(map[string]clablabruntime.NodeLocation, len(nodeOrder))\n\tfor idx, name := range nodeOrder {\n\t\tbyRequest[name] = locations[idx]\n\t}\n\n\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresolved := &resolvedCapture{}\n\tgroups := map[string]*captureGroup{}\n\tseen := map[string]bool{}\n\tfor _, target := range req.Targets {\n\t\tlocation := byRequest[target.Node]\n\t\tentry, ok := findCaptureInterface(listed[location.NodeName], target.Interface)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n\t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n\t\t\t\tdescribeCaptureInterfaces(listed[location.NodeName]))\n\t\t}\n\n\t\tkey := location.NodeName + \"\\x00\" + entry.Interface\n\t\tif seen[key] {\n\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n\t\t\t\tentry.Interface, target.Node)\n\t\t}\n\t\tseen[key] = true\n\n\t\tgroup := groups[location.NodeName]\n\t\tif group == nil {\n\t\t\tgroup = &captureGroup{\n\t\t\t\tlocation: location,\n\t\t\t\tdisplay:  names.display(location.NodeName),\n\t\t\t}\n\t\t\tgroups[location.NodeName] = group\n\t\t\tresolved.groups = append(resolved.groups, group)\n\t\t}\n\n\t\tid := uint32(len(resolved.names)) //nolint:gosec // bounded by the targets\n\t\tgroup.interfaces = append(group.interfaces, entry.Interface)\n\t\tgroup.ids = append(group.ids, id)\n\t\tresolved.names = append(resolved.names, group.display+\":\"+entry.Interface)\n\t}\n\n\treturn resolved, nil\n}\n\n// findCaptureInterface matches a requested interface by its planned name or its alias.\nfunc findCaptureInterface(entries []clabwireInterface, name string) (clabwireInterface, bool) {\n\tfor _, entry := range entries {\n\t\tif entry.Interface == name {\n\t\t\treturn entry, true\n\t\t}\n\t}\n\tfor _, entry := range entries {\n\t\tif entry.Alias != \"\" && entry.Alias == name {\n\t\t\treturn entry, true\n\t\t}\n\t}\n\n\treturn clabwireInterface{}, false\n}\n\nfunc describeCaptureInterfaces(entries []clabwireInterface) string {\n\tif len(entries) == 0 {\n\t\treturn \"none\"\n\t}\n\n\tnames := make([]string, 0, len(entries))\n\tfor _, entry := range entries {\n\t\tname := entry.Interface\n\t\tif entry.Alias != \"\" {\n\t\t\tname += \" (\" + entry.Alias + \")\"\n\t\t}\n\t\tnames = append(names, name)\n\t}\n\n\treturn strings.Join(names, \", \")\n}\n\n// Capture streams pcapng from lab link interfaces to w: one section, one Interface Description\n// Block per target in request order named <node>:<interface>, then the packets of every target.\n//\n// Each node's interfaces are captured by one clabwire process in the node's pod. clabwire limits\n// a capture to one hour, so a longer capture (or one without Duration) chains captures: the next\n// one starts before the current one ends, and the stream switches at a cut in the overlap. See\n// captureChain for how packets of the overlap are kept once.\n//\n// Packets go out in timestamp order across nodes, through a reorder buffer (captureReorder).\n//\n// Every clabwire process runs with stdin attached and --stop-on-stdin-close: a Kubernetes exec\n// does not stop its process when the stream closes, so containerlab closes stdin whenever a\n// segment ends (the capture ends, fails, its output fails, or a newer segment took over) and\n// clabwire ends the capture itself.\n//\n// Capture returns when Duration has passed, PacketLimit packets were written, or ctx ends; an\n// ended ctx is not an error. Every block reaches w in one write, so the stream is a valid capture\n// whenever it stops. A clabwire Denied or Failed audit record is returned as an error.\nfunc (r *Runtime) Capture(\n\tctx context.Context,\n\treq clablabruntime.CaptureRequest,\n\tw io.Writer,\n) error {\n\tif err := clabcapture.ValidateRequest(&req); err != nil {\n\t\treturn err\n\t}\n\n\tr, err := r.connect(ctx, req.Identity)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresolved, err := r.resolveCaptureTargets(ctx, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcaptureCtx, stop := context.WithCancel(ctx)\n\tdefer stop()\n\n\tout, err := clabcapture.NewOutput(w, resolved.names, req.SnapLength, req.PacketLimit,\n\t\tr.captureReorderWindowLength(), stop)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trun := &captureRun{\n\t\tr:       r,\n\t\treq:     req,\n\t\tout:     out,\n\t\tsegment: r.captureSegmentLength(),\n\t}\n\tif req.Duration > 0 {\n\t\trun.deadline = time.Now().Add(req.Duration)\n\t}\n\trun.overlap = min(maxCaptureOverlap, run.segment/3)\n\trun.window = min(maxCaptureCutWindow, run.overlap/4)\n\n\tif req.Duration > 0 {\n\t\t// a clabwire process that does not end on its own does not hold the capture open\n\t\tvar cancelTimeout context.CancelFunc\n\t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx,\n\t\t\treq.Duration+run.overlap+captureEndGrace)\n\t\tdefer cancelTimeout()\n\t}\n\n\tgroup, groupCtx := errgroup.WithContext(captureCtx)\n\tfor _, captureGroup := range resolved.groups {\n\t\tchain := &captureChain{capture: run, group: captureGroup}\n\t\tgroup.Go(func() error {\n\t\t\treturn chain.run(groupCtx)\n\t\t})\n\t}\n\n\terr = group.Wait()\n\tif writeErr := out.Close(); writeErr != nil {\n\t\treturn writeErr\n\t}\n\tif err != nil && !(errors.Is(err, context.Canceled) && captureCtx.Err() != nil) {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n// captureRun is the state a capture's chains share.\ntype captureRun struct {\n\tr   *Runtime\n\treq clablabruntime.CaptureRequest\n\t// out is the merged stream; it writes the packets of every chain in timestamp order and\n\t// stops every chain once the packet limit is reached.\n\tout *clabcapture.Output\n\n\tsegment  time.Duration\n\toverlap  time.Duration\n\twindow   time.Duration\n\tdeadline time.Time\n}\n\n// emit writes a packet under its merged interface ID. It reports false once the packet limit is\n// reached and the capture stops.\nfunc (run *captureRun) emit(id uint32, packet *clabcapture.Packet) (bool, error) {\n\treturn run.out.Emit(id, packet)\n}\n\nfunc (run *captureRun) reportGap(gap clablabruntime.CaptureGap) {\n\tclabcapture.ReportGap(run.req.OnGap, gap)\n}\n\n// captureSegment is one clabwire capture process of a chain.\ntype captureSegment struct {\n\tindex      int\n\tlocalStart time.Time\n\tduration   time.Duration\n\tcancel     context.CancelFunc\n\t// closeStdin closes the stdin of the segment's clabwire process, which ends it; it may be\n\t// called any number of times.\n\tcloseStdin func()\n\t// stopTimer closes stdin once the segment is no longer needed after a switch-over.\n\tstopTimer *time.Timer\n\t// started and ended are the pod-clock times of the Started and Succeeded audit records.\n\tstarted time.Time\n\tended   time.Time\n\tdone    bool\n}\n\nfunc (s *captureSegment) plannedEnd() time.Time {\n\treturn s.started.Add(s.duration)\n}\n\n// segmentEvent is something a segment reported: a packet, an audit record, or its end.\ntype segmentEvent struct {\n\tsegment *captureSegment\n\tpacket  *clabcapture.Packet\n\taudit   *captureAudit\n\tdone    bool\n\terr     error\n}\n\n// captureChain runs the chained clabwire captures of one group.\n//\n// Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both\n// capture the same packets for a while. clabwire stamps packets when it reads them, so two\n// processes give the same packet timestamps a few microseconds apart, and timestamps alone\n// cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by\n// content close to the cut:\n//\n//  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is\n//     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.\n//  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the\n//     content of what it wrote since segment k+1 started.\n//  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped\n//     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped\n//     when segment k wrote the same bytes on the same interface, and every other one is written.\n//     From then on segment k+1 streams live.\n//\n// Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its\n// planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other\n// nodes' later packets do not overtake them in the merged stream.\n//\n// W (500 ms, less for short test segments) covers the stamping difference. Identical frames on\n// the same interface within W of the cut can be paired with each other, which can drop a true\n// repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves\n// a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.\ntype captureChain struct {\n\tcapture *captureRun\n\tgroup   *captureGroup\n\n\tevents chan segmentEvent\n\twg     sync.WaitGroup\n\n\tactive *captureSegment\n\tnext   *captureSegment\n\t// cut is the switch time between active and next, in nanoseconds; zero until known.\n\tcut int64\n\t// emitted remembers the content of the packets active wrote while next runs.\n\temitted map[uint64]int\n\t// held are the packets of next until active ends.\n\theld     []*clabcapture.Packet\n\tsegments int\n\tretries  int\n\t// final is set once no further segment is due.\n\tfinal bool\n\t// stopping is set once ctx ended: the segments are asked to end and what they still\n\t// deliver is written.\n\tstopping bool\n}\n\n// run runs the chain until its last segment ended. When ctx ends, it stops the segments and\n// keeps writing the packets they read until then; a segment that does not end within\n// captureStdinCloseGrace is cut.\nfunc (c *captureChain) run(ctx context.Context) error {\n\tc.events = make(chan segmentEvent, 256)\n\t// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them\n\tsegmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))\n\tvar abort *time.Timer\n\tdefer func() {\n\t\tif abort != nil {\n\t\t\tabort.Stop()\n\t\t}\n\t\tcancel()\n\t\tc.drain()\n\t\tc.capture.out.Release(c)\n\t}()\n\n\tc.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))\n\ttimer := time.NewTimer(c.nextStartIn())\n\tdefer timer.Stop()\n\n\tdone := ctx.Done()\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\tdone = nil\n\t\t\tc.stop(timer)\n\t\t\tabort = time.AfterFunc(captureStdinCloseGrace, cancel)\n\t\tcase <-segmentsCtx.Done():\n\t\t\treturn nil\n\t\tcase <-timer.C:\n\t\t\tif c.next == nil && !c.final {\n\t\t\t\tc.startNext(segmentsCtx)\n\t\t\t}\n\t\tcase event := <-c.events:\n\t\t\tstop, err := c.handle(segmentsCtx, event, timer)\n\t\t\tif err != nil || stop {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n}\n\n// stop ends the chain early, like a deadline would: no further segment starts and the running\n// ones are asked to end. The chain then writes what they deliver until they ended.\nfunc (c *captureChain) stop(timer *time.Timer) {\n\tc.stopping = true\n\tc.final = true\n\ttimer.Stop()\n\tc.active.closeStdin()\n\tif c.next != nil {\n\t\tc.next.closeStdin()\n\t}\n}\n\n// drain waits for the segment goroutines after the chain ended.\nfunc (c *captureChain) drain() {\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tc.wg.Wait()\n\t\tclose(done)\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\treturn\n\t\tcase <-c.events:\n\t\t}\n\t}\n}\n\n// segmentDuration is the requested duration of a segment starting now.\nfunc (c *captureChain) segmentDuration(now time.Time) time.Duration {\n\tduration := c.capture.segment\n\tif !c.capture.deadline.IsZero() {\n\t\tduration = min(duration, c.capture.deadline.Sub(now))\n\t}\n\n\treturn max(duration, minCaptureSegment)\n}\n\n// nextStartIn is the time until the follow-up of the active segment is due. It marks the chain\n// final when none is due.\nfunc (c *captureChain) nextStartIn() time.Duration {\n\tif c.stopping {\n\t\tc.final = true\n\t\treturn maxCaptureSegment\n\t}\n\tactiveEnd := c.active.localStart.Add(c.active.duration)\n\tif !c.capture.deadline.IsZero() &&\n\t\t!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {\n\t\tc.final = true\n\t\treturn maxCaptureSegment\n\t}\n\tc.final = false\n\n\treturn max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)\n}\n\nfunc (c *captureChain) startNext(ctx context.Context) {\n\tc.next = c.start(ctx, c.segmentDuration(time.Now()))\n\tc.emitted = map[uint64]int{}\n\tc.held = nil\n\tc.cut = 0\n}\n\nfunc (c *captureChain) handle(\n\tctx context.Context,\n\tevent segmentEvent,\n\ttimer *time.Timer,\n) (bool, error) {\n\tsegment := event.segment\n\n\tswitch {\n\tcase event.audit != nil:\n\t\treturn false, c.handleAudit(segment, event.audit)\n\tcase event.packet != nil:\n\t\treturn c.handlePacket(segment, event.packet)\n\tcase event.done:\n\t\tsegment.done = true\n\t\tif segment.stopTimer != nil {\n\t\t\tsegment.stopTimer.Stop()\n\t\t}\n\t\tif event.err != nil && !c.stopping {\n\t\t\tif segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {\n\t\t\t\t// the follow-up did not start; try again while the active one still runs\n\t\t\t\tc.retries++\n\t\t\t\tlog.Warn(\"Capture follow-up segment failed to start, retrying\",\n\t\t\t\t\t\"node\", c.group.display, \"error\", event.err)\n\t\t\t\tc.next = nil\n\t\t\t\tresetTimer(timer, time.Second)\n\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\treturn true, fmt.Errorf(\"capture on c9s node %s/%s/%s failed: %w\",\n\t\t\t\tc.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)\n\t\t}\n\t\tif segment != c.active {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn c.switchSegments(ctx, timer)\n\t}\n\n\treturn false, nil\n}\n\nfunc (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {\n\tswitch audit.Status {\n\tcase captureAuditStarted:\n\t\tsegment.started = audit.Time\n\t\tlog.Debug(\"Capture segment started\", \"node\", c.group.display, \"segment\", segment.index,\n\t\t\t\"interfaces\", strings.Join(c.group.interfaces, \",\"), \"duration\", segment.duration)\n\t\tif segment == c.next && !c.active.started.IsZero() {\n\t\t\tc.setCut()\n\t\t}\n\t\tif segment == c.next {\n\t\t\tc.retries = 0\n\t\t}\n\tcase captureAuditSucceeded:\n\t\tsegment.ended = audit.Time\n\t\tlog.Debug(\"Capture segment succeeded\", \"node\", c.group.display,\n\t\t\t\"segment\", segment.index, \"packets\", audit.Packets)\n\tcase captureAuditDenied, captureAuditFailed:\n\t\treturn captureAuditError(c.group.display, audit)\n\t}\n\n\treturn nil\n}\n\n// captureAuditError turns a Denied or Failed clabwire audit record into an error.\nfunc captureAuditError(node string, audit *captureAudit) error {\n\tverb := \"failed\"\n\tif audit.Status == captureAuditDenied {\n\t\tverb = \"was denied\"\n\t}\n\tinterfaces := make([]string, 0, len(audit.Interfaces))\n\tfor _, intf := range audit.Interfaces {\n\t\tinterfaces = append(interfaces, intf.Name)\n\t}\n\n\treturn fmt.Errorf(\"capture of %s on node %s %s by clabwire: %s\",\n\t\tstrings.Join(interfaces, \",\"), node, verb, audit.Reason)\n}\n\n// setCut places the cut in the middle of the overlap of the active and the next segment, both\n// measured on the pod clock.\nfunc (c *captureChain) setCut() {\n\toverlapStart := c.next.started\n\toverlapEnd := c.active.plannedEnd()\n\tif overlapEnd.Sub(overlapStart) < 2*c.capture.window {\n\t\t// the overlap is too short to match packets around a cut: the switch is reported as a\n\t\t// gap once the active segment ended\n\t\tc.cut = 0\n\t\treturn\n\t}\n\tc.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()\n\n\twindow := c.capture.window.Nanoseconds()\n\t// Packets the next segment holds back are stamped from T-W on: other chains' packets after\n\t// that wait in the reorder buffer until the switch, so the merged stream stays in order.\n\tc.capture.out.Hold(c, c.cut-window)\n\n\t// The active segment only matters for packets stamped before T. Once the pod clock passed\n\t// T+W, it is closed: packets it read until then are still delivered, and the ones it reads\n\t// later are stamped after T and dropped anyway. The next segment's Started record was\n\t// written on the pod clock no later than now, so the pod clock passes T+W no later than\n\t// (T - Started + W) from now.\n\tactive := c.active\n\tactive.stopTimer = time.AfterFunc(\n\t\ttime.Duration(c.cut-c.next.started.UnixNano()+window), active.closeStdin)\n}\n\nfunc (c *captureChain) handlePacket(\n\tsegment *captureSegment,\n\tpacket *clabcapture.Packet,\n) (bool, error) {\n\tswitch segment {\n\tcase c.active:\n\t\tif c.cut != 0 && packet.Timestamp >= c.cut {\n\t\t\treturn false, nil\n\t\t}\n\t\tif c.next != nil {\n\t\t\tc.emitted[packetKey(packet)]++\n\t\t}\n\n\t\treturn c.emit(packet)\n\tcase c.next:\n\t\tc.held = append(c.held, packet)\n\t}\n\n\treturn false, nil\n}\n\nfunc (c *captureChain) emit(packet *clabcapture.Packet) (bool, error) {\n\tif int(packet.InterfaceID) >= len(c.group.ids) {\n\t\treturn true, fmt.Errorf(\"clabwire wrote a packet for interface %d of %d\",\n\t\t\tpacket.InterfaceID, len(c.group.ids))\n\t}\n\tmore, err := c.capture.emit(c.group.ids[packet.InterfaceID], packet)\n\n\treturn !more, err\n}\n\n// switchSegments makes the next segment the active one after the active one ended, writing the\n// held packets of the next one that the active one did not write.\nfunc (c *captureChain) switchSegments(ctx context.Context, timer *time.Timer) (bool, error) {\n\t// the held packets are in the reorder buffer once this returns\n\tdefer c.capture.out.Release(c)\n\n\tended := c.active\n\tif c.stopping && c.next != nil && c.next.started.IsZero() {\n\t\t// the chain is stopping: a follow-up that has not started takes nothing over\n\t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n\t}\n\tif c.final && c.next == nil {\n\t\treturn true, nil\n\t}\n\n\tif c.next == nil || c.next.started.IsZero() || c.cut == 0 {\n\t\tfrom := ended.ended\n\t\tif from.IsZero() {\n\t\t\tfrom = ended.plannedEnd()\n\t\t}\n\t\tgap := clablabruntime.CaptureGap{\n\t\t\tNode: c.group.display, Interfaces: c.group.interfaces, From: from,\n\t\t\tReason: \"the follow-up capture did not overlap the previous one\",\n\t\t}\n\t\tif c.next != nil && !c.next.started.IsZero() {\n\t\t\tgap.To = c.next.started\n\t\t}\n\t\tc.capture.reportGap(gap)\n\t}\n\n\tif c.next != nil && c.next.done && !c.stopping {\n\t\t// the follow-up already ended (it started too late to take over): keep what it\n\t\t// captured and continue with a fresh segment\n\t\tfor _, packet := range c.held {\n\t\t\tif stop, err := c.emit(packet); stop || err != nil {\n\t\t\t\treturn true, err\n\t\t\t}\n\t\t}\n\t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n\t}\n\n\tif c.next == nil {\n\t\tif !c.capture.deadline.IsZero() &&\n\t\t\t!time.Now().Before(c.capture.deadline.Add(-c.capture.window)) {\n\t\t\treturn true, nil\n\t\t}\n\t\tc.active = c.start(ctx, c.segmentDuration(time.Now()))\n\t\tresetTimer(timer, c.nextStartIn())\n\n\t\treturn false, nil\n\t}\n\n\twindow := c.capture.window.Nanoseconds()\n\tfor _, packet := range c.held {\n\t\tif c.cut != 0 {\n\t\t\tif packet.Timestamp < c.cut-window {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif packet.Timestamp < c.cut+window {\n\t\t\t\tkey := packetKey(packet)\n\t\t\t\tif c.emitted[key] > 0 {\n\t\t\t\t\tc.emitted[key]--\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif stop, err := c.emit(packet); stop || err != nil {\n\t\t\treturn true, err\n\t\t}\n\t}\n\n\tc.active, c.next = c.next, nil\n\tc.held, c.emitted, c.cut = nil, nil, 0\n\tif c.active.done {\n\t\t// the chain is stopping and the follow-up ended before the active one\n\t\treturn true, nil\n\t}\n\tresetTimer(timer, c.nextStartIn())\n\n\treturn false, nil\n}\n\nfunc resetTimer(timer *time.Timer, d time.Duration) {\n\tif !timer.Stop() {\n\t\tselect {\n\t\tcase <-timer.C:\n\t\tdefault:\n\t\t}\n\t}\n\ttimer.Reset(d)\n}\n\n// packetKey identifies a packet by its interface and content.\nfunc packetKey(packet *clabcapture.Packet) uint64 {\n\thash := fnv.New64a()\n\tvar id [4]byte\n\tid[0] = byte(packet.InterfaceID)\n\tid[1] = byte(packet.InterfaceID >> 8)\n\t_, _ = hash.Write(id[:])\n\t_, _ = hash.Write(packet.Data)\n\n\treturn hash.Sum64()\n}\n\n// start runs one clabwire capture and reports its packets, audit records and end as events.\nfunc (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {\n\tsegmentCtx, cancel := context.WithCancel(ctx)\n\tstdinReader, stdinWriter := io.Pipe()\n\tsegment := &captureSegment{\n\t\tindex: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,\n\t\tcloseStdin: func() { _ = stdinWriter.Close() },\n\t}\n\tc.segments++\n\n\tcommand := []string{\n\t\tclabwireManager, \"node-runtime\", \"packet-capture\",\n\t\t\"--nodeName\", c.group.location.NodeName,\n\t\t\"--format\", \"pcapng\",\n\t\t\"--snapLength\", strconv.Itoa(c.capture.req.SnapLength),\n\t\t\"--duration\", duration.String(),\n\t\tclabwireStopOnStdinClose,\n\t}\n\tfor _, name := range c.group.interfaces {\n\t\tcommand = append(command, \"--interface\", name)\n\t}\n\tif c.capture.req.PacketLimit > 0 {\n\t\tremaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()\n\t\tcommand = append(command, \"--packetLimit\",\n\t\t\tstrconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))\n\t}\n\n\tsend := func(event segmentEvent) {\n\t\tevent.segment = segment\n\t\tselect {\n\t\tcase c.events <- event:\n\t\tcase <-segmentCtx.Done():\n\t\t}\n\t}\n\n\tstdoutReader, stdoutWriter := io.Pipe()\n\tstderr := &auditLineWriter{send: func(audit *captureAudit) { send(segmentEvent{audit: audit}) }}\n\n\t// The exec outlives the segment's context by up to captureStdinCloseGrace: when the segment\n\t// ends for any reason (the capture is cancelled or failed, the output failed, or a newer\n\t// segment took over), its stdin is closed first so clabwire ends on its own, and the stream\n\t// is cut only if it does not.\n\texecCtx, cancelExec := context.WithCancel(context.WithoutCancel(segmentCtx))\n\texecDone := make(chan struct{})\n\n\tc.wg.Add(3)\n\treadDone := make(chan error, 1)\n\tgo func() {\n\t\tdefer c.wg.Done()\n\t\treadDone <- c.readSegment(stdoutReader, func(packet *clabcapture.Packet) {\n\t\t\tsend(segmentEvent{packet: packet})\n\t\t})\n\t\t_, _ = io.Copy(io.Discard, stdoutReader)\n\t}()\n\tgo func() {\n\t\tdefer c.wg.Done()\n\t\tselect {\n\t\tcase <-execDone:\n\t\t\treturn\n\t\tcase <-segmentCtx.Done():\n\t\t}\n\t\tsegment.closeStdin()\n\t\tgrace := time.NewTimer(captureStdinCloseGrace)\n\t\tdefer grace.Stop()\n\t\tselect {\n\t\tcase <-execDone:\n\t\tcase <-grace.C:\n\t\t\tlog.Debug(\"Capture segment did not end after its stdin closed, cutting the stream\",\n\t\t\t\t\"node\", c.group.display, \"segment\", segment.index)\n\t\t\tcancelExec()\n\t\t}\n\t}()\n\tgo func() {\n\t\tdefer c.wg.Done()\n\t\tdefer cancel()\n\t\tdefer cancelExec()\n\n\t\terr := c.capture.r.execInPodContainer()(execCtx, c.group.location.Namespace,\n\t\t\tc.group.location.Pod, clabwireContainer, command, stdinReader, stdoutWriter, stderr)\n\t\tclose(execDone)\n\t\t// the process ended: release the stdin copy of the exec stream\n\t\tsegment.closeStdin()\n\t\t_ = stdoutWriter.Close()\n\t\treadErr := <-readDone\n\t\tstderr.flush()\n\t\tif err == nil && readErr != nil {\n\t\t\terr = readErr\n\t\t}\n\t\tif err != nil && stderr.text() != \"\" {\n\t\t\tif unsupported := unsupportedClabwire(\n\t\t\t\tc.group.location,\n\t\t\t\tstderr.text(),\n\t\t\t); unsupported != nil {\n\t\t\t\terr = unsupported\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"%w: %s\", err, stderr.text())\n\t\t\t}\n\t\t}\n\t\tsend(segmentEvent{done: true, err: err})\n\t}()\n\n\treturn segment\n}\n\n// unsupportedClabwire recognizes a clabwire that rejects --stop-on-stdin-close, which every\n// capture passes: its release predates the capture contract the runtime needs.\nfunc unsupportedClabwire(location clablabruntime.NodeLocation, stderr string) error {\n\tif !strings.Contains(stderr, \"flag provided but not defined\") ||\n\t\t!strings.Contains(stderr, strings.TrimPrefix(clabwireStopOnStdinClose, \"-\")) {\n\t\treturn nil\n\t}\n\n\treturn &unsupportedClabernetesError{reason: fmt.Sprintf(\n\t\t\"clabwire in pod %s/%s does not accept packet-capture %s\",\n\t\tlocation.Namespace, location.Pod, clabwireStopOnStdinClose)}\n}\n\n// readSegment checks that a segment's interfaces are the requested ones and passes its packets\n// on with the segment's interface index.\nfunc (c *captureChain) readSegment(stdout io.Reader, packet func(*clabcapture.Packet)) error {\n\treader := clabcapture.NewReader(stdout)\n\tinterfaces := 0\n\tfor {\n\t\tevent, err := reader.Next()\n\t\tif errors.Is(err, io.EOF) {\n\t\t\treturn nil\n\t\t}\n\t\tif errors.Is(err, io.ErrUnexpectedEOF) {\n\t\t\t// the process was stopped inside a block\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read the clabwire capture: %w\", err)\n\t\t}\n\t\tif event.Interface != nil {\n\t\t\tif interfaces >= len(c.group.interfaces) ||\n\t\t\t\tevent.Interface.Name != c.group.interfaces[interfaces] {\n\t\t\t\treturn fmt.Errorf(\"clabwire described interface %q, want %s in order\",\n\t\t\t\t\tevent.Interface.Name, strings.Join(c.group.interfaces, \", \"))\n\t\t\t}\n\t\t\tinterfaces++\n\t\t\tcontinue\n\t\t}\n\t\tif event.Packet != nil {\n\t\t\tpacket(event.Packet)\n\t\t}\n\t}\n}\n\n// auditLineWriter parses clabwire's stderr: audit records go to send, other lines are kept for\n// error messages.\ntype auditLineWriter struct {\n\tsend func(*captureAudit)\n\n\tmu      sync.Mutex\n\tpartial []byte\n\tother   []string\n}\n\nfunc (w *auditLineWriter) Write(data []byte) (int, error) {\n\tw.mu.Lock()\n\tw.partial = append(w.partial, data...)\n\tvar lines [][]byte\n\tfor {\n\t\tidx := bytes.IndexByte(w.partial, '\\n')\n\t\tif idx < 0 {\n\t\t\tbreak\n\t\t}\n\t\tlines = append(lines, append([]byte(nil), w.partial[:idx]...))\n\t\tw.partial = w.partial[idx+1:]\n\t}\n\tw.mu.Unlock()\n\n\tfor _, line := range lines {\n\t\tw.line(line)\n\t}\n\n\treturn len(data), nil\n}\n\nfunc (w *auditLineWriter) flush() {\n\tw.mu.Lock()\n\tline := w.partial\n\tw.partial = nil\n\tw.mu.Unlock()\n\tif len(bytes.TrimSpace(line)) != 0 {\n\t\tw.line(line)\n\t}\n}\n\nfunc (w *auditLineWriter) line(line []byte) {\n\tline = bytes.TrimSpace(line)\n\tif len(line) == 0 {\n\t\treturn\n\t}\n\n\tvar audit captureAudit\n\tif err := json.Unmarshal(\n\t\tline,\n\t\t&audit,\n\t); err == nil &&\n\t\taudit.SchemaVersion == captureAuditSchema {\n\t\tw.send(&audit)\n\t\treturn\n\t}\n\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\tif len(w.other) < 20 {\n\t\tw.other = append(w.other, string(line))\n\t}\n}\n\nfunc (w *auditLineWriter) text() string {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\n\treturn strings.Join(w.other, \"; \")\n}",
        "lineStart": 1,
        "lineEnd": 1202,
        "totalLines": 1202,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523274719,
      "end": 1793523274729
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1965153ec0011qmRsKsOsbxqqM",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196514a21001Ayu8dXKBiaV3GA",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 57489,
    "input": 6470,
    "output": 33,
    "reasoning": 42,
    "cache": {
      "read": 50944,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196514a21001Ayu8dXKBiaV3GA",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523272225,
    "completed": 1793523274735
  },
  "parentID": "msg_19650e899001051OTPpm7MOch6",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 57489,
    "input": 6470,
    "output": 33,
    "reasoning": 42,
    "cache": {
      "read": 50944,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 19
step-start
{
  "type": "step-start",
  "id": "prt_196515d9b001ndYhMbWblOja6a",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965153f5001Rc1pht8HI7IZpm"
}
Reasoning
This is a very intricate piece of code. Let me note potential issues:

1. `captureChain.handle` for `event.done` on `c.active` → `switchSegments(ctx, timer)`. But when the chain is stopping (ctx ended) and the active segment's done event arrives, `switchSegments` is called. In stopping case: `c.stopping && c.next != nil && c.next.started.IsZero()` → next dropped. Then `if c.final && c.next == nil → return true, nil`. Good.

2. Race: `handle` runs on the chain's single goroutine (events channel), so segment field access is single-threaded, except `stopTimer` AfterFunc callback `active.closeStdin` — closes stdin writer, safe (io.Pipe Close is safe).

3. `setCut` computes stopTimer duration: `c.cut - c.next.started.UnixNano() + window`. cut = overlapStart + overlap/2 where overlapEnd = active.plannedEnd. cut - nextStarted = overlap/2. So AfterFunc fires at overlap/2 + window after next Started. OK.

4. Potential deadlock: `c.events` is buffered 256. `send` blocks if channel full and segmentCtx not done. The chain loop reads events. When chain is in `drain()`, it consumes events. When chain returns (e.g., error), `defer` runs drain, which consumes events until wg done. The segment goroutines: the stdout reader goroutine sends packets; after chain returned with error, drain consumes them. wg includes 3 goroutines per segment. readSegment goroutine ends after readDone sent and io.Copy finishes... Actually the reader goroutine sends `readDone <- err` first (buffered 1), then io.Copy(io.Discard, stdoutReader) until stdoutReader EOF — stdoutWriter closed by exec goroutine after exec returns. Then wg.Done. The exec goroutine waits `readErr := <-readDone` — readDone has buffer 1, so ok.

But one subtle deadlock: the exec goroutine writes packets to `stdoutWriter` (io.Pipe). If the chain has returned and drain is consuming events, ok. But if the segment's stdout reader is blocked in `send` while the chain goroutine is blocked... chain always consumes. OK.

5. `captureChain.run` — when the chain returns with error, other chains' `group.Wait` returns the first error, and `Capture` calls `out.Close()` then returns writeErr or err. Other chains keep running until captureCtx? Actually `group.Wait` waits for all chains to return. A chain only returns on error/stop/final. If one chain errors, others keep streaming until... the erroring chain returned but other chains are not cancelled! `groupCtx` is only cancelled when all return or Wait returns? errgroup: Wait returns after all goroutines return; ctx is cancelled when the first function returns non-nil error. Yes — errgroup.WithContext cancels groupCtx on first error return. So other chains see ctx.Done → stop → return nil. OK.

But: `if err != nil && !(errors.Is(err, context.Canceled) && captureCtx.Err() != nil)` — a chain returning `context.Canceled` when its segmentsCtx ended... segmentsCtx is WithoutCancel(ctx), so chains don't return due to captureCtx cancellation except via the `done` select. Fine.

6. Hold semantics: `c.capture.out.Hold(c, c.cut-window)` — hold registered under chain pointer c. Released in switchSegments (defer) and in run's defer. But note: in switchSegments, `defer c.capture.out.Release(c)` — then after switching, `resetTimer(timer, c.nextStartIn())`. But the next segment may soon start a new next and call Hold again — after Release, ordering: Hold is called in setCut (from handleAudit in the events loop), Release called in switchSegments. Since all in the same goroutine, no race. But the hold release wakes the reorder buffer — good.

Wait — there's an issue: `switchSegments` releases the hold at its start (defer runs at return). Held packets are emitted via `c.emit` → reorder Push — but Release happens at function return, i.e., after emissions. Push of packets with timestamps possibly > hold limit... The hold is released at the end, so packets pushed while hold still active with timestamp > limit get held in the reorder buffer until Release. That's fine.

7. `handlePacket` for `c.next` — appends to `c.held` unboundedly. The overlap is bounded (max 10s), but if the active segment never ends (hangs), held grows unbounded until cut... The stopTimer closes active stdin after cut+window; if clabwire ignores stdin close, the grace cuts the stream after captureStdinCloseGrace. Held packets: next keeps producing until active ends. Bounded-ish. But consider the stopping case: on ctx done, `c.stop(timer)` closes stdins; segments deliver remaining; `c.held` grows but bounded by delivery time.

Actually, wait — potential unbounded memory: while stopping, the chain keeps receiving packet events from segments and appends next's packets to held; the emit path... When stopping, active keeps streaming? After stop, active.closeStdin called; active continues to stream until it ends. handlePacket for active: `if c.cut != 0 && packet.Timestamp >= c.cut → drop`, else emit. Emit → reorder.Push. Reorder has maxReorderBytes bound. OK.

8. `c.emitted` map keyed by fnv64 hash of interface+data — used only while next exists. Cleared at startNext and at switch. Fine.

9. Packet dropped in handlePacket for active when `c.cut != 0 && packet.Timestamp >= c.cut` — those are matched from next's held stream. But what if next's Started arrives after active ends (started.IsZero)? Then handle done(active) → switchSegments with c.next.started.IsZero() → gap reported; then in the "c.next != nil && c.next.done" branch — next may still be running (not done). Then it goes to the held-emission loop with c.cut == 0 (setCut never called since active.started zero? Actually setCut is called when next reports Started and `!c.active.started.IsZero()`. If active has already ended (done event processed before next's Started audit?), hmm order: events are sequential. If active ends first (done), switchSegments runs with next.started zero → gap; then `if c.next != nil && c.next.done && !c.stopping` — next not done → falls through; then `if c.next == nil` no; then emission loop with cut==0: emits all held; then `c.active, c.next = c.next, nil` — takes over. OK.

But there's a subtle case: next reports Started while active already done? setCut only called if `!c.active.started.IsZero()` — active.started is nonzero (it started earlier). But c.active.done already true and switchSegments already ran → c.active was replaced. Wait, in switchSegments, `c.active, c.next = c.next, nil`. The old segment becomes inactive. If the old next's Started audit arrives after switchSegments... it was c.next at that time; after switch it's c.active. handleAudit: `if segment == c.next && !c.active.started.IsZero()` — now segment == c.active, so no setCut. Fine. But then c.cut remains 0 for this new active... The timer was reset in switchSegments to nextStartIn, so the chain will start another next. When that next starts, setCut runs. OK.

Hmm, but in switchSegments when the active ends and next is running but its Started hasn't arrived: it emits all held with cut == 0, sets active = next. Then next's Started arrives → handleAudit sets segment.started, and `segment == c.next` is false now, so no setCut, no hold. Then cut stays 0 until the *next* chain switch, meaning during this active segment, when its own next starts, setCut is called. Fine.

10. Potential issue: in switchSegments, when `c.next != nil && !c.next.started.IsZero()` the gap To is set — but the gap is reported when `c.cut == 0` too (overlap too short). The comment in setCut says "the switch is reported as a gap once the active segment ended". OK consistent.

11. `handle` event.done for segment != c.active and != c.next: only active/next exist. `if segment != c.active return false,nil` — a next that ends → return; then later active ends → switchSegments. OK.

12. Big one: `captureChain.start` — `remaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()`. `out.Written()` counts *handed to stream* (including held-back? Emit increments written before reorder push). But out.Written counts packets handed to the output, not those written. Reordered buffer may hold many. The actual written count ≤ Written. remaining could be negative if the limit was already reached — but then stop() was called and chains stopped. min(max(remaining,1),...) → 1. Fine.

13. Reorder window interplay: the c9s capture uses window default 250ms. Held packets emitted after active ends — with hold at T-W. OK.

14. `readSegment` returns nil on ErrUnexpectedEOF — treats a cut mid-block as clean end. OK by design.

15. `auditLineWriter.line` — json.Unmarshal on every line; audit only when schemaVersion matches. OK.

16. `stderrSuffix` fine.

Now `capture_interfaces.go` and diffs in `clabernetes.go`/`runtime.go`, plus `cmd/options.go`, `cmd/root.go` diffs for FinishOnCancel, etc. Let me read capture_interfaces.go and the diff hunks for cmd/* and clabernetes.go/runtime.go.
This is a complex chaining implementation. Let me examine the remaining c9s files and the diff hunks for the modified `cmd/` files.
read · completed

Input

{
  "filePath": "/source/head/labruntime/clabernetes/capture_interfaces.go"
}

Output

<path>/source/head/labruntime/clabernetes/capture_interfaces.go</path>
<type>file</type>
<content>
1: package clabernetes
2: 
3: import (
4: 	"bytes"
5: 	"context"
6: 	"errors"
7: 	"fmt"
8: 	"io"
9: 	"sort"
10: 	"sync"
11: 
12: 	"github.com/charmbracelet/log"
13: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
14: 	clabtypes "github.com/srl-labs/containerlab/types"
15: 	corev1 "k8s.io/api/core/v1"
16: 	"k8s.io/client-go/kubernetes/scheme"
17: 	"k8s.io/client-go/tools/remotecommand"
18: 	kubeexec "k8s.io/client-go/util/exec"
19: )
20: 
21: // streamPodExec runs a command in a pod container without a terminal and streams its stdout
22: // and stderr. A non-nil stdin is attached: when it ends, the process's stdin is closed (the
23: // websocket v5 close signal, or a half-closed SPDY stream). A nonzero exit returns a
24: // *labruntime.CommandExitError.
25: func (r *Runtime) streamPodExec(
26: 	ctx context.Context,
27: 	namespace, pod, container string,
28: 	command []string,
29: 	stdin io.Reader,
30: 	stdout, stderr io.Writer,
31: ) error {
32: 	execURL := r.kubeClient.CoreV1().RESTClient().Post().
33: 		Resource("pods").
34: 		Name(pod).
35: 		Namespace(namespace).
36: 		SubResource("exec").
37: 		VersionedParams(&corev1.PodExecOptions{
38: 			Container: container,
39: 			Command:   command,
40: 			Stdin:     stdin != nil,
41: 			Stdout:    stdout != nil,
42: 			Stderr:    stderr != nil,
43: 		}, scheme.ParameterCodec).URL()
44: 
45: 	executor, err := r.newExecutor(execURL)
46: 	if err != nil {
47: 		return err
48: 	}
49: 
50: 	// client-go reports streams cut by a cancelled context through the context's logger; a
51: 	// capture ends that way on purpose, so it goes to the debug log
52: 	err = executor.StreamWithContext(withKubernetesClientDebugLogs(ctx),
53: 		remotecommand.StreamOptions{
54: 			Stdin:  stdin,
55: 			Stdout: stdout,
56: 			Stderr: stderr,
57: 		})
58: 
59: 	var exitErr kubeexec.ExitError
60: 	if errors.As(err, &exitErr) {
61: 		return &clablabruntime.CommandExitError{Code: exitErr.ExitStatus()}
62: 	}
63: 	if err != nil {
64: 		return fmt.Errorf("failed to execute command in pod %s/%s container %s: %w",
65: 			namespace, pod, container, err)
66: 	}
67: 
68: 	return nil
69: }
70: 
71: // InspectInterfaces lists the capturable link interfaces of the requested nodes, or of every
72: // running node, in the shape of `inspect interfaces`: per node (named <lab>-<node> like in
73: // inspect), the interface and its alias as clabwire reports them, and the MAC address, index,
74: // MTU and operational state read from sysfs in the device container. A node whose device
75: // container has no shell reports its interfaces without these attributes.
76: func (r *Runtime) InspectInterfaces(
77: 	ctx context.Context,
78: 	req clablabruntime.NodeRequest,
79: ) ([]*clabtypes.ContainerInterfaces, error) {
80: 	r, err := r.connect(ctx, req.Identity)
81: 	if err != nil {
82: 		return nil, err
83: 	}
84: 
85: 	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{
86: 		Name: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,
87: 	})
88: 	if err != nil {
89: 		return nil, err
90: 	}
91: 
92: 	running := make([]clablabruntime.NodeLocation, 0, len(locations))
93: 	for _, location := range locations {
94: 		if location.Pod == "" {
95: 			log.Warn("Skipping interface detection of a node that does not run",
96: 				"node", location.NodeName)
97: 			continue
98: 		}
99: 		running = append(running, location)
100: 	}
101: 
102: 	listed, err := r.listCaptureInterfaces(ctx, req.Name, running)
103: 	if err != nil {
104: 		return nil, err
105: 	}
106: 	states := r.sampleInterfaceStates(ctx, running)
107: 
108: 	result := make([]*clabtypes.ContainerInterfaces, 0, len(running))
109: 	for _, location := range running {
110: 		container := &clabtypes.ContainerInterfaces{
111: 			ContainerName: req.Name + "-" + location.NodeName,
112: 			Interfaces:    []*clabtypes.ContainerInterfaceDetails{},
113: 		}
114: 		for _, entry := range listed[location.NodeName] {
115: 			details := &clabtypes.ContainerInterfaceDetails{
116: 				InterfaceName:  entry.Interface,
117: 				InterfaceAlias: entry.Alias,
118: 				// clabwire realizes every lab link interface as a veth pair
119: 				InterfaceType: "veth",
120: 			}
121: 			if state, ok := states[location.NodeName][entry.Interface]; ok {
122: 				details.InterfaceMAC = state.MAC
123: 				details.InterfaceIndex = state.Index
124: 				details.InterfaceMTU = state.MTU
125: 				details.InterfaceState = state.OperState
126: 			}
127: 			container.Interfaces = append(container.Interfaces, details)
128: 		}
129: 		sort.Slice(container.Interfaces, func(i, j int) bool {
130: 			return container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName
131: 		})
132: 		result = append(result, container)
133: 	}
134: 	sort.Slice(result, func(i, j int) bool {
135: 		return result[i].ContainerName < result[j].ContainerName
136: 	})
137: 
138: 	return result, nil
139: }
140: 
141: // sampleInterfaceStates reads the sysfs interface attributes of every node's device container,
142: // one exec per node, with the script the interface events use.
143: func (r *Runtime) sampleInterfaceStates(
144: 	ctx context.Context,
145: 	locations []clablabruntime.NodeLocation,
146: ) map[string]map[string]c9sIfaceState {
147: 	var mu sync.Mutex
148: 	result := map[string]map[string]c9sIfaceState{}
149: 
150: 	var wg sync.WaitGroup
151: 	workers := make(chan struct{}, interfaceSampleWorkers)
152: 	exec := r.execInPodContainer()
153: 	for _, location := range locations {
154: 		wg.Add(1)
155: 		go func() {
156: 			defer wg.Done()
157: 			workers <- struct{}{}
158: 			defer func() { <-workers }()
159: 
160: 			var stdout, stderr bytes.Buffer
161: 			err := exec(ctx, location.Namespace, location.Pod, location.Container,
162: 				[]string{"sh", "-c", interfaceSampleScript}, nil, &stdout, &stderr)
163: 			if err != nil {
164: 				log.Debug("Cannot read the interface state of a c9s node",
165: 					"node", location.NodeName, "error", err)
166: 				return
167: 			}
168: 			_, ifaces, _, err := parseInterfaceSample(stdout.Bytes())
169: 			if err != nil {
170: 				log.Debug("Cannot parse the interface state of a c9s node",
171: 					"node", location.NodeName, "error", err)
172: 				return
173: 			}
174: 
175: 			byName := make(map[string]c9sIfaceState, len(ifaces))
176: 			for _, iface := range ifaces {
177: 				byName[iface.Name] = iface
178: 			}
179: 			mu.Lock()
180: 			result[location.NodeName] = byName
181: 			mu.Unlock()
182: 		}()
183: 	}
184: 	wg.Wait()
185: 
186: 	return result
187: }

(End of file - total 187 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196519874001ybcyrcaV5PQ1YB",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965153f5001Rc1pht8HI7IZpm",
  "callID": "call_654092f0d7cb4f9191cf7c2b",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/capture_interfaces.go"
    },
    "output": "<path>/source/head/labruntime/clabernetes/capture_interfaces.go</path>\n<type>file</type>\n<content>\n1: package clabernetes\n2: \n3: import (\n4: \t\"bytes\"\n5: \t\"context\"\n6: \t\"errors\"\n7: \t\"fmt\"\n8: \t\"io\"\n9: \t\"sort\"\n10: \t\"sync\"\n11: \n12: \t\"github.com/charmbracelet/log\"\n13: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n14: \tclabtypes \"github.com/srl-labs/containerlab/types\"\n15: \tcorev1 \"k8s.io/api/core/v1\"\n16: \t\"k8s.io/client-go/kubernetes/scheme\"\n17: \t\"k8s.io/client-go/tools/remotecommand\"\n18: \tkubeexec \"k8s.io/client-go/util/exec\"\n19: )\n20: \n21: // streamPodExec runs a command in a pod container without a terminal and streams its stdout\n22: // and stderr. A non-nil stdin is attached: when it ends, the process's stdin is closed (the\n23: // websocket v5 close signal, or a half-closed SPDY stream). A nonzero exit returns a\n24: // *labruntime.CommandExitError.\n25: func (r *Runtime) streamPodExec(\n26: \tctx context.Context,\n27: \tnamespace, pod, container string,\n28: \tcommand []string,\n29: \tstdin io.Reader,\n30: \tstdout, stderr io.Writer,\n31: ) error {\n32: \texecURL := r.kubeClient.CoreV1().RESTClient().Post().\n33: \t\tResource(\"pods\").\n34: \t\tName(pod).\n35: \t\tNamespace(namespace).\n36: \t\tSubResource(\"exec\").\n37: \t\tVersionedParams(&corev1.PodExecOptions{\n38: \t\t\tContainer: container,\n39: \t\t\tCommand:   command,\n40: \t\t\tStdin:     stdin != nil,\n41: \t\t\tStdout:    stdout != nil,\n42: \t\t\tStderr:    stderr != nil,\n43: \t\t}, scheme.ParameterCodec).URL()\n44: \n45: \texecutor, err := r.newExecutor(execURL)\n46: \tif err != nil {\n47: \t\treturn err\n48: \t}\n49: \n50: \t// client-go reports streams cut by a cancelled context through the context's logger; a\n51: \t// capture ends that way on purpose, so it goes to the debug log\n52: \terr = executor.StreamWithContext(withKubernetesClientDebugLogs(ctx),\n53: \t\tremotecommand.StreamOptions{\n54: \t\t\tStdin:  stdin,\n55: \t\t\tStdout: stdout,\n56: \t\t\tStderr: stderr,\n57: \t\t})\n58: \n59: \tvar exitErr kubeexec.ExitError\n60: \tif errors.As(err, &exitErr) {\n61: \t\treturn &clablabruntime.CommandExitError{Code: exitErr.ExitStatus()}\n62: \t}\n63: \tif err != nil {\n64: \t\treturn fmt.Errorf(\"failed to execute command in pod %s/%s container %s: %w\",\n65: \t\t\tnamespace, pod, container, err)\n66: \t}\n67: \n68: \treturn nil\n69: }\n70: \n71: // InspectInterfaces lists the capturable link interfaces of the requested nodes, or of every\n72: // running node, in the shape of `inspect interfaces`: per node (named <lab>-<node> like in\n73: // inspect), the interface and its alias as clabwire reports them, and the MAC address, index,\n74: // MTU and operational state read from sysfs in the device container. A node whose device\n75: // container has no shell reports its interfaces without these attributes.\n76: func (r *Runtime) InspectInterfaces(\n77: \tctx context.Context,\n78: \treq clablabruntime.NodeRequest,\n79: ) ([]*clabtypes.ContainerInterfaces, error) {\n80: \tr, err := r.connect(ctx, req.Identity)\n81: \tif err != nil {\n82: \t\treturn nil, err\n83: \t}\n84: \n85: \tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n86: \t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n87: \t})\n88: \tif err != nil {\n89: \t\treturn nil, err\n90: \t}\n91: \n92: \trunning := make([]clablabruntime.NodeLocation, 0, len(locations))\n93: \tfor _, location := range locations {\n94: \t\tif location.Pod == \"\" {\n95: \t\t\tlog.Warn(\"Skipping interface detection of a node that does not run\",\n96: \t\t\t\t\"node\", location.NodeName)\n97: \t\t\tcontinue\n98: \t\t}\n99: \t\trunning = append(running, location)\n100: \t}\n101: \n102: \tlisted, err := r.listCaptureInterfaces(ctx, req.Name, running)\n103: \tif err != nil {\n104: \t\treturn nil, err\n105: \t}\n106: \tstates := r.sampleInterfaceStates(ctx, running)\n107: \n108: \tresult := make([]*clabtypes.ContainerInterfaces, 0, len(running))\n109: \tfor _, location := range running {\n110: \t\tcontainer := &clabtypes.ContainerInterfaces{\n111: \t\t\tContainerName: req.Name + \"-\" + location.NodeName,\n112: \t\t\tInterfaces:    []*clabtypes.ContainerInterfaceDetails{},\n113: \t\t}\n114: \t\tfor _, entry := range listed[location.NodeName] {\n115: \t\t\tdetails := &clabtypes.ContainerInterfaceDetails{\n116: \t\t\t\tInterfaceName:  entry.Interface,\n117: \t\t\t\tInterfaceAlias: entry.Alias,\n118: \t\t\t\t// clabwire realizes every lab link interface as a veth pair\n119: \t\t\t\tInterfaceType: \"veth\",\n120: \t\t\t}\n121: \t\t\tif state, ok := states[location.NodeName][entry.Interface]; ok {\n122: \t\t\t\tdetails.InterfaceMAC = state.MAC\n123: \t\t\t\tdetails.InterfaceIndex = state.Index\n124: \t\t\t\tdetails.InterfaceMTU = state.MTU\n125: \t\t\t\tdetails.InterfaceState = state.OperState\n126: \t\t\t}\n127: \t\t\tcontainer.Interfaces = append(container.Interfaces, details)\n128: \t\t}\n129: \t\tsort.Slice(container.Interfaces, func(i, j int) bool {\n130: \t\t\treturn container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName\n131: \t\t})\n132: \t\tresult = append(result, container)\n133: \t}\n134: \tsort.Slice(result, func(i, j int) bool {\n135: \t\treturn result[i].ContainerName < result[j].ContainerName\n136: \t})\n137: \n138: \treturn result, nil\n139: }\n140: \n141: // sampleInterfaceStates reads the sysfs interface attributes of every node's device container,\n142: // one exec per node, with the script the interface events use.\n143: func (r *Runtime) sampleInterfaceStates(\n144: \tctx context.Context,\n145: \tlocations []clablabruntime.NodeLocation,\n146: ) map[string]map[string]c9sIfaceState {\n147: \tvar mu sync.Mutex\n148: \tresult := map[string]map[string]c9sIfaceState{}\n149: \n150: \tvar wg sync.WaitGroup\n151: \tworkers := make(chan struct{}, interfaceSampleWorkers)\n152: \texec := r.execInPodContainer()\n153: \tfor _, location := range locations {\n154: \t\twg.Add(1)\n155: \t\tgo func() {\n156: \t\t\tdefer wg.Done()\n157: \t\t\tworkers <- struct{}{}\n158: \t\t\tdefer func() { <-workers }()\n159: \n160: \t\t\tvar stdout, stderr bytes.Buffer\n161: \t\t\terr := exec(ctx, location.Namespace, location.Pod, location.Container,\n162: \t\t\t\t[]string{\"sh\", \"-c\", interfaceSampleScript}, nil, &stdout, &stderr)\n163: \t\t\tif err != nil {\n164: \t\t\t\tlog.Debug(\"Cannot read the interface state of a c9s node\",\n165: \t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n166: \t\t\t\treturn\n167: \t\t\t}\n168: \t\t\t_, ifaces, _, err := parseInterfaceSample(stdout.Bytes())\n169: \t\t\tif err != nil {\n170: \t\t\t\tlog.Debug(\"Cannot parse the interface state of a c9s node\",\n171: \t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n172: \t\t\t\treturn\n173: \t\t\t}\n174: \n175: \t\t\tbyName := make(map[string]c9sIfaceState, len(ifaces))\n176: \t\t\tfor _, iface := range ifaces {\n177: \t\t\t\tbyName[iface.Name] = iface\n178: \t\t\t}\n179: \t\t\tmu.Lock()\n180: \t\t\tresult[location.NodeName] = byName\n181: \t\t\tmu.Unlock()\n182: \t\t}()\n183: \t}\n184: \twg.Wait()\n185: \n186: \treturn result\n187: }\n\n(End of file - total 187 lines)\n</content>",
    "title": "source/head/labruntime/clabernetes/capture_interfaces.go",
    "metadata": {
      "preview": "package clabernetes\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\t\"sync\"\n\n\t\"github.com/charmbracelet/log\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\tclabtypes \"github.com/srl-labs/containerlab/types\"\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/client-go/kubernetes/scheme\"\n\t\"k8s.io/client-go/tools/remotecommand\"\n\tkubeexec \"k8s.io/client-go/util/exec\"\n)\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/capture_interfaces.go",
        "text": "package clabernetes\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\t\"sync\"\n\n\t\"github.com/charmbracelet/log\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\tclabtypes \"github.com/srl-labs/containerlab/types\"\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/client-go/kubernetes/scheme\"\n\t\"k8s.io/client-go/tools/remotecommand\"\n\tkubeexec \"k8s.io/client-go/util/exec\"\n)\n\n// streamPodExec runs a command in a pod container without a terminal and streams its stdout\n// and stderr. A non-nil stdin is attached: when it ends, the process's stdin is closed (the\n// websocket v5 close signal, or a half-closed SPDY stream). A nonzero exit returns a\n// *labruntime.CommandExitError.\nfunc (r *Runtime) streamPodExec(\n\tctx context.Context,\n\tnamespace, pod, container string,\n\tcommand []string,\n\tstdin io.Reader,\n\tstdout, stderr io.Writer,\n) error {\n\texecURL := r.kubeClient.CoreV1().RESTClient().Post().\n\t\tResource(\"pods\").\n\t\tName(pod).\n\t\tNamespace(namespace).\n\t\tSubResource(\"exec\").\n\t\tVersionedParams(&corev1.PodExecOptions{\n\t\t\tContainer: container,\n\t\t\tCommand:   command,\n\t\t\tStdin:     stdin != nil,\n\t\t\tStdout:    stdout != nil,\n\t\t\tStderr:    stderr != nil,\n\t\t}, scheme.ParameterCodec).URL()\n\n\texecutor, err := r.newExecutor(execURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// client-go reports streams cut by a cancelled context through the context's logger; a\n\t// capture ends that way on purpose, so it goes to the debug log\n\terr = executor.StreamWithContext(withKubernetesClientDebugLogs(ctx),\n\t\tremotecommand.StreamOptions{\n\t\t\tStdin:  stdin,\n\t\t\tStdout: stdout,\n\t\t\tStderr: stderr,\n\t\t})\n\n\tvar exitErr kubeexec.ExitError\n\tif errors.As(err, &exitErr) {\n\t\treturn &clablabruntime.CommandExitError{Code: exitErr.ExitStatus()}\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to execute command in pod %s/%s container %s: %w\",\n\t\t\tnamespace, pod, container, err)\n\t}\n\n\treturn nil\n}\n\n// InspectInterfaces lists the capturable link interfaces of the requested nodes, or of every\n// running node, in the shape of `inspect interfaces`: per node (named <lab>-<node> like in\n// inspect), the interface and its alias as clabwire reports them, and the MAC address, index,\n// MTU and operational state read from sysfs in the device container. A node whose device\n// container has no shell reports its interfaces without these attributes.\nfunc (r *Runtime) InspectInterfaces(\n\tctx context.Context,\n\treq clablabruntime.NodeRequest,\n) ([]*clabtypes.ContainerInterfaces, error) {\n\tr, err := r.connect(ctx, req.Identity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n\t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trunning := make([]clablabruntime.NodeLocation, 0, len(locations))\n\tfor _, location := range locations {\n\t\tif location.Pod == \"\" {\n\t\t\tlog.Warn(\"Skipping interface detection of a node that does not run\",\n\t\t\t\t\"node\", location.NodeName)\n\t\t\tcontinue\n\t\t}\n\t\trunning = append(running, location)\n\t}\n\n\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, running)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstates := r.sampleInterfaceStates(ctx, running)\n\n\tresult := make([]*clabtypes.ContainerInterfaces, 0, len(running))\n\tfor _, location := range running {\n\t\tcontainer := &clabtypes.ContainerInterfaces{\n\t\t\tContainerName: req.Name + \"-\" + location.NodeName,\n\t\t\tInterfaces:    []*clabtypes.ContainerInterfaceDetails{},\n\t\t}\n\t\tfor _, entry := range listed[location.NodeName] {\n\t\t\tdetails := &clabtypes.ContainerInterfaceDetails{\n\t\t\t\tInterfaceName:  entry.Interface,\n\t\t\t\tInterfaceAlias: entry.Alias,\n\t\t\t\t// clabwire realizes every lab link interface as a veth pair\n\t\t\t\tInterfaceType: \"veth\",\n\t\t\t}\n\t\t\tif state, ok := states[location.NodeName][entry.Interface]; ok {\n\t\t\t\tdetails.InterfaceMAC = state.MAC\n\t\t\t\tdetails.InterfaceIndex = state.Index\n\t\t\t\tdetails.InterfaceMTU = state.MTU\n\t\t\t\tdetails.InterfaceState = state.OperState\n\t\t\t}\n\t\t\tcontainer.Interfaces = append(container.Interfaces, details)\n\t\t}\n\t\tsort.Slice(container.Interfaces, func(i, j int) bool {\n\t\t\treturn container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName\n\t\t})\n\t\tresult = append(result, container)\n\t}\n\tsort.Slice(result, func(i, j int) bool {\n\t\treturn result[i].ContainerName < result[j].ContainerName\n\t})\n\n\treturn result, nil\n}\n\n// sampleInterfaceStates reads the sysfs interface attributes of every node's device container,\n// one exec per node, with the script the interface events use.\nfunc (r *Runtime) sampleInterfaceStates(\n\tctx context.Context,\n\tlocations []clablabruntime.NodeLocation,\n) map[string]map[string]c9sIfaceState {\n\tvar mu sync.Mutex\n\tresult := map[string]map[string]c9sIfaceState{}\n\n\tvar wg sync.WaitGroup\n\tworkers := make(chan struct{}, interfaceSampleWorkers)\n\texec := r.execInPodContainer()\n\tfor _, location := range locations {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tworkers <- struct{}{}\n\t\t\tdefer func() { <-workers }()\n\n\t\t\tvar stdout, stderr bytes.Buffer\n\t\t\terr := exec(ctx, location.Namespace, location.Pod, location.Container,\n\t\t\t\t[]string{\"sh\", \"-c\", interfaceSampleScript}, nil, &stdout, &stderr)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"Cannot read the interface state of a c9s node\",\n\t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t_, ifaces, _, err := parseInterfaceSample(stdout.Bytes())\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"Cannot parse the interface state of a c9s node\",\n\t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tbyName := make(map[string]c9sIfaceState, len(ifaces))\n\t\t\tfor _, iface := range ifaces {\n\t\t\t\tbyName[iface.Name] = iface\n\t\t\t}\n\t\t\tmu.Lock()\n\t\t\tresult[location.NodeName] = byName\n\t\t\tmu.Unlock()\n\t\t}()\n\t}\n\twg.Wait()\n\n\treturn result\n}",
        "lineStart": 1,
        "lineEnd": 187,
        "totalLines": 187,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523292283,
      "end": 1793523292293
    }
  }
}
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "offset": 2544,
  "limit": 340
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
2544: diff --git a/cmd/context.go b/cmd/context.go
2545: index 223cb1d..21d5bea 100644
2546: --- a/cmd/context.go
2547: +++ b/cmd/context.go
2548: @@ -51,10 +51,20 @@ func SignalHandledContext() (context.Context, context.CancelFunc) {
2549:  
2550:  		cancel()
2551:  
2552:  		options := GetOptions()
2553:  
2554: +		if options.Global.FinishOnCancel.Load() {
2555: +			log.Info("Stopping, press Ctrl+C again to abort")
2556: +
2557: +			sig = <-sigs
2558: +
2559: +			log.Errorf("received signal %q while stopping, exiting", sig)
2560: +
2561: +			os.Exit(1)
2562: +		}
2563: +
2564:  		if !options.Global.CleanOnCancel.Load() {
2565:  			log.Debug("clean on cancel is not true, exiting")
2566:  
2567:  			os.Exit(1)
2568:  		}
2569: diff --git a/cmd/inspect.go b/cmd/inspect.go
2570: index 1b6f41d..55fb61f 100644
2571: --- a/cmd/inspect.go
2572: +++ b/cmd/inspect.go
2573: @@ -70,10 +70,14 @@ func inspectCmd(o *Options) (*cobra.Command, error) {
2574:  		Short: "inspect interfaces of one or multiple nodes in a lab",
2575:  		Long: "show interfaces and their attributes in a specific deployed lab\n" +
2576:  			"reference: https://containerlab.dev/cmd/inspect/interfaces/",
2577:  		Aliases: []string{"int", "intf"},
2578:  		PreRunE: func(_ *cobra.Command, _ []string) error {
2579: +			if commandSkipsRoot(o.Global.Runtime) {
2580: +				return nil
2581: +			}
2582: +
2583:  			return clabutils.CheckAndGetRootPrivs()
2584:  		},
2585:  		RunE: func(cobraCmd *cobra.Command, _ []string) error {
2586:  			return inspectInterfacesFn(cobraCmd, o)
2587:  		},
2588: diff --git a/cmd/inspect_interfaces.go b/cmd/inspect_interfaces.go
2589: index 0f64f03..91035c2 100644
2590: --- a/cmd/inspect_interfaces.go
2591: +++ b/cmd/inspect_interfaces.go
2592: @@ -33,10 +33,25 @@ func inspectInterfacesFn(cobraCmd *cobra.Command, o *Options) error {
2593:  	c, err := clabcore.NewContainerLab(o.ToClabOptions()...)
2594:  	if err != nil {
2595:  		return fmt.Errorf("could not parse the topology file: %v", err)
2596:  	}
2597:  
2598: +	if c.LabRuntime != nil {
2599: +		// lab runtimes list the link interfaces packet capture accepts, with their state
2600: +		containerInterfaces, err := c.LabRuntimeInterfaces(cobraCmd.Context(),
2601: +			o.Inspect.InterfacesNode)
2602: +		if err != nil {
2603: +			return fmt.Errorf("failed to list node interfaces: %w", err)
2604: +		}
2605: +		if len(containerInterfaces) == 0 {
2606: +			log.Info("no running nodes found")
2607: +			return nil
2608: +		}
2609: +
2610: +		return printContainerInterfaces(containerInterfaces, o.Inspect.InterfacesFormat)
2611: +	}
2612: +
2613:  	var labNameFilterLabel string
2614:  
2615:  	switch {
2616:  	case o.Global.TopologyName != "":
2617:  		labNameFilterLabel = o.Global.TopologyName
2618: diff --git a/cmd/options.go b/cmd/options.go
2619: index 8717d3b..6037551 100644
2620: --- a/cmd/options.go
2621: +++ b/cmd/options.go
2622: @@ -53,10 +53,14 @@ func GetOptions() *Options {
2623:  				InterfacesFormat: "table",
2624:  			},
2625:  			Logs: &LogsOptions{
2626:  				Tail: -1,
2627:  			},
2628: +			Capture: &CaptureOptions{
2629: +				Write:  "-",
2630: +				Format: "table",
2631: +			},
2632:  			Graph: &GraphOptions{
2633:  				Server:           "0.0.0.0:50080",
2634:  				MermaidDirection: "TD",
2635:  				DrawIOVersion:    "latest",
2636:  			},
2637: @@ -142,10 +146,11 @@ type Options struct {
2638:  	Exec           *ExecOptions
2639:  	Inspect        *InspectOptions
2640:  	Graph          *GraphOptions
2641:  	Events         *EventsOptions
2642:  	Logs           *LogsOptions
2643: +	Capture        *CaptureOptions
2644:  	ToolsAPI       *ToolsApiOptions
2645:  	ToolsCert      *ToolsCertOptions
2646:  	ToolsTxOffload *ToolsDisableTxOffloadOptions
2647:  	ToolsGoTTY     *ToolsGoTTYOptions
2648:  	ToolsNetem     *ToolsNetemOptions
2649: @@ -257,10 +262,15 @@ type GlobalOptions struct {
2650:  	// special flag that should only be set by deploy, informs the context handler to destroy
2651:  	// (or not) when root context is canceled. The signal handler goroutine reads it while
2652:  	// deploy is running, so it is atomic.
2653:  	CleanOnCancel atomic.Bool
2654:  
2655: +	// FinishOnCancel informs the context handler that the running command ends cleanly on its
2656: +	// own once the root context is canceled (capture finishes its output), so the handler
2657: +	// waits for it instead of exiting.
2658: +	FinishOnCancel atomic.Bool
2659: +
2660:  	// special flag that is only set on deploy,
2661:  	// if true, the topology file backup is created at /tmp/.clab/bak
2662:  	BackupTopologyFile bool
2663:  }
2664:  
2665: diff --git a/cmd/root.go b/cmd/root.go
2666: index 0baf203..a9b1c8b 100644
2667: --- a/cmd/root.go
2668: +++ b/cmd/root.go
2669: @@ -35,10 +35,11 @@ func subcommandRegisterFuncs() []func(*Options) (*cobra.Command, error) {
2670:  		generateCmd,
2671:  		graphCmd,
2672:  		eventsCmd,
2673:  		inspectCmd,
2674:  		logsCmd,
2675: +		captureCmd,
2676:  		redeployCmd,
2677:  		saveCmd,
2678:  		toolsCmd,
2679:  		validateCmd,
2680:  	}
2681: @@ -263,15 +264,10 @@ func checkLabRuntimeCommandSupport(cobraCmd *cobra.Command, runtimeName string)
2682:  			"the %q command needs running containers with lab runtime %q unless it renders "+
2683:  				"from the topology file alone; use --offline, --dot, --mermaid or --drawio",
2684:  			"graph", runtimeName)
2685:  	}
2686:  
2687: -	if getCommandPath(cobraCmd) == "inspect.interfaces" {
2688: -		return fmt.Errorf("the %q command is not supported with lab runtime %q",
2689: -			"inspect interfaces", runtimeName)
2690: -	}
2691: -
2692:  	var unsupported []string
2693:  	for _, flagName := range labRuntimeUnsupportedFlags[getCommandPath(cobraCmd)] {
2694:  		if labRuntimeFlagWasSet(cobraCmd, flagName) {
2695:  			unsupported = append(unsupported, "--"+flagName)
2696:  		}
2697: @@ -339,10 +335,11 @@ func getTopoFilePath(cobraCmd *cobra.Command, o *Options) error { // skipcq: GO-
2698:  		cobraCmd.Name() != "inspect" &&
2699:  		cobraCmd.Name() != "save" &&
2700:  		cobraCmd.Name() != "graph" &&
2701:  		cobraCmd.Name() != "validate" &&
2702:  		cobraCmd.Name() != "logs" &&
2703: +		cobraCmd.Name() != "capture" &&
2704:  		cobraCmd.Name() != "interfaces" {
2705:  		return nil
2706:  	}
2707:  
2708:  	// start/stop/restart topology lookup applies only to top-level lifecycle commands.
2709: diff --git a/cmd/root_test.go b/cmd/root_test.go
2710: index 418a947..af02e34 100644
2711: --- a/cmd/root_test.go
2712: +++ b/cmd/root_test.go
2713: @@ -289,20 +289,23 @@ func TestCheckLabRuntimeFlagAndNestedCommandSupport(t *testing.T) {
2714:  				t.Fatalf("checkLabRuntimeCommandSupport() error = %v, wantErr %v", err, tt.wantErr)
2715:  			}
2716:  		})
2717:  	}
2718:  
2719: -	t.Run("inspect interfaces rejected", func(t *testing.T) {
2720: +	t.Run("inspect interfaces and capture accepted", func(t *testing.T) {
2721:  		root := &cobra.Command{Use: "containerlab"}
2722:  		inspect := &cobra.Command{Use: "inspect"}
2723:  		interfaces := &cobra.Command{Use: "interfaces"}
2724: -		root.AddCommand(inspect)
2725: +		capture := &cobra.Command{Use: "capture"}
2726: +		root.AddCommand(inspect, capture)
2727:  		inspect.AddCommand(interfaces)
2728:  
2729: -		if err := checkLabRuntimeCommandSupport(
2730: -			interfaces,
2731: -			clablabruntime.ClabernetesRuntimeName,
2732: -		); err == nil {
2733: -			t.Fatal("inspect interfaces was accepted for clabernetes")
2734: +		for _, cmd := range []*cobra.Command{interfaces, capture} {
2735: +			if err := checkLabRuntimeCommandSupport(
2736: +				cmd,
2737: +				clablabruntime.ClabernetesRuntimeName,
2738: +			); err != nil {
2739: +				t.Fatalf("%s rejected for clabernetes: %v", cmd.Name(), err)
2740: +			}
2741:  		}
2742:  	})
2743:  }
2744: diff --git a/core/capture.go b/core/capture.go
2745: new file mode 100644
2746: index 0000000..2e12fc2
2747: --- /dev/null
2748: +++ b/core/capture.go
2749: @@ -0,0 +1,93 @@
2750: +package core
2751: +
2752: +import (
2753: +	"context"
2754: +	"io"
2755: +
2756: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2757: +	clabtypes "github.com/srl-labs/containerlab/types"
2758: +)
2759: +
2760: +// CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for
2761: +// every running node, with the peer at the other end of each link. With Docker and Podman, the
2762: +// interfaces come from the topology's links; lab runtimes list them through their packet
2763: +// capturer.
2764: +func (c *CLab) CaptureInterfaces(
2765: +	ctx context.Context,
2766: +	nodeNames ...string,
2767: +) ([]clablabruntime.CaptureInterface, error) {
2768: +	if c.LabRuntime == nil {
2769: +		return c.localCaptureInterfacesOf(ctx, nodeNames)
2770: +	}
2771: +
2772: +	capturer, err := c.packetCapturer()
2773: +	if err != nil {
2774: +		return nil, err
2775: +	}
2776: +
2777: +	return capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{
2778: +		Name:     c.Config.Name,
2779: +		Nodes:    nodeNames,
2780: +		Identity: c.labRuntimeIdentity,
2781: +	})
2782: +}
2783: +
2784: +// Capture streams pcapng from lab link interfaces to w until req.Duration passed,
2785: +// req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name
2786: +// and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces
2787: +// itself through packet sockets in the nodes' network namespaces, which needs root; lab
2788: +// runtimes capture through their packet capturer.
2789: +func (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {
2790: +	if c.LabRuntime == nil {
2791: +		return c.captureLocal(ctx, req, w)
2792: +	}
2793: +
2794: +	capturer, err := c.packetCapturer()
2795: +	if err != nil {
2796: +		return err
2797: +	}
2798: +
2799: +	if req.Name == "" {
2800: +		req.Name = c.Config.Name
2801: +	}
2802: +	if req.Identity.IsZero() {
2803: +		req.Identity = c.labRuntimeIdentity
2804: +	}
2805: +
2806: +	return capturer.Capture(ctx, req, w)
2807: +}
2808: +
2809: +// LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their
2810: +// state, in the shape ListContainersInterfaces reports for local containers.
2811: +func (c *CLab) LabRuntimeInterfaces(
2812: +	ctx context.Context,
2813: +	nodeName string,
2814: +) ([]*clabtypes.ContainerInterfaces, error) {
2815: +	inspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](
2816: +		c, "inspecting interfaces")
2817: +	if err != nil {
2818: +		return nil, err
2819: +	}
2820: +	if err := c.requireLabName(); err != nil {
2821: +		return nil, err
2822: +	}
2823: +
2824: +	req := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}
2825: +	if nodeName != "" {
2826: +		req.Nodes = []string{nodeName}
2827: +	}
2828: +
2829: +	return inspector.InspectInterfaces(ctx, req)
2830: +}
2831: +
2832: +func (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {
2833: +	capturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, "packet capture")
2834: +	if err != nil {
2835: +		return nil, err
2836: +	}
2837: +	if err := c.requireLabName(); err != nil {
2838: +		return nil, err
2839: +	}
2840: +
2841: +	return capturer, nil
2842: +}
2843: diff --git a/core/capture_local.go b/core/capture_local.go
2844: new file mode 100644
2845: index 0000000..fada0bf
2846: --- /dev/null
2847: +++ b/core/capture_local.go
2848: @@ -0,0 +1,255 @@
2849: +package core
2850: +
2851: +import (
2852: +	"context"
2853: +	"fmt"
2854: +	"io"
2855: +	"slices"
2856: +	"sort"
2857: +	"strings"
2858: +
2859: +	clabcapture "github.com/srl-labs/containerlab/capture"
2860: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2861: +	clablinks "github.com/srl-labs/containerlab/links"
2862: +	clabnodes "github.com/srl-labs/containerlab/nodes"
2863: +	clabruntime "github.com/srl-labs/containerlab/runtime"
2864: +)
2865: +
2866: +// localCaptureInterface is a lab link interface of a node on this machine.
2867: +type localCaptureInterface struct {
2868: +	node clabnodes.Node
2869: +	info clablabruntime.CaptureInterface
2870: +}
2871: +
2872: +// localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with
2873: +// the far end of each link, per node name. Host and management network endpoints are the far
2874: +// ends of links, not nodes to capture on.
2875: +func (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {
2876: +	if len(c.Nodes) == 0 {
2877: +		return nil, fmt.Errorf("the topology of lab %q is not available; capture reads the "+
2878: +			"lab's links from it, pass it with --topo", c.Config.Name)
2879: +	}
2880: +	if len(c.Links) == 0 {
2881: +		if err := c.ResolveLinks(); err != nil {
2882: +			return nil, fmt.Errorf("failed to resolve the links of lab %q: %w", c.Config.Name, err)
2883: +		}

(Showing lines 2544-2883 of 7018. Use offset=2884 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1965198b70016BjP7wD87wU1Ou",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965153f5001Rc1pht8HI7IZpm",
  "callID": "call_d9a1e64241604c048114a63a",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "offset": 2544,
      "limit": 340
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n2544: diff --git a/cmd/context.go b/cmd/context.go\n2545: index 223cb1d..21d5bea 100644\n2546: --- a/cmd/context.go\n2547: +++ b/cmd/context.go\n2548: @@ -51,10 +51,20 @@ func SignalHandledContext() (context.Context, context.CancelFunc) {\n2549:  \n2550:  \t\tcancel()\n2551:  \n2552:  \t\toptions := GetOptions()\n2553:  \n2554: +\t\tif options.Global.FinishOnCancel.Load() {\n2555: +\t\t\tlog.Info(\"Stopping, press Ctrl+C again to abort\")\n2556: +\n2557: +\t\t\tsig = <-sigs\n2558: +\n2559: +\t\t\tlog.Errorf(\"received signal %q while stopping, exiting\", sig)\n2560: +\n2561: +\t\t\tos.Exit(1)\n2562: +\t\t}\n2563: +\n2564:  \t\tif !options.Global.CleanOnCancel.Load() {\n2565:  \t\t\tlog.Debug(\"clean on cancel is not true, exiting\")\n2566:  \n2567:  \t\t\tos.Exit(1)\n2568:  \t\t}\n2569: diff --git a/cmd/inspect.go b/cmd/inspect.go\n2570: index 1b6f41d..55fb61f 100644\n2571: --- a/cmd/inspect.go\n2572: +++ b/cmd/inspect.go\n2573: @@ -70,10 +70,14 @@ func inspectCmd(o *Options) (*cobra.Command, error) {\n2574:  \t\tShort: \"inspect interfaces of one or multiple nodes in a lab\",\n2575:  \t\tLong: \"show interfaces and their attributes in a specific deployed lab\\n\" +\n2576:  \t\t\t\"reference: https://containerlab.dev/cmd/inspect/interfaces/\",\n2577:  \t\tAliases: []string{\"int\", \"intf\"},\n2578:  \t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n2579: +\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n2580: +\t\t\t\treturn nil\n2581: +\t\t\t}\n2582: +\n2583:  \t\t\treturn clabutils.CheckAndGetRootPrivs()\n2584:  \t\t},\n2585:  \t\tRunE: func(cobraCmd *cobra.Command, _ []string) error {\n2586:  \t\t\treturn inspectInterfacesFn(cobraCmd, o)\n2587:  \t\t},\n2588: diff --git a/cmd/inspect_interfaces.go b/cmd/inspect_interfaces.go\n2589: index 0f64f03..91035c2 100644\n2590: --- a/cmd/inspect_interfaces.go\n2591: +++ b/cmd/inspect_interfaces.go\n2592: @@ -33,10 +33,25 @@ func inspectInterfacesFn(cobraCmd *cobra.Command, o *Options) error {\n2593:  \tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n2594:  \tif err != nil {\n2595:  \t\treturn fmt.Errorf(\"could not parse the topology file: %v\", err)\n2596:  \t}\n2597:  \n2598: +\tif c.LabRuntime != nil {\n2599: +\t\t// lab runtimes list the link interfaces packet capture accepts, with their state\n2600: +\t\tcontainerInterfaces, err := c.LabRuntimeInterfaces(cobraCmd.Context(),\n2601: +\t\t\to.Inspect.InterfacesNode)\n2602: +\t\tif err != nil {\n2603: +\t\t\treturn fmt.Errorf(\"failed to list node interfaces: %w\", err)\n2604: +\t\t}\n2605: +\t\tif len(containerInterfaces) == 0 {\n2606: +\t\t\tlog.Info(\"no running nodes found\")\n2607: +\t\t\treturn nil\n2608: +\t\t}\n2609: +\n2610: +\t\treturn printContainerInterfaces(containerInterfaces, o.Inspect.InterfacesFormat)\n2611: +\t}\n2612: +\n2613:  \tvar labNameFilterLabel string\n2614:  \n2615:  \tswitch {\n2616:  \tcase o.Global.TopologyName != \"\":\n2617:  \t\tlabNameFilterLabel = o.Global.TopologyName\n2618: diff --git a/cmd/options.go b/cmd/options.go\n2619: index 8717d3b..6037551 100644\n2620: --- a/cmd/options.go\n2621: +++ b/cmd/options.go\n2622: @@ -53,10 +53,14 @@ func GetOptions() *Options {\n2623:  \t\t\t\tInterfacesFormat: \"table\",\n2624:  \t\t\t},\n2625:  \t\t\tLogs: &LogsOptions{\n2626:  \t\t\t\tTail: -1,\n2627:  \t\t\t},\n2628: +\t\t\tCapture: &CaptureOptions{\n2629: +\t\t\t\tWrite:  \"-\",\n2630: +\t\t\t\tFormat: \"table\",\n2631: +\t\t\t},\n2632:  \t\t\tGraph: &GraphOptions{\n2633:  \t\t\t\tServer:           \"0.0.0.0:50080\",\n2634:  \t\t\t\tMermaidDirection: \"TD\",\n2635:  \t\t\t\tDrawIOVersion:    \"latest\",\n2636:  \t\t\t},\n2637: @@ -142,10 +146,11 @@ type Options struct {\n2638:  \tExec           *ExecOptions\n2639:  \tInspect        *InspectOptions\n2640:  \tGraph          *GraphOptions\n2641:  \tEvents         *EventsOptions\n2642:  \tLogs           *LogsOptions\n2643: +\tCapture        *CaptureOptions\n2644:  \tToolsAPI       *ToolsApiOptions\n2645:  \tToolsCert      *ToolsCertOptions\n2646:  \tToolsTxOffload *ToolsDisableTxOffloadOptions\n2647:  \tToolsGoTTY     *ToolsGoTTYOptions\n2648:  \tToolsNetem     *ToolsNetemOptions\n2649: @@ -257,10 +262,15 @@ type GlobalOptions struct {\n2650:  \t// special flag that should only be set by deploy, informs the context handler to destroy\n2651:  \t// (or not) when root context is canceled. The signal handler goroutine reads it while\n2652:  \t// deploy is running, so it is atomic.\n2653:  \tCleanOnCancel atomic.Bool\n2654:  \n2655: +\t// FinishOnCancel informs the context handler that the running command ends cleanly on its\n2656: +\t// own once the root context is canceled (capture finishes its output), so the handler\n2657: +\t// waits for it instead of exiting.\n2658: +\tFinishOnCancel atomic.Bool\n2659: +\n2660:  \t// special flag that is only set on deploy,\n2661:  \t// if true, the topology file backup is created at /tmp/.clab/bak\n2662:  \tBackupTopologyFile bool\n2663:  }\n2664:  \n2665: diff --git a/cmd/root.go b/cmd/root.go\n2666: index 0baf203..a9b1c8b 100644\n2667: --- a/cmd/root.go\n2668: +++ b/cmd/root.go\n2669: @@ -35,10 +35,11 @@ func subcommandRegisterFuncs() []func(*Options) (*cobra.Command, error) {\n2670:  \t\tgenerateCmd,\n2671:  \t\tgraphCmd,\n2672:  \t\teventsCmd,\n2673:  \t\tinspectCmd,\n2674:  \t\tlogsCmd,\n2675: +\t\tcaptureCmd,\n2676:  \t\tredeployCmd,\n2677:  \t\tsaveCmd,\n2678:  \t\ttoolsCmd,\n2679:  \t\tvalidateCmd,\n2680:  \t}\n2681: @@ -263,15 +264,10 @@ func checkLabRuntimeCommandSupport(cobraCmd *cobra.Command, runtimeName string)\n2682:  \t\t\t\"the %q command needs running containers with lab runtime %q unless it renders \"+\n2683:  \t\t\t\t\"from the topology file alone; use --offline, --dot, --mermaid or --drawio\",\n2684:  \t\t\t\"graph\", runtimeName)\n2685:  \t}\n2686:  \n2687: -\tif getCommandPath(cobraCmd) == \"inspect.interfaces\" {\n2688: -\t\treturn fmt.Errorf(\"the %q command is not supported with lab runtime %q\",\n2689: -\t\t\t\"inspect interfaces\", runtimeName)\n2690: -\t}\n2691: -\n2692:  \tvar unsupported []string\n2693:  \tfor _, flagName := range labRuntimeUnsupportedFlags[getCommandPath(cobraCmd)] {\n2694:  \t\tif labRuntimeFlagWasSet(cobraCmd, flagName) {\n2695:  \t\t\tunsupported = append(unsupported, \"--\"+flagName)\n2696:  \t\t}\n2697: @@ -339,10 +335,11 @@ func getTopoFilePath(cobraCmd *cobra.Command, o *Options) error { // skipcq: GO-\n2698:  \t\tcobraCmd.Name() != \"inspect\" &&\n2699:  \t\tcobraCmd.Name() != \"save\" &&\n2700:  \t\tcobraCmd.Name() != \"graph\" &&\n2701:  \t\tcobraCmd.Name() != \"validate\" &&\n2702:  \t\tcobraCmd.Name() != \"logs\" &&\n2703: +\t\tcobraCmd.Name() != \"capture\" &&\n2704:  \t\tcobraCmd.Name() != \"interfaces\" {\n2705:  \t\treturn nil\n2706:  \t}\n2707:  \n2708:  \t// start/stop/restart topology lookup applies only to top-level lifecycle commands.\n2709: diff --git a/cmd/root_test.go b/cmd/root_test.go\n2710: index 418a947..af02e34 100644\n2711: --- a/cmd/root_test.go\n2712: +++ b/cmd/root_test.go\n2713: @@ -289,20 +289,23 @@ func TestCheckLabRuntimeFlagAndNestedCommandSupport(t *testing.T) {\n2714:  \t\t\t\tt.Fatalf(\"checkLabRuntimeCommandSupport() error = %v, wantErr %v\", err, tt.wantErr)\n2715:  \t\t\t}\n2716:  \t\t})\n2717:  \t}\n2718:  \n2719: -\tt.Run(\"inspect interfaces rejected\", func(t *testing.T) {\n2720: +\tt.Run(\"inspect interfaces and capture accepted\", func(t *testing.T) {\n2721:  \t\troot := &cobra.Command{Use: \"containerlab\"}\n2722:  \t\tinspect := &cobra.Command{Use: \"inspect\"}\n2723:  \t\tinterfaces := &cobra.Command{Use: \"interfaces\"}\n2724: -\t\troot.AddCommand(inspect)\n2725: +\t\tcapture := &cobra.Command{Use: \"capture\"}\n2726: +\t\troot.AddCommand(inspect, capture)\n2727:  \t\tinspect.AddCommand(interfaces)\n2728:  \n2729: -\t\tif err := checkLabRuntimeCommandSupport(\n2730: -\t\t\tinterfaces,\n2731: -\t\t\tclablabruntime.ClabernetesRuntimeName,\n2732: -\t\t); err == nil {\n2733: -\t\t\tt.Fatal(\"inspect interfaces was accepted for clabernetes\")\n2734: +\t\tfor _, cmd := range []*cobra.Command{interfaces, capture} {\n2735: +\t\t\tif err := checkLabRuntimeCommandSupport(\n2736: +\t\t\t\tcmd,\n2737: +\t\t\t\tclablabruntime.ClabernetesRuntimeName,\n2738: +\t\t\t); err != nil {\n2739: +\t\t\t\tt.Fatalf(\"%s rejected for clabernetes: %v\", cmd.Name(), err)\n2740: +\t\t\t}\n2741:  \t\t}\n2742:  \t})\n2743:  }\n2744: diff --git a/core/capture.go b/core/capture.go\n2745: new file mode 100644\n2746: index 0000000..2e12fc2\n2747: --- /dev/null\n2748: +++ b/core/capture.go\n2749: @@ -0,0 +1,93 @@\n2750: +package core\n2751: +\n2752: +import (\n2753: +\t\"context\"\n2754: +\t\"io\"\n2755: +\n2756: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2757: +\tclabtypes \"github.com/srl-labs/containerlab/types\"\n2758: +)\n2759: +\n2760: +// CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for\n2761: +// every running node, with the peer at the other end of each link. With Docker and Podman, the\n2762: +// interfaces come from the topology's links; lab runtimes list them through their packet\n2763: +// capturer.\n2764: +func (c *CLab) CaptureInterfaces(\n2765: +\tctx context.Context,\n2766: +\tnodeNames ...string,\n2767: +) ([]clablabruntime.CaptureInterface, error) {\n2768: +\tif c.LabRuntime == nil {\n2769: +\t\treturn c.localCaptureInterfacesOf(ctx, nodeNames)\n2770: +\t}\n2771: +\n2772: +\tcapturer, err := c.packetCapturer()\n2773: +\tif err != nil {\n2774: +\t\treturn nil, err\n2775: +\t}\n2776: +\n2777: +\treturn capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{\n2778: +\t\tName:     c.Config.Name,\n2779: +\t\tNodes:    nodeNames,\n2780: +\t\tIdentity: c.labRuntimeIdentity,\n2781: +\t})\n2782: +}\n2783: +\n2784: +// Capture streams pcapng from lab link interfaces to w until req.Duration passed,\n2785: +// req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name\n2786: +// and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces\n2787: +// itself through packet sockets in the nodes' network namespaces, which needs root; lab\n2788: +// runtimes capture through their packet capturer.\n2789: +func (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {\n2790: +\tif c.LabRuntime == nil {\n2791: +\t\treturn c.captureLocal(ctx, req, w)\n2792: +\t}\n2793: +\n2794: +\tcapturer, err := c.packetCapturer()\n2795: +\tif err != nil {\n2796: +\t\treturn err\n2797: +\t}\n2798: +\n2799: +\tif req.Name == \"\" {\n2800: +\t\treq.Name = c.Config.Name\n2801: +\t}\n2802: +\tif req.Identity.IsZero() {\n2803: +\t\treq.Identity = c.labRuntimeIdentity\n2804: +\t}\n2805: +\n2806: +\treturn capturer.Capture(ctx, req, w)\n2807: +}\n2808: +\n2809: +// LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their\n2810: +// state, in the shape ListContainersInterfaces reports for local containers.\n2811: +func (c *CLab) LabRuntimeInterfaces(\n2812: +\tctx context.Context,\n2813: +\tnodeName string,\n2814: +) ([]*clabtypes.ContainerInterfaces, error) {\n2815: +\tinspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](\n2816: +\t\tc, \"inspecting interfaces\")\n2817: +\tif err != nil {\n2818: +\t\treturn nil, err\n2819: +\t}\n2820: +\tif err := c.requireLabName(); err != nil {\n2821: +\t\treturn nil, err\n2822: +\t}\n2823: +\n2824: +\treq := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}\n2825: +\tif nodeName != \"\" {\n2826: +\t\treq.Nodes = []string{nodeName}\n2827: +\t}\n2828: +\n2829: +\treturn inspector.InspectInterfaces(ctx, req)\n2830: +}\n2831: +\n2832: +func (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {\n2833: +\tcapturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, \"packet capture\")\n2834: +\tif err != nil {\n2835: +\t\treturn nil, err\n2836: +\t}\n2837: +\tif err := c.requireLabName(); err != nil {\n2838: +\t\treturn nil, err\n2839: +\t}\n2840: +\n2841: +\treturn capturer, nil\n2842: +}\n2843: diff --git a/core/capture_local.go b/core/capture_local.go\n2844: new file mode 100644\n2845: index 0000000..fada0bf\n2846: --- /dev/null\n2847: +++ b/core/capture_local.go\n2848: @@ -0,0 +1,255 @@\n2849: +package core\n2850: +\n2851: +import (\n2852: +\t\"context\"\n2853: +\t\"fmt\"\n2854: +\t\"io\"\n2855: +\t\"slices\"\n2856: +\t\"sort\"\n2857: +\t\"strings\"\n2858: +\n2859: +\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n2860: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2861: +\tclablinks \"github.com/srl-labs/containerlab/links\"\n2862: +\tclabnodes \"github.com/srl-labs/containerlab/nodes\"\n2863: +\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n2864: +)\n2865: +\n2866: +// localCaptureInterface is a lab link interface of a node on this machine.\n2867: +type localCaptureInterface struct {\n2868: +\tnode clabnodes.Node\n2869: +\tinfo clablabruntime.CaptureInterface\n2870: +}\n2871: +\n2872: +// localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with\n2873: +// the far end of each link, per node name. Host and management network endpoints are the far\n2874: +// ends of links, not nodes to capture on.\n2875: +func (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {\n2876: +\tif len(c.Nodes) == 0 {\n2877: +\t\treturn nil, fmt.Errorf(\"the topology of lab %q is not available; capture reads the \"+\n2878: +\t\t\t\"lab's links from it, pass it with --topo\", c.Config.Name)\n2879: +\t}\n2880: +\tif len(c.Links) == 0 {\n2881: +\t\tif err := c.ResolveLinks(); err != nil {\n2882: +\t\t\treturn nil, fmt.Errorf(\"failed to resolve the links of lab %q: %w\", c.Config.Name, err)\n2883: +\t\t}\n\n(Showing lines 2544-2883 of 7018. Use offset=2884 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "diff --git a/cmd/context.go b/cmd/context.go\nindex 223cb1d..21d5bea 100644\n--- a/cmd/context.go\n+++ b/cmd/context.go\n@@ -51,10 +51,20 @@ func SignalHandledContext() (context.Context, context.CancelFunc) {\n \n \t\tcancel()\n \n \t\toptions := GetOptions()\n \n+\t\tif options.Global.FinishOnCancel.Load() {\n+\t\t\tlog.Info(\"Stopping, press Ctrl+C again to abort\")\n+\n+\t\t\tsig = <-sigs\n+\n+\t\t\tlog.Errorf(\"received signal %q while stopping, exiting\", sig)\n+\n+\t\t\tos.Exit(1)\n+\t\t}\n+",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "diff --git a/cmd/context.go b/cmd/context.go\nindex 223cb1d..21d5bea 100644\n--- a/cmd/context.go\n+++ b/cmd/context.go\n@@ -51,10 +51,20 @@ func SignalHandledContext() (context.Context, context.CancelFunc) {\n \n \t\tcancel()\n \n \t\toptions := GetOptions()\n \n+\t\tif options.Global.FinishOnCancel.Load() {\n+\t\t\tlog.Info(\"Stopping, press Ctrl+C again to abort\")\n+\n+\t\t\tsig = <-sigs\n+\n+\t\t\tlog.Errorf(\"received signal %q while stopping, exiting\", sig)\n+\n+\t\t\tos.Exit(1)\n+\t\t}\n+\n \t\tif !options.Global.CleanOnCancel.Load() {\n \t\t\tlog.Debug(\"clean on cancel is not true, exiting\")\n \n \t\t\tos.Exit(1)\n \t\t}\ndiff --git a/cmd/inspect.go b/cmd/inspect.go\nindex 1b6f41d..55fb61f 100644\n--- a/cmd/inspect.go\n+++ b/cmd/inspect.go\n@@ -70,10 +70,14 @@ func inspectCmd(o *Options) (*cobra.Command, error) {\n \t\tShort: \"inspect interfaces of one or multiple nodes in a lab\",\n \t\tLong: \"show interfaces and their attributes in a specific deployed lab\\n\" +\n \t\t\t\"reference: https://containerlab.dev/cmd/inspect/interfaces/\",\n \t\tAliases: []string{\"int\", \"intf\"},\n \t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n+\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n+\t\t\t\treturn nil\n+\t\t\t}\n+\n \t\t\treturn clabutils.CheckAndGetRootPrivs()\n \t\t},\n \t\tRunE: func(cobraCmd *cobra.Command, _ []string) error {\n \t\t\treturn inspectInterfacesFn(cobraCmd, o)\n \t\t},\ndiff --git a/cmd/inspect_interfaces.go b/cmd/inspect_interfaces.go\nindex 0f64f03..91035c2 100644\n--- a/cmd/inspect_interfaces.go\n+++ b/cmd/inspect_interfaces.go\n@@ -33,10 +33,25 @@ func inspectInterfacesFn(cobraCmd *cobra.Command, o *Options) error {\n \tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"could not parse the topology file: %v\", err)\n \t}\n \n+\tif c.LabRuntime != nil {\n+\t\t// lab runtimes list the link interfaces packet capture accepts, with their state\n+\t\tcontainerInterfaces, err := c.LabRuntimeInterfaces(cobraCmd.Context(),\n+\t\t\to.Inspect.InterfacesNode)\n+\t\tif err != nil {\n+\t\t\treturn fmt.Errorf(\"failed to list node interfaces: %w\", err)\n+\t\t}\n+\t\tif len(containerInterfaces) == 0 {\n+\t\t\tlog.Info(\"no running nodes found\")\n+\t\t\treturn nil\n+\t\t}\n+\n+\t\treturn printContainerInterfaces(containerInterfaces, o.Inspect.InterfacesFormat)\n+\t}\n+\n \tvar labNameFilterLabel string\n \n \tswitch {\n \tcase o.Global.TopologyName != \"\":\n \t\tlabNameFilterLabel = o.Global.TopologyName\ndiff --git a/cmd/options.go b/cmd/options.go\nindex 8717d3b..6037551 100644\n--- a/cmd/options.go\n+++ b/cmd/options.go\n@@ -53,10 +53,14 @@ func GetOptions() *Options {\n \t\t\t\tInterfacesFormat: \"table\",\n \t\t\t},\n \t\t\tLogs: &LogsOptions{\n \t\t\t\tTail: -1,\n \t\t\t},\n+\t\t\tCapture: &CaptureOptions{\n+\t\t\t\tWrite:  \"-\",\n+\t\t\t\tFormat: \"table\",\n+\t\t\t},\n \t\t\tGraph: &GraphOptions{\n \t\t\t\tServer:           \"0.0.0.0:50080\",\n \t\t\t\tMermaidDirection: \"TD\",\n \t\t\t\tDrawIOVersion:    \"latest\",\n \t\t\t},\n@@ -142,10 +146,11 @@ type Options struct {\n \tExec           *ExecOptions\n \tInspect        *InspectOptions\n \tGraph          *GraphOptions\n \tEvents         *EventsOptions\n \tLogs           *LogsOptions\n+\tCapture        *CaptureOptions\n \tToolsAPI       *ToolsApiOptions\n \tToolsCert      *ToolsCertOptions\n \tToolsTxOffload *ToolsDisableTxOffloadOptions\n \tToolsGoTTY     *ToolsGoTTYOptions\n \tToolsNetem     *ToolsNetemOptions\n@@ -257,10 +262,15 @@ type GlobalOptions struct {\n \t// special flag that should only be set by deploy, informs the context handler to destroy\n \t// (or not) when root context is canceled. The signal handler goroutine reads it while\n \t// deploy is running, so it is atomic.\n \tCleanOnCancel atomic.Bool\n \n+\t// FinishOnCancel informs the context handler that the running command ends cleanly on its\n+\t// own once the root context is canceled (capture finishes its output), so the handler\n+\t// waits for it instead of exiting.\n+\tFinishOnCancel atomic.Bool\n+\n \t// special flag that is only set on deploy,\n \t// if true, the topology file backup is created at /tmp/.clab/bak\n \tBackupTopologyFile bool\n }\n \ndiff --git a/cmd/root.go b/cmd/root.go\nindex 0baf203..a9b1c8b 100644\n--- a/cmd/root.go\n+++ b/cmd/root.go\n@@ -35,10 +35,11 @@ func subcommandRegisterFuncs() []func(*Options) (*cobra.Command, error) {\n \t\tgenerateCmd,\n \t\tgraphCmd,\n \t\teventsCmd,\n \t\tinspectCmd,\n \t\tlogsCmd,\n+\t\tcaptureCmd,\n \t\tredeployCmd,\n \t\tsaveCmd,\n \t\ttoolsCmd,\n \t\tvalidateCmd,\n \t}\n@@ -263,15 +264,10 @@ func checkLabRuntimeCommandSupport(cobraCmd *cobra.Command, runtimeName string)\n \t\t\t\"the %q command needs running containers with lab runtime %q unless it renders \"+\n \t\t\t\t\"from the topology file alone; use --offline, --dot, --mermaid or --drawio\",\n \t\t\t\"graph\", runtimeName)\n \t}\n \n-\tif getCommandPath(cobraCmd) == \"inspect.interfaces\" {\n-\t\treturn fmt.Errorf(\"the %q command is not supported with lab runtime %q\",\n-\t\t\t\"inspect interfaces\", runtimeName)\n-\t}\n-\n \tvar unsupported []string\n \tfor _, flagName := range labRuntimeUnsupportedFlags[getCommandPath(cobraCmd)] {\n \t\tif labRuntimeFlagWasSet(cobraCmd, flagName) {\n \t\t\tunsupported = append(unsupported, \"--\"+flagName)\n \t\t}\n@@ -339,10 +335,11 @@ func getTopoFilePath(cobraCmd *cobra.Command, o *Options) error { // skipcq: GO-\n \t\tcobraCmd.Name() != \"inspect\" &&\n \t\tcobraCmd.Name() != \"save\" &&\n \t\tcobraCmd.Name() != \"graph\" &&\n \t\tcobraCmd.Name() != \"validate\" &&\n \t\tcobraCmd.Name() != \"logs\" &&\n+\t\tcobraCmd.Name() != \"capture\" &&\n \t\tcobraCmd.Name() != \"interfaces\" {\n \t\treturn nil\n \t}\n \n \t// start/stop/restart topology lookup applies only to top-level lifecycle commands.\ndiff --git a/cmd/root_test.go b/cmd/root_test.go\nindex 418a947..af02e34 100644\n--- a/cmd/root_test.go\n+++ b/cmd/root_test.go\n@@ -289,20 +289,23 @@ func TestCheckLabRuntimeFlagAndNestedCommandSupport(t *testing.T) {\n \t\t\t\tt.Fatalf(\"checkLabRuntimeCommandSupport() error = %v, wantErr %v\", err, tt.wantErr)\n \t\t\t}\n \t\t})\n \t}\n \n-\tt.Run(\"inspect interfaces rejected\", func(t *testing.T) {\n+\tt.Run(\"inspect interfaces and capture accepted\", func(t *testing.T) {\n \t\troot := &cobra.Command{Use: \"containerlab\"}\n \t\tinspect := &cobra.Command{Use: \"inspect\"}\n \t\tinterfaces := &cobra.Command{Use: \"interfaces\"}\n-\t\troot.AddCommand(inspect)\n+\t\tcapture := &cobra.Command{Use: \"capture\"}\n+\t\troot.AddCommand(inspect, capture)\n \t\tinspect.AddCommand(interfaces)\n \n-\t\tif err := checkLabRuntimeCommandSupport(\n-\t\t\tinterfaces,\n-\t\t\tclablabruntime.ClabernetesRuntimeName,\n-\t\t); err == nil {\n-\t\t\tt.Fatal(\"inspect interfaces was accepted for clabernetes\")\n+\t\tfor _, cmd := range []*cobra.Command{interfaces, capture} {\n+\t\t\tif err := checkLabRuntimeCommandSupport(\n+\t\t\t\tcmd,\n+\t\t\t\tclablabruntime.ClabernetesRuntimeName,\n+\t\t\t); err != nil {\n+\t\t\t\tt.Fatalf(\"%s rejected for clabernetes: %v\", cmd.Name(), err)\n+\t\t\t}\n \t\t}\n \t})\n }\ndiff --git a/core/capture.go b/core/capture.go\nnew file mode 100644\nindex 0000000..2e12fc2\n--- /dev/null\n+++ b/core/capture.go\n@@ -0,0 +1,93 @@\n+package core\n+\n+import (\n+\t\"context\"\n+\t\"io\"\n+\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tclabtypes \"github.com/srl-labs/containerlab/types\"\n+)\n+\n+// CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for\n+// every running node, with the peer at the other end of each link. With Docker and Podman, the\n+// interfaces come from the topology's links; lab runtimes list them through their packet\n+// capturer.\n+func (c *CLab) CaptureInterfaces(\n+\tctx context.Context,\n+\tnodeNames ...string,\n+) ([]clablabruntime.CaptureInterface, error) {\n+\tif c.LabRuntime == nil {\n+\t\treturn c.localCaptureInterfacesOf(ctx, nodeNames)\n+\t}\n+\n+\tcapturer, err := c.packetCapturer()\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treturn capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{\n+\t\tName:     c.Config.Name,\n+\t\tNodes:    nodeNames,\n+\t\tIdentity: c.labRuntimeIdentity,\n+\t})\n+}\n+\n+// Capture streams pcapng from lab link interfaces to w until req.Duration passed,\n+// req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name\n+// and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces\n+// itself through packet sockets in the nodes' network namespaces, which needs root; lab\n+// runtimes capture through their packet capturer.\n+func (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {\n+\tif c.LabRuntime == nil {\n+\t\treturn c.captureLocal(ctx, req, w)\n+\t}\n+\n+\tcapturer, err := c.packetCapturer()\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tif req.Name == \"\" {\n+\t\treq.Name = c.Config.Name\n+\t}\n+\tif req.Identity.IsZero() {\n+\t\treq.Identity = c.labRuntimeIdentity\n+\t}\n+\n+\treturn capturer.Capture(ctx, req, w)\n+}\n+\n+// LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their\n+// state, in the shape ListContainersInterfaces reports for local containers.\n+func (c *CLab) LabRuntimeInterfaces(\n+\tctx context.Context,\n+\tnodeName string,\n+) ([]*clabtypes.ContainerInterfaces, error) {\n+\tinspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](\n+\t\tc, \"inspecting interfaces\")\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tif err := c.requireLabName(); err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treq := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}\n+\tif nodeName != \"\" {\n+\t\treq.Nodes = []string{nodeName}\n+\t}\n+\n+\treturn inspector.InspectInterfaces(ctx, req)\n+}\n+\n+func (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {\n+\tcapturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, \"packet capture\")\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tif err := c.requireLabName(); err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treturn capturer, nil\n+}\ndiff --git a/core/capture_local.go b/core/capture_local.go\nnew file mode 100644\nindex 0000000..fada0bf\n--- /dev/null\n+++ b/core/capture_local.go\n@@ -0,0 +1,255 @@\n+package core\n+\n+import (\n+\t\"context\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"slices\"\n+\t\"sort\"\n+\t\"strings\"\n+\n+\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tclablinks \"github.com/srl-labs/containerlab/links\"\n+\tclabnodes \"github.com/srl-labs/containerlab/nodes\"\n+\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n+)\n+\n+// localCaptureInterface is a lab link interface of a node on this machine.\n+type localCaptureInterface struct {\n+\tnode clabnodes.Node\n+\tinfo clablabruntime.CaptureInterface\n+}\n+\n+// localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with\n+// the far end of each link, per node name. Host and management network endpoints are the far\n+// ends of links, not nodes to capture on.\n+func (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {\n+\tif len(c.Nodes) == 0 {\n+\t\treturn nil, fmt.Errorf(\"the topology of lab %q is not available; capture reads the \"+\n+\t\t\t\"lab's links from it, pass it with --topo\", c.Config.Name)\n+\t}\n+\tif len(c.Links) == 0 {\n+\t\tif err := c.ResolveLinks(); err != nil {\n+\t\t\treturn nil, fmt.Errorf(\"failed to resolve the links of lab %q: %w\", c.Config.Name, err)\n+\t\t}",
        "lineStart": 2544,
        "lineEnd": 2883,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523292348,
      "end": 1793523292365
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1965198d0001XpEbrTprXBaOC8",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965153f5001Rc1pht8HI7IZpm",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 73017,
    "input": 13422,
    "output": 76,
    "reasoning": 2111,
    "cache": {
      "read": 57408,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1965153f5001Rc1pht8HI7IZpm",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523274742,
    "completed": 1793523292372
  },
  "parentID": "msg_19650e899001051OTPpm7MOch6",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 73017,
    "input": 13422,
    "output": 76,
    "reasoning": 2111,
    "cache": {
      "read": 57408,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 20
step-start
{
  "type": "step-start",
  "id": "prt_19651a117001i99VMIDSUum1Q2",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965198db001prIIeKml33BCWn"
}
Reasoning
The `cmd/context.go` change: `SignalHandledContext` — when FinishOnCancel is set, the signal handler waits for a second signal, then `os.Exit(1)`. But there's a subtlety: after first signal, the handler cancels the root context; the command finishes its output. If the second signal comes, exit(1). But if the command finishes cleanly and the process exits, the goroutine is still blocked on `<-sigs` — that's fine, process exit cleans it.

Wait — one issue: with FinishOnCancel, the handler cancels ctx and logs "Stopping, press Ctrl+C again to abort". But `SignalHandledContext` cancel happens before this branch? Let me read the full context.go to check.

Also potential issue: `cmd/capture.go` — when capturing with `-w -` (stdout), logs go to stderr presumably; but there's a concern: when writing pcapng to stdout, any log output to stdout would corrupt. The `Run Capture --list -f json` uses stdout. The capture command with `-w -` writes pcapng to stdout. If the `log` package writes to stderr by default in containerlab? Probably fine.

More significant: `captureFn` sets `o.Global.FinishOnCancel.Store(true)` AFTER checking targets and creating `c`, but before creating the file. Then arms. Fine.

Let me now read the head cmd/context.go fully to understand the signal handling flow.
read · completed

Input

{
  "filePath": "/source/head/cmd/context.go"
}

Output

<path>/source/head/cmd/context.go</path>
<type>file</type>
<content>
1: package cmd
2: 
3: import (
4: 	"context"
5: 	"os"
6: 	"os/signal"
7: 	"syscall"
8: 	"time"
9: 
10: 	"github.com/charmbracelet/log"
11: 	"github.com/spf13/cobra"
12: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
13: )
14: 
15: const (
16: 	// maxCancelledDestroyTimeout bounds the rollback of a cancelled deployment on local
17: 	// runtimes, where removing what was created is a local and fast operation.
18: 	maxCancelledDestroyTimeout = 20 * time.Second
19: )
20: 
21: var (
22: 	// panics when closed twice, this way there can only be one signal handled context.
23: 	onlyOneSignalHandler = make(chan struct{}) //nolint: gochecknoglobals
24: 
25: 	// cancellationSignaled is closed once a SIGINT or SIGTERM has been received, letting
26: 	// commands tell a user-requested cancellation apart from an ordinary failure.
27: 	cancellationSignaled = make(chan struct{}) //nolint: gochecknoglobals
28: )
29: 
30: // SignalHandledContext returns a context that will be canceled if a SIGINT or SIGTERM is
31: // received. Rolling back whatever the canceled operation had already created is the job of
32: // the command that owns it, so that its output stays ordered and the rollback cannot race
33: // with a deployment that is still unwinding. This handler only guarantees that the process
34: // still ends when there is nothing to roll back, or when the user signals a second time.
35: func SignalHandledContext() (context.Context, context.CancelFunc) {
36: 	// panics when called twice, this way there can only be one signal handled context
37: 	close(onlyOneSignalHandler)
38: 
39: 	ctx, cancel := context.WithCancel(context.Background())
40: 
41: 	sigs := make(chan os.Signal, 2) //nolint:mnd
42: 
43: 	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
44: 
45: 	go func() {
46: 		sig := <-sigs
47: 
48: 		log.Errorf("received signal %q, canceling context", sig)
49: 
50: 		close(cancellationSignaled)
51: 
52: 		cancel()
53: 
54: 		options := GetOptions()
55: 
56: 		if options.Global.FinishOnCancel.Load() {
57: 			log.Info("Stopping, press Ctrl+C again to abort")
58: 
59: 			sig = <-sigs
60: 
61: 			log.Errorf("received signal %q while stopping, exiting", sig)
62: 
63: 			os.Exit(1)
64: 		}
65: 
66: 		if !options.Global.CleanOnCancel.Load() {
67: 			log.Debug("clean on cancel is not true, exiting")
68: 
69: 			os.Exit(1)
70: 		}
71: 
72: 		log.Info("Cleaning up the cancelled deployment, press Ctrl+C again to abort")
73: 
74: 		// The command performs the cleanup itself; exiting here would cut it short. A
75: 		// cleanup takes as long as the runtime needs to remove what was already created,
76: 		// so it is not put on a timer -- a second signal is the escape hatch instead.
77: 		sig = <-sigs
78: 
79: 		log.Errorf("received signal %q during cleanup, exiting", sig)
80: 
81: 		os.Exit(1)
82: 	}()
83: 
84: 	return ctx, cancel
85: }
86: 
87: // cancellationRequested reports whether a SIGINT or SIGTERM has been received.
88: func cancellationRequested() bool {
89: 	select {
90: 	case <-cancellationSignaled:
91: 		return true
92: 	default:
93: 		return false
94: 	}
95: }
96: 
97: // destroyCancelledDeploy removes the lab that a cancelled deployment was in the middle of
98: // creating. It runs on a fresh context because the command context is canceled by then.
99: func destroyCancelledDeploy(o *Options) {
100: 	destroyCtx, destroyCancel := context.WithTimeout(
101: 		context.Background(),
102: 		cancelledDestroyTimeout(o),
103: 	)
104: 	defer destroyCancel()
105: 
106: 	// destroyFn requires a cobra.Command but only needs the ctx from it
107: 	destroyCmd := &cobra.Command{}
108: 	destroyCmd.SetContext(destroyCtx)
109: 
110: 	err := destroyFn(destroyCmd, o)
111: 	if err != nil {
112: 		log.Errorf("failed destroying lab after cancellation signal: %v", err)
113: 	}
114: }
115: 
116: // cancelledDestroyTimeout bounds the rollback of a cancelled deployment. Controller-driven
117: // runtimes delete remote resources and wait for the cluster to converge on the deletion,
118: // which legitimately outlasts the bound that is generous for a local teardown.
119: func cancelledDestroyTimeout(o *Options) time.Duration {
120: 	if clablabruntime.IsLabRuntimeName(o.Global.Runtime) {
121: 		return o.Global.Timeout
122: 	}
123: 
124: 	return maxCancelledDestroyTimeout
125: }

(End of file - total 125 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19651a91a001wSe48EQ7zxQldX",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965198db001prIIeKml33BCWn",
  "callID": "call_32154fd316f34992805de3fe",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/cmd/context.go"
    },
    "output": "<path>/source/head/cmd/context.go</path>\n<type>file</type>\n<content>\n1: package cmd\n2: \n3: import (\n4: \t\"context\"\n5: \t\"os\"\n6: \t\"os/signal\"\n7: \t\"syscall\"\n8: \t\"time\"\n9: \n10: \t\"github.com/charmbracelet/log\"\n11: \t\"github.com/spf13/cobra\"\n12: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n13: )\n14: \n15: const (\n16: \t// maxCancelledDestroyTimeout bounds the rollback of a cancelled deployment on local\n17: \t// runtimes, where removing what was created is a local and fast operation.\n18: \tmaxCancelledDestroyTimeout = 20 * time.Second\n19: )\n20: \n21: var (\n22: \t// panics when closed twice, this way there can only be one signal handled context.\n23: \tonlyOneSignalHandler = make(chan struct{}) //nolint: gochecknoglobals\n24: \n25: \t// cancellationSignaled is closed once a SIGINT or SIGTERM has been received, letting\n26: \t// commands tell a user-requested cancellation apart from an ordinary failure.\n27: \tcancellationSignaled = make(chan struct{}) //nolint: gochecknoglobals\n28: )\n29: \n30: // SignalHandledContext returns a context that will be canceled if a SIGINT or SIGTERM is\n31: // received. Rolling back whatever the canceled operation had already created is the job of\n32: // the command that owns it, so that its output stays ordered and the rollback cannot race\n33: // with a deployment that is still unwinding. This handler only guarantees that the process\n34: // still ends when there is nothing to roll back, or when the user signals a second time.\n35: func SignalHandledContext() (context.Context, context.CancelFunc) {\n36: \t// panics when called twice, this way there can only be one signal handled context\n37: \tclose(onlyOneSignalHandler)\n38: \n39: \tctx, cancel := context.WithCancel(context.Background())\n40: \n41: \tsigs := make(chan os.Signal, 2) //nolint:mnd\n42: \n43: \tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n44: \n45: \tgo func() {\n46: \t\tsig := <-sigs\n47: \n48: \t\tlog.Errorf(\"received signal %q, canceling context\", sig)\n49: \n50: \t\tclose(cancellationSignaled)\n51: \n52: \t\tcancel()\n53: \n54: \t\toptions := GetOptions()\n55: \n56: \t\tif options.Global.FinishOnCancel.Load() {\n57: \t\t\tlog.Info(\"Stopping, press Ctrl+C again to abort\")\n58: \n59: \t\t\tsig = <-sigs\n60: \n61: \t\t\tlog.Errorf(\"received signal %q while stopping, exiting\", sig)\n62: \n63: \t\t\tos.Exit(1)\n64: \t\t}\n65: \n66: \t\tif !options.Global.CleanOnCancel.Load() {\n67: \t\t\tlog.Debug(\"clean on cancel is not true, exiting\")\n68: \n69: \t\t\tos.Exit(1)\n70: \t\t}\n71: \n72: \t\tlog.Info(\"Cleaning up the cancelled deployment, press Ctrl+C again to abort\")\n73: \n74: \t\t// The command performs the cleanup itself; exiting here would cut it short. A\n75: \t\t// cleanup takes as long as the runtime needs to remove what was already created,\n76: \t\t// so it is not put on a timer -- a second signal is the escape hatch instead.\n77: \t\tsig = <-sigs\n78: \n79: \t\tlog.Errorf(\"received signal %q during cleanup, exiting\", sig)\n80: \n81: \t\tos.Exit(1)\n82: \t}()\n83: \n84: \treturn ctx, cancel\n85: }\n86: \n87: // cancellationRequested reports whether a SIGINT or SIGTERM has been received.\n88: func cancellationRequested() bool {\n89: \tselect {\n90: \tcase <-cancellationSignaled:\n91: \t\treturn true\n92: \tdefault:\n93: \t\treturn false\n94: \t}\n95: }\n96: \n97: // destroyCancelledDeploy removes the lab that a cancelled deployment was in the middle of\n98: // creating. It runs on a fresh context because the command context is canceled by then.\n99: func destroyCancelledDeploy(o *Options) {\n100: \tdestroyCtx, destroyCancel := context.WithTimeout(\n101: \t\tcontext.Background(),\n102: \t\tcancelledDestroyTimeout(o),\n103: \t)\n104: \tdefer destroyCancel()\n105: \n106: \t// destroyFn requires a cobra.Command but only needs the ctx from it\n107: \tdestroyCmd := &cobra.Command{}\n108: \tdestroyCmd.SetContext(destroyCtx)\n109: \n110: \terr := destroyFn(destroyCmd, o)\n111: \tif err != nil {\n112: \t\tlog.Errorf(\"failed destroying lab after cancellation signal: %v\", err)\n113: \t}\n114: }\n115: \n116: // cancelledDestroyTimeout bounds the rollback of a cancelled deployment. Controller-driven\n117: // runtimes delete remote resources and wait for the cluster to converge on the deletion,\n118: // which legitimately outlasts the bound that is generous for a local teardown.\n119: func cancelledDestroyTimeout(o *Options) time.Duration {\n120: \tif clablabruntime.IsLabRuntimeName(o.Global.Runtime) {\n121: \t\treturn o.Global.Timeout\n122: \t}\n123: \n124: \treturn maxCancelledDestroyTimeout\n125: }\n\n(End of file - total 125 lines)\n</content>",
    "title": "source/head/cmd/context.go",
    "metadata": {
      "preview": "package cmd\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\t\"github.com/spf13/cobra\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\nconst (\n\t// maxCancelledDestroyTimeout bounds the rollback of a cancelled deployment on local\n\t// runtimes, where removing what was created is a local and fast operation.\n\tmaxCancelledDestroyTimeout = 20 * time.Second\n)\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/cmd/context.go",
        "text": "package cmd\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\t\"github.com/spf13/cobra\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\nconst (\n\t// maxCancelledDestroyTimeout bounds the rollback of a cancelled deployment on local\n\t// runtimes, where removing what was created is a local and fast operation.\n\tmaxCancelledDestroyTimeout = 20 * time.Second\n)\n\nvar (\n\t// panics when closed twice, this way there can only be one signal handled context.\n\tonlyOneSignalHandler = make(chan struct{}) //nolint: gochecknoglobals\n\n\t// cancellationSignaled is closed once a SIGINT or SIGTERM has been received, letting\n\t// commands tell a user-requested cancellation apart from an ordinary failure.\n\tcancellationSignaled = make(chan struct{}) //nolint: gochecknoglobals\n)\n\n// SignalHandledContext returns a context that will be canceled if a SIGINT or SIGTERM is\n// received. Rolling back whatever the canceled operation had already created is the job of\n// the command that owns it, so that its output stays ordered and the rollback cannot race\n// with a deployment that is still unwinding. This handler only guarantees that the process\n// still ends when there is nothing to roll back, or when the user signals a second time.\nfunc SignalHandledContext() (context.Context, context.CancelFunc) {\n\t// panics when called twice, this way there can only be one signal handled context\n\tclose(onlyOneSignalHandler)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tsigs := make(chan os.Signal, 2) //nolint:mnd\n\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\n\tgo func() {\n\t\tsig := <-sigs\n\n\t\tlog.Errorf(\"received signal %q, canceling context\", sig)\n\n\t\tclose(cancellationSignaled)\n\n\t\tcancel()\n\n\t\toptions := GetOptions()\n\n\t\tif options.Global.FinishOnCancel.Load() {\n\t\t\tlog.Info(\"Stopping, press Ctrl+C again to abort\")\n\n\t\t\tsig = <-sigs\n\n\t\t\tlog.Errorf(\"received signal %q while stopping, exiting\", sig)\n\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tif !options.Global.CleanOnCancel.Load() {\n\t\t\tlog.Debug(\"clean on cancel is not true, exiting\")\n\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tlog.Info(\"Cleaning up the cancelled deployment, press Ctrl+C again to abort\")\n\n\t\t// The command performs the cleanup itself; exiting here would cut it short. A\n\t\t// cleanup takes as long as the runtime needs to remove what was already created,\n\t\t// so it is not put on a timer -- a second signal is the escape hatch instead.\n\t\tsig = <-sigs\n\n\t\tlog.Errorf(\"received signal %q during cleanup, exiting\", sig)\n\n\t\tos.Exit(1)\n\t}()\n\n\treturn ctx, cancel\n}\n\n// cancellationRequested reports whether a SIGINT or SIGTERM has been received.\nfunc cancellationRequested() bool {\n\tselect {\n\tcase <-cancellationSignaled:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n// destroyCancelledDeploy removes the lab that a cancelled deployment was in the middle of\n// creating. It runs on a fresh context because the command context is canceled by then.\nfunc destroyCancelledDeploy(o *Options) {\n\tdestroyCtx, destroyCancel := context.WithTimeout(\n\t\tcontext.Background(),\n\t\tcancelledDestroyTimeout(o),\n\t)\n\tdefer destroyCancel()\n\n\t// destroyFn requires a cobra.Command but only needs the ctx from it\n\tdestroyCmd := &cobra.Command{}\n\tdestroyCmd.SetContext(destroyCtx)\n\n\terr := destroyFn(destroyCmd, o)\n\tif err != nil {\n\t\tlog.Errorf(\"failed destroying lab after cancellation signal: %v\", err)\n\t}\n}\n\n// cancelledDestroyTimeout bounds the rollback of a cancelled deployment. Controller-driven\n// runtimes delete remote resources and wait for the cluster to converge on the deletion,\n// which legitimately outlasts the bound that is generous for a local teardown.\nfunc cancelledDestroyTimeout(o *Options) time.Duration {\n\tif clablabruntime.IsLabRuntimeName(o.Global.Runtime) {\n\t\treturn o.Global.Timeout\n\t}\n\n\treturn maxCancelledDestroyTimeout\n}",
        "lineStart": 1,
        "lineEnd": 125,
        "totalLines": 125,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523296544,
      "end": 1793523296557
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19651a930001muj2hN5LKzskM9",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965198db001prIIeKml33BCWn",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 79883,
    "input": 6605,
    "output": 14,
    "reasoning": 304,
    "cache": {
      "read": 72960,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1965198db001prIIeKml33BCWn",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523292379,
    "completed": 1793523296565
  },
  "parentID": "msg_19650e899001051OTPpm7MOch6",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 79883,
    "input": 6605,
    "output": 14,
    "reasoning": 304,
    "cache": {
      "read": 72960,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 21
step-start
{
  "type": "step-start",
  "id": "prt_19651b146001TI2Ujyz82BCHuR",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19651a93c00145gf5iHrMk55rq"
}
Reasoning
One observation: when `FinishOnCancel` is set and the capture finishes cleanly (e.g., duration expires) before the user presses Ctrl+C again, the process exits normally — but the signal-handler goroutine remains blocked on `<-sigs`, which is fine.

However, there's a subtle issue: the second signal during "stopping" exits with code 1 — reasonable.

Another consideration: `defer o.Global.FinishOnCancel.Store(false)` in captureFn — if captureFn returns normally and the user had already sent one Ctrl+C... The context cancel triggers capture end; captureFn returns nil; the goroutine is still waiting for the second signal. Then main returns and the process exits. Fine.

But there's a subtle race: after `FinishOnCancel.Store(false)` (defer runs at captureFn exit), if the handler goroutine is between `GetOptions()` and the `Load()`... Actually the handler reads options once via GetOptions at that point; the `Load()` happens right after. Sequence: signal arrives → cancel() → GetOptions() → Load(). If the capture ends before the signal arrives, no issue. If the signal arrives just before captureFn's defer resets the flag, the handler sees true and waits for a second signal — process exits normally when main returns. No leak issue beyond a goroutine.

Now let me look at the diff hunks I haven't seen in detail: capture/local_test.go, pcapng_test.go, reorder_test.go, cmd/capture_test.go, core/capture_test.go, labruntime_cluster_test.go, docs, and labruntime/clabernetes/capture_test.go (1050 lines). Also the diff for labruntime/runtime.go (interface additions) and clabernetes.go.

I've already seen runtime.go diff tail (PacketCapturer interface etc. at 6410-6474). Let me view the beginning of the runtime.go hunk and clabernetes.go hunk.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 120,
  "offset": 6357
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
6357: diff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go
6358: index 3c556e7..e869191 100644
6359: --- a/labruntime/clabernetes/clabernetes.go
6360: +++ b/labruntime/clabernetes/clabernetes.go
6361: @@ -84,10 +84,18 @@ type Runtime struct {
6362:  	// identity is the configured identity of calls without one; in a connected view it is the
6363:  	// identity the clients impersonate.
6364:  	identity clablabruntime.Identity
6365:  	// pollInterval overrides how often waits poll the cluster (tests).
6366:  	pollInterval time.Duration
6367: +	// podExec overrides how commands run in pod containers (tests).
6368: +	podExec podExecFunc
6369: +	// captureSegment is the length of one chained packet capture; zero uses the clabwire
6370: +	// maximum of one hour.
6371: +	captureSegment time.Duration
6372: +	// captureReorderWindow is how long the merged capture stream holds packets back to write
6373: +	// them in timestamp order: zero uses the default, a negative value disables reordering.
6374: +	captureReorderWindow time.Duration
6375:  	// support checks once per runtime instance, before the first cluster call, that the
6376:  	// cluster runs a clabernetes release with the contract this runtime needs. Every view
6377:  	// shares it. It is nil when the clients were injected (tests).
6378:  	support *supportCheck
6379:  }
6380: @@ -253,7 +261,9 @@ func New(cfg clablabruntime.Config) (clablabruntime.LabRuntime, error) {
6381:  		timeout:              cfg.Timeout,
6382:  		kindLinkApplyMode:    cfg.KindLinkApplyMode,
6383:  		identity:             cfg.Identity,
6384:  		clients:              newClientLoader(),
6385:  		support:              &supportCheck{},
6386: +		captureSegment:       captureSegmentFromEnv(),
6387: +		captureReorderWindow: captureReorderWindowFromEnv(),
6388:  	}, nil
6389:  }
6390: diff --git a/labruntime/runtime.go b/labruntime/runtime.go
6391: index 76e651c..367565d 100644
6392: --- a/labruntime/runtime.go
6393: +++ b/labruntime/runtime.go
6394: @@ -387,10 +387,80 @@ type NodeLogStreamer interface {
6395:  // exactly one node. Closing the connection closes the stream.
6396:  type NodePortForwarder interface {
6397:  	DialPort(ctx context.Context, req NodeRequest, port int) (net.Conn, error)
6398:  }
6399:  
6400: +// CaptureInterface is a lab link interface packet capture accepts, with the far end of its link.
6401: +type CaptureInterface struct {
6402: +	// Node is the node name as the topology spells it.
6403: +	Node string `json:"node"`
6404: +	// Interface is the interface name inside the node, which capture output carries.
6405: +	Interface string `json:"interface"`
6406: +	// Alias is the name the topology used for the interface when the node kind maps it (for
6407: +	// example ethernet-1/1 for SR Linux e1-1). Capture targets accept either name.
6408: +	Alias string `json:"alias,omitempty"`
6409: +	// PeerNode is the node at the other end of the link, "host" for a host endpoint, or empty
6410: +	// when the runtime cannot name it.
6411: +	PeerNode string `json:"peer_node"`
6412: +	// PeerInterface is the peer's interface as the topology wrote it.
6413: +	PeerInterface string `json:"peer_interface"`
6414: +}
6415: +
6416: +// CaptureTarget is one interface of one node to capture. Node takes the name the topology or
6417: +// the runtime uses, Interface the interface name or its alias.
6418: +type CaptureTarget struct {
6419: +	Node      string
6420: +	Interface string
6421: +}
6422: +
6423: +// CaptureRequest selects what Capture streams.
6424: +type CaptureRequest struct {
6425: +	// Name is the lab name.
6426: +	Name      string
6427: +	Namespace string
6428: +	Targets   []CaptureTarget
6429: +	// Duration ends the capture; zero captures until the context ends.
6430: +	Duration time.Duration
6431: +	// PacketLimit ends the capture after that many packets across all targets; zero means no
6432: +	// limit.
6433: +	PacketLimit int
6434: +	// SnapLength is the number of bytes kept of each packet; zero uses the runtime default.
6435: +	SnapLength int
6436: +	// OnGap is called when the capture missed traffic, for example because a chained capture
6437: +	// did not start in time. Without it, gaps are logged as warnings.
6438: +	OnGap    func(CaptureGap)
6439: +	Identity Identity
6440: +}
6441: +
6442: +// CaptureGap is a time span a capture has no packets for, although it was running.
6443: +type CaptureGap struct {
6444: +	Node       string
6445: +	Interfaces []string
6446: +	// From and To bound the gap on the node's clock; To is zero when it is unknown.
6447: +	From   time.Time
6448: +	To     time.Time
6449: +	Reason string
6450: +}
6451: +
6452: +// PacketCapturer streams pcapng from lab link interfaces. Capture writes one section with one
6453: +// Interface Description Block per target, named <node>:<interface>, before any packet. It
6454: +// returns when Duration passed, PacketLimit packets were written, or the context ended (which
6455: +// is not an error); the output is a valid capture whenever it stops.
6456: +type PacketCapturer interface {
6457: +	CaptureInterfaces(ctx context.Context, req NodeRequest) ([]CaptureInterface, error)
6458: +	Capture(ctx context.Context, req CaptureRequest, w io.Writer) error
6459: +}
6460: +
6461: +// InterfaceInspector lists the link interfaces of a lab's nodes with their current state, in the
6462: +// shape of `inspect interfaces`.
6463: +type InterfaceInspector interface {
6464: +	InspectInterfaces(
6465: +		ctx context.Context,
6466: +		req NodeRequest,
6467: +	) ([]*clabtypes.ContainerInterfaces, error)
6468: +}
6469: +
6470:  // NodeStatsSampler reports the resource usage of a lab's nodes. It returns an error wrapping
6471:  // ErrMetricsUnavailable when the cluster serves no resource metrics.
6472:  type NodeStatsSampler interface {
6473:  	SampleStats(ctx context.Context, req InspectRequest) ([]NodeStats, error)
6474:  }
6475: diff --git a/mkdocs.yml b/mkdocs.yml
6476: index 0285ad6..8dc17bd 100644

(Showing lines 6357-6476 of 7018. Use offset=6477 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19651bbc2001g9MaAn11Hum85f",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19651a93c00145gf5iHrMk55rq",
  "callID": "call_6233fc1230c74e2f963b6b4b",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 120,
      "offset": 6357
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n6357: diff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go\n6358: index 3c556e7..e869191 100644\n6359: --- a/labruntime/clabernetes/clabernetes.go\n6360: +++ b/labruntime/clabernetes/clabernetes.go\n6361: @@ -84,10 +84,18 @@ type Runtime struct {\n6362:  \t// identity is the configured identity of calls without one; in a connected view it is the\n6363:  \t// identity the clients impersonate.\n6364:  \tidentity clablabruntime.Identity\n6365:  \t// pollInterval overrides how often waits poll the cluster (tests).\n6366:  \tpollInterval time.Duration\n6367: +\t// podExec overrides how commands run in pod containers (tests).\n6368: +\tpodExec podExecFunc\n6369: +\t// captureSegment is the length of one chained packet capture; zero uses the clabwire\n6370: +\t// maximum of one hour.\n6371: +\tcaptureSegment time.Duration\n6372: +\t// captureReorderWindow is how long the merged capture stream holds packets back to write\n6373: +\t// them in timestamp order: zero uses the default, a negative value disables reordering.\n6374: +\tcaptureReorderWindow time.Duration\n6375:  \t// support checks once per runtime instance, before the first cluster call, that the\n6376:  \t// cluster runs a clabernetes release with the contract this runtime needs. Every view\n6377:  \t// shares it. It is nil when the clients were injected (tests).\n6378:  \tsupport *supportCheck\n6379:  }\n6380: @@ -253,7 +261,9 @@ func New(cfg clablabruntime.Config) (clablabruntime.LabRuntime, error) {\n6381:  \t\ttimeout:              cfg.Timeout,\n6382:  \t\tkindLinkApplyMode:    cfg.KindLinkApplyMode,\n6383:  \t\tidentity:             cfg.Identity,\n6384:  \t\tclients:              newClientLoader(),\n6385:  \t\tsupport:              &supportCheck{},\n6386: +\t\tcaptureSegment:       captureSegmentFromEnv(),\n6387: +\t\tcaptureReorderWindow: captureReorderWindowFromEnv(),\n6388:  \t}, nil\n6389:  }\n6390: diff --git a/labruntime/runtime.go b/labruntime/runtime.go\n6391: index 76e651c..367565d 100644\n6392: --- a/labruntime/runtime.go\n6393: +++ b/labruntime/runtime.go\n6394: @@ -387,10 +387,80 @@ type NodeLogStreamer interface {\n6395:  // exactly one node. Closing the connection closes the stream.\n6396:  type NodePortForwarder interface {\n6397:  \tDialPort(ctx context.Context, req NodeRequest, port int) (net.Conn, error)\n6398:  }\n6399:  \n6400: +// CaptureInterface is a lab link interface packet capture accepts, with the far end of its link.\n6401: +type CaptureInterface struct {\n6402: +\t// Node is the node name as the topology spells it.\n6403: +\tNode string `json:\"node\"`\n6404: +\t// Interface is the interface name inside the node, which capture output carries.\n6405: +\tInterface string `json:\"interface\"`\n6406: +\t// Alias is the name the topology used for the interface when the node kind maps it (for\n6407: +\t// example ethernet-1/1 for SR Linux e1-1). Capture targets accept either name.\n6408: +\tAlias string `json:\"alias,omitempty\"`\n6409: +\t// PeerNode is the node at the other end of the link, \"host\" for a host endpoint, or empty\n6410: +\t// when the runtime cannot name it.\n6411: +\tPeerNode string `json:\"peer_node\"`\n6412: +\t// PeerInterface is the peer's interface as the topology wrote it.\n6413: +\tPeerInterface string `json:\"peer_interface\"`\n6414: +}\n6415: +\n6416: +// CaptureTarget is one interface of one node to capture. Node takes the name the topology or\n6417: +// the runtime uses, Interface the interface name or its alias.\n6418: +type CaptureTarget struct {\n6419: +\tNode      string\n6420: +\tInterface string\n6421: +}\n6422: +\n6423: +// CaptureRequest selects what Capture streams.\n6424: +type CaptureRequest struct {\n6425: +\t// Name is the lab name.\n6426: +\tName      string\n6427: +\tNamespace string\n6428: +\tTargets   []CaptureTarget\n6429: +\t// Duration ends the capture; zero captures until the context ends.\n6430: +\tDuration time.Duration\n6431: +\t// PacketLimit ends the capture after that many packets across all targets; zero means no\n6432: +\t// limit.\n6433: +\tPacketLimit int\n6434: +\t// SnapLength is the number of bytes kept of each packet; zero uses the runtime default.\n6435: +\tSnapLength int\n6436: +\t// OnGap is called when the capture missed traffic, for example because a chained capture\n6437: +\t// did not start in time. Without it, gaps are logged as warnings.\n6438: +\tOnGap    func(CaptureGap)\n6439: +\tIdentity Identity\n6440: +}\n6441: +\n6442: +// CaptureGap is a time span a capture has no packets for, although it was running.\n6443: +type CaptureGap struct {\n6444: +\tNode       string\n6445: +\tInterfaces []string\n6446: +\t// From and To bound the gap on the node's clock; To is zero when it is unknown.\n6447: +\tFrom   time.Time\n6448: +\tTo     time.Time\n6449: +\tReason string\n6450: +}\n6451: +\n6452: +// PacketCapturer streams pcapng from lab link interfaces. Capture writes one section with one\n6453: +// Interface Description Block per target, named <node>:<interface>, before any packet. It\n6454: +// returns when Duration passed, PacketLimit packets were written, or the context ended (which\n6455: +// is not an error); the output is a valid capture whenever it stops.\n6456: +type PacketCapturer interface {\n6457: +\tCaptureInterfaces(ctx context.Context, req NodeRequest) ([]CaptureInterface, error)\n6458: +\tCapture(ctx context.Context, req CaptureRequest, w io.Writer) error\n6459: +}\n6460: +\n6461: +// InterfaceInspector lists the link interfaces of a lab's nodes with their current state, in the\n6462: +// shape of `inspect interfaces`.\n6463: +type InterfaceInspector interface {\n6464: +\tInspectInterfaces(\n6465: +\t\tctx context.Context,\n6466: +\t\treq NodeRequest,\n6467: +\t) ([]*clabtypes.ContainerInterfaces, error)\n6468: +}\n6469: +\n6470:  // NodeStatsSampler reports the resource usage of a lab's nodes. It returns an error wrapping\n6471:  // ErrMetricsUnavailable when the cluster serves no resource metrics.\n6472:  type NodeStatsSampler interface {\n6473:  \tSampleStats(ctx context.Context, req InspectRequest) ([]NodeStats, error)\n6474:  }\n6475: diff --git a/mkdocs.yml b/mkdocs.yml\n6476: index 0285ad6..8dc17bd 100644\n\n(Showing lines 6357-6476 of 7018. Use offset=6477 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "diff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go\nindex 3c556e7..e869191 100644\n--- a/labruntime/clabernetes/clabernetes.go\n+++ b/labruntime/clabernetes/clabernetes.go\n@@ -84,10 +84,18 @@ type Runtime struct {\n \t// identity is the configured identity of calls without one; in a connected view it is the\n \t// identity the clients impersonate.\n \tidentity clablabruntime.Identity\n \t// pollInterval overrides how often waits poll the cluster (tests).\n \tpollInterval time.Duration\n+\t// podExec overrides how commands run in pod containers (tests).\n+\tpodExec podExecFunc\n+\t// captureSegment is the length of one chained packet capture; zero uses the clabwire\n+\t// maximum of one hour.\n+\tcaptureSegment time.Duration\n+\t// captureReorderWindow is how long the merged capture stream holds packets back to write\n+\t// them in timestamp order: zero uses the default, a negative value disables reordering.\n+\tcaptureReorderWindow time.Duration\n \t// support checks once per runtime instance, before the first cluster call, that the\n \t// cluster runs a clabernetes release with the contract this runtime needs. Every view",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "diff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go\nindex 3c556e7..e869191 100644\n--- a/labruntime/clabernetes/clabernetes.go\n+++ b/labruntime/clabernetes/clabernetes.go\n@@ -84,10 +84,18 @@ type Runtime struct {\n \t// identity is the configured identity of calls without one; in a connected view it is the\n \t// identity the clients impersonate.\n \tidentity clablabruntime.Identity\n \t// pollInterval overrides how often waits poll the cluster (tests).\n \tpollInterval time.Duration\n+\t// podExec overrides how commands run in pod containers (tests).\n+\tpodExec podExecFunc\n+\t// captureSegment is the length of one chained packet capture; zero uses the clabwire\n+\t// maximum of one hour.\n+\tcaptureSegment time.Duration\n+\t// captureReorderWindow is how long the merged capture stream holds packets back to write\n+\t// them in timestamp order: zero uses the default, a negative value disables reordering.\n+\tcaptureReorderWindow time.Duration\n \t// support checks once per runtime instance, before the first cluster call, that the\n \t// cluster runs a clabernetes release with the contract this runtime needs. Every view\n \t// shares it. It is nil when the clients were injected (tests).\n \tsupport *supportCheck\n }\n@@ -253,7 +261,9 @@ func New(cfg clablabruntime.Config) (clablabruntime.LabRuntime, error) {\n \t\ttimeout:              cfg.Timeout,\n \t\tkindLinkApplyMode:    cfg.KindLinkApplyMode,\n \t\tidentity:             cfg.Identity,\n \t\tclients:              newClientLoader(),\n \t\tsupport:              &supportCheck{},\n+\t\tcaptureSegment:       captureSegmentFromEnv(),\n+\t\tcaptureReorderWindow: captureReorderWindowFromEnv(),\n \t}, nil\n }\ndiff --git a/labruntime/runtime.go b/labruntime/runtime.go\nindex 76e651c..367565d 100644\n--- a/labruntime/runtime.go\n+++ b/labruntime/runtime.go\n@@ -387,10 +387,80 @@ type NodeLogStreamer interface {\n // exactly one node. Closing the connection closes the stream.\n type NodePortForwarder interface {\n \tDialPort(ctx context.Context, req NodeRequest, port int) (net.Conn, error)\n }\n \n+// CaptureInterface is a lab link interface packet capture accepts, with the far end of its link.\n+type CaptureInterface struct {\n+\t// Node is the node name as the topology spells it.\n+\tNode string `json:\"node\"`\n+\t// Interface is the interface name inside the node, which capture output carries.\n+\tInterface string `json:\"interface\"`\n+\t// Alias is the name the topology used for the interface when the node kind maps it (for\n+\t// example ethernet-1/1 for SR Linux e1-1). Capture targets accept either name.\n+\tAlias string `json:\"alias,omitempty\"`\n+\t// PeerNode is the node at the other end of the link, \"host\" for a host endpoint, or empty\n+\t// when the runtime cannot name it.\n+\tPeerNode string `json:\"peer_node\"`\n+\t// PeerInterface is the peer's interface as the topology wrote it.\n+\tPeerInterface string `json:\"peer_interface\"`\n+}\n+\n+// CaptureTarget is one interface of one node to capture. Node takes the name the topology or\n+// the runtime uses, Interface the interface name or its alias.\n+type CaptureTarget struct {\n+\tNode      string\n+\tInterface string\n+}\n+\n+// CaptureRequest selects what Capture streams.\n+type CaptureRequest struct {\n+\t// Name is the lab name.\n+\tName      string\n+\tNamespace string\n+\tTargets   []CaptureTarget\n+\t// Duration ends the capture; zero captures until the context ends.\n+\tDuration time.Duration\n+\t// PacketLimit ends the capture after that many packets across all targets; zero means no\n+\t// limit.\n+\tPacketLimit int\n+\t// SnapLength is the number of bytes kept of each packet; zero uses the runtime default.\n+\tSnapLength int\n+\t// OnGap is called when the capture missed traffic, for example because a chained capture\n+\t// did not start in time. Without it, gaps are logged as warnings.\n+\tOnGap    func(CaptureGap)\n+\tIdentity Identity\n+}\n+\n+// CaptureGap is a time span a capture has no packets for, although it was running.\n+type CaptureGap struct {\n+\tNode       string\n+\tInterfaces []string\n+\t// From and To bound the gap on the node's clock; To is zero when it is unknown.\n+\tFrom   time.Time\n+\tTo     time.Time\n+\tReason string\n+}\n+\n+// PacketCapturer streams pcapng from lab link interfaces. Capture writes one section with one\n+// Interface Description Block per target, named <node>:<interface>, before any packet. It\n+// returns when Duration passed, PacketLimit packets were written, or the context ended (which\n+// is not an error); the output is a valid capture whenever it stops.\n+type PacketCapturer interface {\n+\tCaptureInterfaces(ctx context.Context, req NodeRequest) ([]CaptureInterface, error)\n+\tCapture(ctx context.Context, req CaptureRequest, w io.Writer) error\n+}\n+\n+// InterfaceInspector lists the link interfaces of a lab's nodes with their current state, in the\n+// shape of `inspect interfaces`.\n+type InterfaceInspector interface {\n+\tInspectInterfaces(\n+\t\tctx context.Context,\n+\t\treq NodeRequest,\n+\t) ([]*clabtypes.ContainerInterfaces, error)\n+}\n+\n // NodeStatsSampler reports the resource usage of a lab's nodes. It returns an error wrapping\n // ErrMetricsUnavailable when the cluster serves no resource metrics.\n type NodeStatsSampler interface {\n \tSampleStats(ctx context.Context, req InspectRequest) ([]NodeStats, error)\n }\ndiff --git a/mkdocs.yml b/mkdocs.yml\nindex 0285ad6..8dc17bd 100644",
        "lineStart": 6357,
        "lineEnd": 6476,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523301317,
      "end": 1793523301332
    }
  }
}
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 130,
  "offset": 3900
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
3900: diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go
3901: new file mode 100644
3902: index 0000000..69d4072
3903: --- /dev/null
3904: +++ b/labruntime/clabernetes/capture.go
3905: @@ -0,0 +1,1202 @@
3906: +package clabernetes
3907: +
3908: +import (
3909: +	"bytes"
3910: +	"context"
3911: +	"encoding/json"
3912: +	"errors"
3913: +	"fmt"
3914: +	"hash/fnv"
3915: +	"io"
3916: +	"os"
3917: +	"sort"
3918: +	"strconv"
3919: +	"strings"
3920: +	"sync"
3921: +	"time"
3922: +
3923: +	"github.com/charmbracelet/log"
3924: +	clabcapture "github.com/srl-labs/containerlab/capture"
3925: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
3926: +	"golang.org/x/sync/errgroup"
3927: +)
3928: +
3929: +// The clabwire packet capture contract (clabernetes 0.11 or newer).
3930: +const (
3931: +	clabwireContainer = "clabwire"
3932: +	clabwireManager   = "/clabernetes/manager"
3933: +	// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.
3934: +	captureAuditSchema = "c9s.direct-packet-capture-audit/v1alpha1"
3935: +
3936: +	captureAuditStarted   = "Started"
3937: +	captureAuditSucceeded = "Succeeded"
3938: +	captureAuditFailed    = "Failed"
3939: +	captureAuditDenied    = "Denied"
3940: +
3941: +	// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.
3942: +	maxCaptureSegment = time.Hour
3943: +	// maxClabwirePackets is the packet limit of a single clabwire capture.
3944: +	maxClabwirePackets = 1_000_000
3945: +	// maxCaptureOverlap is how long two chained segments run side by side.
3946: +	maxCaptureOverlap = 10 * time.Second
3947: +	// maxCaptureCutWindow is the half-width of the window around the cut in which packets of
3948: +	// two segments are matched by content; it covers the difference between the timestamps
3949: +	// two clabwire processes give the same packet.
3950: +	maxCaptureCutWindow = 500 * time.Millisecond
3951: +	// minCaptureSegment is the shortest segment the chain requests.
3952: +	minCaptureSegment = 100 * time.Millisecond
3953: +	// captureEndGrace is how long a capture with a duration waits for its last clabwire
3954: +	// process to end after the duration passed.
3955: +	captureEndGrace = 30 * time.Second
3956: +	// captureStartRetries bounds the attempts to start a follow-up segment.
3957: +	captureStartRetries = 3
3958: +	// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was
3959: +	// closed before the stream is cut.
3960: +	captureStdinCloseGrace = 3 * time.Second
3961: +	// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A
3962: +	// Kubernetes exec does not stop its process when the stream ends, but it closes the
3963: +	// process's stdin, so every capture runs with stdin attached and this flag.
3964: +	clabwireStopOnStdinClose = "--stop-on-stdin-close"
3965: +
3966: +	// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests
3967: +	// without hour-long captures.
3968: +	envCaptureSegment = "CLAB_C9S_CAPTURE_SEGMENT"
3969: +	// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets
3970: +	// of other nodes stamped earlier but delivered later still go out before it.
3971: +	defaultCaptureReorderWindow = 250 * time.Millisecond
3972: +	// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.
3973: +	// It is an internal knob, not a supported setting.
3974: +	envCaptureReorderWindow = "CLAB_C9S_CAPTURE_REORDER_WINDOW"
3975: +)
3976: +
3977: +// podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns
3978: +// a *labruntime.CommandExitError.
3979: +type podExecFunc func(
3980: +	ctx context.Context,
3981: +	namespace, pod, container string,
3982: +	command []string,
3983: +	stdin io.Reader,
3984: +	stdout, stderr io.Writer,
3985: +) error
3986: +
3987: +// clabwireInterface is one entry of `packet-capture --list-interfaces`.
3988: +type clabwireInterface struct {
3989: +	Node          string `json:"node"`
3990: +	Interface     string `json:"interface"`
3991: +	Alias         string `json:"alias,omitempty"`
3992: +	PeerNode      string `json:"peerNode"`
3993: +	PeerInterface string `json:"peerInterface"`
3994: +}
3995: +
3996: +// captureAudit is one clabwire audit line.
3997: +type captureAudit struct {
3998: +	SchemaVersion string    `json:"schemaVersion"`
3999: +	Time          time.Time `json:"time"`
4000: +	Status        string    `json:"status"`
4001: +	NodeName      string    `json:"nodeName"`
4002: +	Format        string    `json:"format"`
4003: +	Reason        string    `json:"reason"`
4004: +	Packets       int       `json:"packets"`
4005: +	Interfaces    []struct {
4006: +		Name    string `json:"name"`
4007: +		ID      string `json:"id"`
4008: +		Packets int    `json:"packets"`
4009: +	} `json:"interfaces"`
4010: +}
4011: +
4012: +func (r *Runtime) execInPodContainer() podExecFunc {
4013: +	if r.podExec != nil {
4014: +		return r.podExec
4015: +	}
4016: +
4017: +	return r.streamPodExec
4018: +}
4019: +
4020: +// captureSegmentLength is the length of one clabwire capture before the next takes over.
4021: +func (r *Runtime) captureSegmentLength() time.Duration {
4022: +	if r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {
4023: +		return r.captureSegment
4024: +	}
4025: +
4026: +	return maxCaptureSegment
4027: +}
4028: +
4029: +// captureReorderWindowLength is the reorder window of the merged stream; zero disables

(Showing lines 3900-4029 of 7018. Use offset=4030 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19651bc03001mHZiu7XSddIikr",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19651a93c00145gf5iHrMk55rq",
  "callID": "call_b7d1f6dbfb654391a0477a78",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 130,
      "offset": 3900
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n3900: diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go\n3901: new file mode 100644\n3902: index 0000000..69d4072\n3903: --- /dev/null\n3904: +++ b/labruntime/clabernetes/capture.go\n3905: @@ -0,0 +1,1202 @@\n3906: +package clabernetes\n3907: +\n3908: +import (\n3909: +\t\"bytes\"\n3910: +\t\"context\"\n3911: +\t\"encoding/json\"\n3912: +\t\"errors\"\n3913: +\t\"fmt\"\n3914: +\t\"hash/fnv\"\n3915: +\t\"io\"\n3916: +\t\"os\"\n3917: +\t\"sort\"\n3918: +\t\"strconv\"\n3919: +\t\"strings\"\n3920: +\t\"sync\"\n3921: +\t\"time\"\n3922: +\n3923: +\t\"github.com/charmbracelet/log\"\n3924: +\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n3925: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n3926: +\t\"golang.org/x/sync/errgroup\"\n3927: +)\n3928: +\n3929: +// The clabwire packet capture contract (clabernetes 0.11 or newer).\n3930: +const (\n3931: +\tclabwireContainer = \"clabwire\"\n3932: +\tclabwireManager   = \"/clabernetes/manager\"\n3933: +\t// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.\n3934: +\tcaptureAuditSchema = \"c9s.direct-packet-capture-audit/v1alpha1\"\n3935: +\n3936: +\tcaptureAuditStarted   = \"Started\"\n3937: +\tcaptureAuditSucceeded = \"Succeeded\"\n3938: +\tcaptureAuditFailed    = \"Failed\"\n3939: +\tcaptureAuditDenied    = \"Denied\"\n3940: +\n3941: +\t// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.\n3942: +\tmaxCaptureSegment = time.Hour\n3943: +\t// maxClabwirePackets is the packet limit of a single clabwire capture.\n3944: +\tmaxClabwirePackets = 1_000_000\n3945: +\t// maxCaptureOverlap is how long two chained segments run side by side.\n3946: +\tmaxCaptureOverlap = 10 * time.Second\n3947: +\t// maxCaptureCutWindow is the half-width of the window around the cut in which packets of\n3948: +\t// two segments are matched by content; it covers the difference between the timestamps\n3949: +\t// two clabwire processes give the same packet.\n3950: +\tmaxCaptureCutWindow = 500 * time.Millisecond\n3951: +\t// minCaptureSegment is the shortest segment the chain requests.\n3952: +\tminCaptureSegment = 100 * time.Millisecond\n3953: +\t// captureEndGrace is how long a capture with a duration waits for its last clabwire\n3954: +\t// process to end after the duration passed.\n3955: +\tcaptureEndGrace = 30 * time.Second\n3956: +\t// captureStartRetries bounds the attempts to start a follow-up segment.\n3957: +\tcaptureStartRetries = 3\n3958: +\t// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was\n3959: +\t// closed before the stream is cut.\n3960: +\tcaptureStdinCloseGrace = 3 * time.Second\n3961: +\t// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A\n3962: +\t// Kubernetes exec does not stop its process when the stream ends, but it closes the\n3963: +\t// process's stdin, so every capture runs with stdin attached and this flag.\n3964: +\tclabwireStopOnStdinClose = \"--stop-on-stdin-close\"\n3965: +\n3966: +\t// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests\n3967: +\t// without hour-long captures.\n3968: +\tenvCaptureSegment = \"CLAB_C9S_CAPTURE_SEGMENT\"\n3969: +\t// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets\n3970: +\t// of other nodes stamped earlier but delivered later still go out before it.\n3971: +\tdefaultCaptureReorderWindow = 250 * time.Millisecond\n3972: +\t// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.\n3973: +\t// It is an internal knob, not a supported setting.\n3974: +\tenvCaptureReorderWindow = \"CLAB_C9S_CAPTURE_REORDER_WINDOW\"\n3975: +)\n3976: +\n3977: +// podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns\n3978: +// a *labruntime.CommandExitError.\n3979: +type podExecFunc func(\n3980: +\tctx context.Context,\n3981: +\tnamespace, pod, container string,\n3982: +\tcommand []string,\n3983: +\tstdin io.Reader,\n3984: +\tstdout, stderr io.Writer,\n3985: +) error\n3986: +\n3987: +// clabwireInterface is one entry of `packet-capture --list-interfaces`.\n3988: +type clabwireInterface struct {\n3989: +\tNode          string `json:\"node\"`\n3990: +\tInterface     string `json:\"interface\"`\n3991: +\tAlias         string `json:\"alias,omitempty\"`\n3992: +\tPeerNode      string `json:\"peerNode\"`\n3993: +\tPeerInterface string `json:\"peerInterface\"`\n3994: +}\n3995: +\n3996: +// captureAudit is one clabwire audit line.\n3997: +type captureAudit struct {\n3998: +\tSchemaVersion string    `json:\"schemaVersion\"`\n3999: +\tTime          time.Time `json:\"time\"`\n4000: +\tStatus        string    `json:\"status\"`\n4001: +\tNodeName      string    `json:\"nodeName\"`\n4002: +\tFormat        string    `json:\"format\"`\n4003: +\tReason        string    `json:\"reason\"`\n4004: +\tPackets       int       `json:\"packets\"`\n4005: +\tInterfaces    []struct {\n4006: +\t\tName    string `json:\"name\"`\n4007: +\t\tID      string `json:\"id\"`\n4008: +\t\tPackets int    `json:\"packets\"`\n4009: +\t} `json:\"interfaces\"`\n4010: +}\n4011: +\n4012: +func (r *Runtime) execInPodContainer() podExecFunc {\n4013: +\tif r.podExec != nil {\n4014: +\t\treturn r.podExec\n4015: +\t}\n4016: +\n4017: +\treturn r.streamPodExec\n4018: +}\n4019: +\n4020: +// captureSegmentLength is the length of one clabwire capture before the next takes over.\n4021: +func (r *Runtime) captureSegmentLength() time.Duration {\n4022: +\tif r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {\n4023: +\t\treturn r.captureSegment\n4024: +\t}\n4025: +\n4026: +\treturn maxCaptureSegment\n4027: +}\n4028: +\n4029: +// captureReorderWindowLength is the reorder window of the merged stream; zero disables\n\n(Showing lines 3900-4029 of 7018. Use offset=4030 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go\nnew file mode 100644\nindex 0000000..69d4072\n--- /dev/null\n+++ b/labruntime/clabernetes/capture.go\n@@ -0,0 +1,1202 @@\n+package clabernetes\n+\n+import (\n+\t\"bytes\"\n+\t\"context\"\n+\t\"encoding/json\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"hash/fnv\"\n+\t\"io\"\n+\t\"os\"\n+\t\"sort\"\n+\t\"strconv\"\n+\t\"strings\"",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go\nnew file mode 100644\nindex 0000000..69d4072\n--- /dev/null\n+++ b/labruntime/clabernetes/capture.go\n@@ -0,0 +1,1202 @@\n+package clabernetes\n+\n+import (\n+\t\"bytes\"\n+\t\"context\"\n+\t\"encoding/json\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"hash/fnv\"\n+\t\"io\"\n+\t\"os\"\n+\t\"sort\"\n+\t\"strconv\"\n+\t\"strings\"\n+\t\"sync\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\t\"golang.org/x/sync/errgroup\"\n+)\n+\n+// The clabwire packet capture contract (clabernetes 0.11 or newer).\n+const (\n+\tclabwireContainer = \"clabwire\"\n+\tclabwireManager   = \"/clabernetes/manager\"\n+\t// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.\n+\tcaptureAuditSchema = \"c9s.direct-packet-capture-audit/v1alpha1\"\n+\n+\tcaptureAuditStarted   = \"Started\"\n+\tcaptureAuditSucceeded = \"Succeeded\"\n+\tcaptureAuditFailed    = \"Failed\"\n+\tcaptureAuditDenied    = \"Denied\"\n+\n+\t// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.\n+\tmaxCaptureSegment = time.Hour\n+\t// maxClabwirePackets is the packet limit of a single clabwire capture.\n+\tmaxClabwirePackets = 1_000_000\n+\t// maxCaptureOverlap is how long two chained segments run side by side.\n+\tmaxCaptureOverlap = 10 * time.Second\n+\t// maxCaptureCutWindow is the half-width of the window around the cut in which packets of\n+\t// two segments are matched by content; it covers the difference between the timestamps\n+\t// two clabwire processes give the same packet.\n+\tmaxCaptureCutWindow = 500 * time.Millisecond\n+\t// minCaptureSegment is the shortest segment the chain requests.\n+\tminCaptureSegment = 100 * time.Millisecond\n+\t// captureEndGrace is how long a capture with a duration waits for its last clabwire\n+\t// process to end after the duration passed.\n+\tcaptureEndGrace = 30 * time.Second\n+\t// captureStartRetries bounds the attempts to start a follow-up segment.\n+\tcaptureStartRetries = 3\n+\t// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was\n+\t// closed before the stream is cut.\n+\tcaptureStdinCloseGrace = 3 * time.Second\n+\t// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A\n+\t// Kubernetes exec does not stop its process when the stream ends, but it closes the\n+\t// process's stdin, so every capture runs with stdin attached and this flag.\n+\tclabwireStopOnStdinClose = \"--stop-on-stdin-close\"\n+\n+\t// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests\n+\t// without hour-long captures.\n+\tenvCaptureSegment = \"CLAB_C9S_CAPTURE_SEGMENT\"\n+\t// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets\n+\t// of other nodes stamped earlier but delivered later still go out before it.\n+\tdefaultCaptureReorderWindow = 250 * time.Millisecond\n+\t// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.\n+\t// It is an internal knob, not a supported setting.\n+\tenvCaptureReorderWindow = \"CLAB_C9S_CAPTURE_REORDER_WINDOW\"\n+)\n+\n+// podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns\n+// a *labruntime.CommandExitError.\n+type podExecFunc func(\n+\tctx context.Context,\n+\tnamespace, pod, container string,\n+\tcommand []string,\n+\tstdin io.Reader,\n+\tstdout, stderr io.Writer,\n+) error\n+\n+// clabwireInterface is one entry of `packet-capture --list-interfaces`.\n+type clabwireInterface struct {\n+\tNode          string `json:\"node\"`\n+\tInterface     string `json:\"interface\"`\n+\tAlias         string `json:\"alias,omitempty\"`\n+\tPeerNode      string `json:\"peerNode\"`\n+\tPeerInterface string `json:\"peerInterface\"`\n+}\n+\n+// captureAudit is one clabwire audit line.\n+type captureAudit struct {\n+\tSchemaVersion string    `json:\"schemaVersion\"`\n+\tTime          time.Time `json:\"time\"`\n+\tStatus        string    `json:\"status\"`\n+\tNodeName      string    `json:\"nodeName\"`\n+\tFormat        string    `json:\"format\"`\n+\tReason        string    `json:\"reason\"`\n+\tPackets       int       `json:\"packets\"`\n+\tInterfaces    []struct {\n+\t\tName    string `json:\"name\"`\n+\t\tID      string `json:\"id\"`\n+\t\tPackets int    `json:\"packets\"`\n+\t} `json:\"interfaces\"`\n+}\n+\n+func (r *Runtime) execInPodContainer() podExecFunc {\n+\tif r.podExec != nil {\n+\t\treturn r.podExec\n+\t}\n+\n+\treturn r.streamPodExec\n+}\n+\n+// captureSegmentLength is the length of one clabwire capture before the next takes over.\n+func (r *Runtime) captureSegmentLength() time.Duration {\n+\tif r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {\n+\t\treturn r.captureSegment\n+\t}\n+\n+\treturn maxCaptureSegment\n+}\n+\n+// captureReorderWindowLength is the reorder window of the merged stream; zero disables",
        "lineStart": 3900,
        "lineEnd": 4029,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523301383,
      "end": 1793523301395
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19651bc15001W7VdBIDk3N2MA6",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19651a93c00145gf5iHrMk55rq",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 81584,
    "input": 1260,
    "output": 53,
    "reasoning": 399,
    "cache": {
      "read": 79872,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19651a93c00145gf5iHrMk55rq",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523296572,
    "completed": 1793523301400
  },
  "parentID": "msg_19650e899001051OTPpm7MOch6",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 81584,
    "input": 1260,
    "output": 53,
    "reasoning": 399,
    "cache": {
      "read": 79872,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 22
step-start
{
  "type": "step-start",
  "id": "prt_19651c4b5001gkQMs6vlaZBBEx",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19651bc1e001AQP4o3Kun6N68z"
}
Reasoning
I've now seen the core of the c9s capture.go. Let me look at the remaining diff regions I haven't seen closely: the docs (docs/cmd/capture.md, docs/manual/clabernetes/runtime.md, docs/manual/wireshark.md, docs/cmd/inspect/interfaces.md), and the test files (capture/local_test.go, pcapng_test.go, reorder_test.go, cmd/capture_test.go, core/capture_test.go, labruntime_cluster_test.go, clabernetes/capture_test.go), plus `.github/workflows` changes already seen, and the diff for `core/test_data/capture.clab.yml` (seen at 3490-3510).

Also need to check `cmd/capture.go`'s `-w -` stdout behavior vs. logs; and check the schema — `clab.schema.json` relates to topology files; new test topo uses standard fields (links type host, host-interface). No new topology keys, so no schema change needed.

Now let me focus on hunting for real defects. Key areas to check:

1. **`Output.Emit` packet limit counting vs. written**: limit counts handed-to-stream, fine.

2. **Reorder `Push` when `q.err != nil`**: returns q.err. OK.

3. **Reorder.Run timer busy-loop**: `wait = max(next.Sub(q.now()), time.Millisecond)` — if due already passed (negative), 1ms → loops at 1ms until due processed. Fine.

4. **`writeDue` holds scan**: iterates `q.holds` map each call — fine, few holds.

5. **`Reorder.Push` cursor check**: `q.cursor != 0 && packet.Timestamp < q.cursor`. Cursor is the max timestamp written in order. But early `writeLocked` in Push (late packet) writes without advancing cursor. However, the late packet may have a timestamp greater than cursor but... no, it's less. Fine.

But subtle: cursor is updated by popLocked via `max(q.cursor, item.packet.Timestamp)`. Once a packet was written out of order (late) with a timestamp *greater* than cursor... can that happen? A late packet has Timestamp < cursor, so no.

But wait: what about a packet written directly when window <= 0 — cursor never advances, irrelevant.

Another subtle issue: after a late packet is written out of order, subsequent packets with timestamps between the late packet's and cursor are also "late" — correct behavior.

6. **`Output.Close`**: cancelRun, wait runDone, Flush. But `Emit` may still be called concurrently after Close? CaptureLocal: readers exit before out.Close is called (wg.Wait). c9s: group.Wait then out.Close. OK.

7. **Potential goroutine leak in `Output`**: runDone closed on cancelRun; reorder.Run returns on ctx done. OK.

8. **`Reorder.Push` after `Flush`**: In c9s Capture, after out.Close()... chains already done. OK.

9. **`capture/local.go` `drain`** — `r.out.Emit` may return error → return. Also `time.Now().Before(deadline)` where deadline = end+250ms. But `drain` is called with `time.Now()` at ctx done. OK.

10. **`localReader.run` ctx check**: after `stop()` (packet limit reached), Emit returns false → return without drain. Fine.

11. **CaptureLocal openAll**: if `l.open` returns fewer/more sources... only with test stubs. Fine.

12. **`openPacketSockets`**: on error closes only sources opened so far in this namespace — but sources from previous nodes were appended; closeAll closes all non-nil. Good.

13. **afpacket**: `OptFrameSize(blockSize)` — TPacket frame size must be >= block size? In gopacket afpacket, for TPACKET_V3, frame size and block size are set; block size must be multiple of frame size and page size... Setting both equal to blockSize (1MiB) with 8 blocks = 8MiB ring per interface. Fine.

14. **pcapng `Writer.WritePacket`**: body cap `20+len+3` — padding at most 3. Good.

15. **`Reader.Next` peek at SHB**: If SHB is the last block and stream ends right after 8-byte header, Peek(4) returns ErrUnexpectedEOF — but the stream might legitimately end... a truncated stream. Acceptable.

16. **`pcapngNanosecondsFrom`**: tsresol raw value semantics: if_tsresol byte: most significant bit 0 → power of 10; value = exponent. So tsresol=9 → nanoseconds. `tsresol > pcapngNanoseconds` rejects e.g. 10..127, allows 0..9. And msb set → fractional (2^-n) — rejected. Comment says "Only decimal resolutions up to nanoseconds occur in clabwire streams." OK.

17. **`Reader` interface dedup between segments**: interfaces reset on new section. Packets reference ID per current section. OK.

18. **`Reorder` window vs c9s hold**: hold at cut-W; held packets of next with timestamps ≥ cut-W are emitted after active ends; the hold prevents other chains' packets with timestamps > cut-W from being written before the switch. Good.

19. **`switchSegments` gap reporting when `c.cut != 0`**: condition `if c.next == nil || c.next.started.IsZero() || c.cut == 0` → report gap. But when cut != 0 and next.started != 0, no gap — correct since overlap existed.

However — hmm, there's a subtle bug candidate: `c.cut == 0` also happens when `setCut` found the overlap too short (< 2*window). In that case the switch is reported as a gap — but packets from both segments in the overlap may double! If overlap < 2*window, the cut is not set, active streams until it ends (no dropping at cut), and held packets of next are all emitted (cut==0 → no dedup) → **duplicate packets in the overlap**. The comment in setCut says "the switch is reported as a gap" — but the overlap packets would be duplicated, not missing. Actually wait: when overlap is too short, the gap is reported (From active end / plannedEnd, To next.started). But the next segment started before active ended — packets captured by both during the overlap are emitted twice (active emits until it ends; then held of next all emitted with cut==0). Hmm, but actually does the overlap < 2*window case happen in practice? overlap = min(maxCaptureOverlap, segment/3). window = min(maxCaptureCutWindow, overlap/4). So window = overlap/4 when overlap < 2000ms → 2*window = overlap/2 < overlap → setCut succeeds. When overlap = 10s, window = 500ms, 2*window = 1s < 10s. So setCut always succeeds for computed overlaps. The cut==0 with next.started non-zero case only arises if... setCut is called on next's Started with active's plannedEnd — that's overlapEnd. overlapEnd.Sub(overlapStart) < 2*window can happen if the next started very late (near or after active's planned end). Then the switch emits held packets of next with cut==0 — dedup by content is skipped, and active wrote packets up to its end. The next's packets stamped before the active's end were captured by both → duplicates. Since the gap is reported, some data-quality loss is expected, but duplicates are a real overlap issue. Minor.

20. **`handle` retry path**: on next's done with error while active still running → retries++ and resetTimer(1s) — but `c.next = nil` and the timer fires `if c.next == nil && !c.final → startNext`. Wait: startNext is invoked on timer.C when `c.next == nil`. But after a retry the timer is set to 1s. When it fires, `startNext` again. But if the retry exhausts (retries >= captureStartRetries), the done-with-error path returns an error. OK.

But note: after `c.next = nil; resetTimer(timer, time.Second)` — the timer that fired was the next-start timer; fine.

Hmm, wait — there's a potential bug: in `handle`, the retry case returns `(false, nil)` — but the `timer` passed is the run's timer. In `run`, timer.C fires → `if c.next == nil && !c.final { c.startNext(segmentsCtx) }`. Good.

21. **`startNext` resets `c.emitted`, `c.held`, `c.cut`** — but if the previous next is still around? startNext is only called when c.next == nil. OK.

22. **`captureChain.run` — `c.active = c.start(segmentsCtx, ...)`; timer := NewTimer(c.nextStartIn())`. nextStartIn marks final if deadline near. OK.

23. **Deadline handling in `nextStartIn`**: `activeEnd.Before(deadline.Add(-window))` → if active would end after deadline - window, final. So the last segment ends near deadline. OK.

24. **`switchSegments` when final && next == nil → return true** — chain ends. But if final and next != nil (started in time), continues to emit held and switch. OK.

25. **Stopping behavior**: On ctx done, `c.stop(timer)` — closes stdins of active and next. Segments end; their done events → handle → `event.err != nil && !c.stopping` false → not error. active done → switchSegments: stopping && next not started → drop next; `if c.final && c.next == nil → return true`. Wait — `c.final` was set true by stop(). And next dropped to nil. So return true. But what about held packets not yet emitted when cut != 0? In stopping with cut != 0: held packets of next with timestamps... hmm. In switchSegments with stopping: if next.started is zero, drop next & held. If next.started non-zero (cut set), we fall through: `if c.final && c.next == nil` — next != nil → skip; gap report skipped (next.started != 0 and cut != 0); `if c.next != nil && c.next.done && !c.stopping` — stopping → skip; `if c.next == nil` — no; then the held emission loop with cut dedup — good, stopping still writes deduped held packets; then active = next; `if c.active.done → return true`. Good — final packets delivered.

26. **`drain()` on chain return**: consumes events until wg done. But wg done requires the exec goroutine to finish: exec returns when execCtx cancelled (deferred cancel at chain return — wait, `defer cancel()` is segmentsCtx cancel; segmentCtx of the *last* segments derives from segmentsCtx. execCtx is WithoutCancel(segmentCtx), so cancel of segmentCtx does NOT cancel exec. exec goroutine: after stdin closed → clabwire ends → exec returns → closes stdoutWriter → readDone → sends done event → wg.Done. If clabwire doesn't end on stdin close, the watcher goroutine cuts the stream after captureStdinCloseGrace (cancelExec). OK — bounded.

But careful: the watcher goroutine `select { case <-execDone: return; case <-segmentCtx.Done(): }` — after segmentCtx done, closes stdin, waits grace, cancels exec. Fine.

27. **Events channel capacity 256 with `send` blocking on full**: while chain is processing handle, sends from multiple segments' reader goroutines queue; capacity 256; if chain goroutine is stuck in e.g. `out.Emit`→reorder.Push (which doesn't block) fine. What about chain stuck in `switchSegments`'s emit loop? Push doesn't block. `c.events <- event` in send only blocks when full; chain loop consumes steadily. Deadlock possible? The chain calls `c.capture.emit` → `run.out.Emit` → `reorder.Push` — mutex, may block on mutex held by reorder.Run's writeDue — writeDue holds the lock while writing through `write` = writer.WritePacket → p.w.Write (io.Writer to w). If w is a slow consumer (pipe to wireshark), writeDue holds q.mu during write; Push blocks on q.mu; chain blocked; events fill up (256); send blocks; segment reader goroutines block; exec's stdoutWriter (io.Pipe) blocks; the exec goroutine blocks writing to stdoutWriter; clabwire process blocks writing stdout (kernel pipe full). Backpressure — no deadlock, just slowdown. OK.

But one real deadlock candidate: `Output.Close` waits for runDone (reorder.Run returns after cancelRun) then Flush. Reorder.Run's writeDue holds q.mu and writes. Flush takes q.mu. OK.

28. **`CaptureLocal` with `wg.Go`** — Go 1.25 `sync.WaitGroup.Go`. Fine.

29. **cmd/capture.go: stdout mode + logs**: When `-w -`, output is stdout. Does the charmbracelet log write to stdout? In containerlab, log output typically goes to stderr. Let me check the root command setup quickly.

30. **`captureFn` file Sync but no explicit Close error handling** — defer file.Close; error ignored. Minor.

31. **`printCaptureInterfaces` table**: fine.

32. **cmd/inspect_interfaces.go**: For lab runtime, `c.LabRuntimeInterfaces(cobraCmd.Context(), o.Inspect.InterfacesNode)`. Previously `inspect interfaces` was rejected for lab runtimes; now supported. Need `--name` filter? It uses o.Inspect.InterfacesNode. OK.

Now let me check the root command's log output destination to verify stdout purity, and look at docs. Also check `commandSkipsRoot` (used in capture PreRunE and inspect.interfaces). Let me grep.
Let me check a few supporting pieces: `commandSkipsRoot`, log output destination (purity of stdout pcapng), and the docs that were added.
grep · completed

Input

{
  "path": "/source/head/cmd",
  "pattern": "func commandSkipsRoot"
}

Output

Found 1 matches
/source/head/cmd/root.go:
  Line 211: func commandSkipsRoot(name string) bool {
Tool metadata
{
  "type": "tool",
  "id": "prt_1965213e4001xgibK1VyFy8Ju0",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19651bc1e001AQP4o3Kun6N68z",
  "callID": "call_baa5fddfbb124f34a6004484",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/cmd",
      "pattern": "func commandSkipsRoot"
    },
    "output": "Found 1 matches\n/source/head/cmd/root.go:\n  Line 211: func commandSkipsRoot(name string) bool {\n",
    "title": "func commandSkipsRoot",
    "metadata": {
      "matches": 1,
      "truncated": false
    },
    "time": {
      "start": 1793523323881,
      "end": 1793523323890
    }
  }
}
grep · completed

Input

{
  "path": "/source/head/cmd",
  "pattern": "log\\.SetOutput|SetOutput|log\\.New\\("
}

Output

Found 12 matches
/source/head/cmd/capture.go:
  Line 244: 	table.SetOutputMirror(w)


/source/head/cmd/inspect.go:
  Line 364: 	table.SetOutputMirror(os.Stdout)


/source/head/cmd/tools_sshx.go:
  Line 542: 		t.SetOutputMirror(os.Stdout)


/source/head/cmd/deploy_test.go:
  Line 176: 	log.SetOutput(w)

  Line 180: 		log.SetOutput(os.Stderr)


/source/head/cmd/deploy.go:
  Line 495: 	table.SetOutputMirror(os.Stdout)

  Line 524: 	table.SetOutputMirror(os.Stdout)


/source/head/cmd/tools_api_status.go:
  Line 122: 		t.SetOutputMirror(os.Stdout)


/source/head/cmd/tools_gotty.go:
  Line 564: 		t.SetOutputMirror(os.Stdout)


/source/head/cmd/root.go:
  Line 163: 	log.SetOutput(os.Stderr)


/source/head/cmd/tools_netem.go:
  Line 287: 	table.SetOutputMirror(os.Stdout)


/source/head/cmd/inspect_interfaces.go:
  Line 139: 		table.SetOutputMirror(os.Stdout)
Tool metadata
{
  "type": "tool",
  "id": "prt_19652147e0018SbYq1kjesCQFV",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19651bc1e001AQP4o3Kun6N68z",
  "callID": "call_d8885b6be86449c084a418e8",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/cmd",
      "pattern": "log\\.SetOutput|SetOutput|log\\.New\\("
    },
    "output": "Found 12 matches\n/source/head/cmd/capture.go:\n  Line 244: \ttable.SetOutputMirror(w)\n\n\n/source/head/cmd/inspect.go:\n  Line 364: \ttable.SetOutputMirror(os.Stdout)\n\n\n/source/head/cmd/tools_sshx.go:\n  Line 542: \t\tt.SetOutputMirror(os.Stdout)\n\n\n/source/head/cmd/deploy_test.go:\n  Line 176: \tlog.SetOutput(w)\n\n  Line 180: \t\tlog.SetOutput(os.Stderr)\n\n\n/source/head/cmd/deploy.go:\n  Line 495: \ttable.SetOutputMirror(os.Stdout)\n\n  Line 524: \ttable.SetOutputMirror(os.Stdout)\n\n\n/source/head/cmd/tools_api_status.go:\n  Line 122: \t\tt.SetOutputMirror(os.Stdout)\n\n\n/source/head/cmd/tools_gotty.go:\n  Line 564: \t\tt.SetOutputMirror(os.Stdout)\n\n\n/source/head/cmd/root.go:\n  Line 163: \tlog.SetOutput(os.Stderr)\n\n\n/source/head/cmd/tools_netem.go:\n  Line 287: \ttable.SetOutputMirror(os.Stdout)\n\n\n/source/head/cmd/inspect_interfaces.go:\n  Line 139: \t\ttable.SetOutputMirror(os.Stdout)\n",
    "title": "log\\.SetOutput|SetOutput|log\\.New\\(",
    "metadata": {
      "matches": 12,
      "truncated": false
    },
    "time": {
      "start": 1793523324034,
      "end": 1793523324046
    }
  }
}
read · completed

Input

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

Output

<path>/source/head/docs/cmd/capture.md</path>
<type>file</type>
<content>
1: # capture command
2: 
3: ### Description
4: 
5: The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.
6: 
7: It works with every runtime:
8: 
9: - **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).
10: - **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).
11: 
12: The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.
13: 
14: --8<-- "docs/cmd/deploy.md:env-vars-flags"
15: 
16: ### Usage
17: 
18: `containerlab [global-flags] capture [local-flags]`
19: 
20: ### Flags
21: 
22: #### topology | name
23: 
24: Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.
25: 
26: With Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.
27: 
28: #### target
29: 
30: The local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:
31: 
32: ```text
33: --target srl1:e1-1,e1-2 --target srl2:e1-1
34: ```
35: 
36: The node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.
37: 
38: Only lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.
39: 
40: #### duration
41: 
42: The local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).
43: 
44: #### packet-limit
45: 
46: The local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.
47: 
48: #### snap-length
49: 
50: The local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.
51: 
52: #### write
53: 
54: The local `--write | -w` flag names the output file. The default `-` writes to stdout.
55: 
56: #### list
57: 
58: The local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.
59: 
60: ### Output
61: 
62: The output is one pcapng section:
63: 
64: - a Section Header Block with `shb_userappl` set to `containerlab`
65: - one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it
66: - Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes
67: 
68: The interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.
69: 
70: When the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.
71: 
72: `--list -f json` prints an array:
73: 
74: ```json
75: [
76:   {
77:     "node": "srl1",
78:     "interface": "e1-1",
79:     "alias": "ethernet-1/1",
80:     "peer_node": "srl2",
81:     "peer_interface": "ethernet-1/1"
82:   }
83: ]
84: ```
85: 
86: `alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.
87: 
88: ### How Docker and Podman captures work
89: 
90: For each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.
91: 
92: - Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.
93: - 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.
94: - Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.
95: - An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.
96: 
97: The command needs root (to open packet sockets and enter network namespaces), as other lab commands do.
98: 
99: ### Long captures
100: 
101: Docker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.
102: 
103: ### Examples
104: 
105: #### Capture two nodes for 30 seconds into one file
106: 
107: ```bash
108: containerlab capture -t srl.clab.yml \
109:   --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng
110: ```
111: 
112: #### Watch a capture live in Wireshark
113: 
114: ```bash
115: containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -
116: ```
117: 
118: #### Capture the first 100 packets with tshark
119: 
120: ```bash
121: containerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -
122: ```
123: 
124: #### List the capturable interfaces
125: 
126: ```bash
127: containerlab capture --name srl --list
128: ```
129: 
130: #### Capture a c9s lab
131: 
132: ```bash
133: containerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng
134: ```

(End of file - total 134 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1965214a0001CJmGxNfQuyibrn",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19651bc1e001AQP4o3Kun6N68z",
  "callID": "call_955a2e60e1a8456b8ad37995",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/docs/cmd/capture.md"
    },
    "output": "<path>/source/head/docs/cmd/capture.md</path>\n<type>file</type>\n<content>\n1: # capture command\n2: \n3: ### Description\n4: \n5: The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.\n6: \n7: It works with every runtime:\n8: \n9: - **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).\n10: - **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).\n11: \n12: The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.\n13: \n14: --8<-- \"docs/cmd/deploy.md:env-vars-flags\"\n15: \n16: ### Usage\n17: \n18: `containerlab [global-flags] capture [local-flags]`\n19: \n20: ### Flags\n21: \n22: #### topology | name\n23: \n24: Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.\n25: \n26: With Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.\n27: \n28: #### target\n29: \n30: The local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:\n31: \n32: ```text\n33: --target srl1:e1-1,e1-2 --target srl2:e1-1\n34: ```\n35: \n36: The node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.\n37: \n38: Only lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.\n39: \n40: #### duration\n41: \n42: The local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).\n43: \n44: #### packet-limit\n45: \n46: The local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.\n47: \n48: #### snap-length\n49: \n50: The local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.\n51: \n52: #### write\n53: \n54: The local `--write | -w` flag names the output file. The default `-` writes to stdout.\n55: \n56: #### list\n57: \n58: The local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.\n59: \n60: ### Output\n61: \n62: The output is one pcapng section:\n63: \n64: - a Section Header Block with `shb_userappl` set to `containerlab`\n65: - one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it\n66: - Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes\n67: \n68: The interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.\n69: \n70: When the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.\n71: \n72: `--list -f json` prints an array:\n73: \n74: ```json\n75: [\n76:   {\n77:     \"node\": \"srl1\",\n78:     \"interface\": \"e1-1\",\n79:     \"alias\": \"ethernet-1/1\",\n80:     \"peer_node\": \"srl2\",\n81:     \"peer_interface\": \"ethernet-1/1\"\n82:   }\n83: ]\n84: ```\n85: \n86: `alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.\n87: \n88: ### How Docker and Podman captures work\n89: \n90: For each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.\n91: \n92: - Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.\n93: - 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.\n94: - Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.\n95: - An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.\n96: \n97: The command needs root (to open packet sockets and enter network namespaces), as other lab commands do.\n98: \n99: ### Long captures\n100: \n101: Docker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.\n102: \n103: ### Examples\n104: \n105: #### Capture two nodes for 30 seconds into one file\n106: \n107: ```bash\n108: containerlab capture -t srl.clab.yml \\\n109:   --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n110: ```\n111: \n112: #### Watch a capture live in Wireshark\n113: \n114: ```bash\n115: containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n116: ```\n117: \n118: #### Capture the first 100 packets with tshark\n119: \n120: ```bash\n121: containerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -\n122: ```\n123: \n124: #### List the capturable interfaces\n125: \n126: ```bash\n127: containerlab capture --name srl --list\n128: ```\n129: \n130: #### Capture a c9s lab\n131: \n132: ```bash\n133: containerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng\n134: ```\n\n(End of file - total 134 lines)\n</content>",
    "title": "source/head/docs/cmd/capture.md",
    "metadata": {
      "preview": "# capture command\n\n### Description\n\nThe `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.\n\nIt works with every runtime:\n\n- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).\n- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).\n\nThe output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.\n\n--8<-- \"docs/cmd/deploy.md:env-vars-flags\"\n\n### Usage\n\n`containerlab [global-flags] capture [local-flags]`\n\n### Flags",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/docs/cmd/capture.md",
        "text": "# capture command\n\n### Description\n\nThe `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.\n\nIt works with every runtime:\n\n- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).\n- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).\n\nThe output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.\n\n--8<-- \"docs/cmd/deploy.md:env-vars-flags\"\n\n### Usage\n\n`containerlab [global-flags] capture [local-flags]`\n\n### Flags\n\n#### topology | name\n\nUse the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.\n\nWith Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.\n\n#### target\n\nThe local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:\n\n```text\n--target srl1:e1-1,e1-2 --target srl2:e1-1\n```\n\nThe node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.\n\nOnly lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.\n\n#### duration\n\nThe local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).\n\n#### packet-limit\n\nThe local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.\n\n#### snap-length\n\nThe local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.\n\n#### write\n\nThe local `--write | -w` flag names the output file. The default `-` writes to stdout.\n\n#### list\n\nThe local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.\n\n### Output\n\nThe output is one pcapng section:\n\n- a Section Header Block with `shb_userappl` set to `containerlab`\n- one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it\n- Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes\n\nThe interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.\n\nWhen the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.\n\n`--list -f json` prints an array:\n\n```json\n[\n  {\n    \"node\": \"srl1\",\n    \"interface\": \"e1-1\",\n    \"alias\": \"ethernet-1/1\",\n    \"peer_node\": \"srl2\",\n    \"peer_interface\": \"ethernet-1/1\"\n  }\n]\n```\n\n`alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.\n\n### How Docker and Podman captures work\n\nFor each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.\n\n- Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.\n- 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.\n- Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.\n- An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.\n\nThe command needs root (to open packet sockets and enter network namespaces), as other lab commands do.\n\n### Long captures\n\nDocker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.\n\n### Examples\n\n#### Capture two nodes for 30 seconds into one file\n\n```bash\ncontainerlab capture -t srl.clab.yml \\\n  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n```\n\n#### Watch a capture live in Wireshark\n\n```bash\ncontainerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n```\n\n#### Capture the first 100 packets with tshark\n\n```bash\ncontainerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -\n```\n\n#### List the capturable interfaces\n\n```bash\ncontainerlab capture --name srl --list\n```\n\n#### Capture a c9s lab\n\n```bash\ncontainerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng\n```",
        "lineStart": 1,
        "lineEnd": 134,
        "totalLines": 134,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523324068,
      "end": 1793523324085
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1965214b8001AUr65Jid0xRkG5",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19651bc1e001AQP4o3Kun6N68z",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 88422,
    "input": 3909,
    "output": 97,
    "reasoning": 3008,
    "cache": {
      "read": 81408,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19651bc1e001AQP4o3Kun6N68z",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523301406,
    "completed": 1793523324091
  },
  "parentID": "msg_19650e899001051OTPpm7MOch6",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 88422,
    "input": 3909,
    "output": 97,
    "reasoning": 3008,
    "cache": {
      "read": 81408,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
User · 23
compaction
{
  "type": "compaction",
  "id": "prt_1965214bd001KGLCCFEDlx60mc",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965214bc001V4qO87RkNunl5l",
  "auto": true,
  "overflow": false,
  "tail_start_id": "msg_1965198db001prIIeKml33BCWn"
}
Message metadata
{
  "role": "user",
  "id": "msg_1965214bc001V4qO87RkNunl5l",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523324092
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 24
step-start
{
  "type": "step-start",
  "id": "prt_196521b4b001STAM5ft73BrjG5",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965214cd001OiEB6AGoktsxhx"
}
Reasoning
Combine summaries. Need to capture all the detailed observations from the conversation — the review notes on capture package files, cmd files, etc. Keep terse but preserve key identifiers and findings.
## Objective
- Review the read-only PR snapshot at `/source` (srl-labs/containerlab): read `standards.json` + referenced rules, fully review `diff.txt` (7018 lines, 37 changed paths) and head/base files, completing per-path checks (callers, tests, docs, schema) before producing the trusted result schema.

## Important Details
- Head commit: `657b1700664a99c5e12c60b4cfd179eb11889bae`; base/mergeBase: `00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4`.
- Permalink roots: head=`https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/`; base=`https://github.com/srl-labs/containerlab/blob/00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4/`.
- Snapshot incomplete: false; full inventory in `/source/manifest.json` (head at `657b170...`, confirmed).
- Source-only review; cannot execute tests — disclose limitation in final result.
- Standards: `.cursor/rules/karpathy-guidelines.mdc` (surgical changes, simplicity) and `.cursor/rules/ponytail.mdc` (YAGNI, reuse, shortest diff).
- Direct `read` of the `/source` directory itself is denied; read individual files. **Head files live under `/source/head/...`** (e.g., `/source/head/capture/local.go`), not `/source/capture/...`.
- The PR adds a packet-capture feature: new `capture` package (`local.go`, `reorder.go`, `pcapng.go`, `output.go` + tests), new `cmd/capture.go` (+test), new `core/capture.go`/`core/capture_local.go` (+test), c9s (clabernetes) runtime capture (`labruntime/clabernetes/capture.go`, ~1202 lines; `capture_interfaces.go`) with chained capture segments (max 1h segment, 10s overlap, 500ms cut window) and `CaptureGap` reporting, `streamPodExec` in clabernetes, plus doc/workflow/CMD-modification changes.
- Full 37-path inventory from manifest.json (status): M: `.github/workflows/clabernetes-tests.yml`, `.github/workflows/smoke-tests.yml`, `cmd/context.go`, `cmd/inspect.go`, `cmd/inspect_interfaces.go`, `cmd/options.go`, `cmd/root.go`, `cmd/root_test.go`; A: `capture/{local.go, local_test.go, output.go, pcapng.go, pcapng_test.go, reorder.go, reorder_test.go}`, `cmd/{capture.go, capture_test.go}`, `core/{capture.go, capture_local.go, capture_test.go}`, `core/labruntime_cluster_test.go` (M), `core/test_data/capture.clab.yml`, `docs/cmd/capture.md`, `docs/cmd/inspect/interfaces.md` (M), `docs/manual/clabernetes/runtime.md` (M), `docs/manual/wireshark.md` (M), plus `labruntime/clabernetes/capture*.go` and others (manifest truncated after ~20 entries; remaining ~17 paths include `labruntime/clabernetes/` files — need to finish enumerating from diff grep results which listed through line 3900+).
- Diff grep anchors (`^diff --git` line numbers): workflows (1, 21), capture/* (37–1676), cmd/* (2161–2709), core/* (2744–3320), test_data (3490), docs (3511–3879), labruntime/clabernetes/... starts at 3900.

## Work State
### Completed
- Read `standards.json` and both referenced rule files.
- Full diff.txt traversed via overlapping offset reads (1, 1702, 3478, 4780, 6410) covering all 7018 lines; grep enumerated 37 `diff --git` headers.
- Read `manifest.json` (head/base/mergeBase hashes, ~20 of 37 changed paths visible before truncation).
- Reviewed head files in detail: `/source/head/capture/local.go` (constants: localReorderWindow=100ms, localBlockTimeout=10ms, localPollTimeout=100ms, localReopenInterval=200ms, localDrainQuiet=5×block, localDrainTimeout=250ms, ring 8×1MiB blocks, vlanHeaderLength=4; afpacket + ns package use), `/source/head/capture/reorder.go` (Reorder with min-heap, maxReorderBytes=64MiB, holds map, cursor tracking, late/forced stats), `/source/head/capture/pcapng.go` (block type consts, pcapngMaxBlockLength=1MiB+1024, InterfaceDescription/Packet types, errPCAPNGByteOrder), `/source/head/capture/output.go` (ValidateRequest: DefaultSnapLength=256KiB, Min=64, Max=1MiB; FindInterface by name then alias), `/source/head/cmd/capture.go` (flags: --target `<node>:<iface>[,...]` repeatable, --duration, --packet-limit, --snap-length, --write, --list, --format; PreRunE skips root via `commandSkipsRoot(o.Global.Runtime)` for c9s), `/source/head/core/capture.go` (CLab.Capture/CaptureInterfaces dispatching to local capture or packetCapturer), `/source/head/core/capture_local.go` (localCaptureInterfaces; skips nodeless/runtime-discovered endpoints; ResolveLinks if c.Links empty), `/source/head/labruntime/clabernetes/capture.go` (captureChain state machine: events chan buf 256, clabwire audit schema `c9s.direct-packet-capture-audit/v1alpha1`, audit states Started/Succeeded/Failed/Denied, maxCaptureSegment=1h, maxClabwirePackets=1M, setCut/switchSegments/hold+Release semantics, emitted-map dedup via fnv64 of interface+data), `/source/head/labruntime/clabernetes/capture_interfaces.go` (streamPodExec via remotecommand StreamWithContext, kubeexec.ExitError → labruntime.CommandExitError).
- Read diff hunks for `cmd/context.go` (new FinishOnCancel: on first signal logs "Stopping, press Ctrl+C again to abort", waits for second signal, `os.Exit(1)`), `cmd/inspect.go` (PreRunE root-skip via commandSkipsRoot), `cmd/inspect_interfaces.go` (partial).
- Initial defect-scan notes collected (see Active).

### Active
- Reviewing remaining files: rest of `/source/head/labruntime/clabernetes/capture.go` internals, diff hunks for `cmd/options.go`, `cmd/root.go`, `cmd/root_test.go`, `labruntime/clabernetes/clabernetes.go` and `runtime.go` changes, `core/labruntime_cluster_test.go`, docs (`docs/manual/clabernetes/runtime.md`, `docs/manual/wireshark.md`, `docs/cmd/inspect/interfaces.md`), and workflows.
- Candidate issues noted so far (to verify/refine): `Output.Emit` increments `written` before `reorder.Push` may fail; `openAll` assumes opened-sources count == len(names) (possible index panic/nil); pcapng `Next` returns ErrUnexpectedEOF on clean EOF when SHB peek short-reads; `WritePacket` wraps negative timestamps (nolint'd); drain deadline uses `time.Now().Before(deadline)` with 100ms-blocking ReadPacket; reorder late-packet direct write doesn't update cursor (benign); held-packet growth in captureChain while stopping (bounded by reorder maxReorderBytes).
- Trace-level reasoning for captureChain event ordering (switchSegments with next not-yet-Started, setCut only when segment==c.next && active.started nonzero, hold Release ordering, errgroup ctx cancel on first error) — appears consistent so far.

### Blocked
- Cannot execute tests (read-only snapshot) — must be disclosed in final result.
- manifest.json truncated in tool output; remaining changed paths must be enumerated via diff headers (grep done; need to finish mapping line 3900–7018 paths to names).

## Next Move
1. Read remaining diff hunks: `cmd/options.go` (2618), `cmd/root.go` (2665), `cmd/root_test.go` (2709), `core/labruntime_cluster_test.go` (3320), docs (3511–3899), and `labruntime/clabernetes/` paths (3900+) — enumerate exact remaining paths from diff headers.
2. Review `/source/head/labruntime/clabernetes/` supporting changes (clabernetes.go, runtime.go, command exit handling), then assemble final trusted result with per-path verdicts, the test-execution limitation disclosed, and permalink references.

## Relevant Files
- `/source/standards.json`, `/source/standards/karpathy-guidelines.mdc`, `/source/standards/ponytail.mdc` — review standards (read).
- `/source/diff.txt` — full 7018-line PR diff (fully traversed).
- `/source/manifest.json` — full 37-path inventory (partially shown; head hash `657b1700664a99c5e12c60b4cfd179eb11889bae`).
- `/source/head/capture/{local.go, local_test.go, output.go, pcapng.go, pcapng_test.go, reorder.go, reorder_test.go}` — new capture package (local.go, reorder.go, pcapng.go, output.go read; tests not yet read).
- `/source/head/cmd/capture.go`, `/source/head/cmd/capture_test.go`, `/source/head/cmd/{context.go, inspect.go, inspect_interfaces.go, options.go, root.go, root_test.go}` — command layer (capture.go read; rest via diff only).
- `/source/head/core/{capture.go, capture_local.go, capture_test.go, labruntime_cluster_test.go}` — core integration (capture.go, capture_local.go read).
- `/source/head/labruntime/clabernetes/{capture.go, capture_interfaces.go, clabernetes.go, runtime.go}` — c9s capture implementation (capture.go + capture_interfaces.go partially read).
- `/source/core/test_data/capture.clab.yml` — new test topology (2× nokia_srlinux + alpine:3, 4 links incl. host + mgmt-net).
- `/source/docs/cmd/capture.md`, `/source/docs/cmd/inspect/interfaces.md`, `/source/docs/manual/clabernetes/runtime.md`, `/source/docs/manual/wireshark.md` — documentation changes.
- `/source/.github/workflows/{clabernetes-tests.yml, smoke-tests.yml}` — CI changes (tshark install; `"33*.robot"` glob).
step-finish
{
  "type": "step-finish",
  "id": "prt_196524553001fv6wtkUQpGdGO7",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965214cd001OiEB6AGoktsxhx",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 17495,
    "input": 15077,
    "output": 2381,
    "reasoning": 37,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1965214cd001OiEB6AGoktsxhx",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523324109,
    "completed": 1793523336536
  },
  "parentID": "msg_1965214bc001V4qO87RkNunl5l",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "compaction",
  "agent": "compaction",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "summary": true,
  "cost": 0,
  "tokens": {
    "total": 17495,
    "input": 15077,
    "output": 2381,
    "reasoning": 37,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "stop"
}
User · 25
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_19652455c001bTBRfavhAuXSsP",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523336540
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 26
step-start
{
  "type": "step-start",
  "id": "prt_196524d1e001QYuBFiifSUGAdH",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196524566001amBVNvfJ9FiMxm"
}
Reasoning
I should continue the review. Remaining work: review remaining diff hunks (cmd/options.go, cmd/root.go, cmd/root_test.go, core/labruntime_cluster_test.go, docs, labruntime/clabernetes/capture.go details, capture_interfaces.go, capture_test.go), and verify candidate issues, then produce final review + JSON.

Let me read the diff sections I haven't seen: lines 2161-2744 (cmd changes) I saw partially earlier? In the summary I noted reading diff hunks for cmd/context.go, cmd/inspect.go, cmd/inspect_interfaces.go partial. Let me re-read diff 2161-2744 and 3320-3900 (core test + docs), and the rest of capture_test files. Also cmd/root.go hunk (commandSkipsRoot), options.go.

Also verify the cmd/capture.go stdout purity: log output goes to stderr (root.go line 163), so `-w -` is fine. But `printCaptureInterfaces` writes to stdout for --list. OK.

Let me proceed reading the remaining diff.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 600,
  "offset": 2161
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
2161: diff --git a/cmd/capture.go b/cmd/capture.go
2162: new file mode 100644
2163: index 0000000..20117bc
2164: --- /dev/null
2165: +++ b/cmd/capture.go
2166: @@ -0,0 +1,262 @@
2167: +package cmd
2168: +
2169: +import (
2170: +	"encoding/json"
2171: +	"fmt"
2172: +	"io"
2173: +	"os"
2174: +	"strings"
2175: +	"time"
2176: +
2177: +	"github.com/charmbracelet/log"
2178: +	tableWriter "github.com/jedib0t/go-pretty/v6/table"
2179: +	"github.com/jedib0t/go-pretty/v6/text"
2180: +	"github.com/spf13/cobra"
2181: +	clabconstants "github.com/srl-labs/containerlab/constants"
2182: +	clabcore "github.com/srl-labs/containerlab/core"
2183: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2184: +	clabutils "github.com/srl-labs/containerlab/utils"
2185: +)
2186: +
2187: +// CaptureOptions are the flags of the capture command.
2188: +type CaptureOptions struct {
2189: +	Targets     []string
2190: +	Duration    time.Duration
2191: +	PacketLimit int
2192: +	SnapLength  int
2193: +	Write       string
2194: +	List        bool
2195: +	Format      string
2196: +}
2197: +
2198: +func captureCmd(o *Options) (*cobra.Command, error) {
2199: +	c := &cobra.Command{
2200: +		Use:   "capture",
2201: +		Short: "capture packets on lab link interfaces",
2202: +		Long: "capture packets on lab link interfaces of one or more nodes into one pcapng " +
2203: +			"stream\nreference: https://containerlab.dev/cmd/capture/",
2204: +		PreRunE: func(_ *cobra.Command, _ []string) error {
2205: +			if commandSkipsRoot(o.Global.Runtime) {
2206: +				return nil
2207: +			}
2208: +
2209: +			// Docker and Podman captures open packet sockets in the nodes' namespaces
2210: +			return clabutils.CheckAndGetRootPrivs()
2211: +		},
2212: +		SilenceUsage: true,
2213: +		RunE: func(cmd *cobra.Command, _ []string) error {
2214: +			return captureFn(cmd, o)
2215: +		},
2216: +	}
2217: +
2218: +	c.Flags().StringArrayVar(
2219: +		&o.Capture.Targets,
2220: +		"target",
2221: +		o.Capture.Targets,
2222: +		"node and interfaces to capture, as <node>:<interface>[,<interface>...]; repeatable",
2223: +	)
2224: +	c.Flags().DurationVar(
2225: +		&o.Capture.Duration,
2226: +		"duration",
2227: +		o.Capture.Duration,
2228: +		"stop after this duration; 0 captures until interrupted",
2229: +	)
2230: +	c.Flags().IntVar(
2231: +		&o.Capture.PacketLimit,
2232: +		"packet-limit",
2233: +		o.Capture.PacketLimit,
2234: +		"stop after this many packets across all targets; 0 means no limit",
2235: +	)
2236: +	c.Flags().IntVar(
2237: +		&o.Capture.SnapLength,
2238: +		"snap-length",
2239: +		o.Capture.SnapLength,
2240: +		"bytes kept of each packet (64 to 1048576); 0 uses the runtime default",
2241: +	)
2242: +	c.Flags().StringVarP(
2243: +		&o.Capture.Write,
2244: +		"write",
2245: +		"w",
2246: +		o.Capture.Write,
2247: +		"pcapng output file; - writes to stdout",
2248: +	)
2249: +	c.Flags().BoolVar(
2250: +		&o.Capture.List,
2251: +		"list",
2252: +		o.Capture.List,
2253: +		"list the capturable interfaces instead of capturing",
2254: +	)
2255: +	c.Flags().StringVarP(
2256: +		&o.Capture.Format,
2257: +		"format",
2258: +		"f",
2259: +		o.Capture.Format,
2260: +		"output format of --list: table or json",
2261: +	)
2262: +
2263: +	c.Example = `# Capture e1-1 of srl1 and e1-1 of srl2 for 30 seconds into one file
2264: +containerlab capture -t srl.clab.yml --target srl1:e1-1 --target srl2:e1-1 \
2265: +  --duration 30s -w srl.pcapng
2266: +
2267: +# Capture two interfaces of one node and watch them live in Wireshark
2268: +containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -
2269: +
2270: +# List the interfaces capture accepts
2271: +containerlab capture --name srl --list -f json
2272: +
2273: +# Capture a lab running on the c9s runtime
2274: +containerlab -r c9s capture --name srl --target srl1:e1-1 -w srl.pcapng`
2275: +
2276: +	return c, nil
2277: +}
2278: +
2279: +func captureFn(cmd *cobra.Command, o *Options) error {
2280: +	if o.Global.TopologyName == "" && o.Global.TopologyFile == "" {
2281: +		return fmt.Errorf("provide either a lab name (--name) or a topology file path (--topo)")
2282: +	}
2283: +
2284: +	if o.Capture.List {
2285: +		return captureListFn(cmd, o)
2286: +	}
2287: +
2288: +	targets, err := parseCaptureTargets(o.Capture.Targets)
2289: +	if err != nil {
2290: +		return err
2291: +	}
2292: +
2293: +	c, err := clabcore.NewContainerLab(o.ToClabOptions()...)
2294: +	if err != nil {
2295: +		return err
2296: +	}
2297: +
2298: +	// An interrupt ends the capture; the command still finishes the file and exits cleanly.
2299: +	// Armed before the file is created, so an interrupt never leaves it empty.
2300: +	o.Global.FinishOnCancel.Store(true)
2301: +	defer o.Global.FinishOnCancel.Store(false)
2302: +
2303: +	output := cmd.OutOrStdout()
2304: +	if o.Capture.Write != "" && o.Capture.Write != "-" {
2305: +		file, err := os.Create(o.Capture.Write)
2306: +		if err != nil {
2307: +			return fmt.Errorf("failed to create the capture file: %w", err)
2308: +		}
2309: +		defer file.Close()
2310: +		output = file
2311: +
2312: +		// the file belongs to the user who ran the command, also through sudo or setuid
2313: +		if err := clabutils.SetUIDAndGID(o.Capture.Write); err != nil {
2314: +			log.Debug("Cannot hand the capture file to the user", "file", o.Capture.Write,
2315: +				"error", err)
2316: +		}
2317: +	}
2318: +
2319: +	err = c.Capture(cmd.Context(), clablabruntime.CaptureRequest{
2320: +		Targets:     targets,
2321: +		Duration:    o.Capture.Duration,
2322: +		PacketLimit: o.Capture.PacketLimit,
2323: +		SnapLength:  o.Capture.SnapLength,
2324: +	}, output)
2325: +	if err != nil {
2326: +		return err
2327: +	}
2328: +
2329: +	if file, ok := output.(*os.File); ok && output != cmd.OutOrStdout() {
2330: +		if err := file.Sync(); err != nil {
2331: +			return fmt.Errorf("failed to write the capture file: %w", err)
2332: +		}
2333: +	}
2334: +
2335: +	return nil
2336: +}
2337: +
2338: +// parseCaptureTargets parses --target values: <node>:<interface>[,<interface>...]. The node name
2339: +// ends at the first colon, so interface names may contain colons or slashes.
2340: +func parseCaptureTargets(values []string) ([]clablabruntime.CaptureTarget, error) {
2341: +	if len(values) == 0 {
2342: +		return nil, fmt.Errorf("provide at least one --target <node>:<interface>[,<interface>...]")
2343: +	}
2344: +
2345: +	targets := make([]clablabruntime.CaptureTarget, 0, len(values))
2346: +	for _, value := range values {
2347: +		node, interfaces, ok := strings.Cut(strings.TrimSpace(value), ":")
2348: +		node = strings.TrimSpace(node)
2349: +		if !ok || node == "" || strings.TrimSpace(interfaces) == "" {
2350: +			return nil, fmt.Errorf("invalid --target %q: use <node>:<interface>[,<interface>...]",
2351: +				value)
2352: +		}
2353: +
2354: +		for _, name := range strings.Split(interfaces, ",") {
2355: +			name = strings.TrimSpace(name)
2356: +			if name == "" {
2357: +				return nil, fmt.Errorf("invalid --target %q: empty interface name", value)
2358: +			}
2359: +			targets = append(targets, clablabruntime.CaptureTarget{Node: node, Interface: name})
2360: +		}
2361: +	}
2362: +
2363: +	return targets, nil
2364: +}
2365: +
2366: +func captureListFn(cmd *cobra.Command, o *Options) error {
2367: +	format := o.Capture.Format
2368: +	if format == "" {
2369: +		format = clabconstants.FormatTable
2370: +	}
2371: +	if format != clabconstants.FormatTable && format != clabconstants.FormatJSON {
2372: +		return fmt.Errorf("output format %q is not supported, use 'table' or 'json'", format)
2373: +	}
2374: +	if len(o.Capture.Targets) != 0 {
2375: +		return fmt.Errorf("--list lists every running node's interfaces; it takes no --target")
2376: +	}
2377: +
2378: +	c, err := clabcore.NewContainerLab(o.ToClabOptions()...)
2379: +	if err != nil {
2380: +		return err
2381: +	}
2382: +
2383: +	interfaces, err := c.CaptureInterfaces(cmd.Context())
2384: +	if err != nil {
2385: +		return err
2386: +	}
2387: +
2388: +	return printCaptureInterfaces(cmd.OutOrStdout(), interfaces, format)
2389: +}
2390: +
2391: +func printCaptureInterfaces(
2392: +	w io.Writer,
2393: +	interfaces []clablabruntime.CaptureInterface,
2394: +	format string,
2395: +) error {
2396: +	if format == clabconstants.FormatJSON {
2397: +		if interfaces == nil {
2398: +			interfaces = []clablabruntime.CaptureInterface{}
2399: +		}
2400: +		data, err := json.MarshalIndent(interfaces, "", "  ")
2401: +		if err != nil {
2402: +			return err
2403: +		}
2404: +		_, err = fmt.Fprintln(w, string(data))
2405: +
2406: +		return err
2407: +	}
2408: +
2409: +	table := tableWriter.NewWriter()
2410: +	table.SetOutputMirror(w)
2411: +	table.SetStyle(tableWriter.StyleRounded)
2412: +	table.Style().Format.Header = text.FormatTitle
2413: +	table.Style().Format.HeaderAlign = text.AlignCenter
2414: +	table.AppendHeader(tableWriter.Row{"Node", "Interface", "Alias", "Peer Node", "Peer Interface"})
2415: +	table.SetColumnConfigs([]tableWriter.ColumnConfig{{Number: 1, AutoMerge: true}})
2416: +	for _, intf := range interfaces {
2417: +		alias := intf.Alias
2418: +		if alias == "" {
2419: +			alias = clabconstants.NotApplicable
2420: +		}
2421: +		table.AppendRow(tableWriter.Row{
2422: +			intf.Node, intf.Interface, alias, intf.PeerNode, intf.PeerInterface,
2423: +		})
2424: +	}
2425: +	table.Render()
2426: +
2427: +	return nil
2428: +}
2429: diff --git a/cmd/capture_test.go b/cmd/capture_test.go
2430: new file mode 100644
2431: index 0000000..da12d66
2432: --- /dev/null
2433: +++ b/cmd/capture_test.go
2434: @@ -0,0 +1,109 @@
2435: +package cmd
2436: +
2437: +import (
2438: +	"bytes"
2439: +	"encoding/json"
2440: +	"slices"
2441: +	"strings"
2442: +	"testing"
2443: +
2444: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2445: +)
2446: +
2447: +func TestParseCaptureTargets(t *testing.T) {
2448: +	t.Parallel()
2449: +
2450: +	targets, err := parseCaptureTargets([]string{
2451: +		"srl1:e1-1,ethernet-1/2", " sros : 1/1/3 ", "r1:eth1",
2452: +	})
2453: +	if err != nil {
2454: +		t.Fatal(err)
2455: +	}
2456: +	want := []clablabruntime.CaptureTarget{
2457: +		{Node: "srl1", Interface: "e1-1"},
2458: +		{Node: "srl1", Interface: "ethernet-1/2"},
2459: +		{Node: "sros", Interface: "1/1/3"},
2460: +		{Node: "r1", Interface: "eth1"},
2461: +	}
2462: +	if !slices.Equal(targets, want) {
2463: +		t.Fatalf("targets = %+v, want %+v", targets, want)
2464: +	}
2465: +
2466: +	for _, bad := range [][]string{nil, {"srl1"}, {":e1-1"}, {"srl1:"}, {"srl1:e1-1,,e1-2"}} {
2467: +		if _, err := parseCaptureTargets(bad); err == nil {
2468: +			t.Errorf("parseCaptureTargets(%q) succeeded", bad)
2469: +		}
2470: +	}
2471: +}
2472: +
2473: +func TestCaptureCommandFlags(t *testing.T) {
2474: +	o := GetOptions()
2475: +	cmd, err := captureCmd(o)
2476: +	if err != nil {
2477: +		t.Fatal(err)
2478: +	}
2479: +	if err := cmd.ParseFlags([]string{
2480: +		"--target", "srl1:e1-1", "--target", "srl2:e1-1,e1-2", "--duration", "90m",
2481: +		"--packet-limit", "100", "--snap-length", "128", "-w", "out.pcapng",
2482: +	}); err != nil {
2483: +		t.Fatal(err)
2484: +	}
2485: +	if !slices.Equal(o.Capture.Targets, []string{"srl1:e1-1", "srl2:e1-1,e1-2"}) ||
2486: +		o.Capture.Duration.Minutes() != 90 || o.Capture.PacketLimit != 100 ||
2487: +		o.Capture.SnapLength != 128 || o.Capture.Write != "out.pcapng" {
2488: +		t.Fatalf("capture options = %+v", o.Capture)
2489: +	}
2490: +	if def := cmd.Flag("write").DefValue; def != "-" {
2491: +		t.Fatalf("--write default = %q, want stdout", def)
2492: +	}
2493: +}
2494: +
2495: +func TestPrintCaptureInterfaces(t *testing.T) {
2496: +	t.Parallel()
2497: +
2498: +	interfaces := []clablabruntime.CaptureInterface{
2499: +		{
2500: +			Node:          "srl1",
2501: +			Interface:     "e1-1",
2502: +			Alias:         "ethernet-1/1",
2503: +			PeerNode:      "srl2",
2504: +			PeerInterface: "ethernet-1/1",
2505: +		},
2506: +		{Node: "srl1", Interface: "e1-2", PeerNode: "host", PeerInterface: "srl1-e1-2"},
2507: +	}
2508: +
2509: +	var out bytes.Buffer
2510: +	if err := printCaptureInterfaces(&out, interfaces, "json"); err != nil {
2511: +		t.Fatal(err)
2512: +	}
2513: +	var decoded []map[string]any
2514: +	if err := json.Unmarshal(out.Bytes(), &decoded); err != nil {
2515: +		t.Fatal(err)
2516: +	}
2517: +	if decoded[0]["peer_node"] != "srl2" || decoded[0]["alias"] != "ethernet-1/1" {
2518: +		t.Fatalf("json = %s", out.String())
2519: +	}
2520: +	if _, hasAlias := decoded[1]["alias"]; hasAlias {
2521: +		t.Fatalf("an empty alias is printed: %s", out.String())
2522: +	}
2523: +
2524: +	out.Reset()
2525: +	if err := printCaptureInterfaces(
2526: +		&out,
2527: +		nil,
2528: +		"json",
2529: +	); err != nil ||
2530: +		strings.TrimSpace(out.String()) != "[]" {
2531: +		t.Fatalf("empty json = %q, %v", out.String(), err)
2532: +	}
2533: +
2534: +	out.Reset()
2535: +	if err := printCaptureInterfaces(&out, interfaces, "table"); err != nil {
2536: +		t.Fatal(err)
2537: +	}
2538: +	for _, want := range []string{"Peer Interface", "ethernet-1/1", "srl1-e1-2", "N/A"} {
2539: +		if !strings.Contains(out.String(), want) {
2540: +			t.Fatalf("table does not contain %q:\n%s", want, out.String())
2541: +		}
2542: +	}
2543: +}
2544: diff --git a/cmd/context.go b/cmd/context.go
2545: index 223cb1d..21d5bea 100644
2546: --- a/cmd/context.go
2547: +++ b/cmd/context.go
2548: @@ -51,10 +51,20 @@ func SignalHandledContext() (context.Context, context.CancelFunc) {
2549:  
2550:  		cancel()
2551:  
2552:  		options := GetOptions()
2553:  
2554: +		if options.Global.FinishOnCancel.Load() {
2555: +			log.Info("Stopping, press Ctrl+C again to abort")
2556: +
2557: +			sig = <-sigs
2558: +
2559: +			log.Errorf("received signal %q while stopping, exiting", sig)
2560: +
2561: +			os.Exit(1)
2562: +		}
2563: +
2564:  		if !options.Global.CleanOnCancel.Load() {
2565:  			log.Debug("clean on cancel is not true, exiting")
2566:  
2567:  			os.Exit(1)
2568:  		}
2569: diff --git a/cmd/inspect.go b/cmd/inspect.go
2570: index 1b6f41d..55fb61f 100644
2571: --- a/cmd/inspect.go
2572: +++ b/cmd/inspect.go
2573: @@ -70,10 +70,14 @@ func inspectCmd(o *Options) (*cobra.Command, error) {
2574:  		Short: "inspect interfaces of one or multiple nodes in a lab",
2575:  		Long: "show interfaces and their attributes in a specific deployed lab\n" +
2576:  			"reference: https://containerlab.dev/cmd/inspect/interfaces/",
2577:  		Aliases: []string{"int", "intf"},
2578:  		PreRunE: func(_ *cobra.Command, _ []string) error {
2579: +			if commandSkipsRoot(o.Global.Runtime) {
2580: +				return nil
2581: +			}
2582: +
2583:  			return clabutils.CheckAndGetRootPrivs()
2584:  		},
2585:  		RunE: func(cobraCmd *cobra.Command, _ []string) error {
2586:  			return inspectInterfacesFn(cobraCmd, o)
2587:  		},
2588: diff --git a/cmd/inspect_interfaces.go b/cmd/inspect_interfaces.go
2589: index 0f64f03..91035c2 100644
2590: --- a/cmd/inspect_interfaces.go
2591: +++ b/cmd/inspect_interfaces.go
2592: @@ -33,10 +33,25 @@ func inspectInterfacesFn(cobraCmd *cobra.Command, o *Options) error {
2593:  	c, err := clabcore.NewContainerLab(o.ToClabOptions()...)
2594:  	if err != nil {
2595:  		return fmt.Errorf("could not parse the topology file: %v", err)
2596:  	}
2597:  
2598: +	if c.LabRuntime != nil {
2599: +		// lab runtimes list the link interfaces packet capture accepts, with their state
2600: +		containerInterfaces, err := c.LabRuntimeInterfaces(cobraCmd.Context(),
2601: +			o.Inspect.InterfacesNode)
2602: +		if err != nil {
2603: +			return fmt.Errorf("failed to list node interfaces: %w", err)
2604: +		}
2605: +		if len(containerInterfaces) == 0 {
2606: +			log.Info("no running nodes found")
2607: +			return nil
2608: +		}
2609: +
2610: +		return printContainerInterfaces(containerInterfaces, o.Inspect.InterfacesFormat)
2611: +	}
2612: +
2613:  	var labNameFilterLabel string
2614:  
2615:  	switch {
2616:  	case o.Global.TopologyName != "":
2617:  		labNameFilterLabel = o.Global.TopologyName
2618: diff --git a/cmd/options.go b/cmd/options.go
2619: index 8717d3b..6037551 100644
2620: --- a/cmd/options.go
2621: +++ b/cmd/options.go
2622: @@ -53,10 +53,14 @@ func GetOptions() *Options {
2623:  				InterfacesFormat: "table",
2624:  			},
2625:  			Logs: &LogsOptions{
2626:  				Tail: -1,
2627:  			},
2628: +			Capture: &CaptureOptions{
2629: +				Write:  "-",
2630: +				Format: "table",
2631: +			},
2632:  			Graph: &GraphOptions{
2633:  				Server:           "0.0.0.0:50080",
2634:  				MermaidDirection: "TD",
2635:  				DrawIOVersion:    "latest",
2636:  			},
2637: @@ -142,10 +146,11 @@ type Options struct {
2638:  	Exec           *ExecOptions
2639:  	Inspect        *InspectOptions
2640:  	Graph          *GraphOptions
2641:  	Events         *EventsOptions
2642:  	Logs           *LogsOptions
2643: +	Capture        *CaptureOptions
2644:  	ToolsAPI       *ToolsApiOptions
2645:  	ToolsCert      *ToolsCertOptions
2646:  	ToolsTxOffload *ToolsDisableTxOffloadOptions
2647:  	ToolsGoTTY     *ToolsGoTTYOptions
2648:  	ToolsNetem     *ToolsNetemOptions
2649: @@ -257,10 +262,15 @@ type GlobalOptions struct {
2650:  	// special flag that should only be set by deploy, informs the context handler to destroy
2651:  	// (or not) when root context is canceled. The signal handler goroutine reads it while
2652:  	// deploy is running, so it is atomic.
2653:  	CleanOnCancel atomic.Bool
2654:  
2655: +	// FinishOnCancel informs the context handler that the running command ends cleanly on its
2656: +	// own once the root context is canceled (capture finishes its output), so the handler
2657: +	// waits for it instead of exiting.
2658: +	FinishOnCancel atomic.Bool
2659: +
2660:  	// special flag that is only set on deploy,
2661:  	// if true, the topology file backup is created at /tmp/.clab/bak
2662:  	BackupTopologyFile bool
2663:  }
2664:  
2665: diff --git a/cmd/root.go b/cmd/root.go
2666: index 0baf203..a9b1c8b 100644
2667: --- a/cmd/root.go
2668: +++ b/cmd/root.go
2669: @@ -35,10 +35,11 @@ func subcommandRegisterFuncs() []func(*Options) (*cobra.Command, error) {
2670:  		generateCmd,
2671:  		graphCmd,
2672:  		eventsCmd,
2673:  		inspectCmd,
2674:  		logsCmd,
2675: +		captureCmd,
2676:  		redeployCmd,
2677:  		saveCmd,
2678:  		toolsCmd,
2679:  		validateCmd,
2680:  	}
2681: @@ -263,15 +264,10 @@ func checkLabRuntimeCommandSupport(cobraCmd *cobra.Command, runtimeName string)
2682:  			"the %q command needs running containers with lab runtime %q unless it renders "+
2683:  				"from the topology file alone; use --offline, --dot, --mermaid or --drawio",
2684:  			"graph", runtimeName)
2685:  	}
2686:  
2687: -	if getCommandPath(cobraCmd) == "inspect.interfaces" {
2688: -		return fmt.Errorf("the %q command is not supported with lab runtime %q",
2689: -			"inspect interfaces", runtimeName)
2690: -	}
2691: -
2692:  	var unsupported []string
2693:  	for _, flagName := range labRuntimeUnsupportedFlags[getCommandPath(cobraCmd)] {
2694:  		if labRuntimeFlagWasSet(cobraCmd, flagName) {
2695:  			unsupported = append(unsupported, "--"+flagName)
2696:  		}
2697: @@ -339,10 +335,11 @@ func getTopoFilePath(cobraCmd *cobra.Command, o *Options) error { // skipcq: GO-
2698:  		cobraCmd.Name() != "inspect" &&
2699:  		cobraCmd.Name() != "save" &&
2700:  		cobraCmd.Name() != "graph" &&
2701:  		cobraCmd.Name() != "validate" &&
2702:  		cobraCmd.Name() != "logs" &&
2703: +		cobraCmd.Name() != "capture" &&
2704:  		cobraCmd.Name() != "interfaces" {
2705:  		return nil
2706:  	}
2707:  
2708:  	// start/stop/restart topology lookup applies only to top-level lifecycle commands.
2709: diff --git a/cmd/root_test.go b/cmd/root_test.go
2710: index 418a947..af02e34 100644
2711: --- a/cmd/root_test.go
2712: +++ b/cmd/root_test.go
2713: @@ -289,20 +289,23 @@ func TestCheckLabRuntimeFlagAndNestedCommandSupport(t *testing.T) {
2714:  				t.Fatalf("checkLabRuntimeCommandSupport() error = %v, wantErr %v", err, tt.wantErr)
2715:  			}
2716:  		})
2717:  	}
2718:  
2719: -	t.Run("inspect interfaces rejected", func(t *testing.T) {
2720: +	t.Run("inspect interfaces and capture accepted", func(t *testing.T) {
2721:  		root := &cobra.Command{Use: "containerlab"}
2722:  		inspect := &cobra.Command{Use: "inspect"}
2723:  		interfaces := &cobra.Command{Use: "interfaces"}
2724: -		root.AddCommand(inspect)
2725: +		capture := &cobra.Command{Use: "capture"}
2726: +		root.AddCommand(inspect, capture)
2727:  		inspect.AddCommand(interfaces)
2728:  
2729: -		if err := checkLabRuntimeCommandSupport(
2730: -			interfaces,
2731: -			clablabruntime.ClabernetesRuntimeName,
2732: -		); err == nil {
2733: -			t.Fatal("inspect interfaces was accepted for clabernetes")
2734: +		for _, cmd := range []*cobra.Command{interfaces, capture} {
2735: +			if err := checkLabRuntimeCommandSupport(
2736: +				cmd,
2737: +				clablabruntime.ClabernetesRuntimeName,
2738: +			); err != nil {
2739: +				t.Fatalf("%s rejected for clabernetes: %v", cmd.Name(), err)
2740: +			}
2741:  		}
2742:  	})
2743:  }
2744: diff --git a/core/capture.go b/core/capture.go
2745: new file mode 100644
2746: index 0000000..2e12fc2
2747: --- /dev/null
2748: +++ b/core/capture.go
2749: @@ -0,0 +1,93 @@
2750: +package core
2751: +
2752: +import (
2753: +	"context"
2754: +	"io"
2755: +
2756: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2757: +	clabtypes "github.com/srl-labs/containerlab/types"
2758: +)
2759: +
2760: +// CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for

(Showing lines 2161-2760 of 7018. Use offset=2761 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196525308001c9yqn2Z4fxat8x",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196524566001amBVNvfJ9FiMxm",
  "callID": "call_c6784917344445ef98642b50",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 600,
      "offset": 2161
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n2161: diff --git a/cmd/capture.go b/cmd/capture.go\n2162: new file mode 100644\n2163: index 0000000..20117bc\n2164: --- /dev/null\n2165: +++ b/cmd/capture.go\n2166: @@ -0,0 +1,262 @@\n2167: +package cmd\n2168: +\n2169: +import (\n2170: +\t\"encoding/json\"\n2171: +\t\"fmt\"\n2172: +\t\"io\"\n2173: +\t\"os\"\n2174: +\t\"strings\"\n2175: +\t\"time\"\n2176: +\n2177: +\t\"github.com/charmbracelet/log\"\n2178: +\ttableWriter \"github.com/jedib0t/go-pretty/v6/table\"\n2179: +\t\"github.com/jedib0t/go-pretty/v6/text\"\n2180: +\t\"github.com/spf13/cobra\"\n2181: +\tclabconstants \"github.com/srl-labs/containerlab/constants\"\n2182: +\tclabcore \"github.com/srl-labs/containerlab/core\"\n2183: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2184: +\tclabutils \"github.com/srl-labs/containerlab/utils\"\n2185: +)\n2186: +\n2187: +// CaptureOptions are the flags of the capture command.\n2188: +type CaptureOptions struct {\n2189: +\tTargets     []string\n2190: +\tDuration    time.Duration\n2191: +\tPacketLimit int\n2192: +\tSnapLength  int\n2193: +\tWrite       string\n2194: +\tList        bool\n2195: +\tFormat      string\n2196: +}\n2197: +\n2198: +func captureCmd(o *Options) (*cobra.Command, error) {\n2199: +\tc := &cobra.Command{\n2200: +\t\tUse:   \"capture\",\n2201: +\t\tShort: \"capture packets on lab link interfaces\",\n2202: +\t\tLong: \"capture packets on lab link interfaces of one or more nodes into one pcapng \" +\n2203: +\t\t\t\"stream\\nreference: https://containerlab.dev/cmd/capture/\",\n2204: +\t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n2205: +\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n2206: +\t\t\t\treturn nil\n2207: +\t\t\t}\n2208: +\n2209: +\t\t\t// Docker and Podman captures open packet sockets in the nodes' namespaces\n2210: +\t\t\treturn clabutils.CheckAndGetRootPrivs()\n2211: +\t\t},\n2212: +\t\tSilenceUsage: true,\n2213: +\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n2214: +\t\t\treturn captureFn(cmd, o)\n2215: +\t\t},\n2216: +\t}\n2217: +\n2218: +\tc.Flags().StringArrayVar(\n2219: +\t\t&o.Capture.Targets,\n2220: +\t\t\"target\",\n2221: +\t\to.Capture.Targets,\n2222: +\t\t\"node and interfaces to capture, as <node>:<interface>[,<interface>...]; repeatable\",\n2223: +\t)\n2224: +\tc.Flags().DurationVar(\n2225: +\t\t&o.Capture.Duration,\n2226: +\t\t\"duration\",\n2227: +\t\to.Capture.Duration,\n2228: +\t\t\"stop after this duration; 0 captures until interrupted\",\n2229: +\t)\n2230: +\tc.Flags().IntVar(\n2231: +\t\t&o.Capture.PacketLimit,\n2232: +\t\t\"packet-limit\",\n2233: +\t\to.Capture.PacketLimit,\n2234: +\t\t\"stop after this many packets across all targets; 0 means no limit\",\n2235: +\t)\n2236: +\tc.Flags().IntVar(\n2237: +\t\t&o.Capture.SnapLength,\n2238: +\t\t\"snap-length\",\n2239: +\t\to.Capture.SnapLength,\n2240: +\t\t\"bytes kept of each packet (64 to 1048576); 0 uses the runtime default\",\n2241: +\t)\n2242: +\tc.Flags().StringVarP(\n2243: +\t\t&o.Capture.Write,\n2244: +\t\t\"write\",\n2245: +\t\t\"w\",\n2246: +\t\to.Capture.Write,\n2247: +\t\t\"pcapng output file; - writes to stdout\",\n2248: +\t)\n2249: +\tc.Flags().BoolVar(\n2250: +\t\t&o.Capture.List,\n2251: +\t\t\"list\",\n2252: +\t\to.Capture.List,\n2253: +\t\t\"list the capturable interfaces instead of capturing\",\n2254: +\t)\n2255: +\tc.Flags().StringVarP(\n2256: +\t\t&o.Capture.Format,\n2257: +\t\t\"format\",\n2258: +\t\t\"f\",\n2259: +\t\to.Capture.Format,\n2260: +\t\t\"output format of --list: table or json\",\n2261: +\t)\n2262: +\n2263: +\tc.Example = `# Capture e1-1 of srl1 and e1-1 of srl2 for 30 seconds into one file\n2264: +containerlab capture -t srl.clab.yml --target srl1:e1-1 --target srl2:e1-1 \\\n2265: +  --duration 30s -w srl.pcapng\n2266: +\n2267: +# Capture two interfaces of one node and watch them live in Wireshark\n2268: +containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n2269: +\n2270: +# List the interfaces capture accepts\n2271: +containerlab capture --name srl --list -f json\n2272: +\n2273: +# Capture a lab running on the c9s runtime\n2274: +containerlab -r c9s capture --name srl --target srl1:e1-1 -w srl.pcapng`\n2275: +\n2276: +\treturn c, nil\n2277: +}\n2278: +\n2279: +func captureFn(cmd *cobra.Command, o *Options) error {\n2280: +\tif o.Global.TopologyName == \"\" && o.Global.TopologyFile == \"\" {\n2281: +\t\treturn fmt.Errorf(\"provide either a lab name (--name) or a topology file path (--topo)\")\n2282: +\t}\n2283: +\n2284: +\tif o.Capture.List {\n2285: +\t\treturn captureListFn(cmd, o)\n2286: +\t}\n2287: +\n2288: +\ttargets, err := parseCaptureTargets(o.Capture.Targets)\n2289: +\tif err != nil {\n2290: +\t\treturn err\n2291: +\t}\n2292: +\n2293: +\tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n2294: +\tif err != nil {\n2295: +\t\treturn err\n2296: +\t}\n2297: +\n2298: +\t// An interrupt ends the capture; the command still finishes the file and exits cleanly.\n2299: +\t// Armed before the file is created, so an interrupt never leaves it empty.\n2300: +\to.Global.FinishOnCancel.Store(true)\n2301: +\tdefer o.Global.FinishOnCancel.Store(false)\n2302: +\n2303: +\toutput := cmd.OutOrStdout()\n2304: +\tif o.Capture.Write != \"\" && o.Capture.Write != \"-\" {\n2305: +\t\tfile, err := os.Create(o.Capture.Write)\n2306: +\t\tif err != nil {\n2307: +\t\t\treturn fmt.Errorf(\"failed to create the capture file: %w\", err)\n2308: +\t\t}\n2309: +\t\tdefer file.Close()\n2310: +\t\toutput = file\n2311: +\n2312: +\t\t// the file belongs to the user who ran the command, also through sudo or setuid\n2313: +\t\tif err := clabutils.SetUIDAndGID(o.Capture.Write); err != nil {\n2314: +\t\t\tlog.Debug(\"Cannot hand the capture file to the user\", \"file\", o.Capture.Write,\n2315: +\t\t\t\t\"error\", err)\n2316: +\t\t}\n2317: +\t}\n2318: +\n2319: +\terr = c.Capture(cmd.Context(), clablabruntime.CaptureRequest{\n2320: +\t\tTargets:     targets,\n2321: +\t\tDuration:    o.Capture.Duration,\n2322: +\t\tPacketLimit: o.Capture.PacketLimit,\n2323: +\t\tSnapLength:  o.Capture.SnapLength,\n2324: +\t}, output)\n2325: +\tif err != nil {\n2326: +\t\treturn err\n2327: +\t}\n2328: +\n2329: +\tif file, ok := output.(*os.File); ok && output != cmd.OutOrStdout() {\n2330: +\t\tif err := file.Sync(); err != nil {\n2331: +\t\t\treturn fmt.Errorf(\"failed to write the capture file: %w\", err)\n2332: +\t\t}\n2333: +\t}\n2334: +\n2335: +\treturn nil\n2336: +}\n2337: +\n2338: +// parseCaptureTargets parses --target values: <node>:<interface>[,<interface>...]. The node name\n2339: +// ends at the first colon, so interface names may contain colons or slashes.\n2340: +func parseCaptureTargets(values []string) ([]clablabruntime.CaptureTarget, error) {\n2341: +\tif len(values) == 0 {\n2342: +\t\treturn nil, fmt.Errorf(\"provide at least one --target <node>:<interface>[,<interface>...]\")\n2343: +\t}\n2344: +\n2345: +\ttargets := make([]clablabruntime.CaptureTarget, 0, len(values))\n2346: +\tfor _, value := range values {\n2347: +\t\tnode, interfaces, ok := strings.Cut(strings.TrimSpace(value), \":\")\n2348: +\t\tnode = strings.TrimSpace(node)\n2349: +\t\tif !ok || node == \"\" || strings.TrimSpace(interfaces) == \"\" {\n2350: +\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: use <node>:<interface>[,<interface>...]\",\n2351: +\t\t\t\tvalue)\n2352: +\t\t}\n2353: +\n2354: +\t\tfor _, name := range strings.Split(interfaces, \",\") {\n2355: +\t\t\tname = strings.TrimSpace(name)\n2356: +\t\t\tif name == \"\" {\n2357: +\t\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: empty interface name\", value)\n2358: +\t\t\t}\n2359: +\t\t\ttargets = append(targets, clablabruntime.CaptureTarget{Node: node, Interface: name})\n2360: +\t\t}\n2361: +\t}\n2362: +\n2363: +\treturn targets, nil\n2364: +}\n2365: +\n2366: +func captureListFn(cmd *cobra.Command, o *Options) error {\n2367: +\tformat := o.Capture.Format\n2368: +\tif format == \"\" {\n2369: +\t\tformat = clabconstants.FormatTable\n2370: +\t}\n2371: +\tif format != clabconstants.FormatTable && format != clabconstants.FormatJSON {\n2372: +\t\treturn fmt.Errorf(\"output format %q is not supported, use 'table' or 'json'\", format)\n2373: +\t}\n2374: +\tif len(o.Capture.Targets) != 0 {\n2375: +\t\treturn fmt.Errorf(\"--list lists every running node's interfaces; it takes no --target\")\n2376: +\t}\n2377: +\n2378: +\tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n2379: +\tif err != nil {\n2380: +\t\treturn err\n2381: +\t}\n2382: +\n2383: +\tinterfaces, err := c.CaptureInterfaces(cmd.Context())\n2384: +\tif err != nil {\n2385: +\t\treturn err\n2386: +\t}\n2387: +\n2388: +\treturn printCaptureInterfaces(cmd.OutOrStdout(), interfaces, format)\n2389: +}\n2390: +\n2391: +func printCaptureInterfaces(\n2392: +\tw io.Writer,\n2393: +\tinterfaces []clablabruntime.CaptureInterface,\n2394: +\tformat string,\n2395: +) error {\n2396: +\tif format == clabconstants.FormatJSON {\n2397: +\t\tif interfaces == nil {\n2398: +\t\t\tinterfaces = []clablabruntime.CaptureInterface{}\n2399: +\t\t}\n2400: +\t\tdata, err := json.MarshalIndent(interfaces, \"\", \"  \")\n2401: +\t\tif err != nil {\n2402: +\t\t\treturn err\n2403: +\t\t}\n2404: +\t\t_, err = fmt.Fprintln(w, string(data))\n2405: +\n2406: +\t\treturn err\n2407: +\t}\n2408: +\n2409: +\ttable := tableWriter.NewWriter()\n2410: +\ttable.SetOutputMirror(w)\n2411: +\ttable.SetStyle(tableWriter.StyleRounded)\n2412: +\ttable.Style().Format.Header = text.FormatTitle\n2413: +\ttable.Style().Format.HeaderAlign = text.AlignCenter\n2414: +\ttable.AppendHeader(tableWriter.Row{\"Node\", \"Interface\", \"Alias\", \"Peer Node\", \"Peer Interface\"})\n2415: +\ttable.SetColumnConfigs([]tableWriter.ColumnConfig{{Number: 1, AutoMerge: true}})\n2416: +\tfor _, intf := range interfaces {\n2417: +\t\talias := intf.Alias\n2418: +\t\tif alias == \"\" {\n2419: +\t\t\talias = clabconstants.NotApplicable\n2420: +\t\t}\n2421: +\t\ttable.AppendRow(tableWriter.Row{\n2422: +\t\t\tintf.Node, intf.Interface, alias, intf.PeerNode, intf.PeerInterface,\n2423: +\t\t})\n2424: +\t}\n2425: +\ttable.Render()\n2426: +\n2427: +\treturn nil\n2428: +}\n2429: diff --git a/cmd/capture_test.go b/cmd/capture_test.go\n2430: new file mode 100644\n2431: index 0000000..da12d66\n2432: --- /dev/null\n2433: +++ b/cmd/capture_test.go\n2434: @@ -0,0 +1,109 @@\n2435: +package cmd\n2436: +\n2437: +import (\n2438: +\t\"bytes\"\n2439: +\t\"encoding/json\"\n2440: +\t\"slices\"\n2441: +\t\"strings\"\n2442: +\t\"testing\"\n2443: +\n2444: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2445: +)\n2446: +\n2447: +func TestParseCaptureTargets(t *testing.T) {\n2448: +\tt.Parallel()\n2449: +\n2450: +\ttargets, err := parseCaptureTargets([]string{\n2451: +\t\t\"srl1:e1-1,ethernet-1/2\", \" sros : 1/1/3 \", \"r1:eth1\",\n2452: +\t})\n2453: +\tif err != nil {\n2454: +\t\tt.Fatal(err)\n2455: +\t}\n2456: +\twant := []clablabruntime.CaptureTarget{\n2457: +\t\t{Node: \"srl1\", Interface: \"e1-1\"},\n2458: +\t\t{Node: \"srl1\", Interface: \"ethernet-1/2\"},\n2459: +\t\t{Node: \"sros\", Interface: \"1/1/3\"},\n2460: +\t\t{Node: \"r1\", Interface: \"eth1\"},\n2461: +\t}\n2462: +\tif !slices.Equal(targets, want) {\n2463: +\t\tt.Fatalf(\"targets = %+v, want %+v\", targets, want)\n2464: +\t}\n2465: +\n2466: +\tfor _, bad := range [][]string{nil, {\"srl1\"}, {\":e1-1\"}, {\"srl1:\"}, {\"srl1:e1-1,,e1-2\"}} {\n2467: +\t\tif _, err := parseCaptureTargets(bad); err == nil {\n2468: +\t\t\tt.Errorf(\"parseCaptureTargets(%q) succeeded\", bad)\n2469: +\t\t}\n2470: +\t}\n2471: +}\n2472: +\n2473: +func TestCaptureCommandFlags(t *testing.T) {\n2474: +\to := GetOptions()\n2475: +\tcmd, err := captureCmd(o)\n2476: +\tif err != nil {\n2477: +\t\tt.Fatal(err)\n2478: +\t}\n2479: +\tif err := cmd.ParseFlags([]string{\n2480: +\t\t\"--target\", \"srl1:e1-1\", \"--target\", \"srl2:e1-1,e1-2\", \"--duration\", \"90m\",\n2481: +\t\t\"--packet-limit\", \"100\", \"--snap-length\", \"128\", \"-w\", \"out.pcapng\",\n2482: +\t}); err != nil {\n2483: +\t\tt.Fatal(err)\n2484: +\t}\n2485: +\tif !slices.Equal(o.Capture.Targets, []string{\"srl1:e1-1\", \"srl2:e1-1,e1-2\"}) ||\n2486: +\t\to.Capture.Duration.Minutes() != 90 || o.Capture.PacketLimit != 100 ||\n2487: +\t\to.Capture.SnapLength != 128 || o.Capture.Write != \"out.pcapng\" {\n2488: +\t\tt.Fatalf(\"capture options = %+v\", o.Capture)\n2489: +\t}\n2490: +\tif def := cmd.Flag(\"write\").DefValue; def != \"-\" {\n2491: +\t\tt.Fatalf(\"--write default = %q, want stdout\", def)\n2492: +\t}\n2493: +}\n2494: +\n2495: +func TestPrintCaptureInterfaces(t *testing.T) {\n2496: +\tt.Parallel()\n2497: +\n2498: +\tinterfaces := []clablabruntime.CaptureInterface{\n2499: +\t\t{\n2500: +\t\t\tNode:          \"srl1\",\n2501: +\t\t\tInterface:     \"e1-1\",\n2502: +\t\t\tAlias:         \"ethernet-1/1\",\n2503: +\t\t\tPeerNode:      \"srl2\",\n2504: +\t\t\tPeerInterface: \"ethernet-1/1\",\n2505: +\t\t},\n2506: +\t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"srl1-e1-2\"},\n2507: +\t}\n2508: +\n2509: +\tvar out bytes.Buffer\n2510: +\tif err := printCaptureInterfaces(&out, interfaces, \"json\"); err != nil {\n2511: +\t\tt.Fatal(err)\n2512: +\t}\n2513: +\tvar decoded []map[string]any\n2514: +\tif err := json.Unmarshal(out.Bytes(), &decoded); err != nil {\n2515: +\t\tt.Fatal(err)\n2516: +\t}\n2517: +\tif decoded[0][\"peer_node\"] != \"srl2\" || decoded[0][\"alias\"] != \"ethernet-1/1\" {\n2518: +\t\tt.Fatalf(\"json = %s\", out.String())\n2519: +\t}\n2520: +\tif _, hasAlias := decoded[1][\"alias\"]; hasAlias {\n2521: +\t\tt.Fatalf(\"an empty alias is printed: %s\", out.String())\n2522: +\t}\n2523: +\n2524: +\tout.Reset()\n2525: +\tif err := printCaptureInterfaces(\n2526: +\t\t&out,\n2527: +\t\tnil,\n2528: +\t\t\"json\",\n2529: +\t); err != nil ||\n2530: +\t\tstrings.TrimSpace(out.String()) != \"[]\" {\n2531: +\t\tt.Fatalf(\"empty json = %q, %v\", out.String(), err)\n2532: +\t}\n2533: +\n2534: +\tout.Reset()\n2535: +\tif err := printCaptureInterfaces(&out, interfaces, \"table\"); err != nil {\n2536: +\t\tt.Fatal(err)\n2537: +\t}\n2538: +\tfor _, want := range []string{\"Peer Interface\", \"ethernet-1/1\", \"srl1-e1-2\", \"N/A\"} {\n2539: +\t\tif !strings.Contains(out.String(), want) {\n2540: +\t\t\tt.Fatalf(\"table does not contain %q:\\n%s\", want, out.String())\n2541: +\t\t}\n2542: +\t}\n2543: +}\n2544: diff --git a/cmd/context.go b/cmd/context.go\n2545: index 223cb1d..21d5bea 100644\n2546: --- a/cmd/context.go\n2547: +++ b/cmd/context.go\n2548: @@ -51,10 +51,20 @@ func SignalHandledContext() (context.Context, context.CancelFunc) {\n2549:  \n2550:  \t\tcancel()\n2551:  \n2552:  \t\toptions := GetOptions()\n2553:  \n2554: +\t\tif options.Global.FinishOnCancel.Load() {\n2555: +\t\t\tlog.Info(\"Stopping, press Ctrl+C again to abort\")\n2556: +\n2557: +\t\t\tsig = <-sigs\n2558: +\n2559: +\t\t\tlog.Errorf(\"received signal %q while stopping, exiting\", sig)\n2560: +\n2561: +\t\t\tos.Exit(1)\n2562: +\t\t}\n2563: +\n2564:  \t\tif !options.Global.CleanOnCancel.Load() {\n2565:  \t\t\tlog.Debug(\"clean on cancel is not true, exiting\")\n2566:  \n2567:  \t\t\tos.Exit(1)\n2568:  \t\t}\n2569: diff --git a/cmd/inspect.go b/cmd/inspect.go\n2570: index 1b6f41d..55fb61f 100644\n2571: --- a/cmd/inspect.go\n2572: +++ b/cmd/inspect.go\n2573: @@ -70,10 +70,14 @@ func inspectCmd(o *Options) (*cobra.Command, error) {\n2574:  \t\tShort: \"inspect interfaces of one or multiple nodes in a lab\",\n2575:  \t\tLong: \"show interfaces and their attributes in a specific deployed lab\\n\" +\n2576:  \t\t\t\"reference: https://containerlab.dev/cmd/inspect/interfaces/\",\n2577:  \t\tAliases: []string{\"int\", \"intf\"},\n2578:  \t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n2579: +\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n2580: +\t\t\t\treturn nil\n2581: +\t\t\t}\n2582: +\n2583:  \t\t\treturn clabutils.CheckAndGetRootPrivs()\n2584:  \t\t},\n2585:  \t\tRunE: func(cobraCmd *cobra.Command, _ []string) error {\n2586:  \t\t\treturn inspectInterfacesFn(cobraCmd, o)\n2587:  \t\t},\n2588: diff --git a/cmd/inspect_interfaces.go b/cmd/inspect_interfaces.go\n2589: index 0f64f03..91035c2 100644\n2590: --- a/cmd/inspect_interfaces.go\n2591: +++ b/cmd/inspect_interfaces.go\n2592: @@ -33,10 +33,25 @@ func inspectInterfacesFn(cobraCmd *cobra.Command, o *Options) error {\n2593:  \tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n2594:  \tif err != nil {\n2595:  \t\treturn fmt.Errorf(\"could not parse the topology file: %v\", err)\n2596:  \t}\n2597:  \n2598: +\tif c.LabRuntime != nil {\n2599: +\t\t// lab runtimes list the link interfaces packet capture accepts, with their state\n2600: +\t\tcontainerInterfaces, err := c.LabRuntimeInterfaces(cobraCmd.Context(),\n2601: +\t\t\to.Inspect.InterfacesNode)\n2602: +\t\tif err != nil {\n2603: +\t\t\treturn fmt.Errorf(\"failed to list node interfaces: %w\", err)\n2604: +\t\t}\n2605: +\t\tif len(containerInterfaces) == 0 {\n2606: +\t\t\tlog.Info(\"no running nodes found\")\n2607: +\t\t\treturn nil\n2608: +\t\t}\n2609: +\n2610: +\t\treturn printContainerInterfaces(containerInterfaces, o.Inspect.InterfacesFormat)\n2611: +\t}\n2612: +\n2613:  \tvar labNameFilterLabel string\n2614:  \n2615:  \tswitch {\n2616:  \tcase o.Global.TopologyName != \"\":\n2617:  \t\tlabNameFilterLabel = o.Global.TopologyName\n2618: diff --git a/cmd/options.go b/cmd/options.go\n2619: index 8717d3b..6037551 100644\n2620: --- a/cmd/options.go\n2621: +++ b/cmd/options.go\n2622: @@ -53,10 +53,14 @@ func GetOptions() *Options {\n2623:  \t\t\t\tInterfacesFormat: \"table\",\n2624:  \t\t\t},\n2625:  \t\t\tLogs: &LogsOptions{\n2626:  \t\t\t\tTail: -1,\n2627:  \t\t\t},\n2628: +\t\t\tCapture: &CaptureOptions{\n2629: +\t\t\t\tWrite:  \"-\",\n2630: +\t\t\t\tFormat: \"table\",\n2631: +\t\t\t},\n2632:  \t\t\tGraph: &GraphOptions{\n2633:  \t\t\t\tServer:           \"0.0.0.0:50080\",\n2634:  \t\t\t\tMermaidDirection: \"TD\",\n2635:  \t\t\t\tDrawIOVersion:    \"latest\",\n2636:  \t\t\t},\n2637: @@ -142,10 +146,11 @@ type Options struct {\n2638:  \tExec           *ExecOptions\n2639:  \tInspect        *InspectOptions\n2640:  \tGraph          *GraphOptions\n2641:  \tEvents         *EventsOptions\n2642:  \tLogs           *LogsOptions\n2643: +\tCapture        *CaptureOptions\n2644:  \tToolsAPI       *ToolsApiOptions\n2645:  \tToolsCert      *ToolsCertOptions\n2646:  \tToolsTxOffload *ToolsDisableTxOffloadOptions\n2647:  \tToolsGoTTY     *ToolsGoTTYOptions\n2648:  \tToolsNetem     *ToolsNetemOptions\n2649: @@ -257,10 +262,15 @@ type GlobalOptions struct {\n2650:  \t// special flag that should only be set by deploy, informs the context handler to destroy\n2651:  \t// (or not) when root context is canceled. The signal handler goroutine reads it while\n2652:  \t// deploy is running, so it is atomic.\n2653:  \tCleanOnCancel atomic.Bool\n2654:  \n2655: +\t// FinishOnCancel informs the context handler that the running command ends cleanly on its\n2656: +\t// own once the root context is canceled (capture finishes its output), so the handler\n2657: +\t// waits for it instead of exiting.\n2658: +\tFinishOnCancel atomic.Bool\n2659: +\n2660:  \t// special flag that is only set on deploy,\n2661:  \t// if true, the topology file backup is created at /tmp/.clab/bak\n2662:  \tBackupTopologyFile bool\n2663:  }\n2664:  \n2665: diff --git a/cmd/root.go b/cmd/root.go\n2666: index 0baf203..a9b1c8b 100644\n2667: --- a/cmd/root.go\n2668: +++ b/cmd/root.go\n2669: @@ -35,10 +35,11 @@ func subcommandRegisterFuncs() []func(*Options) (*cobra.Command, error) {\n2670:  \t\tgenerateCmd,\n2671:  \t\tgraphCmd,\n2672:  \t\teventsCmd,\n2673:  \t\tinspectCmd,\n2674:  \t\tlogsCmd,\n2675: +\t\tcaptureCmd,\n2676:  \t\tredeployCmd,\n2677:  \t\tsaveCmd,\n2678:  \t\ttoolsCmd,\n2679:  \t\tvalidateCmd,\n2680:  \t}\n2681: @@ -263,15 +264,10 @@ func checkLabRuntimeCommandSupport(cobraCmd *cobra.Command, runtimeName string)\n2682:  \t\t\t\"the %q command needs running containers with lab runtime %q unless it renders \"+\n2683:  \t\t\t\t\"from the topology file alone; use --offline, --dot, --mermaid or --drawio\",\n2684:  \t\t\t\"graph\", runtimeName)\n2685:  \t}\n2686:  \n2687: -\tif getCommandPath(cobraCmd) == \"inspect.interfaces\" {\n2688: -\t\treturn fmt.Errorf(\"the %q command is not supported with lab runtime %q\",\n2689: -\t\t\t\"inspect interfaces\", runtimeName)\n2690: -\t}\n2691: -\n2692:  \tvar unsupported []string\n2693:  \tfor _, flagName := range labRuntimeUnsupportedFlags[getCommandPath(cobraCmd)] {\n2694:  \t\tif labRuntimeFlagWasSet(cobraCmd, flagName) {\n2695:  \t\t\tunsupported = append(unsupported, \"--\"+flagName)\n2696:  \t\t}\n2697: @@ -339,10 +335,11 @@ func getTopoFilePath(cobraCmd *cobra.Command, o *Options) error { // skipcq: GO-\n2698:  \t\tcobraCmd.Name() != \"inspect\" &&\n2699:  \t\tcobraCmd.Name() != \"save\" &&\n2700:  \t\tcobraCmd.Name() != \"graph\" &&\n2701:  \t\tcobraCmd.Name() != \"validate\" &&\n2702:  \t\tcobraCmd.Name() != \"logs\" &&\n2703: +\t\tcobraCmd.Name() != \"capture\" &&\n2704:  \t\tcobraCmd.Name() != \"interfaces\" {\n2705:  \t\treturn nil\n2706:  \t}\n2707:  \n2708:  \t// start/stop/restart topology lookup applies only to top-level lifecycle commands.\n2709: diff --git a/cmd/root_test.go b/cmd/root_test.go\n2710: index 418a947..af02e34 100644\n2711: --- a/cmd/root_test.go\n2712: +++ b/cmd/root_test.go\n2713: @@ -289,20 +289,23 @@ func TestCheckLabRuntimeFlagAndNestedCommandSupport(t *testing.T) {\n2714:  \t\t\t\tt.Fatalf(\"checkLabRuntimeCommandSupport() error = %v, wantErr %v\", err, tt.wantErr)\n2715:  \t\t\t}\n2716:  \t\t})\n2717:  \t}\n2718:  \n2719: -\tt.Run(\"inspect interfaces rejected\", func(t *testing.T) {\n2720: +\tt.Run(\"inspect interfaces and capture accepted\", func(t *testing.T) {\n2721:  \t\troot := &cobra.Command{Use: \"containerlab\"}\n2722:  \t\tinspect := &cobra.Command{Use: \"inspect\"}\n2723:  \t\tinterfaces := &cobra.Command{Use: \"interfaces\"}\n2724: -\t\troot.AddCommand(inspect)\n2725: +\t\tcapture := &cobra.Command{Use: \"capture\"}\n2726: +\t\troot.AddCommand(inspect, capture)\n2727:  \t\tinspect.AddCommand(interfaces)\n2728:  \n2729: -\t\tif err := checkLabRuntimeCommandSupport(\n2730: -\t\t\tinterfaces,\n2731: -\t\t\tclablabruntime.ClabernetesRuntimeName,\n2732: -\t\t); err == nil {\n2733: -\t\t\tt.Fatal(\"inspect interfaces was accepted for clabernetes\")\n2734: +\t\tfor _, cmd := range []*cobra.Command{interfaces, capture} {\n2735: +\t\t\tif err := checkLabRuntimeCommandSupport(\n2736: +\t\t\t\tcmd,\n2737: +\t\t\t\tclablabruntime.ClabernetesRuntimeName,\n2738: +\t\t\t); err != nil {\n2739: +\t\t\t\tt.Fatalf(\"%s rejected for clabernetes: %v\", cmd.Name(), err)\n2740: +\t\t\t}\n2741:  \t\t}\n2742:  \t})\n2743:  }\n2744: diff --git a/core/capture.go b/core/capture.go\n2745: new file mode 100644\n2746: index 0000000..2e12fc2\n2747: --- /dev/null\n2748: +++ b/core/capture.go\n2749: @@ -0,0 +1,93 @@\n2750: +package core\n2751: +\n2752: +import (\n2753: +\t\"context\"\n2754: +\t\"io\"\n2755: +\n2756: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2757: +\tclabtypes \"github.com/srl-labs/containerlab/types\"\n2758: +)\n2759: +\n2760: +// CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for\n\n(Showing lines 2161-2760 of 7018. Use offset=2761 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "diff --git a/cmd/capture.go b/cmd/capture.go\nnew file mode 100644\nindex 0000000..20117bc\n--- /dev/null\n+++ b/cmd/capture.go\n@@ -0,0 +1,262 @@\n+package cmd\n+\n+import (\n+\t\"encoding/json\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"os\"\n+\t\"strings\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\ttableWriter \"github.com/jedib0t/go-pretty/v6/table\"\n+\t\"github.com/jedib0t/go-pretty/v6/text\"\n+\t\"github.com/spf13/cobra\"",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "diff --git a/cmd/capture.go b/cmd/capture.go\nnew file mode 100644\nindex 0000000..20117bc\n--- /dev/null\n+++ b/cmd/capture.go\n@@ -0,0 +1,262 @@\n+package cmd\n+\n+import (\n+\t\"encoding/json\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"os\"\n+\t\"strings\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\ttableWriter \"github.com/jedib0t/go-pretty/v6/table\"\n+\t\"github.com/jedib0t/go-pretty/v6/text\"\n+\t\"github.com/spf13/cobra\"\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+\tclabutils \"github.com/srl-labs/containerlab/utils\"\n+)\n+\n+// CaptureOptions are the flags of the capture command.\n+type CaptureOptions struct {\n+\tTargets     []string\n+\tDuration    time.Duration\n+\tPacketLimit int\n+\tSnapLength  int\n+\tWrite       string\n+\tList        bool\n+\tFormat      string\n+}\n+\n+func captureCmd(o *Options) (*cobra.Command, error) {\n+\tc := &cobra.Command{\n+\t\tUse:   \"capture\",\n+\t\tShort: \"capture packets on lab link interfaces\",\n+\t\tLong: \"capture packets on lab link interfaces of one or more nodes into one pcapng \" +\n+\t\t\t\"stream\\nreference: https://containerlab.dev/cmd/capture/\",\n+\t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n+\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n+\t\t\t\treturn nil\n+\t\t\t}\n+\n+\t\t\t// Docker and Podman captures open packet sockets in the nodes' namespaces\n+\t\t\treturn clabutils.CheckAndGetRootPrivs()\n+\t\t},\n+\t\tSilenceUsage: true,\n+\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n+\t\t\treturn captureFn(cmd, o)\n+\t\t},\n+\t}\n+\n+\tc.Flags().StringArrayVar(\n+\t\t&o.Capture.Targets,\n+\t\t\"target\",\n+\t\to.Capture.Targets,\n+\t\t\"node and interfaces to capture, as <node>:<interface>[,<interface>...]; repeatable\",\n+\t)\n+\tc.Flags().DurationVar(\n+\t\t&o.Capture.Duration,\n+\t\t\"duration\",\n+\t\to.Capture.Duration,\n+\t\t\"stop after this duration; 0 captures until interrupted\",\n+\t)\n+\tc.Flags().IntVar(\n+\t\t&o.Capture.PacketLimit,\n+\t\t\"packet-limit\",\n+\t\to.Capture.PacketLimit,\n+\t\t\"stop after this many packets across all targets; 0 means no limit\",\n+\t)\n+\tc.Flags().IntVar(\n+\t\t&o.Capture.SnapLength,\n+\t\t\"snap-length\",\n+\t\to.Capture.SnapLength,\n+\t\t\"bytes kept of each packet (64 to 1048576); 0 uses the runtime default\",\n+\t)\n+\tc.Flags().StringVarP(\n+\t\t&o.Capture.Write,\n+\t\t\"write\",\n+\t\t\"w\",\n+\t\to.Capture.Write,\n+\t\t\"pcapng output file; - writes to stdout\",\n+\t)\n+\tc.Flags().BoolVar(\n+\t\t&o.Capture.List,\n+\t\t\"list\",\n+\t\to.Capture.List,\n+\t\t\"list the capturable interfaces instead of capturing\",\n+\t)\n+\tc.Flags().StringVarP(\n+\t\t&o.Capture.Format,\n+\t\t\"format\",\n+\t\t\"f\",\n+\t\to.Capture.Format,\n+\t\t\"output format of --list: table or json\",\n+\t)\n+\n+\tc.Example = `# Capture e1-1 of srl1 and e1-1 of srl2 for 30 seconds into one file\n+containerlab capture -t srl.clab.yml --target srl1:e1-1 --target srl2:e1-1 \\\n+  --duration 30s -w srl.pcapng\n+\n+# Capture two interfaces of one node and watch them live in Wireshark\n+containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n+\n+# List the interfaces capture accepts\n+containerlab capture --name srl --list -f json\n+\n+# Capture a lab running on the c9s runtime\n+containerlab -r c9s capture --name srl --target srl1:e1-1 -w srl.pcapng`\n+\n+\treturn c, nil\n+}\n+\n+func captureFn(cmd *cobra.Command, o *Options) error {\n+\tif o.Global.TopologyName == \"\" && o.Global.TopologyFile == \"\" {\n+\t\treturn fmt.Errorf(\"provide either a lab name (--name) or a topology file path (--topo)\")\n+\t}\n+\n+\tif o.Capture.List {\n+\t\treturn captureListFn(cmd, o)\n+\t}\n+\n+\ttargets, err := parseCaptureTargets(o.Capture.Targets)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\t// An interrupt ends the capture; the command still finishes the file and exits cleanly.\n+\t// Armed before the file is created, so an interrupt never leaves it empty.\n+\to.Global.FinishOnCancel.Store(true)\n+\tdefer o.Global.FinishOnCancel.Store(false)\n+\n+\toutput := cmd.OutOrStdout()\n+\tif o.Capture.Write != \"\" && o.Capture.Write != \"-\" {\n+\t\tfile, err := os.Create(o.Capture.Write)\n+\t\tif err != nil {\n+\t\t\treturn fmt.Errorf(\"failed to create the capture file: %w\", err)\n+\t\t}\n+\t\tdefer file.Close()\n+\t\toutput = file\n+\n+\t\t// the file belongs to the user who ran the command, also through sudo or setuid\n+\t\tif err := clabutils.SetUIDAndGID(o.Capture.Write); err != nil {\n+\t\t\tlog.Debug(\"Cannot hand the capture file to the user\", \"file\", o.Capture.Write,\n+\t\t\t\t\"error\", err)\n+\t\t}\n+\t}\n+\n+\terr = c.Capture(cmd.Context(), clablabruntime.CaptureRequest{\n+\t\tTargets:     targets,\n+\t\tDuration:    o.Capture.Duration,\n+\t\tPacketLimit: o.Capture.PacketLimit,\n+\t\tSnapLength:  o.Capture.SnapLength,\n+\t}, output)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tif file, ok := output.(*os.File); ok && output != cmd.OutOrStdout() {\n+\t\tif err := file.Sync(); err != nil {\n+\t\t\treturn fmt.Errorf(\"failed to write the capture file: %w\", err)\n+\t\t}\n+\t}\n+\n+\treturn nil\n+}\n+\n+// parseCaptureTargets parses --target values: <node>:<interface>[,<interface>...]. The node name\n+// ends at the first colon, so interface names may contain colons or slashes.\n+func parseCaptureTargets(values []string) ([]clablabruntime.CaptureTarget, error) {\n+\tif len(values) == 0 {\n+\t\treturn nil, fmt.Errorf(\"provide at least one --target <node>:<interface>[,<interface>...]\")\n+\t}\n+\n+\ttargets := make([]clablabruntime.CaptureTarget, 0, len(values))\n+\tfor _, value := range values {\n+\t\tnode, interfaces, ok := strings.Cut(strings.TrimSpace(value), \":\")\n+\t\tnode = strings.TrimSpace(node)\n+\t\tif !ok || node == \"\" || strings.TrimSpace(interfaces) == \"\" {\n+\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: use <node>:<interface>[,<interface>...]\",\n+\t\t\t\tvalue)\n+\t\t}\n+\n+\t\tfor _, name := range strings.Split(interfaces, \",\") {\n+\t\t\tname = strings.TrimSpace(name)\n+\t\t\tif name == \"\" {\n+\t\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: empty interface name\", value)\n+\t\t\t}\n+\t\t\ttargets = append(targets, clablabruntime.CaptureTarget{Node: node, Interface: name})\n+\t\t}\n+\t}\n+\n+\treturn targets, nil\n+}\n+\n+func captureListFn(cmd *cobra.Command, o *Options) error {\n+\tformat := o.Capture.Format\n+\tif format == \"\" {\n+\t\tformat = clabconstants.FormatTable\n+\t}\n+\tif format != clabconstants.FormatTable && format != clabconstants.FormatJSON {\n+\t\treturn fmt.Errorf(\"output format %q is not supported, use 'table' or 'json'\", format)\n+\t}\n+\tif len(o.Capture.Targets) != 0 {\n+\t\treturn fmt.Errorf(\"--list lists every running node's interfaces; it takes no --target\")\n+\t}\n+\n+\tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tinterfaces, err := c.CaptureInterfaces(cmd.Context())\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\treturn printCaptureInterfaces(cmd.OutOrStdout(), interfaces, format)\n+}\n+\n+func printCaptureInterfaces(\n+\tw io.Writer,\n+\tinterfaces []clablabruntime.CaptureInterface,\n+\tformat string,\n+) error {\n+\tif format == clabconstants.FormatJSON {\n+\t\tif interfaces == nil {\n+\t\t\tinterfaces = []clablabruntime.CaptureInterface{}\n+\t\t}\n+\t\tdata, err := json.MarshalIndent(interfaces, \"\", \"  \")\n+\t\tif err != nil {\n+\t\t\treturn err\n+\t\t}\n+\t\t_, err = fmt.Fprintln(w, string(data))\n+\n+\t\treturn err\n+\t}\n+\n+\ttable := tableWriter.NewWriter()\n+\ttable.SetOutputMirror(w)\n+\ttable.SetStyle(tableWriter.StyleRounded)\n+\ttable.Style().Format.Header = text.FormatTitle\n+\ttable.Style().Format.HeaderAlign = text.AlignCenter\n+\ttable.AppendHeader(tableWriter.Row{\"Node\", \"Interface\", \"Alias\", \"Peer Node\", \"Peer Interface\"})\n+\ttable.SetColumnConfigs([]tableWriter.ColumnConfig{{Number: 1, AutoMerge: true}})\n+\tfor _, intf := range interfaces {\n+\t\talias := intf.Alias\n+\t\tif alias == \"\" {\n+\t\t\talias = clabconstants.NotApplicable\n+\t\t}\n+\t\ttable.AppendRow(tableWriter.Row{\n+\t\t\tintf.Node, intf.Interface, alias, intf.PeerNode, intf.PeerInterface,\n+\t\t})\n+\t}\n+\ttable.Render()\n+\n+\treturn nil\n+}\ndiff --git a/cmd/capture_test.go b/cmd/capture_test.go\nnew file mode 100644\nindex 0000000..da12d66\n--- /dev/null\n+++ b/cmd/capture_test.go\n@@ -0,0 +1,109 @@\n+package cmd\n+\n+import (\n+\t\"bytes\"\n+\t\"encoding/json\"\n+\t\"slices\"\n+\t\"strings\"\n+\t\"testing\"\n+\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+)\n+\n+func TestParseCaptureTargets(t *testing.T) {\n+\tt.Parallel()\n+\n+\ttargets, err := parseCaptureTargets([]string{\n+\t\t\"srl1:e1-1,ethernet-1/2\", \" sros : 1/1/3 \", \"r1:eth1\",\n+\t})\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\twant := []clablabruntime.CaptureTarget{\n+\t\t{Node: \"srl1\", Interface: \"e1-1\"},\n+\t\t{Node: \"srl1\", Interface: \"ethernet-1/2\"},\n+\t\t{Node: \"sros\", Interface: \"1/1/3\"},\n+\t\t{Node: \"r1\", Interface: \"eth1\"},\n+\t}\n+\tif !slices.Equal(targets, want) {\n+\t\tt.Fatalf(\"targets = %+v, want %+v\", targets, want)\n+\t}\n+\n+\tfor _, bad := range [][]string{nil, {\"srl1\"}, {\":e1-1\"}, {\"srl1:\"}, {\"srl1:e1-1,,e1-2\"}} {\n+\t\tif _, err := parseCaptureTargets(bad); err == nil {\n+\t\t\tt.Errorf(\"parseCaptureTargets(%q) succeeded\", bad)\n+\t\t}\n+\t}\n+}\n+\n+func TestCaptureCommandFlags(t *testing.T) {\n+\to := GetOptions()\n+\tcmd, err := captureCmd(o)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif err := cmd.ParseFlags([]string{\n+\t\t\"--target\", \"srl1:e1-1\", \"--target\", \"srl2:e1-1,e1-2\", \"--duration\", \"90m\",\n+\t\t\"--packet-limit\", \"100\", \"--snap-length\", \"128\", \"-w\", \"out.pcapng\",\n+\t}); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif !slices.Equal(o.Capture.Targets, []string{\"srl1:e1-1\", \"srl2:e1-1,e1-2\"}) ||\n+\t\to.Capture.Duration.Minutes() != 90 || o.Capture.PacketLimit != 100 ||\n+\t\to.Capture.SnapLength != 128 || o.Capture.Write != \"out.pcapng\" {\n+\t\tt.Fatalf(\"capture options = %+v\", o.Capture)\n+\t}\n+\tif def := cmd.Flag(\"write\").DefValue; def != \"-\" {\n+\t\tt.Fatalf(\"--write default = %q, want stdout\", def)\n+\t}\n+}\n+\n+func TestPrintCaptureInterfaces(t *testing.T) {\n+\tt.Parallel()\n+\n+\tinterfaces := []clablabruntime.CaptureInterface{\n+\t\t{\n+\t\t\tNode:          \"srl1\",\n+\t\t\tInterface:     \"e1-1\",\n+\t\t\tAlias:         \"ethernet-1/1\",\n+\t\t\tPeerNode:      \"srl2\",\n+\t\t\tPeerInterface: \"ethernet-1/1\",\n+\t\t},\n+\t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"srl1-e1-2\"},\n+\t}\n+\n+\tvar out bytes.Buffer\n+\tif err := printCaptureInterfaces(&out, interfaces, \"json\"); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tvar decoded []map[string]any\n+\tif err := json.Unmarshal(out.Bytes(), &decoded); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif decoded[0][\"peer_node\"] != \"srl2\" || decoded[0][\"alias\"] != \"ethernet-1/1\" {\n+\t\tt.Fatalf(\"json = %s\", out.String())\n+\t}\n+\tif _, hasAlias := decoded[1][\"alias\"]; hasAlias {\n+\t\tt.Fatalf(\"an empty alias is printed: %s\", out.String())\n+\t}\n+\n+\tout.Reset()\n+\tif err := printCaptureInterfaces(\n+\t\t&out,\n+\t\tnil,\n+\t\t\"json\",\n+\t); err != nil ||\n+\t\tstrings.TrimSpace(out.String()) != \"[]\" {\n+\t\tt.Fatalf(\"empty json = %q, %v\", out.String(), err)\n+\t}\n+\n+\tout.Reset()\n+\tif err := printCaptureInterfaces(&out, interfaces, \"table\"); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tfor _, want := range []string{\"Peer Interface\", \"ethernet-1/1\", \"srl1-e1-2\", \"N/A\"} {\n+\t\tif !strings.Contains(out.String(), want) {\n+\t\t\tt.Fatalf(\"table does not contain %q:\\n%s\", want, out.String())\n+\t\t}\n+\t}\n+}\ndiff --git a/cmd/context.go b/cmd/context.go\nindex 223cb1d..21d5bea 100644\n--- a/cmd/context.go\n+++ b/cmd/context.go\n@@ -51,10 +51,20 @@ func SignalHandledContext() (context.Context, context.CancelFunc) {\n \n \t\tcancel()\n \n \t\toptions := GetOptions()\n \n+\t\tif options.Global.FinishOnCancel.Load() {\n+\t\t\tlog.Info(\"Stopping, press Ctrl+C again to abort\")\n+\n+\t\t\tsig = <-sigs\n+\n+\t\t\tlog.Errorf(\"received signal %q while stopping, exiting\", sig)\n+\n+\t\t\tos.Exit(1)\n+\t\t}\n+\n \t\tif !options.Global.CleanOnCancel.Load() {\n \t\t\tlog.Debug(\"clean on cancel is not true, exiting\")\n \n \t\t\tos.Exit(1)\n \t\t}\ndiff --git a/cmd/inspect.go b/cmd/inspect.go\nindex 1b6f41d..55fb61f 100644\n--- a/cmd/inspect.go\n+++ b/cmd/inspect.go\n@@ -70,10 +70,14 @@ func inspectCmd(o *Options) (*cobra.Command, error) {\n \t\tShort: \"inspect interfaces of one or multiple nodes in a lab\",\n \t\tLong: \"show interfaces and their attributes in a specific deployed lab\\n\" +\n \t\t\t\"reference: https://containerlab.dev/cmd/inspect/interfaces/\",\n \t\tAliases: []string{\"int\", \"intf\"},\n \t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n+\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n+\t\t\t\treturn nil\n+\t\t\t}\n+\n \t\t\treturn clabutils.CheckAndGetRootPrivs()\n \t\t},\n \t\tRunE: func(cobraCmd *cobra.Command, _ []string) error {\n \t\t\treturn inspectInterfacesFn(cobraCmd, o)\n \t\t},\ndiff --git a/cmd/inspect_interfaces.go b/cmd/inspect_interfaces.go\nindex 0f64f03..91035c2 100644\n--- a/cmd/inspect_interfaces.go\n+++ b/cmd/inspect_interfaces.go\n@@ -33,10 +33,25 @@ func inspectInterfacesFn(cobraCmd *cobra.Command, o *Options) error {\n \tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"could not parse the topology file: %v\", err)\n \t}\n \n+\tif c.LabRuntime != nil {\n+\t\t// lab runtimes list the link interfaces packet capture accepts, with their state\n+\t\tcontainerInterfaces, err := c.LabRuntimeInterfaces(cobraCmd.Context(),\n+\t\t\to.Inspect.InterfacesNode)\n+\t\tif err != nil {\n+\t\t\treturn fmt.Errorf(\"failed to list node interfaces: %w\", err)\n+\t\t}\n+\t\tif len(containerInterfaces) == 0 {\n+\t\t\tlog.Info(\"no running nodes found\")\n+\t\t\treturn nil\n+\t\t}\n+\n+\t\treturn printContainerInterfaces(containerInterfaces, o.Inspect.InterfacesFormat)\n+\t}\n+\n \tvar labNameFilterLabel string\n \n \tswitch {\n \tcase o.Global.TopologyName != \"\":\n \t\tlabNameFilterLabel = o.Global.TopologyName\ndiff --git a/cmd/options.go b/cmd/options.go\nindex 8717d3b..6037551 100644\n--- a/cmd/options.go\n+++ b/cmd/options.go\n@@ -53,10 +53,14 @@ func GetOptions() *Options {\n \t\t\t\tInterfacesFormat: \"table\",\n \t\t\t},\n \t\t\tLogs: &LogsOptions{\n \t\t\t\tTail: -1,\n \t\t\t},\n+\t\t\tCapture: &CaptureOptions{\n+\t\t\t\tWrite:  \"-\",\n+\t\t\t\tFormat: \"table\",\n+\t\t\t},\n \t\t\tGraph: &GraphOptions{\n \t\t\t\tServer:           \"0.0.0.0:50080\",\n \t\t\t\tMermaidDirection: \"TD\",\n \t\t\t\tDrawIOVersion:    \"latest\",\n \t\t\t},\n@@ -142,10 +146,11 @@ type Options struct {\n \tExec           *ExecOptions\n \tInspect        *InspectOptions\n \tGraph          *GraphOptions\n \tEvents         *EventsOptions\n \tLogs           *LogsOptions\n+\tCapture        *CaptureOptions\n \tToolsAPI       *ToolsApiOptions\n \tToolsCert      *ToolsCertOptions\n \tToolsTxOffload *ToolsDisableTxOffloadOptions\n \tToolsGoTTY     *ToolsGoTTYOptions\n \tToolsNetem     *ToolsNetemOptions\n@@ -257,10 +262,15 @@ type GlobalOptions struct {\n \t// special flag that should only be set by deploy, informs the context handler to destroy\n \t// (or not) when root context is canceled. The signal handler goroutine reads it while\n \t// deploy is running, so it is atomic.\n \tCleanOnCancel atomic.Bool\n \n+\t// FinishOnCancel informs the context handler that the running command ends cleanly on its\n+\t// own once the root context is canceled (capture finishes its output), so the handler\n+\t// waits for it instead of exiting.\n+\tFinishOnCancel atomic.Bool\n+\n \t// special flag that is only set on deploy,\n \t// if true, the topology file backup is created at /tmp/.clab/bak\n \tBackupTopologyFile bool\n }\n \ndiff --git a/cmd/root.go b/cmd/root.go\nindex 0baf203..a9b1c8b 100644\n--- a/cmd/root.go\n+++ b/cmd/root.go\n@@ -35,10 +35,11 @@ func subcommandRegisterFuncs() []func(*Options) (*cobra.Command, error) {\n \t\tgenerateCmd,\n \t\tgraphCmd,\n \t\teventsCmd,\n \t\tinspectCmd,\n \t\tlogsCmd,\n+\t\tcaptureCmd,\n \t\tredeployCmd,\n \t\tsaveCmd,\n \t\ttoolsCmd,\n \t\tvalidateCmd,\n \t}\n@@ -263,15 +264,10 @@ func checkLabRuntimeCommandSupport(cobraCmd *cobra.Command, runtimeName string)\n \t\t\t\"the %q command needs running containers with lab runtime %q unless it renders \"+\n \t\t\t\t\"from the topology file alone; use --offline, --dot, --mermaid or --drawio\",\n \t\t\t\"graph\", runtimeName)\n \t}\n \n-\tif getCommandPath(cobraCmd) == \"inspect.interfaces\" {\n-\t\treturn fmt.Errorf(\"the %q command is not supported with lab runtime %q\",\n-\t\t\t\"inspect interfaces\", runtimeName)\n-\t}\n-\n \tvar unsupported []string\n \tfor _, flagName := range labRuntimeUnsupportedFlags[getCommandPath(cobraCmd)] {\n \t\tif labRuntimeFlagWasSet(cobraCmd, flagName) {\n \t\t\tunsupported = append(unsupported, \"--\"+flagName)\n \t\t}\n@@ -339,10 +335,11 @@ func getTopoFilePath(cobraCmd *cobra.Command, o *Options) error { // skipcq: GO-\n \t\tcobraCmd.Name() != \"inspect\" &&\n \t\tcobraCmd.Name() != \"save\" &&\n \t\tcobraCmd.Name() != \"graph\" &&\n \t\tcobraCmd.Name() != \"validate\" &&\n \t\tcobraCmd.Name() != \"logs\" &&\n+\t\tcobraCmd.Name() != \"capture\" &&\n \t\tcobraCmd.Name() != \"interfaces\" {\n \t\treturn nil\n \t}\n \n \t// start/stop/restart topology lookup applies only to top-level lifecycle commands.\ndiff --git a/cmd/root_test.go b/cmd/root_test.go\nindex 418a947..af02e34 100644\n--- a/cmd/root_test.go\n+++ b/cmd/root_test.go\n@@ -289,20 +289,23 @@ func TestCheckLabRuntimeFlagAndNestedCommandSupport(t *testing.T) {\n \t\t\t\tt.Fatalf(\"checkLabRuntimeCommandSupport() error = %v, wantErr %v\", err, tt.wantErr)\n \t\t\t}\n \t\t})\n \t}\n \n-\tt.Run(\"inspect interfaces rejected\", func(t *testing.T) {\n+\tt.Run(\"inspect interfaces and capture accepted\", func(t *testing.T) {\n \t\troot := &cobra.Command{Use: \"containerlab\"}\n \t\tinspect := &cobra.Command{Use: \"inspect\"}\n \t\tinterfaces := &cobra.Command{Use: \"interfaces\"}\n-\t\troot.AddCommand(inspect)\n+\t\tcapture := &cobra.Command{Use: \"capture\"}\n+\t\troot.AddCommand(inspect, capture)\n \t\tinspect.AddCommand(interfaces)\n \n-\t\tif err := checkLabRuntimeCommandSupport(\n-\t\t\tinterfaces,\n-\t\t\tclablabruntime.ClabernetesRuntimeName,\n-\t\t); err == nil {\n-\t\t\tt.Fatal(\"inspect interfaces was accepted for clabernetes\")\n+\t\tfor _, cmd := range []*cobra.Command{interfaces, capture} {\n+\t\t\tif err := checkLabRuntimeCommandSupport(\n+\t\t\t\tcmd,\n+\t\t\t\tclablabruntime.ClabernetesRuntimeName,\n+\t\t\t); err != nil {\n+\t\t\t\tt.Fatalf(\"%s rejected for clabernetes: %v\", cmd.Name(), err)\n+\t\t\t}\n \t\t}\n \t})\n }\ndiff --git a/core/capture.go b/core/capture.go\nnew file mode 100644\nindex 0000000..2e12fc2\n--- /dev/null\n+++ b/core/capture.go\n@@ -0,0 +1,93 @@\n+package core\n+\n+import (\n+\t\"context\"\n+\t\"io\"\n+\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tclabtypes \"github.com/srl-labs/containerlab/types\"\n+)\n+\n+// CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for",
        "lineStart": 2161,
        "lineEnd": 2760,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523340044,
      "end": 1793523340064
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196525323001kYkUcWzX8O0PFK",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196524566001amBVNvfJ9FiMxm",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 17083,
    "input": 16832,
    "output": 26,
    "reasoning": 225,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196524566001amBVNvfJ9FiMxm",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523336550,
    "completed": 1793523340070
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 17083,
    "input": 16832,
    "output": 26,
    "reasoning": 225,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 27
step-start
{
  "type": "step-start",
  "id": "prt_196525aa3001brz9AfFT54QZyV",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19652532d001VBllmmBAf5BXgY"
}
Reasoning
Now let me continue reading the diff: 2761-3520 (core/capture.go, capture_local.go, capture_test.go, labruntime_cluster_test.go, test_data, docs).
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 760,
  "offset": 2761
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
2761: +// every running node, with the peer at the other end of each link. With Docker and Podman, the
2762: +// interfaces come from the topology's links; lab runtimes list them through their packet
2763: +// capturer.
2764: +func (c *CLab) CaptureInterfaces(
2765: +	ctx context.Context,
2766: +	nodeNames ...string,
2767: +) ([]clablabruntime.CaptureInterface, error) {
2768: +	if c.LabRuntime == nil {
2769: +		return c.localCaptureInterfacesOf(ctx, nodeNames)
2770: +	}
2771: +
2772: +	capturer, err := c.packetCapturer()
2773: +	if err != nil {
2774: +		return nil, err
2775: +	}
2776: +
2777: +	return capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{
2778: +		Name:     c.Config.Name,
2779: +		Nodes:    nodeNames,
2780: +		Identity: c.labRuntimeIdentity,
2781: +	})
2782: +}
2783: +
2784: +// Capture streams pcapng from lab link interfaces to w until req.Duration passed,
2785: +// req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name
2786: +// and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces
2787: +// itself through packet sockets in the nodes' network namespaces, which needs root; lab
2788: +// runtimes capture through their packet capturer.
2789: +func (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {
2790: +	if c.LabRuntime == nil {
2791: +		return c.captureLocal(ctx, req, w)
2792: +	}
2793: +
2794: +	capturer, err := c.packetCapturer()
2795: +	if err != nil {
2796: +		return err
2797: +	}
2798: +
2799: +	if req.Name == "" {
2800: +		req.Name = c.Config.Name
2801: +	}
2802: +	if req.Identity.IsZero() {
2803: +		req.Identity = c.labRuntimeIdentity
2804: +	}
2805: +
2806: +	return capturer.Capture(ctx, req, w)
2807: +}
2808: +
2809: +// LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their
2810: +// state, in the shape ListContainersInterfaces reports for local containers.
2811: +func (c *CLab) LabRuntimeInterfaces(
2812: +	ctx context.Context,
2813: +	nodeName string,
2814: +) ([]*clabtypes.ContainerInterfaces, error) {
2815: +	inspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](
2816: +		c, "inspecting interfaces")
2817: +	if err != nil {
2818: +		return nil, err
2819: +	}
2820: +	if err := c.requireLabName(); err != nil {
2821: +		return nil, err
2822: +	}
2823: +
2824: +	req := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}
2825: +	if nodeName != "" {
2826: +		req.Nodes = []string{nodeName}
2827: +	}
2828: +
2829: +	return inspector.InspectInterfaces(ctx, req)
2830: +}
2831: +
2832: +func (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {
2833: +	capturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, "packet capture")
2834: +	if err != nil {
2835: +		return nil, err
2836: +	}
2837: +	if err := c.requireLabName(); err != nil {
2838: +		return nil, err
2839: +	}
2840: +
2841: +	return capturer, nil
2842: +}
2843: diff --git a/core/capture_local.go b/core/capture_local.go
2844: new file mode 100644
2845: index 0000000..fada0bf
2846: --- /dev/null
2847: +++ b/core/capture_local.go
2848: @@ -0,0 +1,255 @@
2849: +package core
2850: +
2851: +import (
2852: +	"context"
2853: +	"fmt"
2854: +	"io"
2855: +	"slices"
2856: +	"sort"
2857: +	"strings"
2858: +
2859: +	clabcapture "github.com/srl-labs/containerlab/capture"
2860: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2861: +	clablinks "github.com/srl-labs/containerlab/links"
2862: +	clabnodes "github.com/srl-labs/containerlab/nodes"
2863: +	clabruntime "github.com/srl-labs/containerlab/runtime"
2864: +)
2865: +
2866: +// localCaptureInterface is a lab link interface of a node on this machine.
2867: +type localCaptureInterface struct {
2868: +	node clabnodes.Node
2869: +	info clablabruntime.CaptureInterface
2870: +}
2871: +
2872: +// localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with
2873: +// the far end of each link, per node name. Host and management network endpoints are the far
2874: +// ends of links, not nodes to capture on.
2875: +func (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {
2876: +	if len(c.Nodes) == 0 {
2877: +		return nil, fmt.Errorf("the topology of lab %q is not available; capture reads the "+
2878: +			"lab's links from it, pass it with --topo", c.Config.Name)
2879: +	}
2880: +	if len(c.Links) == 0 {
2881: +		if err := c.ResolveLinks(); err != nil {
2882: +			return nil, fmt.Errorf("failed to resolve the links of lab %q: %w", c.Config.Name, err)
2883: +		}
2884: +	}
2885: +
2886: +	indexes := make([]int, 0, len(c.Links))
2887: +	for idx := range c.Links {
2888: +		indexes = append(indexes, idx)
2889: +	}
2890: +	sort.Ints(indexes)
2891: +
2892: +	result := map[string][]localCaptureInterface{}
2893: +	for _, idx := range indexes {
2894: +		endpoints := c.Links[idx].GetEndpoints()
2895: +		for epIdx, endpoint := range endpoints {
2896: +			if endpoint.IsNodeless() || endpoint.IsRuntimeDiscovered() ||
2897: +				endpoint.GetNode() == nil {
2898: +				continue
2899: +			}
2900: +			name := endpoint.GetNode().GetShortName()
2901: +			node, ok := c.Nodes[name]
2902: +			if !ok {
2903: +				continue
2904: +			}
2905: +
2906: +			info := clablabruntime.CaptureInterface{
2907: +				Node:      name,
2908: +				Interface: endpoint.GetIfaceName(),
2909: +			}
2910: +			if alias := endpoint.GetIfaceAlias(); alias != info.Interface {
2911: +				info.Alias = alias
2912: +			}
2913: +			if len(endpoints) == 2 {
2914: +				peer := endpoints[1-epIdx]
2915: +				info.PeerNode = capturePeerNode(peer)
2916: +				info.PeerInterface = peer.GetIfaceDisplayName()
2917: +			}
2918: +
2919: +			result[name] = append(result[name], localCaptureInterface{node: node, info: info})
2920: +		}
2921: +	}
2922: +
2923: +	return result, nil
2924: +}
2925: +
2926: +// capturePeerNode names the node at the far end of a link: "host" for a host endpoint and
2927: +// "mgmt-net" for the management network, whose shared link nodes carry other names once a lab
2928: +// was deployed.
2929: +func capturePeerNode(peer clablinks.Endpoint) string {
2930: +	if peer.IsNodeless() {
2931: +		if _, ok := peer.(*clablinks.EndpointBridge); ok {
2932: +			return string(clablinks.LinkTypeMgmtNet)
2933: +		}
2934: +
2935: +		return string(clablinks.LinkTypeHost)
2936: +	}
2937: +	if peer.GetNode() == nil {
2938: +		return ""
2939: +	}
2940: +
2941: +	return peer.GetNode().GetShortName()
2942: +}
2943: +
2944: +// lookupLocalNode finds a lab node by its topology name or its container name.
2945: +func (c *CLab) lookupLocalNode(name string) (clabnodes.Node, error) {
2946: +	if node, ok := c.Nodes[name]; ok {
2947: +		return node, nil
2948: +	}
2949: +	for _, node := range c.Nodes {
2950: +		if node.Config().LongName == name {
2951: +			return node, nil
2952: +		}
2953: +	}
2954: +
2955: +	names := make([]string, 0, len(c.Nodes))
2956: +	for nodeName := range c.Nodes {
2957: +		names = append(names, nodeName)
2958: +	}
2959: +	slices.Sort(names)
2960: +
2961: +	return nil, fmt.Errorf("node %q is not part of lab %q; nodes: %s", name, c.Config.Name,
2962: +		strings.Join(names, ", "))
2963: +}
2964: +
2965: +// nodeRuns reports whether a node's network namespace can be entered.
2966: +func nodeRuns(ctx context.Context, node clabnodes.Node) bool {
2967: +	if node.Config().IsRootNamespaceBased {
2968: +		return true
2969: +	}
2970: +
2971: +	return clabruntime.ContainerHasJoinableNetns(node.GetContainerStatus(ctx))
2972: +}
2973: +
2974: +// localCaptureInterfacesOf implements CaptureInterfaces for Docker and Podman: the requested
2975: +// nodes, or every running node.
2976: +func (c *CLab) localCaptureInterfacesOf(
2977: +	ctx context.Context,
2978: +	nodeNames []string,
2979: +) ([]clablabruntime.CaptureInterface, error) {
2980: +	if err := c.requireLabName(); err != nil {
2981: +		return nil, err
2982: +	}
2983: +	byNode, err := c.localCaptureInterfaces()
2984: +	if err != nil {
2985: +		return nil, err
2986: +	}
2987: +
2988: +	var nodes []clabnodes.Node
2989: +	if len(nodeNames) == 0 {
2990: +		for _, node := range c.Nodes {
2991: +			if nodeRuns(ctx, node) {
2992: +				nodes = append(nodes, node)
2993: +			}
2994: +		}
2995: +	} else {
2996: +		for _, name := range nodeNames {
2997: +			node, err := c.lookupLocalNode(name)
2998: +			if err != nil {
2999: +				return nil, err
3000: +			}
3001: +			nodes = append(nodes, node)
3002: +		}
3003: +	}
3004: +
3005: +	result := make([]clablabruntime.CaptureInterface, 0)
3006: +	seen := map[string]bool{}
3007: +	for _, node := range nodes {
3008: +		name := node.Config().ShortName
3009: +		if seen[name] {
3010: +			continue
3011: +		}
3012: +		seen[name] = true
3013: +		for _, entry := range byNode[name] {
3014: +			result = append(result, entry.info)
3015: +		}
3016: +	}
3017: +	sortCaptureInterfaces(result)
3018: +
3019: +	return result, nil
3020: +}
3021: +
3022: +func sortCaptureInterfaces(interfaces []clablabruntime.CaptureInterface) {
3023: +	sort.SliceStable(interfaces, func(i, j int) bool {
3024: +		if interfaces[i].Node != interfaces[j].Node {
3025: +			return interfaces[i].Node < interfaces[j].Node
3026: +		}
3027: +
3028: +		return interfaces[i].Interface < interfaces[j].Interface
3029: +	})
3030: +}
3031: +
3032: +// resolveLocalCaptureTargets checks every target against the node's link interfaces, by name or
3033: +// alias, and returns them in request order.
3034: +func (c *CLab) resolveLocalCaptureTargets(
3035: +	targets []clablabruntime.CaptureTarget,
3036: +) ([]clabcapture.LocalTarget, error) {
3037: +	byNode, err := c.localCaptureInterfaces()
3038: +	if err != nil {
3039: +		return nil, err
3040: +	}
3041: +
3042: +	resolved := make([]clabcapture.LocalTarget, 0, len(targets))
3043: +	seen := map[string]bool{}
3044: +	for _, target := range targets {
3045: +		node, err := c.lookupLocalNode(target.Node)
3046: +		if err != nil {
3047: +			return nil, err
3048: +		}
3049: +		name := node.Config().ShortName
3050: +
3051: +		infos := make([]clablabruntime.CaptureInterface, 0, len(byNode[name]))
3052: +		for _, entry := range byNode[name] {
3053: +			infos = append(infos, entry.info)
3054: +		}
3055: +		sortCaptureInterfaces(infos)
3056: +		info, ok := clabcapture.FindInterface(infos, target.Interface)
3057: +		if !ok {
3058: +			return nil, fmt.Errorf("interface %q of node %q is not a capturable link "+
3059: +				"interface; capturable: %s", target.Interface, target.Node,
3060: +				clabcapture.DescribeInterfaces(infos))
3061: +		}
3062: +
3063: +		key := name + "\x00" + info.Interface
3064: +		if seen[key] {
3065: +			return nil, fmt.Errorf("interface %q of node %q is requested more than once",
3066: +				info.Interface, target.Node)
3067: +		}
3068: +		seen[key] = true
3069: +
3070: +		resolved = append(resolved, clabcapture.LocalTarget{
3071: +			Node:      name,
3072: +			Interface: info.Interface,
3073: +			Exec:      node.ExecFunction,
3074: +		})
3075: +	}
3076: +
3077: +	return resolved, nil
3078: +}
3079: +
3080: +// captureLocal implements Capture for Docker and Podman through packet sockets in the nodes'
3081: +// network namespaces.
3082: +func (c *CLab) captureLocal(
3083: +	ctx context.Context,
3084: +	req clablabruntime.CaptureRequest,
3085: +	w io.Writer,
3086: +) error {
3087: +	if err := c.requireLabName(); err != nil {
3088: +		return err
3089: +	}
3090: +	if req.Name == "" {
3091: +		req.Name = c.Config.Name
3092: +	}
3093: +	if err := clabcapture.ValidateRequest(&req); err != nil {
3094: +		return err
3095: +	}
3096: +
3097: +	targets, err := c.resolveLocalCaptureTargets(req.Targets)
3098: +	if err != nil {
3099: +		return err
3100: +	}
3101: +
3102: +	return clabcapture.CaptureLocal(ctx, req, targets, w)
3103: +}
3104: diff --git a/core/capture_test.go b/core/capture_test.go
3105: new file mode 100644
3106: index 0000000..b5d34b0
3107: --- /dev/null
3108: +++ b/core/capture_test.go
3109: @@ -0,0 +1,210 @@
3110: +package core
3111: +
3112: +import (
3113: +	"bytes"
3114: +	"context"
3115: +	"io"
3116: +	"slices"
3117: +	"strings"
3118: +	"testing"
3119: +
3120: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
3121: +	clabtypes "github.com/srl-labs/containerlab/types"
3122: +)
3123: +
3124: +// captureLabRuntime records the capture requests core sends.
3125: +type captureLabRuntime struct {
3126: +	clablabruntime.LabRuntime
3127: +
3128: +	nodeRequest    clablabruntime.NodeRequest
3129: +	captureRequest clablabruntime.CaptureRequest
3130: +}
3131: +
3132: +func (r *captureLabRuntime) CaptureInterfaces(
3133: +	_ context.Context,
3134: +	req clablabruntime.NodeRequest,
3135: +) ([]clablabruntime.CaptureInterface, error) {
3136: +	r.nodeRequest = req
3137: +
3138: +	return []clablabruntime.CaptureInterface{{Node: "r1", Interface: "eth1"}}, nil
3139: +}
3140: +
3141: +func (r *captureLabRuntime) Capture(
3142: +	_ context.Context,
3143: +	req clablabruntime.CaptureRequest,
3144: +	w io.Writer,
3145: +) error {
3146: +	r.captureRequest = req
3147: +	_, err := io.WriteString(w, "pcapng")
3148: +
3149: +	return err
3150: +}
3151: +
3152: +func (r *captureLabRuntime) InspectInterfaces(
3153: +	_ context.Context,
3154: +	req clablabruntime.NodeRequest,
3155: +) ([]*clabtypes.ContainerInterfaces, error) {
3156: +	r.nodeRequest = req
3157: +
3158: +	return []*clabtypes.ContainerInterfaces{{ContainerName: "lab1-r1"}}, nil
3159: +}
3160: +
3161: +func TestCaptureHelpersFillLabAndIdentity(t *testing.T) {
3162: +	t.Parallel()
3163: +
3164: +	lr := &captureLabRuntime{}
3165: +	c := newAccessTestCLab(lr)
3166: +	ctx := context.Background()
3167: +
3168: +	interfaces, err := c.CaptureInterfaces(ctx, "R1")
3169: +	if err != nil || len(interfaces) != 1 {
3170: +		t.Fatalf("CaptureInterfaces() = %+v, %v", interfaces, err)
3171: +	}
3172: +	if lr.nodeRequest.Name != "lab1" || lr.nodeRequest.Nodes[0] != "R1" ||
3173: +		!lr.nodeRequest.Identity.Equal(testIdentity) {
3174: +		t.Fatalf("interfaces request = %+v", lr.nodeRequest)
3175: +	}
3176: +
3177: +	var out bytes.Buffer
3178: +	if err := c.Capture(ctx, clablabruntime.CaptureRequest{
3179: +		Targets: []clablabruntime.CaptureTarget{{Node: "r1", Interface: "eth1"}},
3180: +	}, &out); err != nil {
3181: +		t.Fatal(err)
3182: +	}
3183: +	if out.String() != "pcapng" || lr.captureRequest.Name != "lab1" ||
3184: +		!lr.captureRequest.Identity.Equal(testIdentity) {
3185: +		t.Fatalf("capture request = %+v, output %q", lr.captureRequest, out.String())
3186: +	}
3187: +
3188: +	ifaces, err := c.LabRuntimeInterfaces(ctx, "r1")
3189: +	if err != nil || len(ifaces) != 1 || lr.nodeRequest.Nodes[0] != "r1" {
3190: +		t.Fatalf("LabRuntimeInterfaces() = %+v, %v, request %+v", ifaces, err, lr.nodeRequest)
3191: +	}
3192: +	if _, err := c.LabRuntimeInterfaces(ctx, ""); err != nil || lr.nodeRequest.Nodes != nil {
3193: +		t.Fatalf("all nodes request = %+v, %v", lr.nodeRequest, err)
3194: +	}
3195: +}
3196: +
3197: +// newLocalCaptureCLab loads the capture test topology. Its host and mgmt-net links register
3198: +// endpoints on link nodes the whole process shares, so the tests using it do not run in
3199: +// parallel and release the endpoints when they end.
3200: +func newLocalCaptureCLab(t *testing.T) *CLab {
3201: +	t.Helper()
3202: +
3203: +	c, err := NewContainerLab(WithTopoPath("test_data/capture.clab.yml", nil))
3204: +	if err != nil {
3205: +		t.Fatal(err)
3206: +	}
3207: +	t.Cleanup(c.resetResolvedLinks)
3208: +
3209: +	return c
3210: +}
3211: +
3212: +func TestLocalCaptureInterfacesComeFromTheTopologyLinks(t *testing.T) {
3213: +	c := newLocalCaptureCLab(t)
3214: +
3215: +	got, err := c.CaptureInterfaces(context.Background(), "srl1", "client")
3216: +	if err != nil {
3217: +		t.Fatal(err)
3218: +	}
3219: +	want := []clablabruntime.CaptureInterface{
3220: +		{Node: "client", Interface: "eth1", PeerNode: "srl1", PeerInterface: "e1-2"},
3221: +		{Node: "client", Interface: "eth2", PeerNode: "host", PeerInterface: "client-eth2"},
3222: +		{Node: "client", Interface: "eth3", PeerNode: "mgmt-net", PeerInterface: "client-eth3"},
3223: +		{
3224: +			Node: "srl1", Interface: "e1-1", Alias: "ethernet-1/1",
3225: +			PeerNode: "srl2", PeerInterface: "e1-1",
3226: +		},
3227: +		{Node: "srl1", Interface: "e1-2", PeerNode: "client", PeerInterface: "eth1"},
3228: +	}
3229: +	if !slices.Equal(got, want) {
3230: +		t.Fatalf("CaptureInterfaces() =\n%+v\nwant\n%+v", got, want)
3231: +	}
3232: +
3233: +	if _, err := c.CaptureInterfaces(context.Background(), "r9"); err == nil ||
3234: +		!strings.Contains(err.Error(), `node "r9" is not part of lab "capture"`) {
3235: +		t.Fatalf("unknown node: error = %v", err)
3236: +	}
3237: +}
3238: +
3239: +func TestLocalCaptureTargetsResolveByNameOrAlias(t *testing.T) {
3240: +	c := newLocalCaptureCLab(t)
3241: +
3242: +	targets, err := c.resolveLocalCaptureTargets([]clablabruntime.CaptureTarget{
3243: +		{Node: "srl2", Interface: "e1-1"},
3244: +		{Node: "srl1", Interface: "ethernet-1/1"},
3245: +		{Node: "clab-capture-client", Interface: "eth2"},
3246: +	})
3247: +	if err != nil {
3248: +		t.Fatal(err)
3249: +	}
3250: +	var got []string
3251: +	for _, target := range targets {
3252: +		if target.Exec == nil {
3253: +			t.Fatalf("target %s:%s has no namespace exec", target.Node, target.Interface)
3254: +		}
3255: +		got = append(got, target.Node+":"+target.Interface)
3256: +	}
3257: +	if want := []string{"srl2:e1-1", "srl1:e1-1", "client:eth2"}; !slices.Equal(got, want) {
3258: +		t.Fatalf("targets = %v, want %v", got, want)
3259: +	}
3260: +
3261: +	for _, tc := range []struct {
3262: +		name    string
3263: +		targets []clablabruntime.CaptureTarget
3264: +		want    string
3265: +	}{
3266: +		{
3267: +			name:    "management interface",
3268: +			targets: []clablabruntime.CaptureTarget{{Node: "client", Interface: "eth0"}},
3269: +			want: `interface "eth0" of node "client" is not a capturable link interface; ` +
3270: +				"capturable: eth1, eth2, eth3",
3271: +		},
3272: +		{
3273: +			name: "same interface twice",
3274: +			targets: []clablabruntime.CaptureTarget{
3275: +				{Node: "srl1", Interface: "e1-1"}, {Node: "srl1", Interface: "ethernet-1/1"},
3276: +			},
3277: +			want: `interface "e1-1" of node "srl1" is requested more than once`,
3278: +		},
3279: +		{
3280: +			name:    "unknown node",
3281: +			targets: []clablabruntime.CaptureTarget{{Node: "r9", Interface: "eth1"}},
3282: +			want:    `node "r9" is not part of lab "capture"`,
3283: +		},
3284: +	} {
3285: +		if _, err := c.resolveLocalCaptureTargets(tc.targets); err == nil ||
3286: +			!strings.Contains(err.Error(), tc.want) {
3287: +			t.Errorf("%s: error = %v, want %q", tc.name, err, tc.want)
3288: +		}
3289: +	}
3290: +}
3291: +
3292: +func TestLocalCaptureNeedsTheTopology(t *testing.T) {
3293: +	t.Parallel()
3294: +
3295: +	c := &CLab{Config: &Config{Name: "lab1"}, globalRuntimeName: "docker"}
3296: +	err := c.Capture(context.Background(), clablabruntime.CaptureRequest{
3297: +		Targets: []clablabruntime.CaptureTarget{{Node: "r1", Interface: "eth1"}},
3298: +	}, io.Discard)
3299: +	if err == nil || !strings.Contains(err.Error(), `the topology of lab "lab1" is not available`) {
3300: +		t.Fatalf("error = %v", err)
3301: +	}
3302: +	if err := c.Capture(context.Background(), clablabruntime.CaptureRequest{},
3303: +		io.Discard); err == nil || !strings.Contains(err.Error(), "at least one capture target") {
3304: +		t.Fatalf("no targets: error = %v", err)
3305: +	}
3306: +}
3307: +
3308: +func TestLabRuntimeWithoutCaptureFails(t *testing.T) {
3309: +	t.Parallel()
3310: +
3311: +	unsupported := newAccessTestCLab(&recordingDestroyLabRuntime{})
3312: +	if err := unsupported.Capture(
3313: +		context.Background(),
3314: +		clablabruntime.CaptureRequest{},
3315: +		io.Discard,
3316: +	); err == nil || !strings.Contains(err.Error(), "does not support packet capture") {
3317: +		t.Fatalf("lab runtime without capture: error = %v", err)
3318: +	}
3319: +}
3320: diff --git a/core/labruntime_cluster_test.go b/core/labruntime_cluster_test.go
3321: index 06ecf57..981a302 100644
3322: --- a/core/labruntime_cluster_test.go
3323: +++ b/core/labruntime_cluster_test.go
3324: @@ -1,10 +1,11 @@
3325:  package core
3326:  
3327:  import (
3328:  	"bytes"
3329:  	"context"
3330: +	"encoding/binary"
3331:  	"errors"
3332:  	"io"
3333:  	"net"
3334:  	"net/http"
3335:  	"os"
3336: @@ -175,5 +176,153 @@ func TestC9sClusterNodeAccess(t *testing.T) {
3337:  		if err == nil || !strings.Contains(err.Error(), "forbidden") {
3338:  			t.Fatalf("impersonated user without rights: error = %v, want forbidden", err)
3339:  		}
3340:  	})
3341:  }
3342: +
3343: +// TestC9sClusterCapture captures through the library against a deployed c9s lab, as an identity
3344: +// that holds only the clabernetes-lab-editor role in the lab namespace. It runs only when
3345: +// CLAB_C9S_TEST_LAB names the lab and CLAB_C9S_TEST_CAPTURE_USER the identity (tests/14-clabernetes
3346: +// sets both). The lab must have linux nodes "client" (10.10.10.1) and "server" (10.10.10.2)
3347: +// linked by eth1. CLAB_C9S_TEST_FORBIDDEN_USER names an identity without a binding.
3348: +func TestC9sClusterCapture(t *testing.T) {
3349: +	lab := os.Getenv("CLAB_C9S_TEST_LAB")
3350: +	user := os.Getenv("CLAB_C9S_TEST_CAPTURE_USER")
3351: +	if lab == "" || user == "" {
3352: +		t.Skip("CLAB_C9S_TEST_LAB or CLAB_C9S_TEST_CAPTURE_USER is not set")
3353: +	}
3354: +
3355: +	newCLab := func(t *testing.T, user string) *CLab {
3356: +		t.Helper()
3357: +
3358: +		c, err := NewContainerLab(
3359: +			WithRuntime(clablabruntime.ClabernetesRuntimeName, nil),
3360: +			WithTopologyName(lab),
3361: +			WithLabRuntimeIdentity(clablabruntime.Identity{User: user}),
3362: +		)
3363: +		if err != nil {
3364: +			t.Fatal(err)
3365: +		}
3366: +
3367: +		return c
3368: +	}
3369: +	c := newCLab(t, user)
3370: +
3371: +	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
3372: +	defer cancel()
3373: +
3374: +	t.Run("version check", func(t *testing.T) {
3375: +		if err := c.CheckLabRuntimeSupport(ctx); err != nil {
3376: +			t.Fatal(err)
3377: +		}
3378: +	})
3379: +
3380: +	t.Run("capture interfaces", func(t *testing.T) {
3381: +		interfaces, err := c.CaptureInterfaces(ctx)
3382: +		if err != nil {
3383: +			t.Fatal(err)
3384: +		}
3385: +		want := []clablabruntime.CaptureInterface{
3386: +			{Node: "client", Interface: "eth1", PeerNode: "server", PeerInterface: "eth1"},
3387: +			{Node: "server", Interface: "eth1", PeerNode: "client", PeerInterface: "eth1"},
3388: +		}
3389: +		if len(interfaces) != 2 || interfaces[0] != want[0] || interfaces[1] != want[1] {
3390: +			t.Fatalf("interfaces = %+v", interfaces)
3391: +		}
3392: +	})
3393: +
3394: +	t.Run("capture both ends of a link", func(t *testing.T) {
3395: +		pinged := make(chan error, 1)
3396: +		go func() {
3397: +			time.Sleep(time.Second)
3398: +			pinged <- c.AttachLabRuntimeNode(ctx, clablabruntime.AttachRequest{
3399: +				NodeName: "client",
3400: +				Command:  []string{"ping", "-c", "4", "-i", "0.3", "10.10.10.2"},
3401: +			}, clablabruntime.AttachStreams{Stdout: io.Discard})
3402: +		}()
3403: +
3404: +		var out bytes.Buffer
3405: +		err := c.Capture(ctx, clablabruntime.CaptureRequest{
3406: +			Targets: []clablabruntime.CaptureTarget{
3407: +				{Node: "client", Interface: "eth1"}, {Node: "server", Interface: "eth1"},
3408: +			},
3409: +			Duration: 5 * time.Second,
3410: +		}, &out)
3411: +		if err != nil {
3412: +			t.Fatal(err)
3413: +		}
3414: +		if err := <-pinged; err != nil {
3415: +			t.Fatalf("ping: %v", err)
3416: +		}
3417: +
3418: +		names, icmp := summarizePCAPNG(t, out.Bytes())
3419: +		if len(names) != 2 || names[0] != "client:eth1" || names[1] != "server:eth1" {
3420: +			t.Fatalf("interfaces = %v", names)
3421: +		}
3422: +		// every echo request and reply crosses both ends
3423: +		if icmp[0] < 8 || icmp[1] < 8 {
3424: +			t.Fatalf("ICMP packets per interface = %v, want at least 8 on each", icmp)
3425: +		}
3426: +	})
3427: +
3428: +	t.Run("restart as lab editor", func(t *testing.T) {
3429: +		if err := c.RestartNodes(ctx, []string{"server"}); err != nil {
3430: +			t.Fatal(err)
3431: +		}
3432: +	})
3433: +
3434: +	t.Run("forbidden identity", func(t *testing.T) {
3435: +		forbidden := os.Getenv("CLAB_C9S_TEST_FORBIDDEN_USER")
3436: +		if forbidden == "" {
3437: +			t.Skip("CLAB_C9S_TEST_FORBIDDEN_USER is not set")
3438: +		}
3439: +
3440: +		err := newCLab(t, forbidden).Capture(ctx, clablabruntime.CaptureRequest{
3441: +			Targets:  []clablabruntime.CaptureTarget{{Node: "client", Interface: "eth1"}},
3442: +			Duration: time.Second,
3443: +		}, io.Discard)
3444: +		if err == nil || !strings.Contains(err.Error(), "forbidden") {
3445: +			t.Fatalf("capture as %s = %v, want forbidden", forbidden, err)
3446: +		}
3447: +	})
3448: +}
3449: +
3450: +// summarizePCAPNG returns the interface names of a little-endian pcapng stream and its IPv4 ICMP
3451: +// packets per interface ID.
3452: +func summarizePCAPNG(t *testing.T, data []byte) ([]string, map[uint32]int) {
3453: +	t.Helper()
3454: +
3455: +	var names []string
3456: +	icmp := map[uint32]int{}
3457: +	for len(data) >= 12 {
3458: +		blockType := binary.LittleEndian.Uint32(data[0:4])
3459: +		length := int(binary.LittleEndian.Uint32(data[4:8]))
3460: +		if length < 12 || length > len(data) {
3461: +			t.Fatalf("invalid block length %d", length)
3462: +		}
3463: +		body := data[8 : length-4]
3464: +		switch blockType {
3465: +		case 1: // Interface Description Block
3466: +			options := body[8:]
3467: +			for len(options) >= 4 {
3468: +				code := binary.LittleEndian.Uint16(options[0:2])
3469: +				size := int(binary.LittleEndian.Uint16(options[2:4]))
3470: +				if code == 0 {
3471: +					break
3472: +				}
3473: +				if code == 2 {
3474: +					names = append(names, string(options[4:4+size]))
3475: +				}
3476: +				options = options[4+size+(4-size%4)%4:]
3477: +			}
3478: +		case 6: // Enhanced Packet Block
3479: +			id := binary.LittleEndian.Uint32(body[0:4])
3480: +			frame := body[20 : 20+binary.LittleEndian.Uint32(body[12:16])]
3481: +			if len(frame) > 23 && frame[12] == 0x08 && frame[13] == 0x00 && frame[23] == 1 {
3482: +				icmp[id]++
3483: +			}
3484: +		}
3485: +		data = data[length:]
3486: +	}
3487: +
3488: +	return names, icmp
3489: +}
3490: diff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml
3491: new file mode 100644
3492: index 0000000..0422c22
3493: --- /dev/null
3494: +++ b/core/test_data/capture.clab.yml
3495: @@ -0,0 +1,15 @@
3496: +name: capture
3497: +topology:
3498: +  nodes:
3499: +    srl1:
3500: +      kind: nokia_srlinux
3501: +    srl2:
3502: +      kind: nokia_srlinux
3503: +    client:
3504: +      kind: linux
3505: +      image: alpine:3
3506: +  links:
3507: +    - endpoints: ["srl1:ethernet-1/1", "srl2:e1-1"]
3508: +    - endpoints: ["srl1:e1-2", "client:eth1"]
3509: +    - endpoints: ["client:eth2", "host:client-eth2"]
3510: +    - endpoints: ["client:eth3", "mgmt-net:client-eth3"]
3511: diff --git a/docs/cmd/capture.md b/docs/cmd/capture.md
3512: new file mode 100644
3513: index 0000000..15006ff
3514: --- /dev/null
3515: +++ b/docs/cmd/capture.md
3516: @@ -0,0 +1,134 @@
3517: +# capture command
3518: +
3519: +### Description
3520: +

(Showing lines 2761-3520 of 7018. Use offset=3521 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196525b99001OPzmJUAVm9oFII",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19652532d001VBllmmBAf5BXgY",
  "callID": "call_c3f30ceff7e04804b83fbc15",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 760,
      "offset": 2761
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n2761: +// every running node, with the peer at the other end of each link. With Docker and Podman, the\n2762: +// interfaces come from the topology's links; lab runtimes list them through their packet\n2763: +// capturer.\n2764: +func (c *CLab) CaptureInterfaces(\n2765: +\tctx context.Context,\n2766: +\tnodeNames ...string,\n2767: +) ([]clablabruntime.CaptureInterface, error) {\n2768: +\tif c.LabRuntime == nil {\n2769: +\t\treturn c.localCaptureInterfacesOf(ctx, nodeNames)\n2770: +\t}\n2771: +\n2772: +\tcapturer, err := c.packetCapturer()\n2773: +\tif err != nil {\n2774: +\t\treturn nil, err\n2775: +\t}\n2776: +\n2777: +\treturn capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{\n2778: +\t\tName:     c.Config.Name,\n2779: +\t\tNodes:    nodeNames,\n2780: +\t\tIdentity: c.labRuntimeIdentity,\n2781: +\t})\n2782: +}\n2783: +\n2784: +// Capture streams pcapng from lab link interfaces to w until req.Duration passed,\n2785: +// req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name\n2786: +// and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces\n2787: +// itself through packet sockets in the nodes' network namespaces, which needs root; lab\n2788: +// runtimes capture through their packet capturer.\n2789: +func (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {\n2790: +\tif c.LabRuntime == nil {\n2791: +\t\treturn c.captureLocal(ctx, req, w)\n2792: +\t}\n2793: +\n2794: +\tcapturer, err := c.packetCapturer()\n2795: +\tif err != nil {\n2796: +\t\treturn err\n2797: +\t}\n2798: +\n2799: +\tif req.Name == \"\" {\n2800: +\t\treq.Name = c.Config.Name\n2801: +\t}\n2802: +\tif req.Identity.IsZero() {\n2803: +\t\treq.Identity = c.labRuntimeIdentity\n2804: +\t}\n2805: +\n2806: +\treturn capturer.Capture(ctx, req, w)\n2807: +}\n2808: +\n2809: +// LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their\n2810: +// state, in the shape ListContainersInterfaces reports for local containers.\n2811: +func (c *CLab) LabRuntimeInterfaces(\n2812: +\tctx context.Context,\n2813: +\tnodeName string,\n2814: +) ([]*clabtypes.ContainerInterfaces, error) {\n2815: +\tinspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](\n2816: +\t\tc, \"inspecting interfaces\")\n2817: +\tif err != nil {\n2818: +\t\treturn nil, err\n2819: +\t}\n2820: +\tif err := c.requireLabName(); err != nil {\n2821: +\t\treturn nil, err\n2822: +\t}\n2823: +\n2824: +\treq := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}\n2825: +\tif nodeName != \"\" {\n2826: +\t\treq.Nodes = []string{nodeName}\n2827: +\t}\n2828: +\n2829: +\treturn inspector.InspectInterfaces(ctx, req)\n2830: +}\n2831: +\n2832: +func (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {\n2833: +\tcapturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, \"packet capture\")\n2834: +\tif err != nil {\n2835: +\t\treturn nil, err\n2836: +\t}\n2837: +\tif err := c.requireLabName(); err != nil {\n2838: +\t\treturn nil, err\n2839: +\t}\n2840: +\n2841: +\treturn capturer, nil\n2842: +}\n2843: diff --git a/core/capture_local.go b/core/capture_local.go\n2844: new file mode 100644\n2845: index 0000000..fada0bf\n2846: --- /dev/null\n2847: +++ b/core/capture_local.go\n2848: @@ -0,0 +1,255 @@\n2849: +package core\n2850: +\n2851: +import (\n2852: +\t\"context\"\n2853: +\t\"fmt\"\n2854: +\t\"io\"\n2855: +\t\"slices\"\n2856: +\t\"sort\"\n2857: +\t\"strings\"\n2858: +\n2859: +\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n2860: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2861: +\tclablinks \"github.com/srl-labs/containerlab/links\"\n2862: +\tclabnodes \"github.com/srl-labs/containerlab/nodes\"\n2863: +\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n2864: +)\n2865: +\n2866: +// localCaptureInterface is a lab link interface of a node on this machine.\n2867: +type localCaptureInterface struct {\n2868: +\tnode clabnodes.Node\n2869: +\tinfo clablabruntime.CaptureInterface\n2870: +}\n2871: +\n2872: +// localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with\n2873: +// the far end of each link, per node name. Host and management network endpoints are the far\n2874: +// ends of links, not nodes to capture on.\n2875: +func (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {\n2876: +\tif len(c.Nodes) == 0 {\n2877: +\t\treturn nil, fmt.Errorf(\"the topology of lab %q is not available; capture reads the \"+\n2878: +\t\t\t\"lab's links from it, pass it with --topo\", c.Config.Name)\n2879: +\t}\n2880: +\tif len(c.Links) == 0 {\n2881: +\t\tif err := c.ResolveLinks(); err != nil {\n2882: +\t\t\treturn nil, fmt.Errorf(\"failed to resolve the links of lab %q: %w\", c.Config.Name, err)\n2883: +\t\t}\n2884: +\t}\n2885: +\n2886: +\tindexes := make([]int, 0, len(c.Links))\n2887: +\tfor idx := range c.Links {\n2888: +\t\tindexes = append(indexes, idx)\n2889: +\t}\n2890: +\tsort.Ints(indexes)\n2891: +\n2892: +\tresult := map[string][]localCaptureInterface{}\n2893: +\tfor _, idx := range indexes {\n2894: +\t\tendpoints := c.Links[idx].GetEndpoints()\n2895: +\t\tfor epIdx, endpoint := range endpoints {\n2896: +\t\t\tif endpoint.IsNodeless() || endpoint.IsRuntimeDiscovered() ||\n2897: +\t\t\t\tendpoint.GetNode() == nil {\n2898: +\t\t\t\tcontinue\n2899: +\t\t\t}\n2900: +\t\t\tname := endpoint.GetNode().GetShortName()\n2901: +\t\t\tnode, ok := c.Nodes[name]\n2902: +\t\t\tif !ok {\n2903: +\t\t\t\tcontinue\n2904: +\t\t\t}\n2905: +\n2906: +\t\t\tinfo := clablabruntime.CaptureInterface{\n2907: +\t\t\t\tNode:      name,\n2908: +\t\t\t\tInterface: endpoint.GetIfaceName(),\n2909: +\t\t\t}\n2910: +\t\t\tif alias := endpoint.GetIfaceAlias(); alias != info.Interface {\n2911: +\t\t\t\tinfo.Alias = alias\n2912: +\t\t\t}\n2913: +\t\t\tif len(endpoints) == 2 {\n2914: +\t\t\t\tpeer := endpoints[1-epIdx]\n2915: +\t\t\t\tinfo.PeerNode = capturePeerNode(peer)\n2916: +\t\t\t\tinfo.PeerInterface = peer.GetIfaceDisplayName()\n2917: +\t\t\t}\n2918: +\n2919: +\t\t\tresult[name] = append(result[name], localCaptureInterface{node: node, info: info})\n2920: +\t\t}\n2921: +\t}\n2922: +\n2923: +\treturn result, nil\n2924: +}\n2925: +\n2926: +// capturePeerNode names the node at the far end of a link: \"host\" for a host endpoint and\n2927: +// \"mgmt-net\" for the management network, whose shared link nodes carry other names once a lab\n2928: +// was deployed.\n2929: +func capturePeerNode(peer clablinks.Endpoint) string {\n2930: +\tif peer.IsNodeless() {\n2931: +\t\tif _, ok := peer.(*clablinks.EndpointBridge); ok {\n2932: +\t\t\treturn string(clablinks.LinkTypeMgmtNet)\n2933: +\t\t}\n2934: +\n2935: +\t\treturn string(clablinks.LinkTypeHost)\n2936: +\t}\n2937: +\tif peer.GetNode() == nil {\n2938: +\t\treturn \"\"\n2939: +\t}\n2940: +\n2941: +\treturn peer.GetNode().GetShortName()\n2942: +}\n2943: +\n2944: +// lookupLocalNode finds a lab node by its topology name or its container name.\n2945: +func (c *CLab) lookupLocalNode(name string) (clabnodes.Node, error) {\n2946: +\tif node, ok := c.Nodes[name]; ok {\n2947: +\t\treturn node, nil\n2948: +\t}\n2949: +\tfor _, node := range c.Nodes {\n2950: +\t\tif node.Config().LongName == name {\n2951: +\t\t\treturn node, nil\n2952: +\t\t}\n2953: +\t}\n2954: +\n2955: +\tnames := make([]string, 0, len(c.Nodes))\n2956: +\tfor nodeName := range c.Nodes {\n2957: +\t\tnames = append(names, nodeName)\n2958: +\t}\n2959: +\tslices.Sort(names)\n2960: +\n2961: +\treturn nil, fmt.Errorf(\"node %q is not part of lab %q; nodes: %s\", name, c.Config.Name,\n2962: +\t\tstrings.Join(names, \", \"))\n2963: +}\n2964: +\n2965: +// nodeRuns reports whether a node's network namespace can be entered.\n2966: +func nodeRuns(ctx context.Context, node clabnodes.Node) bool {\n2967: +\tif node.Config().IsRootNamespaceBased {\n2968: +\t\treturn true\n2969: +\t}\n2970: +\n2971: +\treturn clabruntime.ContainerHasJoinableNetns(node.GetContainerStatus(ctx))\n2972: +}\n2973: +\n2974: +// localCaptureInterfacesOf implements CaptureInterfaces for Docker and Podman: the requested\n2975: +// nodes, or every running node.\n2976: +func (c *CLab) localCaptureInterfacesOf(\n2977: +\tctx context.Context,\n2978: +\tnodeNames []string,\n2979: +) ([]clablabruntime.CaptureInterface, error) {\n2980: +\tif err := c.requireLabName(); err != nil {\n2981: +\t\treturn nil, err\n2982: +\t}\n2983: +\tbyNode, err := c.localCaptureInterfaces()\n2984: +\tif err != nil {\n2985: +\t\treturn nil, err\n2986: +\t}\n2987: +\n2988: +\tvar nodes []clabnodes.Node\n2989: +\tif len(nodeNames) == 0 {\n2990: +\t\tfor _, node := range c.Nodes {\n2991: +\t\t\tif nodeRuns(ctx, node) {\n2992: +\t\t\t\tnodes = append(nodes, node)\n2993: +\t\t\t}\n2994: +\t\t}\n2995: +\t} else {\n2996: +\t\tfor _, name := range nodeNames {\n2997: +\t\t\tnode, err := c.lookupLocalNode(name)\n2998: +\t\t\tif err != nil {\n2999: +\t\t\t\treturn nil, err\n3000: +\t\t\t}\n3001: +\t\t\tnodes = append(nodes, node)\n3002: +\t\t}\n3003: +\t}\n3004: +\n3005: +\tresult := make([]clablabruntime.CaptureInterface, 0)\n3006: +\tseen := map[string]bool{}\n3007: +\tfor _, node := range nodes {\n3008: +\t\tname := node.Config().ShortName\n3009: +\t\tif seen[name] {\n3010: +\t\t\tcontinue\n3011: +\t\t}\n3012: +\t\tseen[name] = true\n3013: +\t\tfor _, entry := range byNode[name] {\n3014: +\t\t\tresult = append(result, entry.info)\n3015: +\t\t}\n3016: +\t}\n3017: +\tsortCaptureInterfaces(result)\n3018: +\n3019: +\treturn result, nil\n3020: +}\n3021: +\n3022: +func sortCaptureInterfaces(interfaces []clablabruntime.CaptureInterface) {\n3023: +\tsort.SliceStable(interfaces, func(i, j int) bool {\n3024: +\t\tif interfaces[i].Node != interfaces[j].Node {\n3025: +\t\t\treturn interfaces[i].Node < interfaces[j].Node\n3026: +\t\t}\n3027: +\n3028: +\t\treturn interfaces[i].Interface < interfaces[j].Interface\n3029: +\t})\n3030: +}\n3031: +\n3032: +// resolveLocalCaptureTargets checks every target against the node's link interfaces, by name or\n3033: +// alias, and returns them in request order.\n3034: +func (c *CLab) resolveLocalCaptureTargets(\n3035: +\ttargets []clablabruntime.CaptureTarget,\n3036: +) ([]clabcapture.LocalTarget, error) {\n3037: +\tbyNode, err := c.localCaptureInterfaces()\n3038: +\tif err != nil {\n3039: +\t\treturn nil, err\n3040: +\t}\n3041: +\n3042: +\tresolved := make([]clabcapture.LocalTarget, 0, len(targets))\n3043: +\tseen := map[string]bool{}\n3044: +\tfor _, target := range targets {\n3045: +\t\tnode, err := c.lookupLocalNode(target.Node)\n3046: +\t\tif err != nil {\n3047: +\t\t\treturn nil, err\n3048: +\t\t}\n3049: +\t\tname := node.Config().ShortName\n3050: +\n3051: +\t\tinfos := make([]clablabruntime.CaptureInterface, 0, len(byNode[name]))\n3052: +\t\tfor _, entry := range byNode[name] {\n3053: +\t\t\tinfos = append(infos, entry.info)\n3054: +\t\t}\n3055: +\t\tsortCaptureInterfaces(infos)\n3056: +\t\tinfo, ok := clabcapture.FindInterface(infos, target.Interface)\n3057: +\t\tif !ok {\n3058: +\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n3059: +\t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n3060: +\t\t\t\tclabcapture.DescribeInterfaces(infos))\n3061: +\t\t}\n3062: +\n3063: +\t\tkey := name + \"\\x00\" + info.Interface\n3064: +\t\tif seen[key] {\n3065: +\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n3066: +\t\t\t\tinfo.Interface, target.Node)\n3067: +\t\t}\n3068: +\t\tseen[key] = true\n3069: +\n3070: +\t\tresolved = append(resolved, clabcapture.LocalTarget{\n3071: +\t\t\tNode:      name,\n3072: +\t\t\tInterface: info.Interface,\n3073: +\t\t\tExec:      node.ExecFunction,\n3074: +\t\t})\n3075: +\t}\n3076: +\n3077: +\treturn resolved, nil\n3078: +}\n3079: +\n3080: +// captureLocal implements Capture for Docker and Podman through packet sockets in the nodes'\n3081: +// network namespaces.\n3082: +func (c *CLab) captureLocal(\n3083: +\tctx context.Context,\n3084: +\treq clablabruntime.CaptureRequest,\n3085: +\tw io.Writer,\n3086: +) error {\n3087: +\tif err := c.requireLabName(); err != nil {\n3088: +\t\treturn err\n3089: +\t}\n3090: +\tif req.Name == \"\" {\n3091: +\t\treq.Name = c.Config.Name\n3092: +\t}\n3093: +\tif err := clabcapture.ValidateRequest(&req); err != nil {\n3094: +\t\treturn err\n3095: +\t}\n3096: +\n3097: +\ttargets, err := c.resolveLocalCaptureTargets(req.Targets)\n3098: +\tif err != nil {\n3099: +\t\treturn err\n3100: +\t}\n3101: +\n3102: +\treturn clabcapture.CaptureLocal(ctx, req, targets, w)\n3103: +}\n3104: diff --git a/core/capture_test.go b/core/capture_test.go\n3105: new file mode 100644\n3106: index 0000000..b5d34b0\n3107: --- /dev/null\n3108: +++ b/core/capture_test.go\n3109: @@ -0,0 +1,210 @@\n3110: +package core\n3111: +\n3112: +import (\n3113: +\t\"bytes\"\n3114: +\t\"context\"\n3115: +\t\"io\"\n3116: +\t\"slices\"\n3117: +\t\"strings\"\n3118: +\t\"testing\"\n3119: +\n3120: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n3121: +\tclabtypes \"github.com/srl-labs/containerlab/types\"\n3122: +)\n3123: +\n3124: +// captureLabRuntime records the capture requests core sends.\n3125: +type captureLabRuntime struct {\n3126: +\tclablabruntime.LabRuntime\n3127: +\n3128: +\tnodeRequest    clablabruntime.NodeRequest\n3129: +\tcaptureRequest clablabruntime.CaptureRequest\n3130: +}\n3131: +\n3132: +func (r *captureLabRuntime) CaptureInterfaces(\n3133: +\t_ context.Context,\n3134: +\treq clablabruntime.NodeRequest,\n3135: +) ([]clablabruntime.CaptureInterface, error) {\n3136: +\tr.nodeRequest = req\n3137: +\n3138: +\treturn []clablabruntime.CaptureInterface{{Node: \"r1\", Interface: \"eth1\"}}, nil\n3139: +}\n3140: +\n3141: +func (r *captureLabRuntime) Capture(\n3142: +\t_ context.Context,\n3143: +\treq clablabruntime.CaptureRequest,\n3144: +\tw io.Writer,\n3145: +) error {\n3146: +\tr.captureRequest = req\n3147: +\t_, err := io.WriteString(w, \"pcapng\")\n3148: +\n3149: +\treturn err\n3150: +}\n3151: +\n3152: +func (r *captureLabRuntime) InspectInterfaces(\n3153: +\t_ context.Context,\n3154: +\treq clablabruntime.NodeRequest,\n3155: +) ([]*clabtypes.ContainerInterfaces, error) {\n3156: +\tr.nodeRequest = req\n3157: +\n3158: +\treturn []*clabtypes.ContainerInterfaces{{ContainerName: \"lab1-r1\"}}, nil\n3159: +}\n3160: +\n3161: +func TestCaptureHelpersFillLabAndIdentity(t *testing.T) {\n3162: +\tt.Parallel()\n3163: +\n3164: +\tlr := &captureLabRuntime{}\n3165: +\tc := newAccessTestCLab(lr)\n3166: +\tctx := context.Background()\n3167: +\n3168: +\tinterfaces, err := c.CaptureInterfaces(ctx, \"R1\")\n3169: +\tif err != nil || len(interfaces) != 1 {\n3170: +\t\tt.Fatalf(\"CaptureInterfaces() = %+v, %v\", interfaces, err)\n3171: +\t}\n3172: +\tif lr.nodeRequest.Name != \"lab1\" || lr.nodeRequest.Nodes[0] != \"R1\" ||\n3173: +\t\t!lr.nodeRequest.Identity.Equal(testIdentity) {\n3174: +\t\tt.Fatalf(\"interfaces request = %+v\", lr.nodeRequest)\n3175: +\t}\n3176: +\n3177: +\tvar out bytes.Buffer\n3178: +\tif err := c.Capture(ctx, clablabruntime.CaptureRequest{\n3179: +\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n3180: +\t}, &out); err != nil {\n3181: +\t\tt.Fatal(err)\n3182: +\t}\n3183: +\tif out.String() != \"pcapng\" || lr.captureRequest.Name != \"lab1\" ||\n3184: +\t\t!lr.captureRequest.Identity.Equal(testIdentity) {\n3185: +\t\tt.Fatalf(\"capture request = %+v, output %q\", lr.captureRequest, out.String())\n3186: +\t}\n3187: +\n3188: +\tifaces, err := c.LabRuntimeInterfaces(ctx, \"r1\")\n3189: +\tif err != nil || len(ifaces) != 1 || lr.nodeRequest.Nodes[0] != \"r1\" {\n3190: +\t\tt.Fatalf(\"LabRuntimeInterfaces() = %+v, %v, request %+v\", ifaces, err, lr.nodeRequest)\n3191: +\t}\n3192: +\tif _, err := c.LabRuntimeInterfaces(ctx, \"\"); err != nil || lr.nodeRequest.Nodes != nil {\n3193: +\t\tt.Fatalf(\"all nodes request = %+v, %v\", lr.nodeRequest, err)\n3194: +\t}\n3195: +}\n3196: +\n3197: +// newLocalCaptureCLab loads the capture test topology. Its host and mgmt-net links register\n3198: +// endpoints on link nodes the whole process shares, so the tests using it do not run in\n3199: +// parallel and release the endpoints when they end.\n3200: +func newLocalCaptureCLab(t *testing.T) *CLab {\n3201: +\tt.Helper()\n3202: +\n3203: +\tc, err := NewContainerLab(WithTopoPath(\"test_data/capture.clab.yml\", nil))\n3204: +\tif err != nil {\n3205: +\t\tt.Fatal(err)\n3206: +\t}\n3207: +\tt.Cleanup(c.resetResolvedLinks)\n3208: +\n3209: +\treturn c\n3210: +}\n3211: +\n3212: +func TestLocalCaptureInterfacesComeFromTheTopologyLinks(t *testing.T) {\n3213: +\tc := newLocalCaptureCLab(t)\n3214: +\n3215: +\tgot, err := c.CaptureInterfaces(context.Background(), \"srl1\", \"client\")\n3216: +\tif err != nil {\n3217: +\t\tt.Fatal(err)\n3218: +\t}\n3219: +\twant := []clablabruntime.CaptureInterface{\n3220: +\t\t{Node: \"client\", Interface: \"eth1\", PeerNode: \"srl1\", PeerInterface: \"e1-2\"},\n3221: +\t\t{Node: \"client\", Interface: \"eth2\", PeerNode: \"host\", PeerInterface: \"client-eth2\"},\n3222: +\t\t{Node: \"client\", Interface: \"eth3\", PeerNode: \"mgmt-net\", PeerInterface: \"client-eth3\"},\n3223: +\t\t{\n3224: +\t\t\tNode: \"srl1\", Interface: \"e1-1\", Alias: \"ethernet-1/1\",\n3225: +\t\t\tPeerNode: \"srl2\", PeerInterface: \"e1-1\",\n3226: +\t\t},\n3227: +\t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"client\", PeerInterface: \"eth1\"},\n3228: +\t}\n3229: +\tif !slices.Equal(got, want) {\n3230: +\t\tt.Fatalf(\"CaptureInterfaces() =\\n%+v\\nwant\\n%+v\", got, want)\n3231: +\t}\n3232: +\n3233: +\tif _, err := c.CaptureInterfaces(context.Background(), \"r9\"); err == nil ||\n3234: +\t\t!strings.Contains(err.Error(), `node \"r9\" is not part of lab \"capture\"`) {\n3235: +\t\tt.Fatalf(\"unknown node: error = %v\", err)\n3236: +\t}\n3237: +}\n3238: +\n3239: +func TestLocalCaptureTargetsResolveByNameOrAlias(t *testing.T) {\n3240: +\tc := newLocalCaptureCLab(t)\n3241: +\n3242: +\ttargets, err := c.resolveLocalCaptureTargets([]clablabruntime.CaptureTarget{\n3243: +\t\t{Node: \"srl2\", Interface: \"e1-1\"},\n3244: +\t\t{Node: \"srl1\", Interface: \"ethernet-1/1\"},\n3245: +\t\t{Node: \"clab-capture-client\", Interface: \"eth2\"},\n3246: +\t})\n3247: +\tif err != nil {\n3248: +\t\tt.Fatal(err)\n3249: +\t}\n3250: +\tvar got []string\n3251: +\tfor _, target := range targets {\n3252: +\t\tif target.Exec == nil {\n3253: +\t\t\tt.Fatalf(\"target %s:%s has no namespace exec\", target.Node, target.Interface)\n3254: +\t\t}\n3255: +\t\tgot = append(got, target.Node+\":\"+target.Interface)\n3256: +\t}\n3257: +\tif want := []string{\"srl2:e1-1\", \"srl1:e1-1\", \"client:eth2\"}; !slices.Equal(got, want) {\n3258: +\t\tt.Fatalf(\"targets = %v, want %v\", got, want)\n3259: +\t}\n3260: +\n3261: +\tfor _, tc := range []struct {\n3262: +\t\tname    string\n3263: +\t\ttargets []clablabruntime.CaptureTarget\n3264: +\t\twant    string\n3265: +\t}{\n3266: +\t\t{\n3267: +\t\t\tname:    \"management interface\",\n3268: +\t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"client\", Interface: \"eth0\"}},\n3269: +\t\t\twant: `interface \"eth0\" of node \"client\" is not a capturable link interface; ` +\n3270: +\t\t\t\t\"capturable: eth1, eth2, eth3\",\n3271: +\t\t},\n3272: +\t\t{\n3273: +\t\t\tname: \"same interface twice\",\n3274: +\t\t\ttargets: []clablabruntime.CaptureTarget{\n3275: +\t\t\t\t{Node: \"srl1\", Interface: \"e1-1\"}, {Node: \"srl1\", Interface: \"ethernet-1/1\"},\n3276: +\t\t\t},\n3277: +\t\t\twant: `interface \"e1-1\" of node \"srl1\" is requested more than once`,\n3278: +\t\t},\n3279: +\t\t{\n3280: +\t\t\tname:    \"unknown node\",\n3281: +\t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"r9\", Interface: \"eth1\"}},\n3282: +\t\t\twant:    `node \"r9\" is not part of lab \"capture\"`,\n3283: +\t\t},\n3284: +\t} {\n3285: +\t\tif _, err := c.resolveLocalCaptureTargets(tc.targets); err == nil ||\n3286: +\t\t\t!strings.Contains(err.Error(), tc.want) {\n3287: +\t\t\tt.Errorf(\"%s: error = %v, want %q\", tc.name, err, tc.want)\n3288: +\t\t}\n3289: +\t}\n3290: +}\n3291: +\n3292: +func TestLocalCaptureNeedsTheTopology(t *testing.T) {\n3293: +\tt.Parallel()\n3294: +\n3295: +\tc := &CLab{Config: &Config{Name: \"lab1\"}, globalRuntimeName: \"docker\"}\n3296: +\terr := c.Capture(context.Background(), clablabruntime.CaptureRequest{\n3297: +\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n3298: +\t}, io.Discard)\n3299: +\tif err == nil || !strings.Contains(err.Error(), `the topology of lab \"lab1\" is not available`) {\n3300: +\t\tt.Fatalf(\"error = %v\", err)\n3301: +\t}\n3302: +\tif err := c.Capture(context.Background(), clablabruntime.CaptureRequest{},\n3303: +\t\tio.Discard); err == nil || !strings.Contains(err.Error(), \"at least one capture target\") {\n3304: +\t\tt.Fatalf(\"no targets: error = %v\", err)\n3305: +\t}\n3306: +}\n3307: +\n3308: +func TestLabRuntimeWithoutCaptureFails(t *testing.T) {\n3309: +\tt.Parallel()\n3310: +\n3311: +\tunsupported := newAccessTestCLab(&recordingDestroyLabRuntime{})\n3312: +\tif err := unsupported.Capture(\n3313: +\t\tcontext.Background(),\n3314: +\t\tclablabruntime.CaptureRequest{},\n3315: +\t\tio.Discard,\n3316: +\t); err == nil || !strings.Contains(err.Error(), \"does not support packet capture\") {\n3317: +\t\tt.Fatalf(\"lab runtime without capture: error = %v\", err)\n3318: +\t}\n3319: +}\n3320: diff --git a/core/labruntime_cluster_test.go b/core/labruntime_cluster_test.go\n3321: index 06ecf57..981a302 100644\n3322: --- a/core/labruntime_cluster_test.go\n3323: +++ b/core/labruntime_cluster_test.go\n3324: @@ -1,10 +1,11 @@\n3325:  package core\n3326:  \n3327:  import (\n3328:  \t\"bytes\"\n3329:  \t\"context\"\n3330: +\t\"encoding/binary\"\n3331:  \t\"errors\"\n3332:  \t\"io\"\n3333:  \t\"net\"\n3334:  \t\"net/http\"\n3335:  \t\"os\"\n3336: @@ -175,5 +176,153 @@ func TestC9sClusterNodeAccess(t *testing.T) {\n3337:  \t\tif err == nil || !strings.Contains(err.Error(), \"forbidden\") {\n3338:  \t\t\tt.Fatalf(\"impersonated user without rights: error = %v, want forbidden\", err)\n3339:  \t\t}\n3340:  \t})\n3341:  }\n3342: +\n3343: +// TestC9sClusterCapture captures through the library against a deployed c9s lab, as an identity\n3344: +// that holds only the clabernetes-lab-editor role in the lab namespace. It runs only when\n3345: +// CLAB_C9S_TEST_LAB names the lab and CLAB_C9S_TEST_CAPTURE_USER the identity (tests/14-clabernetes\n3346: +// sets both). The lab must have linux nodes \"client\" (10.10.10.1) and \"server\" (10.10.10.2)\n3347: +// linked by eth1. CLAB_C9S_TEST_FORBIDDEN_USER names an identity without a binding.\n3348: +func TestC9sClusterCapture(t *testing.T) {\n3349: +\tlab := os.Getenv(\"CLAB_C9S_TEST_LAB\")\n3350: +\tuser := os.Getenv(\"CLAB_C9S_TEST_CAPTURE_USER\")\n3351: +\tif lab == \"\" || user == \"\" {\n3352: +\t\tt.Skip(\"CLAB_C9S_TEST_LAB or CLAB_C9S_TEST_CAPTURE_USER is not set\")\n3353: +\t}\n3354: +\n3355: +\tnewCLab := func(t *testing.T, user string) *CLab {\n3356: +\t\tt.Helper()\n3357: +\n3358: +\t\tc, err := NewContainerLab(\n3359: +\t\t\tWithRuntime(clablabruntime.ClabernetesRuntimeName, nil),\n3360: +\t\t\tWithTopologyName(lab),\n3361: +\t\t\tWithLabRuntimeIdentity(clablabruntime.Identity{User: user}),\n3362: +\t\t)\n3363: +\t\tif err != nil {\n3364: +\t\t\tt.Fatal(err)\n3365: +\t\t}\n3366: +\n3367: +\t\treturn c\n3368: +\t}\n3369: +\tc := newCLab(t, user)\n3370: +\n3371: +\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)\n3372: +\tdefer cancel()\n3373: +\n3374: +\tt.Run(\"version check\", func(t *testing.T) {\n3375: +\t\tif err := c.CheckLabRuntimeSupport(ctx); err != nil {\n3376: +\t\t\tt.Fatal(err)\n3377: +\t\t}\n3378: +\t})\n3379: +\n3380: +\tt.Run(\"capture interfaces\", func(t *testing.T) {\n3381: +\t\tinterfaces, err := c.CaptureInterfaces(ctx)\n3382: +\t\tif err != nil {\n3383: +\t\t\tt.Fatal(err)\n3384: +\t\t}\n3385: +\t\twant := []clablabruntime.CaptureInterface{\n3386: +\t\t\t{Node: \"client\", Interface: \"eth1\", PeerNode: \"server\", PeerInterface: \"eth1\"},\n3387: +\t\t\t{Node: \"server\", Interface: \"eth1\", PeerNode: \"client\", PeerInterface: \"eth1\"},\n3388: +\t\t}\n3389: +\t\tif len(interfaces) != 2 || interfaces[0] != want[0] || interfaces[1] != want[1] {\n3390: +\t\t\tt.Fatalf(\"interfaces = %+v\", interfaces)\n3391: +\t\t}\n3392: +\t})\n3393: +\n3394: +\tt.Run(\"capture both ends of a link\", func(t *testing.T) {\n3395: +\t\tpinged := make(chan error, 1)\n3396: +\t\tgo func() {\n3397: +\t\t\ttime.Sleep(time.Second)\n3398: +\t\t\tpinged <- c.AttachLabRuntimeNode(ctx, clablabruntime.AttachRequest{\n3399: +\t\t\t\tNodeName: \"client\",\n3400: +\t\t\t\tCommand:  []string{\"ping\", \"-c\", \"4\", \"-i\", \"0.3\", \"10.10.10.2\"},\n3401: +\t\t\t}, clablabruntime.AttachStreams{Stdout: io.Discard})\n3402: +\t\t}()\n3403: +\n3404: +\t\tvar out bytes.Buffer\n3405: +\t\terr := c.Capture(ctx, clablabruntime.CaptureRequest{\n3406: +\t\t\tTargets: []clablabruntime.CaptureTarget{\n3407: +\t\t\t\t{Node: \"client\", Interface: \"eth1\"}, {Node: \"server\", Interface: \"eth1\"},\n3408: +\t\t\t},\n3409: +\t\t\tDuration: 5 * time.Second,\n3410: +\t\t}, &out)\n3411: +\t\tif err != nil {\n3412: +\t\t\tt.Fatal(err)\n3413: +\t\t}\n3414: +\t\tif err := <-pinged; err != nil {\n3415: +\t\t\tt.Fatalf(\"ping: %v\", err)\n3416: +\t\t}\n3417: +\n3418: +\t\tnames, icmp := summarizePCAPNG(t, out.Bytes())\n3419: +\t\tif len(names) != 2 || names[0] != \"client:eth1\" || names[1] != \"server:eth1\" {\n3420: +\t\t\tt.Fatalf(\"interfaces = %v\", names)\n3421: +\t\t}\n3422: +\t\t// every echo request and reply crosses both ends\n3423: +\t\tif icmp[0] < 8 || icmp[1] < 8 {\n3424: +\t\t\tt.Fatalf(\"ICMP packets per interface = %v, want at least 8 on each\", icmp)\n3425: +\t\t}\n3426: +\t})\n3427: +\n3428: +\tt.Run(\"restart as lab editor\", func(t *testing.T) {\n3429: +\t\tif err := c.RestartNodes(ctx, []string{\"server\"}); err != nil {\n3430: +\t\t\tt.Fatal(err)\n3431: +\t\t}\n3432: +\t})\n3433: +\n3434: +\tt.Run(\"forbidden identity\", func(t *testing.T) {\n3435: +\t\tforbidden := os.Getenv(\"CLAB_C9S_TEST_FORBIDDEN_USER\")\n3436: +\t\tif forbidden == \"\" {\n3437: +\t\t\tt.Skip(\"CLAB_C9S_TEST_FORBIDDEN_USER is not set\")\n3438: +\t\t}\n3439: +\n3440: +\t\terr := newCLab(t, forbidden).Capture(ctx, clablabruntime.CaptureRequest{\n3441: +\t\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"client\", Interface: \"eth1\"}},\n3442: +\t\t\tDuration: time.Second,\n3443: +\t\t}, io.Discard)\n3444: +\t\tif err == nil || !strings.Contains(err.Error(), \"forbidden\") {\n3445: +\t\t\tt.Fatalf(\"capture as %s = %v, want forbidden\", forbidden, err)\n3446: +\t\t}\n3447: +\t})\n3448: +}\n3449: +\n3450: +// summarizePCAPNG returns the interface names of a little-endian pcapng stream and its IPv4 ICMP\n3451: +// packets per interface ID.\n3452: +func summarizePCAPNG(t *testing.T, data []byte) ([]string, map[uint32]int) {\n3453: +\tt.Helper()\n3454: +\n3455: +\tvar names []string\n3456: +\ticmp := map[uint32]int{}\n3457: +\tfor len(data) >= 12 {\n3458: +\t\tblockType := binary.LittleEndian.Uint32(data[0:4])\n3459: +\t\tlength := int(binary.LittleEndian.Uint32(data[4:8]))\n3460: +\t\tif length < 12 || length > len(data) {\n3461: +\t\t\tt.Fatalf(\"invalid block length %d\", length)\n3462: +\t\t}\n3463: +\t\tbody := data[8 : length-4]\n3464: +\t\tswitch blockType {\n3465: +\t\tcase 1: // Interface Description Block\n3466: +\t\t\toptions := body[8:]\n3467: +\t\t\tfor len(options) >= 4 {\n3468: +\t\t\t\tcode := binary.LittleEndian.Uint16(options[0:2])\n3469: +\t\t\t\tsize := int(binary.LittleEndian.Uint16(options[2:4]))\n3470: +\t\t\t\tif code == 0 {\n3471: +\t\t\t\t\tbreak\n3472: +\t\t\t\t}\n3473: +\t\t\t\tif code == 2 {\n3474: +\t\t\t\t\tnames = append(names, string(options[4:4+size]))\n3475: +\t\t\t\t}\n3476: +\t\t\t\toptions = options[4+size+(4-size%4)%4:]\n3477: +\t\t\t}\n3478: +\t\tcase 6: // Enhanced Packet Block\n3479: +\t\t\tid := binary.LittleEndian.Uint32(body[0:4])\n3480: +\t\t\tframe := body[20 : 20+binary.LittleEndian.Uint32(body[12:16])]\n3481: +\t\t\tif len(frame) > 23 && frame[12] == 0x08 && frame[13] == 0x00 && frame[23] == 1 {\n3482: +\t\t\t\ticmp[id]++\n3483: +\t\t\t}\n3484: +\t\t}\n3485: +\t\tdata = data[length:]\n3486: +\t}\n3487: +\n3488: +\treturn names, icmp\n3489: +}\n3490: diff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml\n3491: new file mode 100644\n3492: index 0000000..0422c22\n3493: --- /dev/null\n3494: +++ b/core/test_data/capture.clab.yml\n3495: @@ -0,0 +1,15 @@\n3496: +name: capture\n3497: +topology:\n3498: +  nodes:\n3499: +    srl1:\n3500: +      kind: nokia_srlinux\n3501: +    srl2:\n3502: +      kind: nokia_srlinux\n3503: +    client:\n3504: +      kind: linux\n3505: +      image: alpine:3\n3506: +  links:\n3507: +    - endpoints: [\"srl1:ethernet-1/1\", \"srl2:e1-1\"]\n3508: +    - endpoints: [\"srl1:e1-2\", \"client:eth1\"]\n3509: +    - endpoints: [\"client:eth2\", \"host:client-eth2\"]\n3510: +    - endpoints: [\"client:eth3\", \"mgmt-net:client-eth3\"]\n3511: diff --git a/docs/cmd/capture.md b/docs/cmd/capture.md\n3512: new file mode 100644\n3513: index 0000000..15006ff\n3514: --- /dev/null\n3515: +++ b/docs/cmd/capture.md\n3516: @@ -0,0 +1,134 @@\n3517: +# capture command\n3518: +\n3519: +### Description\n3520: +\n\n(Showing lines 2761-3520 of 7018. Use offset=3521 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+// every running node, with the peer at the other end of each link. With Docker and Podman, the\n+// interfaces come from the topology's links; lab runtimes list them through their packet\n+// capturer.\n+func (c *CLab) CaptureInterfaces(\n+\tctx context.Context,\n+\tnodeNames ...string,\n+) ([]clablabruntime.CaptureInterface, error) {\n+\tif c.LabRuntime == nil {\n+\t\treturn c.localCaptureInterfacesOf(ctx, nodeNames)\n+\t}\n+\n+\tcapturer, err := c.packetCapturer()\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treturn capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{\n+\t\tName:     c.Config.Name,\n+\t\tNodes:    nodeNames,\n+\t\tIdentity: c.labRuntimeIdentity,",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+// every running node, with the peer at the other end of each link. With Docker and Podman, the\n+// interfaces come from the topology's links; lab runtimes list them through their packet\n+// capturer.\n+func (c *CLab) CaptureInterfaces(\n+\tctx context.Context,\n+\tnodeNames ...string,\n+) ([]clablabruntime.CaptureInterface, error) {\n+\tif c.LabRuntime == nil {\n+\t\treturn c.localCaptureInterfacesOf(ctx, nodeNames)\n+\t}\n+\n+\tcapturer, err := c.packetCapturer()\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treturn capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{\n+\t\tName:     c.Config.Name,\n+\t\tNodes:    nodeNames,\n+\t\tIdentity: c.labRuntimeIdentity,\n+\t})\n+}\n+\n+// Capture streams pcapng from lab link interfaces to w until req.Duration passed,\n+// req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name\n+// and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces\n+// itself through packet sockets in the nodes' network namespaces, which needs root; lab\n+// runtimes capture through their packet capturer.\n+func (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {\n+\tif c.LabRuntime == nil {\n+\t\treturn c.captureLocal(ctx, req, w)\n+\t}\n+\n+\tcapturer, err := c.packetCapturer()\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tif req.Name == \"\" {\n+\t\treq.Name = c.Config.Name\n+\t}\n+\tif req.Identity.IsZero() {\n+\t\treq.Identity = c.labRuntimeIdentity\n+\t}\n+\n+\treturn capturer.Capture(ctx, req, w)\n+}\n+\n+// LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their\n+// state, in the shape ListContainersInterfaces reports for local containers.\n+func (c *CLab) LabRuntimeInterfaces(\n+\tctx context.Context,\n+\tnodeName string,\n+) ([]*clabtypes.ContainerInterfaces, error) {\n+\tinspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](\n+\t\tc, \"inspecting interfaces\")\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tif err := c.requireLabName(); err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treq := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}\n+\tif nodeName != \"\" {\n+\t\treq.Nodes = []string{nodeName}\n+\t}\n+\n+\treturn inspector.InspectInterfaces(ctx, req)\n+}\n+\n+func (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {\n+\tcapturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, \"packet capture\")\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tif err := c.requireLabName(); err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treturn capturer, nil\n+}\ndiff --git a/core/capture_local.go b/core/capture_local.go\nnew file mode 100644\nindex 0000000..fada0bf\n--- /dev/null\n+++ b/core/capture_local.go\n@@ -0,0 +1,255 @@\n+package core\n+\n+import (\n+\t\"context\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"slices\"\n+\t\"sort\"\n+\t\"strings\"\n+\n+\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tclablinks \"github.com/srl-labs/containerlab/links\"\n+\tclabnodes \"github.com/srl-labs/containerlab/nodes\"\n+\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n+)\n+\n+// localCaptureInterface is a lab link interface of a node on this machine.\n+type localCaptureInterface struct {\n+\tnode clabnodes.Node\n+\tinfo clablabruntime.CaptureInterface\n+}\n+\n+// localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with\n+// the far end of each link, per node name. Host and management network endpoints are the far\n+// ends of links, not nodes to capture on.\n+func (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {\n+\tif len(c.Nodes) == 0 {\n+\t\treturn nil, fmt.Errorf(\"the topology of lab %q is not available; capture reads the \"+\n+\t\t\t\"lab's links from it, pass it with --topo\", c.Config.Name)\n+\t}\n+\tif len(c.Links) == 0 {\n+\t\tif err := c.ResolveLinks(); err != nil {\n+\t\t\treturn nil, fmt.Errorf(\"failed to resolve the links of lab %q: %w\", c.Config.Name, err)\n+\t\t}\n+\t}\n+\n+\tindexes := make([]int, 0, len(c.Links))\n+\tfor idx := range c.Links {\n+\t\tindexes = append(indexes, idx)\n+\t}\n+\tsort.Ints(indexes)\n+\n+\tresult := map[string][]localCaptureInterface{}\n+\tfor _, idx := range indexes {\n+\t\tendpoints := c.Links[idx].GetEndpoints()\n+\t\tfor epIdx, endpoint := range endpoints {\n+\t\t\tif endpoint.IsNodeless() || endpoint.IsRuntimeDiscovered() ||\n+\t\t\t\tendpoint.GetNode() == nil {\n+\t\t\t\tcontinue\n+\t\t\t}\n+\t\t\tname := endpoint.GetNode().GetShortName()\n+\t\t\tnode, ok := c.Nodes[name]\n+\t\t\tif !ok {\n+\t\t\t\tcontinue\n+\t\t\t}\n+\n+\t\t\tinfo := clablabruntime.CaptureInterface{\n+\t\t\t\tNode:      name,\n+\t\t\t\tInterface: endpoint.GetIfaceName(),\n+\t\t\t}\n+\t\t\tif alias := endpoint.GetIfaceAlias(); alias != info.Interface {\n+\t\t\t\tinfo.Alias = alias\n+\t\t\t}\n+\t\t\tif len(endpoints) == 2 {\n+\t\t\t\tpeer := endpoints[1-epIdx]\n+\t\t\t\tinfo.PeerNode = capturePeerNode(peer)\n+\t\t\t\tinfo.PeerInterface = peer.GetIfaceDisplayName()\n+\t\t\t}\n+\n+\t\t\tresult[name] = append(result[name], localCaptureInterface{node: node, info: info})\n+\t\t}\n+\t}\n+\n+\treturn result, nil\n+}\n+\n+// capturePeerNode names the node at the far end of a link: \"host\" for a host endpoint and\n+// \"mgmt-net\" for the management network, whose shared link nodes carry other names once a lab\n+// was deployed.\n+func capturePeerNode(peer clablinks.Endpoint) string {\n+\tif peer.IsNodeless() {\n+\t\tif _, ok := peer.(*clablinks.EndpointBridge); ok {\n+\t\t\treturn string(clablinks.LinkTypeMgmtNet)\n+\t\t}\n+\n+\t\treturn string(clablinks.LinkTypeHost)\n+\t}\n+\tif peer.GetNode() == nil {\n+\t\treturn \"\"\n+\t}\n+\n+\treturn peer.GetNode().GetShortName()\n+}\n+\n+// lookupLocalNode finds a lab node by its topology name or its container name.\n+func (c *CLab) lookupLocalNode(name string) (clabnodes.Node, error) {\n+\tif node, ok := c.Nodes[name]; ok {\n+\t\treturn node, nil\n+\t}\n+\tfor _, node := range c.Nodes {\n+\t\tif node.Config().LongName == name {\n+\t\t\treturn node, nil\n+\t\t}\n+\t}\n+\n+\tnames := make([]string, 0, len(c.Nodes))\n+\tfor nodeName := range c.Nodes {\n+\t\tnames = append(names, nodeName)\n+\t}\n+\tslices.Sort(names)\n+\n+\treturn nil, fmt.Errorf(\"node %q is not part of lab %q; nodes: %s\", name, c.Config.Name,\n+\t\tstrings.Join(names, \", \"))\n+}\n+\n+// nodeRuns reports whether a node's network namespace can be entered.\n+func nodeRuns(ctx context.Context, node clabnodes.Node) bool {\n+\tif node.Config().IsRootNamespaceBased {\n+\t\treturn true\n+\t}\n+\n+\treturn clabruntime.ContainerHasJoinableNetns(node.GetContainerStatus(ctx))\n+}\n+\n+// localCaptureInterfacesOf implements CaptureInterfaces for Docker and Podman: the requested\n+// nodes, or every running node.\n+func (c *CLab) localCaptureInterfacesOf(\n+\tctx context.Context,\n+\tnodeNames []string,\n+) ([]clablabruntime.CaptureInterface, error) {\n+\tif err := c.requireLabName(); err != nil {\n+\t\treturn nil, err\n+\t}\n+\tbyNode, err := c.localCaptureInterfaces()\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\tvar nodes []clabnodes.Node\n+\tif len(nodeNames) == 0 {\n+\t\tfor _, node := range c.Nodes {\n+\t\t\tif nodeRuns(ctx, node) {\n+\t\t\t\tnodes = append(nodes, node)\n+\t\t\t}\n+\t\t}\n+\t} else {\n+\t\tfor _, name := range nodeNames {\n+\t\t\tnode, err := c.lookupLocalNode(name)\n+\t\t\tif err != nil {\n+\t\t\t\treturn nil, err\n+\t\t\t}\n+\t\t\tnodes = append(nodes, node)\n+\t\t}\n+\t}\n+\n+\tresult := make([]clablabruntime.CaptureInterface, 0)\n+\tseen := map[string]bool{}\n+\tfor _, node := range nodes {\n+\t\tname := node.Config().ShortName\n+\t\tif seen[name] {\n+\t\t\tcontinue\n+\t\t}\n+\t\tseen[name] = true\n+\t\tfor _, entry := range byNode[name] {\n+\t\t\tresult = append(result, entry.info)\n+\t\t}\n+\t}\n+\tsortCaptureInterfaces(result)\n+\n+\treturn result, nil\n+}\n+\n+func sortCaptureInterfaces(interfaces []clablabruntime.CaptureInterface) {\n+\tsort.SliceStable(interfaces, func(i, j int) bool {\n+\t\tif interfaces[i].Node != interfaces[j].Node {\n+\t\t\treturn interfaces[i].Node < interfaces[j].Node\n+\t\t}\n+\n+\t\treturn interfaces[i].Interface < interfaces[j].Interface\n+\t})\n+}\n+\n+// resolveLocalCaptureTargets checks every target against the node's link interfaces, by name or\n+// alias, and returns them in request order.\n+func (c *CLab) resolveLocalCaptureTargets(\n+\ttargets []clablabruntime.CaptureTarget,\n+) ([]clabcapture.LocalTarget, error) {\n+\tbyNode, err := c.localCaptureInterfaces()\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\tresolved := make([]clabcapture.LocalTarget, 0, len(targets))\n+\tseen := map[string]bool{}\n+\tfor _, target := range targets {\n+\t\tnode, err := c.lookupLocalNode(target.Node)\n+\t\tif err != nil {\n+\t\t\treturn nil, err\n+\t\t}\n+\t\tname := node.Config().ShortName\n+\n+\t\tinfos := make([]clablabruntime.CaptureInterface, 0, len(byNode[name]))\n+\t\tfor _, entry := range byNode[name] {\n+\t\t\tinfos = append(infos, entry.info)\n+\t\t}\n+\t\tsortCaptureInterfaces(infos)\n+\t\tinfo, ok := clabcapture.FindInterface(infos, target.Interface)\n+\t\tif !ok {\n+\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n+\t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n+\t\t\t\tclabcapture.DescribeInterfaces(infos))\n+\t\t}\n+\n+\t\tkey := name + \"\\x00\" + info.Interface\n+\t\tif seen[key] {\n+\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n+\t\t\t\tinfo.Interface, target.Node)\n+\t\t}\n+\t\tseen[key] = true\n+\n+\t\tresolved = append(resolved, clabcapture.LocalTarget{\n+\t\t\tNode:      name,\n+\t\t\tInterface: info.Interface,\n+\t\t\tExec:      node.ExecFunction,\n+\t\t})\n+\t}\n+\n+\treturn resolved, nil\n+}\n+\n+// captureLocal implements Capture for Docker and Podman through packet sockets in the nodes'\n+// network namespaces.\n+func (c *CLab) captureLocal(\n+\tctx context.Context,\n+\treq clablabruntime.CaptureRequest,\n+\tw io.Writer,\n+) error {\n+\tif err := c.requireLabName(); err != nil {\n+\t\treturn err\n+\t}\n+\tif req.Name == \"\" {\n+\t\treq.Name = c.Config.Name\n+\t}\n+\tif err := clabcapture.ValidateRequest(&req); err != nil {\n+\t\treturn err\n+\t}\n+\n+\ttargets, err := c.resolveLocalCaptureTargets(req.Targets)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\treturn clabcapture.CaptureLocal(ctx, req, targets, w)\n+}\ndiff --git a/core/capture_test.go b/core/capture_test.go\nnew file mode 100644\nindex 0000000..b5d34b0\n--- /dev/null\n+++ b/core/capture_test.go\n@@ -0,0 +1,210 @@\n+package core\n+\n+import (\n+\t\"bytes\"\n+\t\"context\"\n+\t\"io\"\n+\t\"slices\"\n+\t\"strings\"\n+\t\"testing\"\n+\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tclabtypes \"github.com/srl-labs/containerlab/types\"\n+)\n+\n+// captureLabRuntime records the capture requests core sends.\n+type captureLabRuntime struct {\n+\tclablabruntime.LabRuntime\n+\n+\tnodeRequest    clablabruntime.NodeRequest\n+\tcaptureRequest clablabruntime.CaptureRequest\n+}\n+\n+func (r *captureLabRuntime) CaptureInterfaces(\n+\t_ context.Context,\n+\treq clablabruntime.NodeRequest,\n+) ([]clablabruntime.CaptureInterface, error) {\n+\tr.nodeRequest = req\n+\n+\treturn []clablabruntime.CaptureInterface{{Node: \"r1\", Interface: \"eth1\"}}, nil\n+}\n+\n+func (r *captureLabRuntime) Capture(\n+\t_ context.Context,\n+\treq clablabruntime.CaptureRequest,\n+\tw io.Writer,\n+) error {\n+\tr.captureRequest = req\n+\t_, err := io.WriteString(w, \"pcapng\")\n+\n+\treturn err\n+}\n+\n+func (r *captureLabRuntime) InspectInterfaces(\n+\t_ context.Context,\n+\treq clablabruntime.NodeRequest,\n+) ([]*clabtypes.ContainerInterfaces, error) {\n+\tr.nodeRequest = req\n+\n+\treturn []*clabtypes.ContainerInterfaces{{ContainerName: \"lab1-r1\"}}, nil\n+}\n+\n+func TestCaptureHelpersFillLabAndIdentity(t *testing.T) {\n+\tt.Parallel()\n+\n+\tlr := &captureLabRuntime{}\n+\tc := newAccessTestCLab(lr)\n+\tctx := context.Background()\n+\n+\tinterfaces, err := c.CaptureInterfaces(ctx, \"R1\")\n+\tif err != nil || len(interfaces) != 1 {\n+\t\tt.Fatalf(\"CaptureInterfaces() = %+v, %v\", interfaces, err)\n+\t}\n+\tif lr.nodeRequest.Name != \"lab1\" || lr.nodeRequest.Nodes[0] != \"R1\" ||\n+\t\t!lr.nodeRequest.Identity.Equal(testIdentity) {\n+\t\tt.Fatalf(\"interfaces request = %+v\", lr.nodeRequest)\n+\t}\n+\n+\tvar out bytes.Buffer\n+\tif err := c.Capture(ctx, clablabruntime.CaptureRequest{\n+\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n+\t}, &out); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif out.String() != \"pcapng\" || lr.captureRequest.Name != \"lab1\" ||\n+\t\t!lr.captureRequest.Identity.Equal(testIdentity) {\n+\t\tt.Fatalf(\"capture request = %+v, output %q\", lr.captureRequest, out.String())\n+\t}\n+\n+\tifaces, err := c.LabRuntimeInterfaces(ctx, \"r1\")\n+\tif err != nil || len(ifaces) != 1 || lr.nodeRequest.Nodes[0] != \"r1\" {\n+\t\tt.Fatalf(\"LabRuntimeInterfaces() = %+v, %v, request %+v\", ifaces, err, lr.nodeRequest)\n+\t}\n+\tif _, err := c.LabRuntimeInterfaces(ctx, \"\"); err != nil || lr.nodeRequest.Nodes != nil {\n+\t\tt.Fatalf(\"all nodes request = %+v, %v\", lr.nodeRequest, err)\n+\t}\n+}\n+\n+// newLocalCaptureCLab loads the capture test topology. Its host and mgmt-net links register\n+// endpoints on link nodes the whole process shares, so the tests using it do not run in\n+// parallel and release the endpoints when they end.\n+func newLocalCaptureCLab(t *testing.T) *CLab {\n+\tt.Helper()\n+\n+\tc, err := NewContainerLab(WithTopoPath(\"test_data/capture.clab.yml\", nil))\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tt.Cleanup(c.resetResolvedLinks)\n+\n+\treturn c\n+}\n+\n+func TestLocalCaptureInterfacesComeFromTheTopologyLinks(t *testing.T) {\n+\tc := newLocalCaptureCLab(t)\n+\n+\tgot, err := c.CaptureInterfaces(context.Background(), \"srl1\", \"client\")\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\twant := []clablabruntime.CaptureInterface{\n+\t\t{Node: \"client\", Interface: \"eth1\", PeerNode: \"srl1\", PeerInterface: \"e1-2\"},\n+\t\t{Node: \"client\", Interface: \"eth2\", PeerNode: \"host\", PeerInterface: \"client-eth2\"},\n+\t\t{Node: \"client\", Interface: \"eth3\", PeerNode: \"mgmt-net\", PeerInterface: \"client-eth3\"},\n+\t\t{\n+\t\t\tNode: \"srl1\", Interface: \"e1-1\", Alias: \"ethernet-1/1\",\n+\t\t\tPeerNode: \"srl2\", PeerInterface: \"e1-1\",\n+\t\t},\n+\t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"client\", PeerInterface: \"eth1\"},\n+\t}\n+\tif !slices.Equal(got, want) {\n+\t\tt.Fatalf(\"CaptureInterfaces() =\\n%+v\\nwant\\n%+v\", got, want)\n+\t}\n+\n+\tif _, err := c.CaptureInterfaces(context.Background(), \"r9\"); err == nil ||\n+\t\t!strings.Contains(err.Error(), `node \"r9\" is not part of lab \"capture\"`) {\n+\t\tt.Fatalf(\"unknown node: error = %v\", err)\n+\t}\n+}\n+\n+func TestLocalCaptureTargetsResolveByNameOrAlias(t *testing.T) {\n+\tc := newLocalCaptureCLab(t)\n+\n+\ttargets, err := c.resolveLocalCaptureTargets([]clablabruntime.CaptureTarget{\n+\t\t{Node: \"srl2\", Interface: \"e1-1\"},\n+\t\t{Node: \"srl1\", Interface: \"ethernet-1/1\"},\n+\t\t{Node: \"clab-capture-client\", Interface: \"eth2\"},\n+\t})\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tvar got []string\n+\tfor _, target := range targets {\n+\t\tif target.Exec == nil {\n+\t\t\tt.Fatalf(\"target %s:%s has no namespace exec\", target.Node, target.Interface)\n+\t\t}\n+\t\tgot = append(got, target.Node+\":\"+target.Interface)\n+\t}\n+\tif want := []string{\"srl2:e1-1\", \"srl1:e1-1\", \"client:eth2\"}; !slices.Equal(got, want) {\n+\t\tt.Fatalf(\"targets = %v, want %v\", got, want)\n+\t}\n+\n+\tfor _, tc := range []struct {\n+\t\tname    string\n+\t\ttargets []clablabruntime.CaptureTarget\n+\t\twant    string\n+\t}{\n+\t\t{\n+\t\t\tname:    \"management interface\",\n+\t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"client\", Interface: \"eth0\"}},\n+\t\t\twant: `interface \"eth0\" of node \"client\" is not a capturable link interface; ` +\n+\t\t\t\t\"capturable: eth1, eth2, eth3\",\n+\t\t},\n+\t\t{\n+\t\t\tname: \"same interface twice\",\n+\t\t\ttargets: []clablabruntime.CaptureTarget{\n+\t\t\t\t{Node: \"srl1\", Interface: \"e1-1\"}, {Node: \"srl1\", Interface: \"ethernet-1/1\"},\n+\t\t\t},\n+\t\t\twant: `interface \"e1-1\" of node \"srl1\" is requested more than once`,\n+\t\t},\n+\t\t{\n+\t\t\tname:    \"unknown node\",\n+\t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"r9\", Interface: \"eth1\"}},\n+\t\t\twant:    `node \"r9\" is not part of lab \"capture\"`,\n+\t\t},\n+\t} {\n+\t\tif _, err := c.resolveLocalCaptureTargets(tc.targets); err == nil ||\n+\t\t\t!strings.Contains(err.Error(), tc.want) {\n+\t\t\tt.Errorf(\"%s: error = %v, want %q\", tc.name, err, tc.want)\n+\t\t}\n+\t}\n+}\n+\n+func TestLocalCaptureNeedsTheTopology(t *testing.T) {\n+\tt.Parallel()\n+\n+\tc := &CLab{Config: &Config{Name: \"lab1\"}, globalRuntimeName: \"docker\"}\n+\terr := c.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n+\t}, io.Discard)\n+\tif err == nil || !strings.Contains(err.Error(), `the topology of lab \"lab1\" is not available`) {\n+\t\tt.Fatalf(\"error = %v\", err)\n+\t}\n+\tif err := c.Capture(context.Background(), clablabruntime.CaptureRequest{},\n+\t\tio.Discard); err == nil || !strings.Contains(err.Error(), \"at least one capture target\") {\n+\t\tt.Fatalf(\"no targets: error = %v\", err)\n+\t}\n+}\n+\n+func TestLabRuntimeWithoutCaptureFails(t *testing.T) {\n+\tt.Parallel()\n+\n+\tunsupported := newAccessTestCLab(&recordingDestroyLabRuntime{})\n+\tif err := unsupported.Capture(\n+\t\tcontext.Background(),\n+\t\tclablabruntime.CaptureRequest{},\n+\t\tio.Discard,\n+\t); err == nil || !strings.Contains(err.Error(), \"does not support packet capture\") {\n+\t\tt.Fatalf(\"lab runtime without capture: error = %v\", err)\n+\t}\n+}\ndiff --git a/core/labruntime_cluster_test.go b/core/labruntime_cluster_test.go\nindex 06ecf57..981a302 100644\n--- a/core/labruntime_cluster_test.go\n+++ b/core/labruntime_cluster_test.go\n@@ -1,10 +1,11 @@\n package core\n \n import (\n \t\"bytes\"\n \t\"context\"\n+\t\"encoding/binary\"\n \t\"errors\"\n \t\"io\"\n \t\"net\"\n \t\"net/http\"\n \t\"os\"\n@@ -175,5 +176,153 @@ func TestC9sClusterNodeAccess(t *testing.T) {\n \t\tif err == nil || !strings.Contains(err.Error(), \"forbidden\") {\n \t\t\tt.Fatalf(\"impersonated user without rights: error = %v, want forbidden\", err)\n \t\t}\n \t})\n }\n+\n+// TestC9sClusterCapture captures through the library against a deployed c9s lab, as an identity\n+// that holds only the clabernetes-lab-editor role in the lab namespace. It runs only when\n+// CLAB_C9S_TEST_LAB names the lab and CLAB_C9S_TEST_CAPTURE_USER the identity (tests/14-clabernetes\n+// sets both). The lab must have linux nodes \"client\" (10.10.10.1) and \"server\" (10.10.10.2)\n+// linked by eth1. CLAB_C9S_TEST_FORBIDDEN_USER names an identity without a binding.\n+func TestC9sClusterCapture(t *testing.T) {\n+\tlab := os.Getenv(\"CLAB_C9S_TEST_LAB\")\n+\tuser := os.Getenv(\"CLAB_C9S_TEST_CAPTURE_USER\")\n+\tif lab == \"\" || user == \"\" {\n+\t\tt.Skip(\"CLAB_C9S_TEST_LAB or CLAB_C9S_TEST_CAPTURE_USER is not set\")\n+\t}\n+\n+\tnewCLab := func(t *testing.T, user string) *CLab {\n+\t\tt.Helper()\n+\n+\t\tc, err := NewContainerLab(\n+\t\t\tWithRuntime(clablabruntime.ClabernetesRuntimeName, nil),\n+\t\t\tWithTopologyName(lab),\n+\t\t\tWithLabRuntimeIdentity(clablabruntime.Identity{User: user}),\n+\t\t)\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\n+\t\treturn c\n+\t}\n+\tc := newCLab(t, user)\n+\n+\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)\n+\tdefer cancel()\n+\n+\tt.Run(\"version check\", func(t *testing.T) {\n+\t\tif err := c.CheckLabRuntimeSupport(ctx); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t})\n+\n+\tt.Run(\"capture interfaces\", func(t *testing.T) {\n+\t\tinterfaces, err := c.CaptureInterfaces(ctx)\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\twant := []clablabruntime.CaptureInterface{\n+\t\t\t{Node: \"client\", Interface: \"eth1\", PeerNode: \"server\", PeerInterface: \"eth1\"},\n+\t\t\t{Node: \"server\", Interface: \"eth1\", PeerNode: \"client\", PeerInterface: \"eth1\"},\n+\t\t}\n+\t\tif len(interfaces) != 2 || interfaces[0] != want[0] || interfaces[1] != want[1] {\n+\t\t\tt.Fatalf(\"interfaces = %+v\", interfaces)\n+\t\t}\n+\t})\n+\n+\tt.Run(\"capture both ends of a link\", func(t *testing.T) {\n+\t\tpinged := make(chan error, 1)\n+\t\tgo func() {\n+\t\t\ttime.Sleep(time.Second)\n+\t\t\tpinged <- c.AttachLabRuntimeNode(ctx, clablabruntime.AttachRequest{\n+\t\t\t\tNodeName: \"client\",\n+\t\t\t\tCommand:  []string{\"ping\", \"-c\", \"4\", \"-i\", \"0.3\", \"10.10.10.2\"},\n+\t\t\t}, clablabruntime.AttachStreams{Stdout: io.Discard})\n+\t\t}()\n+\n+\t\tvar out bytes.Buffer\n+\t\terr := c.Capture(ctx, clablabruntime.CaptureRequest{\n+\t\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t\t{Node: \"client\", Interface: \"eth1\"}, {Node: \"server\", Interface: \"eth1\"},\n+\t\t\t},\n+\t\t\tDuration: 5 * time.Second,\n+\t\t}, &out)\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\tif err := <-pinged; err != nil {\n+\t\t\tt.Fatalf(\"ping: %v\", err)\n+\t\t}\n+\n+\t\tnames, icmp := summarizePCAPNG(t, out.Bytes())\n+\t\tif len(names) != 2 || names[0] != \"client:eth1\" || names[1] != \"server:eth1\" {\n+\t\t\tt.Fatalf(\"interfaces = %v\", names)\n+\t\t}\n+\t\t// every echo request and reply crosses both ends\n+\t\tif icmp[0] < 8 || icmp[1] < 8 {\n+\t\t\tt.Fatalf(\"ICMP packets per interface = %v, want at least 8 on each\", icmp)\n+\t\t}\n+\t})\n+\n+\tt.Run(\"restart as lab editor\", func(t *testing.T) {\n+\t\tif err := c.RestartNodes(ctx, []string{\"server\"}); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t})\n+\n+\tt.Run(\"forbidden identity\", func(t *testing.T) {\n+\t\tforbidden := os.Getenv(\"CLAB_C9S_TEST_FORBIDDEN_USER\")\n+\t\tif forbidden == \"\" {\n+\t\t\tt.Skip(\"CLAB_C9S_TEST_FORBIDDEN_USER is not set\")\n+\t\t}\n+\n+\t\terr := newCLab(t, forbidden).Capture(ctx, clablabruntime.CaptureRequest{\n+\t\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"client\", Interface: \"eth1\"}},\n+\t\t\tDuration: time.Second,\n+\t\t}, io.Discard)\n+\t\tif err == nil || !strings.Contains(err.Error(), \"forbidden\") {\n+\t\t\tt.Fatalf(\"capture as %s = %v, want forbidden\", forbidden, err)\n+\t\t}\n+\t})\n+}\n+\n+// summarizePCAPNG returns the interface names of a little-endian pcapng stream and its IPv4 ICMP\n+// packets per interface ID.\n+func summarizePCAPNG(t *testing.T, data []byte) ([]string, map[uint32]int) {\n+\tt.Helper()\n+\n+\tvar names []string\n+\ticmp := map[uint32]int{}\n+\tfor len(data) >= 12 {\n+\t\tblockType := binary.LittleEndian.Uint32(data[0:4])\n+\t\tlength := int(binary.LittleEndian.Uint32(data[4:8]))\n+\t\tif length < 12 || length > len(data) {\n+\t\t\tt.Fatalf(\"invalid block length %d\", length)\n+\t\t}\n+\t\tbody := data[8 : length-4]\n+\t\tswitch blockType {\n+\t\tcase 1: // Interface Description Block\n+\t\t\toptions := body[8:]\n+\t\t\tfor len(options) >= 4 {\n+\t\t\t\tcode := binary.LittleEndian.Uint16(options[0:2])\n+\t\t\t\tsize := int(binary.LittleEndian.Uint16(options[2:4]))\n+\t\t\t\tif code == 0 {\n+\t\t\t\t\tbreak\n+\t\t\t\t}\n+\t\t\t\tif code == 2 {\n+\t\t\t\t\tnames = append(names, string(options[4:4+size]))\n+\t\t\t\t}\n+\t\t\t\toptions = options[4+size+(4-size%4)%4:]\n+\t\t\t}\n+\t\tcase 6: // Enhanced Packet Block\n+\t\t\tid := binary.LittleEndian.Uint32(body[0:4])\n+\t\t\tframe := body[20 : 20+binary.LittleEndian.Uint32(body[12:16])]\n+\t\t\tif len(frame) > 23 && frame[12] == 0x08 && frame[13] == 0x00 && frame[23] == 1 {\n+\t\t\t\ticmp[id]++\n+\t\t\t}\n+\t\t}\n+\t\tdata = data[length:]\n+\t}\n+\n+\treturn names, icmp\n+}\ndiff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml\nnew file mode 100644\nindex 0000000..0422c22\n--- /dev/null\n+++ b/core/test_data/capture.clab.yml\n@@ -0,0 +1,15 @@\n+name: capture\n+topology:\n+  nodes:\n+    srl1:\n+      kind: nokia_srlinux\n+    srl2:\n+      kind: nokia_srlinux\n+    client:\n+      kind: linux\n+      image: alpine:3\n+  links:\n+    - endpoints: [\"srl1:ethernet-1/1\", \"srl2:e1-1\"]\n+    - endpoints: [\"srl1:e1-2\", \"client:eth1\"]\n+    - endpoints: [\"client:eth2\", \"host:client-eth2\"]\n+    - endpoints: [\"client:eth3\", \"mgmt-net:client-eth3\"]\ndiff --git a/docs/cmd/capture.md b/docs/cmd/capture.md\nnew file mode 100644\nindex 0000000..15006ff\n--- /dev/null\n+++ b/docs/cmd/capture.md\n@@ -0,0 +1,134 @@\n+# capture command\n+\n+### Description\n+",
        "lineStart": 2761,
        "lineEnd": 3520,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523342237,
      "end": 1793523342307
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196525be8001KAr76v9fueT0DR",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19652532d001VBllmmBAf5BXgY",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 25010,
    "input": 8044,
    "output": 28,
    "reasoning": 42,
    "cache": {
      "read": 16896,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19652532d001VBllmmBAf5BXgY",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523340077,
    "completed": 1793523342319
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 25010,
    "input": 8044,
    "output": 28,
    "reasoning": 42,
    "cache": {
      "read": 16896,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 28
step-start
{
  "type": "step-start",
  "id": "prt_19652664d001VwXsdfGlj92Won",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196525bfc001zLWkm9tE0OVysO"
}
Reasoning
Now let me read the remaining diff: 3521-3900 (docs/cmd/capture.md, docs/cmd/inspect/interfaces.md, docs/manual/clabernetes/runtime.md, docs/manual/wireshark.md) and 4030-6356 (labruntime/clabernetes/capture.go and capture_interfaces.go and capture_test.go, runtime changes). I've already seen much of the c9s capture.go details from the summary. Let me read 3521-3900.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 380,
  "offset": 3521
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
3521: +The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.
3522: +
3523: +It works with every runtime:
3524: +
3525: +- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).
3526: +- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).
3527: +
3528: +The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.
3529: +
3530: +--8<-- "docs/cmd/deploy.md:env-vars-flags"
3531: +
3532: +### Usage
3533: +
3534: +`containerlab [global-flags] capture [local-flags]`
3535: +
3536: +### Flags
3537: +
3538: +#### topology | name
3539: +
3540: +Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.
3541: +
3542: +With Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.
3543: +
3544: +#### target
3545: +
3546: +The local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:
3547: +
3548: +```text
3549: +--target srl1:e1-1,e1-2 --target srl2:e1-1
3550: +```
3551: +
3552: +The node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.
3553: +
3554: +Only lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.
3555: +
3556: +#### duration
3557: +
3558: +The local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).
3559: +
3560: +#### packet-limit
3561: +
3562: +The local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.
3563: +
3564: +#### snap-length
3565: +
3566: +The local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.
3567: +
3568: +#### write
3569: +
3570: +The local `--write | -w` flag names the output file. The default `-` writes to stdout.
3571: +
3572: +#### list
3573: +
3574: +The local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.
3575: +
3576: +### Output
3577: +
3578: +The output is one pcapng section:
3579: +
3580: +- a Section Header Block with `shb_userappl` set to `containerlab`
3581: +- one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it
3582: +- Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes
3583: +
3584: +The interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.
3585: +
3586: +When the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.
3587: +
3588: +`--list -f json` prints an array:
3589: +
3590: +```json
3591: +[
3592: +  {
3593: +    "node": "srl1",
3594: +    "interface": "e1-1",
3595: +    "alias": "ethernet-1/1",
3596: +    "peer_node": "srl2",
3597: +    "peer_interface": "ethernet-1/1"
3598: +  }
3599: +]
3600: +```
3601: +
3602: +`alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.
3603: +
3604: +### How Docker and Podman captures work
3605: +
3606: +For each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.
3607: +
3608: +- Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.
3609: +- 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.
3610: +- Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.
3611: +- An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.
3612: +
3613: +The command needs root (to open packet sockets and enter network namespaces), as other lab commands do.
3614: +
3615: +### Long captures
3616: +
3617: +Docker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.
3618: +
3619: +### Examples
3620: +
3621: +#### Capture two nodes for 30 seconds into one file
3622: +
3623: +```bash
3624: +containerlab capture -t srl.clab.yml \
3625: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng
3626: +```
3627: +
3628: +#### Watch a capture live in Wireshark
3629: +
3630: +```bash
3631: +containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -
3632: +```
3633: +
3634: +#### Capture the first 100 packets with tshark
3635: +
3636: +```bash
3637: +containerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -
3638: +```
3639: +
3640: +#### List the capturable interfaces
3641: +
3642: +```bash
3643: +containerlab capture --name srl --list
3644: +```
3645: +
3646: +#### Capture a c9s lab
3647: +
3648: +```bash
3649: +containerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng
3650: +```
3651: diff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md
3652: index 3dc8e27..2354dc1 100644
3653: --- a/docs/cmd/inspect/interfaces.md
3654: +++ b/docs/cmd/inspect/interfaces.md
3655: @@ -3,10 +3,12 @@
3656:  ### Description
3657:  
3658:  The `inspect interfaces` subcommand provides information about the network interfaces of deployed nodes of a deployed lab.
3659:  The subcommand gathers information directly from deployed containers, and displays information about their operational state, network interface type, and if applicable, the applied network interface alias.
3660:  
3661: +With the [c9s runtime](../../manual/clabernetes/runtime.md#packet-capture), the listing covers the lab link interfaces of each running node, the ones [`capture`](../capture.md) accepts, with the alias the topology used, and the MAC address, index, MTU and operational state read in the node's device container. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields are the same as with Docker.
3662: +
3663:  ### Usage
3664:  
3665:  `containerlab [global-flags] inspect interfaces [local-flags]`
3666:  
3667:  A shorthand can be used for this subcommand: `int` or `intf`.
3668: diff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md
3669: index 0ce708d..8174c98 100644
3670: --- a/docs/manual/clabernetes/runtime.md
3671: +++ b/docs/manual/clabernetes/runtime.md
3672: @@ -110,10 +110,13 @@ The c9s runtime currently supports the main lab lifecycle and node operations:
3673:  | `start` | sets the node's `spec.runState` to `Running` |
3674:  | `stop` | sets the node's `spec.runState` to `Stopped` |
3675:  | `restart` | requests a Pod replacement with a `c9s.run/restart-requested` token |
3676:  | `save` | runs the node's save lifecycle inside its device container |
3677:  | `events` | watches Clabernetes resources and pods |
3678: +| `logs` | streams the device container log |
3679: +| `capture` | captures lab link interfaces through the `clabwire` sidecar into one pcapng stream |
3680: +| `inspect interfaces` | lists the capturable link interfaces with their sysfs state |
3681:  | `validate` | checks c9s compatibility without creating Kubernetes resources |
3682:  | `deploy --dry-run` | compiles and diffs Namespace, ConfigMap, NodeProfile, Link, and Node resources without changing them |
3683:  | `deploy --emit-crs` | prints the Namespace, ConfigMap, and Topology (or NodeProfile, Link, and Node) manifests deploy would create, without contacting the cluster |
3684:  
3685:  ## Requirements
3686: @@ -141,11 +144,11 @@ Containerlab needs a clabernetes release that has:
3687:  
3688:  - Node run state: `nodes.c9s.run` `spec.runState` (`Running` | `Stopped`), the
3689:    `Stopped` condition, and restart requests through the
3690:    `c9s.run/restart-requested` annotation
3691:  - the clabwire packet capture contract: `--nodeName`, repeated `--interface`,
3692: -  `--format pcapng` and `--list-interfaces`
3693: +  `--format pcapng`, `--list-interfaces` and `--stop-on-stdin-close`
3694:  - the namespace-bindable `clabernetes-lab-viewer` and `clabernetes-lab-editor`
3695:    roles
3696:  
3697:  Both features ship in the same release, so containerlab checks one field: the
3698:  published OpenAPI schema of `nodes.c9s.run` (`/openapi/v3/apis/c9s.run/v1alpha1`)
3699: @@ -159,10 +162,21 @@ an older release every other command fails like this:
3700:  the clabernetes release on this cluster is not supported: nodes.c9s.run has no
3701:  spec.runState (Node run state); the c9s runtime needs clabernetes with Node run
3702:  state and the clabwire capture contract (0.11 or newer)
3703:  ```
3704:  
3705: +A cluster that passes this check but runs a `clabwire` without
3706: +`--stop-on-stdin-close` (a development build between the two features) fails
3707: +the first capture with the same kind of error, naming the pod:
3708: +
3709: +```text
3710: +the clabernetes release on this cluster is not supported: clabwire in pod
3711: +<namespace>/<pod> does not accept packet-capture --stop-on-stdin-close; the c9s
3712: +runtime needs clabernetes with Node run state and the clabwire capture contract
3713: +(0.11 or newer)
3714: +```
3715: +
3716:  Library users can run the check up front with
3717:  `(*core.CLab).CheckLabRuntimeSupport(ctx)` or the optional
3718:  `labruntime.SupportChecker` interface; the error wraps
3719:  `labruntime.ErrUnsupportedRuntimeVersion`.
3720:  
3721: @@ -579,10 +593,82 @@ containerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timest
3722:  
3723:  It reads the `pods/log` subresource of the node's pod, so RBAC must allow
3724:  `get` on `pods/log`. Kubernetes returns stdout and stderr as one stream. See
3725:  the [`logs` command](../../cmd/logs.md) for the flags.
3726:  
3727: +## Packet capture
3728: +
3729: +[`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of
3730: +one or more nodes into one pcapng stream. Each node's pod runs the `clabwire`
3731: +sidecar, which realized the node's links; containerlab execs its capture
3732: +command (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.
3733: +No capture service runs in the cluster, and nothing is captured outside the
3734: +lab's planned link interfaces.
3735: +
3736: +```bash
3737: +# both ends of a link, for 30 seconds
3738: +containerlab -r c9s capture -t clos.clab.yml \
3739: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng
3740: +
3741: +# live in Wireshark until Wireshark or Ctrl+C ends it
3742: +containerlab -r c9s capture --name clos --target srl1:e1-1,e1-2 -w - | wireshark -k -i -
3743: +
3744: +# what can be captured, with the peer of each link
3745: +containerlab -r c9s capture --name clos --list
3746: +```
3747: +
3748: +How it works:
3749: +
3750: +- containerlab locates each target node's pod and runs one `clabwire` capture
3751: +  per node, with `--nodeName`, every requested interface of that node,
3752: +  `--format pcapng` and `--stop-on-stdin-close`, with stdin attached.
3753: +- The streams are merged into one section: one Interface Description Block per
3754: +  target named `<node>:<interface>` (the node as the topology spells it),
3755: +  written before the first packet, and the packets of every target with their
3756: +  interface IDs remapped.
3757: +- Packets are written in timestamp order. Each node's stream arrives over its
3758: +  own exec stream, so the merged stream holds every packet for 250 ms and
3759: +  writes the held packets ordered by timestamp. A packet that arrives later
3760: +  than that, stamped before a packet already written, is written as it comes;
3761: +  the number of such packets goes to the debug log.
3762: +- `clabwire` limits one capture to one hour. Longer captures, and captures
3763: +  without `--duration`, chain captures with a few seconds of overlap and switch
3764: +  in the middle of it; packets near the switch are matched by content so each
3765: +  is written once. A follow-up that does not start in time is reported as a
3766: +  gap, with its time span.
3767: +- `clabwire` audit records (JSON on its stderr, schema
3768: +  `c9s.direct-packet-capture-audit/v1alpha1`) with status `Denied` or `Failed`
3769: +  end the command with their reason. `Started` and `Succeeded` go to the debug
3770: +  log.
3771: +
3772: +Interface names are the names inside the node; targets may also use the alias
3773: +the topology used for an interface:
3774: +
3775: +| Kind | Interface | Alias |
3776: +| ---- | --------- | ----- |
3777: +| linux | `eth1` | |
3778: +| SR Linux | `e1-1` | `ethernet-1/1` |
3779: +| vr-sros / nokia_sros | `eth3` | `1/1/3` |
3780: +
3781: +The management interface and the pod's `c9s0` interface cannot be captured.
3782: +
3783: +Ctrl+C or SIGTERM ends a capture cleanly: the output stays a valid pcapng
3784: +file and the command exits with code 0. Kubernetes does not stop a command
3785: +when its exec stream closes, but it closes the command's stdin. containerlab
3786: +closes the stdin of every `clabwire` capture when the capture ends for any
3787: +reason (the duration or packet limit, Ctrl+C, an error, a failed write of the
3788: +output such as a closed Wireshark, or a newer segment taking over), and
3789: +`clabwire` then ends the capture within milliseconds. If the process does not
3790: +end within three seconds, containerlab cuts the exec stream. A killed
3791: +containerlab drops the connection, which closes stdin as well.
3792: +
3793: +Capturing needs `get` and `create` on `pods/exec` in the lab namespace, which
3794: +`clabernetes-lab-editor` grants. `inspect interfaces -r c9s` lists the same
3795: +interfaces, with the MAC address, index, MTU and operational state read from
3796: +sysfs in the device container (type `veth`, which is how `clabwire` realizes
3797: +lab links).
3798: +
3799:  ## Start, stop, and restart
3800:  
3801:  Node lifecycle commands ask the clabernetes controllers for a run state; they
3802:  never touch Deployments or Pods.
3803:  
3804: @@ -863,16 +949,22 @@ implemented by the c9s runtime:
3805:  | `NodeLocator` | `LocateNode(ctx, NodeRequest) ([]NodeLocation, error)` | the namespace, pod, primary device container, Node UID, exposed ports and LoadBalancer address of nodes |
3806:  | `NodeAttacher` | `Attach(ctx, AttachRequest, AttachStreams) error` | an interactive exec with stdin, an optional TTY and a resize channel, in the device container or a chosen container |
3807:  | `NodeLogStreamer` | `StreamLogs(ctx, LogRequest, io.Writer) error` | the device container log, with tail, follow and timestamps |
3808:  | `NodePortForwarder` | `DialPort(ctx, NodeRequest, port) (net.Conn, error)` | a connection to a TCP port of the node's pod through `pods/portforward` (SSH, web UIs) |
3809:  | `NodeStatsSampler` | `SampleStats(ctx, InspectRequest) ([]NodeStats, error)` | CPU and memory per node from `metrics.k8s.io` PodMetrics, summing the node's device containers; without the metrics API the error wraps `labruntime.ErrMetricsUnavailable` |
3810: +| `PacketCapturer` | `CaptureInterfaces(ctx, NodeRequest) ([]CaptureInterface, error)` | the capturable link interfaces of nodes, with alias, peer node and peer interface |
3811: +| `PacketCapturer` | `Capture(ctx, CaptureRequest, io.Writer) error` | one pcapng stream of the request's targets, for `Duration` (0: until ctx ends), `PacketLimit` and `SnapLength`; gaps go to `OnGap` |
3812: +| `InterfaceInspector` | `InspectInterfaces(ctx, NodeRequest) ([]*types.ContainerInterfaces, error)` | the `inspect interfaces` view of the link interfaces |
3813: +| `SupportChecker` | `CheckSupport(ctx, Identity) error` | the clabernetes release check |
3814:  
3815:  The `core` package wraps them per lab and node name, accepting the node name
3816:  as the topology file spells it or as it was sanitized:
3817:  `CLab.LocateLabRuntimeNodes`, `CLab.AttachLabRuntimeNode`,
3818: -`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats` and
3819: -`CLab.NodeLogs`, which also serves Docker and Podman.
3820: +`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats`,
3821: +`CLab.CaptureInterfaces`, `CLab.Capture`, `CLab.LabRuntimeInterfaces`,
3822: +`CLab.CheckLabRuntimeSupport` and `CLab.NodeLogs`, which also serves Docker and
3823: +Podman.
3824:  
3825:  ```go
3826:  c, err := clabcore.NewContainerLab(
3827:  	clabcore.WithRuntime("c9s", nil),
3828:  	clabcore.WithTopologyName("clos"),
3829: @@ -884,10 +976,18 @@ c, err := clabcore.NewContainerLab(
3830:  if err != nil {
3831:  	return err
3832:  }
3833:  
3834:  conn, err := c.DialLabRuntimeNodePort(ctx, "srl1", 22)
3835: +
3836: +// stream pcapng to a websocket, a file or Wireshark until ctx ends
3837: +err = c.Capture(ctx, clablabruntime.CaptureRequest{
3838: +	Targets: []clablabruntime.CaptureTarget{
3839: +		{Node: "srl1", Interface: "ethernet-1/1"},
3840: +		{Node: "srl2", Interface: "e1-1"},
3841: +	},
3842: +}, w)
3843:  ```
3844:  
3845:  ### Acting as a user
3846:  
3847:  A server that runs labs for many users acts as each user, so the cluster's RBAC
3848: @@ -936,11 +1036,12 @@ to:
3849:  - create, get, list, watch, and delete c9s `Link` and `NodeProfile` resources
3850:  - get, list, watch, and delete `Topology` resources when Topology-based labs
3851:    must remain manageable
3852:  - list and watch Pods
3853:  - create, get, list, update, and delete ConfigMaps used for local files
3854: -- exec into device Pods with `pods/exec`
3855: +- exec into device Pods with `pods/exec`, also for `capture` and `inspect
3856: +  interfaces` (in the `clabwire` and device containers)
3857:  - list and delete PersistentVolumeClaims for `destroy --cleanup`
3858:  - read container logs with `pods/log` for `logs`
3859:  - port-forward with `pods/portforward` for `NodePortForwarder`
3860:  - list `pods.metrics.k8s.io` for `NodeStatsSampler`
3861:  
3862: @@ -1152,12 +1253,14 @@ Known command differences:
3863:    `--export-template`, `--restore`, and `--restore-all` are rejected.
3864:  - Destroy flags `--graceful` and `--keep-mgmt-net` are rejected. `--cleanup`
3865:    also deletes the lab's persistent claims (saved device state) and removes
3866:    the local lab directory; a plain destroy keeps the claims.
3867:  - Local Docker commands on the outer host are not authoritative for c9s labs.
3868: -- `inspect interfaces` is rejected. Host-side `tc` or netem operations do not
3869: -  have the same local namespace access they have with Docker labs.
3870: +- `inspect interfaces` lists only the lab link interfaces (those `capture`
3871: +  accepts), not the management or pod interfaces. Host-side `tc` or netem
3872: +  operations do not have the same local namespace access they have with Docker
3873: +  labs.
3874:  - `graph` renders from the topology file only: `--mermaid`, `--dot`, `--drawio`
3875:    and `--offline` work, the default mode that reads running containers is
3876:    rejected, and so is `--node-filter`. `--drawio` runs the clab-io-draw
3877:    container, so it needs Docker or Podman on the outer host.
3878:  - `tools` commands operate on local containers and host networking and are
3879: diff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md
3880: index b194b29..4654128 100644
3881: --- a/docs/manual/wireshark.md
3882: +++ b/docs/manual/wireshark.md
3883: @@ -15,10 +15,16 @@ Every lab emulation software must provide its users with the packet capturing ab
3884:  
3885:  Containerlab offers a simple way to capture the packets from any interface of any node in the lab. This article will explain how to do that.
3886:  
3887:  ///tip
3888:  
3889: +The [`containerlab capture`](../cmd/capture.md) command captures one or more lab link interfaces, of one or more nodes, into one pcapng file or stream, with nothing to install in the nodes or on the host:
3890: +
3891: +```bash
3892: +containerlab capture --name quickstart --target srl:e1-1 -w - | wireshark -k -i -
3893: +```
3894: +
3895:  If you are looking for a free Web UI for packet capture with Wireshark, check out our [Edgeshark integration](#edgeshark-integration).
3896:  ///
3897:  
3898:  Consider the following lab topology which highlights the typical points of packet capture.
3899:  
3900: diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go

(Showing lines 3521-3900 of 7018. Use offset=3901 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1965268400010eYCEk8YoiomGu",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196525bfc001zLWkm9tE0OVysO",
  "callID": "call_b62d474bcc894725895eae24",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 380,
      "offset": 3521
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n3521: +The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.\n3522: +\n3523: +It works with every runtime:\n3524: +\n3525: +- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).\n3526: +- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).\n3527: +\n3528: +The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.\n3529: +\n3530: +--8<-- \"docs/cmd/deploy.md:env-vars-flags\"\n3531: +\n3532: +### Usage\n3533: +\n3534: +`containerlab [global-flags] capture [local-flags]`\n3535: +\n3536: +### Flags\n3537: +\n3538: +#### topology | name\n3539: +\n3540: +Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.\n3541: +\n3542: +With Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.\n3543: +\n3544: +#### target\n3545: +\n3546: +The local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:\n3547: +\n3548: +```text\n3549: +--target srl1:e1-1,e1-2 --target srl2:e1-1\n3550: +```\n3551: +\n3552: +The node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.\n3553: +\n3554: +Only lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.\n3555: +\n3556: +#### duration\n3557: +\n3558: +The local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).\n3559: +\n3560: +#### packet-limit\n3561: +\n3562: +The local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.\n3563: +\n3564: +#### snap-length\n3565: +\n3566: +The local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.\n3567: +\n3568: +#### write\n3569: +\n3570: +The local `--write | -w` flag names the output file. The default `-` writes to stdout.\n3571: +\n3572: +#### list\n3573: +\n3574: +The local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.\n3575: +\n3576: +### Output\n3577: +\n3578: +The output is one pcapng section:\n3579: +\n3580: +- a Section Header Block with `shb_userappl` set to `containerlab`\n3581: +- one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it\n3582: +- Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes\n3583: +\n3584: +The interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.\n3585: +\n3586: +When the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.\n3587: +\n3588: +`--list -f json` prints an array:\n3589: +\n3590: +```json\n3591: +[\n3592: +  {\n3593: +    \"node\": \"srl1\",\n3594: +    \"interface\": \"e1-1\",\n3595: +    \"alias\": \"ethernet-1/1\",\n3596: +    \"peer_node\": \"srl2\",\n3597: +    \"peer_interface\": \"ethernet-1/1\"\n3598: +  }\n3599: +]\n3600: +```\n3601: +\n3602: +`alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.\n3603: +\n3604: +### How Docker and Podman captures work\n3605: +\n3606: +For each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.\n3607: +\n3608: +- Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.\n3609: +- 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.\n3610: +- Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.\n3611: +- An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.\n3612: +\n3613: +The command needs root (to open packet sockets and enter network namespaces), as other lab commands do.\n3614: +\n3615: +### Long captures\n3616: +\n3617: +Docker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.\n3618: +\n3619: +### Examples\n3620: +\n3621: +#### Capture two nodes for 30 seconds into one file\n3622: +\n3623: +```bash\n3624: +containerlab capture -t srl.clab.yml \\\n3625: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n3626: +```\n3627: +\n3628: +#### Watch a capture live in Wireshark\n3629: +\n3630: +```bash\n3631: +containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n3632: +```\n3633: +\n3634: +#### Capture the first 100 packets with tshark\n3635: +\n3636: +```bash\n3637: +containerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -\n3638: +```\n3639: +\n3640: +#### List the capturable interfaces\n3641: +\n3642: +```bash\n3643: +containerlab capture --name srl --list\n3644: +```\n3645: +\n3646: +#### Capture a c9s lab\n3647: +\n3648: +```bash\n3649: +containerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng\n3650: +```\n3651: diff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md\n3652: index 3dc8e27..2354dc1 100644\n3653: --- a/docs/cmd/inspect/interfaces.md\n3654: +++ b/docs/cmd/inspect/interfaces.md\n3655: @@ -3,10 +3,12 @@\n3656:  ### Description\n3657:  \n3658:  The `inspect interfaces` subcommand provides information about the network interfaces of deployed nodes of a deployed lab.\n3659:  The subcommand gathers information directly from deployed containers, and displays information about their operational state, network interface type, and if applicable, the applied network interface alias.\n3660:  \n3661: +With the [c9s runtime](../../manual/clabernetes/runtime.md#packet-capture), the listing covers the lab link interfaces of each running node, the ones [`capture`](../capture.md) accepts, with the alias the topology used, and the MAC address, index, MTU and operational state read in the node's device container. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields are the same as with Docker.\n3662: +\n3663:  ### Usage\n3664:  \n3665:  `containerlab [global-flags] inspect interfaces [local-flags]`\n3666:  \n3667:  A shorthand can be used for this subcommand: `int` or `intf`.\n3668: diff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md\n3669: index 0ce708d..8174c98 100644\n3670: --- a/docs/manual/clabernetes/runtime.md\n3671: +++ b/docs/manual/clabernetes/runtime.md\n3672: @@ -110,10 +110,13 @@ The c9s runtime currently supports the main lab lifecycle and node operations:\n3673:  | `start` | sets the node's `spec.runState` to `Running` |\n3674:  | `stop` | sets the node's `spec.runState` to `Stopped` |\n3675:  | `restart` | requests a Pod replacement with a `c9s.run/restart-requested` token |\n3676:  | `save` | runs the node's save lifecycle inside its device container |\n3677:  | `events` | watches Clabernetes resources and pods |\n3678: +| `logs` | streams the device container log |\n3679: +| `capture` | captures lab link interfaces through the `clabwire` sidecar into one pcapng stream |\n3680: +| `inspect interfaces` | lists the capturable link interfaces with their sysfs state |\n3681:  | `validate` | checks c9s compatibility without creating Kubernetes resources |\n3682:  | `deploy --dry-run` | compiles and diffs Namespace, ConfigMap, NodeProfile, Link, and Node resources without changing them |\n3683:  | `deploy --emit-crs` | prints the Namespace, ConfigMap, and Topology (or NodeProfile, Link, and Node) manifests deploy would create, without contacting the cluster |\n3684:  \n3685:  ## Requirements\n3686: @@ -141,11 +144,11 @@ Containerlab needs a clabernetes release that has:\n3687:  \n3688:  - Node run state: `nodes.c9s.run` `spec.runState` (`Running` | `Stopped`), the\n3689:    `Stopped` condition, and restart requests through the\n3690:    `c9s.run/restart-requested` annotation\n3691:  - the clabwire packet capture contract: `--nodeName`, repeated `--interface`,\n3692: -  `--format pcapng` and `--list-interfaces`\n3693: +  `--format pcapng`, `--list-interfaces` and `--stop-on-stdin-close`\n3694:  - the namespace-bindable `clabernetes-lab-viewer` and `clabernetes-lab-editor`\n3695:    roles\n3696:  \n3697:  Both features ship in the same release, so containerlab checks one field: the\n3698:  published OpenAPI schema of `nodes.c9s.run` (`/openapi/v3/apis/c9s.run/v1alpha1`)\n3699: @@ -159,10 +162,21 @@ an older release every other command fails like this:\n3700:  the clabernetes release on this cluster is not supported: nodes.c9s.run has no\n3701:  spec.runState (Node run state); the c9s runtime needs clabernetes with Node run\n3702:  state and the clabwire capture contract (0.11 or newer)\n3703:  ```\n3704:  \n3705: +A cluster that passes this check but runs a `clabwire` without\n3706: +`--stop-on-stdin-close` (a development build between the two features) fails\n3707: +the first capture with the same kind of error, naming the pod:\n3708: +\n3709: +```text\n3710: +the clabernetes release on this cluster is not supported: clabwire in pod\n3711: +<namespace>/<pod> does not accept packet-capture --stop-on-stdin-close; the c9s\n3712: +runtime needs clabernetes with Node run state and the clabwire capture contract\n3713: +(0.11 or newer)\n3714: +```\n3715: +\n3716:  Library users can run the check up front with\n3717:  `(*core.CLab).CheckLabRuntimeSupport(ctx)` or the optional\n3718:  `labruntime.SupportChecker` interface; the error wraps\n3719:  `labruntime.ErrUnsupportedRuntimeVersion`.\n3720:  \n3721: @@ -579,10 +593,82 @@ containerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timest\n3722:  \n3723:  It reads the `pods/log` subresource of the node's pod, so RBAC must allow\n3724:  `get` on `pods/log`. Kubernetes returns stdout and stderr as one stream. See\n3725:  the [`logs` command](../../cmd/logs.md) for the flags.\n3726:  \n3727: +## Packet capture\n3728: +\n3729: +[`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of\n3730: +one or more nodes into one pcapng stream. Each node's pod runs the `clabwire`\n3731: +sidecar, which realized the node's links; containerlab execs its capture\n3732: +command (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.\n3733: +No capture service runs in the cluster, and nothing is captured outside the\n3734: +lab's planned link interfaces.\n3735: +\n3736: +```bash\n3737: +# both ends of a link, for 30 seconds\n3738: +containerlab -r c9s capture -t clos.clab.yml \\\n3739: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n3740: +\n3741: +# live in Wireshark until Wireshark or Ctrl+C ends it\n3742: +containerlab -r c9s capture --name clos --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n3743: +\n3744: +# what can be captured, with the peer of each link\n3745: +containerlab -r c9s capture --name clos --list\n3746: +```\n3747: +\n3748: +How it works:\n3749: +\n3750: +- containerlab locates each target node's pod and runs one `clabwire` capture\n3751: +  per node, with `--nodeName`, every requested interface of that node,\n3752: +  `--format pcapng` and `--stop-on-stdin-close`, with stdin attached.\n3753: +- The streams are merged into one section: one Interface Description Block per\n3754: +  target named `<node>:<interface>` (the node as the topology spells it),\n3755: +  written before the first packet, and the packets of every target with their\n3756: +  interface IDs remapped.\n3757: +- Packets are written in timestamp order. Each node's stream arrives over its\n3758: +  own exec stream, so the merged stream holds every packet for 250 ms and\n3759: +  writes the held packets ordered by timestamp. A packet that arrives later\n3760: +  than that, stamped before a packet already written, is written as it comes;\n3761: +  the number of such packets goes to the debug log.\n3762: +- `clabwire` limits one capture to one hour. Longer captures, and captures\n3763: +  without `--duration`, chain captures with a few seconds of overlap and switch\n3764: +  in the middle of it; packets near the switch are matched by content so each\n3765: +  is written once. A follow-up that does not start in time is reported as a\n3766: +  gap, with its time span.\n3767: +- `clabwire` audit records (JSON on its stderr, schema\n3768: +  `c9s.direct-packet-capture-audit/v1alpha1`) with status `Denied` or `Failed`\n3769: +  end the command with their reason. `Started` and `Succeeded` go to the debug\n3770: +  log.\n3771: +\n3772: +Interface names are the names inside the node; targets may also use the alias\n3773: +the topology used for an interface:\n3774: +\n3775: +| Kind | Interface | Alias |\n3776: +| ---- | --------- | ----- |\n3777: +| linux | `eth1` | |\n3778: +| SR Linux | `e1-1` | `ethernet-1/1` |\n3779: +| vr-sros / nokia_sros | `eth3` | `1/1/3` |\n3780: +\n3781: +The management interface and the pod's `c9s0` interface cannot be captured.\n3782: +\n3783: +Ctrl+C or SIGTERM ends a capture cleanly: the output stays a valid pcapng\n3784: +file and the command exits with code 0. Kubernetes does not stop a command\n3785: +when its exec stream closes, but it closes the command's stdin. containerlab\n3786: +closes the stdin of every `clabwire` capture when the capture ends for any\n3787: +reason (the duration or packet limit, Ctrl+C, an error, a failed write of the\n3788: +output such as a closed Wireshark, or a newer segment taking over), and\n3789: +`clabwire` then ends the capture within milliseconds. If the process does not\n3790: +end within three seconds, containerlab cuts the exec stream. A killed\n3791: +containerlab drops the connection, which closes stdin as well.\n3792: +\n3793: +Capturing needs `get` and `create` on `pods/exec` in the lab namespace, which\n3794: +`clabernetes-lab-editor` grants. `inspect interfaces -r c9s` lists the same\n3795: +interfaces, with the MAC address, index, MTU and operational state read from\n3796: +sysfs in the device container (type `veth`, which is how `clabwire` realizes\n3797: +lab links).\n3798: +\n3799:  ## Start, stop, and restart\n3800:  \n3801:  Node lifecycle commands ask the clabernetes controllers for a run state; they\n3802:  never touch Deployments or Pods.\n3803:  \n3804: @@ -863,16 +949,22 @@ implemented by the c9s runtime:\n3805:  | `NodeLocator` | `LocateNode(ctx, NodeRequest) ([]NodeLocation, error)` | the namespace, pod, primary device container, Node UID, exposed ports and LoadBalancer address of nodes |\n3806:  | `NodeAttacher` | `Attach(ctx, AttachRequest, AttachStreams) error` | an interactive exec with stdin, an optional TTY and a resize channel, in the device container or a chosen container |\n3807:  | `NodeLogStreamer` | `StreamLogs(ctx, LogRequest, io.Writer) error` | the device container log, with tail, follow and timestamps |\n3808:  | `NodePortForwarder` | `DialPort(ctx, NodeRequest, port) (net.Conn, error)` | a connection to a TCP port of the node's pod through `pods/portforward` (SSH, web UIs) |\n3809:  | `NodeStatsSampler` | `SampleStats(ctx, InspectRequest) ([]NodeStats, error)` | CPU and memory per node from `metrics.k8s.io` PodMetrics, summing the node's device containers; without the metrics API the error wraps `labruntime.ErrMetricsUnavailable` |\n3810: +| `PacketCapturer` | `CaptureInterfaces(ctx, NodeRequest) ([]CaptureInterface, error)` | the capturable link interfaces of nodes, with alias, peer node and peer interface |\n3811: +| `PacketCapturer` | `Capture(ctx, CaptureRequest, io.Writer) error` | one pcapng stream of the request's targets, for `Duration` (0: until ctx ends), `PacketLimit` and `SnapLength`; gaps go to `OnGap` |\n3812: +| `InterfaceInspector` | `InspectInterfaces(ctx, NodeRequest) ([]*types.ContainerInterfaces, error)` | the `inspect interfaces` view of the link interfaces |\n3813: +| `SupportChecker` | `CheckSupport(ctx, Identity) error` | the clabernetes release check |\n3814:  \n3815:  The `core` package wraps them per lab and node name, accepting the node name\n3816:  as the topology file spells it or as it was sanitized:\n3817:  `CLab.LocateLabRuntimeNodes`, `CLab.AttachLabRuntimeNode`,\n3818: -`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats` and\n3819: -`CLab.NodeLogs`, which also serves Docker and Podman.\n3820: +`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats`,\n3821: +`CLab.CaptureInterfaces`, `CLab.Capture`, `CLab.LabRuntimeInterfaces`,\n3822: +`CLab.CheckLabRuntimeSupport` and `CLab.NodeLogs`, which also serves Docker and\n3823: +Podman.\n3824:  \n3825:  ```go\n3826:  c, err := clabcore.NewContainerLab(\n3827:  \tclabcore.WithRuntime(\"c9s\", nil),\n3828:  \tclabcore.WithTopologyName(\"clos\"),\n3829: @@ -884,10 +976,18 @@ c, err := clabcore.NewContainerLab(\n3830:  if err != nil {\n3831:  \treturn err\n3832:  }\n3833:  \n3834:  conn, err := c.DialLabRuntimeNodePort(ctx, \"srl1\", 22)\n3835: +\n3836: +// stream pcapng to a websocket, a file or Wireshark until ctx ends\n3837: +err = c.Capture(ctx, clablabruntime.CaptureRequest{\n3838: +\tTargets: []clablabruntime.CaptureTarget{\n3839: +\t\t{Node: \"srl1\", Interface: \"ethernet-1/1\"},\n3840: +\t\t{Node: \"srl2\", Interface: \"e1-1\"},\n3841: +\t},\n3842: +}, w)\n3843:  ```\n3844:  \n3845:  ### Acting as a user\n3846:  \n3847:  A server that runs labs for many users acts as each user, so the cluster's RBAC\n3848: @@ -936,11 +1036,12 @@ to:\n3849:  - create, get, list, watch, and delete c9s `Link` and `NodeProfile` resources\n3850:  - get, list, watch, and delete `Topology` resources when Topology-based labs\n3851:    must remain manageable\n3852:  - list and watch Pods\n3853:  - create, get, list, update, and delete ConfigMaps used for local files\n3854: -- exec into device Pods with `pods/exec`\n3855: +- exec into device Pods with `pods/exec`, also for `capture` and `inspect\n3856: +  interfaces` (in the `clabwire` and device containers)\n3857:  - list and delete PersistentVolumeClaims for `destroy --cleanup`\n3858:  - read container logs with `pods/log` for `logs`\n3859:  - port-forward with `pods/portforward` for `NodePortForwarder`\n3860:  - list `pods.metrics.k8s.io` for `NodeStatsSampler`\n3861:  \n3862: @@ -1152,12 +1253,14 @@ Known command differences:\n3863:    `--export-template`, `--restore`, and `--restore-all` are rejected.\n3864:  - Destroy flags `--graceful` and `--keep-mgmt-net` are rejected. `--cleanup`\n3865:    also deletes the lab's persistent claims (saved device state) and removes\n3866:    the local lab directory; a plain destroy keeps the claims.\n3867:  - Local Docker commands on the outer host are not authoritative for c9s labs.\n3868: -- `inspect interfaces` is rejected. Host-side `tc` or netem operations do not\n3869: -  have the same local namespace access they have with Docker labs.\n3870: +- `inspect interfaces` lists only the lab link interfaces (those `capture`\n3871: +  accepts), not the management or pod interfaces. Host-side `tc` or netem\n3872: +  operations do not have the same local namespace access they have with Docker\n3873: +  labs.\n3874:  - `graph` renders from the topology file only: `--mermaid`, `--dot`, `--drawio`\n3875:    and `--offline` work, the default mode that reads running containers is\n3876:    rejected, and so is `--node-filter`. `--drawio` runs the clab-io-draw\n3877:    container, so it needs Docker or Podman on the outer host.\n3878:  - `tools` commands operate on local containers and host networking and are\n3879: diff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md\n3880: index b194b29..4654128 100644\n3881: --- a/docs/manual/wireshark.md\n3882: +++ b/docs/manual/wireshark.md\n3883: @@ -15,10 +15,16 @@ Every lab emulation software must provide its users with the packet capturing ab\n3884:  \n3885:  Containerlab offers a simple way to capture the packets from any interface of any node in the lab. This article will explain how to do that.\n3886:  \n3887:  ///tip\n3888:  \n3889: +The [`containerlab capture`](../cmd/capture.md) command captures one or more lab link interfaces, of one or more nodes, into one pcapng file or stream, with nothing to install in the nodes or on the host:\n3890: +\n3891: +```bash\n3892: +containerlab capture --name quickstart --target srl:e1-1 -w - | wireshark -k -i -\n3893: +```\n3894: +\n3895:  If you are looking for a free Web UI for packet capture with Wireshark, check out our [Edgeshark integration](#edgeshark-integration).\n3896:  ///\n3897:  \n3898:  Consider the following lab topology which highlights the typical points of packet capture.\n3899:  \n3900: diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go\n\n(Showing lines 3521-3900 of 7018. Use offset=3901 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.\n+\n+It works with every runtime:\n+\n+- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).\n+- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).\n+\n+The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.\n+\n+--8<-- \"docs/cmd/deploy.md:env-vars-flags\"\n+\n+### Usage\n+\n+`containerlab [global-flags] capture [local-flags]`\n+\n+### Flags\n+\n+#### topology | name\n+\n+Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.\n+\n+It works with every runtime:\n+\n+- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).\n+- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).\n+\n+The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.\n+\n+--8<-- \"docs/cmd/deploy.md:env-vars-flags\"\n+\n+### Usage\n+\n+`containerlab [global-flags] capture [local-flags]`\n+\n+### Flags\n+\n+#### topology | name\n+\n+Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.\n+\n+With Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.\n+\n+#### target\n+\n+The local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:\n+\n+```text\n+--target srl1:e1-1,e1-2 --target srl2:e1-1\n+```\n+\n+The node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.\n+\n+Only lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.\n+\n+#### duration\n+\n+The local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).\n+\n+#### packet-limit\n+\n+The local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.\n+\n+#### snap-length\n+\n+The local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.\n+\n+#### write\n+\n+The local `--write | -w` flag names the output file. The default `-` writes to stdout.\n+\n+#### list\n+\n+The local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.\n+\n+### Output\n+\n+The output is one pcapng section:\n+\n+- a Section Header Block with `shb_userappl` set to `containerlab`\n+- one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it\n+- Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes\n+\n+The interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.\n+\n+When the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.\n+\n+`--list -f json` prints an array:\n+\n+```json\n+[\n+  {\n+    \"node\": \"srl1\",\n+    \"interface\": \"e1-1\",\n+    \"alias\": \"ethernet-1/1\",\n+    \"peer_node\": \"srl2\",\n+    \"peer_interface\": \"ethernet-1/1\"\n+  }\n+]\n+```\n+\n+`alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.\n+\n+### How Docker and Podman captures work\n+\n+For each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.\n+\n+- Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.\n+- 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.\n+- Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.\n+- An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.\n+\n+The command needs root (to open packet sockets and enter network namespaces), as other lab commands do.\n+\n+### Long captures\n+\n+Docker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.\n+\n+### Examples\n+\n+#### Capture two nodes for 30 seconds into one file\n+\n+```bash\n+containerlab capture -t srl.clab.yml \\\n+  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n+```\n+\n+#### Watch a capture live in Wireshark\n+\n+```bash\n+containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n+```\n+\n+#### Capture the first 100 packets with tshark\n+\n+```bash\n+containerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -\n+```\n+\n+#### List the capturable interfaces\n+\n+```bash\n+containerlab capture --name srl --list\n+```\n+\n+#### Capture a c9s lab\n+\n+```bash\n+containerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng\n+```\ndiff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md\nindex 3dc8e27..2354dc1 100644\n--- a/docs/cmd/inspect/interfaces.md\n+++ b/docs/cmd/inspect/interfaces.md\n@@ -3,10 +3,12 @@\n ### Description\n \n The `inspect interfaces` subcommand provides information about the network interfaces of deployed nodes of a deployed lab.\n The subcommand gathers information directly from deployed containers, and displays information about their operational state, network interface type, and if applicable, the applied network interface alias.\n \n+With the [c9s runtime](../../manual/clabernetes/runtime.md#packet-capture), the listing covers the lab link interfaces of each running node, the ones [`capture`](../capture.md) accepts, with the alias the topology used, and the MAC address, index, MTU and operational state read in the node's device container. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields are the same as with Docker.\n+\n ### Usage\n \n `containerlab [global-flags] inspect interfaces [local-flags]`\n \n A shorthand can be used for this subcommand: `int` or `intf`.\ndiff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md\nindex 0ce708d..8174c98 100644\n--- a/docs/manual/clabernetes/runtime.md\n+++ b/docs/manual/clabernetes/runtime.md\n@@ -110,10 +110,13 @@ The c9s runtime currently supports the main lab lifecycle and node operations:\n | `start` | sets the node's `spec.runState` to `Running` |\n | `stop` | sets the node's `spec.runState` to `Stopped` |\n | `restart` | requests a Pod replacement with a `c9s.run/restart-requested` token |\n | `save` | runs the node's save lifecycle inside its device container |\n | `events` | watches Clabernetes resources and pods |\n+| `logs` | streams the device container log |\n+| `capture` | captures lab link interfaces through the `clabwire` sidecar into one pcapng stream |\n+| `inspect interfaces` | lists the capturable link interfaces with their sysfs state |\n | `validate` | checks c9s compatibility without creating Kubernetes resources |\n | `deploy --dry-run` | compiles and diffs Namespace, ConfigMap, NodeProfile, Link, and Node resources without changing them |\n | `deploy --emit-crs` | prints the Namespace, ConfigMap, and Topology (or NodeProfile, Link, and Node) manifests deploy would create, without contacting the cluster |\n \n ## Requirements\n@@ -141,11 +144,11 @@ Containerlab needs a clabernetes release that has:\n \n - Node run state: `nodes.c9s.run` `spec.runState` (`Running` | `Stopped`), the\n   `Stopped` condition, and restart requests through the\n   `c9s.run/restart-requested` annotation\n - the clabwire packet capture contract: `--nodeName`, repeated `--interface`,\n-  `--format pcapng` and `--list-interfaces`\n+  `--format pcapng`, `--list-interfaces` and `--stop-on-stdin-close`\n - the namespace-bindable `clabernetes-lab-viewer` and `clabernetes-lab-editor`\n   roles\n \n Both features ship in the same release, so containerlab checks one field: the\n published OpenAPI schema of `nodes.c9s.run` (`/openapi/v3/apis/c9s.run/v1alpha1`)\n@@ -159,10 +162,21 @@ an older release every other command fails like this:\n the clabernetes release on this cluster is not supported: nodes.c9s.run has no\n spec.runState (Node run state); the c9s runtime needs clabernetes with Node run\n state and the clabwire capture contract (0.11 or newer)\n ```\n \n+A cluster that passes this check but runs a `clabwire` without\n+`--stop-on-stdin-close` (a development build between the two features) fails\n+the first capture with the same kind of error, naming the pod:\n+\n+```text\n+the clabernetes release on this cluster is not supported: clabwire in pod\n+<namespace>/<pod> does not accept packet-capture --stop-on-stdin-close; the c9s\n+runtime needs clabernetes with Node run state and the clabwire capture contract\n+(0.11 or newer)\n+```\n+\n Library users can run the check up front with\n `(*core.CLab).CheckLabRuntimeSupport(ctx)` or the optional\n `labruntime.SupportChecker` interface; the error wraps\n `labruntime.ErrUnsupportedRuntimeVersion`.\n \n@@ -579,10 +593,82 @@ containerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timest\n \n It reads the `pods/log` subresource of the node's pod, so RBAC must allow\n `get` on `pods/log`. Kubernetes returns stdout and stderr as one stream. See\n the [`logs` command](../../cmd/logs.md) for the flags.\n \n+## Packet capture\n+\n+[`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of\n+one or more nodes into one pcapng stream. Each node's pod runs the `clabwire`\n+sidecar, which realized the node's links; containerlab execs its capture\n+command (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.\n+No capture service runs in the cluster, and nothing is captured outside the\n+lab's planned link interfaces.\n+\n+```bash\n+# both ends of a link, for 30 seconds\n+containerlab -r c9s capture -t clos.clab.yml \\\n+  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n+\n+# live in Wireshark until Wireshark or Ctrl+C ends it\n+containerlab -r c9s capture --name clos --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n+\n+# what can be captured, with the peer of each link\n+containerlab -r c9s capture --name clos --list\n+```\n+\n+How it works:\n+\n+- containerlab locates each target node's pod and runs one `clabwire` capture\n+  per node, with `--nodeName`, every requested interface of that node,\n+  `--format pcapng` and `--stop-on-stdin-close`, with stdin attached.\n+- The streams are merged into one section: one Interface Description Block per\n+  target named `<node>:<interface>` (the node as the topology spells it),\n+  written before the first packet, and the packets of every target with their\n+  interface IDs remapped.\n+- Packets are written in timestamp order. Each node's stream arrives over its\n+  own exec stream, so the merged stream holds every packet for 250 ms and\n+  writes the held packets ordered by timestamp. A packet that arrives later\n+  than that, stamped before a packet already written, is written as it comes;\n+  the number of such packets goes to the debug log.\n+- `clabwire` limits one capture to one hour. Longer captures, and captures\n+  without `--duration`, chain captures with a few seconds of overlap and switch\n+  in the middle of it; packets near the switch are matched by content so each\n+  is written once. A follow-up that does not start in time is reported as a\n+  gap, with its time span.\n+- `clabwire` audit records (JSON on its stderr, schema\n+  `c9s.direct-packet-capture-audit/v1alpha1`) with status `Denied` or `Failed`\n+  end the command with their reason. `Started` and `Succeeded` go to the debug\n+  log.\n+\n+Interface names are the names inside the node; targets may also use the alias\n+the topology used for an interface:\n+\n+| Kind | Interface | Alias |\n+| ---- | --------- | ----- |\n+| linux | `eth1` | |\n+| SR Linux | `e1-1` | `ethernet-1/1` |\n+| vr-sros / nokia_sros | `eth3` | `1/1/3` |\n+\n+The management interface and the pod's `c9s0` interface cannot be captured.\n+\n+Ctrl+C or SIGTERM ends a capture cleanly: the output stays a valid pcapng\n+file and the command exits with code 0. Kubernetes does not stop a command\n+when its exec stream closes, but it closes the command's stdin. containerlab\n+closes the stdin of every `clabwire` capture when the capture ends for any\n+reason (the duration or packet limit, Ctrl+C, an error, a failed write of the\n+output such as a closed Wireshark, or a newer segment taking over), and\n+`clabwire` then ends the capture within milliseconds. If the process does not\n+end within three seconds, containerlab cuts the exec stream. A killed\n+containerlab drops the connection, which closes stdin as well.\n+\n+Capturing needs `get` and `create` on `pods/exec` in the lab namespace, which\n+`clabernetes-lab-editor` grants. `inspect interfaces -r c9s` lists the same\n+interfaces, with the MAC address, index, MTU and operational state read from\n+sysfs in the device container (type `veth`, which is how `clabwire` realizes\n+lab links).\n+\n ## Start, stop, and restart\n \n Node lifecycle commands ask the clabernetes controllers for a run state; they\n never touch Deployments or Pods.\n \n@@ -863,16 +949,22 @@ implemented by the c9s runtime:\n | `NodeLocator` | `LocateNode(ctx, NodeRequest) ([]NodeLocation, error)` | the namespace, pod, primary device container, Node UID, exposed ports and LoadBalancer address of nodes |\n | `NodeAttacher` | `Attach(ctx, AttachRequest, AttachStreams) error` | an interactive exec with stdin, an optional TTY and a resize channel, in the device container or a chosen container |\n | `NodeLogStreamer` | `StreamLogs(ctx, LogRequest, io.Writer) error` | the device container log, with tail, follow and timestamps |\n | `NodePortForwarder` | `DialPort(ctx, NodeRequest, port) (net.Conn, error)` | a connection to a TCP port of the node's pod through `pods/portforward` (SSH, web UIs) |\n | `NodeStatsSampler` | `SampleStats(ctx, InspectRequest) ([]NodeStats, error)` | CPU and memory per node from `metrics.k8s.io` PodMetrics, summing the node's device containers; without the metrics API the error wraps `labruntime.ErrMetricsUnavailable` |\n+| `PacketCapturer` | `CaptureInterfaces(ctx, NodeRequest) ([]CaptureInterface, error)` | the capturable link interfaces of nodes, with alias, peer node and peer interface |\n+| `PacketCapturer` | `Capture(ctx, CaptureRequest, io.Writer) error` | one pcapng stream of the request's targets, for `Duration` (0: until ctx ends), `PacketLimit` and `SnapLength`; gaps go to `OnGap` |\n+| `InterfaceInspector` | `InspectInterfaces(ctx, NodeRequest) ([]*types.ContainerInterfaces, error)` | the `inspect interfaces` view of the link interfaces |\n+| `SupportChecker` | `CheckSupport(ctx, Identity) error` | the clabernetes release check |\n \n The `core` package wraps them per lab and node name, accepting the node name\n as the topology file spells it or as it was sanitized:\n `CLab.LocateLabRuntimeNodes`, `CLab.AttachLabRuntimeNode`,\n-`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats` and\n-`CLab.NodeLogs`, which also serves Docker and Podman.\n+`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats`,\n+`CLab.CaptureInterfaces`, `CLab.Capture`, `CLab.LabRuntimeInterfaces`,\n+`CLab.CheckLabRuntimeSupport` and `CLab.NodeLogs`, which also serves Docker and\n+Podman.\n \n ```go\n c, err := clabcore.NewContainerLab(\n \tclabcore.WithRuntime(\"c9s\", nil),\n \tclabcore.WithTopologyName(\"clos\"),\n@@ -884,10 +976,18 @@ c, err := clabcore.NewContainerLab(\n if err != nil {\n \treturn err\n }\n \n conn, err := c.DialLabRuntimeNodePort(ctx, \"srl1\", 22)\n+\n+// stream pcapng to a websocket, a file or Wireshark until ctx ends\n+err = c.Capture(ctx, clablabruntime.CaptureRequest{\n+\tTargets: []clablabruntime.CaptureTarget{\n+\t\t{Node: \"srl1\", Interface: \"ethernet-1/1\"},\n+\t\t{Node: \"srl2\", Interface: \"e1-1\"},\n+\t},\n+}, w)\n ```\n \n ### Acting as a user\n \n A server that runs labs for many users acts as each user, so the cluster's RBAC\n@@ -936,11 +1036,12 @@ to:\n - create, get, list, watch, and delete c9s `Link` and `NodeProfile` resources\n - get, list, watch, and delete `Topology` resources when Topology-based labs\n   must remain manageable\n - list and watch Pods\n - create, get, list, update, and delete ConfigMaps used for local files\n-- exec into device Pods with `pods/exec`\n+- exec into device Pods with `pods/exec`, also for `capture` and `inspect\n+  interfaces` (in the `clabwire` and device containers)\n - list and delete PersistentVolumeClaims for `destroy --cleanup`\n - read container logs with `pods/log` for `logs`\n - port-forward with `pods/portforward` for `NodePortForwarder`\n - list `pods.metrics.k8s.io` for `NodeStatsSampler`\n \n@@ -1152,12 +1253,14 @@ Known command differences:\n   `--export-template`, `--restore`, and `--restore-all` are rejected.\n - Destroy flags `--graceful` and `--keep-mgmt-net` are rejected. `--cleanup`\n   also deletes the lab's persistent claims (saved device state) and removes\n   the local lab directory; a plain destroy keeps the claims.\n - Local Docker commands on the outer host are not authoritative for c9s labs.\n-- `inspect interfaces` is rejected. Host-side `tc` or netem operations do not\n-  have the same local namespace access they have with Docker labs.\n+- `inspect interfaces` lists only the lab link interfaces (those `capture`\n+  accepts), not the management or pod interfaces. Host-side `tc` or netem\n+  operations do not have the same local namespace access they have with Docker\n+  labs.\n - `graph` renders from the topology file only: `--mermaid`, `--dot`, `--drawio`\n   and `--offline` work, the default mode that reads running containers is\n   rejected, and so is `--node-filter`. `--drawio` runs the clab-io-draw\n   container, so it needs Docker or Podman on the outer host.\n - `tools` commands operate on local containers and host networking and are\ndiff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md\nindex b194b29..4654128 100644\n--- a/docs/manual/wireshark.md\n+++ b/docs/manual/wireshark.md\n@@ -15,10 +15,16 @@ Every lab emulation software must provide its users with the packet capturing ab\n \n Containerlab offers a simple way to capture the packets from any interface of any node in the lab. This article will explain how to do that.\n \n ///tip\n \n+The [`containerlab capture`](../cmd/capture.md) command captures one or more lab link interfaces, of one or more nodes, into one pcapng file or stream, with nothing to install in the nodes or on the host:\n+\n+```bash\n+containerlab capture --name quickstart --target srl:e1-1 -w - | wireshark -k -i -\n+```\n+\n If you are looking for a free Web UI for packet capture with Wireshark, check out our [Edgeshark integration](#edgeshark-integration).\n ///\n \n Consider the following lab topology which highlights the typical points of packet capture.\n \ndiff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go",
        "lineStart": 3521,
        "lineEnd": 3900,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523345477,
      "end": 1793523345493
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196526858001jdnvGIyoY66qWO",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196525bfc001zLWkm9tE0OVysO",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 35243,
    "input": 32230,
    "output": 27,
    "reasoning": 106,
    "cache": {
      "read": 2880,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196525bfc001zLWkm9tE0OVysO",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523342332,
    "completed": 1793523345500
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 35243,
    "input": 32230,
    "output": 27,
    "reasoning": 106,
    "cache": {
      "read": 2880,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 29
step-start
{
  "type": "step-start",
  "id": "prt_19652702f001w3o0oFIkyqfb16",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196526863001CoB4SCcGn05S5b"
}
Reasoning
Now the c9s capture.go full file (1202 lines) — I read much of it in the prior session per the summary. Let me re-verify the key sections by reading the head file in chunks, focusing on correctness-critical parts: `captureChain` (run/handle/switchSegments/setCut/startNext/stop/drain), `segment` (audit handling, stdin close, stream cutting), `merge` (remap, reorder), and `CaptureInterfaces`.

Let me read /source/head/labruntime/clabernetes/capture.go in a few chunks.
Now let me read the full c9s capture implementation to verify the chain state machine and merge logic.
read · completed

Input

{
  "filePath": "/source/head/labruntime/clabernetes/capture.go",
  "limit": 620,
  "offset": 60
}

Output

<path>/source/head/labruntime/clabernetes/capture.go</path>
<type>file</type>
<content>
60: 
61: 	// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests
62: 	// without hour-long captures.
63: 	envCaptureSegment = "CLAB_C9S_CAPTURE_SEGMENT"
64: 	// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets
65: 	// of other nodes stamped earlier but delivered later still go out before it.
66: 	defaultCaptureReorderWindow = 250 * time.Millisecond
67: 	// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.
68: 	// It is an internal knob, not a supported setting.
69: 	envCaptureReorderWindow = "CLAB_C9S_CAPTURE_REORDER_WINDOW"
70: )
71: 
72: // podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns
73: // a *labruntime.CommandExitError.
74: type podExecFunc func(
75: 	ctx context.Context,
76: 	namespace, pod, container string,
77: 	command []string,
78: 	stdin io.Reader,
79: 	stdout, stderr io.Writer,
80: ) error
81: 
82: // clabwireInterface is one entry of `packet-capture --list-interfaces`.
83: type clabwireInterface struct {
84: 	Node          string `json:"node"`
85: 	Interface     string `json:"interface"`
86: 	Alias         string `json:"alias,omitempty"`
87: 	PeerNode      string `json:"peerNode"`
88: 	PeerInterface string `json:"peerInterface"`
89: }
90: 
91: // captureAudit is one clabwire audit line.
92: type captureAudit struct {
93: 	SchemaVersion string    `json:"schemaVersion"`
94: 	Time          time.Time `json:"time"`
95: 	Status        string    `json:"status"`
96: 	NodeName      string    `json:"nodeName"`
97: 	Format        string    `json:"format"`
98: 	Reason        string    `json:"reason"`
99: 	Packets       int       `json:"packets"`
100: 	Interfaces    []struct {
101: 		Name    string `json:"name"`
102: 		ID      string `json:"id"`
103: 		Packets int    `json:"packets"`
104: 	} `json:"interfaces"`
105: }
106: 
107: func (r *Runtime) execInPodContainer() podExecFunc {
108: 	if r.podExec != nil {
109: 		return r.podExec
110: 	}
111: 
112: 	return r.streamPodExec
113: }
114: 
115: // captureSegmentLength is the length of one clabwire capture before the next takes over.
116: func (r *Runtime) captureSegmentLength() time.Duration {
117: 	if r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {
118: 		return r.captureSegment
119: 	}
120: 
121: 	return maxCaptureSegment
122: }
123: 
124: // captureReorderWindowLength is the reorder window of the merged stream; zero disables
125: // reordering.
126: func (r *Runtime) captureReorderWindowLength() time.Duration {
127: 	switch {
128: 	case r.captureReorderWindow < 0:
129: 		return 0
130: 	case r.captureReorderWindow > 0:
131: 		return r.captureReorderWindow
132: 	}
133: 
134: 	return defaultCaptureReorderWindow
135: }
136: 
137: // captureReorderWindowFromEnv reads the reorder window knob: unset or invalid keeps the
138: // default (0), "0" disables reordering (-1).
139: func captureReorderWindowFromEnv() time.Duration {
140: 	value, err := time.ParseDuration(os.Getenv(envCaptureReorderWindow))
141: 	switch {
142: 	case err != nil || value < 0:
143: 		return 0
144: 	case value == 0:
145: 		return -1
146: 	}
147: 
148: 	return value
149: }
150: 
151: func captureSegmentFromEnv() time.Duration {
152: 	value, err := time.ParseDuration(os.Getenv(envCaptureSegment))
153: 	if err != nil || value <= 0 {
154: 		return 0
155: 	}
156: 
157: 	return value
158: }
159: 
160: // CaptureInterfaces lists the capturable lab link interfaces of the requested nodes, or of every
161: // node, as clabwire reports them, with their peers. Node names are reported as the topology
162: // spells them.
163: func (r *Runtime) CaptureInterfaces(
164: 	ctx context.Context,
165: 	req clablabruntime.NodeRequest,
166: ) ([]clablabruntime.CaptureInterface, error) {
167: 	r, err := r.connect(ctx, req.Identity)
168: 	if err != nil {
169: 		return nil, err
170: 	}
171: 
172: 	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{
173: 		Name: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,
174: 	})
175: 	if err != nil {
176: 		return nil, err
177: 	}
178: 	if len(req.Nodes) == 0 {
179: 		// a lab-wide listing skips nodes that do not run
180: 		running := locations[:0]
181: 		for _, location := range locations {
182: 			if location.Pod != "" {
183: 				running = append(running, location)
184: 			}
185: 		}
186: 		locations = running
187: 	}
188: 
189: 	listed, err := r.listCaptureInterfaces(ctx, req.Name, locations)
190: 	if err != nil {
191: 		return nil, err
192: 	}
193: 	names, err := r.nodeDisplayNames(ctx, req.Name, locations)
194: 	if err != nil {
195: 		return nil, err
196: 	}
197: 
198: 	result := make([]clablabruntime.CaptureInterface, 0)
199: 	for _, location := range locations {
200: 		for _, entry := range listed[location.NodeName] {
201: 			result = append(result, clablabruntime.CaptureInterface{
202: 				Node:          names.display(entry.Node),
203: 				Interface:     entry.Interface,
204: 				Alias:         entry.Alias,
205: 				PeerNode:      names.display(entry.PeerNode),
206: 				PeerInterface: entry.PeerInterface,
207: 			})
208: 		}
209: 	}
210: 	sort.SliceStable(result, func(i, j int) bool {
211: 		if result[i].Node != result[j].Node {
212: 			return result[i].Node < result[j].Node
213: 		}
214: 
215: 		return result[i].Interface < result[j].Interface
216: 	})
217: 
218: 	return result, nil
219: }
220: 
221: // listCaptureInterfaces runs one --list-interfaces per pod and returns the entries per Node.
222: func (r *Runtime) listCaptureInterfaces(
223: 	ctx context.Context,
224: 	lab string,
225: 	locations []clablabruntime.NodeLocation,
226: ) (map[string][]clabwireInterface, error) {
227: 	pods := map[string]clablabruntime.NodeLocation{}
228: 	wanted := map[string]bool{}
229: 	for _, location := range locations {
230: 		if location.Pod == "" {
231: 			return nil, fmt.Errorf("c9s node %s/%s/%s has no pod; is it running?",
232: 				location.Namespace, lab, location.NodeName)
233: 		}
234: 		pods[location.Namespace+"/"+location.Pod] = location
235: 		wanted[location.NodeName] = true
236: 	}
237: 
238: 	var mu sync.Mutex
239: 	result := map[string][]clabwireInterface{}
240: 	group, groupCtx := errgroup.WithContext(ctx)
241: 	group.SetLimit(interfaceSampleWorkers)
242: 	exec := r.execInPodContainer()
243: 	for _, location := range pods {
244: 		group.Go(func() error {
245: 			var stdout, stderr bytes.Buffer
246: 			err := exec(groupCtx, location.Namespace, location.Pod, clabwireContainer,
247: 				[]string{clabwireManager, "node-runtime", "packet-capture", "--list-interfaces"},
248: 				nil, &stdout, &stderr)
249: 			if err != nil {
250: 				return fmt.Errorf("failed to list the capturable interfaces of pod %s/%s: %w%s",
251: 					location.Namespace, location.Pod, err, stderrSuffix(stderr.Bytes()))
252: 			}
253: 
254: 			var entries []clabwireInterface
255: 			if err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {
256: 				return fmt.Errorf("failed to parse the capturable interfaces of pod %s/%s: %w",
257: 					location.Namespace, location.Pod, err)
258: 			}
259: 
260: 			mu.Lock()
261: 			defer mu.Unlock()
262: 			for _, entry := range entries {
263: 				if wanted[entry.Node] {
264: 					result[entry.Node] = append(result[entry.Node], entry)
265: 				}
266: 			}
267: 
268: 			return nil
269: 		})
270: 	}
271: 	if err := group.Wait(); err != nil {
272: 		return nil, err
273: 	}
274: 
275: 	return result, nil
276: }
277: 
278: func stderrSuffix(stderr []byte) string {
279: 	text := strings.TrimSpace(string(stderr))
280: 	if text == "" {
281: 		return ""
282: 	}
283: 
284: 	return ": " + text
285: }
286: 
287: // nodeNames maps the node names the cluster carries to the names the topology file uses.
288: type nodeNames map[string]string
289: 
290: func (n nodeNames) display(name string) string {
291: 	if original := n[name]; original != "" {
292: 		return original
293: 	}
294: 
295: 	return name
296: }
297: 
298: // nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the
299: // lab's Nodes.
300: func (r *Runtime) nodeDisplayNames(
301: 	ctx context.Context,
302: 	lab string,
303: 	locations []clablabruntime.NodeLocation,
304: ) (nodeNames, error) {
305: 	names := nodeNames{}
306: 	if len(locations) == 0 {
307: 		return names, nil
308: 	}
309: 
310: 	nodes, err := r.nodesForTopology(ctx, lab, locations[0].Namespace)
311: 	if err != nil {
312: 		return nil, err
313: 	}
314: 	for idx := range nodes.Items {
315: 		if original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != "" {
316: 			names[nodes.Items[idx].GetName()] = original
317: 		}
318: 	}
319: 
320: 	return names, nil
321: }
322: 
323: // captureGroup is the part of a capture one clabwire process serves: the requested interfaces of
324: // one node, in one pod.
325: type captureGroup struct {
326: 	location clablabruntime.NodeLocation
327: 	display  string
328: 	// interfaces are the planned interface names, in the order the merged stream lists them.
329: 	interfaces []string
330: 	// ids are the merged interface IDs of interfaces.
331: 	ids []uint32
332: }
333: 
334: // resolvedCapture is a validated capture request.
335: type resolvedCapture struct {
336: 	groups []*captureGroup
337: 	// names are the merged interface names (<node>:<interface>), indexed by merged ID.
338: 	names []string
339: }
340: 
341: // resolveCaptureTargets locates every target node, checks every interface against the
342: // interfaces clabwire allows, and groups the targets per node.
343: func (r *Runtime) resolveCaptureTargets(
344: 	ctx context.Context,
345: 	req clablabruntime.CaptureRequest,
346: ) (*resolvedCapture, error) {
347: 	nodeOrder := make([]string, 0, len(req.Targets))
348: 	seenNodes := map[string]bool{}
349: 	for _, target := range req.Targets {
350: 		if !seenNodes[target.Node] {
351: 			seenNodes[target.Node] = true
352: 			nodeOrder = append(nodeOrder, target.Node)
353: 		}
354: 	}
355: 
356: 	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{
357: 		Name: req.Name, Namespace: req.Namespace, Nodes: nodeOrder, Identity: req.Identity,
358: 	})
359: 	if err != nil {
360: 		return nil, err
361: 	}
362: 	byRequest := make(map[string]clablabruntime.NodeLocation, len(nodeOrder))
363: 	for idx, name := range nodeOrder {
364: 		byRequest[name] = locations[idx]
365: 	}
366: 
367: 	listed, err := r.listCaptureInterfaces(ctx, req.Name, locations)
368: 	if err != nil {
369: 		return nil, err
370: 	}
371: 	names, err := r.nodeDisplayNames(ctx, req.Name, locations)
372: 	if err != nil {
373: 		return nil, err
374: 	}
375: 
376: 	resolved := &resolvedCapture{}
377: 	groups := map[string]*captureGroup{}
378: 	seen := map[string]bool{}
379: 	for _, target := range req.Targets {
380: 		location := byRequest[target.Node]
381: 		entry, ok := findCaptureInterface(listed[location.NodeName], target.Interface)
382: 		if !ok {
383: 			return nil, fmt.Errorf("interface %q of node %q is not a capturable link "+
384: 				"interface; capturable: %s", target.Interface, target.Node,
385: 				describeCaptureInterfaces(listed[location.NodeName]))
386: 		}
387: 
388: 		key := location.NodeName + "\x00" + entry.Interface
389: 		if seen[key] {
390: 			return nil, fmt.Errorf("interface %q of node %q is requested more than once",
391: 				entry.Interface, target.Node)
392: 		}
393: 		seen[key] = true
394: 
395: 		group := groups[location.NodeName]
396: 		if group == nil {
397: 			group = &captureGroup{
398: 				location: location,
399: 				display:  names.display(location.NodeName),
400: 			}
401: 			groups[location.NodeName] = group
402: 			resolved.groups = append(resolved.groups, group)
403: 		}
404: 
405: 		id := uint32(len(resolved.names)) //nolint:gosec // bounded by the targets
406: 		group.interfaces = append(group.interfaces, entry.Interface)
407: 		group.ids = append(group.ids, id)
408: 		resolved.names = append(resolved.names, group.display+":"+entry.Interface)
409: 	}
410: 
411: 	return resolved, nil
412: }
413: 
414: // findCaptureInterface matches a requested interface by its planned name or its alias.
415: func findCaptureInterface(entries []clabwireInterface, name string) (clabwireInterface, bool) {
416: 	for _, entry := range entries {
417: 		if entry.Interface == name {
418: 			return entry, true
419: 		}
420: 	}
421: 	for _, entry := range entries {
422: 		if entry.Alias != "" && entry.Alias == name {
423: 			return entry, true
424: 		}
425: 	}
426: 
427: 	return clabwireInterface{}, false
428: }
429: 
430: func describeCaptureInterfaces(entries []clabwireInterface) string {
431: 	if len(entries) == 0 {
432: 		return "none"
433: 	}
434: 
435: 	names := make([]string, 0, len(entries))
436: 	for _, entry := range entries {
437: 		name := entry.Interface
438: 		if entry.Alias != "" {
439: 			name += " (" + entry.Alias + ")"
440: 		}
441: 		names = append(names, name)
442: 	}
443: 
444: 	return strings.Join(names, ", ")
445: }
446: 
447: // Capture streams pcapng from lab link interfaces to w: one section, one Interface Description
448: // Block per target in request order named <node>:<interface>, then the packets of every target.
449: //
450: // Each node's interfaces are captured by one clabwire process in the node's pod. clabwire limits
451: // a capture to one hour, so a longer capture (or one without Duration) chains captures: the next
452: // one starts before the current one ends, and the stream switches at a cut in the overlap. See
453: // captureChain for how packets of the overlap are kept once.
454: //
455: // Packets go out in timestamp order across nodes, through a reorder buffer (captureReorder).
456: //
457: // Every clabwire process runs with stdin attached and --stop-on-stdin-close: a Kubernetes exec
458: // does not stop its process when the stream closes, so containerlab closes stdin whenever a
459: // segment ends (the capture ends, fails, its output fails, or a newer segment took over) and
460: // clabwire ends the capture itself.
461: //
462: // Capture returns when Duration has passed, PacketLimit packets were written, or ctx ends; an
463: // ended ctx is not an error. Every block reaches w in one write, so the stream is a valid capture
464: // whenever it stops. A clabwire Denied or Failed audit record is returned as an error.
465: func (r *Runtime) Capture(
466: 	ctx context.Context,
467: 	req clablabruntime.CaptureRequest,
468: 	w io.Writer,
469: ) error {
470: 	if err := clabcapture.ValidateRequest(&req); err != nil {
471: 		return err
472: 	}
473: 
474: 	r, err := r.connect(ctx, req.Identity)
475: 	if err != nil {
476: 		return err
477: 	}
478: 
479: 	resolved, err := r.resolveCaptureTargets(ctx, req)
480: 	if err != nil {
481: 		return err
482: 	}
483: 
484: 	captureCtx, stop := context.WithCancel(ctx)
485: 	defer stop()
486: 
487: 	out, err := clabcapture.NewOutput(w, resolved.names, req.SnapLength, req.PacketLimit,
488: 		r.captureReorderWindowLength(), stop)
489: 	if err != nil {
490: 		return err
491: 	}
492: 
493: 	run := &captureRun{
494: 		r:       r,
495: 		req:     req,
496: 		out:     out,
497: 		segment: r.captureSegmentLength(),
498: 	}
499: 	if req.Duration > 0 {
500: 		run.deadline = time.Now().Add(req.Duration)
501: 	}
502: 	run.overlap = min(maxCaptureOverlap, run.segment/3)
503: 	run.window = min(maxCaptureCutWindow, run.overlap/4)
504: 
505: 	if req.Duration > 0 {
506: 		// a clabwire process that does not end on its own does not hold the capture open
507: 		var cancelTimeout context.CancelFunc
508: 		captureCtx, cancelTimeout = context.WithTimeout(captureCtx,
509: 			req.Duration+run.overlap+captureEndGrace)
510: 		defer cancelTimeout()
511: 	}
512: 
513: 	group, groupCtx := errgroup.WithContext(captureCtx)
514: 	for _, captureGroup := range resolved.groups {
515: 		chain := &captureChain{capture: run, group: captureGroup}
516: 		group.Go(func() error {
517: 			return chain.run(groupCtx)
518: 		})
519: 	}
520: 
521: 	err = group.Wait()
522: 	if writeErr := out.Close(); writeErr != nil {
523: 		return writeErr
524: 	}
525: 	if err != nil && !(errors.Is(err, context.Canceled) && captureCtx.Err() != nil) {
526: 		return err
527: 	}
528: 
529: 	return nil
530: }
531: 
532: // captureRun is the state a capture's chains share.
533: type captureRun struct {
534: 	r   *Runtime
535: 	req clablabruntime.CaptureRequest
536: 	// out is the merged stream; it writes the packets of every chain in timestamp order and
537: 	// stops every chain once the packet limit is reached.
538: 	out *clabcapture.Output
539: 
540: 	segment  time.Duration
541: 	overlap  time.Duration
542: 	window   time.Duration
543: 	deadline time.Time
544: }
545: 
546: // emit writes a packet under its merged interface ID. It reports false once the packet limit is
547: // reached and the capture stops.
548: func (run *captureRun) emit(id uint32, packet *clabcapture.Packet) (bool, error) {
549: 	return run.out.Emit(id, packet)
550: }
551: 
552: func (run *captureRun) reportGap(gap clablabruntime.CaptureGap) {
553: 	clabcapture.ReportGap(run.req.OnGap, gap)
554: }
555: 
556: // captureSegment is one clabwire capture process of a chain.
557: type captureSegment struct {
558: 	index      int
559: 	localStart time.Time
560: 	duration   time.Duration
561: 	cancel     context.CancelFunc
562: 	// closeStdin closes the stdin of the segment's clabwire process, which ends it; it may be
563: 	// called any number of times.
564: 	closeStdin func()
565: 	// stopTimer closes stdin once the segment is no longer needed after a switch-over.
566: 	stopTimer *time.Timer
567: 	// started and ended are the pod-clock times of the Started and Succeeded audit records.
568: 	started time.Time
569: 	ended   time.Time
570: 	done    bool
571: }
572: 
573: func (s *captureSegment) plannedEnd() time.Time {
574: 	return s.started.Add(s.duration)
575: }
576: 
577: // segmentEvent is something a segment reported: a packet, an audit record, or its end.
578: type segmentEvent struct {
579: 	segment *captureSegment
580: 	packet  *clabcapture.Packet
581: 	audit   *captureAudit
582: 	done    bool
583: 	err     error
584: }
585: 
586: // captureChain runs the chained clabwire captures of one group.
587: //
588: // Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both
589: // capture the same packets for a while. clabwire stamps packets when it reads them, so two
590: // processes give the same packet timestamps a few microseconds apart, and timestamps alone
591: // cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by
592: // content close to the cut:
593: //
594: //  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is
595: //     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.
596: //  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the
597: //     content of what it wrote since segment k+1 started.
598: //  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped
599: //     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped
600: //     when segment k wrote the same bytes on the same interface, and every other one is written.
601: //     From then on segment k+1 streams live.
602: //
603: // Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its
604: // planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other
605: // nodes' later packets do not overtake them in the merged stream.
606: //
607: // W (500 ms, less for short test segments) covers the stamping difference. Identical frames on
608: // the same interface within W of the cut can be paired with each other, which can drop a true
609: // repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves
610: // a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.
611: type captureChain struct {
612: 	capture *captureRun
613: 	group   *captureGroup
614: 
615: 	events chan segmentEvent
616: 	wg     sync.WaitGroup
617: 
618: 	active *captureSegment
619: 	next   *captureSegment
620: 	// cut is the switch time between active and next, in nanoseconds; zero until known.
621: 	cut int64
622: 	// emitted remembers the content of the packets active wrote while next runs.
623: 	emitted map[uint64]int
624: 	// held are the packets of next until active ends.
625: 	held     []*clabcapture.Packet
626: 	segments int
627: 	retries  int
628: 	// final is set once no further segment is due.
629: 	final bool
630: 	// stopping is set once ctx ended: the segments are asked to end and what they still
631: 	// deliver is written.
632: 	stopping bool
633: }
634: 
635: // run runs the chain until its last segment ended. When ctx ends, it stops the segments and
636: // keeps writing the packets they read until then; a segment that does not end within
637: // captureStdinCloseGrace is cut.
638: func (c *captureChain) run(ctx context.Context) error {
639: 	c.events = make(chan segmentEvent, 256)
640: 	// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them
641: 	segmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
642: 	var abort *time.Timer
643: 	defer func() {
644: 		if abort != nil {
645: 			abort.Stop()
646: 		}
647: 		cancel()
648: 		c.drain()
649: 		c.capture.out.Release(c)
650: 	}()
651: 
652: 	c.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))
653: 	timer := time.NewTimer(c.nextStartIn())
654: 	defer timer.Stop()
655: 
656: 	done := ctx.Done()
657: 	for {
658: 		select {
659: 		case <-done:
660: 			done = nil
661: 			c.stop(timer)
662: 			abort = time.AfterFunc(captureStdinCloseGrace, cancel)
663: 		case <-segmentsCtx.Done():
664: 			return nil
665: 		case <-timer.C:
666: 			if c.next == nil && !c.final {
667: 				c.startNext(segmentsCtx)
668: 			}
669: 		case event := <-c.events:
670: 			stop, err := c.handle(segmentsCtx, event, timer)
671: 			if err != nil || stop {
672: 				return err
673: 			}
674: 		}
675: 	}
676: }
677: 
678: // stop ends the chain early, like a deadline would: no further segment starts and the running
679: // ones are asked to end. The chain then writes what they deliver until they ended.

(Showing lines 60-679 of 1202. Use offset=680 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1965275d5001yhAnZ3tJwaYMa6",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196526863001CoB4SCcGn05S5b",
  "callID": "call_c97f56cf606743f0a6e4d7b4",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/capture.go",
      "limit": 620,
      "offset": 60
    },
    "output": "<path>/source/head/labruntime/clabernetes/capture.go</path>\n<type>file</type>\n<content>\n60: \n61: \t// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests\n62: \t// without hour-long captures.\n63: \tenvCaptureSegment = \"CLAB_C9S_CAPTURE_SEGMENT\"\n64: \t// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets\n65: \t// of other nodes stamped earlier but delivered later still go out before it.\n66: \tdefaultCaptureReorderWindow = 250 * time.Millisecond\n67: \t// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.\n68: \t// It is an internal knob, not a supported setting.\n69: \tenvCaptureReorderWindow = \"CLAB_C9S_CAPTURE_REORDER_WINDOW\"\n70: )\n71: \n72: // podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns\n73: // a *labruntime.CommandExitError.\n74: type podExecFunc func(\n75: \tctx context.Context,\n76: \tnamespace, pod, container string,\n77: \tcommand []string,\n78: \tstdin io.Reader,\n79: \tstdout, stderr io.Writer,\n80: ) error\n81: \n82: // clabwireInterface is one entry of `packet-capture --list-interfaces`.\n83: type clabwireInterface struct {\n84: \tNode          string `json:\"node\"`\n85: \tInterface     string `json:\"interface\"`\n86: \tAlias         string `json:\"alias,omitempty\"`\n87: \tPeerNode      string `json:\"peerNode\"`\n88: \tPeerInterface string `json:\"peerInterface\"`\n89: }\n90: \n91: // captureAudit is one clabwire audit line.\n92: type captureAudit struct {\n93: \tSchemaVersion string    `json:\"schemaVersion\"`\n94: \tTime          time.Time `json:\"time\"`\n95: \tStatus        string    `json:\"status\"`\n96: \tNodeName      string    `json:\"nodeName\"`\n97: \tFormat        string    `json:\"format\"`\n98: \tReason        string    `json:\"reason\"`\n99: \tPackets       int       `json:\"packets\"`\n100: \tInterfaces    []struct {\n101: \t\tName    string `json:\"name\"`\n102: \t\tID      string `json:\"id\"`\n103: \t\tPackets int    `json:\"packets\"`\n104: \t} `json:\"interfaces\"`\n105: }\n106: \n107: func (r *Runtime) execInPodContainer() podExecFunc {\n108: \tif r.podExec != nil {\n109: \t\treturn r.podExec\n110: \t}\n111: \n112: \treturn r.streamPodExec\n113: }\n114: \n115: // captureSegmentLength is the length of one clabwire capture before the next takes over.\n116: func (r *Runtime) captureSegmentLength() time.Duration {\n117: \tif r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {\n118: \t\treturn r.captureSegment\n119: \t}\n120: \n121: \treturn maxCaptureSegment\n122: }\n123: \n124: // captureReorderWindowLength is the reorder window of the merged stream; zero disables\n125: // reordering.\n126: func (r *Runtime) captureReorderWindowLength() time.Duration {\n127: \tswitch {\n128: \tcase r.captureReorderWindow < 0:\n129: \t\treturn 0\n130: \tcase r.captureReorderWindow > 0:\n131: \t\treturn r.captureReorderWindow\n132: \t}\n133: \n134: \treturn defaultCaptureReorderWindow\n135: }\n136: \n137: // captureReorderWindowFromEnv reads the reorder window knob: unset or invalid keeps the\n138: // default (0), \"0\" disables reordering (-1).\n139: func captureReorderWindowFromEnv() time.Duration {\n140: \tvalue, err := time.ParseDuration(os.Getenv(envCaptureReorderWindow))\n141: \tswitch {\n142: \tcase err != nil || value < 0:\n143: \t\treturn 0\n144: \tcase value == 0:\n145: \t\treturn -1\n146: \t}\n147: \n148: \treturn value\n149: }\n150: \n151: func captureSegmentFromEnv() time.Duration {\n152: \tvalue, err := time.ParseDuration(os.Getenv(envCaptureSegment))\n153: \tif err != nil || value <= 0 {\n154: \t\treturn 0\n155: \t}\n156: \n157: \treturn value\n158: }\n159: \n160: // CaptureInterfaces lists the capturable lab link interfaces of the requested nodes, or of every\n161: // node, as clabwire reports them, with their peers. Node names are reported as the topology\n162: // spells them.\n163: func (r *Runtime) CaptureInterfaces(\n164: \tctx context.Context,\n165: \treq clablabruntime.NodeRequest,\n166: ) ([]clablabruntime.CaptureInterface, error) {\n167: \tr, err := r.connect(ctx, req.Identity)\n168: \tif err != nil {\n169: \t\treturn nil, err\n170: \t}\n171: \n172: \tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n173: \t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n174: \t})\n175: \tif err != nil {\n176: \t\treturn nil, err\n177: \t}\n178: \tif len(req.Nodes) == 0 {\n179: \t\t// a lab-wide listing skips nodes that do not run\n180: \t\trunning := locations[:0]\n181: \t\tfor _, location := range locations {\n182: \t\t\tif location.Pod != \"\" {\n183: \t\t\t\trunning = append(running, location)\n184: \t\t\t}\n185: \t\t}\n186: \t\tlocations = running\n187: \t}\n188: \n189: \tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n190: \tif err != nil {\n191: \t\treturn nil, err\n192: \t}\n193: \tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n194: \tif err != nil {\n195: \t\treturn nil, err\n196: \t}\n197: \n198: \tresult := make([]clablabruntime.CaptureInterface, 0)\n199: \tfor _, location := range locations {\n200: \t\tfor _, entry := range listed[location.NodeName] {\n201: \t\t\tresult = append(result, clablabruntime.CaptureInterface{\n202: \t\t\t\tNode:          names.display(entry.Node),\n203: \t\t\t\tInterface:     entry.Interface,\n204: \t\t\t\tAlias:         entry.Alias,\n205: \t\t\t\tPeerNode:      names.display(entry.PeerNode),\n206: \t\t\t\tPeerInterface: entry.PeerInterface,\n207: \t\t\t})\n208: \t\t}\n209: \t}\n210: \tsort.SliceStable(result, func(i, j int) bool {\n211: \t\tif result[i].Node != result[j].Node {\n212: \t\t\treturn result[i].Node < result[j].Node\n213: \t\t}\n214: \n215: \t\treturn result[i].Interface < result[j].Interface\n216: \t})\n217: \n218: \treturn result, nil\n219: }\n220: \n221: // listCaptureInterfaces runs one --list-interfaces per pod and returns the entries per Node.\n222: func (r *Runtime) listCaptureInterfaces(\n223: \tctx context.Context,\n224: \tlab string,\n225: \tlocations []clablabruntime.NodeLocation,\n226: ) (map[string][]clabwireInterface, error) {\n227: \tpods := map[string]clablabruntime.NodeLocation{}\n228: \twanted := map[string]bool{}\n229: \tfor _, location := range locations {\n230: \t\tif location.Pod == \"\" {\n231: \t\t\treturn nil, fmt.Errorf(\"c9s node %s/%s/%s has no pod; is it running?\",\n232: \t\t\t\tlocation.Namespace, lab, location.NodeName)\n233: \t\t}\n234: \t\tpods[location.Namespace+\"/\"+location.Pod] = location\n235: \t\twanted[location.NodeName] = true\n236: \t}\n237: \n238: \tvar mu sync.Mutex\n239: \tresult := map[string][]clabwireInterface{}\n240: \tgroup, groupCtx := errgroup.WithContext(ctx)\n241: \tgroup.SetLimit(interfaceSampleWorkers)\n242: \texec := r.execInPodContainer()\n243: \tfor _, location := range pods {\n244: \t\tgroup.Go(func() error {\n245: \t\t\tvar stdout, stderr bytes.Buffer\n246: \t\t\terr := exec(groupCtx, location.Namespace, location.Pod, clabwireContainer,\n247: \t\t\t\t[]string{clabwireManager, \"node-runtime\", \"packet-capture\", \"--list-interfaces\"},\n248: \t\t\t\tnil, &stdout, &stderr)\n249: \t\t\tif err != nil {\n250: \t\t\t\treturn fmt.Errorf(\"failed to list the capturable interfaces of pod %s/%s: %w%s\",\n251: \t\t\t\t\tlocation.Namespace, location.Pod, err, stderrSuffix(stderr.Bytes()))\n252: \t\t\t}\n253: \n254: \t\t\tvar entries []clabwireInterface\n255: \t\t\tif err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {\n256: \t\t\t\treturn fmt.Errorf(\"failed to parse the capturable interfaces of pod %s/%s: %w\",\n257: \t\t\t\t\tlocation.Namespace, location.Pod, err)\n258: \t\t\t}\n259: \n260: \t\t\tmu.Lock()\n261: \t\t\tdefer mu.Unlock()\n262: \t\t\tfor _, entry := range entries {\n263: \t\t\t\tif wanted[entry.Node] {\n264: \t\t\t\t\tresult[entry.Node] = append(result[entry.Node], entry)\n265: \t\t\t\t}\n266: \t\t\t}\n267: \n268: \t\t\treturn nil\n269: \t\t})\n270: \t}\n271: \tif err := group.Wait(); err != nil {\n272: \t\treturn nil, err\n273: \t}\n274: \n275: \treturn result, nil\n276: }\n277: \n278: func stderrSuffix(stderr []byte) string {\n279: \ttext := strings.TrimSpace(string(stderr))\n280: \tif text == \"\" {\n281: \t\treturn \"\"\n282: \t}\n283: \n284: \treturn \": \" + text\n285: }\n286: \n287: // nodeNames maps the node names the cluster carries to the names the topology file uses.\n288: type nodeNames map[string]string\n289: \n290: func (n nodeNames) display(name string) string {\n291: \tif original := n[name]; original != \"\" {\n292: \t\treturn original\n293: \t}\n294: \n295: \treturn name\n296: }\n297: \n298: // nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the\n299: // lab's Nodes.\n300: func (r *Runtime) nodeDisplayNames(\n301: \tctx context.Context,\n302: \tlab string,\n303: \tlocations []clablabruntime.NodeLocation,\n304: ) (nodeNames, error) {\n305: \tnames := nodeNames{}\n306: \tif len(locations) == 0 {\n307: \t\treturn names, nil\n308: \t}\n309: \n310: \tnodes, err := r.nodesForTopology(ctx, lab, locations[0].Namespace)\n311: \tif err != nil {\n312: \t\treturn nil, err\n313: \t}\n314: \tfor idx := range nodes.Items {\n315: \t\tif original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != \"\" {\n316: \t\t\tnames[nodes.Items[idx].GetName()] = original\n317: \t\t}\n318: \t}\n319: \n320: \treturn names, nil\n321: }\n322: \n323: // captureGroup is the part of a capture one clabwire process serves: the requested interfaces of\n324: // one node, in one pod.\n325: type captureGroup struct {\n326: \tlocation clablabruntime.NodeLocation\n327: \tdisplay  string\n328: \t// interfaces are the planned interface names, in the order the merged stream lists them.\n329: \tinterfaces []string\n330: \t// ids are the merged interface IDs of interfaces.\n331: \tids []uint32\n332: }\n333: \n334: // resolvedCapture is a validated capture request.\n335: type resolvedCapture struct {\n336: \tgroups []*captureGroup\n337: \t// names are the merged interface names (<node>:<interface>), indexed by merged ID.\n338: \tnames []string\n339: }\n340: \n341: // resolveCaptureTargets locates every target node, checks every interface against the\n342: // interfaces clabwire allows, and groups the targets per node.\n343: func (r *Runtime) resolveCaptureTargets(\n344: \tctx context.Context,\n345: \treq clablabruntime.CaptureRequest,\n346: ) (*resolvedCapture, error) {\n347: \tnodeOrder := make([]string, 0, len(req.Targets))\n348: \tseenNodes := map[string]bool{}\n349: \tfor _, target := range req.Targets {\n350: \t\tif !seenNodes[target.Node] {\n351: \t\t\tseenNodes[target.Node] = true\n352: \t\t\tnodeOrder = append(nodeOrder, target.Node)\n353: \t\t}\n354: \t}\n355: \n356: \tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n357: \t\tName: req.Name, Namespace: req.Namespace, Nodes: nodeOrder, Identity: req.Identity,\n358: \t})\n359: \tif err != nil {\n360: \t\treturn nil, err\n361: \t}\n362: \tbyRequest := make(map[string]clablabruntime.NodeLocation, len(nodeOrder))\n363: \tfor idx, name := range nodeOrder {\n364: \t\tbyRequest[name] = locations[idx]\n365: \t}\n366: \n367: \tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n368: \tif err != nil {\n369: \t\treturn nil, err\n370: \t}\n371: \tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n372: \tif err != nil {\n373: \t\treturn nil, err\n374: \t}\n375: \n376: \tresolved := &resolvedCapture{}\n377: \tgroups := map[string]*captureGroup{}\n378: \tseen := map[string]bool{}\n379: \tfor _, target := range req.Targets {\n380: \t\tlocation := byRequest[target.Node]\n381: \t\tentry, ok := findCaptureInterface(listed[location.NodeName], target.Interface)\n382: \t\tif !ok {\n383: \t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n384: \t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n385: \t\t\t\tdescribeCaptureInterfaces(listed[location.NodeName]))\n386: \t\t}\n387: \n388: \t\tkey := location.NodeName + \"\\x00\" + entry.Interface\n389: \t\tif seen[key] {\n390: \t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n391: \t\t\t\tentry.Interface, target.Node)\n392: \t\t}\n393: \t\tseen[key] = true\n394: \n395: \t\tgroup := groups[location.NodeName]\n396: \t\tif group == nil {\n397: \t\t\tgroup = &captureGroup{\n398: \t\t\t\tlocation: location,\n399: \t\t\t\tdisplay:  names.display(location.NodeName),\n400: \t\t\t}\n401: \t\t\tgroups[location.NodeName] = group\n402: \t\t\tresolved.groups = append(resolved.groups, group)\n403: \t\t}\n404: \n405: \t\tid := uint32(len(resolved.names)) //nolint:gosec // bounded by the targets\n406: \t\tgroup.interfaces = append(group.interfaces, entry.Interface)\n407: \t\tgroup.ids = append(group.ids, id)\n408: \t\tresolved.names = append(resolved.names, group.display+\":\"+entry.Interface)\n409: \t}\n410: \n411: \treturn resolved, nil\n412: }\n413: \n414: // findCaptureInterface matches a requested interface by its planned name or its alias.\n415: func findCaptureInterface(entries []clabwireInterface, name string) (clabwireInterface, bool) {\n416: \tfor _, entry := range entries {\n417: \t\tif entry.Interface == name {\n418: \t\t\treturn entry, true\n419: \t\t}\n420: \t}\n421: \tfor _, entry := range entries {\n422: \t\tif entry.Alias != \"\" && entry.Alias == name {\n423: \t\t\treturn entry, true\n424: \t\t}\n425: \t}\n426: \n427: \treturn clabwireInterface{}, false\n428: }\n429: \n430: func describeCaptureInterfaces(entries []clabwireInterface) string {\n431: \tif len(entries) == 0 {\n432: \t\treturn \"none\"\n433: \t}\n434: \n435: \tnames := make([]string, 0, len(entries))\n436: \tfor _, entry := range entries {\n437: \t\tname := entry.Interface\n438: \t\tif entry.Alias != \"\" {\n439: \t\t\tname += \" (\" + entry.Alias + \")\"\n440: \t\t}\n441: \t\tnames = append(names, name)\n442: \t}\n443: \n444: \treturn strings.Join(names, \", \")\n445: }\n446: \n447: // Capture streams pcapng from lab link interfaces to w: one section, one Interface Description\n448: // Block per target in request order named <node>:<interface>, then the packets of every target.\n449: //\n450: // Each node's interfaces are captured by one clabwire process in the node's pod. clabwire limits\n451: // a capture to one hour, so a longer capture (or one without Duration) chains captures: the next\n452: // one starts before the current one ends, and the stream switches at a cut in the overlap. See\n453: // captureChain for how packets of the overlap are kept once.\n454: //\n455: // Packets go out in timestamp order across nodes, through a reorder buffer (captureReorder).\n456: //\n457: // Every clabwire process runs with stdin attached and --stop-on-stdin-close: a Kubernetes exec\n458: // does not stop its process when the stream closes, so containerlab closes stdin whenever a\n459: // segment ends (the capture ends, fails, its output fails, or a newer segment took over) and\n460: // clabwire ends the capture itself.\n461: //\n462: // Capture returns when Duration has passed, PacketLimit packets were written, or ctx ends; an\n463: // ended ctx is not an error. Every block reaches w in one write, so the stream is a valid capture\n464: // whenever it stops. A clabwire Denied or Failed audit record is returned as an error.\n465: func (r *Runtime) Capture(\n466: \tctx context.Context,\n467: \treq clablabruntime.CaptureRequest,\n468: \tw io.Writer,\n469: ) error {\n470: \tif err := clabcapture.ValidateRequest(&req); err != nil {\n471: \t\treturn err\n472: \t}\n473: \n474: \tr, err := r.connect(ctx, req.Identity)\n475: \tif err != nil {\n476: \t\treturn err\n477: \t}\n478: \n479: \tresolved, err := r.resolveCaptureTargets(ctx, req)\n480: \tif err != nil {\n481: \t\treturn err\n482: \t}\n483: \n484: \tcaptureCtx, stop := context.WithCancel(ctx)\n485: \tdefer stop()\n486: \n487: \tout, err := clabcapture.NewOutput(w, resolved.names, req.SnapLength, req.PacketLimit,\n488: \t\tr.captureReorderWindowLength(), stop)\n489: \tif err != nil {\n490: \t\treturn err\n491: \t}\n492: \n493: \trun := &captureRun{\n494: \t\tr:       r,\n495: \t\treq:     req,\n496: \t\tout:     out,\n497: \t\tsegment: r.captureSegmentLength(),\n498: \t}\n499: \tif req.Duration > 0 {\n500: \t\trun.deadline = time.Now().Add(req.Duration)\n501: \t}\n502: \trun.overlap = min(maxCaptureOverlap, run.segment/3)\n503: \trun.window = min(maxCaptureCutWindow, run.overlap/4)\n504: \n505: \tif req.Duration > 0 {\n506: \t\t// a clabwire process that does not end on its own does not hold the capture open\n507: \t\tvar cancelTimeout context.CancelFunc\n508: \t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx,\n509: \t\t\treq.Duration+run.overlap+captureEndGrace)\n510: \t\tdefer cancelTimeout()\n511: \t}\n512: \n513: \tgroup, groupCtx := errgroup.WithContext(captureCtx)\n514: \tfor _, captureGroup := range resolved.groups {\n515: \t\tchain := &captureChain{capture: run, group: captureGroup}\n516: \t\tgroup.Go(func() error {\n517: \t\t\treturn chain.run(groupCtx)\n518: \t\t})\n519: \t}\n520: \n521: \terr = group.Wait()\n522: \tif writeErr := out.Close(); writeErr != nil {\n523: \t\treturn writeErr\n524: \t}\n525: \tif err != nil && !(errors.Is(err, context.Canceled) && captureCtx.Err() != nil) {\n526: \t\treturn err\n527: \t}\n528: \n529: \treturn nil\n530: }\n531: \n532: // captureRun is the state a capture's chains share.\n533: type captureRun struct {\n534: \tr   *Runtime\n535: \treq clablabruntime.CaptureRequest\n536: \t// out is the merged stream; it writes the packets of every chain in timestamp order and\n537: \t// stops every chain once the packet limit is reached.\n538: \tout *clabcapture.Output\n539: \n540: \tsegment  time.Duration\n541: \toverlap  time.Duration\n542: \twindow   time.Duration\n543: \tdeadline time.Time\n544: }\n545: \n546: // emit writes a packet under its merged interface ID. It reports false once the packet limit is\n547: // reached and the capture stops.\n548: func (run *captureRun) emit(id uint32, packet *clabcapture.Packet) (bool, error) {\n549: \treturn run.out.Emit(id, packet)\n550: }\n551: \n552: func (run *captureRun) reportGap(gap clablabruntime.CaptureGap) {\n553: \tclabcapture.ReportGap(run.req.OnGap, gap)\n554: }\n555: \n556: // captureSegment is one clabwire capture process of a chain.\n557: type captureSegment struct {\n558: \tindex      int\n559: \tlocalStart time.Time\n560: \tduration   time.Duration\n561: \tcancel     context.CancelFunc\n562: \t// closeStdin closes the stdin of the segment's clabwire process, which ends it; it may be\n563: \t// called any number of times.\n564: \tcloseStdin func()\n565: \t// stopTimer closes stdin once the segment is no longer needed after a switch-over.\n566: \tstopTimer *time.Timer\n567: \t// started and ended are the pod-clock times of the Started and Succeeded audit records.\n568: \tstarted time.Time\n569: \tended   time.Time\n570: \tdone    bool\n571: }\n572: \n573: func (s *captureSegment) plannedEnd() time.Time {\n574: \treturn s.started.Add(s.duration)\n575: }\n576: \n577: // segmentEvent is something a segment reported: a packet, an audit record, or its end.\n578: type segmentEvent struct {\n579: \tsegment *captureSegment\n580: \tpacket  *clabcapture.Packet\n581: \taudit   *captureAudit\n582: \tdone    bool\n583: \terr     error\n584: }\n585: \n586: // captureChain runs the chained clabwire captures of one group.\n587: //\n588: // Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both\n589: // capture the same packets for a while. clabwire stamps packets when it reads them, so two\n590: // processes give the same packet timestamps a few microseconds apart, and timestamps alone\n591: // cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by\n592: // content close to the cut:\n593: //\n594: //  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is\n595: //     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.\n596: //  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the\n597: //     content of what it wrote since segment k+1 started.\n598: //  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped\n599: //     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped\n600: //     when segment k wrote the same bytes on the same interface, and every other one is written.\n601: //     From then on segment k+1 streams live.\n602: //\n603: // Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its\n604: // planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other\n605: // nodes' later packets do not overtake them in the merged stream.\n606: //\n607: // W (500 ms, less for short test segments) covers the stamping difference. Identical frames on\n608: // the same interface within W of the cut can be paired with each other, which can drop a true\n609: // repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves\n610: // a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.\n611: type captureChain struct {\n612: \tcapture *captureRun\n613: \tgroup   *captureGroup\n614: \n615: \tevents chan segmentEvent\n616: \twg     sync.WaitGroup\n617: \n618: \tactive *captureSegment\n619: \tnext   *captureSegment\n620: \t// cut is the switch time between active and next, in nanoseconds; zero until known.\n621: \tcut int64\n622: \t// emitted remembers the content of the packets active wrote while next runs.\n623: \temitted map[uint64]int\n624: \t// held are the packets of next until active ends.\n625: \theld     []*clabcapture.Packet\n626: \tsegments int\n627: \tretries  int\n628: \t// final is set once no further segment is due.\n629: \tfinal bool\n630: \t// stopping is set once ctx ended: the segments are asked to end and what they still\n631: \t// deliver is written.\n632: \tstopping bool\n633: }\n634: \n635: // run runs the chain until its last segment ended. When ctx ends, it stops the segments and\n636: // keeps writing the packets they read until then; a segment that does not end within\n637: // captureStdinCloseGrace is cut.\n638: func (c *captureChain) run(ctx context.Context) error {\n639: \tc.events = make(chan segmentEvent, 256)\n640: \t// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them\n641: \tsegmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))\n642: \tvar abort *time.Timer\n643: \tdefer func() {\n644: \t\tif abort != nil {\n645: \t\t\tabort.Stop()\n646: \t\t}\n647: \t\tcancel()\n648: \t\tc.drain()\n649: \t\tc.capture.out.Release(c)\n650: \t}()\n651: \n652: \tc.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))\n653: \ttimer := time.NewTimer(c.nextStartIn())\n654: \tdefer timer.Stop()\n655: \n656: \tdone := ctx.Done()\n657: \tfor {\n658: \t\tselect {\n659: \t\tcase <-done:\n660: \t\t\tdone = nil\n661: \t\t\tc.stop(timer)\n662: \t\t\tabort = time.AfterFunc(captureStdinCloseGrace, cancel)\n663: \t\tcase <-segmentsCtx.Done():\n664: \t\t\treturn nil\n665: \t\tcase <-timer.C:\n666: \t\t\tif c.next == nil && !c.final {\n667: \t\t\t\tc.startNext(segmentsCtx)\n668: \t\t\t}\n669: \t\tcase event := <-c.events:\n670: \t\t\tstop, err := c.handle(segmentsCtx, event, timer)\n671: \t\t\tif err != nil || stop {\n672: \t\t\t\treturn err\n673: \t\t\t}\n674: \t\t}\n675: \t}\n676: }\n677: \n678: // stop ends the chain early, like a deadline would: no further segment starts and the running\n679: // ones are asked to end. The chain then writes what they deliver until they ended.\n\n(Showing lines 60-679 of 1202. Use offset=680 to continue.)\n</content>",
    "title": "source/head/labruntime/clabernetes/capture.go",
    "metadata": {
      "preview": "\n\t// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests\n\t// without hour-long captures.\n\tenvCaptureSegment = \"CLAB_C9S_CAPTURE_SEGMENT\"\n\t// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets\n\t// of other nodes stamped earlier but delivered later still go out before it.\n\tdefaultCaptureReorderWindow = 250 * time.Millisecond\n\t// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.\n\t// It is an internal knob, not a supported setting.\n\tenvCaptureReorderWindow = \"CLAB_C9S_CAPTURE_REORDER_WINDOW\"\n)\n\n// podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns\n// a *labruntime.CommandExitError.\ntype podExecFunc func(\n\tctx context.Context,\n\tnamespace, pod, container string,\n\tcommand []string,\n\tstdin io.Reader,\n\tstdout, stderr io.Writer,",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/capture.go",
        "text": "\n\t// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests\n\t// without hour-long captures.\n\tenvCaptureSegment = \"CLAB_C9S_CAPTURE_SEGMENT\"\n\t// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets\n\t// of other nodes stamped earlier but delivered later still go out before it.\n\tdefaultCaptureReorderWindow = 250 * time.Millisecond\n\t// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.\n\t// It is an internal knob, not a supported setting.\n\tenvCaptureReorderWindow = \"CLAB_C9S_CAPTURE_REORDER_WINDOW\"\n)\n\n// podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns\n// a *labruntime.CommandExitError.\ntype podExecFunc func(\n\tctx context.Context,\n\tnamespace, pod, container string,\n\tcommand []string,\n\tstdin io.Reader,\n\tstdout, stderr io.Writer,\n) error\n\n// clabwireInterface is one entry of `packet-capture --list-interfaces`.\ntype clabwireInterface struct {\n\tNode          string `json:\"node\"`\n\tInterface     string `json:\"interface\"`\n\tAlias         string `json:\"alias,omitempty\"`\n\tPeerNode      string `json:\"peerNode\"`\n\tPeerInterface string `json:\"peerInterface\"`\n}\n\n// captureAudit is one clabwire audit line.\ntype captureAudit struct {\n\tSchemaVersion string    `json:\"schemaVersion\"`\n\tTime          time.Time `json:\"time\"`\n\tStatus        string    `json:\"status\"`\n\tNodeName      string    `json:\"nodeName\"`\n\tFormat        string    `json:\"format\"`\n\tReason        string    `json:\"reason\"`\n\tPackets       int       `json:\"packets\"`\n\tInterfaces    []struct {\n\t\tName    string `json:\"name\"`\n\t\tID      string `json:\"id\"`\n\t\tPackets int    `json:\"packets\"`\n\t} `json:\"interfaces\"`\n}\n\nfunc (r *Runtime) execInPodContainer() podExecFunc {\n\tif r.podExec != nil {\n\t\treturn r.podExec\n\t}\n\n\treturn r.streamPodExec\n}\n\n// captureSegmentLength is the length of one clabwire capture before the next takes over.\nfunc (r *Runtime) captureSegmentLength() time.Duration {\n\tif r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {\n\t\treturn r.captureSegment\n\t}\n\n\treturn maxCaptureSegment\n}\n\n// captureReorderWindowLength is the reorder window of the merged stream; zero disables\n// reordering.\nfunc (r *Runtime) captureReorderWindowLength() time.Duration {\n\tswitch {\n\tcase r.captureReorderWindow < 0:\n\t\treturn 0\n\tcase r.captureReorderWindow > 0:\n\t\treturn r.captureReorderWindow\n\t}\n\n\treturn defaultCaptureReorderWindow\n}\n\n// captureReorderWindowFromEnv reads the reorder window knob: unset or invalid keeps the\n// default (0), \"0\" disables reordering (-1).\nfunc captureReorderWindowFromEnv() time.Duration {\n\tvalue, err := time.ParseDuration(os.Getenv(envCaptureReorderWindow))\n\tswitch {\n\tcase err != nil || value < 0:\n\t\treturn 0\n\tcase value == 0:\n\t\treturn -1\n\t}\n\n\treturn value\n}\n\nfunc captureSegmentFromEnv() time.Duration {\n\tvalue, err := time.ParseDuration(os.Getenv(envCaptureSegment))\n\tif err != nil || value <= 0 {\n\t\treturn 0\n\t}\n\n\treturn value\n}\n\n// CaptureInterfaces lists the capturable lab link interfaces of the requested nodes, or of every\n// node, as clabwire reports them, with their peers. Node names are reported as the topology\n// spells them.\nfunc (r *Runtime) CaptureInterfaces(\n\tctx context.Context,\n\treq clablabruntime.NodeRequest,\n) ([]clablabruntime.CaptureInterface, error) {\n\tr, err := r.connect(ctx, req.Identity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n\t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(req.Nodes) == 0 {\n\t\t// a lab-wide listing skips nodes that do not run\n\t\trunning := locations[:0]\n\t\tfor _, location := range locations {\n\t\t\tif location.Pod != \"\" {\n\t\t\t\trunning = append(running, location)\n\t\t\t}\n\t\t}\n\t\tlocations = running\n\t}\n\n\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := make([]clablabruntime.CaptureInterface, 0)\n\tfor _, location := range locations {\n\t\tfor _, entry := range listed[location.NodeName] {\n\t\t\tresult = append(result, clablabruntime.CaptureInterface{\n\t\t\t\tNode:          names.display(entry.Node),\n\t\t\t\tInterface:     entry.Interface,\n\t\t\t\tAlias:         entry.Alias,\n\t\t\t\tPeerNode:      names.display(entry.PeerNode),\n\t\t\t\tPeerInterface: entry.PeerInterface,\n\t\t\t})\n\t\t}\n\t}\n\tsort.SliceStable(result, func(i, j int) bool {\n\t\tif result[i].Node != result[j].Node {\n\t\t\treturn result[i].Node < result[j].Node\n\t\t}\n\n\t\treturn result[i].Interface < result[j].Interface\n\t})\n\n\treturn result, nil\n}\n\n// listCaptureInterfaces runs one --list-interfaces per pod and returns the entries per Node.\nfunc (r *Runtime) listCaptureInterfaces(\n\tctx context.Context,\n\tlab string,\n\tlocations []clablabruntime.NodeLocation,\n) (map[string][]clabwireInterface, error) {\n\tpods := map[string]clablabruntime.NodeLocation{}\n\twanted := map[string]bool{}\n\tfor _, location := range locations {\n\t\tif location.Pod == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"c9s node %s/%s/%s has no pod; is it running?\",\n\t\t\t\tlocation.Namespace, lab, location.NodeName)\n\t\t}\n\t\tpods[location.Namespace+\"/\"+location.Pod] = location\n\t\twanted[location.NodeName] = true\n\t}\n\n\tvar mu sync.Mutex\n\tresult := map[string][]clabwireInterface{}\n\tgroup, groupCtx := errgroup.WithContext(ctx)\n\tgroup.SetLimit(interfaceSampleWorkers)\n\texec := r.execInPodContainer()\n\tfor _, location := range pods {\n\t\tgroup.Go(func() error {\n\t\t\tvar stdout, stderr bytes.Buffer\n\t\t\terr := exec(groupCtx, location.Namespace, location.Pod, clabwireContainer,\n\t\t\t\t[]string{clabwireManager, \"node-runtime\", \"packet-capture\", \"--list-interfaces\"},\n\t\t\t\tnil, &stdout, &stderr)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to list the capturable interfaces of pod %s/%s: %w%s\",\n\t\t\t\t\tlocation.Namespace, location.Pod, err, stderrSuffix(stderr.Bytes()))\n\t\t\t}\n\n\t\t\tvar entries []clabwireInterface\n\t\t\tif err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to parse the capturable interfaces of pod %s/%s: %w\",\n\t\t\t\t\tlocation.Namespace, location.Pod, err)\n\t\t\t}\n\n\t\t\tmu.Lock()\n\t\t\tdefer mu.Unlock()\n\t\t\tfor _, entry := range entries {\n\t\t\t\tif wanted[entry.Node] {\n\t\t\t\t\tresult[entry.Node] = append(result[entry.Node], entry)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err := group.Wait(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\nfunc stderrSuffix(stderr []byte) string {\n\ttext := strings.TrimSpace(string(stderr))\n\tif text == \"\" {\n\t\treturn \"\"\n\t}\n\n\treturn \": \" + text\n}\n\n// nodeNames maps the node names the cluster carries to the names the topology file uses.\ntype nodeNames map[string]string\n\nfunc (n nodeNames) display(name string) string {\n\tif original := n[name]; original != \"\" {\n\t\treturn original\n\t}\n\n\treturn name\n}\n\n// nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the\n// lab's Nodes.\nfunc (r *Runtime) nodeDisplayNames(\n\tctx context.Context,\n\tlab string,\n\tlocations []clablabruntime.NodeLocation,\n) (nodeNames, error) {\n\tnames := nodeNames{}\n\tif len(locations) == 0 {\n\t\treturn names, nil\n\t}\n\n\tnodes, err := r.nodesForTopology(ctx, lab, locations[0].Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor idx := range nodes.Items {\n\t\tif original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != \"\" {\n\t\t\tnames[nodes.Items[idx].GetName()] = original\n\t\t}\n\t}\n\n\treturn names, nil\n}\n\n// captureGroup is the part of a capture one clabwire process serves: the requested interfaces of\n// one node, in one pod.\ntype captureGroup struct {\n\tlocation clablabruntime.NodeLocation\n\tdisplay  string\n\t// interfaces are the planned interface names, in the order the merged stream lists them.\n\tinterfaces []string\n\t// ids are the merged interface IDs of interfaces.\n\tids []uint32\n}\n\n// resolvedCapture is a validated capture request.\ntype resolvedCapture struct {\n\tgroups []*captureGroup\n\t// names are the merged interface names (<node>:<interface>), indexed by merged ID.\n\tnames []string\n}\n\n// resolveCaptureTargets locates every target node, checks every interface against the\n// interfaces clabwire allows, and groups the targets per node.\nfunc (r *Runtime) resolveCaptureTargets(\n\tctx context.Context,\n\treq clablabruntime.CaptureRequest,\n) (*resolvedCapture, error) {\n\tnodeOrder := make([]string, 0, len(req.Targets))\n\tseenNodes := map[string]bool{}\n\tfor _, target := range req.Targets {\n\t\tif !seenNodes[target.Node] {\n\t\t\tseenNodes[target.Node] = true\n\t\t\tnodeOrder = append(nodeOrder, target.Node)\n\t\t}\n\t}\n\n\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n\t\tName: req.Name, Namespace: req.Namespace, Nodes: nodeOrder, Identity: req.Identity,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbyRequest := make(map[string]clablabruntime.NodeLocation, len(nodeOrder))\n\tfor idx, name := range nodeOrder {\n\t\tbyRequest[name] = locations[idx]\n\t}\n\n\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresolved := &resolvedCapture{}\n\tgroups := map[string]*captureGroup{}\n\tseen := map[string]bool{}\n\tfor _, target := range req.Targets {\n\t\tlocation := byRequest[target.Node]\n\t\tentry, ok := findCaptureInterface(listed[location.NodeName], target.Interface)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n\t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n\t\t\t\tdescribeCaptureInterfaces(listed[location.NodeName]))\n\t\t}\n\n\t\tkey := location.NodeName + \"\\x00\" + entry.Interface\n\t\tif seen[key] {\n\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n\t\t\t\tentry.Interface, target.Node)\n\t\t}\n\t\tseen[key] = true\n\n\t\tgroup := groups[location.NodeName]\n\t\tif group == nil {\n\t\t\tgroup = &captureGroup{\n\t\t\t\tlocation: location,\n\t\t\t\tdisplay:  names.display(location.NodeName),\n\t\t\t}\n\t\t\tgroups[location.NodeName] = group\n\t\t\tresolved.groups = append(resolved.groups, group)\n\t\t}\n\n\t\tid := uint32(len(resolved.names)) //nolint:gosec // bounded by the targets\n\t\tgroup.interfaces = append(group.interfaces, entry.Interface)\n\t\tgroup.ids = append(group.ids, id)\n\t\tresolved.names = append(resolved.names, group.display+\":\"+entry.Interface)\n\t}\n\n\treturn resolved, nil\n}\n\n// findCaptureInterface matches a requested interface by its planned name or its alias.\nfunc findCaptureInterface(entries []clabwireInterface, name string) (clabwireInterface, bool) {\n\tfor _, entry := range entries {\n\t\tif entry.Interface == name {\n\t\t\treturn entry, true\n\t\t}\n\t}\n\tfor _, entry := range entries {\n\t\tif entry.Alias != \"\" && entry.Alias == name {\n\t\t\treturn entry, true\n\t\t}\n\t}\n\n\treturn clabwireInterface{}, false\n}\n\nfunc describeCaptureInterfaces(entries []clabwireInterface) string {\n\tif len(entries) == 0 {\n\t\treturn \"none\"\n\t}\n\n\tnames := make([]string, 0, len(entries))\n\tfor _, entry := range entries {\n\t\tname := entry.Interface\n\t\tif entry.Alias != \"\" {\n\t\t\tname += \" (\" + entry.Alias + \")\"\n\t\t}\n\t\tnames = append(names, name)\n\t}\n\n\treturn strings.Join(names, \", \")\n}\n\n// Capture streams pcapng from lab link interfaces to w: one section, one Interface Description\n// Block per target in request order named <node>:<interface>, then the packets of every target.\n//\n// Each node's interfaces are captured by one clabwire process in the node's pod. clabwire limits\n// a capture to one hour, so a longer capture (or one without Duration) chains captures: the next\n// one starts before the current one ends, and the stream switches at a cut in the overlap. See\n// captureChain for how packets of the overlap are kept once.\n//\n// Packets go out in timestamp order across nodes, through a reorder buffer (captureReorder).\n//\n// Every clabwire process runs with stdin attached and --stop-on-stdin-close: a Kubernetes exec\n// does not stop its process when the stream closes, so containerlab closes stdin whenever a\n// segment ends (the capture ends, fails, its output fails, or a newer segment took over) and\n// clabwire ends the capture itself.\n//\n// Capture returns when Duration has passed, PacketLimit packets were written, or ctx ends; an\n// ended ctx is not an error. Every block reaches w in one write, so the stream is a valid capture\n// whenever it stops. A clabwire Denied or Failed audit record is returned as an error.\nfunc (r *Runtime) Capture(\n\tctx context.Context,\n\treq clablabruntime.CaptureRequest,\n\tw io.Writer,\n) error {\n\tif err := clabcapture.ValidateRequest(&req); err != nil {\n\t\treturn err\n\t}\n\n\tr, err := r.connect(ctx, req.Identity)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresolved, err := r.resolveCaptureTargets(ctx, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcaptureCtx, stop := context.WithCancel(ctx)\n\tdefer stop()\n\n\tout, err := clabcapture.NewOutput(w, resolved.names, req.SnapLength, req.PacketLimit,\n\t\tr.captureReorderWindowLength(), stop)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trun := &captureRun{\n\t\tr:       r,\n\t\treq:     req,\n\t\tout:     out,\n\t\tsegment: r.captureSegmentLength(),\n\t}\n\tif req.Duration > 0 {\n\t\trun.deadline = time.Now().Add(req.Duration)\n\t}\n\trun.overlap = min(maxCaptureOverlap, run.segment/3)\n\trun.window = min(maxCaptureCutWindow, run.overlap/4)\n\n\tif req.Duration > 0 {\n\t\t// a clabwire process that does not end on its own does not hold the capture open\n\t\tvar cancelTimeout context.CancelFunc\n\t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx,\n\t\t\treq.Duration+run.overlap+captureEndGrace)\n\t\tdefer cancelTimeout()\n\t}\n\n\tgroup, groupCtx := errgroup.WithContext(captureCtx)\n\tfor _, captureGroup := range resolved.groups {\n\t\tchain := &captureChain{capture: run, group: captureGroup}\n\t\tgroup.Go(func() error {\n\t\t\treturn chain.run(groupCtx)\n\t\t})\n\t}\n\n\terr = group.Wait()\n\tif writeErr := out.Close(); writeErr != nil {\n\t\treturn writeErr\n\t}\n\tif err != nil && !(errors.Is(err, context.Canceled) && captureCtx.Err() != nil) {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n// captureRun is the state a capture's chains share.\ntype captureRun struct {\n\tr   *Runtime\n\treq clablabruntime.CaptureRequest\n\t// out is the merged stream; it writes the packets of every chain in timestamp order and\n\t// stops every chain once the packet limit is reached.\n\tout *clabcapture.Output\n\n\tsegment  time.Duration\n\toverlap  time.Duration\n\twindow   time.Duration\n\tdeadline time.Time\n}\n\n// emit writes a packet under its merged interface ID. It reports false once the packet limit is\n// reached and the capture stops.\nfunc (run *captureRun) emit(id uint32, packet *clabcapture.Packet) (bool, error) {\n\treturn run.out.Emit(id, packet)\n}\n\nfunc (run *captureRun) reportGap(gap clablabruntime.CaptureGap) {\n\tclabcapture.ReportGap(run.req.OnGap, gap)\n}\n\n// captureSegment is one clabwire capture process of a chain.\ntype captureSegment struct {\n\tindex      int\n\tlocalStart time.Time\n\tduration   time.Duration\n\tcancel     context.CancelFunc\n\t// closeStdin closes the stdin of the segment's clabwire process, which ends it; it may be\n\t// called any number of times.\n\tcloseStdin func()\n\t// stopTimer closes stdin once the segment is no longer needed after a switch-over.\n\tstopTimer *time.Timer\n\t// started and ended are the pod-clock times of the Started and Succeeded audit records.\n\tstarted time.Time\n\tended   time.Time\n\tdone    bool\n}\n\nfunc (s *captureSegment) plannedEnd() time.Time {\n\treturn s.started.Add(s.duration)\n}\n\n// segmentEvent is something a segment reported: a packet, an audit record, or its end.\ntype segmentEvent struct {\n\tsegment *captureSegment\n\tpacket  *clabcapture.Packet\n\taudit   *captureAudit\n\tdone    bool\n\terr     error\n}\n\n// captureChain runs the chained clabwire captures of one group.\n//\n// Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both\n// capture the same packets for a while. clabwire stamps packets when it reads them, so two\n// processes give the same packet timestamps a few microseconds apart, and timestamps alone\n// cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by\n// content close to the cut:\n//\n//  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is\n//     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.\n//  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the\n//     content of what it wrote since segment k+1 started.\n//  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped\n//     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped\n//     when segment k wrote the same bytes on the same interface, and every other one is written.\n//     From then on segment k+1 streams live.\n//\n// Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its\n// planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other\n// nodes' later packets do not overtake them in the merged stream.\n//\n// W (500 ms, less for short test segments) covers the stamping difference. Identical frames on\n// the same interface within W of the cut can be paired with each other, which can drop a true\n// repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves\n// a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.\ntype captureChain struct {\n\tcapture *captureRun\n\tgroup   *captureGroup\n\n\tevents chan segmentEvent\n\twg     sync.WaitGroup\n\n\tactive *captureSegment\n\tnext   *captureSegment\n\t// cut is the switch time between active and next, in nanoseconds; zero until known.\n\tcut int64\n\t// emitted remembers the content of the packets active wrote while next runs.\n\temitted map[uint64]int\n\t// held are the packets of next until active ends.\n\theld     []*clabcapture.Packet\n\tsegments int\n\tretries  int\n\t// final is set once no further segment is due.\n\tfinal bool\n\t// stopping is set once ctx ended: the segments are asked to end and what they still\n\t// deliver is written.\n\tstopping bool\n}\n\n// run runs the chain until its last segment ended. When ctx ends, it stops the segments and\n// keeps writing the packets they read until then; a segment that does not end within\n// captureStdinCloseGrace is cut.\nfunc (c *captureChain) run(ctx context.Context) error {\n\tc.events = make(chan segmentEvent, 256)\n\t// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them\n\tsegmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))\n\tvar abort *time.Timer\n\tdefer func() {\n\t\tif abort != nil {\n\t\t\tabort.Stop()\n\t\t}\n\t\tcancel()\n\t\tc.drain()\n\t\tc.capture.out.Release(c)\n\t}()\n\n\tc.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))\n\ttimer := time.NewTimer(c.nextStartIn())\n\tdefer timer.Stop()\n\n\tdone := ctx.Done()\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\tdone = nil\n\t\t\tc.stop(timer)\n\t\t\tabort = time.AfterFunc(captureStdinCloseGrace, cancel)\n\t\tcase <-segmentsCtx.Done():\n\t\t\treturn nil\n\t\tcase <-timer.C:\n\t\t\tif c.next == nil && !c.final {\n\t\t\t\tc.startNext(segmentsCtx)\n\t\t\t}\n\t\tcase event := <-c.events:\n\t\t\tstop, err := c.handle(segmentsCtx, event, timer)\n\t\t\tif err != nil || stop {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n}\n\n// stop ends the chain early, like a deadline would: no further segment starts and the running\n// ones are asked to end. The chain then writes what they deliver until they ended.",
        "lineStart": 60,
        "lineEnd": 679,
        "totalLines": 1202,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523348954,
      "end": 1793523348963
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1965275e6001LCnFjxd166ypJs",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196526863001CoB4SCcGn05S5b",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 42764,
    "input": 7521,
    "output": 53,
    "reasoning": 118,
    "cache": {
      "read": 35072,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196526863001CoB4SCcGn05S5b",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523345507,
    "completed": 1793523348969
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 42764,
    "input": 7521,
    "output": 53,
    "reasoning": 118,
    "cache": {
      "read": 35072,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 30
step-start
{
  "type": "step-start",
  "id": "prt_196527d9e001D6Vd2x7IZ67CqM",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965275f0001jy0JtWtHQA7Mlj"
}
read · completed

Input

{
  "filePath": "/source/head/labruntime/clabernetes/capture.go",
  "limit": 530,
  "offset": 680
}

Output

<path>/source/head/labruntime/clabernetes/capture.go</path>
<type>file</type>
<content>
680: func (c *captureChain) stop(timer *time.Timer) {
681: 	c.stopping = true
682: 	c.final = true
683: 	timer.Stop()
684: 	c.active.closeStdin()
685: 	if c.next != nil {
686: 		c.next.closeStdin()
687: 	}
688: }
689: 
690: // drain waits for the segment goroutines after the chain ended.
691: func (c *captureChain) drain() {
692: 	done := make(chan struct{})
693: 	go func() {
694: 		c.wg.Wait()
695: 		close(done)
696: 	}()
697: 	for {
698: 		select {
699: 		case <-done:
700: 			return
701: 		case <-c.events:
702: 		}
703: 	}
704: }
705: 
706: // segmentDuration is the requested duration of a segment starting now.
707: func (c *captureChain) segmentDuration(now time.Time) time.Duration {
708: 	duration := c.capture.segment
709: 	if !c.capture.deadline.IsZero() {
710: 		duration = min(duration, c.capture.deadline.Sub(now))
711: 	}
712: 
713: 	return max(duration, minCaptureSegment)
714: }
715: 
716: // nextStartIn is the time until the follow-up of the active segment is due. It marks the chain
717: // final when none is due.
718: func (c *captureChain) nextStartIn() time.Duration {
719: 	if c.stopping {
720: 		c.final = true
721: 		return maxCaptureSegment
722: 	}
723: 	activeEnd := c.active.localStart.Add(c.active.duration)
724: 	if !c.capture.deadline.IsZero() &&
725: 		!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {
726: 		c.final = true
727: 		return maxCaptureSegment
728: 	}
729: 	c.final = false
730: 
731: 	return max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)
732: }
733: 
734: func (c *captureChain) startNext(ctx context.Context) {
735: 	c.next = c.start(ctx, c.segmentDuration(time.Now()))
736: 	c.emitted = map[uint64]int{}
737: 	c.held = nil
738: 	c.cut = 0
739: }
740: 
741: func (c *captureChain) handle(
742: 	ctx context.Context,
743: 	event segmentEvent,
744: 	timer *time.Timer,
745: ) (bool, error) {
746: 	segment := event.segment
747: 
748: 	switch {
749: 	case event.audit != nil:
750: 		return false, c.handleAudit(segment, event.audit)
751: 	case event.packet != nil:
752: 		return c.handlePacket(segment, event.packet)
753: 	case event.done:
754: 		segment.done = true
755: 		if segment.stopTimer != nil {
756: 			segment.stopTimer.Stop()
757: 		}
758: 		if event.err != nil && !c.stopping {
759: 			if segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {
760: 				// the follow-up did not start; try again while the active one still runs
761: 				c.retries++
762: 				log.Warn("Capture follow-up segment failed to start, retrying",
763: 					"node", c.group.display, "error", event.err)
764: 				c.next = nil
765: 				resetTimer(timer, time.Second)
766: 
767: 				return false, nil
768: 			}
769: 
770: 			return true, fmt.Errorf("capture on c9s node %s/%s/%s failed: %w",
771: 				c.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)
772: 		}
773: 		if segment != c.active {
774: 			return false, nil
775: 		}
776: 
777: 		return c.switchSegments(ctx, timer)
778: 	}
779: 
780: 	return false, nil
781: }
782: 
783: func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {
784: 	switch audit.Status {
785: 	case captureAuditStarted:
786: 		segment.started = audit.Time
787: 		log.Debug("Capture segment started", "node", c.group.display, "segment", segment.index,
788: 			"interfaces", strings.Join(c.group.interfaces, ","), "duration", segment.duration)
789: 		if segment == c.next && !c.active.started.IsZero() {
790: 			c.setCut()
791: 		}
792: 		if segment == c.next {
793: 			c.retries = 0
794: 		}
795: 	case captureAuditSucceeded:
796: 		segment.ended = audit.Time
797: 		log.Debug("Capture segment succeeded", "node", c.group.display,
798: 			"segment", segment.index, "packets", audit.Packets)
799: 	case captureAuditDenied, captureAuditFailed:
800: 		return captureAuditError(c.group.display, audit)
801: 	}
802: 
803: 	return nil
804: }
805: 
806: // captureAuditError turns a Denied or Failed clabwire audit record into an error.
807: func captureAuditError(node string, audit *captureAudit) error {
808: 	verb := "failed"
809: 	if audit.Status == captureAuditDenied {
810: 		verb = "was denied"
811: 	}
812: 	interfaces := make([]string, 0, len(audit.Interfaces))
813: 	for _, intf := range audit.Interfaces {
814: 		interfaces = append(interfaces, intf.Name)
815: 	}
816: 
817: 	return fmt.Errorf("capture of %s on node %s %s by clabwire: %s",
818: 		strings.Join(interfaces, ","), node, verb, audit.Reason)
819: }
820: 
821: // setCut places the cut in the middle of the overlap of the active and the next segment, both
822: // measured on the pod clock.
823: func (c *captureChain) setCut() {
824: 	overlapStart := c.next.started
825: 	overlapEnd := c.active.plannedEnd()
826: 	if overlapEnd.Sub(overlapStart) < 2*c.capture.window {
827: 		// the overlap is too short to match packets around a cut: the switch is reported as a
828: 		// gap once the active segment ended
829: 		c.cut = 0
830: 		return
831: 	}
832: 	c.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()
833: 
834: 	window := c.capture.window.Nanoseconds()
835: 	// Packets the next segment holds back are stamped from T-W on: other chains' packets after
836: 	// that wait in the reorder buffer until the switch, so the merged stream stays in order.
837: 	c.capture.out.Hold(c, c.cut-window)
838: 
839: 	// The active segment only matters for packets stamped before T. Once the pod clock passed
840: 	// T+W, it is closed: packets it read until then are still delivered, and the ones it reads
841: 	// later are stamped after T and dropped anyway. The next segment's Started record was
842: 	// written on the pod clock no later than now, so the pod clock passes T+W no later than
843: 	// (T - Started + W) from now.
844: 	active := c.active
845: 	active.stopTimer = time.AfterFunc(
846: 		time.Duration(c.cut-c.next.started.UnixNano()+window), active.closeStdin)
847: }
848: 
849: func (c *captureChain) handlePacket(
850: 	segment *captureSegment,
851: 	packet *clabcapture.Packet,
852: ) (bool, error) {
853: 	switch segment {
854: 	case c.active:
855: 		if c.cut != 0 && packet.Timestamp >= c.cut {
856: 			return false, nil
857: 		}
858: 		if c.next != nil {
859: 			c.emitted[packetKey(packet)]++
860: 		}
861: 
862: 		return c.emit(packet)
863: 	case c.next:
864: 		c.held = append(c.held, packet)
865: 	}
866: 
867: 	return false, nil
868: }
869: 
870: func (c *captureChain) emit(packet *clabcapture.Packet) (bool, error) {
871: 	if int(packet.InterfaceID) >= len(c.group.ids) {
872: 		return true, fmt.Errorf("clabwire wrote a packet for interface %d of %d",
873: 			packet.InterfaceID, len(c.group.ids))
874: 	}
875: 	more, err := c.capture.emit(c.group.ids[packet.InterfaceID], packet)
876: 
877: 	return !more, err
878: }
879: 
880: // switchSegments makes the next segment the active one after the active one ended, writing the
881: // held packets of the next one that the active one did not write.
882: func (c *captureChain) switchSegments(ctx context.Context, timer *time.Timer) (bool, error) {
883: 	// the held packets are in the reorder buffer once this returns
884: 	defer c.capture.out.Release(c)
885: 
886: 	ended := c.active
887: 	if c.stopping && c.next != nil && c.next.started.IsZero() {
888: 		// the chain is stopping: a follow-up that has not started takes nothing over
889: 		c.next, c.held, c.emitted, c.cut = nil, nil, nil, 0
890: 	}
891: 	if c.final && c.next == nil {
892: 		return true, nil
893: 	}
894: 
895: 	if c.next == nil || c.next.started.IsZero() || c.cut == 0 {
896: 		from := ended.ended
897: 		if from.IsZero() {
898: 			from = ended.plannedEnd()
899: 		}
900: 		gap := clablabruntime.CaptureGap{
901: 			Node: c.group.display, Interfaces: c.group.interfaces, From: from,
902: 			Reason: "the follow-up capture did not overlap the previous one",
903: 		}
904: 		if c.next != nil && !c.next.started.IsZero() {
905: 			gap.To = c.next.started
906: 		}
907: 		c.capture.reportGap(gap)
908: 	}
909: 
910: 	if c.next != nil && c.next.done && !c.stopping {
911: 		// the follow-up already ended (it started too late to take over): keep what it
912: 		// captured and continue with a fresh segment
913: 		for _, packet := range c.held {
914: 			if stop, err := c.emit(packet); stop || err != nil {
915: 				return true, err
916: 			}
917: 		}
918: 		c.next, c.held, c.emitted, c.cut = nil, nil, nil, 0
919: 	}
920: 
921: 	if c.next == nil {
922: 		if !c.capture.deadline.IsZero() &&
923: 			!time.Now().Before(c.capture.deadline.Add(-c.capture.window)) {
924: 			return true, nil
925: 		}
926: 		c.active = c.start(ctx, c.segmentDuration(time.Now()))
927: 		resetTimer(timer, c.nextStartIn())
928: 
929: 		return false, nil
930: 	}
931: 
932: 	window := c.capture.window.Nanoseconds()
933: 	for _, packet := range c.held {
934: 		if c.cut != 0 {
935: 			if packet.Timestamp < c.cut-window {
936: 				continue
937: 			}
938: 			if packet.Timestamp < c.cut+window {
939: 				key := packetKey(packet)
940: 				if c.emitted[key] > 0 {
941: 					c.emitted[key]--
942: 					continue
943: 				}
944: 			}
945: 		}
946: 		if stop, err := c.emit(packet); stop || err != nil {
947: 			return true, err
948: 		}
949: 	}
950: 
951: 	c.active, c.next = c.next, nil
952: 	c.held, c.emitted, c.cut = nil, nil, 0
953: 	if c.active.done {
954: 		// the chain is stopping and the follow-up ended before the active one
955: 		return true, nil
956: 	}
957: 	resetTimer(timer, c.nextStartIn())
958: 
959: 	return false, nil
960: }
961: 
962: func resetTimer(timer *time.Timer, d time.Duration) {
963: 	if !timer.Stop() {
964: 		select {
965: 		case <-timer.C:
966: 		default:
967: 		}
968: 	}
969: 	timer.Reset(d)
970: }
971: 
972: // packetKey identifies a packet by its interface and content.
973: func packetKey(packet *clabcapture.Packet) uint64 {
974: 	hash := fnv.New64a()
975: 	var id [4]byte
976: 	id[0] = byte(packet.InterfaceID)
977: 	id[1] = byte(packet.InterfaceID >> 8)
978: 	_, _ = hash.Write(id[:])
979: 	_, _ = hash.Write(packet.Data)
980: 
981: 	return hash.Sum64()
982: }
983: 
984: // start runs one clabwire capture and reports its packets, audit records and end as events.
985: func (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {
986: 	segmentCtx, cancel := context.WithCancel(ctx)
987: 	stdinReader, stdinWriter := io.Pipe()
988: 	segment := &captureSegment{
989: 		index: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,
990: 		closeStdin: func() { _ = stdinWriter.Close() },
991: 	}
992: 	c.segments++
993: 
994: 	command := []string{
995: 		clabwireManager, "node-runtime", "packet-capture",
996: 		"--nodeName", c.group.location.NodeName,
997: 		"--format", "pcapng",
998: 		"--snapLength", strconv.Itoa(c.capture.req.SnapLength),
999: 		"--duration", duration.String(),
1000: 		clabwireStopOnStdinClose,
1001: 	}
1002: 	for _, name := range c.group.interfaces {
1003: 		command = append(command, "--interface", name)
1004: 	}
1005: 	if c.capture.req.PacketLimit > 0 {
1006: 		remaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()
1007: 		command = append(command, "--packetLimit",
1008: 			strconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))
1009: 	}
1010: 
1011: 	send := func(event segmentEvent) {
1012: 		event.segment = segment
1013: 		select {
1014: 		case c.events <- event:
1015: 		case <-segmentCtx.Done():
1016: 		}
1017: 	}
1018: 
1019: 	stdoutReader, stdoutWriter := io.Pipe()
1020: 	stderr := &auditLineWriter{send: func(audit *captureAudit) { send(segmentEvent{audit: audit}) }}
1021: 
1022: 	// The exec outlives the segment's context by up to captureStdinCloseGrace: when the segment
1023: 	// ends for any reason (the capture is cancelled or failed, the output failed, or a newer
1024: 	// segment took over), its stdin is closed first so clabwire ends on its own, and the stream
1025: 	// is cut only if it does not.
1026: 	execCtx, cancelExec := context.WithCancel(context.WithoutCancel(segmentCtx))
1027: 	execDone := make(chan struct{})
1028: 
1029: 	c.wg.Add(3)
1030: 	readDone := make(chan error, 1)
1031: 	go func() {
1032: 		defer c.wg.Done()
1033: 		readDone <- c.readSegment(stdoutReader, func(packet *clabcapture.Packet) {
1034: 			send(segmentEvent{packet: packet})
1035: 		})
1036: 		_, _ = io.Copy(io.Discard, stdoutReader)
1037: 	}()
1038: 	go func() {
1039: 		defer c.wg.Done()
1040: 		select {
1041: 		case <-execDone:
1042: 			return
1043: 		case <-segmentCtx.Done():
1044: 		}
1045: 		segment.closeStdin()
1046: 		grace := time.NewTimer(captureStdinCloseGrace)
1047: 		defer grace.Stop()
1048: 		select {
1049: 		case <-execDone:
1050: 		case <-grace.C:
1051: 			log.Debug("Capture segment did not end after its stdin closed, cutting the stream",
1052: 				"node", c.group.display, "segment", segment.index)
1053: 			cancelExec()
1054: 		}
1055: 	}()
1056: 	go func() {
1057: 		defer c.wg.Done()
1058: 		defer cancel()
1059: 		defer cancelExec()
1060: 
1061: 		err := c.capture.r.execInPodContainer()(execCtx, c.group.location.Namespace,
1062: 			c.group.location.Pod, clabwireContainer, command, stdinReader, stdoutWriter, stderr)
1063: 		close(execDone)
1064: 		// the process ended: release the stdin copy of the exec stream
1065: 		segment.closeStdin()
1066: 		_ = stdoutWriter.Close()
1067: 		readErr := <-readDone
1068: 		stderr.flush()
1069: 		if err == nil && readErr != nil {
1070: 			err = readErr
1071: 		}
1072: 		if err != nil && stderr.text() != "" {
1073: 			if unsupported := unsupportedClabwire(
1074: 				c.group.location,
1075: 				stderr.text(),
1076: 			); unsupported != nil {
1077: 				err = unsupported
1078: 			} else {
1079: 				err = fmt.Errorf("%w: %s", err, stderr.text())
1080: 			}
1081: 		}
1082: 		send(segmentEvent{done: true, err: err})
1083: 	}()
1084: 
1085: 	return segment
1086: }
1087: 
1088: // unsupportedClabwire recognizes a clabwire that rejects --stop-on-stdin-close, which every
1089: // capture passes: its release predates the capture contract the runtime needs.
1090: func unsupportedClabwire(location clablabruntime.NodeLocation, stderr string) error {
1091: 	if !strings.Contains(stderr, "flag provided but not defined") ||
1092: 		!strings.Contains(stderr, strings.TrimPrefix(clabwireStopOnStdinClose, "-")) {
1093: 		return nil
1094: 	}
1095: 
1096: 	return &unsupportedClabernetesError{reason: fmt.Sprintf(
1097: 		"clabwire in pod %s/%s does not accept packet-capture %s",
1098: 		location.Namespace, location.Pod, clabwireStopOnStdinClose)}
1099: }
1100: 
1101: // readSegment checks that a segment's interfaces are the requested ones and passes its packets
1102: // on with the segment's interface index.
1103: func (c *captureChain) readSegment(stdout io.Reader, packet func(*clabcapture.Packet)) error {
1104: 	reader := clabcapture.NewReader(stdout)
1105: 	interfaces := 0
1106: 	for {
1107: 		event, err := reader.Next()
1108: 		if errors.Is(err, io.EOF) {
1109: 			return nil
1110: 		}
1111: 		if errors.Is(err, io.ErrUnexpectedEOF) {
1112: 			// the process was stopped inside a block
1113: 			return nil
1114: 		}
1115: 		if err != nil {
1116: 			return fmt.Errorf("failed to read the clabwire capture: %w", err)
1117: 		}
1118: 		if event.Interface != nil {
1119: 			if interfaces >= len(c.group.interfaces) ||
1120: 				event.Interface.Name != c.group.interfaces[interfaces] {
1121: 				return fmt.Errorf("clabwire described interface %q, want %s in order",
1122: 					event.Interface.Name, strings.Join(c.group.interfaces, ", "))
1123: 			}
1124: 			interfaces++
1125: 			continue
1126: 		}
1127: 		if event.Packet != nil {
1128: 			packet(event.Packet)
1129: 		}
1130: 	}
1131: }
1132: 
1133: // auditLineWriter parses clabwire's stderr: audit records go to send, other lines are kept for
1134: // error messages.
1135: type auditLineWriter struct {
1136: 	send func(*captureAudit)
1137: 
1138: 	mu      sync.Mutex
1139: 	partial []byte
1140: 	other   []string
1141: }
1142: 
1143: func (w *auditLineWriter) Write(data []byte) (int, error) {
1144: 	w.mu.Lock()
1145: 	w.partial = append(w.partial, data...)
1146: 	var lines [][]byte
1147: 	for {
1148: 		idx := bytes.IndexByte(w.partial, '\n')
1149: 		if idx < 0 {
1150: 			break
1151: 		}
1152: 		lines = append(lines, append([]byte(nil), w.partial[:idx]...))
1153: 		w.partial = w.partial[idx+1:]
1154: 	}
1155: 	w.mu.Unlock()
1156: 
1157: 	for _, line := range lines {
1158: 		w.line(line)
1159: 	}
1160: 
1161: 	return len(data), nil
1162: }
1163: 
1164: func (w *auditLineWriter) flush() {
1165: 	w.mu.Lock()
1166: 	line := w.partial
1167: 	w.partial = nil
1168: 	w.mu.Unlock()
1169: 	if len(bytes.TrimSpace(line)) != 0 {
1170: 		w.line(line)
1171: 	}
1172: }
1173: 
1174: func (w *auditLineWriter) line(line []byte) {
1175: 	line = bytes.TrimSpace(line)
1176: 	if len(line) == 0 {
1177: 		return
1178: 	}
1179: 
1180: 	var audit captureAudit
1181: 	if err := json.Unmarshal(
1182: 		line,
1183: 		&audit,
1184: 	); err == nil &&
1185: 		audit.SchemaVersion == captureAuditSchema {
1186: 		w.send(&audit)
1187: 		return
1188: 	}
1189: 
1190: 	w.mu.Lock()
1191: 	defer w.mu.Unlock()
1192: 	if len(w.other) < 20 {
1193: 		w.other = append(w.other, string(line))
1194: 	}
1195: }
1196: 
1197: func (w *auditLineWriter) text() string {
1198: 	w.mu.Lock()
1199: 	defer w.mu.Unlock()
1200: 
1201: 	return strings.Join(w.other, "; ")
1202: }

(End of file - total 1202 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196527e0b001Q8qX5Ih3F4nQRA",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965275f0001jy0JtWtHQA7Mlj",
  "callID": "call_749cf61324324c63b93d4246",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/capture.go",
      "limit": 530,
      "offset": 680
    },
    "output": "<path>/source/head/labruntime/clabernetes/capture.go</path>\n<type>file</type>\n<content>\n680: func (c *captureChain) stop(timer *time.Timer) {\n681: \tc.stopping = true\n682: \tc.final = true\n683: \ttimer.Stop()\n684: \tc.active.closeStdin()\n685: \tif c.next != nil {\n686: \t\tc.next.closeStdin()\n687: \t}\n688: }\n689: \n690: // drain waits for the segment goroutines after the chain ended.\n691: func (c *captureChain) drain() {\n692: \tdone := make(chan struct{})\n693: \tgo func() {\n694: \t\tc.wg.Wait()\n695: \t\tclose(done)\n696: \t}()\n697: \tfor {\n698: \t\tselect {\n699: \t\tcase <-done:\n700: \t\t\treturn\n701: \t\tcase <-c.events:\n702: \t\t}\n703: \t}\n704: }\n705: \n706: // segmentDuration is the requested duration of a segment starting now.\n707: func (c *captureChain) segmentDuration(now time.Time) time.Duration {\n708: \tduration := c.capture.segment\n709: \tif !c.capture.deadline.IsZero() {\n710: \t\tduration = min(duration, c.capture.deadline.Sub(now))\n711: \t}\n712: \n713: \treturn max(duration, minCaptureSegment)\n714: }\n715: \n716: // nextStartIn is the time until the follow-up of the active segment is due. It marks the chain\n717: // final when none is due.\n718: func (c *captureChain) nextStartIn() time.Duration {\n719: \tif c.stopping {\n720: \t\tc.final = true\n721: \t\treturn maxCaptureSegment\n722: \t}\n723: \tactiveEnd := c.active.localStart.Add(c.active.duration)\n724: \tif !c.capture.deadline.IsZero() &&\n725: \t\t!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {\n726: \t\tc.final = true\n727: \t\treturn maxCaptureSegment\n728: \t}\n729: \tc.final = false\n730: \n731: \treturn max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)\n732: }\n733: \n734: func (c *captureChain) startNext(ctx context.Context) {\n735: \tc.next = c.start(ctx, c.segmentDuration(time.Now()))\n736: \tc.emitted = map[uint64]int{}\n737: \tc.held = nil\n738: \tc.cut = 0\n739: }\n740: \n741: func (c *captureChain) handle(\n742: \tctx context.Context,\n743: \tevent segmentEvent,\n744: \ttimer *time.Timer,\n745: ) (bool, error) {\n746: \tsegment := event.segment\n747: \n748: \tswitch {\n749: \tcase event.audit != nil:\n750: \t\treturn false, c.handleAudit(segment, event.audit)\n751: \tcase event.packet != nil:\n752: \t\treturn c.handlePacket(segment, event.packet)\n753: \tcase event.done:\n754: \t\tsegment.done = true\n755: \t\tif segment.stopTimer != nil {\n756: \t\t\tsegment.stopTimer.Stop()\n757: \t\t}\n758: \t\tif event.err != nil && !c.stopping {\n759: \t\t\tif segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {\n760: \t\t\t\t// the follow-up did not start; try again while the active one still runs\n761: \t\t\t\tc.retries++\n762: \t\t\t\tlog.Warn(\"Capture follow-up segment failed to start, retrying\",\n763: \t\t\t\t\t\"node\", c.group.display, \"error\", event.err)\n764: \t\t\t\tc.next = nil\n765: \t\t\t\tresetTimer(timer, time.Second)\n766: \n767: \t\t\t\treturn false, nil\n768: \t\t\t}\n769: \n770: \t\t\treturn true, fmt.Errorf(\"capture on c9s node %s/%s/%s failed: %w\",\n771: \t\t\t\tc.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)\n772: \t\t}\n773: \t\tif segment != c.active {\n774: \t\t\treturn false, nil\n775: \t\t}\n776: \n777: \t\treturn c.switchSegments(ctx, timer)\n778: \t}\n779: \n780: \treturn false, nil\n781: }\n782: \n783: func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {\n784: \tswitch audit.Status {\n785: \tcase captureAuditStarted:\n786: \t\tsegment.started = audit.Time\n787: \t\tlog.Debug(\"Capture segment started\", \"node\", c.group.display, \"segment\", segment.index,\n788: \t\t\t\"interfaces\", strings.Join(c.group.interfaces, \",\"), \"duration\", segment.duration)\n789: \t\tif segment == c.next && !c.active.started.IsZero() {\n790: \t\t\tc.setCut()\n791: \t\t}\n792: \t\tif segment == c.next {\n793: \t\t\tc.retries = 0\n794: \t\t}\n795: \tcase captureAuditSucceeded:\n796: \t\tsegment.ended = audit.Time\n797: \t\tlog.Debug(\"Capture segment succeeded\", \"node\", c.group.display,\n798: \t\t\t\"segment\", segment.index, \"packets\", audit.Packets)\n799: \tcase captureAuditDenied, captureAuditFailed:\n800: \t\treturn captureAuditError(c.group.display, audit)\n801: \t}\n802: \n803: \treturn nil\n804: }\n805: \n806: // captureAuditError turns a Denied or Failed clabwire audit record into an error.\n807: func captureAuditError(node string, audit *captureAudit) error {\n808: \tverb := \"failed\"\n809: \tif audit.Status == captureAuditDenied {\n810: \t\tverb = \"was denied\"\n811: \t}\n812: \tinterfaces := make([]string, 0, len(audit.Interfaces))\n813: \tfor _, intf := range audit.Interfaces {\n814: \t\tinterfaces = append(interfaces, intf.Name)\n815: \t}\n816: \n817: \treturn fmt.Errorf(\"capture of %s on node %s %s by clabwire: %s\",\n818: \t\tstrings.Join(interfaces, \",\"), node, verb, audit.Reason)\n819: }\n820: \n821: // setCut places the cut in the middle of the overlap of the active and the next segment, both\n822: // measured on the pod clock.\n823: func (c *captureChain) setCut() {\n824: \toverlapStart := c.next.started\n825: \toverlapEnd := c.active.plannedEnd()\n826: \tif overlapEnd.Sub(overlapStart) < 2*c.capture.window {\n827: \t\t// the overlap is too short to match packets around a cut: the switch is reported as a\n828: \t\t// gap once the active segment ended\n829: \t\tc.cut = 0\n830: \t\treturn\n831: \t}\n832: \tc.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()\n833: \n834: \twindow := c.capture.window.Nanoseconds()\n835: \t// Packets the next segment holds back are stamped from T-W on: other chains' packets after\n836: \t// that wait in the reorder buffer until the switch, so the merged stream stays in order.\n837: \tc.capture.out.Hold(c, c.cut-window)\n838: \n839: \t// The active segment only matters for packets stamped before T. Once the pod clock passed\n840: \t// T+W, it is closed: packets it read until then are still delivered, and the ones it reads\n841: \t// later are stamped after T and dropped anyway. The next segment's Started record was\n842: \t// written on the pod clock no later than now, so the pod clock passes T+W no later than\n843: \t// (T - Started + W) from now.\n844: \tactive := c.active\n845: \tactive.stopTimer = time.AfterFunc(\n846: \t\ttime.Duration(c.cut-c.next.started.UnixNano()+window), active.closeStdin)\n847: }\n848: \n849: func (c *captureChain) handlePacket(\n850: \tsegment *captureSegment,\n851: \tpacket *clabcapture.Packet,\n852: ) (bool, error) {\n853: \tswitch segment {\n854: \tcase c.active:\n855: \t\tif c.cut != 0 && packet.Timestamp >= c.cut {\n856: \t\t\treturn false, nil\n857: \t\t}\n858: \t\tif c.next != nil {\n859: \t\t\tc.emitted[packetKey(packet)]++\n860: \t\t}\n861: \n862: \t\treturn c.emit(packet)\n863: \tcase c.next:\n864: \t\tc.held = append(c.held, packet)\n865: \t}\n866: \n867: \treturn false, nil\n868: }\n869: \n870: func (c *captureChain) emit(packet *clabcapture.Packet) (bool, error) {\n871: \tif int(packet.InterfaceID) >= len(c.group.ids) {\n872: \t\treturn true, fmt.Errorf(\"clabwire wrote a packet for interface %d of %d\",\n873: \t\t\tpacket.InterfaceID, len(c.group.ids))\n874: \t}\n875: \tmore, err := c.capture.emit(c.group.ids[packet.InterfaceID], packet)\n876: \n877: \treturn !more, err\n878: }\n879: \n880: // switchSegments makes the next segment the active one after the active one ended, writing the\n881: // held packets of the next one that the active one did not write.\n882: func (c *captureChain) switchSegments(ctx context.Context, timer *time.Timer) (bool, error) {\n883: \t// the held packets are in the reorder buffer once this returns\n884: \tdefer c.capture.out.Release(c)\n885: \n886: \tended := c.active\n887: \tif c.stopping && c.next != nil && c.next.started.IsZero() {\n888: \t\t// the chain is stopping: a follow-up that has not started takes nothing over\n889: \t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n890: \t}\n891: \tif c.final && c.next == nil {\n892: \t\treturn true, nil\n893: \t}\n894: \n895: \tif c.next == nil || c.next.started.IsZero() || c.cut == 0 {\n896: \t\tfrom := ended.ended\n897: \t\tif from.IsZero() {\n898: \t\t\tfrom = ended.plannedEnd()\n899: \t\t}\n900: \t\tgap := clablabruntime.CaptureGap{\n901: \t\t\tNode: c.group.display, Interfaces: c.group.interfaces, From: from,\n902: \t\t\tReason: \"the follow-up capture did not overlap the previous one\",\n903: \t\t}\n904: \t\tif c.next != nil && !c.next.started.IsZero() {\n905: \t\t\tgap.To = c.next.started\n906: \t\t}\n907: \t\tc.capture.reportGap(gap)\n908: \t}\n909: \n910: \tif c.next != nil && c.next.done && !c.stopping {\n911: \t\t// the follow-up already ended (it started too late to take over): keep what it\n912: \t\t// captured and continue with a fresh segment\n913: \t\tfor _, packet := range c.held {\n914: \t\t\tif stop, err := c.emit(packet); stop || err != nil {\n915: \t\t\t\treturn true, err\n916: \t\t\t}\n917: \t\t}\n918: \t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n919: \t}\n920: \n921: \tif c.next == nil {\n922: \t\tif !c.capture.deadline.IsZero() &&\n923: \t\t\t!time.Now().Before(c.capture.deadline.Add(-c.capture.window)) {\n924: \t\t\treturn true, nil\n925: \t\t}\n926: \t\tc.active = c.start(ctx, c.segmentDuration(time.Now()))\n927: \t\tresetTimer(timer, c.nextStartIn())\n928: \n929: \t\treturn false, nil\n930: \t}\n931: \n932: \twindow := c.capture.window.Nanoseconds()\n933: \tfor _, packet := range c.held {\n934: \t\tif c.cut != 0 {\n935: \t\t\tif packet.Timestamp < c.cut-window {\n936: \t\t\t\tcontinue\n937: \t\t\t}\n938: \t\t\tif packet.Timestamp < c.cut+window {\n939: \t\t\t\tkey := packetKey(packet)\n940: \t\t\t\tif c.emitted[key] > 0 {\n941: \t\t\t\t\tc.emitted[key]--\n942: \t\t\t\t\tcontinue\n943: \t\t\t\t}\n944: \t\t\t}\n945: \t\t}\n946: \t\tif stop, err := c.emit(packet); stop || err != nil {\n947: \t\t\treturn true, err\n948: \t\t}\n949: \t}\n950: \n951: \tc.active, c.next = c.next, nil\n952: \tc.held, c.emitted, c.cut = nil, nil, 0\n953: \tif c.active.done {\n954: \t\t// the chain is stopping and the follow-up ended before the active one\n955: \t\treturn true, nil\n956: \t}\n957: \tresetTimer(timer, c.nextStartIn())\n958: \n959: \treturn false, nil\n960: }\n961: \n962: func resetTimer(timer *time.Timer, d time.Duration) {\n963: \tif !timer.Stop() {\n964: \t\tselect {\n965: \t\tcase <-timer.C:\n966: \t\tdefault:\n967: \t\t}\n968: \t}\n969: \ttimer.Reset(d)\n970: }\n971: \n972: // packetKey identifies a packet by its interface and content.\n973: func packetKey(packet *clabcapture.Packet) uint64 {\n974: \thash := fnv.New64a()\n975: \tvar id [4]byte\n976: \tid[0] = byte(packet.InterfaceID)\n977: \tid[1] = byte(packet.InterfaceID >> 8)\n978: \t_, _ = hash.Write(id[:])\n979: \t_, _ = hash.Write(packet.Data)\n980: \n981: \treturn hash.Sum64()\n982: }\n983: \n984: // start runs one clabwire capture and reports its packets, audit records and end as events.\n985: func (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {\n986: \tsegmentCtx, cancel := context.WithCancel(ctx)\n987: \tstdinReader, stdinWriter := io.Pipe()\n988: \tsegment := &captureSegment{\n989: \t\tindex: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,\n990: \t\tcloseStdin: func() { _ = stdinWriter.Close() },\n991: \t}\n992: \tc.segments++\n993: \n994: \tcommand := []string{\n995: \t\tclabwireManager, \"node-runtime\", \"packet-capture\",\n996: \t\t\"--nodeName\", c.group.location.NodeName,\n997: \t\t\"--format\", \"pcapng\",\n998: \t\t\"--snapLength\", strconv.Itoa(c.capture.req.SnapLength),\n999: \t\t\"--duration\", duration.String(),\n1000: \t\tclabwireStopOnStdinClose,\n1001: \t}\n1002: \tfor _, name := range c.group.interfaces {\n1003: \t\tcommand = append(command, \"--interface\", name)\n1004: \t}\n1005: \tif c.capture.req.PacketLimit > 0 {\n1006: \t\tremaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()\n1007: \t\tcommand = append(command, \"--packetLimit\",\n1008: \t\t\tstrconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))\n1009: \t}\n1010: \n1011: \tsend := func(event segmentEvent) {\n1012: \t\tevent.segment = segment\n1013: \t\tselect {\n1014: \t\tcase c.events <- event:\n1015: \t\tcase <-segmentCtx.Done():\n1016: \t\t}\n1017: \t}\n1018: \n1019: \tstdoutReader, stdoutWriter := io.Pipe()\n1020: \tstderr := &auditLineWriter{send: func(audit *captureAudit) { send(segmentEvent{audit: audit}) }}\n1021: \n1022: \t// The exec outlives the segment's context by up to captureStdinCloseGrace: when the segment\n1023: \t// ends for any reason (the capture is cancelled or failed, the output failed, or a newer\n1024: \t// segment took over), its stdin is closed first so clabwire ends on its own, and the stream\n1025: \t// is cut only if it does not.\n1026: \texecCtx, cancelExec := context.WithCancel(context.WithoutCancel(segmentCtx))\n1027: \texecDone := make(chan struct{})\n1028: \n1029: \tc.wg.Add(3)\n1030: \treadDone := make(chan error, 1)\n1031: \tgo func() {\n1032: \t\tdefer c.wg.Done()\n1033: \t\treadDone <- c.readSegment(stdoutReader, func(packet *clabcapture.Packet) {\n1034: \t\t\tsend(segmentEvent{packet: packet})\n1035: \t\t})\n1036: \t\t_, _ = io.Copy(io.Discard, stdoutReader)\n1037: \t}()\n1038: \tgo func() {\n1039: \t\tdefer c.wg.Done()\n1040: \t\tselect {\n1041: \t\tcase <-execDone:\n1042: \t\t\treturn\n1043: \t\tcase <-segmentCtx.Done():\n1044: \t\t}\n1045: \t\tsegment.closeStdin()\n1046: \t\tgrace := time.NewTimer(captureStdinCloseGrace)\n1047: \t\tdefer grace.Stop()\n1048: \t\tselect {\n1049: \t\tcase <-execDone:\n1050: \t\tcase <-grace.C:\n1051: \t\t\tlog.Debug(\"Capture segment did not end after its stdin closed, cutting the stream\",\n1052: \t\t\t\t\"node\", c.group.display, \"segment\", segment.index)\n1053: \t\t\tcancelExec()\n1054: \t\t}\n1055: \t}()\n1056: \tgo func() {\n1057: \t\tdefer c.wg.Done()\n1058: \t\tdefer cancel()\n1059: \t\tdefer cancelExec()\n1060: \n1061: \t\terr := c.capture.r.execInPodContainer()(execCtx, c.group.location.Namespace,\n1062: \t\t\tc.group.location.Pod, clabwireContainer, command, stdinReader, stdoutWriter, stderr)\n1063: \t\tclose(execDone)\n1064: \t\t// the process ended: release the stdin copy of the exec stream\n1065: \t\tsegment.closeStdin()\n1066: \t\t_ = stdoutWriter.Close()\n1067: \t\treadErr := <-readDone\n1068: \t\tstderr.flush()\n1069: \t\tif err == nil && readErr != nil {\n1070: \t\t\terr = readErr\n1071: \t\t}\n1072: \t\tif err != nil && stderr.text() != \"\" {\n1073: \t\t\tif unsupported := unsupportedClabwire(\n1074: \t\t\t\tc.group.location,\n1075: \t\t\t\tstderr.text(),\n1076: \t\t\t); unsupported != nil {\n1077: \t\t\t\terr = unsupported\n1078: \t\t\t} else {\n1079: \t\t\t\terr = fmt.Errorf(\"%w: %s\", err, stderr.text())\n1080: \t\t\t}\n1081: \t\t}\n1082: \t\tsend(segmentEvent{done: true, err: err})\n1083: \t}()\n1084: \n1085: \treturn segment\n1086: }\n1087: \n1088: // unsupportedClabwire recognizes a clabwire that rejects --stop-on-stdin-close, which every\n1089: // capture passes: its release predates the capture contract the runtime needs.\n1090: func unsupportedClabwire(location clablabruntime.NodeLocation, stderr string) error {\n1091: \tif !strings.Contains(stderr, \"flag provided but not defined\") ||\n1092: \t\t!strings.Contains(stderr, strings.TrimPrefix(clabwireStopOnStdinClose, \"-\")) {\n1093: \t\treturn nil\n1094: \t}\n1095: \n1096: \treturn &unsupportedClabernetesError{reason: fmt.Sprintf(\n1097: \t\t\"clabwire in pod %s/%s does not accept packet-capture %s\",\n1098: \t\tlocation.Namespace, location.Pod, clabwireStopOnStdinClose)}\n1099: }\n1100: \n1101: // readSegment checks that a segment's interfaces are the requested ones and passes its packets\n1102: // on with the segment's interface index.\n1103: func (c *captureChain) readSegment(stdout io.Reader, packet func(*clabcapture.Packet)) error {\n1104: \treader := clabcapture.NewReader(stdout)\n1105: \tinterfaces := 0\n1106: \tfor {\n1107: \t\tevent, err := reader.Next()\n1108: \t\tif errors.Is(err, io.EOF) {\n1109: \t\t\treturn nil\n1110: \t\t}\n1111: \t\tif errors.Is(err, io.ErrUnexpectedEOF) {\n1112: \t\t\t// the process was stopped inside a block\n1113: \t\t\treturn nil\n1114: \t\t}\n1115: \t\tif err != nil {\n1116: \t\t\treturn fmt.Errorf(\"failed to read the clabwire capture: %w\", err)\n1117: \t\t}\n1118: \t\tif event.Interface != nil {\n1119: \t\t\tif interfaces >= len(c.group.interfaces) ||\n1120: \t\t\t\tevent.Interface.Name != c.group.interfaces[interfaces] {\n1121: \t\t\t\treturn fmt.Errorf(\"clabwire described interface %q, want %s in order\",\n1122: \t\t\t\t\tevent.Interface.Name, strings.Join(c.group.interfaces, \", \"))\n1123: \t\t\t}\n1124: \t\t\tinterfaces++\n1125: \t\t\tcontinue\n1126: \t\t}\n1127: \t\tif event.Packet != nil {\n1128: \t\t\tpacket(event.Packet)\n1129: \t\t}\n1130: \t}\n1131: }\n1132: \n1133: // auditLineWriter parses clabwire's stderr: audit records go to send, other lines are kept for\n1134: // error messages.\n1135: type auditLineWriter struct {\n1136: \tsend func(*captureAudit)\n1137: \n1138: \tmu      sync.Mutex\n1139: \tpartial []byte\n1140: \tother   []string\n1141: }\n1142: \n1143: func (w *auditLineWriter) Write(data []byte) (int, error) {\n1144: \tw.mu.Lock()\n1145: \tw.partial = append(w.partial, data...)\n1146: \tvar lines [][]byte\n1147: \tfor {\n1148: \t\tidx := bytes.IndexByte(w.partial, '\\n')\n1149: \t\tif idx < 0 {\n1150: \t\t\tbreak\n1151: \t\t}\n1152: \t\tlines = append(lines, append([]byte(nil), w.partial[:idx]...))\n1153: \t\tw.partial = w.partial[idx+1:]\n1154: \t}\n1155: \tw.mu.Unlock()\n1156: \n1157: \tfor _, line := range lines {\n1158: \t\tw.line(line)\n1159: \t}\n1160: \n1161: \treturn len(data), nil\n1162: }\n1163: \n1164: func (w *auditLineWriter) flush() {\n1165: \tw.mu.Lock()\n1166: \tline := w.partial\n1167: \tw.partial = nil\n1168: \tw.mu.Unlock()\n1169: \tif len(bytes.TrimSpace(line)) != 0 {\n1170: \t\tw.line(line)\n1171: \t}\n1172: }\n1173: \n1174: func (w *auditLineWriter) line(line []byte) {\n1175: \tline = bytes.TrimSpace(line)\n1176: \tif len(line) == 0 {\n1177: \t\treturn\n1178: \t}\n1179: \n1180: \tvar audit captureAudit\n1181: \tif err := json.Unmarshal(\n1182: \t\tline,\n1183: \t\t&audit,\n1184: \t); err == nil &&\n1185: \t\taudit.SchemaVersion == captureAuditSchema {\n1186: \t\tw.send(&audit)\n1187: \t\treturn\n1188: \t}\n1189: \n1190: \tw.mu.Lock()\n1191: \tdefer w.mu.Unlock()\n1192: \tif len(w.other) < 20 {\n1193: \t\tw.other = append(w.other, string(line))\n1194: \t}\n1195: }\n1196: \n1197: func (w *auditLineWriter) text() string {\n1198: \tw.mu.Lock()\n1199: \tdefer w.mu.Unlock()\n1200: \n1201: \treturn strings.Join(w.other, \"; \")\n1202: }\n\n(End of file - total 1202 lines)\n</content>",
    "title": "source/head/labruntime/clabernetes/capture.go",
    "metadata": {
      "preview": "func (c *captureChain) stop(timer *time.Timer) {\n\tc.stopping = true\n\tc.final = true\n\ttimer.Stop()\n\tc.active.closeStdin()\n\tif c.next != nil {\n\t\tc.next.closeStdin()\n\t}\n}\n\n// drain waits for the segment goroutines after the chain ended.\nfunc (c *captureChain) drain() {\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tc.wg.Wait()\n\t\tclose(done)\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-done:",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/capture.go",
        "text": "func (c *captureChain) stop(timer *time.Timer) {\n\tc.stopping = true\n\tc.final = true\n\ttimer.Stop()\n\tc.active.closeStdin()\n\tif c.next != nil {\n\t\tc.next.closeStdin()\n\t}\n}\n\n// drain waits for the segment goroutines after the chain ended.\nfunc (c *captureChain) drain() {\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tc.wg.Wait()\n\t\tclose(done)\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\treturn\n\t\tcase <-c.events:\n\t\t}\n\t}\n}\n\n// segmentDuration is the requested duration of a segment starting now.\nfunc (c *captureChain) segmentDuration(now time.Time) time.Duration {\n\tduration := c.capture.segment\n\tif !c.capture.deadline.IsZero() {\n\t\tduration = min(duration, c.capture.deadline.Sub(now))\n\t}\n\n\treturn max(duration, minCaptureSegment)\n}\n\n// nextStartIn is the time until the follow-up of the active segment is due. It marks the chain\n// final when none is due.\nfunc (c *captureChain) nextStartIn() time.Duration {\n\tif c.stopping {\n\t\tc.final = true\n\t\treturn maxCaptureSegment\n\t}\n\tactiveEnd := c.active.localStart.Add(c.active.duration)\n\tif !c.capture.deadline.IsZero() &&\n\t\t!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {\n\t\tc.final = true\n\t\treturn maxCaptureSegment\n\t}\n\tc.final = false\n\n\treturn max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)\n}\n\nfunc (c *captureChain) startNext(ctx context.Context) {\n\tc.next = c.start(ctx, c.segmentDuration(time.Now()))\n\tc.emitted = map[uint64]int{}\n\tc.held = nil\n\tc.cut = 0\n}\n\nfunc (c *captureChain) handle(\n\tctx context.Context,\n\tevent segmentEvent,\n\ttimer *time.Timer,\n) (bool, error) {\n\tsegment := event.segment\n\n\tswitch {\n\tcase event.audit != nil:\n\t\treturn false, c.handleAudit(segment, event.audit)\n\tcase event.packet != nil:\n\t\treturn c.handlePacket(segment, event.packet)\n\tcase event.done:\n\t\tsegment.done = true\n\t\tif segment.stopTimer != nil {\n\t\t\tsegment.stopTimer.Stop()\n\t\t}\n\t\tif event.err != nil && !c.stopping {\n\t\t\tif segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {\n\t\t\t\t// the follow-up did not start; try again while the active one still runs\n\t\t\t\tc.retries++\n\t\t\t\tlog.Warn(\"Capture follow-up segment failed to start, retrying\",\n\t\t\t\t\t\"node\", c.group.display, \"error\", event.err)\n\t\t\t\tc.next = nil\n\t\t\t\tresetTimer(timer, time.Second)\n\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\treturn true, fmt.Errorf(\"capture on c9s node %s/%s/%s failed: %w\",\n\t\t\t\tc.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)\n\t\t}\n\t\tif segment != c.active {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn c.switchSegments(ctx, timer)\n\t}\n\n\treturn false, nil\n}\n\nfunc (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {\n\tswitch audit.Status {\n\tcase captureAuditStarted:\n\t\tsegment.started = audit.Time\n\t\tlog.Debug(\"Capture segment started\", \"node\", c.group.display, \"segment\", segment.index,\n\t\t\t\"interfaces\", strings.Join(c.group.interfaces, \",\"), \"duration\", segment.duration)\n\t\tif segment == c.next && !c.active.started.IsZero() {\n\t\t\tc.setCut()\n\t\t}\n\t\tif segment == c.next {\n\t\t\tc.retries = 0\n\t\t}\n\tcase captureAuditSucceeded:\n\t\tsegment.ended = audit.Time\n\t\tlog.Debug(\"Capture segment succeeded\", \"node\", c.group.display,\n\t\t\t\"segment\", segment.index, \"packets\", audit.Packets)\n\tcase captureAuditDenied, captureAuditFailed:\n\t\treturn captureAuditError(c.group.display, audit)\n\t}\n\n\treturn nil\n}\n\n// captureAuditError turns a Denied or Failed clabwire audit record into an error.\nfunc captureAuditError(node string, audit *captureAudit) error {\n\tverb := \"failed\"\n\tif audit.Status == captureAuditDenied {\n\t\tverb = \"was denied\"\n\t}\n\tinterfaces := make([]string, 0, len(audit.Interfaces))\n\tfor _, intf := range audit.Interfaces {\n\t\tinterfaces = append(interfaces, intf.Name)\n\t}\n\n\treturn fmt.Errorf(\"capture of %s on node %s %s by clabwire: %s\",\n\t\tstrings.Join(interfaces, \",\"), node, verb, audit.Reason)\n}\n\n// setCut places the cut in the middle of the overlap of the active and the next segment, both\n// measured on the pod clock.\nfunc (c *captureChain) setCut() {\n\toverlapStart := c.next.started\n\toverlapEnd := c.active.plannedEnd()\n\tif overlapEnd.Sub(overlapStart) < 2*c.capture.window {\n\t\t// the overlap is too short to match packets around a cut: the switch is reported as a\n\t\t// gap once the active segment ended\n\t\tc.cut = 0\n\t\treturn\n\t}\n\tc.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()\n\n\twindow := c.capture.window.Nanoseconds()\n\t// Packets the next segment holds back are stamped from T-W on: other chains' packets after\n\t// that wait in the reorder buffer until the switch, so the merged stream stays in order.\n\tc.capture.out.Hold(c, c.cut-window)\n\n\t// The active segment only matters for packets stamped before T. Once the pod clock passed\n\t// T+W, it is closed: packets it read until then are still delivered, and the ones it reads\n\t// later are stamped after T and dropped anyway. The next segment's Started record was\n\t// written on the pod clock no later than now, so the pod clock passes T+W no later than\n\t// (T - Started + W) from now.\n\tactive := c.active\n\tactive.stopTimer = time.AfterFunc(\n\t\ttime.Duration(c.cut-c.next.started.UnixNano()+window), active.closeStdin)\n}\n\nfunc (c *captureChain) handlePacket(\n\tsegment *captureSegment,\n\tpacket *clabcapture.Packet,\n) (bool, error) {\n\tswitch segment {\n\tcase c.active:\n\t\tif c.cut != 0 && packet.Timestamp >= c.cut {\n\t\t\treturn false, nil\n\t\t}\n\t\tif c.next != nil {\n\t\t\tc.emitted[packetKey(packet)]++\n\t\t}\n\n\t\treturn c.emit(packet)\n\tcase c.next:\n\t\tc.held = append(c.held, packet)\n\t}\n\n\treturn false, nil\n}\n\nfunc (c *captureChain) emit(packet *clabcapture.Packet) (bool, error) {\n\tif int(packet.InterfaceID) >= len(c.group.ids) {\n\t\treturn true, fmt.Errorf(\"clabwire wrote a packet for interface %d of %d\",\n\t\t\tpacket.InterfaceID, len(c.group.ids))\n\t}\n\tmore, err := c.capture.emit(c.group.ids[packet.InterfaceID], packet)\n\n\treturn !more, err\n}\n\n// switchSegments makes the next segment the active one after the active one ended, writing the\n// held packets of the next one that the active one did not write.\nfunc (c *captureChain) switchSegments(ctx context.Context, timer *time.Timer) (bool, error) {\n\t// the held packets are in the reorder buffer once this returns\n\tdefer c.capture.out.Release(c)\n\n\tended := c.active\n\tif c.stopping && c.next != nil && c.next.started.IsZero() {\n\t\t// the chain is stopping: a follow-up that has not started takes nothing over\n\t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n\t}\n\tif c.final && c.next == nil {\n\t\treturn true, nil\n\t}\n\n\tif c.next == nil || c.next.started.IsZero() || c.cut == 0 {\n\t\tfrom := ended.ended\n\t\tif from.IsZero() {\n\t\t\tfrom = ended.plannedEnd()\n\t\t}\n\t\tgap := clablabruntime.CaptureGap{\n\t\t\tNode: c.group.display, Interfaces: c.group.interfaces, From: from,\n\t\t\tReason: \"the follow-up capture did not overlap the previous one\",\n\t\t}\n\t\tif c.next != nil && !c.next.started.IsZero() {\n\t\t\tgap.To = c.next.started\n\t\t}\n\t\tc.capture.reportGap(gap)\n\t}\n\n\tif c.next != nil && c.next.done && !c.stopping {\n\t\t// the follow-up already ended (it started too late to take over): keep what it\n\t\t// captured and continue with a fresh segment\n\t\tfor _, packet := range c.held {\n\t\t\tif stop, err := c.emit(packet); stop || err != nil {\n\t\t\t\treturn true, err\n\t\t\t}\n\t\t}\n\t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n\t}\n\n\tif c.next == nil {\n\t\tif !c.capture.deadline.IsZero() &&\n\t\t\t!time.Now().Before(c.capture.deadline.Add(-c.capture.window)) {\n\t\t\treturn true, nil\n\t\t}\n\t\tc.active = c.start(ctx, c.segmentDuration(time.Now()))\n\t\tresetTimer(timer, c.nextStartIn())\n\n\t\treturn false, nil\n\t}\n\n\twindow := c.capture.window.Nanoseconds()\n\tfor _, packet := range c.held {\n\t\tif c.cut != 0 {\n\t\t\tif packet.Timestamp < c.cut-window {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif packet.Timestamp < c.cut+window {\n\t\t\t\tkey := packetKey(packet)\n\t\t\t\tif c.emitted[key] > 0 {\n\t\t\t\t\tc.emitted[key]--\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif stop, err := c.emit(packet); stop || err != nil {\n\t\t\treturn true, err\n\t\t}\n\t}\n\n\tc.active, c.next = c.next, nil\n\tc.held, c.emitted, c.cut = nil, nil, 0\n\tif c.active.done {\n\t\t// the chain is stopping and the follow-up ended before the active one\n\t\treturn true, nil\n\t}\n\tresetTimer(timer, c.nextStartIn())\n\n\treturn false, nil\n}\n\nfunc resetTimer(timer *time.Timer, d time.Duration) {\n\tif !timer.Stop() {\n\t\tselect {\n\t\tcase <-timer.C:\n\t\tdefault:\n\t\t}\n\t}\n\ttimer.Reset(d)\n}\n\n// packetKey identifies a packet by its interface and content.\nfunc packetKey(packet *clabcapture.Packet) uint64 {\n\thash := fnv.New64a()\n\tvar id [4]byte\n\tid[0] = byte(packet.InterfaceID)\n\tid[1] = byte(packet.InterfaceID >> 8)\n\t_, _ = hash.Write(id[:])\n\t_, _ = hash.Write(packet.Data)\n\n\treturn hash.Sum64()\n}\n\n// start runs one clabwire capture and reports its packets, audit records and end as events.\nfunc (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {\n\tsegmentCtx, cancel := context.WithCancel(ctx)\n\tstdinReader, stdinWriter := io.Pipe()\n\tsegment := &captureSegment{\n\t\tindex: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,\n\t\tcloseStdin: func() { _ = stdinWriter.Close() },\n\t}\n\tc.segments++\n\n\tcommand := []string{\n\t\tclabwireManager, \"node-runtime\", \"packet-capture\",\n\t\t\"--nodeName\", c.group.location.NodeName,\n\t\t\"--format\", \"pcapng\",\n\t\t\"--snapLength\", strconv.Itoa(c.capture.req.SnapLength),\n\t\t\"--duration\", duration.String(),\n\t\tclabwireStopOnStdinClose,\n\t}\n\tfor _, name := range c.group.interfaces {\n\t\tcommand = append(command, \"--interface\", name)\n\t}\n\tif c.capture.req.PacketLimit > 0 {\n\t\tremaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()\n\t\tcommand = append(command, \"--packetLimit\",\n\t\t\tstrconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))\n\t}\n\n\tsend := func(event segmentEvent) {\n\t\tevent.segment = segment\n\t\tselect {\n\t\tcase c.events <- event:\n\t\tcase <-segmentCtx.Done():\n\t\t}\n\t}\n\n\tstdoutReader, stdoutWriter := io.Pipe()\n\tstderr := &auditLineWriter{send: func(audit *captureAudit) { send(segmentEvent{audit: audit}) }}\n\n\t// The exec outlives the segment's context by up to captureStdinCloseGrace: when the segment\n\t// ends for any reason (the capture is cancelled or failed, the output failed, or a newer\n\t// segment took over), its stdin is closed first so clabwire ends on its own, and the stream\n\t// is cut only if it does not.\n\texecCtx, cancelExec := context.WithCancel(context.WithoutCancel(segmentCtx))\n\texecDone := make(chan struct{})\n\n\tc.wg.Add(3)\n\treadDone := make(chan error, 1)\n\tgo func() {\n\t\tdefer c.wg.Done()\n\t\treadDone <- c.readSegment(stdoutReader, func(packet *clabcapture.Packet) {\n\t\t\tsend(segmentEvent{packet: packet})\n\t\t})\n\t\t_, _ = io.Copy(io.Discard, stdoutReader)\n\t}()\n\tgo func() {\n\t\tdefer c.wg.Done()\n\t\tselect {\n\t\tcase <-execDone:\n\t\t\treturn\n\t\tcase <-segmentCtx.Done():\n\t\t}\n\t\tsegment.closeStdin()\n\t\tgrace := time.NewTimer(captureStdinCloseGrace)\n\t\tdefer grace.Stop()\n\t\tselect {\n\t\tcase <-execDone:\n\t\tcase <-grace.C:\n\t\t\tlog.Debug(\"Capture segment did not end after its stdin closed, cutting the stream\",\n\t\t\t\t\"node\", c.group.display, \"segment\", segment.index)\n\t\t\tcancelExec()\n\t\t}\n\t}()\n\tgo func() {\n\t\tdefer c.wg.Done()\n\t\tdefer cancel()\n\t\tdefer cancelExec()\n\n\t\terr := c.capture.r.execInPodContainer()(execCtx, c.group.location.Namespace,\n\t\t\tc.group.location.Pod, clabwireContainer, command, stdinReader, stdoutWriter, stderr)\n\t\tclose(execDone)\n\t\t// the process ended: release the stdin copy of the exec stream\n\t\tsegment.closeStdin()\n\t\t_ = stdoutWriter.Close()\n\t\treadErr := <-readDone\n\t\tstderr.flush()\n\t\tif err == nil && readErr != nil {\n\t\t\terr = readErr\n\t\t}\n\t\tif err != nil && stderr.text() != \"\" {\n\t\t\tif unsupported := unsupportedClabwire(\n\t\t\t\tc.group.location,\n\t\t\t\tstderr.text(),\n\t\t\t); unsupported != nil {\n\t\t\t\terr = unsupported\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"%w: %s\", err, stderr.text())\n\t\t\t}\n\t\t}\n\t\tsend(segmentEvent{done: true, err: err})\n\t}()\n\n\treturn segment\n}\n\n// unsupportedClabwire recognizes a clabwire that rejects --stop-on-stdin-close, which every\n// capture passes: its release predates the capture contract the runtime needs.\nfunc unsupportedClabwire(location clablabruntime.NodeLocation, stderr string) error {\n\tif !strings.Contains(stderr, \"flag provided but not defined\") ||\n\t\t!strings.Contains(stderr, strings.TrimPrefix(clabwireStopOnStdinClose, \"-\")) {\n\t\treturn nil\n\t}\n\n\treturn &unsupportedClabernetesError{reason: fmt.Sprintf(\n\t\t\"clabwire in pod %s/%s does not accept packet-capture %s\",\n\t\tlocation.Namespace, location.Pod, clabwireStopOnStdinClose)}\n}\n\n// readSegment checks that a segment's interfaces are the requested ones and passes its packets\n// on with the segment's interface index.\nfunc (c *captureChain) readSegment(stdout io.Reader, packet func(*clabcapture.Packet)) error {\n\treader := clabcapture.NewReader(stdout)\n\tinterfaces := 0\n\tfor {\n\t\tevent, err := reader.Next()\n\t\tif errors.Is(err, io.EOF) {\n\t\t\treturn nil\n\t\t}\n\t\tif errors.Is(err, io.ErrUnexpectedEOF) {\n\t\t\t// the process was stopped inside a block\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read the clabwire capture: %w\", err)\n\t\t}\n\t\tif event.Interface != nil {\n\t\t\tif interfaces >= len(c.group.interfaces) ||\n\t\t\t\tevent.Interface.Name != c.group.interfaces[interfaces] {\n\t\t\t\treturn fmt.Errorf(\"clabwire described interface %q, want %s in order\",\n\t\t\t\t\tevent.Interface.Name, strings.Join(c.group.interfaces, \", \"))\n\t\t\t}\n\t\t\tinterfaces++\n\t\t\tcontinue\n\t\t}\n\t\tif event.Packet != nil {\n\t\t\tpacket(event.Packet)\n\t\t}\n\t}\n}\n\n// auditLineWriter parses clabwire's stderr: audit records go to send, other lines are kept for\n// error messages.\ntype auditLineWriter struct {\n\tsend func(*captureAudit)\n\n\tmu      sync.Mutex\n\tpartial []byte\n\tother   []string\n}\n\nfunc (w *auditLineWriter) Write(data []byte) (int, error) {\n\tw.mu.Lock()\n\tw.partial = append(w.partial, data...)\n\tvar lines [][]byte\n\tfor {\n\t\tidx := bytes.IndexByte(w.partial, '\\n')\n\t\tif idx < 0 {\n\t\t\tbreak\n\t\t}\n\t\tlines = append(lines, append([]byte(nil), w.partial[:idx]...))\n\t\tw.partial = w.partial[idx+1:]\n\t}\n\tw.mu.Unlock()\n\n\tfor _, line := range lines {\n\t\tw.line(line)\n\t}\n\n\treturn len(data), nil\n}\n\nfunc (w *auditLineWriter) flush() {\n\tw.mu.Lock()\n\tline := w.partial\n\tw.partial = nil\n\tw.mu.Unlock()\n\tif len(bytes.TrimSpace(line)) != 0 {\n\t\tw.line(line)\n\t}\n}\n\nfunc (w *auditLineWriter) line(line []byte) {\n\tline = bytes.TrimSpace(line)\n\tif len(line) == 0 {\n\t\treturn\n\t}\n\n\tvar audit captureAudit\n\tif err := json.Unmarshal(\n\t\tline,\n\t\t&audit,\n\t); err == nil &&\n\t\taudit.SchemaVersion == captureAuditSchema {\n\t\tw.send(&audit)\n\t\treturn\n\t}\n\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\tif len(w.other) < 20 {\n\t\tw.other = append(w.other, string(line))\n\t}\n}\n\nfunc (w *auditLineWriter) text() string {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\n\treturn strings.Join(w.other, \"; \")\n}",
        "lineStart": 680,
        "lineEnd": 1202,
        "totalLines": 1202,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523351055,
      "end": 1793523351062
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196527e18001HXV1KNtBMaYibG",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965275f0001jy0JtWtHQA7Mlj",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 49667,
    "input": 6881,
    "output": 33,
    "reasoning": 1,
    "cache": {
      "read": 42752,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1965275f0001jy0JtWtHQA7Mlj",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523348976,
    "completed": 1793523351068
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 49667,
    "input": 6881,
    "output": 33,
    "reasoning": 1,
    "cache": {
      "read": 42752,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 31
step-start
{
  "type": "step-start",
  "id": "prt_19652851a001KJ5c6Wo158LK6K",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196527e22001cp2k6GtKVWT0Tb"
}
Reasoning
I've now seen the full capture.go. Let me analyze key issues:

1. **`handle` retry path with `c.next = nil` while `c.next` packets may be held**: If next errored before Started, `held` should be empty (packets only come after started? Actually packets can arrive before the Started audit event, since packets and audit records arrive on the same channel in order per segment; audit Started is written when capture starts, before packets. So held is empty). But `c.next = nil` without clearing `c.emitted`/`c.held`/`c.cut` — cut was set only on next Started, so cut==0. held nil. emitted empty. OK.

2. **`switchSegments` retry case**: `c.next.started.IsZero()` and error → retry. But what if the retry exhausts (retries == captureStartRetries) — returns error "failed". OK.

3. **Potential issue in `handlePacket` for `c.next` when stopping**: held appended; but if next is the segment that ended while stopping — handled.

4. **`switchSegments` held emission when `c.cut == 0` and next.started != 0**: All held packets emitted → duplicates from overlap (active wrote everything up to its end). This happens when overlap < 2*window. As computed earlier, with computed overlap (min(10s, segment/3)) and window (min(500ms, overlap/4)), 2*window = overlap/2 when window = overlap/4... wait: window = min(500ms, overlap/4). If overlap/4 < 500ms i.e. overlap < 2s → window = overlap/4 → 2*window = overlap/2 < overlap → OK. If overlap >= 2s → window = 500ms → 2*window = 1s ≤ overlap. OK. So setCut always succeeds with computed values. Good — the cut==0-with-started-next branch is effectively unreachable in production; only defensive.

5. **`emit` error when packet limit reached**: `more, err := c.capture.emit(...)`; `return !more, err` — returns stop=true when packet limit hit. In handlePacket, `return c.emit(packet)` → (true, nil) → chain.run returns nil. Good.

6. **Audit error while stopping**: `case captureAuditDenied, captureAuditFailed: return captureAuditError(...)` — handleAudit returns error; in handle: `return false, c.handleAudit(...)` — an error propagates as chain error even when `c.stopping`. Hmm: if the capture is being stopped by ctx cancel (Ctrl+C), and the active segment's clabwire reports Failed (e.g., because stdin closed abruptly → clabwire may write an audit Failed record?), the chain returns an error, and Capture returns an error after out.Close. But the doc says "Ctrl+C or SIGTERM ends a capture cleanly: the output stays a valid pcapng file and the command exits with code 0". Does closing stdin cause clabwire to write a "Failed" audit? Per contract, stdin-close ends capture... the audit record would presumably be Succeeded (complete) or Failed? The contract is not specified here. If clabwire writes Failed on stdin-close (as an interrupted capture), then Ctrl+C would produce an error despite the doc promise. But we can't verify clabwire behavior; the code's `!c.stopping` guard in handle covers only done-events, not audit errors. This is speculative; note it in coverage notes maybe.

7. **`captureEndGrace` timeout wrapping `captureCtx`** with WithTimeout: `captureCtx, cancelTimeout = context.WithTimeout(captureCtx, req.Duration+run.overlap+captureEndGrace)` — note captureCtx is reassigned; the earlier `defer stop()` cancels the original captureCtx, and the new one derives from it, so stop() also cancels the timeout context. Fine. `groupCtx` derives from the timeout ctx. When duration passes + overlap + grace, groupCtx cancels → chains' `run` sees ctx done → stop → drain (grace for segments) → segmentsCtx cancel aborts. Fine.

8. **`r.connect(ctx, req.Identity)`** — reassigns r; fine.

9. **`resolveCaptureTargets`**: `byRequest[name] = locations[idx]` — assumes LocateNode returns locations in the same order as the request's Nodes. Need to verify LocateNode semantics; presumably established in the codebase. Check.

10. **PacketLimit in segment command**: `remaining := int64(req.PacketLimit) - out.Written()`; `min(max(remaining,1), maxClabwirePackets)`. If remaining <= 0 the segment shouldn't be starting anyway. OK.

11. **`readSegment` interface order check**: clabwire writes IDBs in requested order — contract. OK.

12. **auditLineWriter flush** after exec done: `stderr.flush()` — called after `readDone` wait, in the exec goroutine. But note the auditLineWriter is also written concurrently by the exec goroutine only. OK.

Wait, actually there's a subtle issue: `stderr.flush()` is called in the exec goroutine after `readDone` is received. Audit lines sent via `send` which selects on `c.events <- event` or `<-segmentCtx.Done()`. After chain run returns and drain() consumes events, sends proceed. But drain() runs AFTER run() returns; events sent between... the exec goroutine sends `segmentEvent{done: true}` after audit events, all on c.events — drain consumes them. But hold: audit events that arrive after drain started consuming — fine.

One issue: `drain()` runs `c.wg.Wait()` and consumes events concurrently; the exec goroutine sends `done` — handled by drain (dropped). Good.

13. **Capture output ordering guarantee across chains with hold**: `out.Hold(c, cut-window)` holds reorder for that chain until `out.Release(c)`. Release is deferred in switchSegments and run's defer. In `switchSegments`, `defer c.capture.out.Release(c)` — releases after held packets are pushed. But the held packets have timestamps up to cut+W... The hold is at cut-W; after Release, packets can flow. Hmm, wait: the held packets of next (stamped ≥ cut-W after filtering) are pushed before Release — good, they enter reorder while still held.

But there's a subtlety: Release happens via defer at the END of switchSegments, but if switchSegments returns early (error / packet limit), the held packets not pushed — Release still runs. OK.

Another: In the non-stopping, non-final path where `c.next.done && !c.stopping` (next ended too early): held packets emitted in a loop, then `c.next, c.held... = nil...`, then start fresh segment. Note that Release at defer... but Hold was called only if cut != 0. If cut != 0 and next is being discarded as "too late", the hold is released. OK.

14. **`emitted` map size**: bounded by packets written while next runs (overlap ≤ 10s). With maxClabwirePackets 1M per segment... in a 10s overlap with heavy traffic, emitted could hold many entries (each packet → map entry). For a 10 Gbps line rate of tiny 64B packets: ~15M packets/s × 10s = 150M entries — unbounded memory? Well, the reorder buffer is capped at 64MiB, but `emitted` map is not capped. Hmm. Realistically the reader goroutine processes packets as fast as the pipe delivers; clabwire's own pipe limits. But a map keyed by content hash with 150M entries × ~50B = GBs. This is a potential unbounded memory issue in a pathological case. But also `held` for next is capped? `held` accumulates all packets next read until active ends — bounded by overlap duration × rate, and by clabwire... not capped in code. For 10s at 15Mpps that's huge too. But realistically exec pipe throughput and clabwire behavior bound this. The reorder buffer cap (64MiB) only applies to Output, not to `held`. Worth flagging as P3/P4? The code comments say window covers stamping difference; the design assumes moderate rates. I'd note as coverage note rather than a finding, or a P4 note about unbounded `held`/`emitted` growth during overlap at high packet rates. Hmm — since `maxClabwirePackets` is 1M per segment, held is at most 1M packets... per segment — 1M packets × (avg ~1KB) = ~1GB. Hmm, but snap length default 256KiB... cap 1MiB. 1M packets × 256KiB = way too much if all full-size. Realistically packets are small. The `held` slice holds Packet structs with Data slices until active ends — worst case bounded by clabwire's packet limit (1M) but memory could be large. I'll mention as a P4.

15. **`packetKey`**: fnv64 over interface byte-truncated ID (only low byte(s) — `id[0]`/`id[1]` — truncates InterfaceID to 16 bits! `id[0] = byte(packet.InterfaceID); id[1] = byte(packet.InterfaceID >> 8)` — only 2 bytes; if InterfaceID > 65535, collisions across interfaces. Number of interfaces per node is small; fine.

16. **Local capture** — verify `capture/local.go` details. I read it before per summary. Key concerns noted: `Output.Emit` increments `written` before `reorder.Push` failure; `openAll` count assumption; pcapng `Next` ErrUnexpectedEOF at clean EOF; drain deadline behavior.

Let me re-read `capture/local.go` and `output.go` and `reorder.go` and `pcapng.go` head files to verify these carefully now, since my summary says "initial notes". Also check `Output.Hold/Release` semantics used by c9s (hold map per chain). Let me read output.go and reorder.go fully.
Now let me re-verify the `capture` package internals (`output.go`, `reorder.go`, `local.go`, `pcapng.go`) against the c9s usage.
read · completed

Input

{
  "filePath": "/source/head/capture/output.go"
}

Output

<path>/source/head/capture/output.go</path>
<type>file</type>
<content>
1: package capture
2: 
3: import (
4: 	"context"
5: 	"fmt"
6: 	"io"
7: 	"strings"
8: 	"sync/atomic"
9: 	"time"
10: 
11: 	"github.com/charmbracelet/log"
12: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
13: )
14: 
15: // Snap length bounds of a capture.
16: const (
17: 	// DefaultSnapLength is the snap length of a request without one.
18: 	DefaultSnapLength = 256 << 10
19: 	MinSnapLength     = 64
20: 	MaxSnapLength     = 1 << 20
21: )
22: 
23: // ValidateRequest checks the bounds of a capture request and fills the default snap length.
24: func ValidateRequest(req *clablabruntime.CaptureRequest) error {
25: 	if req.Name == "" {
26: 		return fmt.Errorf("topology name is required")
27: 	}
28: 	if len(req.Targets) == 0 {
29: 		return fmt.Errorf("at least one capture target (node and interface) is required")
30: 	}
31: 	for _, target := range req.Targets {
32: 		if target.Node == "" || target.Interface == "" {
33: 			return fmt.Errorf("capture target %+v needs a node and an interface", target)
34: 		}
35: 	}
36: 	if req.Duration < 0 {
37: 		return fmt.Errorf("capture duration must not be negative")
38: 	}
39: 	if req.PacketLimit < 0 {
40: 		return fmt.Errorf("capture packet limit must not be negative")
41: 	}
42: 	if req.SnapLength == 0 {
43: 		req.SnapLength = DefaultSnapLength
44: 	}
45: 	if req.SnapLength < MinSnapLength || req.SnapLength > MaxSnapLength {
46: 		return fmt.Errorf("capture snap length %d is outside %d to %d bytes", req.SnapLength,
47: 			MinSnapLength, MaxSnapLength)
48: 	}
49: 
50: 	return nil
51: }
52: 
53: // FindInterface matches a requested interface by its name, then by its alias.
54: func FindInterface(
55: 	entries []clablabruntime.CaptureInterface,
56: 	name string,
57: ) (clablabruntime.CaptureInterface, bool) {
58: 	for _, entry := range entries {
59: 		if entry.Interface == name {
60: 			return entry, true
61: 		}
62: 	}
63: 	for _, entry := range entries {
64: 		if entry.Alias != "" && entry.Alias == name {
65: 			return entry, true
66: 		}
67: 	}
68: 
69: 	return clablabruntime.CaptureInterface{}, false
70: }
71: 
72: // DescribeInterfaces lists interfaces for an error message: name (alias), ...
73: func DescribeInterfaces(entries []clablabruntime.CaptureInterface) string {
74: 	if len(entries) == 0 {
75: 		return "none"
76: 	}
77: 
78: 	names := make([]string, 0, len(entries))
79: 	for _, entry := range entries {
80: 		name := entry.Interface
81: 		if entry.Alias != "" {
82: 			name += " (" + entry.Alias + ")"
83: 		}
84: 		names = append(names, name)
85: 	}
86: 
87: 	return strings.Join(names, ", ")
88: }
89: 
90: // ReportGap hands a gap to onGap, or logs it as a warning when onGap is nil.
91: func ReportGap(onGap func(clablabruntime.CaptureGap), gap clablabruntime.CaptureGap) {
92: 	if onGap != nil {
93: 		onGap(gap)
94: 		return
95: 	}
96: 
97: 	to := "unknown"
98: 	if !gap.To.IsZero() {
99: 		to = gap.To.Format(time.RFC3339Nano)
100: 	}
101: 	log.Warn("Capture has a gap", "node", gap.Node, "interfaces", strings.Join(gap.Interfaces, ","),
102: 		"from", gap.From.Format(time.RFC3339Nano), "to", to, "reason", gap.Reason)
103: }
104: 
105: // Output is the merged pcapng stream of one capture: the section header with one interface per
106: // capture target, then the packets of every target in timestamp order (through a Reorder), up
107: // to an optional packet limit.
108: type Output struct {
109: 	writer  *Writer
110: 	reorder *Reorder
111: 	limit   int64
112: 	written atomic.Int64
113: 	stop    func()
114: 
115: 	cancelRun context.CancelFunc
116: 	runDone   chan struct{}
117: }
118: 
119: // NewOutput writes the section header and one Interface Description Block per name to w, then
120: // starts the reorder buffer with the given window (zero or less writes packets as they come).
121: // stop is called once the packet limit is reached or a write failed. Close must be called.
122: func NewOutput(
123: 	w io.Writer,
124: 	names []string,
125: 	snapLength, packetLimit int,
126: 	window time.Duration,
127: 	stop func(),
128: ) (*Output, error) {
129: 	writer := NewWriter(w)
130: 	if err := writer.WriteHeader(
131: 		names,
132: 		uint32(snapLength),
133: 	); err != nil { //nolint:gosec // validated
134: 		return nil, err
135: 	}
136: 
137: 	out := &Output{
138: 		writer:  writer,
139: 		reorder: NewReorder(window, writer.WritePacket, stop),
140: 		limit:   int64(packetLimit),
141: 		stop:    stop,
142: 		runDone: make(chan struct{}),
143: 	}
144: 
145: 	var runCtx context.Context
146: 	runCtx, out.cancelRun = context.WithCancel(context.Background())
147: 	go func() {
148: 		defer close(out.runDone)
149: 		out.reorder.Run(runCtx)
150: 	}()
151: 
152: 	return out, nil
153: }
154: 
155: // Emit hands a packet of the interface with the given index to the stream. It reports false
156: // once the packet limit is reached and the capture stops, and returns the error of a failed
157: // write.
158: func (o *Output) Emit(id uint32, packet *Packet) (bool, error) {
159: 	if o.limit > 0 {
160: 		count := o.written.Add(1)
161: 		if count > o.limit {
162: 			o.stop()
163: 			return false, nil
164: 		}
165: 		if err := o.reorder.Push(id, packet); err != nil {
166: 			return false, err
167: 		}
168: 		if count == o.limit {
169: 			o.stop()
170: 			return false, nil
171: 		}
172: 
173: 		return true, nil
174: 	}
175: 
176: 	o.written.Add(1)
177: 
178: 	return true, o.reorder.Push(id, packet)
179: }
180: 
181: // Written returns the number of packets handed to the stream so far.
182: func (o *Output) Written() int64 {
183: 	return o.written.Load()
184: }
185: 
186: // Hold keeps packets stamped after timestamp back until Release(key).
187: func (o *Output) Hold(key any, timestamp int64) {
188: 	o.reorder.Hold(key, timestamp)
189: }
190: 
191: // Release removes the hold of key.
192: func (o *Output) Release(key any) {
193: 	o.reorder.Release(key)
194: }
195: 
196: // Close writes the packets still held back and returns the first write error.
197: func (o *Output) Close() error {
198: 	o.cancelRun()
199: 	<-o.runDone
200: 	o.reorder.Flush()
201: 
202: 	return o.writer.Err()
203: }

(End of file - total 203 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19652d28e001LN3I9xotNAFQvb",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196527e22001cp2k6GtKVWT0Tb",
  "callID": "call_0c1b80fd09e0420aa446901a",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/capture/output.go"
    },
    "output": "<path>/source/head/capture/output.go</path>\n<type>file</type>\n<content>\n1: package capture\n2: \n3: import (\n4: \t\"context\"\n5: \t\"fmt\"\n6: \t\"io\"\n7: \t\"strings\"\n8: \t\"sync/atomic\"\n9: \t\"time\"\n10: \n11: \t\"github.com/charmbracelet/log\"\n12: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n13: )\n14: \n15: // Snap length bounds of a capture.\n16: const (\n17: \t// DefaultSnapLength is the snap length of a request without one.\n18: \tDefaultSnapLength = 256 << 10\n19: \tMinSnapLength     = 64\n20: \tMaxSnapLength     = 1 << 20\n21: )\n22: \n23: // ValidateRequest checks the bounds of a capture request and fills the default snap length.\n24: func ValidateRequest(req *clablabruntime.CaptureRequest) error {\n25: \tif req.Name == \"\" {\n26: \t\treturn fmt.Errorf(\"topology name is required\")\n27: \t}\n28: \tif len(req.Targets) == 0 {\n29: \t\treturn fmt.Errorf(\"at least one capture target (node and interface) is required\")\n30: \t}\n31: \tfor _, target := range req.Targets {\n32: \t\tif target.Node == \"\" || target.Interface == \"\" {\n33: \t\t\treturn fmt.Errorf(\"capture target %+v needs a node and an interface\", target)\n34: \t\t}\n35: \t}\n36: \tif req.Duration < 0 {\n37: \t\treturn fmt.Errorf(\"capture duration must not be negative\")\n38: \t}\n39: \tif req.PacketLimit < 0 {\n40: \t\treturn fmt.Errorf(\"capture packet limit must not be negative\")\n41: \t}\n42: \tif req.SnapLength == 0 {\n43: \t\treq.SnapLength = DefaultSnapLength\n44: \t}\n45: \tif req.SnapLength < MinSnapLength || req.SnapLength > MaxSnapLength {\n46: \t\treturn fmt.Errorf(\"capture snap length %d is outside %d to %d bytes\", req.SnapLength,\n47: \t\t\tMinSnapLength, MaxSnapLength)\n48: \t}\n49: \n50: \treturn nil\n51: }\n52: \n53: // FindInterface matches a requested interface by its name, then by its alias.\n54: func FindInterface(\n55: \tentries []clablabruntime.CaptureInterface,\n56: \tname string,\n57: ) (clablabruntime.CaptureInterface, bool) {\n58: \tfor _, entry := range entries {\n59: \t\tif entry.Interface == name {\n60: \t\t\treturn entry, true\n61: \t\t}\n62: \t}\n63: \tfor _, entry := range entries {\n64: \t\tif entry.Alias != \"\" && entry.Alias == name {\n65: \t\t\treturn entry, true\n66: \t\t}\n67: \t}\n68: \n69: \treturn clablabruntime.CaptureInterface{}, false\n70: }\n71: \n72: // DescribeInterfaces lists interfaces for an error message: name (alias), ...\n73: func DescribeInterfaces(entries []clablabruntime.CaptureInterface) string {\n74: \tif len(entries) == 0 {\n75: \t\treturn \"none\"\n76: \t}\n77: \n78: \tnames := make([]string, 0, len(entries))\n79: \tfor _, entry := range entries {\n80: \t\tname := entry.Interface\n81: \t\tif entry.Alias != \"\" {\n82: \t\t\tname += \" (\" + entry.Alias + \")\"\n83: \t\t}\n84: \t\tnames = append(names, name)\n85: \t}\n86: \n87: \treturn strings.Join(names, \", \")\n88: }\n89: \n90: // ReportGap hands a gap to onGap, or logs it as a warning when onGap is nil.\n91: func ReportGap(onGap func(clablabruntime.CaptureGap), gap clablabruntime.CaptureGap) {\n92: \tif onGap != nil {\n93: \t\tonGap(gap)\n94: \t\treturn\n95: \t}\n96: \n97: \tto := \"unknown\"\n98: \tif !gap.To.IsZero() {\n99: \t\tto = gap.To.Format(time.RFC3339Nano)\n100: \t}\n101: \tlog.Warn(\"Capture has a gap\", \"node\", gap.Node, \"interfaces\", strings.Join(gap.Interfaces, \",\"),\n102: \t\t\"from\", gap.From.Format(time.RFC3339Nano), \"to\", to, \"reason\", gap.Reason)\n103: }\n104: \n105: // Output is the merged pcapng stream of one capture: the section header with one interface per\n106: // capture target, then the packets of every target in timestamp order (through a Reorder), up\n107: // to an optional packet limit.\n108: type Output struct {\n109: \twriter  *Writer\n110: \treorder *Reorder\n111: \tlimit   int64\n112: \twritten atomic.Int64\n113: \tstop    func()\n114: \n115: \tcancelRun context.CancelFunc\n116: \trunDone   chan struct{}\n117: }\n118: \n119: // NewOutput writes the section header and one Interface Description Block per name to w, then\n120: // starts the reorder buffer with the given window (zero or less writes packets as they come).\n121: // stop is called once the packet limit is reached or a write failed. Close must be called.\n122: func NewOutput(\n123: \tw io.Writer,\n124: \tnames []string,\n125: \tsnapLength, packetLimit int,\n126: \twindow time.Duration,\n127: \tstop func(),\n128: ) (*Output, error) {\n129: \twriter := NewWriter(w)\n130: \tif err := writer.WriteHeader(\n131: \t\tnames,\n132: \t\tuint32(snapLength),\n133: \t); err != nil { //nolint:gosec // validated\n134: \t\treturn nil, err\n135: \t}\n136: \n137: \tout := &Output{\n138: \t\twriter:  writer,\n139: \t\treorder: NewReorder(window, writer.WritePacket, stop),\n140: \t\tlimit:   int64(packetLimit),\n141: \t\tstop:    stop,\n142: \t\trunDone: make(chan struct{}),\n143: \t}\n144: \n145: \tvar runCtx context.Context\n146: \trunCtx, out.cancelRun = context.WithCancel(context.Background())\n147: \tgo func() {\n148: \t\tdefer close(out.runDone)\n149: \t\tout.reorder.Run(runCtx)\n150: \t}()\n151: \n152: \treturn out, nil\n153: }\n154: \n155: // Emit hands a packet of the interface with the given index to the stream. It reports false\n156: // once the packet limit is reached and the capture stops, and returns the error of a failed\n157: // write.\n158: func (o *Output) Emit(id uint32, packet *Packet) (bool, error) {\n159: \tif o.limit > 0 {\n160: \t\tcount := o.written.Add(1)\n161: \t\tif count > o.limit {\n162: \t\t\to.stop()\n163: \t\t\treturn false, nil\n164: \t\t}\n165: \t\tif err := o.reorder.Push(id, packet); err != nil {\n166: \t\t\treturn false, err\n167: \t\t}\n168: \t\tif count == o.limit {\n169: \t\t\to.stop()\n170: \t\t\treturn false, nil\n171: \t\t}\n172: \n173: \t\treturn true, nil\n174: \t}\n175: \n176: \to.written.Add(1)\n177: \n178: \treturn true, o.reorder.Push(id, packet)\n179: }\n180: \n181: // Written returns the number of packets handed to the stream so far.\n182: func (o *Output) Written() int64 {\n183: \treturn o.written.Load()\n184: }\n185: \n186: // Hold keeps packets stamped after timestamp back until Release(key).\n187: func (o *Output) Hold(key any, timestamp int64) {\n188: \to.reorder.Hold(key, timestamp)\n189: }\n190: \n191: // Release removes the hold of key.\n192: func (o *Output) Release(key any) {\n193: \to.reorder.Release(key)\n194: }\n195: \n196: // Close writes the packets still held back and returns the first write error.\n197: func (o *Output) Close() error {\n198: \to.cancelRun()\n199: \t<-o.runDone\n200: \to.reorder.Flush()\n201: \n202: \treturn o.writer.Err()\n203: }\n\n(End of file - total 203 lines)\n</content>",
    "title": "source/head/capture/output.go",
    "metadata": {
      "preview": "package capture\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\n// Snap length bounds of a capture.\nconst (\n\t// DefaultSnapLength is the snap length of a request without one.\n\tDefaultSnapLength = 256 << 10\n\tMinSnapLength     = 64\n\tMaxSnapLength     = 1 << 20",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/capture/output.go",
        "text": "package capture\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\n// Snap length bounds of a capture.\nconst (\n\t// DefaultSnapLength is the snap length of a request without one.\n\tDefaultSnapLength = 256 << 10\n\tMinSnapLength     = 64\n\tMaxSnapLength     = 1 << 20\n)\n\n// ValidateRequest checks the bounds of a capture request and fills the default snap length.\nfunc ValidateRequest(req *clablabruntime.CaptureRequest) error {\n\tif req.Name == \"\" {\n\t\treturn fmt.Errorf(\"topology name is required\")\n\t}\n\tif len(req.Targets) == 0 {\n\t\treturn fmt.Errorf(\"at least one capture target (node and interface) is required\")\n\t}\n\tfor _, target := range req.Targets {\n\t\tif target.Node == \"\" || target.Interface == \"\" {\n\t\t\treturn fmt.Errorf(\"capture target %+v needs a node and an interface\", target)\n\t\t}\n\t}\n\tif req.Duration < 0 {\n\t\treturn fmt.Errorf(\"capture duration must not be negative\")\n\t}\n\tif req.PacketLimit < 0 {\n\t\treturn fmt.Errorf(\"capture packet limit must not be negative\")\n\t}\n\tif req.SnapLength == 0 {\n\t\treq.SnapLength = DefaultSnapLength\n\t}\n\tif req.SnapLength < MinSnapLength || req.SnapLength > MaxSnapLength {\n\t\treturn fmt.Errorf(\"capture snap length %d is outside %d to %d bytes\", req.SnapLength,\n\t\t\tMinSnapLength, MaxSnapLength)\n\t}\n\n\treturn nil\n}\n\n// FindInterface matches a requested interface by its name, then by its alias.\nfunc FindInterface(\n\tentries []clablabruntime.CaptureInterface,\n\tname string,\n) (clablabruntime.CaptureInterface, bool) {\n\tfor _, entry := range entries {\n\t\tif entry.Interface == name {\n\t\t\treturn entry, true\n\t\t}\n\t}\n\tfor _, entry := range entries {\n\t\tif entry.Alias != \"\" && entry.Alias == name {\n\t\t\treturn entry, true\n\t\t}\n\t}\n\n\treturn clablabruntime.CaptureInterface{}, false\n}\n\n// DescribeInterfaces lists interfaces for an error message: name (alias), ...\nfunc DescribeInterfaces(entries []clablabruntime.CaptureInterface) string {\n\tif len(entries) == 0 {\n\t\treturn \"none\"\n\t}\n\n\tnames := make([]string, 0, len(entries))\n\tfor _, entry := range entries {\n\t\tname := entry.Interface\n\t\tif entry.Alias != \"\" {\n\t\t\tname += \" (\" + entry.Alias + \")\"\n\t\t}\n\t\tnames = append(names, name)\n\t}\n\n\treturn strings.Join(names, \", \")\n}\n\n// ReportGap hands a gap to onGap, or logs it as a warning when onGap is nil.\nfunc ReportGap(onGap func(clablabruntime.CaptureGap), gap clablabruntime.CaptureGap) {\n\tif onGap != nil {\n\t\tonGap(gap)\n\t\treturn\n\t}\n\n\tto := \"unknown\"\n\tif !gap.To.IsZero() {\n\t\tto = gap.To.Format(time.RFC3339Nano)\n\t}\n\tlog.Warn(\"Capture has a gap\", \"node\", gap.Node, \"interfaces\", strings.Join(gap.Interfaces, \",\"),\n\t\t\"from\", gap.From.Format(time.RFC3339Nano), \"to\", to, \"reason\", gap.Reason)\n}\n\n// Output is the merged pcapng stream of one capture: the section header with one interface per\n// capture target, then the packets of every target in timestamp order (through a Reorder), up\n// to an optional packet limit.\ntype Output struct {\n\twriter  *Writer\n\treorder *Reorder\n\tlimit   int64\n\twritten atomic.Int64\n\tstop    func()\n\n\tcancelRun context.CancelFunc\n\trunDone   chan struct{}\n}\n\n// NewOutput writes the section header and one Interface Description Block per name to w, then\n// starts the reorder buffer with the given window (zero or less writes packets as they come).\n// stop is called once the packet limit is reached or a write failed. Close must be called.\nfunc NewOutput(\n\tw io.Writer,\n\tnames []string,\n\tsnapLength, packetLimit int,\n\twindow time.Duration,\n\tstop func(),\n) (*Output, error) {\n\twriter := NewWriter(w)\n\tif err := writer.WriteHeader(\n\t\tnames,\n\t\tuint32(snapLength),\n\t); err != nil { //nolint:gosec // validated\n\t\treturn nil, err\n\t}\n\n\tout := &Output{\n\t\twriter:  writer,\n\t\treorder: NewReorder(window, writer.WritePacket, stop),\n\t\tlimit:   int64(packetLimit),\n\t\tstop:    stop,\n\t\trunDone: make(chan struct{}),\n\t}\n\n\tvar runCtx context.Context\n\trunCtx, out.cancelRun = context.WithCancel(context.Background())\n\tgo func() {\n\t\tdefer close(out.runDone)\n\t\tout.reorder.Run(runCtx)\n\t}()\n\n\treturn out, nil\n}\n\n// Emit hands a packet of the interface with the given index to the stream. It reports false\n// once the packet limit is reached and the capture stops, and returns the error of a failed\n// write.\nfunc (o *Output) Emit(id uint32, packet *Packet) (bool, error) {\n\tif o.limit > 0 {\n\t\tcount := o.written.Add(1)\n\t\tif count > o.limit {\n\t\t\to.stop()\n\t\t\treturn false, nil\n\t\t}\n\t\tif err := o.reorder.Push(id, packet); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif count == o.limit {\n\t\t\to.stop()\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn true, nil\n\t}\n\n\to.written.Add(1)\n\n\treturn true, o.reorder.Push(id, packet)\n}\n\n// Written returns the number of packets handed to the stream so far.\nfunc (o *Output) Written() int64 {\n\treturn o.written.Load()\n}\n\n// Hold keeps packets stamped after timestamp back until Release(key).\nfunc (o *Output) Hold(key any, timestamp int64) {\n\to.reorder.Hold(key, timestamp)\n}\n\n// Release removes the hold of key.\nfunc (o *Output) Release(key any) {\n\to.reorder.Release(key)\n}\n\n// Close writes the packets still held back and returns the first write error.\nfunc (o *Output) Close() error {\n\to.cancelRun()\n\t<-o.runDone\n\to.reorder.Flush()\n\n\treturn o.writer.Err()\n}",
        "lineStart": 1,
        "lineEnd": 203,
        "totalLines": 203,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523372692,
      "end": 1793523372699
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/capture/reorder.go"
}

Output

<path>/source/head/capture/reorder.go</path>
<type>file</type>
<content>
1: package capture
2: 
3: import (
4: 	"container/heap"
5: 	"context"
6: 	"sync"
7: 	"time"
8: 
9: 	"github.com/charmbracelet/log"
10: )
11: 
12: // maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets
13: // are written early, which can put them out of order.
14: const maxReorderBytes = 64 << 20
15: 
16: // Reorder writes the packets of several capture sources in timestamp order.
17: //
18: // Each source (a node's capture stream, or a local interface socket) delivers its packets with
19: // its own delay. The buffer holds every packet for `window` after it arrived and writes the held
20: // packets in timestamp order, so a packet that was stamped earlier but delivered up to `window`
21: // later still goes out first. A packet stamped before the last packet written arrived too late
22: // to be ordered: it is written as it comes and counted, and the count goes to the debug log when
23: // the capture ends.
24: //
25: // A source can place a hold at the earliest timestamp it may still write (Hold); packets stamped
26: // after a hold wait for it to be released (Release). The c9s runtime holds while it switches
27: // between chained capture segments.
28: type Reorder struct {
29: 	write  func(id uint32, packet *Packet) error
30: 	onFail func()
31: 	window time.Duration
32: 	now    func() time.Time
33: 
34: 	mu     sync.Mutex
35: 	queue  reorderQueue
36: 	bytes  int
37: 	seq    uint64
38: 	holds  map[any]int64
39: 	err    error
40: 	wake   chan struct{}
41: 	stats  reorderStats
42: 	cursor int64 // timestamp of the latest packet written in order
43: }
44: 
45: type reorderStats struct {
46: 	late    int
47: 	maxLate time.Duration
48: 	forced  int
49: }
50: 
51: // reorderedPacket is a packet waiting in the buffer.
52: type reorderedPacket struct {
53: 	id      uint32
54: 	packet  *Packet
55: 	arrived time.Time
56: 	seq     uint64
57: }
58: 
59: // reorderQueue is a min-heap by timestamp, then arrival.
60: type reorderQueue []reorderedPacket
61: 
62: func (q reorderQueue) Len() int { return len(q) }
63: 
64: func (q reorderQueue) Less(i, j int) bool {
65: 	if q[i].packet.Timestamp != q[j].packet.Timestamp {
66: 		return q[i].packet.Timestamp < q[j].packet.Timestamp
67: 	}
68: 
69: 	return q[i].seq < q[j].seq
70: }
71: 
72: func (q reorderQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
73: 
74: func (q *reorderQueue) Push(
75: 	x any,
76: ) {
77: 	*q = append(*q, x.(reorderedPacket))
78: } //nolint:forcetypeassert // heap contract
79: 
80: func (q *reorderQueue) Pop() any {
81: 	old := *q
82: 	item := old[len(old)-1]
83: 	*q = old[:len(old)-1]
84: 
85: 	return item
86: }
87: 
88: // NewReorder returns a buffer that writes through write; onFail is called once a write
89: // failed. A window of zero or less writes every packet as it arrives.
90: func NewReorder(
91: 	window time.Duration,
92: 	write func(id uint32, packet *Packet) error,
93: 	onFail func(),
94: ) *Reorder {
95: 	return &Reorder{
96: 		write: write, onFail: onFail, window: window, now: time.Now,
97: 		holds: map[any]int64{}, wake: make(chan struct{}, 1),
98: 	}
99: }
100: 
101: // push hands a packet to the buffer. It returns the error of a failed write.
102: func (q *Reorder) Push(id uint32, packet *Packet) error {
103: 	q.mu.Lock()
104: 	defer q.mu.Unlock()
105: 
106: 	if q.err != nil {
107: 		return q.err
108: 	}
109: 	if q.window <= 0 {
110: 		return q.writeLocked(id, packet)
111: 	}
112: 	if q.cursor != 0 && packet.Timestamp < q.cursor {
113: 		q.stats.late++
114: 		q.stats.maxLate = max(q.stats.maxLate, time.Duration(q.cursor-packet.Timestamp))
115: 		if q.stats.late == 1 {
116: 			log.Debug("Capture packet arrived after the reorder window, writing it out of order",
117: 				"late_by", time.Duration(q.cursor-packet.Timestamp), "window", q.window)
118: 		}
119: 
120: 		return q.writeLocked(id, packet)
121: 	}
122: 
123: 	q.seq++
124: 	heap.Push(&q.queue, reorderedPacket{id: id, packet: packet, arrived: q.now(), seq: q.seq})
125: 	q.bytes += len(packet.Data)
126: 	for q.bytes > maxReorderBytes && q.queue.Len() > 0 {
127: 		q.stats.forced++
128: 		if err := q.popLocked(); err != nil {
129: 			return err
130: 		}
131: 	}
132: 
133: 	select {
134: 	case q.wake <- struct{}{}:
135: 	default:
136: 	}
137: 
138: 	return nil
139: }
140: 
141: // hold keeps packets stamped after timestamp in the buffer until release(key).
142: func (q *Reorder) Hold(key any, timestamp int64) {
143: 	q.mu.Lock()
144: 	defer q.mu.Unlock()
145: 
146: 	q.holds[key] = timestamp
147: }
148: 
149: // release removes the hold of key.
150: func (q *Reorder) Release(key any) {
151: 	q.mu.Lock()
152: 	_, held := q.holds[key]
153: 	delete(q.holds, key)
154: 	q.mu.Unlock()
155: 
156: 	if held {
157: 		select {
158: 		case q.wake <- struct{}{}:
159: 		default:
160: 		}
161: 	}
162: }
163: 
164: // run writes due packets until ctx ends.
165: func (q *Reorder) Run(ctx context.Context) {
166: 	if q.window <= 0 {
167: 		return
168: 	}
169: 
170: 	timer := time.NewTimer(time.Hour)
171: 	defer timer.Stop()
172: 
173: 	for {
174: 		next := q.writeDue()
175: 		wait := time.Hour
176: 		if !next.IsZero() {
177: 			wait = max(next.Sub(q.now()), time.Millisecond)
178: 		}
179: 		resetTimer(timer, wait)
180: 
181: 		select {
182: 		case <-ctx.Done():
183: 			return
184: 		case <-q.wake:
185: 		case <-timer.C:
186: 		}
187: 	}
188: }
189: 
190: // writeDue writes the packets that waited for the window and are not behind a hold, in
191: // timestamp order. It returns when the next packet is due, or zero when that depends on a new
192: // packet or a released hold.
193: func (q *Reorder) writeDue() time.Time {
194: 	q.mu.Lock()
195: 	defer q.mu.Unlock()
196: 
197: 	held, limit := false, int64(0)
198: 	for _, timestamp := range q.holds {
199: 		if !held || timestamp < limit {
200: 			held, limit = true, timestamp
201: 		}
202: 	}
203: 
204: 	now := q.now()
205: 	for q.queue.Len() > 0 && q.err == nil {
206: 		head := q.queue[0]
207: 		if held && head.packet.Timestamp > limit {
208: 			return time.Time{}
209: 		}
210: 		if due := head.arrived.Add(q.window); due.After(now) {
211: 			return due
212: 		}
213: 		if q.popLocked() != nil {
214: 			return time.Time{}
215: 		}
216: 	}
217: 
218: 	return time.Time{}
219: }
220: 
221: // flush writes every remaining packet in timestamp order and logs what could not be ordered.
222: func (q *Reorder) Flush() {
223: 	q.mu.Lock()
224: 	defer q.mu.Unlock()
225: 
226: 	for q.queue.Len() > 0 && q.err == nil {
227: 		if q.popLocked() != nil {
228: 			break
229: 		}
230: 	}
231: 	q.queue, q.bytes = nil, 0
232: 
233: 	if q.stats.late > 0 || q.stats.forced > 0 {
234: 		log.Debug("Capture wrote packets out of timestamp order",
235: 			"late_packets", q.stats.late, "max_late_by", q.stats.maxLate,
236: 			"window", q.window, "buffer_overflow_packets", q.stats.forced)
237: 	}
238: }
239: 
240: func (q *Reorder) popLocked() error {
241: 	item := heap.Pop(&q.queue).(reorderedPacket) //nolint:forcetypeassert // heap contract
242: 	q.bytes -= len(item.packet.Data)
243: 	q.cursor = max(q.cursor, item.packet.Timestamp)
244: 
245: 	return q.writeLocked(item.id, item.packet)
246: }
247: 
248: func (q *Reorder) writeLocked(id uint32, packet *Packet) error {
249: 	if err := q.write(id, packet); err != nil {
250: 		if q.err == nil {
251: 			q.err = err
252: 			if q.onFail != nil {
253: 				q.onFail()
254: 			}
255: 		}
256: 
257: 		return err
258: 	}
259: 
260: 	return nil
261: }
262: 
263: func resetTimer(timer *time.Timer, d time.Duration) {
264: 	if !timer.Stop() {
265: 		select {
266: 		case <-timer.C:
267: 		default:
268: 		}
269: 	}
270: 	timer.Reset(d)
271: }

(End of file - total 271 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19652d2bc001AYyOFZ6OC94l63",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196527e22001cp2k6GtKVWT0Tb",
  "callID": "call_68a4088489934230ad5a2958",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/capture/reorder.go"
    },
    "output": "<path>/source/head/capture/reorder.go</path>\n<type>file</type>\n<content>\n1: package capture\n2: \n3: import (\n4: \t\"container/heap\"\n5: \t\"context\"\n6: \t\"sync\"\n7: \t\"time\"\n8: \n9: \t\"github.com/charmbracelet/log\"\n10: )\n11: \n12: // maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets\n13: // are written early, which can put them out of order.\n14: const maxReorderBytes = 64 << 20\n15: \n16: // Reorder writes the packets of several capture sources in timestamp order.\n17: //\n18: // Each source (a node's capture stream, or a local interface socket) delivers its packets with\n19: // its own delay. The buffer holds every packet for `window` after it arrived and writes the held\n20: // packets in timestamp order, so a packet that was stamped earlier but delivered up to `window`\n21: // later still goes out first. A packet stamped before the last packet written arrived too late\n22: // to be ordered: it is written as it comes and counted, and the count goes to the debug log when\n23: // the capture ends.\n24: //\n25: // A source can place a hold at the earliest timestamp it may still write (Hold); packets stamped\n26: // after a hold wait for it to be released (Release). The c9s runtime holds while it switches\n27: // between chained capture segments.\n28: type Reorder struct {\n29: \twrite  func(id uint32, packet *Packet) error\n30: \tonFail func()\n31: \twindow time.Duration\n32: \tnow    func() time.Time\n33: \n34: \tmu     sync.Mutex\n35: \tqueue  reorderQueue\n36: \tbytes  int\n37: \tseq    uint64\n38: \tholds  map[any]int64\n39: \terr    error\n40: \twake   chan struct{}\n41: \tstats  reorderStats\n42: \tcursor int64 // timestamp of the latest packet written in order\n43: }\n44: \n45: type reorderStats struct {\n46: \tlate    int\n47: \tmaxLate time.Duration\n48: \tforced  int\n49: }\n50: \n51: // reorderedPacket is a packet waiting in the buffer.\n52: type reorderedPacket struct {\n53: \tid      uint32\n54: \tpacket  *Packet\n55: \tarrived time.Time\n56: \tseq     uint64\n57: }\n58: \n59: // reorderQueue is a min-heap by timestamp, then arrival.\n60: type reorderQueue []reorderedPacket\n61: \n62: func (q reorderQueue) Len() int { return len(q) }\n63: \n64: func (q reorderQueue) Less(i, j int) bool {\n65: \tif q[i].packet.Timestamp != q[j].packet.Timestamp {\n66: \t\treturn q[i].packet.Timestamp < q[j].packet.Timestamp\n67: \t}\n68: \n69: \treturn q[i].seq < q[j].seq\n70: }\n71: \n72: func (q reorderQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }\n73: \n74: func (q *reorderQueue) Push(\n75: \tx any,\n76: ) {\n77: \t*q = append(*q, x.(reorderedPacket))\n78: } //nolint:forcetypeassert // heap contract\n79: \n80: func (q *reorderQueue) Pop() any {\n81: \told := *q\n82: \titem := old[len(old)-1]\n83: \t*q = old[:len(old)-1]\n84: \n85: \treturn item\n86: }\n87: \n88: // NewReorder returns a buffer that writes through write; onFail is called once a write\n89: // failed. A window of zero or less writes every packet as it arrives.\n90: func NewReorder(\n91: \twindow time.Duration,\n92: \twrite func(id uint32, packet *Packet) error,\n93: \tonFail func(),\n94: ) *Reorder {\n95: \treturn &Reorder{\n96: \t\twrite: write, onFail: onFail, window: window, now: time.Now,\n97: \t\tholds: map[any]int64{}, wake: make(chan struct{}, 1),\n98: \t}\n99: }\n100: \n101: // push hands a packet to the buffer. It returns the error of a failed write.\n102: func (q *Reorder) Push(id uint32, packet *Packet) error {\n103: \tq.mu.Lock()\n104: \tdefer q.mu.Unlock()\n105: \n106: \tif q.err != nil {\n107: \t\treturn q.err\n108: \t}\n109: \tif q.window <= 0 {\n110: \t\treturn q.writeLocked(id, packet)\n111: \t}\n112: \tif q.cursor != 0 && packet.Timestamp < q.cursor {\n113: \t\tq.stats.late++\n114: \t\tq.stats.maxLate = max(q.stats.maxLate, time.Duration(q.cursor-packet.Timestamp))\n115: \t\tif q.stats.late == 1 {\n116: \t\t\tlog.Debug(\"Capture packet arrived after the reorder window, writing it out of order\",\n117: \t\t\t\t\"late_by\", time.Duration(q.cursor-packet.Timestamp), \"window\", q.window)\n118: \t\t}\n119: \n120: \t\treturn q.writeLocked(id, packet)\n121: \t}\n122: \n123: \tq.seq++\n124: \theap.Push(&q.queue, reorderedPacket{id: id, packet: packet, arrived: q.now(), seq: q.seq})\n125: \tq.bytes += len(packet.Data)\n126: \tfor q.bytes > maxReorderBytes && q.queue.Len() > 0 {\n127: \t\tq.stats.forced++\n128: \t\tif err := q.popLocked(); err != nil {\n129: \t\t\treturn err\n130: \t\t}\n131: \t}\n132: \n133: \tselect {\n134: \tcase q.wake <- struct{}{}:\n135: \tdefault:\n136: \t}\n137: \n138: \treturn nil\n139: }\n140: \n141: // hold keeps packets stamped after timestamp in the buffer until release(key).\n142: func (q *Reorder) Hold(key any, timestamp int64) {\n143: \tq.mu.Lock()\n144: \tdefer q.mu.Unlock()\n145: \n146: \tq.holds[key] = timestamp\n147: }\n148: \n149: // release removes the hold of key.\n150: func (q *Reorder) Release(key any) {\n151: \tq.mu.Lock()\n152: \t_, held := q.holds[key]\n153: \tdelete(q.holds, key)\n154: \tq.mu.Unlock()\n155: \n156: \tif held {\n157: \t\tselect {\n158: \t\tcase q.wake <- struct{}{}:\n159: \t\tdefault:\n160: \t\t}\n161: \t}\n162: }\n163: \n164: // run writes due packets until ctx ends.\n165: func (q *Reorder) Run(ctx context.Context) {\n166: \tif q.window <= 0 {\n167: \t\treturn\n168: \t}\n169: \n170: \ttimer := time.NewTimer(time.Hour)\n171: \tdefer timer.Stop()\n172: \n173: \tfor {\n174: \t\tnext := q.writeDue()\n175: \t\twait := time.Hour\n176: \t\tif !next.IsZero() {\n177: \t\t\twait = max(next.Sub(q.now()), time.Millisecond)\n178: \t\t}\n179: \t\tresetTimer(timer, wait)\n180: \n181: \t\tselect {\n182: \t\tcase <-ctx.Done():\n183: \t\t\treturn\n184: \t\tcase <-q.wake:\n185: \t\tcase <-timer.C:\n186: \t\t}\n187: \t}\n188: }\n189: \n190: // writeDue writes the packets that waited for the window and are not behind a hold, in\n191: // timestamp order. It returns when the next packet is due, or zero when that depends on a new\n192: // packet or a released hold.\n193: func (q *Reorder) writeDue() time.Time {\n194: \tq.mu.Lock()\n195: \tdefer q.mu.Unlock()\n196: \n197: \theld, limit := false, int64(0)\n198: \tfor _, timestamp := range q.holds {\n199: \t\tif !held || timestamp < limit {\n200: \t\t\theld, limit = true, timestamp\n201: \t\t}\n202: \t}\n203: \n204: \tnow := q.now()\n205: \tfor q.queue.Len() > 0 && q.err == nil {\n206: \t\thead := q.queue[0]\n207: \t\tif held && head.packet.Timestamp > limit {\n208: \t\t\treturn time.Time{}\n209: \t\t}\n210: \t\tif due := head.arrived.Add(q.window); due.After(now) {\n211: \t\t\treturn due\n212: \t\t}\n213: \t\tif q.popLocked() != nil {\n214: \t\t\treturn time.Time{}\n215: \t\t}\n216: \t}\n217: \n218: \treturn time.Time{}\n219: }\n220: \n221: // flush writes every remaining packet in timestamp order and logs what could not be ordered.\n222: func (q *Reorder) Flush() {\n223: \tq.mu.Lock()\n224: \tdefer q.mu.Unlock()\n225: \n226: \tfor q.queue.Len() > 0 && q.err == nil {\n227: \t\tif q.popLocked() != nil {\n228: \t\t\tbreak\n229: \t\t}\n230: \t}\n231: \tq.queue, q.bytes = nil, 0\n232: \n233: \tif q.stats.late > 0 || q.stats.forced > 0 {\n234: \t\tlog.Debug(\"Capture wrote packets out of timestamp order\",\n235: \t\t\t\"late_packets\", q.stats.late, \"max_late_by\", q.stats.maxLate,\n236: \t\t\t\"window\", q.window, \"buffer_overflow_packets\", q.stats.forced)\n237: \t}\n238: }\n239: \n240: func (q *Reorder) popLocked() error {\n241: \titem := heap.Pop(&q.queue).(reorderedPacket) //nolint:forcetypeassert // heap contract\n242: \tq.bytes -= len(item.packet.Data)\n243: \tq.cursor = max(q.cursor, item.packet.Timestamp)\n244: \n245: \treturn q.writeLocked(item.id, item.packet)\n246: }\n247: \n248: func (q *Reorder) writeLocked(id uint32, packet *Packet) error {\n249: \tif err := q.write(id, packet); err != nil {\n250: \t\tif q.err == nil {\n251: \t\t\tq.err = err\n252: \t\t\tif q.onFail != nil {\n253: \t\t\t\tq.onFail()\n254: \t\t\t}\n255: \t\t}\n256: \n257: \t\treturn err\n258: \t}\n259: \n260: \treturn nil\n261: }\n262: \n263: func resetTimer(timer *time.Timer, d time.Duration) {\n264: \tif !timer.Stop() {\n265: \t\tselect {\n266: \t\tcase <-timer.C:\n267: \t\tdefault:\n268: \t\t}\n269: \t}\n270: \ttimer.Reset(d)\n271: }\n\n(End of file - total 271 lines)\n</content>",
    "title": "source/head/capture/reorder.go",
    "metadata": {
      "preview": "package capture\n\nimport (\n\t\"container/heap\"\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n)\n\n// maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets\n// are written early, which can put them out of order.\nconst maxReorderBytes = 64 << 20\n\n// Reorder writes the packets of several capture sources in timestamp order.\n//\n// Each source (a node's capture stream, or a local interface socket) delivers its packets with\n// its own delay. The buffer holds every packet for `window` after it arrived and writes the held\n// packets in timestamp order, so a packet that was stamped earlier but delivered up to `window`",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/capture/reorder.go",
        "text": "package capture\n\nimport (\n\t\"container/heap\"\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n)\n\n// maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets\n// are written early, which can put them out of order.\nconst maxReorderBytes = 64 << 20\n\n// Reorder writes the packets of several capture sources in timestamp order.\n//\n// Each source (a node's capture stream, or a local interface socket) delivers its packets with\n// its own delay. The buffer holds every packet for `window` after it arrived and writes the held\n// packets in timestamp order, so a packet that was stamped earlier but delivered up to `window`\n// later still goes out first. A packet stamped before the last packet written arrived too late\n// to be ordered: it is written as it comes and counted, and the count goes to the debug log when\n// the capture ends.\n//\n// A source can place a hold at the earliest timestamp it may still write (Hold); packets stamped\n// after a hold wait for it to be released (Release). The c9s runtime holds while it switches\n// between chained capture segments.\ntype Reorder struct {\n\twrite  func(id uint32, packet *Packet) error\n\tonFail func()\n\twindow time.Duration\n\tnow    func() time.Time\n\n\tmu     sync.Mutex\n\tqueue  reorderQueue\n\tbytes  int\n\tseq    uint64\n\tholds  map[any]int64\n\terr    error\n\twake   chan struct{}\n\tstats  reorderStats\n\tcursor int64 // timestamp of the latest packet written in order\n}\n\ntype reorderStats struct {\n\tlate    int\n\tmaxLate time.Duration\n\tforced  int\n}\n\n// reorderedPacket is a packet waiting in the buffer.\ntype reorderedPacket struct {\n\tid      uint32\n\tpacket  *Packet\n\tarrived time.Time\n\tseq     uint64\n}\n\n// reorderQueue is a min-heap by timestamp, then arrival.\ntype reorderQueue []reorderedPacket\n\nfunc (q reorderQueue) Len() int { return len(q) }\n\nfunc (q reorderQueue) Less(i, j int) bool {\n\tif q[i].packet.Timestamp != q[j].packet.Timestamp {\n\t\treturn q[i].packet.Timestamp < q[j].packet.Timestamp\n\t}\n\n\treturn q[i].seq < q[j].seq\n}\n\nfunc (q reorderQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }\n\nfunc (q *reorderQueue) Push(\n\tx any,\n) {\n\t*q = append(*q, x.(reorderedPacket))\n} //nolint:forcetypeassert // heap contract\n\nfunc (q *reorderQueue) Pop() any {\n\told := *q\n\titem := old[len(old)-1]\n\t*q = old[:len(old)-1]\n\n\treturn item\n}\n\n// NewReorder returns a buffer that writes through write; onFail is called once a write\n// failed. A window of zero or less writes every packet as it arrives.\nfunc NewReorder(\n\twindow time.Duration,\n\twrite func(id uint32, packet *Packet) error,\n\tonFail func(),\n) *Reorder {\n\treturn &Reorder{\n\t\twrite: write, onFail: onFail, window: window, now: time.Now,\n\t\tholds: map[any]int64{}, wake: make(chan struct{}, 1),\n\t}\n}\n\n// push hands a packet to the buffer. It returns the error of a failed write.\nfunc (q *Reorder) Push(id uint32, packet *Packet) error {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\tif q.err != nil {\n\t\treturn q.err\n\t}\n\tif q.window <= 0 {\n\t\treturn q.writeLocked(id, packet)\n\t}\n\tif q.cursor != 0 && packet.Timestamp < q.cursor {\n\t\tq.stats.late++\n\t\tq.stats.maxLate = max(q.stats.maxLate, time.Duration(q.cursor-packet.Timestamp))\n\t\tif q.stats.late == 1 {\n\t\t\tlog.Debug(\"Capture packet arrived after the reorder window, writing it out of order\",\n\t\t\t\t\"late_by\", time.Duration(q.cursor-packet.Timestamp), \"window\", q.window)\n\t\t}\n\n\t\treturn q.writeLocked(id, packet)\n\t}\n\n\tq.seq++\n\theap.Push(&q.queue, reorderedPacket{id: id, packet: packet, arrived: q.now(), seq: q.seq})\n\tq.bytes += len(packet.Data)\n\tfor q.bytes > maxReorderBytes && q.queue.Len() > 0 {\n\t\tq.stats.forced++\n\t\tif err := q.popLocked(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tselect {\n\tcase q.wake <- struct{}{}:\n\tdefault:\n\t}\n\n\treturn nil\n}\n\n// hold keeps packets stamped after timestamp in the buffer until release(key).\nfunc (q *Reorder) Hold(key any, timestamp int64) {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\tq.holds[key] = timestamp\n}\n\n// release removes the hold of key.\nfunc (q *Reorder) Release(key any) {\n\tq.mu.Lock()\n\t_, held := q.holds[key]\n\tdelete(q.holds, key)\n\tq.mu.Unlock()\n\n\tif held {\n\t\tselect {\n\t\tcase q.wake <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n}\n\n// run writes due packets until ctx ends.\nfunc (q *Reorder) Run(ctx context.Context) {\n\tif q.window <= 0 {\n\t\treturn\n\t}\n\n\ttimer := time.NewTimer(time.Hour)\n\tdefer timer.Stop()\n\n\tfor {\n\t\tnext := q.writeDue()\n\t\twait := time.Hour\n\t\tif !next.IsZero() {\n\t\t\twait = max(next.Sub(q.now()), time.Millisecond)\n\t\t}\n\t\tresetTimer(timer, wait)\n\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-q.wake:\n\t\tcase <-timer.C:\n\t\t}\n\t}\n}\n\n// writeDue writes the packets that waited for the window and are not behind a hold, in\n// timestamp order. It returns when the next packet is due, or zero when that depends on a new\n// packet or a released hold.\nfunc (q *Reorder) writeDue() time.Time {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\theld, limit := false, int64(0)\n\tfor _, timestamp := range q.holds {\n\t\tif !held || timestamp < limit {\n\t\t\theld, limit = true, timestamp\n\t\t}\n\t}\n\n\tnow := q.now()\n\tfor q.queue.Len() > 0 && q.err == nil {\n\t\thead := q.queue[0]\n\t\tif held && head.packet.Timestamp > limit {\n\t\t\treturn time.Time{}\n\t\t}\n\t\tif due := head.arrived.Add(q.window); due.After(now) {\n\t\t\treturn due\n\t\t}\n\t\tif q.popLocked() != nil {\n\t\t\treturn time.Time{}\n\t\t}\n\t}\n\n\treturn time.Time{}\n}\n\n// flush writes every remaining packet in timestamp order and logs what could not be ordered.\nfunc (q *Reorder) Flush() {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\tfor q.queue.Len() > 0 && q.err == nil {\n\t\tif q.popLocked() != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tq.queue, q.bytes = nil, 0\n\n\tif q.stats.late > 0 || q.stats.forced > 0 {\n\t\tlog.Debug(\"Capture wrote packets out of timestamp order\",\n\t\t\t\"late_packets\", q.stats.late, \"max_late_by\", q.stats.maxLate,\n\t\t\t\"window\", q.window, \"buffer_overflow_packets\", q.stats.forced)\n\t}\n}\n\nfunc (q *Reorder) popLocked() error {\n\titem := heap.Pop(&q.queue).(reorderedPacket) //nolint:forcetypeassert // heap contract\n\tq.bytes -= len(item.packet.Data)\n\tq.cursor = max(q.cursor, item.packet.Timestamp)\n\n\treturn q.writeLocked(item.id, item.packet)\n}\n\nfunc (q *Reorder) writeLocked(id uint32, packet *Packet) error {\n\tif err := q.write(id, packet); err != nil {\n\t\tif q.err == nil {\n\t\t\tq.err = err\n\t\t\tif q.onFail != nil {\n\t\t\t\tq.onFail()\n\t\t\t}\n\t\t}\n\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc resetTimer(timer *time.Timer, d time.Duration) {\n\tif !timer.Stop() {\n\t\tselect {\n\t\tcase <-timer.C:\n\t\tdefault:\n\t\t}\n\t}\n\ttimer.Reset(d)\n}",
        "lineStart": 1,
        "lineEnd": 271,
        "totalLines": 271,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523372736,
      "end": 1793523372751
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19652d2d2001GFqYeL2rsq0jz4",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196527e22001cp2k6GtKVWT0Tb",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 57696,
    "input": 5773,
    "output": 68,
    "reasoning": 2191,
    "cache": {
      "read": 49664,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196527e22001cp2k6GtKVWT0Tb",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523351074,
    "completed": 1793523372758
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 57696,
    "input": 5773,
    "output": 68,
    "reasoning": 2191,
    "cache": {
      "read": 49664,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 32
step-start
{
  "type": "step-start",
  "id": "prt_19652dadc001rDPHLemyEURPn0",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19652d2df0012coQNQ8TBiw02W"
}
Reasoning
Analysis of reorder.go / output.go:

**Issue A — `Output.Close` calls `Flush` after `Run` returned, but `Run` may return while `writeDue` still returns a due time.** No — Run returns only on ctx done. Close then Flush writes remaining. Fine.

**Issue B — `Reorder.Push` blocking**: `Push` takes q.mu; `writeDue` holds q.mu while calling `writeLocked` → `write` = `writer.WritePacket` → writer (to w). If w is a slow pipe, writeDue holds the lock for the duration of the write, blocking all Push calls. Backpressure is intended. But note: c9s chain `send` blocks when events channel full (256). Reader goroutines blocked on send. That's the backpressure chain. OK.

**Issue C — `Reorder.Flush` doesn't wake; fine since called after Run ended.**

But wait — there's a real subtlety: `Output.Close` cancels run and waits, then Flush. However, `Emit` may be called concurrently with `Close`? In c9s, chains have exited (group.Wait) before out.Close. In local, wg.Wait before out.Close. OK.

**Issue D — `Output.Emit` with limit: `count > o.limit` → stop and return (false, nil). But this packet is dropped and not counted... it was counted (written.Add). Fine.

**Issue E — cursor and late packets**: `q.cursor` updated only via popLocked. Late direct writes don't update cursor — but a late packet has Timestamp < cursor, so max() wouldn't change. Fine. But consider window > 0 and a hold: while held, head.timestamp > limit → return zero time; wait = 1 hour; on Release → wake. OK.

**Issue F — `writeDue` returns `due` (next due time) even when the head is behind a hold?** No — it checks hold first: if held && head.ts > limit → return zero (no wake until release). But what if head.ts <= limit and due in future → returns due. Good.

**Issue G — packet with Timestamp == 0?** c9s packets always have timestamps from clabwire. Local packets from afpacket have kernel timestamps. OK.

**Issue H — `Push` when `q.err != nil` returns error. Local reader drains and closes; c9s `send` of packet events continues but handlePacket → emit → Push returns err → chain returns err. But if chain already returned... The chain returns error from handle → run returns err → group.Wait returns first error → Capture returns err (unless ctx canceled). For a write failure (Wireshark closed), stop() cancels captureCtx → groupCtx canceled → other chains stop. Good.

**Issue I — Race on `Output.Close` vs pending `Push` after error?** After a write error, chains stop; group.Wait returns; out.Close called. No more Push. OK.

**Issue J — In `Output.Emit`, when `count == o.limit` → stop() and return false — the packet WAS pushed (Push before the check). Good: the limit-th packet is written.

**Issue K — `Written()` used by c9s `start` for `remaining` computation — reads atomic; races with concurrent Emit from other chains; benign (close enough; min with 1).

Now the local capture — let me re-read local.go fully to verify the drain/openAll concerns and the ctx semantics.
Now let me re-read `capture/local.go` in full to verify the reader lifecycle, drain logic, and error paths.
read · completed

Input

{
  "filePath": "/source/head/capture/local.go"
}

Output

<path>/source/head/capture/local.go</path>
<type>file</type>
<content>
1: package capture
2: 
3: import (
4: 	"context"
5: 	"errors"
6: 	"fmt"
7: 	"io"
8: 	"os"
9: 	"sync"
10: 	"time"
11: 
12: 	"github.com/charmbracelet/log"
13: 	"github.com/containernetworking/plugins/pkg/ns"
14: 	"github.com/gopacket/gopacket"
15: 	"github.com/gopacket/gopacket/afpacket"
16: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
17: )
18: 
19: const (
20: 	// localReorderWindow is how long the merged stream holds packets of local sockets back to
21: 	// write them in timestamp order. Each socket hands over its packets within
22: 	// localBlockTimeout, so a few times that covers the delivery skew between sockets.
23: 	localReorderWindow = 100 * time.Millisecond
24: 	// localBlockTimeout is how long the kernel fills a ring block before it hands it over.
25: 	localBlockTimeout = 10 * time.Millisecond
26: 	// localPollTimeout is how often a socket reader checks whether the capture ended.
27: 	localPollTimeout = 100 * time.Millisecond
28: 	// localReopenInterval is how often a reader tries to reopen the socket of an interface
29: 	// that went down or disappeared.
30: 	localReopenInterval = 200 * time.Millisecond
31: 	// localDrainQuiet is how long after the end of a capture a reader keeps waiting for packets
32: 	// still in the socket's ring: the kernel hands over a block within two block timeouts.
33: 	localDrainQuiet = 5 * localBlockTimeout
34: 	// localDrainTimeout bounds the drain while packets keep arriving.
35: 	localDrainTimeout = 250 * time.Millisecond
36: 	// localRingBlocks and localMinBlockSize size the receive ring of each socket: eight blocks
37: 	// of at least 1 MiB, each larger than the snap length.
38: 	localRingBlocks   = 8
39: 	localMinBlockSize = 1 << 20
40: 	// vlanHeaderLength is the length of the 802.1Q tag put back into frames whose tag the
41: 	// kernel moved out of band.
42: 	vlanHeaderLength = 4
43: )
44: 
45: // errReadTimeout is returned by a packet source that has no packet within the poll timeout.
46: var errReadTimeout = errors.New("no packet within the poll timeout")
47: 
48: // ExecFunc runs f in the network namespace of a node.
49: type ExecFunc func(ctx context.Context, f func(ns.NetNS) error) error
50: 
51: // LocalTarget is one interface of a node on this machine (Docker or Podman) to capture.
52: type LocalTarget struct {
53: 	// Node is the node name as the topology spells it.
54: 	Node string
55: 	// Interface is the interface name inside the node.
56: 	Interface string
57: 	// Exec runs a function in the node's network namespace.
58: 	Exec ExecFunc
59: }
60: 
61: // packetSource reads the packets of one interface.
62: type packetSource interface {
63: 	// ReadPacket returns the next packet; the data is only valid until the next call. It
64: 	// returns errReadTimeout when no packet arrived within the poll timeout.
65: 	ReadPacket() ([]byte, gopacket.CaptureInfo, error)
66: 	Close()
67: }
68: 
69: // openSourcesFunc opens one packet source per interface in the network namespace exec enters.
70: type openSourcesFunc func(
71: 	ctx context.Context,
72: 	exec ExecFunc,
73: 	interfaces []string,
74: 	snapLength int,
75: ) ([]packetSource, error)
76: 
77: // CaptureLocal streams pcapng from interfaces of nodes on this machine to w, with the same
78: // output and end conditions as labruntime.PacketCapturer.Capture: one section, one Interface
79: // Description Block per target named <node>:<interface>, then the packets of every target in
80: // timestamp order. targets lists the interfaces of req.Targets, resolved, in the same order.
81: //
82: // Each interface is read through a packet socket opened in the node's network namespace, so
83: // nothing runs in the node and the node image needs no capture tools; it needs CAP_NET_RAW and
84: // the right to enter the namespace, so root. An interface that goes down is reopened once it is
85: // up again; one that disappears (its node stopped or was recreated) is reattached when it is
86: // back, and the time it was gone is reported as a gap through req.OnGap (or logged).
87: func CaptureLocal(
88: 	ctx context.Context,
89: 	req clablabruntime.CaptureRequest,
90: 	targets []LocalTarget,
91: 	w io.Writer,
92: ) error {
93: 	return localCapture{
94: 		open:           openPacketSockets,
95: 		window:         localReorderWindow,
96: 		reopenInterval: localReopenInterval,
97: 	}.run(ctx, req, targets, w)
98: }
99: 
100: // localCapture is a local capture with its socket opener and timings, which tests replace.
101: type localCapture struct {
102: 	open           openSourcesFunc
103: 	window         time.Duration
104: 	reopenInterval time.Duration
105: }
106: 
107: func (l localCapture) run(
108: 	ctx context.Context,
109: 	req clablabruntime.CaptureRequest,
110: 	targets []LocalTarget,
111: 	w io.Writer,
112: ) error {
113: 	if err := ValidateRequest(&req); err != nil {
114: 		return err
115: 	}
116: 	if len(targets) != len(req.Targets) {
117: 		return fmt.Errorf("capture has %d resolved targets for %d requested ones",
118: 			len(targets), len(req.Targets))
119: 	}
120: 
121: 	sources, err := l.openAll(ctx, targets, req.SnapLength)
122: 	if err != nil {
123: 		return err
124: 	}
125: 
126: 	names := make([]string, len(targets))
127: 	for idx, target := range targets {
128: 		names[idx] = target.Node + ":" + target.Interface
129: 	}
130: 
131: 	captureCtx, stop := context.WithCancel(ctx)
132: 	defer stop()
133: 	if req.Duration > 0 {
134: 		var cancelTimeout context.CancelFunc
135: 		captureCtx, cancelTimeout = context.WithTimeout(captureCtx, req.Duration)
136: 		defer cancelTimeout()
137: 	}
138: 
139: 	out, err := NewOutput(w, names, req.SnapLength, req.PacketLimit, l.window, stop)
140: 	if err != nil {
141: 		for _, source := range sources {
142: 			source.Close()
143: 		}
144: 
145: 		return err
146: 	}
147: 
148: 	var wg sync.WaitGroup
149: 	for idx, source := range sources {
150: 		reader := &localReader{
151: 			capture: l,
152: 			out:     out,
153: 			id:      uint32(idx), //nolint:gosec // bounded by the targets
154: 			target:  targets[idx],
155: 			snap:    req.SnapLength,
156: 			onGap:   req.OnGap,
157: 		}
158: 		wg.Go(func() {
159: 			reader.run(captureCtx, source)
160: 		})
161: 	}
162: 	wg.Wait()
163: 
164: 	return out.Close()
165: }
166: 
167: // openAll opens the sockets of every target before anything is written, one namespace entry
168: // per node, so a capture that cannot start fails without output.
169: func (l localCapture) openAll(
170: 	ctx context.Context,
171: 	targets []LocalTarget,
172: 	snapLength int,
173: ) ([]packetSource, error) {
174: 	type nodeTargets struct {
175: 		exec    ExecFunc
176: 		indexes []int
177: 		names   []string
178: 	}
179: 	var order []string
180: 	byNode := map[string]*nodeTargets{}
181: 	for idx, target := range targets {
182: 		group := byNode[target.Node]
183: 		if group == nil {
184: 			group = &nodeTargets{exec: target.Exec}
185: 			byNode[target.Node] = group
186: 			order = append(order, target.Node)
187: 		}
188: 		group.indexes = append(group.indexes, idx)
189: 		group.names = append(group.names, target.Interface)
190: 	}
191: 
192: 	sources := make([]packetSource, len(targets))
193: 	closeAll := func() {
194: 		for _, source := range sources {
195: 			if source != nil {
196: 				source.Close()
197: 			}
198: 		}
199: 	}
200: 	for _, node := range order {
201: 		group := byNode[node]
202: 		opened, err := l.open(ctx, group.exec, group.names, snapLength)
203: 		if err != nil {
204: 			closeAll()
205: 			return nil, fmt.Errorf("failed to start the capture on node %q: %w", node, err)
206: 		}
207: 		for idx, source := range opened {
208: 			sources[group.indexes[idx]] = source
209: 		}
210: 	}
211: 
212: 	return sources, nil
213: }
214: 
215: // localReader reads one interface into the merged stream.
216: type localReader struct {
217: 	capture localCapture
218: 	out     *Output
219: 	id      uint32
220: 	target  LocalTarget
221: 	snap    int
222: 	onGap   func(clablabruntime.CaptureGap)
223: }
224: 
225: func (r *localReader) run(ctx context.Context, source packetSource) {
226: 	defer func() {
227: 		if source != nil {
228: 			source.Close()
229: 		}
230: 	}()
231: 
232: 	for {
233: 		if ctx.Err() != nil {
234: 			r.drain(source, time.Now())
235: 			return
236: 		}
237: 
238: 		data, info, err := source.ReadPacket()
239: 		if errors.Is(err, errReadTimeout) {
240: 			continue
241: 		}
242: 		if err != nil {
243: 			// The socket reports an error once its interface went down or was removed, and
244: 			// keeps reporting it: it is reopened.
245: 			log.Debug("Capture socket failed, reopening it", "node", r.target.Node,
246: 				"interface", r.target.Interface, "error", err)
247: 			source.Close()
248: 			source = r.reopen(ctx)
249: 			if source == nil {
250: 				return
251: 			}
252: 
253: 			continue
254: 		}
255: 
256: 		if more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {
257: 			return
258: 		}
259: 	}
260: }
261: 
262: // drain writes the packets that arrived before end but were still in the socket's ring: the
263: // kernel hands over a ring block once it is full or its block timeout passed, so the last
264: // packets before a capture ended may not have been read yet.
265: func (r *localReader) drain(source packetSource, end time.Time) {
266: 	deadline := end.Add(localDrainTimeout)
267: 	for time.Now().Before(deadline) {
268: 		data, info, err := source.ReadPacket()
269: 		if errors.Is(err, errReadTimeout) && time.Since(end) < localDrainQuiet {
270: 			continue
271: 		}
272: 		if err != nil || info.Timestamp.After(end) {
273: 			return
274: 		}
275: 		if more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {
276: 			return
277: 		}
278: 	}
279: }
280: 
281: // packet copies a packet out of the socket's ring, cut to the snap length.
282: func (r *localReader) packet(data []byte, info gopacket.CaptureInfo) *Packet {
283: 	length := info.Length
284: 	for _, ancillary := range info.AncillaryData {
285: 		if _, ok := ancillary.(afpacket.AncillaryVLAN); ok {
286: 			// the tag was put back into the data and counts toward the frame length
287: 			length += vlanHeaderLength
288: 			break
289: 		}
290: 	}
291: 	length = max(length, len(data))
292: 
293: 	captured := make([]byte, min(len(data), r.snap))
294: 	copy(captured, data)
295: 
296: 	return &Packet{
297: 		Timestamp:      info.Timestamp.UnixNano(),
298: 		OriginalLength: uint32(length), //nolint:gosec // bounded by the interface MTU
299: 		Data:           captured,
300: 	}
301: }
302: 
303: // reopen opens the interface's socket again once its node and interface are back. It returns
304: // nil when the capture ended first. Time the interface could not be opened is reported as a gap;
305: // an interface that only went down is not, as it has no traffic while down.
306: func (r *localReader) reopen(ctx context.Context) packetSource {
307: 	from := time.Now()
308: 	var unavailable error
309: 
310: 	timer := time.NewTimer(r.capture.reopenInterval)
311: 	defer timer.Stop()
312: 
313: 	for {
314: 		select {
315: 		case <-ctx.Done():
316: 			if unavailable != nil {
317: 				r.reportGap(from, time.Time{}, unavailable)
318: 			}
319: 
320: 			return nil
321: 		case <-timer.C:
322: 		}
323: 
324: 		opened, err := r.capture.open(ctx, r.target.Exec, []string{r.target.Interface}, r.snap)
325: 		if err != nil {
326: 			if unavailable == nil {
327: 				log.Debug("Capture interface is not available, waiting for it",
328: 					"node", r.target.Node, "interface", r.target.Interface, "error", err)
329: 			}
330: 			unavailable = err
331: 			resetTimer(timer, r.capture.reopenInterval)
332: 
333: 			continue
334: 		}
335: 		if unavailable != nil {
336: 			r.reportGap(from, time.Now(), unavailable)
337: 		}
338: 
339: 		return opened[0]
340: 	}
341: }
342: 
343: func (r *localReader) reportGap(from, to time.Time, cause error) {
344: 	ReportGap(r.onGap, clablabruntime.CaptureGap{
345: 		Node:       r.target.Node,
346: 		Interfaces: []string{r.target.Interface},
347: 		From:       from,
348: 		To:         to,
349: 		Reason:     fmt.Sprintf("the interface was not available: %v", cause),
350: 	})
351: }
352: 
353: // openPacketSockets opens one packet socket per interface in the namespace exec enters. A socket
354: // stays bound to its interface after the thread left the namespace.
355: func openPacketSockets(
356: 	ctx context.Context,
357: 	exec ExecFunc,
358: 	interfaces []string,
359: 	snapLength int,
360: ) ([]packetSource, error) {
361: 	sources := make([]packetSource, 0, len(interfaces))
362: 	err := exec(ctx, func(ns.NetNS) error {
363: 		for _, name := range interfaces {
364: 			source, err := openPacketSocket(name, snapLength)
365: 			if err != nil {
366: 				return fmt.Errorf("interface %q: %w", name, err)
367: 			}
368: 			sources = append(sources, source)
369: 		}
370: 
371: 		return nil
372: 	})
373: 	if err != nil {
374: 		for _, source := range sources {
375: 			source.Close()
376: 		}
377: 
378: 		return nil, err
379: 	}
380: 
381: 	return sources, nil
382: }
383: 
384: // afpacketSource is a TPACKET_V3 receive ring on one interface.
385: type afpacketSource struct {
386: 	handle *afpacket.TPacket
387: }
388: 
389: func openPacketSocket(name string, snapLength int) (*afpacketSource, error) {
390: 	// A TPACKET_V3 block holds whole frames: it must be larger than the snap length, plus the
391: 	// block and frame headers, and a multiple of the page size.
392: 	pageSize := os.Getpagesize()
393: 	blockSize := max(localMinBlockSize, snapLength+pageSize)
394: 	blockSize = (blockSize + pageSize - 1) / pageSize * pageSize
395: 
396: 	handle, err := afpacket.NewTPacket(
397: 		afpacket.OptInterface(name),
398: 		afpacket.OptTPacketVersion(afpacket.TPacketVersion3),
399: 		afpacket.OptFrameSize(blockSize),
400: 		afpacket.OptBlockSize(blockSize),
401: 		afpacket.OptNumBlocks(localRingBlocks),
402: 		afpacket.OptBlockTimeout(localBlockTimeout),
403: 		afpacket.OptPollTimeout(localPollTimeout),
404: 		// the kernel moves 802.1Q tags out of the frame; captures show them in place
405: 		afpacket.OptAddVLANHeader(true),
406: 	)
407: 	if err != nil {
408: 		return nil, err
409: 	}
410: 	// promiscuous mode is a membership of this socket and ends with it
411: 	if err := handle.SetPromiscuous(true); err != nil {
412: 		handle.Close()
413: 		return nil, fmt.Errorf("failed to enable promiscuous mode: %w", err)
414: 	}
415: 
416: 	return &afpacketSource{handle: handle}, nil
417: }
418: 
419: func (s *afpacketSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {
420: 	data, info, err := s.handle.ZeroCopyReadPacketData()
421: 	if errors.Is(err, afpacket.ErrTimeout) {
422: 		return nil, info, errReadTimeout
423: 	}
424: 
425: 	return data, info, err
426: }
427: 
428: func (s *afpacketSource) Close() {
429: 	s.handle.Close()
430: }

(End of file - total 430 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19652f683001ZF9WP2yBf20Ha9",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19652d2df0012coQNQ8TBiw02W",
  "callID": "call_1a7902fbcb9e440082b36a44",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/capture/local.go"
    },
    "output": "<path>/source/head/capture/local.go</path>\n<type>file</type>\n<content>\n1: package capture\n2: \n3: import (\n4: \t\"context\"\n5: \t\"errors\"\n6: \t\"fmt\"\n7: \t\"io\"\n8: \t\"os\"\n9: \t\"sync\"\n10: \t\"time\"\n11: \n12: \t\"github.com/charmbracelet/log\"\n13: \t\"github.com/containernetworking/plugins/pkg/ns\"\n14: \t\"github.com/gopacket/gopacket\"\n15: \t\"github.com/gopacket/gopacket/afpacket\"\n16: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n17: )\n18: \n19: const (\n20: \t// localReorderWindow is how long the merged stream holds packets of local sockets back to\n21: \t// write them in timestamp order. Each socket hands over its packets within\n22: \t// localBlockTimeout, so a few times that covers the delivery skew between sockets.\n23: \tlocalReorderWindow = 100 * time.Millisecond\n24: \t// localBlockTimeout is how long the kernel fills a ring block before it hands it over.\n25: \tlocalBlockTimeout = 10 * time.Millisecond\n26: \t// localPollTimeout is how often a socket reader checks whether the capture ended.\n27: \tlocalPollTimeout = 100 * time.Millisecond\n28: \t// localReopenInterval is how often a reader tries to reopen the socket of an interface\n29: \t// that went down or disappeared.\n30: \tlocalReopenInterval = 200 * time.Millisecond\n31: \t// localDrainQuiet is how long after the end of a capture a reader keeps waiting for packets\n32: \t// still in the socket's ring: the kernel hands over a block within two block timeouts.\n33: \tlocalDrainQuiet = 5 * localBlockTimeout\n34: \t// localDrainTimeout bounds the drain while packets keep arriving.\n35: \tlocalDrainTimeout = 250 * time.Millisecond\n36: \t// localRingBlocks and localMinBlockSize size the receive ring of each socket: eight blocks\n37: \t// of at least 1 MiB, each larger than the snap length.\n38: \tlocalRingBlocks   = 8\n39: \tlocalMinBlockSize = 1 << 20\n40: \t// vlanHeaderLength is the length of the 802.1Q tag put back into frames whose tag the\n41: \t// kernel moved out of band.\n42: \tvlanHeaderLength = 4\n43: )\n44: \n45: // errReadTimeout is returned by a packet source that has no packet within the poll timeout.\n46: var errReadTimeout = errors.New(\"no packet within the poll timeout\")\n47: \n48: // ExecFunc runs f in the network namespace of a node.\n49: type ExecFunc func(ctx context.Context, f func(ns.NetNS) error) error\n50: \n51: // LocalTarget is one interface of a node on this machine (Docker or Podman) to capture.\n52: type LocalTarget struct {\n53: \t// Node is the node name as the topology spells it.\n54: \tNode string\n55: \t// Interface is the interface name inside the node.\n56: \tInterface string\n57: \t// Exec runs a function in the node's network namespace.\n58: \tExec ExecFunc\n59: }\n60: \n61: // packetSource reads the packets of one interface.\n62: type packetSource interface {\n63: \t// ReadPacket returns the next packet; the data is only valid until the next call. It\n64: \t// returns errReadTimeout when no packet arrived within the poll timeout.\n65: \tReadPacket() ([]byte, gopacket.CaptureInfo, error)\n66: \tClose()\n67: }\n68: \n69: // openSourcesFunc opens one packet source per interface in the network namespace exec enters.\n70: type openSourcesFunc func(\n71: \tctx context.Context,\n72: \texec ExecFunc,\n73: \tinterfaces []string,\n74: \tsnapLength int,\n75: ) ([]packetSource, error)\n76: \n77: // CaptureLocal streams pcapng from interfaces of nodes on this machine to w, with the same\n78: // output and end conditions as labruntime.PacketCapturer.Capture: one section, one Interface\n79: // Description Block per target named <node>:<interface>, then the packets of every target in\n80: // timestamp order. targets lists the interfaces of req.Targets, resolved, in the same order.\n81: //\n82: // Each interface is read through a packet socket opened in the node's network namespace, so\n83: // nothing runs in the node and the node image needs no capture tools; it needs CAP_NET_RAW and\n84: // the right to enter the namespace, so root. An interface that goes down is reopened once it is\n85: // up again; one that disappears (its node stopped or was recreated) is reattached when it is\n86: // back, and the time it was gone is reported as a gap through req.OnGap (or logged).\n87: func CaptureLocal(\n88: \tctx context.Context,\n89: \treq clablabruntime.CaptureRequest,\n90: \ttargets []LocalTarget,\n91: \tw io.Writer,\n92: ) error {\n93: \treturn localCapture{\n94: \t\topen:           openPacketSockets,\n95: \t\twindow:         localReorderWindow,\n96: \t\treopenInterval: localReopenInterval,\n97: \t}.run(ctx, req, targets, w)\n98: }\n99: \n100: // localCapture is a local capture with its socket opener and timings, which tests replace.\n101: type localCapture struct {\n102: \topen           openSourcesFunc\n103: \twindow         time.Duration\n104: \treopenInterval time.Duration\n105: }\n106: \n107: func (l localCapture) run(\n108: \tctx context.Context,\n109: \treq clablabruntime.CaptureRequest,\n110: \ttargets []LocalTarget,\n111: \tw io.Writer,\n112: ) error {\n113: \tif err := ValidateRequest(&req); err != nil {\n114: \t\treturn err\n115: \t}\n116: \tif len(targets) != len(req.Targets) {\n117: \t\treturn fmt.Errorf(\"capture has %d resolved targets for %d requested ones\",\n118: \t\t\tlen(targets), len(req.Targets))\n119: \t}\n120: \n121: \tsources, err := l.openAll(ctx, targets, req.SnapLength)\n122: \tif err != nil {\n123: \t\treturn err\n124: \t}\n125: \n126: \tnames := make([]string, len(targets))\n127: \tfor idx, target := range targets {\n128: \t\tnames[idx] = target.Node + \":\" + target.Interface\n129: \t}\n130: \n131: \tcaptureCtx, stop := context.WithCancel(ctx)\n132: \tdefer stop()\n133: \tif req.Duration > 0 {\n134: \t\tvar cancelTimeout context.CancelFunc\n135: \t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx, req.Duration)\n136: \t\tdefer cancelTimeout()\n137: \t}\n138: \n139: \tout, err := NewOutput(w, names, req.SnapLength, req.PacketLimit, l.window, stop)\n140: \tif err != nil {\n141: \t\tfor _, source := range sources {\n142: \t\t\tsource.Close()\n143: \t\t}\n144: \n145: \t\treturn err\n146: \t}\n147: \n148: \tvar wg sync.WaitGroup\n149: \tfor idx, source := range sources {\n150: \t\treader := &localReader{\n151: \t\t\tcapture: l,\n152: \t\t\tout:     out,\n153: \t\t\tid:      uint32(idx), //nolint:gosec // bounded by the targets\n154: \t\t\ttarget:  targets[idx],\n155: \t\t\tsnap:    req.SnapLength,\n156: \t\t\tonGap:   req.OnGap,\n157: \t\t}\n158: \t\twg.Go(func() {\n159: \t\t\treader.run(captureCtx, source)\n160: \t\t})\n161: \t}\n162: \twg.Wait()\n163: \n164: \treturn out.Close()\n165: }\n166: \n167: // openAll opens the sockets of every target before anything is written, one namespace entry\n168: // per node, so a capture that cannot start fails without output.\n169: func (l localCapture) openAll(\n170: \tctx context.Context,\n171: \ttargets []LocalTarget,\n172: \tsnapLength int,\n173: ) ([]packetSource, error) {\n174: \ttype nodeTargets struct {\n175: \t\texec    ExecFunc\n176: \t\tindexes []int\n177: \t\tnames   []string\n178: \t}\n179: \tvar order []string\n180: \tbyNode := map[string]*nodeTargets{}\n181: \tfor idx, target := range targets {\n182: \t\tgroup := byNode[target.Node]\n183: \t\tif group == nil {\n184: \t\t\tgroup = &nodeTargets{exec: target.Exec}\n185: \t\t\tbyNode[target.Node] = group\n186: \t\t\torder = append(order, target.Node)\n187: \t\t}\n188: \t\tgroup.indexes = append(group.indexes, idx)\n189: \t\tgroup.names = append(group.names, target.Interface)\n190: \t}\n191: \n192: \tsources := make([]packetSource, len(targets))\n193: \tcloseAll := func() {\n194: \t\tfor _, source := range sources {\n195: \t\t\tif source != nil {\n196: \t\t\t\tsource.Close()\n197: \t\t\t}\n198: \t\t}\n199: \t}\n200: \tfor _, node := range order {\n201: \t\tgroup := byNode[node]\n202: \t\topened, err := l.open(ctx, group.exec, group.names, snapLength)\n203: \t\tif err != nil {\n204: \t\t\tcloseAll()\n205: \t\t\treturn nil, fmt.Errorf(\"failed to start the capture on node %q: %w\", node, err)\n206: \t\t}\n207: \t\tfor idx, source := range opened {\n208: \t\t\tsources[group.indexes[idx]] = source\n209: \t\t}\n210: \t}\n211: \n212: \treturn sources, nil\n213: }\n214: \n215: // localReader reads one interface into the merged stream.\n216: type localReader struct {\n217: \tcapture localCapture\n218: \tout     *Output\n219: \tid      uint32\n220: \ttarget  LocalTarget\n221: \tsnap    int\n222: \tonGap   func(clablabruntime.CaptureGap)\n223: }\n224: \n225: func (r *localReader) run(ctx context.Context, source packetSource) {\n226: \tdefer func() {\n227: \t\tif source != nil {\n228: \t\t\tsource.Close()\n229: \t\t}\n230: \t}()\n231: \n232: \tfor {\n233: \t\tif ctx.Err() != nil {\n234: \t\t\tr.drain(source, time.Now())\n235: \t\t\treturn\n236: \t\t}\n237: \n238: \t\tdata, info, err := source.ReadPacket()\n239: \t\tif errors.Is(err, errReadTimeout) {\n240: \t\t\tcontinue\n241: \t\t}\n242: \t\tif err != nil {\n243: \t\t\t// The socket reports an error once its interface went down or was removed, and\n244: \t\t\t// keeps reporting it: it is reopened.\n245: \t\t\tlog.Debug(\"Capture socket failed, reopening it\", \"node\", r.target.Node,\n246: \t\t\t\t\"interface\", r.target.Interface, \"error\", err)\n247: \t\t\tsource.Close()\n248: \t\t\tsource = r.reopen(ctx)\n249: \t\t\tif source == nil {\n250: \t\t\t\treturn\n251: \t\t\t}\n252: \n253: \t\t\tcontinue\n254: \t\t}\n255: \n256: \t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n257: \t\t\treturn\n258: \t\t}\n259: \t}\n260: }\n261: \n262: // drain writes the packets that arrived before end but were still in the socket's ring: the\n263: // kernel hands over a ring block once it is full or its block timeout passed, so the last\n264: // packets before a capture ended may not have been read yet.\n265: func (r *localReader) drain(source packetSource, end time.Time) {\n266: \tdeadline := end.Add(localDrainTimeout)\n267: \tfor time.Now().Before(deadline) {\n268: \t\tdata, info, err := source.ReadPacket()\n269: \t\tif errors.Is(err, errReadTimeout) && time.Since(end) < localDrainQuiet {\n270: \t\t\tcontinue\n271: \t\t}\n272: \t\tif err != nil || info.Timestamp.After(end) {\n273: \t\t\treturn\n274: \t\t}\n275: \t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n276: \t\t\treturn\n277: \t\t}\n278: \t}\n279: }\n280: \n281: // packet copies a packet out of the socket's ring, cut to the snap length.\n282: func (r *localReader) packet(data []byte, info gopacket.CaptureInfo) *Packet {\n283: \tlength := info.Length\n284: \tfor _, ancillary := range info.AncillaryData {\n285: \t\tif _, ok := ancillary.(afpacket.AncillaryVLAN); ok {\n286: \t\t\t// the tag was put back into the data and counts toward the frame length\n287: \t\t\tlength += vlanHeaderLength\n288: \t\t\tbreak\n289: \t\t}\n290: \t}\n291: \tlength = max(length, len(data))\n292: \n293: \tcaptured := make([]byte, min(len(data), r.snap))\n294: \tcopy(captured, data)\n295: \n296: \treturn &Packet{\n297: \t\tTimestamp:      info.Timestamp.UnixNano(),\n298: \t\tOriginalLength: uint32(length), //nolint:gosec // bounded by the interface MTU\n299: \t\tData:           captured,\n300: \t}\n301: }\n302: \n303: // reopen opens the interface's socket again once its node and interface are back. It returns\n304: // nil when the capture ended first. Time the interface could not be opened is reported as a gap;\n305: // an interface that only went down is not, as it has no traffic while down.\n306: func (r *localReader) reopen(ctx context.Context) packetSource {\n307: \tfrom := time.Now()\n308: \tvar unavailable error\n309: \n310: \ttimer := time.NewTimer(r.capture.reopenInterval)\n311: \tdefer timer.Stop()\n312: \n313: \tfor {\n314: \t\tselect {\n315: \t\tcase <-ctx.Done():\n316: \t\t\tif unavailable != nil {\n317: \t\t\t\tr.reportGap(from, time.Time{}, unavailable)\n318: \t\t\t}\n319: \n320: \t\t\treturn nil\n321: \t\tcase <-timer.C:\n322: \t\t}\n323: \n324: \t\topened, err := r.capture.open(ctx, r.target.Exec, []string{r.target.Interface}, r.snap)\n325: \t\tif err != nil {\n326: \t\t\tif unavailable == nil {\n327: \t\t\t\tlog.Debug(\"Capture interface is not available, waiting for it\",\n328: \t\t\t\t\t\"node\", r.target.Node, \"interface\", r.target.Interface, \"error\", err)\n329: \t\t\t}\n330: \t\t\tunavailable = err\n331: \t\t\tresetTimer(timer, r.capture.reopenInterval)\n332: \n333: \t\t\tcontinue\n334: \t\t}\n335: \t\tif unavailable != nil {\n336: \t\t\tr.reportGap(from, time.Now(), unavailable)\n337: \t\t}\n338: \n339: \t\treturn opened[0]\n340: \t}\n341: }\n342: \n343: func (r *localReader) reportGap(from, to time.Time, cause error) {\n344: \tReportGap(r.onGap, clablabruntime.CaptureGap{\n345: \t\tNode:       r.target.Node,\n346: \t\tInterfaces: []string{r.target.Interface},\n347: \t\tFrom:       from,\n348: \t\tTo:         to,\n349: \t\tReason:     fmt.Sprintf(\"the interface was not available: %v\", cause),\n350: \t})\n351: }\n352: \n353: // openPacketSockets opens one packet socket per interface in the namespace exec enters. A socket\n354: // stays bound to its interface after the thread left the namespace.\n355: func openPacketSockets(\n356: \tctx context.Context,\n357: \texec ExecFunc,\n358: \tinterfaces []string,\n359: \tsnapLength int,\n360: ) ([]packetSource, error) {\n361: \tsources := make([]packetSource, 0, len(interfaces))\n362: \terr := exec(ctx, func(ns.NetNS) error {\n363: \t\tfor _, name := range interfaces {\n364: \t\t\tsource, err := openPacketSocket(name, snapLength)\n365: \t\t\tif err != nil {\n366: \t\t\t\treturn fmt.Errorf(\"interface %q: %w\", name, err)\n367: \t\t\t}\n368: \t\t\tsources = append(sources, source)\n369: \t\t}\n370: \n371: \t\treturn nil\n372: \t})\n373: \tif err != nil {\n374: \t\tfor _, source := range sources {\n375: \t\t\tsource.Close()\n376: \t\t}\n377: \n378: \t\treturn nil, err\n379: \t}\n380: \n381: \treturn sources, nil\n382: }\n383: \n384: // afpacketSource is a TPACKET_V3 receive ring on one interface.\n385: type afpacketSource struct {\n386: \thandle *afpacket.TPacket\n387: }\n388: \n389: func openPacketSocket(name string, snapLength int) (*afpacketSource, error) {\n390: \t// A TPACKET_V3 block holds whole frames: it must be larger than the snap length, plus the\n391: \t// block and frame headers, and a multiple of the page size.\n392: \tpageSize := os.Getpagesize()\n393: \tblockSize := max(localMinBlockSize, snapLength+pageSize)\n394: \tblockSize = (blockSize + pageSize - 1) / pageSize * pageSize\n395: \n396: \thandle, err := afpacket.NewTPacket(\n397: \t\tafpacket.OptInterface(name),\n398: \t\tafpacket.OptTPacketVersion(afpacket.TPacketVersion3),\n399: \t\tafpacket.OptFrameSize(blockSize),\n400: \t\tafpacket.OptBlockSize(blockSize),\n401: \t\tafpacket.OptNumBlocks(localRingBlocks),\n402: \t\tafpacket.OptBlockTimeout(localBlockTimeout),\n403: \t\tafpacket.OptPollTimeout(localPollTimeout),\n404: \t\t// the kernel moves 802.1Q tags out of the frame; captures show them in place\n405: \t\tafpacket.OptAddVLANHeader(true),\n406: \t)\n407: \tif err != nil {\n408: \t\treturn nil, err\n409: \t}\n410: \t// promiscuous mode is a membership of this socket and ends with it\n411: \tif err := handle.SetPromiscuous(true); err != nil {\n412: \t\thandle.Close()\n413: \t\treturn nil, fmt.Errorf(\"failed to enable promiscuous mode: %w\", err)\n414: \t}\n415: \n416: \treturn &afpacketSource{handle: handle}, nil\n417: }\n418: \n419: func (s *afpacketSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {\n420: \tdata, info, err := s.handle.ZeroCopyReadPacketData()\n421: \tif errors.Is(err, afpacket.ErrTimeout) {\n422: \t\treturn nil, info, errReadTimeout\n423: \t}\n424: \n425: \treturn data, info, err\n426: }\n427: \n428: func (s *afpacketSource) Close() {\n429: \ts.handle.Close()\n430: }\n\n(End of file - total 430 lines)\n</content>",
    "title": "source/head/capture/local.go",
    "metadata": {
      "preview": "package capture\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\t\"github.com/containernetworking/plugins/pkg/ns\"\n\t\"github.com/gopacket/gopacket\"\n\t\"github.com/gopacket/gopacket/afpacket\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\nconst (\n\t// localReorderWindow is how long the merged stream holds packets of local sockets back to",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/capture/local.go",
        "text": "package capture\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\t\"github.com/containernetworking/plugins/pkg/ns\"\n\t\"github.com/gopacket/gopacket\"\n\t\"github.com/gopacket/gopacket/afpacket\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\nconst (\n\t// localReorderWindow is how long the merged stream holds packets of local sockets back to\n\t// write them in timestamp order. Each socket hands over its packets within\n\t// localBlockTimeout, so a few times that covers the delivery skew between sockets.\n\tlocalReorderWindow = 100 * time.Millisecond\n\t// localBlockTimeout is how long the kernel fills a ring block before it hands it over.\n\tlocalBlockTimeout = 10 * time.Millisecond\n\t// localPollTimeout is how often a socket reader checks whether the capture ended.\n\tlocalPollTimeout = 100 * time.Millisecond\n\t// localReopenInterval is how often a reader tries to reopen the socket of an interface\n\t// that went down or disappeared.\n\tlocalReopenInterval = 200 * time.Millisecond\n\t// localDrainQuiet is how long after the end of a capture a reader keeps waiting for packets\n\t// still in the socket's ring: the kernel hands over a block within two block timeouts.\n\tlocalDrainQuiet = 5 * localBlockTimeout\n\t// localDrainTimeout bounds the drain while packets keep arriving.\n\tlocalDrainTimeout = 250 * time.Millisecond\n\t// localRingBlocks and localMinBlockSize size the receive ring of each socket: eight blocks\n\t// of at least 1 MiB, each larger than the snap length.\n\tlocalRingBlocks   = 8\n\tlocalMinBlockSize = 1 << 20\n\t// vlanHeaderLength is the length of the 802.1Q tag put back into frames whose tag the\n\t// kernel moved out of band.\n\tvlanHeaderLength = 4\n)\n\n// errReadTimeout is returned by a packet source that has no packet within the poll timeout.\nvar errReadTimeout = errors.New(\"no packet within the poll timeout\")\n\n// ExecFunc runs f in the network namespace of a node.\ntype ExecFunc func(ctx context.Context, f func(ns.NetNS) error) error\n\n// LocalTarget is one interface of a node on this machine (Docker or Podman) to capture.\ntype LocalTarget struct {\n\t// Node is the node name as the topology spells it.\n\tNode string\n\t// Interface is the interface name inside the node.\n\tInterface string\n\t// Exec runs a function in the node's network namespace.\n\tExec ExecFunc\n}\n\n// packetSource reads the packets of one interface.\ntype packetSource interface {\n\t// ReadPacket returns the next packet; the data is only valid until the next call. It\n\t// returns errReadTimeout when no packet arrived within the poll timeout.\n\tReadPacket() ([]byte, gopacket.CaptureInfo, error)\n\tClose()\n}\n\n// openSourcesFunc opens one packet source per interface in the network namespace exec enters.\ntype openSourcesFunc func(\n\tctx context.Context,\n\texec ExecFunc,\n\tinterfaces []string,\n\tsnapLength int,\n) ([]packetSource, error)\n\n// CaptureLocal streams pcapng from interfaces of nodes on this machine to w, with the same\n// output and end conditions as labruntime.PacketCapturer.Capture: one section, one Interface\n// Description Block per target named <node>:<interface>, then the packets of every target in\n// timestamp order. targets lists the interfaces of req.Targets, resolved, in the same order.\n//\n// Each interface is read through a packet socket opened in the node's network namespace, so\n// nothing runs in the node and the node image needs no capture tools; it needs CAP_NET_RAW and\n// the right to enter the namespace, so root. An interface that goes down is reopened once it is\n// up again; one that disappears (its node stopped or was recreated) is reattached when it is\n// back, and the time it was gone is reported as a gap through req.OnGap (or logged).\nfunc CaptureLocal(\n\tctx context.Context,\n\treq clablabruntime.CaptureRequest,\n\ttargets []LocalTarget,\n\tw io.Writer,\n) error {\n\treturn localCapture{\n\t\topen:           openPacketSockets,\n\t\twindow:         localReorderWindow,\n\t\treopenInterval: localReopenInterval,\n\t}.run(ctx, req, targets, w)\n}\n\n// localCapture is a local capture with its socket opener and timings, which tests replace.\ntype localCapture struct {\n\topen           openSourcesFunc\n\twindow         time.Duration\n\treopenInterval time.Duration\n}\n\nfunc (l localCapture) run(\n\tctx context.Context,\n\treq clablabruntime.CaptureRequest,\n\ttargets []LocalTarget,\n\tw io.Writer,\n) error {\n\tif err := ValidateRequest(&req); err != nil {\n\t\treturn err\n\t}\n\tif len(targets) != len(req.Targets) {\n\t\treturn fmt.Errorf(\"capture has %d resolved targets for %d requested ones\",\n\t\t\tlen(targets), len(req.Targets))\n\t}\n\n\tsources, err := l.openAll(ctx, targets, req.SnapLength)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnames := make([]string, len(targets))\n\tfor idx, target := range targets {\n\t\tnames[idx] = target.Node + \":\" + target.Interface\n\t}\n\n\tcaptureCtx, stop := context.WithCancel(ctx)\n\tdefer stop()\n\tif req.Duration > 0 {\n\t\tvar cancelTimeout context.CancelFunc\n\t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx, req.Duration)\n\t\tdefer cancelTimeout()\n\t}\n\n\tout, err := NewOutput(w, names, req.SnapLength, req.PacketLimit, l.window, stop)\n\tif err != nil {\n\t\tfor _, source := range sources {\n\t\t\tsource.Close()\n\t\t}\n\n\t\treturn err\n\t}\n\n\tvar wg sync.WaitGroup\n\tfor idx, source := range sources {\n\t\treader := &localReader{\n\t\t\tcapture: l,\n\t\t\tout:     out,\n\t\t\tid:      uint32(idx), //nolint:gosec // bounded by the targets\n\t\t\ttarget:  targets[idx],\n\t\t\tsnap:    req.SnapLength,\n\t\t\tonGap:   req.OnGap,\n\t\t}\n\t\twg.Go(func() {\n\t\t\treader.run(captureCtx, source)\n\t\t})\n\t}\n\twg.Wait()\n\n\treturn out.Close()\n}\n\n// openAll opens the sockets of every target before anything is written, one namespace entry\n// per node, so a capture that cannot start fails without output.\nfunc (l localCapture) openAll(\n\tctx context.Context,\n\ttargets []LocalTarget,\n\tsnapLength int,\n) ([]packetSource, error) {\n\ttype nodeTargets struct {\n\t\texec    ExecFunc\n\t\tindexes []int\n\t\tnames   []string\n\t}\n\tvar order []string\n\tbyNode := map[string]*nodeTargets{}\n\tfor idx, target := range targets {\n\t\tgroup := byNode[target.Node]\n\t\tif group == nil {\n\t\t\tgroup = &nodeTargets{exec: target.Exec}\n\t\t\tbyNode[target.Node] = group\n\t\t\torder = append(order, target.Node)\n\t\t}\n\t\tgroup.indexes = append(group.indexes, idx)\n\t\tgroup.names = append(group.names, target.Interface)\n\t}\n\n\tsources := make([]packetSource, len(targets))\n\tcloseAll := func() {\n\t\tfor _, source := range sources {\n\t\t\tif source != nil {\n\t\t\t\tsource.Close()\n\t\t\t}\n\t\t}\n\t}\n\tfor _, node := range order {\n\t\tgroup := byNode[node]\n\t\topened, err := l.open(ctx, group.exec, group.names, snapLength)\n\t\tif err != nil {\n\t\t\tcloseAll()\n\t\t\treturn nil, fmt.Errorf(\"failed to start the capture on node %q: %w\", node, err)\n\t\t}\n\t\tfor idx, source := range opened {\n\t\t\tsources[group.indexes[idx]] = source\n\t\t}\n\t}\n\n\treturn sources, nil\n}\n\n// localReader reads one interface into the merged stream.\ntype localReader struct {\n\tcapture localCapture\n\tout     *Output\n\tid      uint32\n\ttarget  LocalTarget\n\tsnap    int\n\tonGap   func(clablabruntime.CaptureGap)\n}\n\nfunc (r *localReader) run(ctx context.Context, source packetSource) {\n\tdefer func() {\n\t\tif source != nil {\n\t\t\tsource.Close()\n\t\t}\n\t}()\n\n\tfor {\n\t\tif ctx.Err() != nil {\n\t\t\tr.drain(source, time.Now())\n\t\t\treturn\n\t\t}\n\n\t\tdata, info, err := source.ReadPacket()\n\t\tif errors.Is(err, errReadTimeout) {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\t// The socket reports an error once its interface went down or was removed, and\n\t\t\t// keeps reporting it: it is reopened.\n\t\t\tlog.Debug(\"Capture socket failed, reopening it\", \"node\", r.target.Node,\n\t\t\t\t\"interface\", r.target.Interface, \"error\", err)\n\t\t\tsource.Close()\n\t\t\tsource = r.reopen(ctx)\n\t\t\tif source == nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// drain writes the packets that arrived before end but were still in the socket's ring: the\n// kernel hands over a ring block once it is full or its block timeout passed, so the last\n// packets before a capture ended may not have been read yet.\nfunc (r *localReader) drain(source packetSource, end time.Time) {\n\tdeadline := end.Add(localDrainTimeout)\n\tfor time.Now().Before(deadline) {\n\t\tdata, info, err := source.ReadPacket()\n\t\tif errors.Is(err, errReadTimeout) && time.Since(end) < localDrainQuiet {\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil || info.Timestamp.After(end) {\n\t\t\treturn\n\t\t}\n\t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// packet copies a packet out of the socket's ring, cut to the snap length.\nfunc (r *localReader) packet(data []byte, info gopacket.CaptureInfo) *Packet {\n\tlength := info.Length\n\tfor _, ancillary := range info.AncillaryData {\n\t\tif _, ok := ancillary.(afpacket.AncillaryVLAN); ok {\n\t\t\t// the tag was put back into the data and counts toward the frame length\n\t\t\tlength += vlanHeaderLength\n\t\t\tbreak\n\t\t}\n\t}\n\tlength = max(length, len(data))\n\n\tcaptured := make([]byte, min(len(data), r.snap))\n\tcopy(captured, data)\n\n\treturn &Packet{\n\t\tTimestamp:      info.Timestamp.UnixNano(),\n\t\tOriginalLength: uint32(length), //nolint:gosec // bounded by the interface MTU\n\t\tData:           captured,\n\t}\n}\n\n// reopen opens the interface's socket again once its node and interface are back. It returns\n// nil when the capture ended first. Time the interface could not be opened is reported as a gap;\n// an interface that only went down is not, as it has no traffic while down.\nfunc (r *localReader) reopen(ctx context.Context) packetSource {\n\tfrom := time.Now()\n\tvar unavailable error\n\n\ttimer := time.NewTimer(r.capture.reopenInterval)\n\tdefer timer.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tif unavailable != nil {\n\t\t\t\tr.reportGap(from, time.Time{}, unavailable)\n\t\t\t}\n\n\t\t\treturn nil\n\t\tcase <-timer.C:\n\t\t}\n\n\t\topened, err := r.capture.open(ctx, r.target.Exec, []string{r.target.Interface}, r.snap)\n\t\tif err != nil {\n\t\t\tif unavailable == nil {\n\t\t\t\tlog.Debug(\"Capture interface is not available, waiting for it\",\n\t\t\t\t\t\"node\", r.target.Node, \"interface\", r.target.Interface, \"error\", err)\n\t\t\t}\n\t\t\tunavailable = err\n\t\t\tresetTimer(timer, r.capture.reopenInterval)\n\n\t\t\tcontinue\n\t\t}\n\t\tif unavailable != nil {\n\t\t\tr.reportGap(from, time.Now(), unavailable)\n\t\t}\n\n\t\treturn opened[0]\n\t}\n}\n\nfunc (r *localReader) reportGap(from, to time.Time, cause error) {\n\tReportGap(r.onGap, clablabruntime.CaptureGap{\n\t\tNode:       r.target.Node,\n\t\tInterfaces: []string{r.target.Interface},\n\t\tFrom:       from,\n\t\tTo:         to,\n\t\tReason:     fmt.Sprintf(\"the interface was not available: %v\", cause),\n\t})\n}\n\n// openPacketSockets opens one packet socket per interface in the namespace exec enters. A socket\n// stays bound to its interface after the thread left the namespace.\nfunc openPacketSockets(\n\tctx context.Context,\n\texec ExecFunc,\n\tinterfaces []string,\n\tsnapLength int,\n) ([]packetSource, error) {\n\tsources := make([]packetSource, 0, len(interfaces))\n\terr := exec(ctx, func(ns.NetNS) error {\n\t\tfor _, name := range interfaces {\n\t\t\tsource, err := openPacketSocket(name, snapLength)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"interface %q: %w\", name, err)\n\t\t\t}\n\t\t\tsources = append(sources, source)\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tfor _, source := range sources {\n\t\t\tsource.Close()\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn sources, nil\n}\n\n// afpacketSource is a TPACKET_V3 receive ring on one interface.\ntype afpacketSource struct {\n\thandle *afpacket.TPacket\n}\n\nfunc openPacketSocket(name string, snapLength int) (*afpacketSource, error) {\n\t// A TPACKET_V3 block holds whole frames: it must be larger than the snap length, plus the\n\t// block and frame headers, and a multiple of the page size.\n\tpageSize := os.Getpagesize()\n\tblockSize := max(localMinBlockSize, snapLength+pageSize)\n\tblockSize = (blockSize + pageSize - 1) / pageSize * pageSize\n\n\thandle, err := afpacket.NewTPacket(\n\t\tafpacket.OptInterface(name),\n\t\tafpacket.OptTPacketVersion(afpacket.TPacketVersion3),\n\t\tafpacket.OptFrameSize(blockSize),\n\t\tafpacket.OptBlockSize(blockSize),\n\t\tafpacket.OptNumBlocks(localRingBlocks),\n\t\tafpacket.OptBlockTimeout(localBlockTimeout),\n\t\tafpacket.OptPollTimeout(localPollTimeout),\n\t\t// the kernel moves 802.1Q tags out of the frame; captures show them in place\n\t\tafpacket.OptAddVLANHeader(true),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// promiscuous mode is a membership of this socket and ends with it\n\tif err := handle.SetPromiscuous(true); err != nil {\n\t\thandle.Close()\n\t\treturn nil, fmt.Errorf(\"failed to enable promiscuous mode: %w\", err)\n\t}\n\n\treturn &afpacketSource{handle: handle}, nil\n}\n\nfunc (s *afpacketSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {\n\tdata, info, err := s.handle.ZeroCopyReadPacketData()\n\tif errors.Is(err, afpacket.ErrTimeout) {\n\t\treturn nil, info, errReadTimeout\n\t}\n\n\treturn data, info, err\n}\n\nfunc (s *afpacketSource) Close() {\n\ts.handle.Close()\n}",
        "lineStart": 1,
        "lineEnd": 430,
        "totalLines": 430,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523381896,
      "end": 1793523381904
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19652f6930016vulbZD23L7s8Y",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19652d2df0012coQNQ8TBiw02W",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 62932,
    "input": 4553,
    "output": 40,
    "reasoning": 739,
    "cache": {
      "read": 57600,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19652d2df0012coQNQ8TBiw02W",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523372767,
    "completed": 1793523381910
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 62932,
    "input": 4553,
    "output": 40,
    "reasoning": 739,
    "cache": {
      "read": 57600,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 33
step-start
{
  "type": "step-start",
  "id": "prt_1965304ee001GNu17N0hNvTk7s",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19652f69d001xsI2OBDEJpPxOR"
}
Reasoning
Verification of local.go concerns:

1. **`openAll` count assumption**: `opened` from `l.open` — openPacketSockets returns exactly len(interfaces) sources on success (appends per interface, and error aborts). So `sources[group.indexes[idx]]` is safe. In tests, `open` is a stub — fine.

2. **`drain` deadline**: `deadline := end.Add(localDrainTimeout)` — end is `time.Now()` at ctx check. Loop condition `time.Now().Before(deadline)`. Inside, `errReadTimeout && time.Since(end) < localDrainQuiet` → continue. Once beyond quiet, errReadTimeout → falls to `if err != nil` → return. Wait: errReadTimeout is an err — `if err != nil || info.Timestamp.After(end)` → return. So after quiet period, drain returns. Good.

Note: `drain` is called with `time.Now()` — but the ctx check happens at loop top; packets read before... fine.

3. **`drain` after packet limit stop**: Emit returns !more → return. OK.

4. **`run` after `reopen` returns nil (ctx done)**: returns. OK.

5. **`reopen` blocks on timer only — checks ctx.Done only every reopenInterval (200ms). Acceptable.

6. **`r.reopen(ctx)` uses `r.capture.open` with ctx — openPacketSockets with a canceled ctx: exec(ctx...) → ns.WithNetNS? presumably fails fast or blocks until ctx... Actually `node.ExecFunction` wraps ns.WithNetNS which doesn't take ctx? ExecFunc signature is `func(ctx context.Context, f func(ns.NetNS) error) error` — hmm, if the underlying exec ignores ctx, reopening in a loop every 200ms until ctx done. Fine.

7. **CaptureInfo.Timestamp**: afpacket ZeroCopyReadPacketData returns the kernel timestamp. Good.

8. **`packet()` length**: `length = info.Length` (original wire length, without the moved-out VLAN tag) + 4 per ancillary VLAN. But if OptAddVLANHeader is on, does `len(data)` include the reinserted tag and info.Length not? They handle that. OK.

Now pcapng.go — let me verify the Reader.Next clean-EOF concern and Writer. Let me read pcapng.go fully.
Now the pcapng codec:
read · completed

Input

{
  "filePath": "/source/head/capture/pcapng.go"
}

Output

<path>/source/head/capture/pcapng.go</path>
<type>file</type>
<content>
1: // Package capture writes the pcapng streams of `containerlab capture`: one section with one
2: // interface per capture target, packets merged across targets in timestamp order. The local
3: // capturer reads lab link interfaces of Docker and Podman nodes through packet sockets; the c9s
4: // lab runtime feeds the same writer from clabwire streams.
5: package capture
6: 
7: import (
8: 	"bufio"
9: 	"encoding/binary"
10: 	"errors"
11: 	"fmt"
12: 	"io"
13: 	"math"
14: 	"sync"
15: )
16: 
17: // pcapng block layout (https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html). clabwire
18: // writes little-endian sections, and so does the merged stream containerlab writes.
19: const (
20: 	pcapngSectionHeaderType  = 0x0a0d0d0a
21: 	pcapngInterfaceType      = 0x00000001
22: 	pcapngEnhancedPacketType = 0x00000006
23: 	pcapngByteOrderMagic     = 0x1a2b3c4d
24: 	pcapngOptionEnd          = 0
25: 	pcapngOptionUserAppl     = 4
26: 	pcapngOptionIfName       = 2
27: 	pcapngOptionIfTSResol    = 9
28: 	pcapngLinkTypeEthernet   = 1
29: 	// pcapngNanoseconds is the if_tsresol value for 10^-9 s resolution.
30: 	pcapngNanoseconds = 9
31: 	// pcapngMaxBlockLength bounds a block read from a capture stream: a packet of the largest
32: 	// clabwire snap length (1 MiB) plus framing.
33: 	pcapngMaxBlockLength = 1<<20 + 1024
34: 	// captureUserApplication names the writer in the merged section header.
35: 	captureUserApplication = "containerlab"
36: )
37: 
38: var errPCAPNGByteOrder = errors.New("pcapng section is not little-endian")
39: 
40: // InterfaceDescription is an Interface Description Block.
41: type InterfaceDescription struct {
42: 	LinkType   uint16
43: 	SnapLength uint32
44: 	Name       string
45: 	// TSResol is the raw if_tsresol value; 6 (microseconds) when the block has none.
46: 	TSResol byte
47: }
48: 
49: // Packet is an Enhanced Packet Block with its timestamp in nanoseconds.
50: type Packet struct {
51: 	InterfaceID    uint32
52: 	Timestamp      int64
53: 	OriginalLength uint32
54: 	Data           []byte
55: }
56: 
57: // Reader reads the blocks of a pcapng stream as clabwire writes it: one or more
58: // little-endian sections, each with its Interface Description Blocks before its packets.
59: type Reader struct {
60: 	r          *bufio.Reader
61: 	interfaces []InterfaceDescription
62: 	// sections counts the Section Header Blocks read so far.
63: 	sections int
64: }
65: 
66: // NewReader returns a reader of the pcapng stream r.
67: func NewReader(r io.Reader) *Reader {
68: 	return &Reader{r: bufio.NewReaderSize(r, 64<<10)}
69: }
70: 
71: // Sections returns the number of Section Header Blocks read so far.
72: func (p *Reader) Sections() int {
73: 	return p.sections
74: }
75: 
76: // Event is one block of interest: a new interface or a packet.
77: type Event struct {
78: 	Interface *InterfaceDescription
79: 	Packet    *Packet
80: }
81: 
82: // Next returns the next interface or packet, skipping other block types. It returns io.EOF at
83: // the clean end of the stream, and io.ErrUnexpectedEOF for a stream cut inside a block.
84: func (p *Reader) Next() (Event, error) {
85: 	for {
86: 		var header [8]byte
87: 		if _, err := io.ReadFull(p.r, header[:]); err != nil {
88: 			if errors.Is(err, io.EOF) {
89: 				return Event{}, io.EOF
90: 			}
91: 
92: 			return Event{}, io.ErrUnexpectedEOF
93: 		}
94: 
95: 		blockType := binary.LittleEndian.Uint32(header[0:4])
96: 		length := binary.LittleEndian.Uint32(header[4:8])
97: 		if blockType == pcapngSectionHeaderType {
98: 			// the byte-order magic tells a big-endian section apart before its length is
99: 			// trusted: that length reads byte swapped
100: 			magic, err := p.r.Peek(4)
101: 			if err != nil {
102: 				return Event{}, io.ErrUnexpectedEOF
103: 			}
104: 			if binary.BigEndian.Uint32(magic) == pcapngByteOrderMagic {
105: 				return Event{}, errPCAPNGByteOrder
106: 			}
107: 		}
108: 		if length < 12 || length%4 != 0 || length > pcapngMaxBlockLength {
109: 			return Event{}, fmt.Errorf("invalid pcapng block length %d (at most %d)", length,
110: 				pcapngMaxBlockLength)
111: 		}
112: 
113: 		body := make([]byte, length-8)
114: 		if _, err := io.ReadFull(p.r, body); err != nil {
115: 			return Event{}, io.ErrUnexpectedEOF
116: 		}
117: 		if binary.LittleEndian.Uint32(body[len(body)-4:]) != length {
118: 			return Event{}, fmt.Errorf("pcapng block lengths do not match")
119: 		}
120: 		body = body[:len(body)-4]
121: 
122: 		switch blockType {
123: 		case pcapngSectionHeaderType:
124: 			if len(body) < 16 {
125: 				return Event{}, fmt.Errorf("short pcapng section header")
126: 			}
127: 			if binary.LittleEndian.Uint32(body[0:4]) != pcapngByteOrderMagic {
128: 				return Event{}, errPCAPNGByteOrder
129: 			}
130: 			p.sections++
131: 			p.interfaces = nil
132: 		case pcapngInterfaceType:
133: 			if p.sections == 0 {
134: 				return Event{}, fmt.Errorf("pcapng interface before a section header")
135: 			}
136: 			intf, err := parsePCAPNGInterface(body)
137: 			if err != nil {
138: 				return Event{}, err
139: 			}
140: 			p.interfaces = append(p.interfaces, intf)
141: 
142: 			return Event{Interface: &p.interfaces[len(p.interfaces)-1]}, nil
143: 		case pcapngEnhancedPacketType:
144: 			packet, err := p.parsePacket(body)
145: 			if err != nil {
146: 				return Event{}, err
147: 			}
148: 
149: 			return Event{Packet: &packet}, nil
150: 		}
151: 	}
152: }
153: 
154: func parsePCAPNGInterface(body []byte) (InterfaceDescription, error) {
155: 	if len(body) < 8 {
156: 		return InterfaceDescription{}, fmt.Errorf("short pcapng interface description")
157: 	}
158: 	intf := InterfaceDescription{
159: 		LinkType:   binary.LittleEndian.Uint16(body[0:2]),
160: 		SnapLength: binary.LittleEndian.Uint32(body[4:8]),
161: 		TSResol:    6,
162: 	}
163: 
164: 	options := body[8:]
165: 	for len(options) >= 4 {
166: 		code := binary.LittleEndian.Uint16(options[0:2])
167: 		size := int(binary.LittleEndian.Uint16(options[2:4]))
168: 		if code == pcapngOptionEnd {
169: 			break
170: 		}
171: 		padded := size + pcapngPadding(size)
172: 		if 4+padded > len(options) {
173: 			return InterfaceDescription{}, fmt.Errorf("truncated pcapng interface option")
174: 		}
175: 		value := options[4 : 4+size]
176: 		switch code {
177: 		case pcapngOptionIfName:
178: 			intf.Name = string(value)
179: 		case pcapngOptionIfTSResol:
180: 			if size == 1 {
181: 				intf.TSResol = value[0]
182: 			}
183: 		}
184: 		options = options[4+padded:]
185: 	}
186: 
187: 	return intf, nil
188: }
189: 
190: func (p *Reader) parsePacket(body []byte) (Packet, error) {
191: 	if len(body) < 20 {
192: 		return Packet{}, fmt.Errorf("short pcapng enhanced packet")
193: 	}
194: 	packet := Packet{
195: 		InterfaceID:    binary.LittleEndian.Uint32(body[0:4]),
196: 		OriginalLength: binary.LittleEndian.Uint32(body[16:20]),
197: 	}
198: 	if int(packet.InterfaceID) >= len(p.interfaces) {
199: 		return Packet{}, fmt.Errorf("pcapng packet for undeclared interface %d",
200: 			packet.InterfaceID)
201: 	}
202: 	captured := binary.LittleEndian.Uint32(body[12:16])
203: 	if int(captured) > len(body)-20 {
204: 		return Packet{}, fmt.Errorf("pcapng packet data exceeds its block")
205: 	}
206: 	packet.Data = body[20 : 20+captured]
207: 
208: 	raw := uint64(binary.LittleEndian.Uint32(body[4:8]))<<32 |
209: 		uint64(binary.LittleEndian.Uint32(body[8:12]))
210: 	timestamp, err := pcapngNanosecondsFrom(raw, p.interfaces[packet.InterfaceID].TSResol)
211: 	if err != nil {
212: 		return Packet{}, err
213: 	}
214: 	packet.Timestamp = timestamp
215: 
216: 	return packet, nil
217: }
218: 
219: // pcapngNanosecondsFrom converts a timestamp in an interface's resolution to nanoseconds.
220: // Only decimal resolutions up to nanoseconds occur in clabwire streams.
221: func pcapngNanosecondsFrom(raw uint64, tsresol byte) (int64, error) {
222: 	if tsresol&0x80 != 0 || tsresol > pcapngNanoseconds {
223: 		return 0, fmt.Errorf("unsupported pcapng timestamp resolution %#x", tsresol)
224: 	}
225: 	scale := uint64(1)
226: 	for range pcapngNanoseconds - int(tsresol) {
227: 		scale *= 10
228: 	}
229: 	if raw > math.MaxInt64/scale {
230: 		return 0, fmt.Errorf("pcapng timestamp out of range")
231: 	}
232: 
233: 	return int64(raw * scale), nil //nolint:gosec // bounded above
234: }
235: 
236: // Writer writes one little-endian section with nanosecond timestamps. Every block goes out
237: // in one Write under a lock, so concurrent writers never interleave blocks and a stream cut
238: // between writes is still a valid capture.
239: type Writer struct {
240: 	mu  sync.Mutex
241: 	w   io.Writer
242: 	err error
243: }
244: 
245: // NewWriter returns a writer of one pcapng section to w.
246: func NewWriter(w io.Writer) *Writer {
247: 	return &Writer{w: w}
248: }
249: 
250: // WriteHeader writes the Section Header Block and one Interface Description Block per name, in
251: // order; packets refer to the interfaces by that index.
252: func (p *Writer) WriteHeader(names []string, snapLength uint32) error {
253: 	section := make([]byte, 16)
254: 	binary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)
255: 	binary.LittleEndian.PutUint16(section[4:], 1)
256: 	binary.LittleEndian.PutUint16(section[6:], 0)
257: 	binary.LittleEndian.PutUint64(section[8:], math.MaxUint64)
258: 	section = appendPCAPNGOption(section, pcapngOptionUserAppl, []byte(captureUserApplication))
259: 	section = appendPCAPNGOption(section, pcapngOptionEnd, nil)
260: 
261: 	header := pcapngBlock(pcapngSectionHeaderType, section)
262: 	for _, name := range names {
263: 		description := make([]byte, 8)
264: 		binary.LittleEndian.PutUint16(description[0:], pcapngLinkTypeEthernet)
265: 		binary.LittleEndian.PutUint32(description[4:], snapLength)
266: 		description = appendPCAPNGOption(description, pcapngOptionIfName, []byte(name))
267: 		description = appendPCAPNGOption(description, pcapngOptionIfTSResol,
268: 			[]byte{pcapngNanoseconds})
269: 		description = appendPCAPNGOption(description, pcapngOptionEnd, nil)
270: 		header = append(header, pcapngBlock(pcapngInterfaceType, description)...)
271: 	}
272: 
273: 	return p.write(header)
274: }
275: 
276: // WritePacket writes an Enhanced Packet Block for the interface with the given index.
277: func (p *Writer) WritePacket(interfaceID uint32, packet *Packet) error {
278: 	timestamp := uint64(packet.Timestamp) //nolint:gosec // capture timestamps are positive
279: 	body := make([]byte, 20, 20+len(packet.Data)+3)
280: 	binary.LittleEndian.PutUint32(body[0:], interfaceID)
281: 	binary.LittleEndian.PutUint32(body[4:], uint32(timestamp>>32))
282: 	binary.LittleEndian.PutUint32(body[8:], uint32(timestamp)) //nolint:gosec // low 32 bits
283: 	binary.LittleEndian.PutUint32(body[12:], uint32(len(packet.Data)))
284: 	binary.LittleEndian.PutUint32(body[16:], packet.OriginalLength)
285: 	body = append(body, packet.Data...)
286: 	body = append(body, make([]byte, pcapngPadding(len(packet.Data)))...)
287: 
288: 	return p.write(pcapngBlock(pcapngEnhancedPacketType, body))
289: }
290: 
291: // Err returns the first write error, or nil.
292: func (p *Writer) Err() error {
293: 	p.mu.Lock()
294: 	defer p.mu.Unlock()
295: 
296: 	return p.err
297: }
298: 
299: func (p *Writer) write(block []byte) error {
300: 	p.mu.Lock()
301: 	defer p.mu.Unlock()
302: 
303: 	if p.err != nil {
304: 		return p.err
305: 	}
306: 	if _, err := p.w.Write(block); err != nil {
307: 		p.err = fmt.Errorf("failed to write the capture: %w", err)
308: 	}
309: 
310: 	return p.err
311: }
312: 
313: func pcapngBlock(blockType uint32, body []byte) []byte {
314: 	total := uint32(12 + len(body)) //nolint:gosec // bounded by the snap length
315: 	block := make([]byte, 8, total)
316: 	binary.LittleEndian.PutUint32(block[0:], blockType)
317: 	binary.LittleEndian.PutUint32(block[4:], total)
318: 	block = append(block, body...)
319: 
320: 	return binary.LittleEndian.AppendUint32(block, total)
321: }
322: 
323: func appendPCAPNGOption(body []byte, code uint16, value []byte) []byte {
324: 	body = binary.LittleEndian.AppendUint16(body, code)
325: 	body = binary.LittleEndian.AppendUint16(body, uint16(len(value))) //nolint:gosec // short
326: 	body = append(body, value...)
327: 
328: 	return append(body, make([]byte, pcapngPadding(len(value)))...)
329: }
330: 
331: func pcapngPadding(length int) int {
332: 	return (4 - length%4) % 4
333: }

(End of file - total 333 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196531183001Q2g2JjKyl15veE",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19652f69d001xsI2OBDEJpPxOR",
  "callID": "call_2c1c9ccb6dbe4a93a8949b41",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/capture/pcapng.go"
    },
    "output": "<path>/source/head/capture/pcapng.go</path>\n<type>file</type>\n<content>\n1: // Package capture writes the pcapng streams of `containerlab capture`: one section with one\n2: // interface per capture target, packets merged across targets in timestamp order. The local\n3: // capturer reads lab link interfaces of Docker and Podman nodes through packet sockets; the c9s\n4: // lab runtime feeds the same writer from clabwire streams.\n5: package capture\n6: \n7: import (\n8: \t\"bufio\"\n9: \t\"encoding/binary\"\n10: \t\"errors\"\n11: \t\"fmt\"\n12: \t\"io\"\n13: \t\"math\"\n14: \t\"sync\"\n15: )\n16: \n17: // pcapng block layout (https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html). clabwire\n18: // writes little-endian sections, and so does the merged stream containerlab writes.\n19: const (\n20: \tpcapngSectionHeaderType  = 0x0a0d0d0a\n21: \tpcapngInterfaceType      = 0x00000001\n22: \tpcapngEnhancedPacketType = 0x00000006\n23: \tpcapngByteOrderMagic     = 0x1a2b3c4d\n24: \tpcapngOptionEnd          = 0\n25: \tpcapngOptionUserAppl     = 4\n26: \tpcapngOptionIfName       = 2\n27: \tpcapngOptionIfTSResol    = 9\n28: \tpcapngLinkTypeEthernet   = 1\n29: \t// pcapngNanoseconds is the if_tsresol value for 10^-9 s resolution.\n30: \tpcapngNanoseconds = 9\n31: \t// pcapngMaxBlockLength bounds a block read from a capture stream: a packet of the largest\n32: \t// clabwire snap length (1 MiB) plus framing.\n33: \tpcapngMaxBlockLength = 1<<20 + 1024\n34: \t// captureUserApplication names the writer in the merged section header.\n35: \tcaptureUserApplication = \"containerlab\"\n36: )\n37: \n38: var errPCAPNGByteOrder = errors.New(\"pcapng section is not little-endian\")\n39: \n40: // InterfaceDescription is an Interface Description Block.\n41: type InterfaceDescription struct {\n42: \tLinkType   uint16\n43: \tSnapLength uint32\n44: \tName       string\n45: \t// TSResol is the raw if_tsresol value; 6 (microseconds) when the block has none.\n46: \tTSResol byte\n47: }\n48: \n49: // Packet is an Enhanced Packet Block with its timestamp in nanoseconds.\n50: type Packet struct {\n51: \tInterfaceID    uint32\n52: \tTimestamp      int64\n53: \tOriginalLength uint32\n54: \tData           []byte\n55: }\n56: \n57: // Reader reads the blocks of a pcapng stream as clabwire writes it: one or more\n58: // little-endian sections, each with its Interface Description Blocks before its packets.\n59: type Reader struct {\n60: \tr          *bufio.Reader\n61: \tinterfaces []InterfaceDescription\n62: \t// sections counts the Section Header Blocks read so far.\n63: \tsections int\n64: }\n65: \n66: // NewReader returns a reader of the pcapng stream r.\n67: func NewReader(r io.Reader) *Reader {\n68: \treturn &Reader{r: bufio.NewReaderSize(r, 64<<10)}\n69: }\n70: \n71: // Sections returns the number of Section Header Blocks read so far.\n72: func (p *Reader) Sections() int {\n73: \treturn p.sections\n74: }\n75: \n76: // Event is one block of interest: a new interface or a packet.\n77: type Event struct {\n78: \tInterface *InterfaceDescription\n79: \tPacket    *Packet\n80: }\n81: \n82: // Next returns the next interface or packet, skipping other block types. It returns io.EOF at\n83: // the clean end of the stream, and io.ErrUnexpectedEOF for a stream cut inside a block.\n84: func (p *Reader) Next() (Event, error) {\n85: \tfor {\n86: \t\tvar header [8]byte\n87: \t\tif _, err := io.ReadFull(p.r, header[:]); err != nil {\n88: \t\t\tif errors.Is(err, io.EOF) {\n89: \t\t\t\treturn Event{}, io.EOF\n90: \t\t\t}\n91: \n92: \t\t\treturn Event{}, io.ErrUnexpectedEOF\n93: \t\t}\n94: \n95: \t\tblockType := binary.LittleEndian.Uint32(header[0:4])\n96: \t\tlength := binary.LittleEndian.Uint32(header[4:8])\n97: \t\tif blockType == pcapngSectionHeaderType {\n98: \t\t\t// the byte-order magic tells a big-endian section apart before its length is\n99: \t\t\t// trusted: that length reads byte swapped\n100: \t\t\tmagic, err := p.r.Peek(4)\n101: \t\t\tif err != nil {\n102: \t\t\t\treturn Event{}, io.ErrUnexpectedEOF\n103: \t\t\t}\n104: \t\t\tif binary.BigEndian.Uint32(magic) == pcapngByteOrderMagic {\n105: \t\t\t\treturn Event{}, errPCAPNGByteOrder\n106: \t\t\t}\n107: \t\t}\n108: \t\tif length < 12 || length%4 != 0 || length > pcapngMaxBlockLength {\n109: \t\t\treturn Event{}, fmt.Errorf(\"invalid pcapng block length %d (at most %d)\", length,\n110: \t\t\t\tpcapngMaxBlockLength)\n111: \t\t}\n112: \n113: \t\tbody := make([]byte, length-8)\n114: \t\tif _, err := io.ReadFull(p.r, body); err != nil {\n115: \t\t\treturn Event{}, io.ErrUnexpectedEOF\n116: \t\t}\n117: \t\tif binary.LittleEndian.Uint32(body[len(body)-4:]) != length {\n118: \t\t\treturn Event{}, fmt.Errorf(\"pcapng block lengths do not match\")\n119: \t\t}\n120: \t\tbody = body[:len(body)-4]\n121: \n122: \t\tswitch blockType {\n123: \t\tcase pcapngSectionHeaderType:\n124: \t\t\tif len(body) < 16 {\n125: \t\t\t\treturn Event{}, fmt.Errorf(\"short pcapng section header\")\n126: \t\t\t}\n127: \t\t\tif binary.LittleEndian.Uint32(body[0:4]) != pcapngByteOrderMagic {\n128: \t\t\t\treturn Event{}, errPCAPNGByteOrder\n129: \t\t\t}\n130: \t\t\tp.sections++\n131: \t\t\tp.interfaces = nil\n132: \t\tcase pcapngInterfaceType:\n133: \t\t\tif p.sections == 0 {\n134: \t\t\t\treturn Event{}, fmt.Errorf(\"pcapng interface before a section header\")\n135: \t\t\t}\n136: \t\t\tintf, err := parsePCAPNGInterface(body)\n137: \t\t\tif err != nil {\n138: \t\t\t\treturn Event{}, err\n139: \t\t\t}\n140: \t\t\tp.interfaces = append(p.interfaces, intf)\n141: \n142: \t\t\treturn Event{Interface: &p.interfaces[len(p.interfaces)-1]}, nil\n143: \t\tcase pcapngEnhancedPacketType:\n144: \t\t\tpacket, err := p.parsePacket(body)\n145: \t\t\tif err != nil {\n146: \t\t\t\treturn Event{}, err\n147: \t\t\t}\n148: \n149: \t\t\treturn Event{Packet: &packet}, nil\n150: \t\t}\n151: \t}\n152: }\n153: \n154: func parsePCAPNGInterface(body []byte) (InterfaceDescription, error) {\n155: \tif len(body) < 8 {\n156: \t\treturn InterfaceDescription{}, fmt.Errorf(\"short pcapng interface description\")\n157: \t}\n158: \tintf := InterfaceDescription{\n159: \t\tLinkType:   binary.LittleEndian.Uint16(body[0:2]),\n160: \t\tSnapLength: binary.LittleEndian.Uint32(body[4:8]),\n161: \t\tTSResol:    6,\n162: \t}\n163: \n164: \toptions := body[8:]\n165: \tfor len(options) >= 4 {\n166: \t\tcode := binary.LittleEndian.Uint16(options[0:2])\n167: \t\tsize := int(binary.LittleEndian.Uint16(options[2:4]))\n168: \t\tif code == pcapngOptionEnd {\n169: \t\t\tbreak\n170: \t\t}\n171: \t\tpadded := size + pcapngPadding(size)\n172: \t\tif 4+padded > len(options) {\n173: \t\t\treturn InterfaceDescription{}, fmt.Errorf(\"truncated pcapng interface option\")\n174: \t\t}\n175: \t\tvalue := options[4 : 4+size]\n176: \t\tswitch code {\n177: \t\tcase pcapngOptionIfName:\n178: \t\t\tintf.Name = string(value)\n179: \t\tcase pcapngOptionIfTSResol:\n180: \t\t\tif size == 1 {\n181: \t\t\t\tintf.TSResol = value[0]\n182: \t\t\t}\n183: \t\t}\n184: \t\toptions = options[4+padded:]\n185: \t}\n186: \n187: \treturn intf, nil\n188: }\n189: \n190: func (p *Reader) parsePacket(body []byte) (Packet, error) {\n191: \tif len(body) < 20 {\n192: \t\treturn Packet{}, fmt.Errorf(\"short pcapng enhanced packet\")\n193: \t}\n194: \tpacket := Packet{\n195: \t\tInterfaceID:    binary.LittleEndian.Uint32(body[0:4]),\n196: \t\tOriginalLength: binary.LittleEndian.Uint32(body[16:20]),\n197: \t}\n198: \tif int(packet.InterfaceID) >= len(p.interfaces) {\n199: \t\treturn Packet{}, fmt.Errorf(\"pcapng packet for undeclared interface %d\",\n200: \t\t\tpacket.InterfaceID)\n201: \t}\n202: \tcaptured := binary.LittleEndian.Uint32(body[12:16])\n203: \tif int(captured) > len(body)-20 {\n204: \t\treturn Packet{}, fmt.Errorf(\"pcapng packet data exceeds its block\")\n205: \t}\n206: \tpacket.Data = body[20 : 20+captured]\n207: \n208: \traw := uint64(binary.LittleEndian.Uint32(body[4:8]))<<32 |\n209: \t\tuint64(binary.LittleEndian.Uint32(body[8:12]))\n210: \ttimestamp, err := pcapngNanosecondsFrom(raw, p.interfaces[packet.InterfaceID].TSResol)\n211: \tif err != nil {\n212: \t\treturn Packet{}, err\n213: \t}\n214: \tpacket.Timestamp = timestamp\n215: \n216: \treturn packet, nil\n217: }\n218: \n219: // pcapngNanosecondsFrom converts a timestamp in an interface's resolution to nanoseconds.\n220: // Only decimal resolutions up to nanoseconds occur in clabwire streams.\n221: func pcapngNanosecondsFrom(raw uint64, tsresol byte) (int64, error) {\n222: \tif tsresol&0x80 != 0 || tsresol > pcapngNanoseconds {\n223: \t\treturn 0, fmt.Errorf(\"unsupported pcapng timestamp resolution %#x\", tsresol)\n224: \t}\n225: \tscale := uint64(1)\n226: \tfor range pcapngNanoseconds - int(tsresol) {\n227: \t\tscale *= 10\n228: \t}\n229: \tif raw > math.MaxInt64/scale {\n230: \t\treturn 0, fmt.Errorf(\"pcapng timestamp out of range\")\n231: \t}\n232: \n233: \treturn int64(raw * scale), nil //nolint:gosec // bounded above\n234: }\n235: \n236: // Writer writes one little-endian section with nanosecond timestamps. Every block goes out\n237: // in one Write under a lock, so concurrent writers never interleave blocks and a stream cut\n238: // between writes is still a valid capture.\n239: type Writer struct {\n240: \tmu  sync.Mutex\n241: \tw   io.Writer\n242: \terr error\n243: }\n244: \n245: // NewWriter returns a writer of one pcapng section to w.\n246: func NewWriter(w io.Writer) *Writer {\n247: \treturn &Writer{w: w}\n248: }\n249: \n250: // WriteHeader writes the Section Header Block and one Interface Description Block per name, in\n251: // order; packets refer to the interfaces by that index.\n252: func (p *Writer) WriteHeader(names []string, snapLength uint32) error {\n253: \tsection := make([]byte, 16)\n254: \tbinary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)\n255: \tbinary.LittleEndian.PutUint16(section[4:], 1)\n256: \tbinary.LittleEndian.PutUint16(section[6:], 0)\n257: \tbinary.LittleEndian.PutUint64(section[8:], math.MaxUint64)\n258: \tsection = appendPCAPNGOption(section, pcapngOptionUserAppl, []byte(captureUserApplication))\n259: \tsection = appendPCAPNGOption(section, pcapngOptionEnd, nil)\n260: \n261: \theader := pcapngBlock(pcapngSectionHeaderType, section)\n262: \tfor _, name := range names {\n263: \t\tdescription := make([]byte, 8)\n264: \t\tbinary.LittleEndian.PutUint16(description[0:], pcapngLinkTypeEthernet)\n265: \t\tbinary.LittleEndian.PutUint32(description[4:], snapLength)\n266: \t\tdescription = appendPCAPNGOption(description, pcapngOptionIfName, []byte(name))\n267: \t\tdescription = appendPCAPNGOption(description, pcapngOptionIfTSResol,\n268: \t\t\t[]byte{pcapngNanoseconds})\n269: \t\tdescription = appendPCAPNGOption(description, pcapngOptionEnd, nil)\n270: \t\theader = append(header, pcapngBlock(pcapngInterfaceType, description)...)\n271: \t}\n272: \n273: \treturn p.write(header)\n274: }\n275: \n276: // WritePacket writes an Enhanced Packet Block for the interface with the given index.\n277: func (p *Writer) WritePacket(interfaceID uint32, packet *Packet) error {\n278: \ttimestamp := uint64(packet.Timestamp) //nolint:gosec // capture timestamps are positive\n279: \tbody := make([]byte, 20, 20+len(packet.Data)+3)\n280: \tbinary.LittleEndian.PutUint32(body[0:], interfaceID)\n281: \tbinary.LittleEndian.PutUint32(body[4:], uint32(timestamp>>32))\n282: \tbinary.LittleEndian.PutUint32(body[8:], uint32(timestamp)) //nolint:gosec // low 32 bits\n283: \tbinary.LittleEndian.PutUint32(body[12:], uint32(len(packet.Data)))\n284: \tbinary.LittleEndian.PutUint32(body[16:], packet.OriginalLength)\n285: \tbody = append(body, packet.Data...)\n286: \tbody = append(body, make([]byte, pcapngPadding(len(packet.Data)))...)\n287: \n288: \treturn p.write(pcapngBlock(pcapngEnhancedPacketType, body))\n289: }\n290: \n291: // Err returns the first write error, or nil.\n292: func (p *Writer) Err() error {\n293: \tp.mu.Lock()\n294: \tdefer p.mu.Unlock()\n295: \n296: \treturn p.err\n297: }\n298: \n299: func (p *Writer) write(block []byte) error {\n300: \tp.mu.Lock()\n301: \tdefer p.mu.Unlock()\n302: \n303: \tif p.err != nil {\n304: \t\treturn p.err\n305: \t}\n306: \tif _, err := p.w.Write(block); err != nil {\n307: \t\tp.err = fmt.Errorf(\"failed to write the capture: %w\", err)\n308: \t}\n309: \n310: \treturn p.err\n311: }\n312: \n313: func pcapngBlock(blockType uint32, body []byte) []byte {\n314: \ttotal := uint32(12 + len(body)) //nolint:gosec // bounded by the snap length\n315: \tblock := make([]byte, 8, total)\n316: \tbinary.LittleEndian.PutUint32(block[0:], blockType)\n317: \tbinary.LittleEndian.PutUint32(block[4:], total)\n318: \tblock = append(block, body...)\n319: \n320: \treturn binary.LittleEndian.AppendUint32(block, total)\n321: }\n322: \n323: func appendPCAPNGOption(body []byte, code uint16, value []byte) []byte {\n324: \tbody = binary.LittleEndian.AppendUint16(body, code)\n325: \tbody = binary.LittleEndian.AppendUint16(body, uint16(len(value))) //nolint:gosec // short\n326: \tbody = append(body, value...)\n327: \n328: \treturn append(body, make([]byte, pcapngPadding(len(value)))...)\n329: }\n330: \n331: func pcapngPadding(length int) int {\n332: \treturn (4 - length%4) % 4\n333: }\n\n(End of file - total 333 lines)\n</content>",
    "title": "source/head/capture/pcapng.go",
    "metadata": {
      "preview": "// Package capture writes the pcapng streams of `containerlab capture`: one section with one\n// interface per capture target, packets merged across targets in timestamp order. The local\n// capturer reads lab link interfaces of Docker and Podman nodes through packet sockets; the c9s\n// lab runtime feeds the same writer from clabwire streams.\npackage capture\n\nimport (\n\t\"bufio\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"sync\"\n)\n\n// pcapng block layout (https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html). clabwire\n// writes little-endian sections, and so does the merged stream containerlab writes.\nconst (\n\tpcapngSectionHeaderType  = 0x0a0d0d0a",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/capture/pcapng.go",
        "text": "// Package capture writes the pcapng streams of `containerlab capture`: one section with one\n// interface per capture target, packets merged across targets in timestamp order. The local\n// capturer reads lab link interfaces of Docker and Podman nodes through packet sockets; the c9s\n// lab runtime feeds the same writer from clabwire streams.\npackage capture\n\nimport (\n\t\"bufio\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"sync\"\n)\n\n// pcapng block layout (https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html). clabwire\n// writes little-endian sections, and so does the merged stream containerlab writes.\nconst (\n\tpcapngSectionHeaderType  = 0x0a0d0d0a\n\tpcapngInterfaceType      = 0x00000001\n\tpcapngEnhancedPacketType = 0x00000006\n\tpcapngByteOrderMagic     = 0x1a2b3c4d\n\tpcapngOptionEnd          = 0\n\tpcapngOptionUserAppl     = 4\n\tpcapngOptionIfName       = 2\n\tpcapngOptionIfTSResol    = 9\n\tpcapngLinkTypeEthernet   = 1\n\t// pcapngNanoseconds is the if_tsresol value for 10^-9 s resolution.\n\tpcapngNanoseconds = 9\n\t// pcapngMaxBlockLength bounds a block read from a capture stream: a packet of the largest\n\t// clabwire snap length (1 MiB) plus framing.\n\tpcapngMaxBlockLength = 1<<20 + 1024\n\t// captureUserApplication names the writer in the merged section header.\n\tcaptureUserApplication = \"containerlab\"\n)\n\nvar errPCAPNGByteOrder = errors.New(\"pcapng section is not little-endian\")\n\n// InterfaceDescription is an Interface Description Block.\ntype InterfaceDescription struct {\n\tLinkType   uint16\n\tSnapLength uint32\n\tName       string\n\t// TSResol is the raw if_tsresol value; 6 (microseconds) when the block has none.\n\tTSResol byte\n}\n\n// Packet is an Enhanced Packet Block with its timestamp in nanoseconds.\ntype Packet struct {\n\tInterfaceID    uint32\n\tTimestamp      int64\n\tOriginalLength uint32\n\tData           []byte\n}\n\n// Reader reads the blocks of a pcapng stream as clabwire writes it: one or more\n// little-endian sections, each with its Interface Description Blocks before its packets.\ntype Reader struct {\n\tr          *bufio.Reader\n\tinterfaces []InterfaceDescription\n\t// sections counts the Section Header Blocks read so far.\n\tsections int\n}\n\n// NewReader returns a reader of the pcapng stream r.\nfunc NewReader(r io.Reader) *Reader {\n\treturn &Reader{r: bufio.NewReaderSize(r, 64<<10)}\n}\n\n// Sections returns the number of Section Header Blocks read so far.\nfunc (p *Reader) Sections() int {\n\treturn p.sections\n}\n\n// Event is one block of interest: a new interface or a packet.\ntype Event struct {\n\tInterface *InterfaceDescription\n\tPacket    *Packet\n}\n\n// Next returns the next interface or packet, skipping other block types. It returns io.EOF at\n// the clean end of the stream, and io.ErrUnexpectedEOF for a stream cut inside a block.\nfunc (p *Reader) Next() (Event, error) {\n\tfor {\n\t\tvar header [8]byte\n\t\tif _, err := io.ReadFull(p.r, header[:]); err != nil {\n\t\t\tif errors.Is(err, io.EOF) {\n\t\t\t\treturn Event{}, io.EOF\n\t\t\t}\n\n\t\t\treturn Event{}, io.ErrUnexpectedEOF\n\t\t}\n\n\t\tblockType := binary.LittleEndian.Uint32(header[0:4])\n\t\tlength := binary.LittleEndian.Uint32(header[4:8])\n\t\tif blockType == pcapngSectionHeaderType {\n\t\t\t// the byte-order magic tells a big-endian section apart before its length is\n\t\t\t// trusted: that length reads byte swapped\n\t\t\tmagic, err := p.r.Peek(4)\n\t\t\tif err != nil {\n\t\t\t\treturn Event{}, io.ErrUnexpectedEOF\n\t\t\t}\n\t\t\tif binary.BigEndian.Uint32(magic) == pcapngByteOrderMagic {\n\t\t\t\treturn Event{}, errPCAPNGByteOrder\n\t\t\t}\n\t\t}\n\t\tif length < 12 || length%4 != 0 || length > pcapngMaxBlockLength {\n\t\t\treturn Event{}, fmt.Errorf(\"invalid pcapng block length %d (at most %d)\", length,\n\t\t\t\tpcapngMaxBlockLength)\n\t\t}\n\n\t\tbody := make([]byte, length-8)\n\t\tif _, err := io.ReadFull(p.r, body); err != nil {\n\t\t\treturn Event{}, io.ErrUnexpectedEOF\n\t\t}\n\t\tif binary.LittleEndian.Uint32(body[len(body)-4:]) != length {\n\t\t\treturn Event{}, fmt.Errorf(\"pcapng block lengths do not match\")\n\t\t}\n\t\tbody = body[:len(body)-4]\n\n\t\tswitch blockType {\n\t\tcase pcapngSectionHeaderType:\n\t\t\tif len(body) < 16 {\n\t\t\t\treturn Event{}, fmt.Errorf(\"short pcapng section header\")\n\t\t\t}\n\t\t\tif binary.LittleEndian.Uint32(body[0:4]) != pcapngByteOrderMagic {\n\t\t\t\treturn Event{}, errPCAPNGByteOrder\n\t\t\t}\n\t\t\tp.sections++\n\t\t\tp.interfaces = nil\n\t\tcase pcapngInterfaceType:\n\t\t\tif p.sections == 0 {\n\t\t\t\treturn Event{}, fmt.Errorf(\"pcapng interface before a section header\")\n\t\t\t}\n\t\t\tintf, err := parsePCAPNGInterface(body)\n\t\t\tif err != nil {\n\t\t\t\treturn Event{}, err\n\t\t\t}\n\t\t\tp.interfaces = append(p.interfaces, intf)\n\n\t\t\treturn Event{Interface: &p.interfaces[len(p.interfaces)-1]}, nil\n\t\tcase pcapngEnhancedPacketType:\n\t\t\tpacket, err := p.parsePacket(body)\n\t\t\tif err != nil {\n\t\t\t\treturn Event{}, err\n\t\t\t}\n\n\t\t\treturn Event{Packet: &packet}, nil\n\t\t}\n\t}\n}\n\nfunc parsePCAPNGInterface(body []byte) (InterfaceDescription, error) {\n\tif len(body) < 8 {\n\t\treturn InterfaceDescription{}, fmt.Errorf(\"short pcapng interface description\")\n\t}\n\tintf := InterfaceDescription{\n\t\tLinkType:   binary.LittleEndian.Uint16(body[0:2]),\n\t\tSnapLength: binary.LittleEndian.Uint32(body[4:8]),\n\t\tTSResol:    6,\n\t}\n\n\toptions := body[8:]\n\tfor len(options) >= 4 {\n\t\tcode := binary.LittleEndian.Uint16(options[0:2])\n\t\tsize := int(binary.LittleEndian.Uint16(options[2:4]))\n\t\tif code == pcapngOptionEnd {\n\t\t\tbreak\n\t\t}\n\t\tpadded := size + pcapngPadding(size)\n\t\tif 4+padded > len(options) {\n\t\t\treturn InterfaceDescription{}, fmt.Errorf(\"truncated pcapng interface option\")\n\t\t}\n\t\tvalue := options[4 : 4+size]\n\t\tswitch code {\n\t\tcase pcapngOptionIfName:\n\t\t\tintf.Name = string(value)\n\t\tcase pcapngOptionIfTSResol:\n\t\t\tif size == 1 {\n\t\t\t\tintf.TSResol = value[0]\n\t\t\t}\n\t\t}\n\t\toptions = options[4+padded:]\n\t}\n\n\treturn intf, nil\n}\n\nfunc (p *Reader) parsePacket(body []byte) (Packet, error) {\n\tif len(body) < 20 {\n\t\treturn Packet{}, fmt.Errorf(\"short pcapng enhanced packet\")\n\t}\n\tpacket := Packet{\n\t\tInterfaceID:    binary.LittleEndian.Uint32(body[0:4]),\n\t\tOriginalLength: binary.LittleEndian.Uint32(body[16:20]),\n\t}\n\tif int(packet.InterfaceID) >= len(p.interfaces) {\n\t\treturn Packet{}, fmt.Errorf(\"pcapng packet for undeclared interface %d\",\n\t\t\tpacket.InterfaceID)\n\t}\n\tcaptured := binary.LittleEndian.Uint32(body[12:16])\n\tif int(captured) > len(body)-20 {\n\t\treturn Packet{}, fmt.Errorf(\"pcapng packet data exceeds its block\")\n\t}\n\tpacket.Data = body[20 : 20+captured]\n\n\traw := uint64(binary.LittleEndian.Uint32(body[4:8]))<<32 |\n\t\tuint64(binary.LittleEndian.Uint32(body[8:12]))\n\ttimestamp, err := pcapngNanosecondsFrom(raw, p.interfaces[packet.InterfaceID].TSResol)\n\tif err != nil {\n\t\treturn Packet{}, err\n\t}\n\tpacket.Timestamp = timestamp\n\n\treturn packet, nil\n}\n\n// pcapngNanosecondsFrom converts a timestamp in an interface's resolution to nanoseconds.\n// Only decimal resolutions up to nanoseconds occur in clabwire streams.\nfunc pcapngNanosecondsFrom(raw uint64, tsresol byte) (int64, error) {\n\tif tsresol&0x80 != 0 || tsresol > pcapngNanoseconds {\n\t\treturn 0, fmt.Errorf(\"unsupported pcapng timestamp resolution %#x\", tsresol)\n\t}\n\tscale := uint64(1)\n\tfor range pcapngNanoseconds - int(tsresol) {\n\t\tscale *= 10\n\t}\n\tif raw > math.MaxInt64/scale {\n\t\treturn 0, fmt.Errorf(\"pcapng timestamp out of range\")\n\t}\n\n\treturn int64(raw * scale), nil //nolint:gosec // bounded above\n}\n\n// Writer writes one little-endian section with nanosecond timestamps. Every block goes out\n// in one Write under a lock, so concurrent writers never interleave blocks and a stream cut\n// between writes is still a valid capture.\ntype Writer struct {\n\tmu  sync.Mutex\n\tw   io.Writer\n\terr error\n}\n\n// NewWriter returns a writer of one pcapng section to w.\nfunc NewWriter(w io.Writer) *Writer {\n\treturn &Writer{w: w}\n}\n\n// WriteHeader writes the Section Header Block and one Interface Description Block per name, in\n// order; packets refer to the interfaces by that index.\nfunc (p *Writer) WriteHeader(names []string, snapLength uint32) error {\n\tsection := make([]byte, 16)\n\tbinary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)\n\tbinary.LittleEndian.PutUint16(section[4:], 1)\n\tbinary.LittleEndian.PutUint16(section[6:], 0)\n\tbinary.LittleEndian.PutUint64(section[8:], math.MaxUint64)\n\tsection = appendPCAPNGOption(section, pcapngOptionUserAppl, []byte(captureUserApplication))\n\tsection = appendPCAPNGOption(section, pcapngOptionEnd, nil)\n\n\theader := pcapngBlock(pcapngSectionHeaderType, section)\n\tfor _, name := range names {\n\t\tdescription := make([]byte, 8)\n\t\tbinary.LittleEndian.PutUint16(description[0:], pcapngLinkTypeEthernet)\n\t\tbinary.LittleEndian.PutUint32(description[4:], snapLength)\n\t\tdescription = appendPCAPNGOption(description, pcapngOptionIfName, []byte(name))\n\t\tdescription = appendPCAPNGOption(description, pcapngOptionIfTSResol,\n\t\t\t[]byte{pcapngNanoseconds})\n\t\tdescription = appendPCAPNGOption(description, pcapngOptionEnd, nil)\n\t\theader = append(header, pcapngBlock(pcapngInterfaceType, description)...)\n\t}\n\n\treturn p.write(header)\n}\n\n// WritePacket writes an Enhanced Packet Block for the interface with the given index.\nfunc (p *Writer) WritePacket(interfaceID uint32, packet *Packet) error {\n\ttimestamp := uint64(packet.Timestamp) //nolint:gosec // capture timestamps are positive\n\tbody := make([]byte, 20, 20+len(packet.Data)+3)\n\tbinary.LittleEndian.PutUint32(body[0:], interfaceID)\n\tbinary.LittleEndian.PutUint32(body[4:], uint32(timestamp>>32))\n\tbinary.LittleEndian.PutUint32(body[8:], uint32(timestamp)) //nolint:gosec // low 32 bits\n\tbinary.LittleEndian.PutUint32(body[12:], uint32(len(packet.Data)))\n\tbinary.LittleEndian.PutUint32(body[16:], packet.OriginalLength)\n\tbody = append(body, packet.Data...)\n\tbody = append(body, make([]byte, pcapngPadding(len(packet.Data)))...)\n\n\treturn p.write(pcapngBlock(pcapngEnhancedPacketType, body))\n}\n\n// Err returns the first write error, or nil.\nfunc (p *Writer) Err() error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\treturn p.err\n}\n\nfunc (p *Writer) write(block []byte) error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\tif p.err != nil {\n\t\treturn p.err\n\t}\n\tif _, err := p.w.Write(block); err != nil {\n\t\tp.err = fmt.Errorf(\"failed to write the capture: %w\", err)\n\t}\n\n\treturn p.err\n}\n\nfunc pcapngBlock(blockType uint32, body []byte) []byte {\n\ttotal := uint32(12 + len(body)) //nolint:gosec // bounded by the snap length\n\tblock := make([]byte, 8, total)\n\tbinary.LittleEndian.PutUint32(block[0:], blockType)\n\tbinary.LittleEndian.PutUint32(block[4:], total)\n\tblock = append(block, body...)\n\n\treturn binary.LittleEndian.AppendUint32(block, total)\n}\n\nfunc appendPCAPNGOption(body []byte, code uint16, value []byte) []byte {\n\tbody = binary.LittleEndian.AppendUint16(body, code)\n\tbody = binary.LittleEndian.AppendUint16(body, uint16(len(value))) //nolint:gosec // short\n\tbody = append(body, value...)\n\n\treturn append(body, make([]byte, pcapngPadding(len(value)))...)\n}\n\nfunc pcapngPadding(length int) int {\n\treturn (4 - length%4) % 4\n}",
        "lineStart": 1,
        "lineEnd": 333,
        "totalLines": 333,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523388810,
      "end": 1793523388825
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19653119b001UnSxAZexVcZPAf",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19652f69d001xsI2OBDEJpPxOR",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 68037,
    "input": 42616,
    "output": 24,
    "reasoning": 501,
    "cache": {
      "read": 24896,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19652f69d001xsI2OBDEJpPxOR",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523381918,
    "completed": 1793523388831
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 68037,
    "input": 42616,
    "output": 24,
    "reasoning": 501,
    "cache": {
      "read": 24896,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 34
step-start
{
  "type": "step-start",
  "id": "prt_196531993001goJWooJ1f4MRK7",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965311a7001k6hdWxAPXEGpKv"
}
Reasoning
pcapng.go verification:

- **SHB body minimum 16**: SHB body = block body after the 8-byte generic header, minus trailing length = 4 bytes. Minimum SHB total 28 → body after removing trailer = 16: byte-order magic (4), major (2), minor (2), section length (8). Yes `len(body) < 16` check. Good.

- **`Next` SHB peek**: `p.r.Peek(4)` after reading 8-byte header; if stream ends right after SHB header → ErrUnexpectedEOF. Correct behavior for truncated stream.

- **Interface event returns pointer into slice `p.interfaces`**: `&p.interfaces[len(p.interfaces)-1]` — slice may be reallocated on the next append, invalidating the earlier pointer. `readSegment` uses it immediately; the test in core uses the merged reader? `c.capture.out` uses `NewReader`? In c9s, readSegment uses NewReader(stdout) and only checks name. OK. But is `Reader.Next`'s returned Event.Interface pointer used after subsequent calls anywhere? In tests: capture_test.go and clabernetes/capture_test.go may hold onto them. Not production. Fine.

- **Writer.WriteHeader section**: major version 1, minor 0. `section = make([]byte, 16)` — but SHB body must be 4 (magic) + 2 + 2 + 8 = 16. Yes.

- **`WritePacket` negative timestamp**: nolint'd; packets have positive timestamps in practice.

- **`parsePacket`**: `captured > len(body)-20` — block padding included in body; fine. Note EPB options after packet data are ignored (packet.Data slice may include padding if captured < padded — they slice exactly captured bytes). Good.

- **EPB timestamp**: high 32 bits at body[4:8] (timestamp_high), low at body[8:12]. Correct per pcapng.

Now `Writer` locking: Emit→Push→writeLocked→write (mutex), and Run's writeDue→popLocked→writeLocked→write. Two paths, both under q.mu before calling write — no deadlock. But note: `Writer.write` has its own mutex; a concurrent writer doesn't exist. OK.

Now check remaining diff hunks: capture_tests (37–1676 range: local_test, pcapng_test, reorder_test), and the clabernetes capture_interfaces.go + capture_test.go + runtime.go changes (LocateNode ordering semantics), plus workflows (already seen), and inspect/interfaces doc (seen). Also `core/labruntime_cluster_test.go` seen.

Let me check `LocateNode` ordering guarantee — search in clabernetes runtime for LocateNode.
The codec looks sound. Let me verify the `LocateNode` ordering assumption in `resolveCaptureTargets` and check the c9s `capture_interfaces.go` and tests.
grep · completed

Input

{
  "path": "/source/head/labruntime/clabernetes",
  "pattern": "func (r \\*Runtime) LocateNode"
}

Output

No files found
Tool metadata
{
  "type": "tool",
  "id": "prt_196532af7001FufLf8VvMnO637",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965311a7001k6hdWxAPXEGpKv",
  "callID": "call_fb79d782d1bc4f3e8fcf9f81",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/labruntime/clabernetes",
      "pattern": "func (r \\*Runtime) LocateNode"
    },
    "output": "No files found",
    "title": "func (r \\*Runtime) LocateNode",
    "metadata": {
      "matches": 0,
      "truncated": false
    },
    "time": {
      "start": 1793523395323,
      "end": 1793523395332
    }
  }
}
grep · completed

Input

{
  "path": "/source/head/labruntime/clabernetes",
  "pattern": "func (r \\*Runtime) nodesForTopology|func (r \\*Runtime) nodeDisplayName|originalNodeName"
}

Output

Found 7 matches
/source/head/labruntime/clabernetes/capture.go:
  Line 298: // nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the


/source/head/labruntime/clabernetes/names.go:
  Line 17: // Every node definition also carries c9s.run/originalNodeName naming the node as the topology file


/source/head/labruntime/clabernetes/clabernetes.go:
  Line 34: 	labelOriginalNodeName = "c9s.run/originalNodeName"


/source/head/labruntime/clabernetes/clabernetes_test.go:
  Line 1279:         c9s.run/originalNodeName: node1

  Line 3065:         c9s.run/originalNodeName: sros

  Line 3070:         c9s.run/originalNodeName: vsrx

  Line 3521:         c9s.run/originalNodeName: node1
Tool metadata
{
  "type": "tool",
  "id": "prt_196532bb5001YHQZ0MmMmpOldV",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965311a7001k6hdWxAPXEGpKv",
  "callID": "call_af5aeaed5f9e43a9845647b4",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/labruntime/clabernetes",
      "pattern": "func (r \\*Runtime) nodesForTopology|func (r \\*Runtime) nodeDisplayName|originalNodeName"
    },
    "output": "Found 7 matches\n/source/head/labruntime/clabernetes/capture.go:\n  Line 298: // nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the\n\n\n/source/head/labruntime/clabernetes/names.go:\n  Line 17: // Every node definition also carries c9s.run/originalNodeName naming the node as the topology file\n\n\n/source/head/labruntime/clabernetes/clabernetes.go:\n  Line 34: \tlabelOriginalNodeName = \"c9s.run/originalNodeName\"\n\n\n/source/head/labruntime/clabernetes/clabernetes_test.go:\n  Line 1279:         c9s.run/originalNodeName: node1\n\n  Line 3065:         c9s.run/originalNodeName: sros\n\n  Line 3070:         c9s.run/originalNodeName: vsrx\n\n  Line 3521:         c9s.run/originalNodeName: node1\n",
    "title": "func (r \\*Runtime) nodesForTopology|func (r \\*Runtime) nodeDisplayName|originalNodeName",
    "metadata": {
      "matches": 7,
      "truncated": false
    },
    "time": {
      "start": 1793523395515,
      "end": 1793523395530
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196532bcc001d8oznEtsToJZeP",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965311a7001k6hdWxAPXEGpKv",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 72647,
    "input": 4119,
    "output": 110,
    "reasoning": 578,
    "cache": {
      "read": 67840,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1965311a7001k6hdWxAPXEGpKv",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523388839,
    "completed": 1793523395534
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 72647,
    "input": 4119,
    "output": 110,
    "reasoning": 578,
    "cache": {
      "read": 67840,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 35
step-start
{
  "type": "step-start",
  "id": "prt_19653344c001eXBlwN87qHPgEF",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196532bd60015VpspkwCnYfZ04"
}
grep · completed

Input

{
  "path": "/source/head/labruntime/clabernetes",
  "pattern": "LocateNode\\(",
  "include": "*.go"
}

Output

Found 9 matches
/source/head/labruntime/clabernetes/capture.go:
  Line 172: 	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{

  Line 356: 	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{


/source/head/labruntime/clabernetes/capture_interfaces.go:
  Line 85: 	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{


/source/head/labruntime/clabernetes/access.go:
  Line 49: func (r *Runtime) LocateNode(

  Line 122: 	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{


/source/head/labruntime/clabernetes/access_test.go:
  Line 76: func TestLocateNode(t *testing.T) {

  Line 81: 	all, err := r.LocateNode(context.Background(), clablabruntime.NodeRequest{Name: "lab1"})

  Line 90: 	named, err := r.LocateNode(context.Background(), clablabruntime.NodeRequest{

  Line 104: 	if _, err := r.LocateNode(context.Background(), clablabruntime.NodeRequest{
Tool metadata
{
  "type": "tool",
  "id": "prt_1965334ac001TECmaEywRkEtq4",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196532bd60015VpspkwCnYfZ04",
  "callID": "call_6b7ae5468cbe46e7ad31dabb",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/labruntime/clabernetes",
      "pattern": "LocateNode\\(",
      "include": "*.go"
    },
    "output": "Found 9 matches\n/source/head/labruntime/clabernetes/capture.go:\n  Line 172: \tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n\n  Line 356: \tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n\n\n/source/head/labruntime/clabernetes/capture_interfaces.go:\n  Line 85: \tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n\n\n/source/head/labruntime/clabernetes/access.go:\n  Line 49: func (r *Runtime) LocateNode(\n\n  Line 122: \tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n\n\n/source/head/labruntime/clabernetes/access_test.go:\n  Line 76: func TestLocateNode(t *testing.T) {\n\n  Line 81: \tall, err := r.LocateNode(context.Background(), clablabruntime.NodeRequest{Name: \"lab1\"})\n\n  Line 90: \tnamed, err := r.LocateNode(context.Background(), clablabruntime.NodeRequest{\n\n  Line 104: \tif _, err := r.LocateNode(context.Background(), clablabruntime.NodeRequest{\n",
    "title": "LocateNode\\(",
    "metadata": {
      "matches": 9,
      "truncated": false
    },
    "time": {
      "start": 1793523397809,
      "end": 1793523397817
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1965334bf001v3QB0Y3L2jAgDK",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196532bd60015VpspkwCnYfZ04",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 72889,
    "input": 408,
    "output": 32,
    "reasoning": 1,
    "cache": {
      "read": 72448,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196532bd60015VpspkwCnYfZ04",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523395542,
    "completed": 1793523397826
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 72889,
    "input": 408,
    "output": 32,
    "reasoning": 1,
    "cache": {
      "read": 72448,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 36
step-start
{
  "type": "step-start",
  "id": "prt_196533c3e001Es0bHwVuSSB3Dg",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965334ca001giLxtUX7G0lyvT"
}
read · completed

Input

{
  "filePath": "/source/head/labruntime/clabernetes/access.go",
  "limit": 90,
  "offset": 40
}

Output

<path>/source/head/labruntime/clabernetes/access.go</path>
<type>file</type>
<content>
40: // defaultAttachCommand runs when an attach request names no command.
41: var defaultAttachCommand = []string{"sh"} //nolint:gochecknoglobals
42: 
43: // portForwardRequestID numbers the port-forward streams of this process.
44: var portForwardRequestID atomic.Int64 //nolint:gochecknoglobals
45: 
46: // LocateNode reports the pod, primary device container, Node UID and exposed ports of the
47: // requested nodes, or of every node of the lab when the request names none. Node names are
48: // accepted as the topology or as the cluster spells them.
49: func (r *Runtime) LocateNode(
50: 	ctx context.Context,
51: 	req clablabruntime.NodeRequest,
52: ) ([]clablabruntime.NodeLocation, error) {
53: 	r, err := r.connect(ctx, req.Identity)
54: 	if err != nil {
55: 		return nil, err
56: 	}
57: 
58: 	state, err := r.Inspect(ctx, clablabruntime.InspectRequest{
59: 		Name:      req.Name,
60: 		Namespace: req.Namespace,
61: 	})
62: 	if err != nil {
63: 		return nil, err
64: 	}
65: 
66: 	nodes := make(map[string]clablabruntime.NodeState, len(state.Nodes))
67: 	for _, node := range state.Nodes {
68: 		nodes[node.Name] = node
69: 	}
70: 
71: 	if len(req.Nodes) == 0 {
72: 		locations := make([]clablabruntime.NodeLocation, 0, len(state.Nodes))
73: 		for _, node := range state.Nodes {
74: 			locations = append(locations, nodeLocation(state, node))
75: 		}
76: 
77: 		return locations, nil
78: 	}
79: 
80: 	locations := make([]clablabruntime.NodeLocation, 0, len(req.Nodes))
81: 	for _, nodeName := range req.Nodes {
82: 		resolved, ok := resolveKnownNodeName(nodes, nodeName)
83: 		if !ok {
84: 			return nil, fmt.Errorf("node %q was not found in c9s lab %s/%s",
85: 				nodeName, state.Namespace, state.Name)
86: 		}
87: 		locations = append(locations, nodeLocation(state, nodes[resolved]))
88: 	}
89: 
90: 	return locations, nil
91: }
92: 
93: func nodeLocation(
94: 	state *clablabruntime.LabState,
95: 	node clablabruntime.NodeState,
96: ) clablabruntime.NodeLocation {
97: 	return clablabruntime.NodeLocation{
98: 		NodeName:            node.Name,
99: 		Namespace:           state.Namespace,
100: 		Pod:                 node.Pod,
101: 		Container:           node.Container,
102: 		NodeUID:             node.NodeUID,
103: 		ExposedPorts:        node.ExposedPorts,
104: 		LoadBalancerAddress: node.LoadBalancerAddress,
105: 	}
106: }
107: 
108: // runningNode locates one node and requires it to have a pod and a device container.
109: func (r *Runtime) runningNode(
110: 	ctx context.Context,
111: 	lab,
112: 	namespace,
113: 	nodeName string,
114: ) (clablabruntime.NodeLocation, error) {
115: 	if lab == "" {
116: 		return clablabruntime.NodeLocation{}, fmt.Errorf("topology name is required")
117: 	}
118: 	if nodeName == "" {
119: 		return clablabruntime.NodeLocation{}, fmt.Errorf("node name is required")
120: 	}
121: 
122: 	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{
123: 		Name:      lab,
124: 		Namespace: namespace,
125: 		Nodes:     []string{nodeName},
126: 	})
127: 	if err != nil {
128: 		return clablabruntime.NodeLocation{}, err
129: 	}

(Showing lines 40-129 of 582. Use offset=130 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196533c8d001KFi53svGlFl28b",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965334ca001giLxtUX7G0lyvT",
  "callID": "call_d5b7fb7af9b34d07b121c4d2",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/access.go",
      "limit": 90,
      "offset": 40
    },
    "output": "<path>/source/head/labruntime/clabernetes/access.go</path>\n<type>file</type>\n<content>\n40: // defaultAttachCommand runs when an attach request names no command.\n41: var defaultAttachCommand = []string{\"sh\"} //nolint:gochecknoglobals\n42: \n43: // portForwardRequestID numbers the port-forward streams of this process.\n44: var portForwardRequestID atomic.Int64 //nolint:gochecknoglobals\n45: \n46: // LocateNode reports the pod, primary device container, Node UID and exposed ports of the\n47: // requested nodes, or of every node of the lab when the request names none. Node names are\n48: // accepted as the topology or as the cluster spells them.\n49: func (r *Runtime) LocateNode(\n50: \tctx context.Context,\n51: \treq clablabruntime.NodeRequest,\n52: ) ([]clablabruntime.NodeLocation, error) {\n53: \tr, err := r.connect(ctx, req.Identity)\n54: \tif err != nil {\n55: \t\treturn nil, err\n56: \t}\n57: \n58: \tstate, err := r.Inspect(ctx, clablabruntime.InspectRequest{\n59: \t\tName:      req.Name,\n60: \t\tNamespace: req.Namespace,\n61: \t})\n62: \tif err != nil {\n63: \t\treturn nil, err\n64: \t}\n65: \n66: \tnodes := make(map[string]clablabruntime.NodeState, len(state.Nodes))\n67: \tfor _, node := range state.Nodes {\n68: \t\tnodes[node.Name] = node\n69: \t}\n70: \n71: \tif len(req.Nodes) == 0 {\n72: \t\tlocations := make([]clablabruntime.NodeLocation, 0, len(state.Nodes))\n73: \t\tfor _, node := range state.Nodes {\n74: \t\t\tlocations = append(locations, nodeLocation(state, node))\n75: \t\t}\n76: \n77: \t\treturn locations, nil\n78: \t}\n79: \n80: \tlocations := make([]clablabruntime.NodeLocation, 0, len(req.Nodes))\n81: \tfor _, nodeName := range req.Nodes {\n82: \t\tresolved, ok := resolveKnownNodeName(nodes, nodeName)\n83: \t\tif !ok {\n84: \t\t\treturn nil, fmt.Errorf(\"node %q was not found in c9s lab %s/%s\",\n85: \t\t\t\tnodeName, state.Namespace, state.Name)\n86: \t\t}\n87: \t\tlocations = append(locations, nodeLocation(state, nodes[resolved]))\n88: \t}\n89: \n90: \treturn locations, nil\n91: }\n92: \n93: func nodeLocation(\n94: \tstate *clablabruntime.LabState,\n95: \tnode clablabruntime.NodeState,\n96: ) clablabruntime.NodeLocation {\n97: \treturn clablabruntime.NodeLocation{\n98: \t\tNodeName:            node.Name,\n99: \t\tNamespace:           state.Namespace,\n100: \t\tPod:                 node.Pod,\n101: \t\tContainer:           node.Container,\n102: \t\tNodeUID:             node.NodeUID,\n103: \t\tExposedPorts:        node.ExposedPorts,\n104: \t\tLoadBalancerAddress: node.LoadBalancerAddress,\n105: \t}\n106: }\n107: \n108: // runningNode locates one node and requires it to have a pod and a device container.\n109: func (r *Runtime) runningNode(\n110: \tctx context.Context,\n111: \tlab,\n112: \tnamespace,\n113: \tnodeName string,\n114: ) (clablabruntime.NodeLocation, error) {\n115: \tif lab == \"\" {\n116: \t\treturn clablabruntime.NodeLocation{}, fmt.Errorf(\"topology name is required\")\n117: \t}\n118: \tif nodeName == \"\" {\n119: \t\treturn clablabruntime.NodeLocation{}, fmt.Errorf(\"node name is required\")\n120: \t}\n121: \n122: \tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n123: \t\tName:      lab,\n124: \t\tNamespace: namespace,\n125: \t\tNodes:     []string{nodeName},\n126: \t})\n127: \tif err != nil {\n128: \t\treturn clablabruntime.NodeLocation{}, err\n129: \t}\n\n(Showing lines 40-129 of 582. Use offset=130 to continue.)\n</content>",
    "title": "source/head/labruntime/clabernetes/access.go",
    "metadata": {
      "preview": "// defaultAttachCommand runs when an attach request names no command.\nvar defaultAttachCommand = []string{\"sh\"} //nolint:gochecknoglobals\n\n// portForwardRequestID numbers the port-forward streams of this process.\nvar portForwardRequestID atomic.Int64 //nolint:gochecknoglobals\n\n// LocateNode reports the pod, primary device container, Node UID and exposed ports of the\n// requested nodes, or of every node of the lab when the request names none. Node names are\n// accepted as the topology or as the cluster spells them.\nfunc (r *Runtime) LocateNode(\n\tctx context.Context,\n\treq clablabruntime.NodeRequest,\n) ([]clablabruntime.NodeLocation, error) {\n\tr, err := r.connect(ctx, req.Identity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstate, err := r.Inspect(ctx, clablabruntime.InspectRequest{\n\t\tName:      req.Name,",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/access.go",
        "text": "// defaultAttachCommand runs when an attach request names no command.\nvar defaultAttachCommand = []string{\"sh\"} //nolint:gochecknoglobals\n\n// portForwardRequestID numbers the port-forward streams of this process.\nvar portForwardRequestID atomic.Int64 //nolint:gochecknoglobals\n\n// LocateNode reports the pod, primary device container, Node UID and exposed ports of the\n// requested nodes, or of every node of the lab when the request names none. Node names are\n// accepted as the topology or as the cluster spells them.\nfunc (r *Runtime) LocateNode(\n\tctx context.Context,\n\treq clablabruntime.NodeRequest,\n) ([]clablabruntime.NodeLocation, error) {\n\tr, err := r.connect(ctx, req.Identity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstate, err := r.Inspect(ctx, clablabruntime.InspectRequest{\n\t\tName:      req.Name,\n\t\tNamespace: req.Namespace,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnodes := make(map[string]clablabruntime.NodeState, len(state.Nodes))\n\tfor _, node := range state.Nodes {\n\t\tnodes[node.Name] = node\n\t}\n\n\tif len(req.Nodes) == 0 {\n\t\tlocations := make([]clablabruntime.NodeLocation, 0, len(state.Nodes))\n\t\tfor _, node := range state.Nodes {\n\t\t\tlocations = append(locations, nodeLocation(state, node))\n\t\t}\n\n\t\treturn locations, nil\n\t}\n\n\tlocations := make([]clablabruntime.NodeLocation, 0, len(req.Nodes))\n\tfor _, nodeName := range req.Nodes {\n\t\tresolved, ok := resolveKnownNodeName(nodes, nodeName)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"node %q was not found in c9s lab %s/%s\",\n\t\t\t\tnodeName, state.Namespace, state.Name)\n\t\t}\n\t\tlocations = append(locations, nodeLocation(state, nodes[resolved]))\n\t}\n\n\treturn locations, nil\n}\n\nfunc nodeLocation(\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n) clablabruntime.NodeLocation {\n\treturn clablabruntime.NodeLocation{\n\t\tNodeName:            node.Name,\n\t\tNamespace:           state.Namespace,\n\t\tPod:                 node.Pod,\n\t\tContainer:           node.Container,\n\t\tNodeUID:             node.NodeUID,\n\t\tExposedPorts:        node.ExposedPorts,\n\t\tLoadBalancerAddress: node.LoadBalancerAddress,\n\t}\n}\n\n// runningNode locates one node and requires it to have a pod and a device container.\nfunc (r *Runtime) runningNode(\n\tctx context.Context,\n\tlab,\n\tnamespace,\n\tnodeName string,\n) (clablabruntime.NodeLocation, error) {\n\tif lab == \"\" {\n\t\treturn clablabruntime.NodeLocation{}, fmt.Errorf(\"topology name is required\")\n\t}\n\tif nodeName == \"\" {\n\t\treturn clablabruntime.NodeLocation{}, fmt.Errorf(\"node name is required\")\n\t}\n\n\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n\t\tName:      lab,\n\t\tNamespace: namespace,\n\t\tNodes:     []string{nodeName},\n\t})\n\tif err != nil {\n\t\treturn clablabruntime.NodeLocation{}, err\n\t}",
        "lineStart": 40,
        "lineEnd": 129,
        "totalLines": 582,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523399825,
      "end": 1793523399831
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196533c98001U18MZ2vkOhW0nO",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965334ca001giLxtUX7G0lyvT",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 73179,
    "input": 316,
    "output": 30,
    "reasoning": 1,
    "cache": {
      "read": 72832,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1965334ca001giLxtUX7G0lyvT",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523397834,
    "completed": 1793523399835
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 73179,
    "input": 316,
    "output": 30,
    "reasoning": 1,
    "cache": {
      "read": 72832,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 37
step-start
{
  "type": "step-start",
  "id": "prt_1965344210019wibHgr81cJajP",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196533ca2001DbAdTJgSwNGYuM"
}
Reasoning
`LocateNode` preserves the request order for named nodes. Good — `resolveCaptureTargets`'s `byRequest` mapping is safe.

Also note: in `resolveCaptureTargets`, if a node's pod is empty (not running), `listed` would fail via `listCaptureInterfaces` (which errors if pod empty). Good.

But wait: in `resolveCaptureTargets`, `locations` includes all requested nodes; `listCaptureInterfaces(ctx, req.Name, locations)` errors if any node has no pod. Good.

One more check in `CaptureInterfaces`: `listed[location.NodeName]` — keyed by NodeName from clabwire entries; if clabwire's `node` field differs from NodeName... clabwire's `--nodeName` matches NodeName. `wanted[entry.Node]` check ensures only entries whose node is wanted. OK.

Now, `CaptureInterfaces` in c9s — one potential mismatch: in `resolveCaptureTargets`, if `req.Nodes` filter in NodeRequest... fine.

Next: check the remaining pieces I haven't verified:
1. `capture_interfaces.go` (c9s InspectInterfaces implementation).
2. `capture_test.go` for c9s (1050 lines) — skim.
3. capture package tests (local_test, pcapng_test, reorder_test) — skim.
4. `cmd/inspect_interfaces.go` head — the lab-runtime branch calls `printContainerInterfaces` — check that function exists and handles format.
5. `streamPodExec` in capture_interfaces.go.
6. `.github/workflows` changes (seen at diff 1–36).
7. `mkdocs.yml` change (nav entry for capture docs).

Also verify `commandSkipsRoot` in root.go — what does it return for c9s?
read · completed

Input

{
  "filePath": "/source/head/cmd/root.go",
  "limit": 40,
  "offset": 195
}

Output

<path>/source/head/cmd/root.go</path>
<type>file</type>
<content>
195: 		return
196: 	}
197: 
198: 	if value, ok := os.LookupEnv(envPrefix + "_TIMEOUT"); ok && strings.TrimSpace(value) != "" {
199: 		return
200: 	}
201: 
202: 	o.Global.Timeout = defaultLabRuntimeTimeout
203: }
204: 
205: func globalRuntimeRequiresRoot(name string) bool {
206: 	return name != "" &&
207: 		name != clabruntimedocker.RuntimeName &&
208: 		!commandSkipsRoot(name)
209: }
210: 
211: func commandSkipsRoot(name string) bool {
212: 	return clablabruntime.IsLabRuntimeName(name)
213: }
214: 
215: // labRuntimeUnsupportedCommands operate on local containers or host networking
216: // and have no lab runtime equivalent.
217: var labRuntimeUnsupportedCommands = map[string]struct{}{
218: 	"tools": {},
219: }
220: 
221: // graphTopologyFileFlags select graph modes that render from the topology file alone, without
222: // running containers. Lab runtimes support only these modes.
223: var graphTopologyFileFlags = []string{ //nolint:gochecknoglobals
224: 	"dot",
225: 	"mermaid",
226: 	"drawio",
227: 	"offline",
228: }
229: 
230: // labRuntimeUnsupportedFlags is the explicit CLI compatibility contract for controller-driven
231: // runtimes. A flag listed here must fail before topology parsing or remote mutation instead of
232: // being accepted and silently ignored by the adapter.
233: var labRuntimeUnsupportedFlags = map[string][]string{ //nolint:gochecknoglobals
234: 	"deploy": {

(Showing lines 195-234 of 461. Use offset=235 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196534d14001E05YJK075to7lm",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196533ca2001DbAdTJgSwNGYuM",
  "callID": "call_ebfbdd827a1d41e9a8c6850b",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/cmd/root.go",
      "limit": 40,
      "offset": 195
    },
    "output": "<path>/source/head/cmd/root.go</path>\n<type>file</type>\n<content>\n195: \t\treturn\n196: \t}\n197: \n198: \tif value, ok := os.LookupEnv(envPrefix + \"_TIMEOUT\"); ok && strings.TrimSpace(value) != \"\" {\n199: \t\treturn\n200: \t}\n201: \n202: \to.Global.Timeout = defaultLabRuntimeTimeout\n203: }\n204: \n205: func globalRuntimeRequiresRoot(name string) bool {\n206: \treturn name != \"\" &&\n207: \t\tname != clabruntimedocker.RuntimeName &&\n208: \t\t!commandSkipsRoot(name)\n209: }\n210: \n211: func commandSkipsRoot(name string) bool {\n212: \treturn clablabruntime.IsLabRuntimeName(name)\n213: }\n214: \n215: // labRuntimeUnsupportedCommands operate on local containers or host networking\n216: // and have no lab runtime equivalent.\n217: var labRuntimeUnsupportedCommands = map[string]struct{}{\n218: \t\"tools\": {},\n219: }\n220: \n221: // graphTopologyFileFlags select graph modes that render from the topology file alone, without\n222: // running containers. Lab runtimes support only these modes.\n223: var graphTopologyFileFlags = []string{ //nolint:gochecknoglobals\n224: \t\"dot\",\n225: \t\"mermaid\",\n226: \t\"drawio\",\n227: \t\"offline\",\n228: }\n229: \n230: // labRuntimeUnsupportedFlags is the explicit CLI compatibility contract for controller-driven\n231: // runtimes. A flag listed here must fail before topology parsing or remote mutation instead of\n232: // being accepted and silently ignored by the adapter.\n233: var labRuntimeUnsupportedFlags = map[string][]string{ //nolint:gochecknoglobals\n234: \t\"deploy\": {\n\n(Showing lines 195-234 of 461. Use offset=235 to continue.)\n</content>",
    "title": "source/head/cmd/root.go",
    "metadata": {
      "preview": "\t\treturn\n\t}\n\n\tif value, ok := os.LookupEnv(envPrefix + \"_TIMEOUT\"); ok && strings.TrimSpace(value) != \"\" {\n\t\treturn\n\t}\n\n\to.Global.Timeout = defaultLabRuntimeTimeout\n}\n\nfunc globalRuntimeRequiresRoot(name string) bool {\n\treturn name != \"\" &&\n\t\tname != clabruntimedocker.RuntimeName &&\n\t\t!commandSkipsRoot(name)\n}\n\nfunc commandSkipsRoot(name string) bool {\n\treturn clablabruntime.IsLabRuntimeName(name)\n}\n",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/cmd/root.go",
        "text": "\t\treturn\n\t}\n\n\tif value, ok := os.LookupEnv(envPrefix + \"_TIMEOUT\"); ok && strings.TrimSpace(value) != \"\" {\n\t\treturn\n\t}\n\n\to.Global.Timeout = defaultLabRuntimeTimeout\n}\n\nfunc globalRuntimeRequiresRoot(name string) bool {\n\treturn name != \"\" &&\n\t\tname != clabruntimedocker.RuntimeName &&\n\t\t!commandSkipsRoot(name)\n}\n\nfunc commandSkipsRoot(name string) bool {\n\treturn clablabruntime.IsLabRuntimeName(name)\n}\n\n// labRuntimeUnsupportedCommands operate on local containers or host networking\n// and have no lab runtime equivalent.\nvar labRuntimeUnsupportedCommands = map[string]struct{}{\n\t\"tools\": {},\n}\n\n// graphTopologyFileFlags select graph modes that render from the topology file alone, without\n// running containers. Lab runtimes support only these modes.\nvar graphTopologyFileFlags = []string{ //nolint:gochecknoglobals\n\t\"dot\",\n\t\"mermaid\",\n\t\"drawio\",\n\t\"offline\",\n}\n\n// labRuntimeUnsupportedFlags is the explicit CLI compatibility contract for controller-driven\n// runtimes. A flag listed here must fail before topology parsing or remote mutation instead of\n// being accepted and silently ignored by the adapter.\nvar labRuntimeUnsupportedFlags = map[string][]string{ //nolint:gochecknoglobals\n\t\"deploy\": {",
        "lineStart": 195,
        "lineEnd": 234,
        "totalLines": 461,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523404056,
      "end": 1793523404061
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/labruntime/clabernetes/capture_interfaces.go"
}

Output

<path>/source/head/labruntime/clabernetes/capture_interfaces.go</path>
<type>file</type>
<content>
1: package clabernetes
2: 
3: import (
4: 	"bytes"
5: 	"context"
6: 	"errors"
7: 	"fmt"
8: 	"io"
9: 	"sort"
10: 	"sync"
11: 
12: 	"github.com/charmbracelet/log"
13: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
14: 	clabtypes "github.com/srl-labs/containerlab/types"
15: 	corev1 "k8s.io/api/core/v1"
16: 	"k8s.io/client-go/kubernetes/scheme"
17: 	"k8s.io/client-go/tools/remotecommand"
18: 	kubeexec "k8s.io/client-go/util/exec"
19: )
20: 
21: // streamPodExec runs a command in a pod container without a terminal and streams its stdout
22: // and stderr. A non-nil stdin is attached: when it ends, the process's stdin is closed (the
23: // websocket v5 close signal, or a half-closed SPDY stream). A nonzero exit returns a
24: // *labruntime.CommandExitError.
25: func (r *Runtime) streamPodExec(
26: 	ctx context.Context,
27: 	namespace, pod, container string,
28: 	command []string,
29: 	stdin io.Reader,
30: 	stdout, stderr io.Writer,
31: ) error {
32: 	execURL := r.kubeClient.CoreV1().RESTClient().Post().
33: 		Resource("pods").
34: 		Name(pod).
35: 		Namespace(namespace).
36: 		SubResource("exec").
37: 		VersionedParams(&corev1.PodExecOptions{
38: 			Container: container,
39: 			Command:   command,
40: 			Stdin:     stdin != nil,
41: 			Stdout:    stdout != nil,
42: 			Stderr:    stderr != nil,
43: 		}, scheme.ParameterCodec).URL()
44: 
45: 	executor, err := r.newExecutor(execURL)
46: 	if err != nil {
47: 		return err
48: 	}
49: 
50: 	// client-go reports streams cut by a cancelled context through the context's logger; a
51: 	// capture ends that way on purpose, so it goes to the debug log
52: 	err = executor.StreamWithContext(withKubernetesClientDebugLogs(ctx),
53: 		remotecommand.StreamOptions{
54: 			Stdin:  stdin,
55: 			Stdout: stdout,
56: 			Stderr: stderr,
57: 		})
58: 
59: 	var exitErr kubeexec.ExitError
60: 	if errors.As(err, &exitErr) {
61: 		return &clablabruntime.CommandExitError{Code: exitErr.ExitStatus()}
62: 	}
63: 	if err != nil {
64: 		return fmt.Errorf("failed to execute command in pod %s/%s container %s: %w",
65: 			namespace, pod, container, err)
66: 	}
67: 
68: 	return nil
69: }
70: 
71: // InspectInterfaces lists the capturable link interfaces of the requested nodes, or of every
72: // running node, in the shape of `inspect interfaces`: per node (named <lab>-<node> like in
73: // inspect), the interface and its alias as clabwire reports them, and the MAC address, index,
74: // MTU and operational state read from sysfs in the device container. A node whose device
75: // container has no shell reports its interfaces without these attributes.
76: func (r *Runtime) InspectInterfaces(
77: 	ctx context.Context,
78: 	req clablabruntime.NodeRequest,
79: ) ([]*clabtypes.ContainerInterfaces, error) {
80: 	r, err := r.connect(ctx, req.Identity)
81: 	if err != nil {
82: 		return nil, err
83: 	}
84: 
85: 	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{
86: 		Name: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,
87: 	})
88: 	if err != nil {
89: 		return nil, err
90: 	}
91: 
92: 	running := make([]clablabruntime.NodeLocation, 0, len(locations))
93: 	for _, location := range locations {
94: 		if location.Pod == "" {
95: 			log.Warn("Skipping interface detection of a node that does not run",
96: 				"node", location.NodeName)
97: 			continue
98: 		}
99: 		running = append(running, location)
100: 	}
101: 
102: 	listed, err := r.listCaptureInterfaces(ctx, req.Name, running)
103: 	if err != nil {
104: 		return nil, err
105: 	}
106: 	states := r.sampleInterfaceStates(ctx, running)
107: 
108: 	result := make([]*clabtypes.ContainerInterfaces, 0, len(running))
109: 	for _, location := range running {
110: 		container := &clabtypes.ContainerInterfaces{
111: 			ContainerName: req.Name + "-" + location.NodeName,
112: 			Interfaces:    []*clabtypes.ContainerInterfaceDetails{},
113: 		}
114: 		for _, entry := range listed[location.NodeName] {
115: 			details := &clabtypes.ContainerInterfaceDetails{
116: 				InterfaceName:  entry.Interface,
117: 				InterfaceAlias: entry.Alias,
118: 				// clabwire realizes every lab link interface as a veth pair
119: 				InterfaceType: "veth",
120: 			}
121: 			if state, ok := states[location.NodeName][entry.Interface]; ok {
122: 				details.InterfaceMAC = state.MAC
123: 				details.InterfaceIndex = state.Index
124: 				details.InterfaceMTU = state.MTU
125: 				details.InterfaceState = state.OperState
126: 			}
127: 			container.Interfaces = append(container.Interfaces, details)
128: 		}
129: 		sort.Slice(container.Interfaces, func(i, j int) bool {
130: 			return container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName
131: 		})
132: 		result = append(result, container)
133: 	}
134: 	sort.Slice(result, func(i, j int) bool {
135: 		return result[i].ContainerName < result[j].ContainerName
136: 	})
137: 
138: 	return result, nil
139: }
140: 
141: // sampleInterfaceStates reads the sysfs interface attributes of every node's device container,
142: // one exec per node, with the script the interface events use.
143: func (r *Runtime) sampleInterfaceStates(
144: 	ctx context.Context,
145: 	locations []clablabruntime.NodeLocation,
146: ) map[string]map[string]c9sIfaceState {
147: 	var mu sync.Mutex
148: 	result := map[string]map[string]c9sIfaceState{}
149: 
150: 	var wg sync.WaitGroup
151: 	workers := make(chan struct{}, interfaceSampleWorkers)
152: 	exec := r.execInPodContainer()
153: 	for _, location := range locations {
154: 		wg.Add(1)
155: 		go func() {
156: 			defer wg.Done()
157: 			workers <- struct{}{}
158: 			defer func() { <-workers }()
159: 
160: 			var stdout, stderr bytes.Buffer
161: 			err := exec(ctx, location.Namespace, location.Pod, location.Container,
162: 				[]string{"sh", "-c", interfaceSampleScript}, nil, &stdout, &stderr)
163: 			if err != nil {
164: 				log.Debug("Cannot read the interface state of a c9s node",
165: 					"node", location.NodeName, "error", err)
166: 				return
167: 			}
168: 			_, ifaces, _, err := parseInterfaceSample(stdout.Bytes())
169: 			if err != nil {
170: 				log.Debug("Cannot parse the interface state of a c9s node",
171: 					"node", location.NodeName, "error", err)
172: 				return
173: 			}
174: 
175: 			byName := make(map[string]c9sIfaceState, len(ifaces))
176: 			for _, iface := range ifaces {
177: 				byName[iface.Name] = iface
178: 			}
179: 			mu.Lock()
180: 			result[location.NodeName] = byName
181: 			mu.Unlock()
182: 		}()
183: 	}
184: 	wg.Wait()
185: 
186: 	return result
187: }

(End of file - total 187 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196534dc7001wyadqXfcsUmwwG",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196533ca2001DbAdTJgSwNGYuM",
  "callID": "call_5ffdde6d9a5240978c2c0b26",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/capture_interfaces.go"
    },
    "output": "<path>/source/head/labruntime/clabernetes/capture_interfaces.go</path>\n<type>file</type>\n<content>\n1: package clabernetes\n2: \n3: import (\n4: \t\"bytes\"\n5: \t\"context\"\n6: \t\"errors\"\n7: \t\"fmt\"\n8: \t\"io\"\n9: \t\"sort\"\n10: \t\"sync\"\n11: \n12: \t\"github.com/charmbracelet/log\"\n13: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n14: \tclabtypes \"github.com/srl-labs/containerlab/types\"\n15: \tcorev1 \"k8s.io/api/core/v1\"\n16: \t\"k8s.io/client-go/kubernetes/scheme\"\n17: \t\"k8s.io/client-go/tools/remotecommand\"\n18: \tkubeexec \"k8s.io/client-go/util/exec\"\n19: )\n20: \n21: // streamPodExec runs a command in a pod container without a terminal and streams its stdout\n22: // and stderr. A non-nil stdin is attached: when it ends, the process's stdin is closed (the\n23: // websocket v5 close signal, or a half-closed SPDY stream). A nonzero exit returns a\n24: // *labruntime.CommandExitError.\n25: func (r *Runtime) streamPodExec(\n26: \tctx context.Context,\n27: \tnamespace, pod, container string,\n28: \tcommand []string,\n29: \tstdin io.Reader,\n30: \tstdout, stderr io.Writer,\n31: ) error {\n32: \texecURL := r.kubeClient.CoreV1().RESTClient().Post().\n33: \t\tResource(\"pods\").\n34: \t\tName(pod).\n35: \t\tNamespace(namespace).\n36: \t\tSubResource(\"exec\").\n37: \t\tVersionedParams(&corev1.PodExecOptions{\n38: \t\t\tContainer: container,\n39: \t\t\tCommand:   command,\n40: \t\t\tStdin:     stdin != nil,\n41: \t\t\tStdout:    stdout != nil,\n42: \t\t\tStderr:    stderr != nil,\n43: \t\t}, scheme.ParameterCodec).URL()\n44: \n45: \texecutor, err := r.newExecutor(execURL)\n46: \tif err != nil {\n47: \t\treturn err\n48: \t}\n49: \n50: \t// client-go reports streams cut by a cancelled context through the context's logger; a\n51: \t// capture ends that way on purpose, so it goes to the debug log\n52: \terr = executor.StreamWithContext(withKubernetesClientDebugLogs(ctx),\n53: \t\tremotecommand.StreamOptions{\n54: \t\t\tStdin:  stdin,\n55: \t\t\tStdout: stdout,\n56: \t\t\tStderr: stderr,\n57: \t\t})\n58: \n59: \tvar exitErr kubeexec.ExitError\n60: \tif errors.As(err, &exitErr) {\n61: \t\treturn &clablabruntime.CommandExitError{Code: exitErr.ExitStatus()}\n62: \t}\n63: \tif err != nil {\n64: \t\treturn fmt.Errorf(\"failed to execute command in pod %s/%s container %s: %w\",\n65: \t\t\tnamespace, pod, container, err)\n66: \t}\n67: \n68: \treturn nil\n69: }\n70: \n71: // InspectInterfaces lists the capturable link interfaces of the requested nodes, or of every\n72: // running node, in the shape of `inspect interfaces`: per node (named <lab>-<node> like in\n73: // inspect), the interface and its alias as clabwire reports them, and the MAC address, index,\n74: // MTU and operational state read from sysfs in the device container. A node whose device\n75: // container has no shell reports its interfaces without these attributes.\n76: func (r *Runtime) InspectInterfaces(\n77: \tctx context.Context,\n78: \treq clablabruntime.NodeRequest,\n79: ) ([]*clabtypes.ContainerInterfaces, error) {\n80: \tr, err := r.connect(ctx, req.Identity)\n81: \tif err != nil {\n82: \t\treturn nil, err\n83: \t}\n84: \n85: \tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n86: \t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n87: \t})\n88: \tif err != nil {\n89: \t\treturn nil, err\n90: \t}\n91: \n92: \trunning := make([]clablabruntime.NodeLocation, 0, len(locations))\n93: \tfor _, location := range locations {\n94: \t\tif location.Pod == \"\" {\n95: \t\t\tlog.Warn(\"Skipping interface detection of a node that does not run\",\n96: \t\t\t\t\"node\", location.NodeName)\n97: \t\t\tcontinue\n98: \t\t}\n99: \t\trunning = append(running, location)\n100: \t}\n101: \n102: \tlisted, err := r.listCaptureInterfaces(ctx, req.Name, running)\n103: \tif err != nil {\n104: \t\treturn nil, err\n105: \t}\n106: \tstates := r.sampleInterfaceStates(ctx, running)\n107: \n108: \tresult := make([]*clabtypes.ContainerInterfaces, 0, len(running))\n109: \tfor _, location := range running {\n110: \t\tcontainer := &clabtypes.ContainerInterfaces{\n111: \t\t\tContainerName: req.Name + \"-\" + location.NodeName,\n112: \t\t\tInterfaces:    []*clabtypes.ContainerInterfaceDetails{},\n113: \t\t}\n114: \t\tfor _, entry := range listed[location.NodeName] {\n115: \t\t\tdetails := &clabtypes.ContainerInterfaceDetails{\n116: \t\t\t\tInterfaceName:  entry.Interface,\n117: \t\t\t\tInterfaceAlias: entry.Alias,\n118: \t\t\t\t// clabwire realizes every lab link interface as a veth pair\n119: \t\t\t\tInterfaceType: \"veth\",\n120: \t\t\t}\n121: \t\t\tif state, ok := states[location.NodeName][entry.Interface]; ok {\n122: \t\t\t\tdetails.InterfaceMAC = state.MAC\n123: \t\t\t\tdetails.InterfaceIndex = state.Index\n124: \t\t\t\tdetails.InterfaceMTU = state.MTU\n125: \t\t\t\tdetails.InterfaceState = state.OperState\n126: \t\t\t}\n127: \t\t\tcontainer.Interfaces = append(container.Interfaces, details)\n128: \t\t}\n129: \t\tsort.Slice(container.Interfaces, func(i, j int) bool {\n130: \t\t\treturn container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName\n131: \t\t})\n132: \t\tresult = append(result, container)\n133: \t}\n134: \tsort.Slice(result, func(i, j int) bool {\n135: \t\treturn result[i].ContainerName < result[j].ContainerName\n136: \t})\n137: \n138: \treturn result, nil\n139: }\n140: \n141: // sampleInterfaceStates reads the sysfs interface attributes of every node's device container,\n142: // one exec per node, with the script the interface events use.\n143: func (r *Runtime) sampleInterfaceStates(\n144: \tctx context.Context,\n145: \tlocations []clablabruntime.NodeLocation,\n146: ) map[string]map[string]c9sIfaceState {\n147: \tvar mu sync.Mutex\n148: \tresult := map[string]map[string]c9sIfaceState{}\n149: \n150: \tvar wg sync.WaitGroup\n151: \tworkers := make(chan struct{}, interfaceSampleWorkers)\n152: \texec := r.execInPodContainer()\n153: \tfor _, location := range locations {\n154: \t\twg.Add(1)\n155: \t\tgo func() {\n156: \t\t\tdefer wg.Done()\n157: \t\t\tworkers <- struct{}{}\n158: \t\t\tdefer func() { <-workers }()\n159: \n160: \t\t\tvar stdout, stderr bytes.Buffer\n161: \t\t\terr := exec(ctx, location.Namespace, location.Pod, location.Container,\n162: \t\t\t\t[]string{\"sh\", \"-c\", interfaceSampleScript}, nil, &stdout, &stderr)\n163: \t\t\tif err != nil {\n164: \t\t\t\tlog.Debug(\"Cannot read the interface state of a c9s node\",\n165: \t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n166: \t\t\t\treturn\n167: \t\t\t}\n168: \t\t\t_, ifaces, _, err := parseInterfaceSample(stdout.Bytes())\n169: \t\t\tif err != nil {\n170: \t\t\t\tlog.Debug(\"Cannot parse the interface state of a c9s node\",\n171: \t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n172: \t\t\t\treturn\n173: \t\t\t}\n174: \n175: \t\t\tbyName := make(map[string]c9sIfaceState, len(ifaces))\n176: \t\t\tfor _, iface := range ifaces {\n177: \t\t\t\tbyName[iface.Name] = iface\n178: \t\t\t}\n179: \t\t\tmu.Lock()\n180: \t\t\tresult[location.NodeName] = byName\n181: \t\t\tmu.Unlock()\n182: \t\t}()\n183: \t}\n184: \twg.Wait()\n185: \n186: \treturn result\n187: }\n\n(End of file - total 187 lines)\n</content>",
    "title": "source/head/labruntime/clabernetes/capture_interfaces.go",
    "metadata": {
      "preview": "package clabernetes\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\t\"sync\"\n\n\t\"github.com/charmbracelet/log\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\tclabtypes \"github.com/srl-labs/containerlab/types\"\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/client-go/kubernetes/scheme\"\n\t\"k8s.io/client-go/tools/remotecommand\"\n\tkubeexec \"k8s.io/client-go/util/exec\"\n)\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/capture_interfaces.go",
        "text": "package clabernetes\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\t\"sync\"\n\n\t\"github.com/charmbracelet/log\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\tclabtypes \"github.com/srl-labs/containerlab/types\"\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/client-go/kubernetes/scheme\"\n\t\"k8s.io/client-go/tools/remotecommand\"\n\tkubeexec \"k8s.io/client-go/util/exec\"\n)\n\n// streamPodExec runs a command in a pod container without a terminal and streams its stdout\n// and stderr. A non-nil stdin is attached: when it ends, the process's stdin is closed (the\n// websocket v5 close signal, or a half-closed SPDY stream). A nonzero exit returns a\n// *labruntime.CommandExitError.\nfunc (r *Runtime) streamPodExec(\n\tctx context.Context,\n\tnamespace, pod, container string,\n\tcommand []string,\n\tstdin io.Reader,\n\tstdout, stderr io.Writer,\n) error {\n\texecURL := r.kubeClient.CoreV1().RESTClient().Post().\n\t\tResource(\"pods\").\n\t\tName(pod).\n\t\tNamespace(namespace).\n\t\tSubResource(\"exec\").\n\t\tVersionedParams(&corev1.PodExecOptions{\n\t\t\tContainer: container,\n\t\t\tCommand:   command,\n\t\t\tStdin:     stdin != nil,\n\t\t\tStdout:    stdout != nil,\n\t\t\tStderr:    stderr != nil,\n\t\t}, scheme.ParameterCodec).URL()\n\n\texecutor, err := r.newExecutor(execURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// client-go reports streams cut by a cancelled context through the context's logger; a\n\t// capture ends that way on purpose, so it goes to the debug log\n\terr = executor.StreamWithContext(withKubernetesClientDebugLogs(ctx),\n\t\tremotecommand.StreamOptions{\n\t\t\tStdin:  stdin,\n\t\t\tStdout: stdout,\n\t\t\tStderr: stderr,\n\t\t})\n\n\tvar exitErr kubeexec.ExitError\n\tif errors.As(err, &exitErr) {\n\t\treturn &clablabruntime.CommandExitError{Code: exitErr.ExitStatus()}\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to execute command in pod %s/%s container %s: %w\",\n\t\t\tnamespace, pod, container, err)\n\t}\n\n\treturn nil\n}\n\n// InspectInterfaces lists the capturable link interfaces of the requested nodes, or of every\n// running node, in the shape of `inspect interfaces`: per node (named <lab>-<node> like in\n// inspect), the interface and its alias as clabwire reports them, and the MAC address, index,\n// MTU and operational state read from sysfs in the device container. A node whose device\n// container has no shell reports its interfaces without these attributes.\nfunc (r *Runtime) InspectInterfaces(\n\tctx context.Context,\n\treq clablabruntime.NodeRequest,\n) ([]*clabtypes.ContainerInterfaces, error) {\n\tr, err := r.connect(ctx, req.Identity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n\t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trunning := make([]clablabruntime.NodeLocation, 0, len(locations))\n\tfor _, location := range locations {\n\t\tif location.Pod == \"\" {\n\t\t\tlog.Warn(\"Skipping interface detection of a node that does not run\",\n\t\t\t\t\"node\", location.NodeName)\n\t\t\tcontinue\n\t\t}\n\t\trunning = append(running, location)\n\t}\n\n\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, running)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstates := r.sampleInterfaceStates(ctx, running)\n\n\tresult := make([]*clabtypes.ContainerInterfaces, 0, len(running))\n\tfor _, location := range running {\n\t\tcontainer := &clabtypes.ContainerInterfaces{\n\t\t\tContainerName: req.Name + \"-\" + location.NodeName,\n\t\t\tInterfaces:    []*clabtypes.ContainerInterfaceDetails{},\n\t\t}\n\t\tfor _, entry := range listed[location.NodeName] {\n\t\t\tdetails := &clabtypes.ContainerInterfaceDetails{\n\t\t\t\tInterfaceName:  entry.Interface,\n\t\t\t\tInterfaceAlias: entry.Alias,\n\t\t\t\t// clabwire realizes every lab link interface as a veth pair\n\t\t\t\tInterfaceType: \"veth\",\n\t\t\t}\n\t\t\tif state, ok := states[location.NodeName][entry.Interface]; ok {\n\t\t\t\tdetails.InterfaceMAC = state.MAC\n\t\t\t\tdetails.InterfaceIndex = state.Index\n\t\t\t\tdetails.InterfaceMTU = state.MTU\n\t\t\t\tdetails.InterfaceState = state.OperState\n\t\t\t}\n\t\t\tcontainer.Interfaces = append(container.Interfaces, details)\n\t\t}\n\t\tsort.Slice(container.Interfaces, func(i, j int) bool {\n\t\t\treturn container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName\n\t\t})\n\t\tresult = append(result, container)\n\t}\n\tsort.Slice(result, func(i, j int) bool {\n\t\treturn result[i].ContainerName < result[j].ContainerName\n\t})\n\n\treturn result, nil\n}\n\n// sampleInterfaceStates reads the sysfs interface attributes of every node's device container,\n// one exec per node, with the script the interface events use.\nfunc (r *Runtime) sampleInterfaceStates(\n\tctx context.Context,\n\tlocations []clablabruntime.NodeLocation,\n) map[string]map[string]c9sIfaceState {\n\tvar mu sync.Mutex\n\tresult := map[string]map[string]c9sIfaceState{}\n\n\tvar wg sync.WaitGroup\n\tworkers := make(chan struct{}, interfaceSampleWorkers)\n\texec := r.execInPodContainer()\n\tfor _, location := range locations {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tworkers <- struct{}{}\n\t\t\tdefer func() { <-workers }()\n\n\t\t\tvar stdout, stderr bytes.Buffer\n\t\t\terr := exec(ctx, location.Namespace, location.Pod, location.Container,\n\t\t\t\t[]string{\"sh\", \"-c\", interfaceSampleScript}, nil, &stdout, &stderr)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"Cannot read the interface state of a c9s node\",\n\t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t_, ifaces, _, err := parseInterfaceSample(stdout.Bytes())\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"Cannot parse the interface state of a c9s node\",\n\t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tbyName := make(map[string]c9sIfaceState, len(ifaces))\n\t\t\tfor _, iface := range ifaces {\n\t\t\t\tbyName[iface.Name] = iface\n\t\t\t}\n\t\t\tmu.Lock()\n\t\t\tresult[location.NodeName] = byName\n\t\t\tmu.Unlock()\n\t\t}()\n\t}\n\twg.Wait()\n\n\treturn result\n}",
        "lineStart": 1,
        "lineEnd": 187,
        "totalLines": 187,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523404235,
      "end": 1793523404247
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196534dd90019MW9wGFLpiVeRP",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196533ca2001DbAdTJgSwNGYuM",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 74559,
    "input": 1053,
    "output": 45,
    "reasoning": 373,
    "cache": {
      "read": 73088,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196533ca2001DbAdTJgSwNGYuM",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523399842,
    "completed": 1793523404252
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 74559,
    "input": 1053,
    "output": 45,
    "reasoning": 373,
    "cache": {
      "read": 73088,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 38
step-start
{
  "type": "step-start",
  "id": "prt_196536126001krtZ1vtL1tv4bW",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196534de3001UGgBavNO6PpMwe"
}
Reasoning
All looks solid. Now check the capture tests and remaining diff regions I haven't seen: diff lines 1-2160 (workflows + capture package files including tests). Let me read the diff for the capture package tests (pcapng_test, reorder_test, local_test) — skim to confirm coverage. Lines 37-2160. Let me read in chunks quickly focusing on test coverage claims.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 400,
  "offset": 1
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1: diff --git a/.github/workflows/clabernetes-tests.yml b/.github/workflows/clabernetes-tests.yml
2: index b1cbd00..7785167 100644
3: --- a/.github/workflows/clabernetes-tests.yml
4: +++ b/.github/workflows/clabernetes-tests.yml
5: @@ -100,10 +100,15 @@ jobs:
6:              upgrade --install --create-namespace --namespace c9s \
7:                clabernetes oci://ghcr.io/clabernetes/clabernetes/clabernetes:0.0.0
8:  
9:            kubectl -n c9s rollout status deploy/clabernetes-manager --timeout=180s
10:  
11: +      - name: Install tshark
12: +        run: |
13: +          sudo apt-get update
14: +          sudo DEBIAN_FRONTEND=noninteractive apt-get install -y tshark
15: +
16:        - name: Run Clabernetes Robot tests
17:          run: |
18:            bash ./tests/rf-run.sh c9s ./tests/14-clabernetes
19:  
20:        - name: Upload test report
21: diff --git a/.github/workflows/smoke-tests.yml b/.github/workflows/smoke-tests.yml
22: index 807acbe..f7ee3c8 100644
23: --- a/.github/workflows/smoke-tests.yml
24: +++ b/.github/workflows/smoke-tests.yml
25: @@ -51,10 +51,11 @@ jobs:
26:            - "28*.robot"
27:            - "29*.robot"
28:            - "30*.robot"
29:            - "31*.robot"
30:            - "32*.robot"
31: +          - "33*.robot"
32:  
33:      # allow podman job to fail, since it started to fail on github actions
34:      continue-on-error: ${{ inputs.runtime == 'podman' }}
35:      steps:
36:        - name: Checkout
37: diff --git a/capture/local.go b/capture/local.go
38: new file mode 100644
39: index 0000000..58dc8aa
40: --- /dev/null
41: +++ b/capture/local.go
42: @@ -0,0 +1,430 @@
43: +package capture
44: +
45: +import (
46: +	"context"
47: +	"errors"
48: +	"fmt"
49: +	"io"
50: +	"os"
51: +	"sync"
52: +	"time"
53: +
54: +	"github.com/charmbracelet/log"
55: +	"github.com/containernetworking/plugins/pkg/ns"
56: +	"github.com/gopacket/gopacket"
57: +	"github.com/gopacket/gopacket/afpacket"
58: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
59: +)
60: +
61: +const (
62: +	// localReorderWindow is how long the merged stream holds packets of local sockets back to
63: +	// write them in timestamp order. Each socket hands over its packets within
64: +	// localBlockTimeout, so a few times that covers the delivery skew between sockets.
65: +	localReorderWindow = 100 * time.Millisecond
66: +	// localBlockTimeout is how long the kernel fills a ring block before it hands it over.
67: +	localBlockTimeout = 10 * time.Millisecond
68: +	// localPollTimeout is how often a socket reader checks whether the capture ended.
69: +	localPollTimeout = 100 * time.Millisecond
70: +	// localReopenInterval is how often a reader tries to reopen the socket of an interface
71: +	// that went down or disappeared.
72: +	localReopenInterval = 200 * time.Millisecond
73: +	// localDrainQuiet is how long after the end of a capture a reader keeps waiting for packets
74: +	// still in the socket's ring: the kernel hands over a block within two block timeouts.
75: +	localDrainQuiet = 5 * localBlockTimeout
76: +	// localDrainTimeout bounds the drain while packets keep arriving.
77: +	localDrainTimeout = 250 * time.Millisecond
78: +	// localRingBlocks and localMinBlockSize size the receive ring of each socket: eight blocks
79: +	// of at least 1 MiB, each larger than the snap length.
80: +	localRingBlocks   = 8
81: +	localMinBlockSize = 1 << 20
82: +	// vlanHeaderLength is the length of the 802.1Q tag put back into frames whose tag the
83: +	// kernel moved out of band.
84: +	vlanHeaderLength = 4
85: +)
86: +
87: +// errReadTimeout is returned by a packet source that has no packet within the poll timeout.
88: +var errReadTimeout = errors.New("no packet within the poll timeout")
89: +
90: +// ExecFunc runs f in the network namespace of a node.
91: +type ExecFunc func(ctx context.Context, f func(ns.NetNS) error) error
92: +
93: +// LocalTarget is one interface of a node on this machine (Docker or Podman) to capture.
94: +type LocalTarget struct {
95: +	// Node is the node name as the topology spells it.
96: +	Node string
97: +	// Interface is the interface name inside the node.
98: +	Interface string
99: +	// Exec runs a function in the node's network namespace.
100: +	Exec ExecFunc
101: +}
102: +
103: +// packetSource reads the packets of one interface.
104: +type packetSource interface {
105: +	// ReadPacket returns the next packet; the data is only valid until the next call. It
106: +	// returns errReadTimeout when no packet arrived within the poll timeout.
107: +	ReadPacket() ([]byte, gopacket.CaptureInfo, error)
108: +	Close()
109: +}
110: +
111: +// openSourcesFunc opens one packet source per interface in the network namespace exec enters.
112: +type openSourcesFunc func(
113: +	ctx context.Context,
114: +	exec ExecFunc,
115: +	interfaces []string,
116: +	snapLength int,
117: +) ([]packetSource, error)
118: +
119: +// CaptureLocal streams pcapng from interfaces of nodes on this machine to w, with the same
120: +// output and end conditions as labruntime.PacketCapturer.Capture: one section, one Interface
121: +// Description Block per target named <node>:<interface>, then the packets of every target in
122: +// timestamp order. targets lists the interfaces of req.Targets, resolved, in the same order.
123: +//
124: +// Each interface is read through a packet socket opened in the node's network namespace, so
125: +// nothing runs in the node and the node image needs no capture tools; it needs CAP_NET_RAW and
126: +// the right to enter the namespace, so root. An interface that goes down is reopened once it is
127: +// up again; one that disappears (its node stopped or was recreated) is reattached when it is
128: +// back, and the time it was gone is reported as a gap through req.OnGap (or logged).
129: +func CaptureLocal(
130: +	ctx context.Context,
131: +	req clablabruntime.CaptureRequest,
132: +	targets []LocalTarget,
133: +	w io.Writer,
134: +) error {
135: +	return localCapture{
136: +		open:           openPacketSockets,
137: +		window:         localReorderWindow,
138: +		reopenInterval: localReopenInterval,
139: +	}.run(ctx, req, targets, w)
140: +}
141: +
142: +// localCapture is a local capture with its socket opener and timings, which tests replace.
143: +type localCapture struct {
144: +	open           openSourcesFunc
145: +	window         time.Duration
146: +	reopenInterval time.Duration
147: +}
148: +
149: +func (l localCapture) run(
150: +	ctx context.Context,
151: +	req clablabruntime.CaptureRequest,
152: +	targets []LocalTarget,
153: +	w io.Writer,
154: +) error {
155: +	if err := ValidateRequest(&req); err != nil {
156: +		return err
157: +	}
158: +	if len(targets) != len(req.Targets) {
159: +		return fmt.Errorf("capture has %d resolved targets for %d requested ones",
160: +			len(targets), len(req.Targets))
161: +	}
162: +
163: +	sources, err := l.openAll(ctx, targets, req.SnapLength)
164: +	if err != nil {
165: +		return err
166: +	}
167: +
168: +	names := make([]string, len(targets))
169: +	for idx, target := range targets {
170: +		names[idx] = target.Node + ":" + target.Interface
171: +	}
172: +
173: +	captureCtx, stop := context.WithCancel(ctx)
174: +	defer stop()
175: +	if req.Duration > 0 {
176: +		var cancelTimeout context.CancelFunc
177: +		captureCtx, cancelTimeout = context.WithTimeout(captureCtx, req.Duration)
178: +		defer cancelTimeout()
179: +	}
180: +
181: +	out, err := NewOutput(w, names, req.SnapLength, req.PacketLimit, l.window, stop)
182: +	if err != nil {
183: +		for _, source := range sources {
184: +			source.Close()
185: +		}
186: +
187: +		return err
188: +	}
189: +
190: +	var wg sync.WaitGroup
191: +	for idx, source := range sources {
192: +		reader := &localReader{
193: +			capture: l,
194: +			out:     out,
195: +			id:      uint32(idx), //nolint:gosec // bounded by the targets
196: +			target:  targets[idx],
197: +			snap:    req.SnapLength,
198: +			onGap:   req.OnGap,
199: +		}
200: +		wg.Go(func() {
201: +			reader.run(captureCtx, source)
202: +		})
203: +	}
204: +	wg.Wait()
205: +
206: +	return out.Close()
207: +}
208: +
209: +// openAll opens the sockets of every target before anything is written, one namespace entry
210: +// per node, so a capture that cannot start fails without output.
211: +func (l localCapture) openAll(
212: +	ctx context.Context,
213: +	targets []LocalTarget,
214: +	snapLength int,
215: +) ([]packetSource, error) {
216: +	type nodeTargets struct {
217: +		exec    ExecFunc
218: +		indexes []int
219: +		names   []string
220: +	}
221: +	var order []string
222: +	byNode := map[string]*nodeTargets{}
223: +	for idx, target := range targets {
224: +		group := byNode[target.Node]
225: +		if group == nil {
226: +			group = &nodeTargets{exec: target.Exec}
227: +			byNode[target.Node] = group
228: +			order = append(order, target.Node)
229: +		}
230: +		group.indexes = append(group.indexes, idx)
231: +		group.names = append(group.names, target.Interface)
232: +	}
233: +
234: +	sources := make([]packetSource, len(targets))
235: +	closeAll := func() {
236: +		for _, source := range sources {
237: +			if source != nil {
238: +				source.Close()
239: +			}
240: +		}
241: +	}
242: +	for _, node := range order {
243: +		group := byNode[node]
244: +		opened, err := l.open(ctx, group.exec, group.names, snapLength)
245: +		if err != nil {
246: +			closeAll()
247: +			return nil, fmt.Errorf("failed to start the capture on node %q: %w", node, err)
248: +		}
249: +		for idx, source := range opened {
250: +			sources[group.indexes[idx]] = source
251: +		}
252: +	}
253: +
254: +	return sources, nil
255: +}
256: +
257: +// localReader reads one interface into the merged stream.
258: +type localReader struct {
259: +	capture localCapture
260: +	out     *Output
261: +	id      uint32
262: +	target  LocalTarget
263: +	snap    int
264: +	onGap   func(clablabruntime.CaptureGap)
265: +}
266: +
267: +func (r *localReader) run(ctx context.Context, source packetSource) {
268: +	defer func() {
269: +		if source != nil {
270: +			source.Close()
271: +		}
272: +	}()
273: +
274: +	for {
275: +		if ctx.Err() != nil {
276: +			r.drain(source, time.Now())
277: +			return
278: +		}
279: +
280: +		data, info, err := source.ReadPacket()
281: +		if errors.Is(err, errReadTimeout) {
282: +			continue
283: +		}
284: +		if err != nil {
285: +			// The socket reports an error once its interface went down or was removed, and
286: +			// keeps reporting it: it is reopened.
287: +			log.Debug("Capture socket failed, reopening it", "node", r.target.Node,
288: +				"interface", r.target.Interface, "error", err)
289: +			source.Close()
290: +			source = r.reopen(ctx)
291: +			if source == nil {
292: +				return
293: +			}
294: +
295: +			continue
296: +		}
297: +
298: +		if more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {
299: +			return
300: +		}
301: +	}
302: +}
303: +
304: +// drain writes the packets that arrived before end but were still in the socket's ring: the
305: +// kernel hands over a ring block once it is full or its block timeout passed, so the last
306: +// packets before a capture ended may not have been read yet.
307: +func (r *localReader) drain(source packetSource, end time.Time) {
308: +	deadline := end.Add(localDrainTimeout)
309: +	for time.Now().Before(deadline) {
310: +		data, info, err := source.ReadPacket()
311: +		if errors.Is(err, errReadTimeout) && time.Since(end) < localDrainQuiet {
312: +			continue
313: +		}
314: +		if err != nil || info.Timestamp.After(end) {
315: +			return
316: +		}
317: +		if more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {
318: +			return
319: +		}
320: +	}
321: +}
322: +
323: +// packet copies a packet out of the socket's ring, cut to the snap length.
324: +func (r *localReader) packet(data []byte, info gopacket.CaptureInfo) *Packet {
325: +	length := info.Length
326: +	for _, ancillary := range info.AncillaryData {
327: +		if _, ok := ancillary.(afpacket.AncillaryVLAN); ok {
328: +			// the tag was put back into the data and counts toward the frame length
329: +			length += vlanHeaderLength
330: +			break
331: +		}
332: +	}
333: +	length = max(length, len(data))
334: +
335: +	captured := make([]byte, min(len(data), r.snap))
336: +	copy(captured, data)
337: +
338: +	return &Packet{
339: +		Timestamp:      info.Timestamp.UnixNano(),
340: +		OriginalLength: uint32(length), //nolint:gosec // bounded by the interface MTU
341: +		Data:           captured,
342: +	}
343: +}
344: +
345: +// reopen opens the interface's socket again once its node and interface are back. It returns
346: +// nil when the capture ended first. Time the interface could not be opened is reported as a gap;
347: +// an interface that only went down is not, as it has no traffic while down.
348: +func (r *localReader) reopen(ctx context.Context) packetSource {
349: +	from := time.Now()
350: +	var unavailable error
351: +
352: +	timer := time.NewTimer(r.capture.reopenInterval)
353: +	defer timer.Stop()
354: +
355: +	for {
356: +		select {
357: +		case <-ctx.Done():
358: +			if unavailable != nil {
359: +				r.reportGap(from, time.Time{}, unavailable)
360: +			}
361: +
362: +			return nil
363: +		case <-timer.C:
364: +		}
365: +
366: +		opened, err := r.capture.open(ctx, r.target.Exec, []string{r.target.Interface}, r.snap)
367: +		if err != nil {
368: +			if unavailable == nil {
369: +				log.Debug("Capture interface is not available, waiting for it",
370: +					"node", r.target.Node, "interface", r.target.Interface, "error", err)
371: +			}
372: +			unavailable = err
373: +			resetTimer(timer, r.capture.reopenInterval)
374: +
375: +			continue
376: +		}
377: +		if unavailable != nil {
378: +			r.reportGap(from, time.Now(), unavailable)
379: +		}
380: +
381: +		return opened[0]
382: +	}
383: +}
384: +
385: +func (r *localReader) reportGap(from, to time.Time, cause error) {
386: +	ReportGap(r.onGap, clablabruntime.CaptureGap{
387: +		Node:       r.target.Node,
388: +		Interfaces: []string{r.target.Interface},
389: +		From:       from,
390: +		To:         to,
391: +		Reason:     fmt.Sprintf("the interface was not available: %v", cause),
392: +	})
393: +}
394: +
395: +// openPacketSockets opens one packet socket per interface in the namespace exec enters. A socket
396: +// stays bound to its interface after the thread left the namespace.
397: +func openPacketSockets(
398: +	ctx context.Context,
399: +	exec ExecFunc,
400: +	interfaces []string,

(Showing lines 1-400 of 7018. Use offset=401 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196536396001QyzBB0nL12edPV",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196534de3001UGgBavNO6PpMwe",
  "callID": "call_9132d41d608049678a2b06f6",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 400,
      "offset": 1
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n1: diff --git a/.github/workflows/clabernetes-tests.yml b/.github/workflows/clabernetes-tests.yml\n2: index b1cbd00..7785167 100644\n3: --- a/.github/workflows/clabernetes-tests.yml\n4: +++ b/.github/workflows/clabernetes-tests.yml\n5: @@ -100,10 +100,15 @@ jobs:\n6:              upgrade --install --create-namespace --namespace c9s \\\n7:                clabernetes oci://ghcr.io/clabernetes/clabernetes/clabernetes:0.0.0\n8:  \n9:            kubectl -n c9s rollout status deploy/clabernetes-manager --timeout=180s\n10:  \n11: +      - name: Install tshark\n12: +        run: |\n13: +          sudo apt-get update\n14: +          sudo DEBIAN_FRONTEND=noninteractive apt-get install -y tshark\n15: +\n16:        - name: Run Clabernetes Robot tests\n17:          run: |\n18:            bash ./tests/rf-run.sh c9s ./tests/14-clabernetes\n19:  \n20:        - name: Upload test report\n21: diff --git a/.github/workflows/smoke-tests.yml b/.github/workflows/smoke-tests.yml\n22: index 807acbe..f7ee3c8 100644\n23: --- a/.github/workflows/smoke-tests.yml\n24: +++ b/.github/workflows/smoke-tests.yml\n25: @@ -51,10 +51,11 @@ jobs:\n26:            - \"28*.robot\"\n27:            - \"29*.robot\"\n28:            - \"30*.robot\"\n29:            - \"31*.robot\"\n30:            - \"32*.robot\"\n31: +          - \"33*.robot\"\n32:  \n33:      # allow podman job to fail, since it started to fail on github actions\n34:      continue-on-error: ${{ inputs.runtime == 'podman' }}\n35:      steps:\n36:        - name: Checkout\n37: diff --git a/capture/local.go b/capture/local.go\n38: new file mode 100644\n39: index 0000000..58dc8aa\n40: --- /dev/null\n41: +++ b/capture/local.go\n42: @@ -0,0 +1,430 @@\n43: +package capture\n44: +\n45: +import (\n46: +\t\"context\"\n47: +\t\"errors\"\n48: +\t\"fmt\"\n49: +\t\"io\"\n50: +\t\"os\"\n51: +\t\"sync\"\n52: +\t\"time\"\n53: +\n54: +\t\"github.com/charmbracelet/log\"\n55: +\t\"github.com/containernetworking/plugins/pkg/ns\"\n56: +\t\"github.com/gopacket/gopacket\"\n57: +\t\"github.com/gopacket/gopacket/afpacket\"\n58: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n59: +)\n60: +\n61: +const (\n62: +\t// localReorderWindow is how long the merged stream holds packets of local sockets back to\n63: +\t// write them in timestamp order. Each socket hands over its packets within\n64: +\t// localBlockTimeout, so a few times that covers the delivery skew between sockets.\n65: +\tlocalReorderWindow = 100 * time.Millisecond\n66: +\t// localBlockTimeout is how long the kernel fills a ring block before it hands it over.\n67: +\tlocalBlockTimeout = 10 * time.Millisecond\n68: +\t// localPollTimeout is how often a socket reader checks whether the capture ended.\n69: +\tlocalPollTimeout = 100 * time.Millisecond\n70: +\t// localReopenInterval is how often a reader tries to reopen the socket of an interface\n71: +\t// that went down or disappeared.\n72: +\tlocalReopenInterval = 200 * time.Millisecond\n73: +\t// localDrainQuiet is how long after the end of a capture a reader keeps waiting for packets\n74: +\t// still in the socket's ring: the kernel hands over a block within two block timeouts.\n75: +\tlocalDrainQuiet = 5 * localBlockTimeout\n76: +\t// localDrainTimeout bounds the drain while packets keep arriving.\n77: +\tlocalDrainTimeout = 250 * time.Millisecond\n78: +\t// localRingBlocks and localMinBlockSize size the receive ring of each socket: eight blocks\n79: +\t// of at least 1 MiB, each larger than the snap length.\n80: +\tlocalRingBlocks   = 8\n81: +\tlocalMinBlockSize = 1 << 20\n82: +\t// vlanHeaderLength is the length of the 802.1Q tag put back into frames whose tag the\n83: +\t// kernel moved out of band.\n84: +\tvlanHeaderLength = 4\n85: +)\n86: +\n87: +// errReadTimeout is returned by a packet source that has no packet within the poll timeout.\n88: +var errReadTimeout = errors.New(\"no packet within the poll timeout\")\n89: +\n90: +// ExecFunc runs f in the network namespace of a node.\n91: +type ExecFunc func(ctx context.Context, f func(ns.NetNS) error) error\n92: +\n93: +// LocalTarget is one interface of a node on this machine (Docker or Podman) to capture.\n94: +type LocalTarget struct {\n95: +\t// Node is the node name as the topology spells it.\n96: +\tNode string\n97: +\t// Interface is the interface name inside the node.\n98: +\tInterface string\n99: +\t// Exec runs a function in the node's network namespace.\n100: +\tExec ExecFunc\n101: +}\n102: +\n103: +// packetSource reads the packets of one interface.\n104: +type packetSource interface {\n105: +\t// ReadPacket returns the next packet; the data is only valid until the next call. It\n106: +\t// returns errReadTimeout when no packet arrived within the poll timeout.\n107: +\tReadPacket() ([]byte, gopacket.CaptureInfo, error)\n108: +\tClose()\n109: +}\n110: +\n111: +// openSourcesFunc opens one packet source per interface in the network namespace exec enters.\n112: +type openSourcesFunc func(\n113: +\tctx context.Context,\n114: +\texec ExecFunc,\n115: +\tinterfaces []string,\n116: +\tsnapLength int,\n117: +) ([]packetSource, error)\n118: +\n119: +// CaptureLocal streams pcapng from interfaces of nodes on this machine to w, with the same\n120: +// output and end conditions as labruntime.PacketCapturer.Capture: one section, one Interface\n121: +// Description Block per target named <node>:<interface>, then the packets of every target in\n122: +// timestamp order. targets lists the interfaces of req.Targets, resolved, in the same order.\n123: +//\n124: +// Each interface is read through a packet socket opened in the node's network namespace, so\n125: +// nothing runs in the node and the node image needs no capture tools; it needs CAP_NET_RAW and\n126: +// the right to enter the namespace, so root. An interface that goes down is reopened once it is\n127: +// up again; one that disappears (its node stopped or was recreated) is reattached when it is\n128: +// back, and the time it was gone is reported as a gap through req.OnGap (or logged).\n129: +func CaptureLocal(\n130: +\tctx context.Context,\n131: +\treq clablabruntime.CaptureRequest,\n132: +\ttargets []LocalTarget,\n133: +\tw io.Writer,\n134: +) error {\n135: +\treturn localCapture{\n136: +\t\topen:           openPacketSockets,\n137: +\t\twindow:         localReorderWindow,\n138: +\t\treopenInterval: localReopenInterval,\n139: +\t}.run(ctx, req, targets, w)\n140: +}\n141: +\n142: +// localCapture is a local capture with its socket opener and timings, which tests replace.\n143: +type localCapture struct {\n144: +\topen           openSourcesFunc\n145: +\twindow         time.Duration\n146: +\treopenInterval time.Duration\n147: +}\n148: +\n149: +func (l localCapture) run(\n150: +\tctx context.Context,\n151: +\treq clablabruntime.CaptureRequest,\n152: +\ttargets []LocalTarget,\n153: +\tw io.Writer,\n154: +) error {\n155: +\tif err := ValidateRequest(&req); err != nil {\n156: +\t\treturn err\n157: +\t}\n158: +\tif len(targets) != len(req.Targets) {\n159: +\t\treturn fmt.Errorf(\"capture has %d resolved targets for %d requested ones\",\n160: +\t\t\tlen(targets), len(req.Targets))\n161: +\t}\n162: +\n163: +\tsources, err := l.openAll(ctx, targets, req.SnapLength)\n164: +\tif err != nil {\n165: +\t\treturn err\n166: +\t}\n167: +\n168: +\tnames := make([]string, len(targets))\n169: +\tfor idx, target := range targets {\n170: +\t\tnames[idx] = target.Node + \":\" + target.Interface\n171: +\t}\n172: +\n173: +\tcaptureCtx, stop := context.WithCancel(ctx)\n174: +\tdefer stop()\n175: +\tif req.Duration > 0 {\n176: +\t\tvar cancelTimeout context.CancelFunc\n177: +\t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx, req.Duration)\n178: +\t\tdefer cancelTimeout()\n179: +\t}\n180: +\n181: +\tout, err := NewOutput(w, names, req.SnapLength, req.PacketLimit, l.window, stop)\n182: +\tif err != nil {\n183: +\t\tfor _, source := range sources {\n184: +\t\t\tsource.Close()\n185: +\t\t}\n186: +\n187: +\t\treturn err\n188: +\t}\n189: +\n190: +\tvar wg sync.WaitGroup\n191: +\tfor idx, source := range sources {\n192: +\t\treader := &localReader{\n193: +\t\t\tcapture: l,\n194: +\t\t\tout:     out,\n195: +\t\t\tid:      uint32(idx), //nolint:gosec // bounded by the targets\n196: +\t\t\ttarget:  targets[idx],\n197: +\t\t\tsnap:    req.SnapLength,\n198: +\t\t\tonGap:   req.OnGap,\n199: +\t\t}\n200: +\t\twg.Go(func() {\n201: +\t\t\treader.run(captureCtx, source)\n202: +\t\t})\n203: +\t}\n204: +\twg.Wait()\n205: +\n206: +\treturn out.Close()\n207: +}\n208: +\n209: +// openAll opens the sockets of every target before anything is written, one namespace entry\n210: +// per node, so a capture that cannot start fails without output.\n211: +func (l localCapture) openAll(\n212: +\tctx context.Context,\n213: +\ttargets []LocalTarget,\n214: +\tsnapLength int,\n215: +) ([]packetSource, error) {\n216: +\ttype nodeTargets struct {\n217: +\t\texec    ExecFunc\n218: +\t\tindexes []int\n219: +\t\tnames   []string\n220: +\t}\n221: +\tvar order []string\n222: +\tbyNode := map[string]*nodeTargets{}\n223: +\tfor idx, target := range targets {\n224: +\t\tgroup := byNode[target.Node]\n225: +\t\tif group == nil {\n226: +\t\t\tgroup = &nodeTargets{exec: target.Exec}\n227: +\t\t\tbyNode[target.Node] = group\n228: +\t\t\torder = append(order, target.Node)\n229: +\t\t}\n230: +\t\tgroup.indexes = append(group.indexes, idx)\n231: +\t\tgroup.names = append(group.names, target.Interface)\n232: +\t}\n233: +\n234: +\tsources := make([]packetSource, len(targets))\n235: +\tcloseAll := func() {\n236: +\t\tfor _, source := range sources {\n237: +\t\t\tif source != nil {\n238: +\t\t\t\tsource.Close()\n239: +\t\t\t}\n240: +\t\t}\n241: +\t}\n242: +\tfor _, node := range order {\n243: +\t\tgroup := byNode[node]\n244: +\t\topened, err := l.open(ctx, group.exec, group.names, snapLength)\n245: +\t\tif err != nil {\n246: +\t\t\tcloseAll()\n247: +\t\t\treturn nil, fmt.Errorf(\"failed to start the capture on node %q: %w\", node, err)\n248: +\t\t}\n249: +\t\tfor idx, source := range opened {\n250: +\t\t\tsources[group.indexes[idx]] = source\n251: +\t\t}\n252: +\t}\n253: +\n254: +\treturn sources, nil\n255: +}\n256: +\n257: +// localReader reads one interface into the merged stream.\n258: +type localReader struct {\n259: +\tcapture localCapture\n260: +\tout     *Output\n261: +\tid      uint32\n262: +\ttarget  LocalTarget\n263: +\tsnap    int\n264: +\tonGap   func(clablabruntime.CaptureGap)\n265: +}\n266: +\n267: +func (r *localReader) run(ctx context.Context, source packetSource) {\n268: +\tdefer func() {\n269: +\t\tif source != nil {\n270: +\t\t\tsource.Close()\n271: +\t\t}\n272: +\t}()\n273: +\n274: +\tfor {\n275: +\t\tif ctx.Err() != nil {\n276: +\t\t\tr.drain(source, time.Now())\n277: +\t\t\treturn\n278: +\t\t}\n279: +\n280: +\t\tdata, info, err := source.ReadPacket()\n281: +\t\tif errors.Is(err, errReadTimeout) {\n282: +\t\t\tcontinue\n283: +\t\t}\n284: +\t\tif err != nil {\n285: +\t\t\t// The socket reports an error once its interface went down or was removed, and\n286: +\t\t\t// keeps reporting it: it is reopened.\n287: +\t\t\tlog.Debug(\"Capture socket failed, reopening it\", \"node\", r.target.Node,\n288: +\t\t\t\t\"interface\", r.target.Interface, \"error\", err)\n289: +\t\t\tsource.Close()\n290: +\t\t\tsource = r.reopen(ctx)\n291: +\t\t\tif source == nil {\n292: +\t\t\t\treturn\n293: +\t\t\t}\n294: +\n295: +\t\t\tcontinue\n296: +\t\t}\n297: +\n298: +\t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n299: +\t\t\treturn\n300: +\t\t}\n301: +\t}\n302: +}\n303: +\n304: +// drain writes the packets that arrived before end but were still in the socket's ring: the\n305: +// kernel hands over a ring block once it is full or its block timeout passed, so the last\n306: +// packets before a capture ended may not have been read yet.\n307: +func (r *localReader) drain(source packetSource, end time.Time) {\n308: +\tdeadline := end.Add(localDrainTimeout)\n309: +\tfor time.Now().Before(deadline) {\n310: +\t\tdata, info, err := source.ReadPacket()\n311: +\t\tif errors.Is(err, errReadTimeout) && time.Since(end) < localDrainQuiet {\n312: +\t\t\tcontinue\n313: +\t\t}\n314: +\t\tif err != nil || info.Timestamp.After(end) {\n315: +\t\t\treturn\n316: +\t\t}\n317: +\t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n318: +\t\t\treturn\n319: +\t\t}\n320: +\t}\n321: +}\n322: +\n323: +// packet copies a packet out of the socket's ring, cut to the snap length.\n324: +func (r *localReader) packet(data []byte, info gopacket.CaptureInfo) *Packet {\n325: +\tlength := info.Length\n326: +\tfor _, ancillary := range info.AncillaryData {\n327: +\t\tif _, ok := ancillary.(afpacket.AncillaryVLAN); ok {\n328: +\t\t\t// the tag was put back into the data and counts toward the frame length\n329: +\t\t\tlength += vlanHeaderLength\n330: +\t\t\tbreak\n331: +\t\t}\n332: +\t}\n333: +\tlength = max(length, len(data))\n334: +\n335: +\tcaptured := make([]byte, min(len(data), r.snap))\n336: +\tcopy(captured, data)\n337: +\n338: +\treturn &Packet{\n339: +\t\tTimestamp:      info.Timestamp.UnixNano(),\n340: +\t\tOriginalLength: uint32(length), //nolint:gosec // bounded by the interface MTU\n341: +\t\tData:           captured,\n342: +\t}\n343: +}\n344: +\n345: +// reopen opens the interface's socket again once its node and interface are back. It returns\n346: +// nil when the capture ended first. Time the interface could not be opened is reported as a gap;\n347: +// an interface that only went down is not, as it has no traffic while down.\n348: +func (r *localReader) reopen(ctx context.Context) packetSource {\n349: +\tfrom := time.Now()\n350: +\tvar unavailable error\n351: +\n352: +\ttimer := time.NewTimer(r.capture.reopenInterval)\n353: +\tdefer timer.Stop()\n354: +\n355: +\tfor {\n356: +\t\tselect {\n357: +\t\tcase <-ctx.Done():\n358: +\t\t\tif unavailable != nil {\n359: +\t\t\t\tr.reportGap(from, time.Time{}, unavailable)\n360: +\t\t\t}\n361: +\n362: +\t\t\treturn nil\n363: +\t\tcase <-timer.C:\n364: +\t\t}\n365: +\n366: +\t\topened, err := r.capture.open(ctx, r.target.Exec, []string{r.target.Interface}, r.snap)\n367: +\t\tif err != nil {\n368: +\t\t\tif unavailable == nil {\n369: +\t\t\t\tlog.Debug(\"Capture interface is not available, waiting for it\",\n370: +\t\t\t\t\t\"node\", r.target.Node, \"interface\", r.target.Interface, \"error\", err)\n371: +\t\t\t}\n372: +\t\t\tunavailable = err\n373: +\t\t\tresetTimer(timer, r.capture.reopenInterval)\n374: +\n375: +\t\t\tcontinue\n376: +\t\t}\n377: +\t\tif unavailable != nil {\n378: +\t\t\tr.reportGap(from, time.Now(), unavailable)\n379: +\t\t}\n380: +\n381: +\t\treturn opened[0]\n382: +\t}\n383: +}\n384: +\n385: +func (r *localReader) reportGap(from, to time.Time, cause error) {\n386: +\tReportGap(r.onGap, clablabruntime.CaptureGap{\n387: +\t\tNode:       r.target.Node,\n388: +\t\tInterfaces: []string{r.target.Interface},\n389: +\t\tFrom:       from,\n390: +\t\tTo:         to,\n391: +\t\tReason:     fmt.Sprintf(\"the interface was not available: %v\", cause),\n392: +\t})\n393: +}\n394: +\n395: +// openPacketSockets opens one packet socket per interface in the namespace exec enters. A socket\n396: +// stays bound to its interface after the thread left the namespace.\n397: +func openPacketSockets(\n398: +\tctx context.Context,\n399: +\texec ExecFunc,\n400: +\tinterfaces []string,\n\n(Showing lines 1-400 of 7018. Use offset=401 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "diff --git a/.github/workflows/clabernetes-tests.yml b/.github/workflows/clabernetes-tests.yml\nindex b1cbd00..7785167 100644\n--- a/.github/workflows/clabernetes-tests.yml\n+++ b/.github/workflows/clabernetes-tests.yml\n@@ -100,10 +100,15 @@ jobs:\n             upgrade --install --create-namespace --namespace c9s \\\n               clabernetes oci://ghcr.io/clabernetes/clabernetes/clabernetes:0.0.0\n \n           kubectl -n c9s rollout status deploy/clabernetes-manager --timeout=180s\n \n+      - name: Install tshark\n+        run: |\n+          sudo apt-get update\n+          sudo DEBIAN_FRONTEND=noninteractive apt-get install -y tshark\n+\n       - name: Run Clabernetes Robot tests\n         run: |\n           bash ./tests/rf-run.sh c9s ./tests/14-clabernetes\n \n       - name: Upload test report",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "diff --git a/.github/workflows/clabernetes-tests.yml b/.github/workflows/clabernetes-tests.yml\nindex b1cbd00..7785167 100644\n--- a/.github/workflows/clabernetes-tests.yml\n+++ b/.github/workflows/clabernetes-tests.yml\n@@ -100,10 +100,15 @@ jobs:\n             upgrade --install --create-namespace --namespace c9s \\\n               clabernetes oci://ghcr.io/clabernetes/clabernetes/clabernetes:0.0.0\n \n           kubectl -n c9s rollout status deploy/clabernetes-manager --timeout=180s\n \n+      - name: Install tshark\n+        run: |\n+          sudo apt-get update\n+          sudo DEBIAN_FRONTEND=noninteractive apt-get install -y tshark\n+\n       - name: Run Clabernetes Robot tests\n         run: |\n           bash ./tests/rf-run.sh c9s ./tests/14-clabernetes\n \n       - name: Upload test report\ndiff --git a/.github/workflows/smoke-tests.yml b/.github/workflows/smoke-tests.yml\nindex 807acbe..f7ee3c8 100644\n--- a/.github/workflows/smoke-tests.yml\n+++ b/.github/workflows/smoke-tests.yml\n@@ -51,10 +51,11 @@ jobs:\n           - \"28*.robot\"\n           - \"29*.robot\"\n           - \"30*.robot\"\n           - \"31*.robot\"\n           - \"32*.robot\"\n+          - \"33*.robot\"\n \n     # allow podman job to fail, since it started to fail on github actions\n     continue-on-error: ${{ inputs.runtime == 'podman' }}\n     steps:\n       - name: Checkout\ndiff --git a/capture/local.go b/capture/local.go\nnew file mode 100644\nindex 0000000..58dc8aa\n--- /dev/null\n+++ b/capture/local.go\n@@ -0,0 +1,430 @@\n+package capture\n+\n+import (\n+\t\"context\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"os\"\n+\t\"sync\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\t\"github.com/containernetworking/plugins/pkg/ns\"\n+\t\"github.com/gopacket/gopacket\"\n+\t\"github.com/gopacket/gopacket/afpacket\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+)\n+\n+const (\n+\t// localReorderWindow is how long the merged stream holds packets of local sockets back to\n+\t// write them in timestamp order. Each socket hands over its packets within\n+\t// localBlockTimeout, so a few times that covers the delivery skew between sockets.\n+\tlocalReorderWindow = 100 * time.Millisecond\n+\t// localBlockTimeout is how long the kernel fills a ring block before it hands it over.\n+\tlocalBlockTimeout = 10 * time.Millisecond\n+\t// localPollTimeout is how often a socket reader checks whether the capture ended.\n+\tlocalPollTimeout = 100 * time.Millisecond\n+\t// localReopenInterval is how often a reader tries to reopen the socket of an interface\n+\t// that went down or disappeared.\n+\tlocalReopenInterval = 200 * time.Millisecond\n+\t// localDrainQuiet is how long after the end of a capture a reader keeps waiting for packets\n+\t// still in the socket's ring: the kernel hands over a block within two block timeouts.\n+\tlocalDrainQuiet = 5 * localBlockTimeout\n+\t// localDrainTimeout bounds the drain while packets keep arriving.\n+\tlocalDrainTimeout = 250 * time.Millisecond\n+\t// localRingBlocks and localMinBlockSize size the receive ring of each socket: eight blocks\n+\t// of at least 1 MiB, each larger than the snap length.\n+\tlocalRingBlocks   = 8\n+\tlocalMinBlockSize = 1 << 20\n+\t// vlanHeaderLength is the length of the 802.1Q tag put back into frames whose tag the\n+\t// kernel moved out of band.\n+\tvlanHeaderLength = 4\n+)\n+\n+// errReadTimeout is returned by a packet source that has no packet within the poll timeout.\n+var errReadTimeout = errors.New(\"no packet within the poll timeout\")\n+\n+// ExecFunc runs f in the network namespace of a node.\n+type ExecFunc func(ctx context.Context, f func(ns.NetNS) error) error\n+\n+// LocalTarget is one interface of a node on this machine (Docker or Podman) to capture.\n+type LocalTarget struct {\n+\t// Node is the node name as the topology spells it.\n+\tNode string\n+\t// Interface is the interface name inside the node.\n+\tInterface string\n+\t// Exec runs a function in the node's network namespace.\n+\tExec ExecFunc\n+}\n+\n+// packetSource reads the packets of one interface.\n+type packetSource interface {\n+\t// ReadPacket returns the next packet; the data is only valid until the next call. It\n+\t// returns errReadTimeout when no packet arrived within the poll timeout.\n+\tReadPacket() ([]byte, gopacket.CaptureInfo, error)\n+\tClose()\n+}\n+\n+// openSourcesFunc opens one packet source per interface in the network namespace exec enters.\n+type openSourcesFunc func(\n+\tctx context.Context,\n+\texec ExecFunc,\n+\tinterfaces []string,\n+\tsnapLength int,\n+) ([]packetSource, error)\n+\n+// CaptureLocal streams pcapng from interfaces of nodes on this machine to w, with the same\n+// output and end conditions as labruntime.PacketCapturer.Capture: one section, one Interface\n+// Description Block per target named <node>:<interface>, then the packets of every target in\n+// timestamp order. targets lists the interfaces of req.Targets, resolved, in the same order.\n+//\n+// Each interface is read through a packet socket opened in the node's network namespace, so\n+// nothing runs in the node and the node image needs no capture tools; it needs CAP_NET_RAW and\n+// the right to enter the namespace, so root. An interface that goes down is reopened once it is\n+// up again; one that disappears (its node stopped or was recreated) is reattached when it is\n+// back, and the time it was gone is reported as a gap through req.OnGap (or logged).\n+func CaptureLocal(\n+\tctx context.Context,\n+\treq clablabruntime.CaptureRequest,\n+\ttargets []LocalTarget,\n+\tw io.Writer,\n+) error {\n+\treturn localCapture{\n+\t\topen:           openPacketSockets,\n+\t\twindow:         localReorderWindow,\n+\t\treopenInterval: localReopenInterval,\n+\t}.run(ctx, req, targets, w)\n+}\n+\n+// localCapture is a local capture with its socket opener and timings, which tests replace.\n+type localCapture struct {\n+\topen           openSourcesFunc\n+\twindow         time.Duration\n+\treopenInterval time.Duration\n+}\n+\n+func (l localCapture) run(\n+\tctx context.Context,\n+\treq clablabruntime.CaptureRequest,\n+\ttargets []LocalTarget,\n+\tw io.Writer,\n+) error {\n+\tif err := ValidateRequest(&req); err != nil {\n+\t\treturn err\n+\t}\n+\tif len(targets) != len(req.Targets) {\n+\t\treturn fmt.Errorf(\"capture has %d resolved targets for %d requested ones\",\n+\t\t\tlen(targets), len(req.Targets))\n+\t}\n+\n+\tsources, err := l.openAll(ctx, targets, req.SnapLength)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tnames := make([]string, len(targets))\n+\tfor idx, target := range targets {\n+\t\tnames[idx] = target.Node + \":\" + target.Interface\n+\t}\n+\n+\tcaptureCtx, stop := context.WithCancel(ctx)\n+\tdefer stop()\n+\tif req.Duration > 0 {\n+\t\tvar cancelTimeout context.CancelFunc\n+\t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx, req.Duration)\n+\t\tdefer cancelTimeout()\n+\t}\n+\n+\tout, err := NewOutput(w, names, req.SnapLength, req.PacketLimit, l.window, stop)\n+\tif err != nil {\n+\t\tfor _, source := range sources {\n+\t\t\tsource.Close()\n+\t\t}\n+\n+\t\treturn err\n+\t}\n+\n+\tvar wg sync.WaitGroup\n+\tfor idx, source := range sources {\n+\t\treader := &localReader{\n+\t\t\tcapture: l,\n+\t\t\tout:     out,\n+\t\t\tid:      uint32(idx), //nolint:gosec // bounded by the targets\n+\t\t\ttarget:  targets[idx],\n+\t\t\tsnap:    req.SnapLength,\n+\t\t\tonGap:   req.OnGap,\n+\t\t}\n+\t\twg.Go(func() {\n+\t\t\treader.run(captureCtx, source)\n+\t\t})\n+\t}\n+\twg.Wait()\n+\n+\treturn out.Close()\n+}\n+\n+// openAll opens the sockets of every target before anything is written, one namespace entry\n+// per node, so a capture that cannot start fails without output.\n+func (l localCapture) openAll(\n+\tctx context.Context,\n+\ttargets []LocalTarget,\n+\tsnapLength int,\n+) ([]packetSource, error) {\n+\ttype nodeTargets struct {\n+\t\texec    ExecFunc\n+\t\tindexes []int\n+\t\tnames   []string\n+\t}\n+\tvar order []string\n+\tbyNode := map[string]*nodeTargets{}\n+\tfor idx, target := range targets {\n+\t\tgroup := byNode[target.Node]\n+\t\tif group == nil {\n+\t\t\tgroup = &nodeTargets{exec: target.Exec}\n+\t\t\tbyNode[target.Node] = group\n+\t\t\torder = append(order, target.Node)\n+\t\t}\n+\t\tgroup.indexes = append(group.indexes, idx)\n+\t\tgroup.names = append(group.names, target.Interface)\n+\t}\n+\n+\tsources := make([]packetSource, len(targets))\n+\tcloseAll := func() {\n+\t\tfor _, source := range sources {\n+\t\t\tif source != nil {\n+\t\t\t\tsource.Close()\n+\t\t\t}\n+\t\t}\n+\t}\n+\tfor _, node := range order {\n+\t\tgroup := byNode[node]\n+\t\topened, err := l.open(ctx, group.exec, group.names, snapLength)\n+\t\tif err != nil {\n+\t\t\tcloseAll()\n+\t\t\treturn nil, fmt.Errorf(\"failed to start the capture on node %q: %w\", node, err)\n+\t\t}\n+\t\tfor idx, source := range opened {\n+\t\t\tsources[group.indexes[idx]] = source\n+\t\t}\n+\t}\n+\n+\treturn sources, nil\n+}\n+\n+// localReader reads one interface into the merged stream.\n+type localReader struct {\n+\tcapture localCapture\n+\tout     *Output\n+\tid      uint32\n+\ttarget  LocalTarget\n+\tsnap    int\n+\tonGap   func(clablabruntime.CaptureGap)\n+}\n+\n+func (r *localReader) run(ctx context.Context, source packetSource) {\n+\tdefer func() {\n+\t\tif source != nil {\n+\t\t\tsource.Close()\n+\t\t}\n+\t}()\n+\n+\tfor {\n+\t\tif ctx.Err() != nil {\n+\t\t\tr.drain(source, time.Now())\n+\t\t\treturn\n+\t\t}\n+\n+\t\tdata, info, err := source.ReadPacket()\n+\t\tif errors.Is(err, errReadTimeout) {\n+\t\t\tcontinue\n+\t\t}\n+\t\tif err != nil {\n+\t\t\t// The socket reports an error once its interface went down or was removed, and\n+\t\t\t// keeps reporting it: it is reopened.\n+\t\t\tlog.Debug(\"Capture socket failed, reopening it\", \"node\", r.target.Node,\n+\t\t\t\t\"interface\", r.target.Interface, \"error\", err)\n+\t\t\tsource.Close()\n+\t\t\tsource = r.reopen(ctx)\n+\t\t\tif source == nil {\n+\t\t\t\treturn\n+\t\t\t}\n+\n+\t\t\tcontinue\n+\t\t}\n+\n+\t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n+\t\t\treturn\n+\t\t}\n+\t}\n+}\n+\n+// drain writes the packets that arrived before end but were still in the socket's ring: the\n+// kernel hands over a ring block once it is full or its block timeout passed, so the last\n+// packets before a capture ended may not have been read yet.\n+func (r *localReader) drain(source packetSource, end time.Time) {\n+\tdeadline := end.Add(localDrainTimeout)\n+\tfor time.Now().Before(deadline) {\n+\t\tdata, info, err := source.ReadPacket()\n+\t\tif errors.Is(err, errReadTimeout) && time.Since(end) < localDrainQuiet {\n+\t\t\tcontinue\n+\t\t}\n+\t\tif err != nil || info.Timestamp.After(end) {\n+\t\t\treturn\n+\t\t}\n+\t\tif more, err := r.out.Emit(r.id, r.packet(data, info)); !more || err != nil {\n+\t\t\treturn\n+\t\t}\n+\t}\n+}\n+\n+// packet copies a packet out of the socket's ring, cut to the snap length.\n+func (r *localReader) packet(data []byte, info gopacket.CaptureInfo) *Packet {\n+\tlength := info.Length\n+\tfor _, ancillary := range info.AncillaryData {\n+\t\tif _, ok := ancillary.(afpacket.AncillaryVLAN); ok {\n+\t\t\t// the tag was put back into the data and counts toward the frame length\n+\t\t\tlength += vlanHeaderLength\n+\t\t\tbreak\n+\t\t}\n+\t}\n+\tlength = max(length, len(data))\n+\n+\tcaptured := make([]byte, min(len(data), r.snap))\n+\tcopy(captured, data)\n+\n+\treturn &Packet{\n+\t\tTimestamp:      info.Timestamp.UnixNano(),\n+\t\tOriginalLength: uint32(length), //nolint:gosec // bounded by the interface MTU\n+\t\tData:           captured,\n+\t}\n+}\n+\n+// reopen opens the interface's socket again once its node and interface are back. It returns\n+// nil when the capture ended first. Time the interface could not be opened is reported as a gap;\n+// an interface that only went down is not, as it has no traffic while down.\n+func (r *localReader) reopen(ctx context.Context) packetSource {\n+\tfrom := time.Now()\n+\tvar unavailable error\n+\n+\ttimer := time.NewTimer(r.capture.reopenInterval)\n+\tdefer timer.Stop()\n+\n+\tfor {\n+\t\tselect {\n+\t\tcase <-ctx.Done():\n+\t\t\tif unavailable != nil {\n+\t\t\t\tr.reportGap(from, time.Time{}, unavailable)\n+\t\t\t}\n+\n+\t\t\treturn nil\n+\t\tcase <-timer.C:\n+\t\t}\n+\n+\t\topened, err := r.capture.open(ctx, r.target.Exec, []string{r.target.Interface}, r.snap)\n+\t\tif err != nil {\n+\t\t\tif unavailable == nil {\n+\t\t\t\tlog.Debug(\"Capture interface is not available, waiting for it\",\n+\t\t\t\t\t\"node\", r.target.Node, \"interface\", r.target.Interface, \"error\", err)\n+\t\t\t}\n+\t\t\tunavailable = err\n+\t\t\tresetTimer(timer, r.capture.reopenInterval)\n+\n+\t\t\tcontinue\n+\t\t}\n+\t\tif unavailable != nil {\n+\t\t\tr.reportGap(from, time.Now(), unavailable)\n+\t\t}\n+\n+\t\treturn opened[0]\n+\t}\n+}\n+\n+func (r *localReader) reportGap(from, to time.Time, cause error) {\n+\tReportGap(r.onGap, clablabruntime.CaptureGap{\n+\t\tNode:       r.target.Node,\n+\t\tInterfaces: []string{r.target.Interface},\n+\t\tFrom:       from,\n+\t\tTo:         to,\n+\t\tReason:     fmt.Sprintf(\"the interface was not available: %v\", cause),\n+\t})\n+}\n+\n+// openPacketSockets opens one packet socket per interface in the namespace exec enters. A socket\n+// stays bound to its interface after the thread left the namespace.\n+func openPacketSockets(\n+\tctx context.Context,\n+\texec ExecFunc,\n+\tinterfaces []string,",
        "lineStart": 1,
        "lineEnd": 400,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523409820,
      "end": 1793523409851
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1965363be001B6IUOAWKkH6AOe",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196534de3001UGgBavNO6PpMwe",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 77102,
    "input": 76994,
    "output": 25,
    "reasoning": 83,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196534de3001UGgBavNO6PpMwe",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523404259,
    "completed": 1793523409857
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 77102,
    "input": 76994,
    "output": 25,
    "reasoning": 83,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 39
step-start
{
  "type": "step-start",
  "id": "prt_196536d46001W59OEF6T1rzIo9",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965363cb001Jt6GT07TwpYY9F"
}
Reasoning
I've seen the main implementation. Now let me skim the capture package tests to assess coverage (lines ~1676-2160: local_test.go, pcapng_test.go, reorder_test.go). Let me read 1676-2160.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 490,
  "offset": 1676
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1676: diff --git a/capture/reorder.go b/capture/reorder.go
1677: new file mode 100644
1678: index 0000000..277ba1a
1679: --- /dev/null
1680: +++ b/capture/reorder.go
1681: @@ -0,0 +1,271 @@
1682: +package capture
1683: +
1684: +import (
1685: +	"container/heap"
1686: +	"context"
1687: +	"sync"
1688: +	"time"
1689: +
1690: +	"github.com/charmbracelet/log"
1691: +)
1692: +
1693: +// maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets
1694: +// are written early, which can put them out of order.
1695: +const maxReorderBytes = 64 << 20
1696: +
1697: +// Reorder writes the packets of several capture sources in timestamp order.
1698: +//
1699: +// Each source (a node's capture stream, or a local interface socket) delivers its packets with
1700: +// its own delay. The buffer holds every packet for `window` after it arrived and writes the held
1701: +// packets in timestamp order, so a packet that was stamped earlier but delivered up to `window`
1702: +// later still goes out first. A packet stamped before the last packet written arrived too late
1703: +// to be ordered: it is written as it comes and counted, and the count goes to the debug log when
1704: +// the capture ends.
1705: +//
1706: +// A source can place a hold at the earliest timestamp it may still write (Hold); packets stamped
1707: +// after a hold wait for it to be released (Release). The c9s runtime holds while it switches
1708: +// between chained capture segments.
1709: +type Reorder struct {
1710: +	write  func(id uint32, packet *Packet) error
1711: +	onFail func()
1712: +	window time.Duration
1713: +	now    func() time.Time
1714: +
1715: +	mu     sync.Mutex
1716: +	queue  reorderQueue
1717: +	bytes  int
1718: +	seq    uint64
1719: +	holds  map[any]int64
1720: +	err    error
1721: +	wake   chan struct{}
1722: +	stats  reorderStats
1723: +	cursor int64 // timestamp of the latest packet written in order
1724: +}
1725: +
1726: +type reorderStats struct {
1727: +	late    int
1728: +	maxLate time.Duration
1729: +	forced  int
1730: +}
1731: +
1732: +// reorderedPacket is a packet waiting in the buffer.
1733: +type reorderedPacket struct {
1734: +	id      uint32
1735: +	packet  *Packet
1736: +	arrived time.Time
1737: +	seq     uint64
1738: +}
1739: +
1740: +// reorderQueue is a min-heap by timestamp, then arrival.
1741: +type reorderQueue []reorderedPacket
1742: +
1743: +func (q reorderQueue) Len() int { return len(q) }
1744: +
1745: +func (q reorderQueue) Less(i, j int) bool {
1746: +	if q[i].packet.Timestamp != q[j].packet.Timestamp {
1747: +		return q[i].packet.Timestamp < q[j].packet.Timestamp
1748: +	}
1749: +
1750: +	return q[i].seq < q[j].seq
1751: +}
1752: +
1753: +func (q reorderQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
1754: +
1755: +func (q *reorderQueue) Push(
1756: +	x any,
1757: +) {
1758: +	*q = append(*q, x.(reorderedPacket))
1759: +} //nolint:forcetypeassert // heap contract
1760: +
1761: +func (q *reorderQueue) Pop() any {
1762: +	old := *q
1763: +	item := old[len(old)-1]
1764: +	*q = old[:len(old)-1]
1765: +
1766: +	return item
1767: +}
1768: +
1769: +// NewReorder returns a buffer that writes through write; onFail is called once a write
1770: +// failed. A window of zero or less writes every packet as it arrives.
1771: +func NewReorder(
1772: +	window time.Duration,
1773: +	write func(id uint32, packet *Packet) error,
1774: +	onFail func(),
1775: +) *Reorder {
1776: +	return &Reorder{
1777: +		write: write, onFail: onFail, window: window, now: time.Now,
1778: +		holds: map[any]int64{}, wake: make(chan struct{}, 1),
1779: +	}
1780: +}
1781: +
1782: +// push hands a packet to the buffer. It returns the error of a failed write.
1783: +func (q *Reorder) Push(id uint32, packet *Packet) error {
1784: +	q.mu.Lock()
1785: +	defer q.mu.Unlock()
1786: +
1787: +	if q.err != nil {
1788: +		return q.err
1789: +	}
1790: +	if q.window <= 0 {
1791: +		return q.writeLocked(id, packet)
1792: +	}
1793: +	if q.cursor != 0 && packet.Timestamp < q.cursor {
1794: +		q.stats.late++
1795: +		q.stats.maxLate = max(q.stats.maxLate, time.Duration(q.cursor-packet.Timestamp))
1796: +		if q.stats.late == 1 {
1797: +			log.Debug("Capture packet arrived after the reorder window, writing it out of order",
1798: +				"late_by", time.Duration(q.cursor-packet.Timestamp), "window", q.window)
1799: +		}
1800: +
1801: +		return q.writeLocked(id, packet)
1802: +	}
1803: +
1804: +	q.seq++
1805: +	heap.Push(&q.queue, reorderedPacket{id: id, packet: packet, arrived: q.now(), seq: q.seq})
1806: +	q.bytes += len(packet.Data)
1807: +	for q.bytes > maxReorderBytes && q.queue.Len() > 0 {
1808: +		q.stats.forced++
1809: +		if err := q.popLocked(); err != nil {
1810: +			return err
1811: +		}
1812: +	}
1813: +
1814: +	select {
1815: +	case q.wake <- struct{}{}:
1816: +	default:
1817: +	}
1818: +
1819: +	return nil
1820: +}
1821: +
1822: +// hold keeps packets stamped after timestamp in the buffer until release(key).
1823: +func (q *Reorder) Hold(key any, timestamp int64) {
1824: +	q.mu.Lock()
1825: +	defer q.mu.Unlock()
1826: +
1827: +	q.holds[key] = timestamp
1828: +}
1829: +
1830: +// release removes the hold of key.
1831: +func (q *Reorder) Release(key any) {
1832: +	q.mu.Lock()
1833: +	_, held := q.holds[key]
1834: +	delete(q.holds, key)
1835: +	q.mu.Unlock()
1836: +
1837: +	if held {
1838: +		select {
1839: +		case q.wake <- struct{}{}:
1840: +		default:
1841: +		}
1842: +	}
1843: +}
1844: +
1845: +// run writes due packets until ctx ends.
1846: +func (q *Reorder) Run(ctx context.Context) {
1847: +	if q.window <= 0 {
1848: +		return
1849: +	}
1850: +
1851: +	timer := time.NewTimer(time.Hour)
1852: +	defer timer.Stop()
1853: +
1854: +	for {
1855: +		next := q.writeDue()
1856: +		wait := time.Hour
1857: +		if !next.IsZero() {
1858: +			wait = max(next.Sub(q.now()), time.Millisecond)
1859: +		}
1860: +		resetTimer(timer, wait)
1861: +
1862: +		select {
1863: +		case <-ctx.Done():
1864: +			return
1865: +		case <-q.wake:
1866: +		case <-timer.C:
1867: +		}
1868: +	}
1869: +}
1870: +
1871: +// writeDue writes the packets that waited for the window and are not behind a hold, in
1872: +// timestamp order. It returns when the next packet is due, or zero when that depends on a new
1873: +// packet or a released hold.
1874: +func (q *Reorder) writeDue() time.Time {
1875: +	q.mu.Lock()
1876: +	defer q.mu.Unlock()
1877: +
1878: +	held, limit := false, int64(0)
1879: +	for _, timestamp := range q.holds {
1880: +		if !held || timestamp < limit {
1881: +			held, limit = true, timestamp
1882: +		}
1883: +	}
1884: +
1885: +	now := q.now()
1886: +	for q.queue.Len() > 0 && q.err == nil {
1887: +		head := q.queue[0]
1888: +		if held && head.packet.Timestamp > limit {
1889: +			return time.Time{}
1890: +		}
1891: +		if due := head.arrived.Add(q.window); due.After(now) {
1892: +			return due
1893: +		}
1894: +		if q.popLocked() != nil {
1895: +			return time.Time{}
1896: +		}
1897: +	}
1898: +
1899: +	return time.Time{}
1900: +}
1901: +
1902: +// flush writes every remaining packet in timestamp order and logs what could not be ordered.
1903: +func (q *Reorder) Flush() {
1904: +	q.mu.Lock()
1905: +	defer q.mu.Unlock()
1906: +
1907: +	for q.queue.Len() > 0 && q.err == nil {
1908: +		if q.popLocked() != nil {
1909: +			break
1910: +		}
1911: +	}
1912: +	q.queue, q.bytes = nil, 0
1913: +
1914: +	if q.stats.late > 0 || q.stats.forced > 0 {
1915: +		log.Debug("Capture wrote packets out of timestamp order",
1916: +			"late_packets", q.stats.late, "max_late_by", q.stats.maxLate,
1917: +			"window", q.window, "buffer_overflow_packets", q.stats.forced)
1918: +	}
1919: +}
1920: +
1921: +func (q *Reorder) popLocked() error {
1922: +	item := heap.Pop(&q.queue).(reorderedPacket) //nolint:forcetypeassert // heap contract
1923: +	q.bytes -= len(item.packet.Data)
1924: +	q.cursor = max(q.cursor, item.packet.Timestamp)
1925: +
1926: +	return q.writeLocked(item.id, item.packet)
1927: +}
1928: +
1929: +func (q *Reorder) writeLocked(id uint32, packet *Packet) error {
1930: +	if err := q.write(id, packet); err != nil {
1931: +		if q.err == nil {
1932: +			q.err = err
1933: +			if q.onFail != nil {
1934: +				q.onFail()
1935: +			}
1936: +		}
1937: +
1938: +		return err
1939: +	}
1940: +
1941: +	return nil
1942: +}
1943: +
1944: +func resetTimer(timer *time.Timer, d time.Duration) {
1945: +	if !timer.Stop() {
1946: +		select {
1947: +		case <-timer.C:
1948: +		default:
1949: +		}
1950: +	}
1951: +	timer.Reset(d)
1952: +}
1953: diff --git a/capture/reorder_test.go b/capture/reorder_test.go
1954: new file mode 100644
1955: index 0000000..d281bed
1956: --- /dev/null
1957: +++ b/capture/reorder_test.go
1958: @@ -0,0 +1,202 @@
1959: +package capture
1960: +
1961: +import (
1962: +	"context"
1963: +	"errors"
1964: +	"slices"
1965: +	"sync"
1966: +	"testing"
1967: +	"time"
1968: +)
1969: +
1970: +// reorderSink records what a reorder buffer writes.
1971: +type reorderSink struct {
1972: +	mu      sync.Mutex
1973: +	written []int64
1974: +	ids     []uint32
1975: +	failAt  int
1976: +}
1977: +
1978: +func (s *reorderSink) write(id uint32, packet *Packet) error {
1979: +	s.mu.Lock()
1980: +	defer s.mu.Unlock()
1981: +	if s.failAt > 0 && len(s.written) == s.failAt {
1982: +		return errors.New("write |1: broken pipe")
1983: +	}
1984: +	s.written = append(s.written, packet.Timestamp)
1985: +	s.ids = append(s.ids, id)
1986: +
1987: +	return nil
1988: +}
1989: +
1990: +func (s *reorderSink) timestamps() []int64 {
1991: +	s.mu.Lock()
1992: +	defer s.mu.Unlock()
1993: +
1994: +	return slices.Clone(s.written)
1995: +}
1996: +
1997: +// interleavedStreams pushes two synthetic streams of ticks, interleaved in time: stream 0 is
1998: +// delivered at once, stream 1 `delay` after its packets were stamped. Both stamp a packet every
1999: +// 2 ms, offset by 1 ms.
2000: +func interleavedStreams(t *testing.T, q *Reorder, ticks int, delay time.Duration) {
2001: +	t.Helper()
2002: +
2003: +	start := time.Now()
2004: +	type delivery struct {
2005: +		at time.Time
2006: +		id uint32
2007: +		ts int64
2008: +	}
2009: +	var deliveries []delivery
2010: +	for tick := range ticks {
2011: +		stamp := start.Add(time.Duration(tick) * 2 * time.Millisecond)
2012: +		deliveries = append(deliveries,
2013: +			delivery{at: stamp, id: 0, ts: stamp.UnixNano()},
2014: +			delivery{
2015: +				at: stamp.Add(time.Millisecond + delay), id: 1,
2016: +				ts: stamp.Add(time.Millisecond).UnixNano(),
2017: +			})
2018: +	}
2019: +	slices.SortStableFunc(deliveries, func(a, b delivery) int { return a.at.Compare(b.at) })
2020: +
2021: +	for _, next := range deliveries {
2022: +		time.Sleep(time.Until(next.at))
2023: +		if err := q.Push(
2024: +			next.id,
2025: +			&Packet{InterfaceID: next.id, Timestamp: next.ts},
2026: +		); err != nil {
2027: +			t.Fatal(err)
2028: +		}
2029: +	}
2030: +}
2031: +
2032: +func runReorder(q *Reorder) func() {
2033: +	ctx, cancel := context.WithCancel(context.Background())
2034: +	done := make(chan struct{})
2035: +	go func() {
2036: +		defer close(done)
2037: +		q.Run(ctx)
2038: +	}()
2039: +
2040: +	return func() {
2041: +		cancel()
2042: +		<-done
2043: +		q.Flush()
2044: +	}
2045: +}
2046: +
2047: +func TestReorderOrdersStreamsWithinTheWindow(t *testing.T) {
2048: +	t.Parallel()
2049: +
2050: +	sink := &reorderSink{}
2051: +	q := NewReorder(100*time.Millisecond, sink.write, nil)
2052: +	stop := runReorder(q)
2053: +	interleavedStreams(t, q, 60, 40*time.Millisecond)
2054: +
2055: +	// packets go out while the capture runs, not only at the end
2056: +	time.Sleep(150 * time.Millisecond)
2057: +	if len(sink.timestamps()) == 0 {
2058: +		t.Fatal("nothing written while the streams ran")
2059: +	}
2060: +	stop()
2061: +
2062: +	written := sink.timestamps()
2063: +	if len(written) != 120 || !slices.IsSorted(written) {
2064: +		t.Fatalf("written %d packets, sorted %v", len(written), slices.IsSorted(written))
2065: +	}
2066: +	if q.stats.late != 0 {
2067: +		t.Fatalf("late packets = %d", q.stats.late)
2068: +	}
2069: +}
2070: +
2071: +func TestReorderWritesLatePacketsAsTheyCome(t *testing.T) {
2072: +	t.Parallel()
2073: +
2074: +	sink := &reorderSink{}
2075: +	q := NewReorder(20*time.Millisecond, sink.write, nil)
2076: +	stop := runReorder(q)
2077: +	// stream 1 arrives 80 ms after its stamps, far beyond the 20 ms window
2078: +	interleavedStreams(t, q, 60, 80*time.Millisecond)
2079: +	stop()
2080: +
2081: +	written := sink.timestamps()
2082: +	if len(written) != 120 {
2083: +		t.Fatalf("written %d packets, want all 120", len(written))
2084: +	}
2085: +	if q.stats.late == 0 || q.stats.maxLate < 40*time.Millisecond || slices.IsSorted(written) {
2086: +		t.Fatalf("late = %d (max %s), sorted %v; want late packets written out of order",
2087: +			q.stats.late, q.stats.maxLate, slices.IsSorted(written))
2088: +	}
2089: +}
2090: +
2091: +func TestReorderHoldsPacketsAfterAHold(t *testing.T) {
2092: +	t.Parallel()
2093: +
2094: +	sink := &reorderSink{}
2095: +	q := NewReorder(time.Millisecond, sink.write, nil)
2096: +	stop := runReorder(q)
2097: +	defer stop()
2098: +
2099: +	chain := &struct{ name string }{"chain"}
2100: +	q.Hold(chain, 100)
2101: +	for _, ts := range []int64{50, 150, 100, 200} {
2102: +		if err := q.Push(0, &Packet{Timestamp: ts}); err != nil {
2103: +			t.Fatal(err)
2104: +		}
2105: +	}
2106: +	time.Sleep(30 * time.Millisecond)
2107: +	if got := sink.timestamps(); !slices.Equal(got, []int64{50, 100}) {
2108: +		t.Fatalf("written under the hold = %v, want [50 100]", got)
2109: +	}
2110: +
2111: +	// the chain writes what it held back, then releases
2112: +	if err := q.Push(1, &Packet{Timestamp: 120}); err != nil {
2113: +		t.Fatal(err)
2114: +	}
2115: +	q.Release(chain)
2116: +	time.Sleep(30 * time.Millisecond)
2117: +	if got := sink.timestamps(); !slices.Equal(got, []int64{50, 100, 120, 150, 200}) {
2118: +		t.Fatalf("written after the release = %v", got)
2119: +	}
2120: +}
2121: +
2122: +func TestReorderStopsAtTheFirstWriteError(t *testing.T) {
2123: +	t.Parallel()
2124: +
2125: +	sink := &reorderSink{failAt: 2}
2126: +	failed := 0
2127: +	q := NewReorder(time.Millisecond, sink.write, func() { failed++ })
2128: +	stop := runReorder(q)
2129: +
2130: +	var err error
2131: +	for ts := int64(1); ts < 50 && err == nil; ts++ {
2132: +		err = q.Push(0, &Packet{Timestamp: ts})
2133: +		time.Sleep(2 * time.Millisecond)
2134: +	}
2135: +	stop()
2136: +
2137: +	if err == nil || failed != 1 || len(sink.timestamps()) != 2 {
2138: +		t.Fatalf(
2139: +			"push error = %v, onFail calls %d, written %d",
2140: +			err,
2141: +			failed,
2142: +			len(sink.timestamps()),
2143: +		)
2144: +	}
2145: +}
2146: +
2147: +func TestReorderWithoutWindowWritesThrough(t *testing.T) {
2148: +	t.Parallel()
2149: +
2150: +	sink := &reorderSink{}
2151: +	q := NewReorder(0, sink.write, nil)
2152: +	for _, ts := range []int64{30, 10, 20} {
2153: +		if err := q.Push(0, &Packet{Timestamp: ts}); err != nil {
2154: +			t.Fatal(err)
2155: +		}
2156: +	}
2157: +	if got := sink.timestamps(); !slices.Equal(got, []int64{30, 10, 20}) {
2158: +		t.Fatalf("written = %v, want arrival order", got)
2159: +	}
2160: +}
2161: diff --git a/cmd/capture.go b/cmd/capture.go
2162: new file mode 100644
2163: index 0000000..20117bc
2164: --- /dev/null
2165: +++ b/cmd/capture.go

(Showing lines 1676-2165 of 7018. Use offset=2166 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196536ea4001w53BSv0SCS0CsA",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965363cb001Jt6GT07TwpYY9F",
  "callID": "call_0cf91ff5fae04cdca91d8084",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 490,
      "offset": 1676
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n1676: diff --git a/capture/reorder.go b/capture/reorder.go\n1677: new file mode 100644\n1678: index 0000000..277ba1a\n1679: --- /dev/null\n1680: +++ b/capture/reorder.go\n1681: @@ -0,0 +1,271 @@\n1682: +package capture\n1683: +\n1684: +import (\n1685: +\t\"container/heap\"\n1686: +\t\"context\"\n1687: +\t\"sync\"\n1688: +\t\"time\"\n1689: +\n1690: +\t\"github.com/charmbracelet/log\"\n1691: +)\n1692: +\n1693: +// maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets\n1694: +// are written early, which can put them out of order.\n1695: +const maxReorderBytes = 64 << 20\n1696: +\n1697: +// Reorder writes the packets of several capture sources in timestamp order.\n1698: +//\n1699: +// Each source (a node's capture stream, or a local interface socket) delivers its packets with\n1700: +// its own delay. The buffer holds every packet for `window` after it arrived and writes the held\n1701: +// packets in timestamp order, so a packet that was stamped earlier but delivered up to `window`\n1702: +// later still goes out first. A packet stamped before the last packet written arrived too late\n1703: +// to be ordered: it is written as it comes and counted, and the count goes to the debug log when\n1704: +// the capture ends.\n1705: +//\n1706: +// A source can place a hold at the earliest timestamp it may still write (Hold); packets stamped\n1707: +// after a hold wait for it to be released (Release). The c9s runtime holds while it switches\n1708: +// between chained capture segments.\n1709: +type Reorder struct {\n1710: +\twrite  func(id uint32, packet *Packet) error\n1711: +\tonFail func()\n1712: +\twindow time.Duration\n1713: +\tnow    func() time.Time\n1714: +\n1715: +\tmu     sync.Mutex\n1716: +\tqueue  reorderQueue\n1717: +\tbytes  int\n1718: +\tseq    uint64\n1719: +\tholds  map[any]int64\n1720: +\terr    error\n1721: +\twake   chan struct{}\n1722: +\tstats  reorderStats\n1723: +\tcursor int64 // timestamp of the latest packet written in order\n1724: +}\n1725: +\n1726: +type reorderStats struct {\n1727: +\tlate    int\n1728: +\tmaxLate time.Duration\n1729: +\tforced  int\n1730: +}\n1731: +\n1732: +// reorderedPacket is a packet waiting in the buffer.\n1733: +type reorderedPacket struct {\n1734: +\tid      uint32\n1735: +\tpacket  *Packet\n1736: +\tarrived time.Time\n1737: +\tseq     uint64\n1738: +}\n1739: +\n1740: +// reorderQueue is a min-heap by timestamp, then arrival.\n1741: +type reorderQueue []reorderedPacket\n1742: +\n1743: +func (q reorderQueue) Len() int { return len(q) }\n1744: +\n1745: +func (q reorderQueue) Less(i, j int) bool {\n1746: +\tif q[i].packet.Timestamp != q[j].packet.Timestamp {\n1747: +\t\treturn q[i].packet.Timestamp < q[j].packet.Timestamp\n1748: +\t}\n1749: +\n1750: +\treturn q[i].seq < q[j].seq\n1751: +}\n1752: +\n1753: +func (q reorderQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }\n1754: +\n1755: +func (q *reorderQueue) Push(\n1756: +\tx any,\n1757: +) {\n1758: +\t*q = append(*q, x.(reorderedPacket))\n1759: +} //nolint:forcetypeassert // heap contract\n1760: +\n1761: +func (q *reorderQueue) Pop() any {\n1762: +\told := *q\n1763: +\titem := old[len(old)-1]\n1764: +\t*q = old[:len(old)-1]\n1765: +\n1766: +\treturn item\n1767: +}\n1768: +\n1769: +// NewReorder returns a buffer that writes through write; onFail is called once a write\n1770: +// failed. A window of zero or less writes every packet as it arrives.\n1771: +func NewReorder(\n1772: +\twindow time.Duration,\n1773: +\twrite func(id uint32, packet *Packet) error,\n1774: +\tonFail func(),\n1775: +) *Reorder {\n1776: +\treturn &Reorder{\n1777: +\t\twrite: write, onFail: onFail, window: window, now: time.Now,\n1778: +\t\tholds: map[any]int64{}, wake: make(chan struct{}, 1),\n1779: +\t}\n1780: +}\n1781: +\n1782: +// push hands a packet to the buffer. It returns the error of a failed write.\n1783: +func (q *Reorder) Push(id uint32, packet *Packet) error {\n1784: +\tq.mu.Lock()\n1785: +\tdefer q.mu.Unlock()\n1786: +\n1787: +\tif q.err != nil {\n1788: +\t\treturn q.err\n1789: +\t}\n1790: +\tif q.window <= 0 {\n1791: +\t\treturn q.writeLocked(id, packet)\n1792: +\t}\n1793: +\tif q.cursor != 0 && packet.Timestamp < q.cursor {\n1794: +\t\tq.stats.late++\n1795: +\t\tq.stats.maxLate = max(q.stats.maxLate, time.Duration(q.cursor-packet.Timestamp))\n1796: +\t\tif q.stats.late == 1 {\n1797: +\t\t\tlog.Debug(\"Capture packet arrived after the reorder window, writing it out of order\",\n1798: +\t\t\t\t\"late_by\", time.Duration(q.cursor-packet.Timestamp), \"window\", q.window)\n1799: +\t\t}\n1800: +\n1801: +\t\treturn q.writeLocked(id, packet)\n1802: +\t}\n1803: +\n1804: +\tq.seq++\n1805: +\theap.Push(&q.queue, reorderedPacket{id: id, packet: packet, arrived: q.now(), seq: q.seq})\n1806: +\tq.bytes += len(packet.Data)\n1807: +\tfor q.bytes > maxReorderBytes && q.queue.Len() > 0 {\n1808: +\t\tq.stats.forced++\n1809: +\t\tif err := q.popLocked(); err != nil {\n1810: +\t\t\treturn err\n1811: +\t\t}\n1812: +\t}\n1813: +\n1814: +\tselect {\n1815: +\tcase q.wake <- struct{}{}:\n1816: +\tdefault:\n1817: +\t}\n1818: +\n1819: +\treturn nil\n1820: +}\n1821: +\n1822: +// hold keeps packets stamped after timestamp in the buffer until release(key).\n1823: +func (q *Reorder) Hold(key any, timestamp int64) {\n1824: +\tq.mu.Lock()\n1825: +\tdefer q.mu.Unlock()\n1826: +\n1827: +\tq.holds[key] = timestamp\n1828: +}\n1829: +\n1830: +// release removes the hold of key.\n1831: +func (q *Reorder) Release(key any) {\n1832: +\tq.mu.Lock()\n1833: +\t_, held := q.holds[key]\n1834: +\tdelete(q.holds, key)\n1835: +\tq.mu.Unlock()\n1836: +\n1837: +\tif held {\n1838: +\t\tselect {\n1839: +\t\tcase q.wake <- struct{}{}:\n1840: +\t\tdefault:\n1841: +\t\t}\n1842: +\t}\n1843: +}\n1844: +\n1845: +// run writes due packets until ctx ends.\n1846: +func (q *Reorder) Run(ctx context.Context) {\n1847: +\tif q.window <= 0 {\n1848: +\t\treturn\n1849: +\t}\n1850: +\n1851: +\ttimer := time.NewTimer(time.Hour)\n1852: +\tdefer timer.Stop()\n1853: +\n1854: +\tfor {\n1855: +\t\tnext := q.writeDue()\n1856: +\t\twait := time.Hour\n1857: +\t\tif !next.IsZero() {\n1858: +\t\t\twait = max(next.Sub(q.now()), time.Millisecond)\n1859: +\t\t}\n1860: +\t\tresetTimer(timer, wait)\n1861: +\n1862: +\t\tselect {\n1863: +\t\tcase <-ctx.Done():\n1864: +\t\t\treturn\n1865: +\t\tcase <-q.wake:\n1866: +\t\tcase <-timer.C:\n1867: +\t\t}\n1868: +\t}\n1869: +}\n1870: +\n1871: +// writeDue writes the packets that waited for the window and are not behind a hold, in\n1872: +// timestamp order. It returns when the next packet is due, or zero when that depends on a new\n1873: +// packet or a released hold.\n1874: +func (q *Reorder) writeDue() time.Time {\n1875: +\tq.mu.Lock()\n1876: +\tdefer q.mu.Unlock()\n1877: +\n1878: +\theld, limit := false, int64(0)\n1879: +\tfor _, timestamp := range q.holds {\n1880: +\t\tif !held || timestamp < limit {\n1881: +\t\t\theld, limit = true, timestamp\n1882: +\t\t}\n1883: +\t}\n1884: +\n1885: +\tnow := q.now()\n1886: +\tfor q.queue.Len() > 0 && q.err == nil {\n1887: +\t\thead := q.queue[0]\n1888: +\t\tif held && head.packet.Timestamp > limit {\n1889: +\t\t\treturn time.Time{}\n1890: +\t\t}\n1891: +\t\tif due := head.arrived.Add(q.window); due.After(now) {\n1892: +\t\t\treturn due\n1893: +\t\t}\n1894: +\t\tif q.popLocked() != nil {\n1895: +\t\t\treturn time.Time{}\n1896: +\t\t}\n1897: +\t}\n1898: +\n1899: +\treturn time.Time{}\n1900: +}\n1901: +\n1902: +// flush writes every remaining packet in timestamp order and logs what could not be ordered.\n1903: +func (q *Reorder) Flush() {\n1904: +\tq.mu.Lock()\n1905: +\tdefer q.mu.Unlock()\n1906: +\n1907: +\tfor q.queue.Len() > 0 && q.err == nil {\n1908: +\t\tif q.popLocked() != nil {\n1909: +\t\t\tbreak\n1910: +\t\t}\n1911: +\t}\n1912: +\tq.queue, q.bytes = nil, 0\n1913: +\n1914: +\tif q.stats.late > 0 || q.stats.forced > 0 {\n1915: +\t\tlog.Debug(\"Capture wrote packets out of timestamp order\",\n1916: +\t\t\t\"late_packets\", q.stats.late, \"max_late_by\", q.stats.maxLate,\n1917: +\t\t\t\"window\", q.window, \"buffer_overflow_packets\", q.stats.forced)\n1918: +\t}\n1919: +}\n1920: +\n1921: +func (q *Reorder) popLocked() error {\n1922: +\titem := heap.Pop(&q.queue).(reorderedPacket) //nolint:forcetypeassert // heap contract\n1923: +\tq.bytes -= len(item.packet.Data)\n1924: +\tq.cursor = max(q.cursor, item.packet.Timestamp)\n1925: +\n1926: +\treturn q.writeLocked(item.id, item.packet)\n1927: +}\n1928: +\n1929: +func (q *Reorder) writeLocked(id uint32, packet *Packet) error {\n1930: +\tif err := q.write(id, packet); err != nil {\n1931: +\t\tif q.err == nil {\n1932: +\t\t\tq.err = err\n1933: +\t\t\tif q.onFail != nil {\n1934: +\t\t\t\tq.onFail()\n1935: +\t\t\t}\n1936: +\t\t}\n1937: +\n1938: +\t\treturn err\n1939: +\t}\n1940: +\n1941: +\treturn nil\n1942: +}\n1943: +\n1944: +func resetTimer(timer *time.Timer, d time.Duration) {\n1945: +\tif !timer.Stop() {\n1946: +\t\tselect {\n1947: +\t\tcase <-timer.C:\n1948: +\t\tdefault:\n1949: +\t\t}\n1950: +\t}\n1951: +\ttimer.Reset(d)\n1952: +}\n1953: diff --git a/capture/reorder_test.go b/capture/reorder_test.go\n1954: new file mode 100644\n1955: index 0000000..d281bed\n1956: --- /dev/null\n1957: +++ b/capture/reorder_test.go\n1958: @@ -0,0 +1,202 @@\n1959: +package capture\n1960: +\n1961: +import (\n1962: +\t\"context\"\n1963: +\t\"errors\"\n1964: +\t\"slices\"\n1965: +\t\"sync\"\n1966: +\t\"testing\"\n1967: +\t\"time\"\n1968: +)\n1969: +\n1970: +// reorderSink records what a reorder buffer writes.\n1971: +type reorderSink struct {\n1972: +\tmu      sync.Mutex\n1973: +\twritten []int64\n1974: +\tids     []uint32\n1975: +\tfailAt  int\n1976: +}\n1977: +\n1978: +func (s *reorderSink) write(id uint32, packet *Packet) error {\n1979: +\ts.mu.Lock()\n1980: +\tdefer s.mu.Unlock()\n1981: +\tif s.failAt > 0 && len(s.written) == s.failAt {\n1982: +\t\treturn errors.New(\"write |1: broken pipe\")\n1983: +\t}\n1984: +\ts.written = append(s.written, packet.Timestamp)\n1985: +\ts.ids = append(s.ids, id)\n1986: +\n1987: +\treturn nil\n1988: +}\n1989: +\n1990: +func (s *reorderSink) timestamps() []int64 {\n1991: +\ts.mu.Lock()\n1992: +\tdefer s.mu.Unlock()\n1993: +\n1994: +\treturn slices.Clone(s.written)\n1995: +}\n1996: +\n1997: +// interleavedStreams pushes two synthetic streams of ticks, interleaved in time: stream 0 is\n1998: +// delivered at once, stream 1 `delay` after its packets were stamped. Both stamp a packet every\n1999: +// 2 ms, offset by 1 ms.\n2000: +func interleavedStreams(t *testing.T, q *Reorder, ticks int, delay time.Duration) {\n2001: +\tt.Helper()\n2002: +\n2003: +\tstart := time.Now()\n2004: +\ttype delivery struct {\n2005: +\t\tat time.Time\n2006: +\t\tid uint32\n2007: +\t\tts int64\n2008: +\t}\n2009: +\tvar deliveries []delivery\n2010: +\tfor tick := range ticks {\n2011: +\t\tstamp := start.Add(time.Duration(tick) * 2 * time.Millisecond)\n2012: +\t\tdeliveries = append(deliveries,\n2013: +\t\t\tdelivery{at: stamp, id: 0, ts: stamp.UnixNano()},\n2014: +\t\t\tdelivery{\n2015: +\t\t\t\tat: stamp.Add(time.Millisecond + delay), id: 1,\n2016: +\t\t\t\tts: stamp.Add(time.Millisecond).UnixNano(),\n2017: +\t\t\t})\n2018: +\t}\n2019: +\tslices.SortStableFunc(deliveries, func(a, b delivery) int { return a.at.Compare(b.at) })\n2020: +\n2021: +\tfor _, next := range deliveries {\n2022: +\t\ttime.Sleep(time.Until(next.at))\n2023: +\t\tif err := q.Push(\n2024: +\t\t\tnext.id,\n2025: +\t\t\t&Packet{InterfaceID: next.id, Timestamp: next.ts},\n2026: +\t\t); err != nil {\n2027: +\t\t\tt.Fatal(err)\n2028: +\t\t}\n2029: +\t}\n2030: +}\n2031: +\n2032: +func runReorder(q *Reorder) func() {\n2033: +\tctx, cancel := context.WithCancel(context.Background())\n2034: +\tdone := make(chan struct{})\n2035: +\tgo func() {\n2036: +\t\tdefer close(done)\n2037: +\t\tq.Run(ctx)\n2038: +\t}()\n2039: +\n2040: +\treturn func() {\n2041: +\t\tcancel()\n2042: +\t\t<-done\n2043: +\t\tq.Flush()\n2044: +\t}\n2045: +}\n2046: +\n2047: +func TestReorderOrdersStreamsWithinTheWindow(t *testing.T) {\n2048: +\tt.Parallel()\n2049: +\n2050: +\tsink := &reorderSink{}\n2051: +\tq := NewReorder(100*time.Millisecond, sink.write, nil)\n2052: +\tstop := runReorder(q)\n2053: +\tinterleavedStreams(t, q, 60, 40*time.Millisecond)\n2054: +\n2055: +\t// packets go out while the capture runs, not only at the end\n2056: +\ttime.Sleep(150 * time.Millisecond)\n2057: +\tif len(sink.timestamps()) == 0 {\n2058: +\t\tt.Fatal(\"nothing written while the streams ran\")\n2059: +\t}\n2060: +\tstop()\n2061: +\n2062: +\twritten := sink.timestamps()\n2063: +\tif len(written) != 120 || !slices.IsSorted(written) {\n2064: +\t\tt.Fatalf(\"written %d packets, sorted %v\", len(written), slices.IsSorted(written))\n2065: +\t}\n2066: +\tif q.stats.late != 0 {\n2067: +\t\tt.Fatalf(\"late packets = %d\", q.stats.late)\n2068: +\t}\n2069: +}\n2070: +\n2071: +func TestReorderWritesLatePacketsAsTheyCome(t *testing.T) {\n2072: +\tt.Parallel()\n2073: +\n2074: +\tsink := &reorderSink{}\n2075: +\tq := NewReorder(20*time.Millisecond, sink.write, nil)\n2076: +\tstop := runReorder(q)\n2077: +\t// stream 1 arrives 80 ms after its stamps, far beyond the 20 ms window\n2078: +\tinterleavedStreams(t, q, 60, 80*time.Millisecond)\n2079: +\tstop()\n2080: +\n2081: +\twritten := sink.timestamps()\n2082: +\tif len(written) != 120 {\n2083: +\t\tt.Fatalf(\"written %d packets, want all 120\", len(written))\n2084: +\t}\n2085: +\tif q.stats.late == 0 || q.stats.maxLate < 40*time.Millisecond || slices.IsSorted(written) {\n2086: +\t\tt.Fatalf(\"late = %d (max %s), sorted %v; want late packets written out of order\",\n2087: +\t\t\tq.stats.late, q.stats.maxLate, slices.IsSorted(written))\n2088: +\t}\n2089: +}\n2090: +\n2091: +func TestReorderHoldsPacketsAfterAHold(t *testing.T) {\n2092: +\tt.Parallel()\n2093: +\n2094: +\tsink := &reorderSink{}\n2095: +\tq := NewReorder(time.Millisecond, sink.write, nil)\n2096: +\tstop := runReorder(q)\n2097: +\tdefer stop()\n2098: +\n2099: +\tchain := &struct{ name string }{\"chain\"}\n2100: +\tq.Hold(chain, 100)\n2101: +\tfor _, ts := range []int64{50, 150, 100, 200} {\n2102: +\t\tif err := q.Push(0, &Packet{Timestamp: ts}); err != nil {\n2103: +\t\t\tt.Fatal(err)\n2104: +\t\t}\n2105: +\t}\n2106: +\ttime.Sleep(30 * time.Millisecond)\n2107: +\tif got := sink.timestamps(); !slices.Equal(got, []int64{50, 100}) {\n2108: +\t\tt.Fatalf(\"written under the hold = %v, want [50 100]\", got)\n2109: +\t}\n2110: +\n2111: +\t// the chain writes what it held back, then releases\n2112: +\tif err := q.Push(1, &Packet{Timestamp: 120}); err != nil {\n2113: +\t\tt.Fatal(err)\n2114: +\t}\n2115: +\tq.Release(chain)\n2116: +\ttime.Sleep(30 * time.Millisecond)\n2117: +\tif got := sink.timestamps(); !slices.Equal(got, []int64{50, 100, 120, 150, 200}) {\n2118: +\t\tt.Fatalf(\"written after the release = %v\", got)\n2119: +\t}\n2120: +}\n2121: +\n2122: +func TestReorderStopsAtTheFirstWriteError(t *testing.T) {\n2123: +\tt.Parallel()\n2124: +\n2125: +\tsink := &reorderSink{failAt: 2}\n2126: +\tfailed := 0\n2127: +\tq := NewReorder(time.Millisecond, sink.write, func() { failed++ })\n2128: +\tstop := runReorder(q)\n2129: +\n2130: +\tvar err error\n2131: +\tfor ts := int64(1); ts < 50 && err == nil; ts++ {\n2132: +\t\terr = q.Push(0, &Packet{Timestamp: ts})\n2133: +\t\ttime.Sleep(2 * time.Millisecond)\n2134: +\t}\n2135: +\tstop()\n2136: +\n2137: +\tif err == nil || failed != 1 || len(sink.timestamps()) != 2 {\n2138: +\t\tt.Fatalf(\n2139: +\t\t\t\"push error = %v, onFail calls %d, written %d\",\n2140: +\t\t\terr,\n2141: +\t\t\tfailed,\n2142: +\t\t\tlen(sink.timestamps()),\n2143: +\t\t)\n2144: +\t}\n2145: +}\n2146: +\n2147: +func TestReorderWithoutWindowWritesThrough(t *testing.T) {\n2148: +\tt.Parallel()\n2149: +\n2150: +\tsink := &reorderSink{}\n2151: +\tq := NewReorder(0, sink.write, nil)\n2152: +\tfor _, ts := range []int64{30, 10, 20} {\n2153: +\t\tif err := q.Push(0, &Packet{Timestamp: ts}); err != nil {\n2154: +\t\t\tt.Fatal(err)\n2155: +\t\t}\n2156: +\t}\n2157: +\tif got := sink.timestamps(); !slices.Equal(got, []int64{30, 10, 20}) {\n2158: +\t\tt.Fatalf(\"written = %v, want arrival order\", got)\n2159: +\t}\n2160: +}\n2161: diff --git a/cmd/capture.go b/cmd/capture.go\n2162: new file mode 100644\n2163: index 0000000..20117bc\n2164: --- /dev/null\n2165: +++ b/cmd/capture.go\n\n(Showing lines 1676-2165 of 7018. Use offset=2166 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "diff --git a/capture/reorder.go b/capture/reorder.go\nnew file mode 100644\nindex 0000000..277ba1a\n--- /dev/null\n+++ b/capture/reorder.go\n@@ -0,0 +1,271 @@\n+package capture\n+\n+import (\n+\t\"container/heap\"\n+\t\"context\"\n+\t\"sync\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+)\n+\n+// maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets\n+// are written early, which can put them out of order.\n+const maxReorderBytes = 64 << 20",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "diff --git a/capture/reorder.go b/capture/reorder.go\nnew file mode 100644\nindex 0000000..277ba1a\n--- /dev/null\n+++ b/capture/reorder.go\n@@ -0,0 +1,271 @@\n+package capture\n+\n+import (\n+\t\"container/heap\"\n+\t\"context\"\n+\t\"sync\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+)\n+\n+// maxReorderBytes bounds the packet data the reorder buffer holds. Past it, the oldest packets\n+// are written early, which can put them out of order.\n+const maxReorderBytes = 64 << 20\n+\n+// Reorder writes the packets of several capture sources in timestamp order.\n+//\n+// Each source (a node's capture stream, or a local interface socket) delivers its packets with\n+// its own delay. The buffer holds every packet for `window` after it arrived and writes the held\n+// packets in timestamp order, so a packet that was stamped earlier but delivered up to `window`\n+// later still goes out first. A packet stamped before the last packet written arrived too late\n+// to be ordered: it is written as it comes and counted, and the count goes to the debug log when\n+// the capture ends.\n+//\n+// A source can place a hold at the earliest timestamp it may still write (Hold); packets stamped\n+// after a hold wait for it to be released (Release). The c9s runtime holds while it switches\n+// between chained capture segments.\n+type Reorder struct {\n+\twrite  func(id uint32, packet *Packet) error\n+\tonFail func()\n+\twindow time.Duration\n+\tnow    func() time.Time\n+\n+\tmu     sync.Mutex\n+\tqueue  reorderQueue\n+\tbytes  int\n+\tseq    uint64\n+\tholds  map[any]int64\n+\terr    error\n+\twake   chan struct{}\n+\tstats  reorderStats\n+\tcursor int64 // timestamp of the latest packet written in order\n+}\n+\n+type reorderStats struct {\n+\tlate    int\n+\tmaxLate time.Duration\n+\tforced  int\n+}\n+\n+// reorderedPacket is a packet waiting in the buffer.\n+type reorderedPacket struct {\n+\tid      uint32\n+\tpacket  *Packet\n+\tarrived time.Time\n+\tseq     uint64\n+}\n+\n+// reorderQueue is a min-heap by timestamp, then arrival.\n+type reorderQueue []reorderedPacket\n+\n+func (q reorderQueue) Len() int { return len(q) }\n+\n+func (q reorderQueue) Less(i, j int) bool {\n+\tif q[i].packet.Timestamp != q[j].packet.Timestamp {\n+\t\treturn q[i].packet.Timestamp < q[j].packet.Timestamp\n+\t}\n+\n+\treturn q[i].seq < q[j].seq\n+}\n+\n+func (q reorderQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }\n+\n+func (q *reorderQueue) Push(\n+\tx any,\n+) {\n+\t*q = append(*q, x.(reorderedPacket))\n+} //nolint:forcetypeassert // heap contract\n+\n+func (q *reorderQueue) Pop() any {\n+\told := *q\n+\titem := old[len(old)-1]\n+\t*q = old[:len(old)-1]\n+\n+\treturn item\n+}\n+\n+// NewReorder returns a buffer that writes through write; onFail is called once a write\n+// failed. A window of zero or less writes every packet as it arrives.\n+func NewReorder(\n+\twindow time.Duration,\n+\twrite func(id uint32, packet *Packet) error,\n+\tonFail func(),\n+) *Reorder {\n+\treturn &Reorder{\n+\t\twrite: write, onFail: onFail, window: window, now: time.Now,\n+\t\tholds: map[any]int64{}, wake: make(chan struct{}, 1),\n+\t}\n+}\n+\n+// push hands a packet to the buffer. It returns the error of a failed write.\n+func (q *Reorder) Push(id uint32, packet *Packet) error {\n+\tq.mu.Lock()\n+\tdefer q.mu.Unlock()\n+\n+\tif q.err != nil {\n+\t\treturn q.err\n+\t}\n+\tif q.window <= 0 {\n+\t\treturn q.writeLocked(id, packet)\n+\t}\n+\tif q.cursor != 0 && packet.Timestamp < q.cursor {\n+\t\tq.stats.late++\n+\t\tq.stats.maxLate = max(q.stats.maxLate, time.Duration(q.cursor-packet.Timestamp))\n+\t\tif q.stats.late == 1 {\n+\t\t\tlog.Debug(\"Capture packet arrived after the reorder window, writing it out of order\",\n+\t\t\t\t\"late_by\", time.Duration(q.cursor-packet.Timestamp), \"window\", q.window)\n+\t\t}\n+\n+\t\treturn q.writeLocked(id, packet)\n+\t}\n+\n+\tq.seq++\n+\theap.Push(&q.queue, reorderedPacket{id: id, packet: packet, arrived: q.now(), seq: q.seq})\n+\tq.bytes += len(packet.Data)\n+\tfor q.bytes > maxReorderBytes && q.queue.Len() > 0 {\n+\t\tq.stats.forced++\n+\t\tif err := q.popLocked(); err != nil {\n+\t\t\treturn err\n+\t\t}\n+\t}\n+\n+\tselect {\n+\tcase q.wake <- struct{}{}:\n+\tdefault:\n+\t}\n+\n+\treturn nil\n+}\n+\n+// hold keeps packets stamped after timestamp in the buffer until release(key).\n+func (q *Reorder) Hold(key any, timestamp int64) {\n+\tq.mu.Lock()\n+\tdefer q.mu.Unlock()\n+\n+\tq.holds[key] = timestamp\n+}\n+\n+// release removes the hold of key.\n+func (q *Reorder) Release(key any) {\n+\tq.mu.Lock()\n+\t_, held := q.holds[key]\n+\tdelete(q.holds, key)\n+\tq.mu.Unlock()\n+\n+\tif held {\n+\t\tselect {\n+\t\tcase q.wake <- struct{}{}:\n+\t\tdefault:\n+\t\t}\n+\t}\n+}\n+\n+// run writes due packets until ctx ends.\n+func (q *Reorder) Run(ctx context.Context) {\n+\tif q.window <= 0 {\n+\t\treturn\n+\t}\n+\n+\ttimer := time.NewTimer(time.Hour)\n+\tdefer timer.Stop()\n+\n+\tfor {\n+\t\tnext := q.writeDue()\n+\t\twait := time.Hour\n+\t\tif !next.IsZero() {\n+\t\t\twait = max(next.Sub(q.now()), time.Millisecond)\n+\t\t}\n+\t\tresetTimer(timer, wait)\n+\n+\t\tselect {\n+\t\tcase <-ctx.Done():\n+\t\t\treturn\n+\t\tcase <-q.wake:\n+\t\tcase <-timer.C:\n+\t\t}\n+\t}\n+}\n+\n+// writeDue writes the packets that waited for the window and are not behind a hold, in\n+// timestamp order. It returns when the next packet is due, or zero when that depends on a new\n+// packet or a released hold.\n+func (q *Reorder) writeDue() time.Time {\n+\tq.mu.Lock()\n+\tdefer q.mu.Unlock()\n+\n+\theld, limit := false, int64(0)\n+\tfor _, timestamp := range q.holds {\n+\t\tif !held || timestamp < limit {\n+\t\t\theld, limit = true, timestamp\n+\t\t}\n+\t}\n+\n+\tnow := q.now()\n+\tfor q.queue.Len() > 0 && q.err == nil {\n+\t\thead := q.queue[0]\n+\t\tif held && head.packet.Timestamp > limit {\n+\t\t\treturn time.Time{}\n+\t\t}\n+\t\tif due := head.arrived.Add(q.window); due.After(now) {\n+\t\t\treturn due\n+\t\t}\n+\t\tif q.popLocked() != nil {\n+\t\t\treturn time.Time{}\n+\t\t}\n+\t}\n+\n+\treturn time.Time{}\n+}\n+\n+// flush writes every remaining packet in timestamp order and logs what could not be ordered.\n+func (q *Reorder) Flush() {\n+\tq.mu.Lock()\n+\tdefer q.mu.Unlock()\n+\n+\tfor q.queue.Len() > 0 && q.err == nil {\n+\t\tif q.popLocked() != nil {\n+\t\t\tbreak\n+\t\t}\n+\t}\n+\tq.queue, q.bytes = nil, 0\n+\n+\tif q.stats.late > 0 || q.stats.forced > 0 {\n+\t\tlog.Debug(\"Capture wrote packets out of timestamp order\",\n+\t\t\t\"late_packets\", q.stats.late, \"max_late_by\", q.stats.maxLate,\n+\t\t\t\"window\", q.window, \"buffer_overflow_packets\", q.stats.forced)\n+\t}\n+}\n+\n+func (q *Reorder) popLocked() error {\n+\titem := heap.Pop(&q.queue).(reorderedPacket) //nolint:forcetypeassert // heap contract\n+\tq.bytes -= len(item.packet.Data)\n+\tq.cursor = max(q.cursor, item.packet.Timestamp)\n+\n+\treturn q.writeLocked(item.id, item.packet)\n+}\n+\n+func (q *Reorder) writeLocked(id uint32, packet *Packet) error {\n+\tif err := q.write(id, packet); err != nil {\n+\t\tif q.err == nil {\n+\t\t\tq.err = err\n+\t\t\tif q.onFail != nil {\n+\t\t\t\tq.onFail()\n+\t\t\t}\n+\t\t}\n+\n+\t\treturn err\n+\t}\n+\n+\treturn nil\n+}\n+\n+func resetTimer(timer *time.Timer, d time.Duration) {\n+\tif !timer.Stop() {\n+\t\tselect {\n+\t\tcase <-timer.C:\n+\t\tdefault:\n+\t\t}\n+\t}\n+\ttimer.Reset(d)\n+}\ndiff --git a/capture/reorder_test.go b/capture/reorder_test.go\nnew file mode 100644\nindex 0000000..d281bed\n--- /dev/null\n+++ b/capture/reorder_test.go\n@@ -0,0 +1,202 @@\n+package capture\n+\n+import (\n+\t\"context\"\n+\t\"errors\"\n+\t\"slices\"\n+\t\"sync\"\n+\t\"testing\"\n+\t\"time\"\n+)\n+\n+// reorderSink records what a reorder buffer writes.\n+type reorderSink struct {\n+\tmu      sync.Mutex\n+\twritten []int64\n+\tids     []uint32\n+\tfailAt  int\n+}\n+\n+func (s *reorderSink) write(id uint32, packet *Packet) error {\n+\ts.mu.Lock()\n+\tdefer s.mu.Unlock()\n+\tif s.failAt > 0 && len(s.written) == s.failAt {\n+\t\treturn errors.New(\"write |1: broken pipe\")\n+\t}\n+\ts.written = append(s.written, packet.Timestamp)\n+\ts.ids = append(s.ids, id)\n+\n+\treturn nil\n+}\n+\n+func (s *reorderSink) timestamps() []int64 {\n+\ts.mu.Lock()\n+\tdefer s.mu.Unlock()\n+\n+\treturn slices.Clone(s.written)\n+}\n+\n+// interleavedStreams pushes two synthetic streams of ticks, interleaved in time: stream 0 is\n+// delivered at once, stream 1 `delay` after its packets were stamped. Both stamp a packet every\n+// 2 ms, offset by 1 ms.\n+func interleavedStreams(t *testing.T, q *Reorder, ticks int, delay time.Duration) {\n+\tt.Helper()\n+\n+\tstart := time.Now()\n+\ttype delivery struct {\n+\t\tat time.Time\n+\t\tid uint32\n+\t\tts int64\n+\t}\n+\tvar deliveries []delivery\n+\tfor tick := range ticks {\n+\t\tstamp := start.Add(time.Duration(tick) * 2 * time.Millisecond)\n+\t\tdeliveries = append(deliveries,\n+\t\t\tdelivery{at: stamp, id: 0, ts: stamp.UnixNano()},\n+\t\t\tdelivery{\n+\t\t\t\tat: stamp.Add(time.Millisecond + delay), id: 1,\n+\t\t\t\tts: stamp.Add(time.Millisecond).UnixNano(),\n+\t\t\t})\n+\t}\n+\tslices.SortStableFunc(deliveries, func(a, b delivery) int { return a.at.Compare(b.at) })\n+\n+\tfor _, next := range deliveries {\n+\t\ttime.Sleep(time.Until(next.at))\n+\t\tif err := q.Push(\n+\t\t\tnext.id,\n+\t\t\t&Packet{InterfaceID: next.id, Timestamp: next.ts},\n+\t\t); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t}\n+}\n+\n+func runReorder(q *Reorder) func() {\n+\tctx, cancel := context.WithCancel(context.Background())\n+\tdone := make(chan struct{})\n+\tgo func() {\n+\t\tdefer close(done)\n+\t\tq.Run(ctx)\n+\t}()\n+\n+\treturn func() {\n+\t\tcancel()\n+\t\t<-done\n+\t\tq.Flush()\n+\t}\n+}\n+\n+func TestReorderOrdersStreamsWithinTheWindow(t *testing.T) {\n+\tt.Parallel()\n+\n+\tsink := &reorderSink{}\n+\tq := NewReorder(100*time.Millisecond, sink.write, nil)\n+\tstop := runReorder(q)\n+\tinterleavedStreams(t, q, 60, 40*time.Millisecond)\n+\n+\t// packets go out while the capture runs, not only at the end\n+\ttime.Sleep(150 * time.Millisecond)\n+\tif len(sink.timestamps()) == 0 {\n+\t\tt.Fatal(\"nothing written while the streams ran\")\n+\t}\n+\tstop()\n+\n+\twritten := sink.timestamps()\n+\tif len(written) != 120 || !slices.IsSorted(written) {\n+\t\tt.Fatalf(\"written %d packets, sorted %v\", len(written), slices.IsSorted(written))\n+\t}\n+\tif q.stats.late != 0 {\n+\t\tt.Fatalf(\"late packets = %d\", q.stats.late)\n+\t}\n+}\n+\n+func TestReorderWritesLatePacketsAsTheyCome(t *testing.T) {\n+\tt.Parallel()\n+\n+\tsink := &reorderSink{}\n+\tq := NewReorder(20*time.Millisecond, sink.write, nil)\n+\tstop := runReorder(q)\n+\t// stream 1 arrives 80 ms after its stamps, far beyond the 20 ms window\n+\tinterleavedStreams(t, q, 60, 80*time.Millisecond)\n+\tstop()\n+\n+\twritten := sink.timestamps()\n+\tif len(written) != 120 {\n+\t\tt.Fatalf(\"written %d packets, want all 120\", len(written))\n+\t}\n+\tif q.stats.late == 0 || q.stats.maxLate < 40*time.Millisecond || slices.IsSorted(written) {\n+\t\tt.Fatalf(\"late = %d (max %s), sorted %v; want late packets written out of order\",\n+\t\t\tq.stats.late, q.stats.maxLate, slices.IsSorted(written))\n+\t}\n+}\n+\n+func TestReorderHoldsPacketsAfterAHold(t *testing.T) {\n+\tt.Parallel()\n+\n+\tsink := &reorderSink{}\n+\tq := NewReorder(time.Millisecond, sink.write, nil)\n+\tstop := runReorder(q)\n+\tdefer stop()\n+\n+\tchain := &struct{ name string }{\"chain\"}\n+\tq.Hold(chain, 100)\n+\tfor _, ts := range []int64{50, 150, 100, 200} {\n+\t\tif err := q.Push(0, &Packet{Timestamp: ts}); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t}\n+\ttime.Sleep(30 * time.Millisecond)\n+\tif got := sink.timestamps(); !slices.Equal(got, []int64{50, 100}) {\n+\t\tt.Fatalf(\"written under the hold = %v, want [50 100]\", got)\n+\t}\n+\n+\t// the chain writes what it held back, then releases\n+\tif err := q.Push(1, &Packet{Timestamp: 120}); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tq.Release(chain)\n+\ttime.Sleep(30 * time.Millisecond)\n+\tif got := sink.timestamps(); !slices.Equal(got, []int64{50, 100, 120, 150, 200}) {\n+\t\tt.Fatalf(\"written after the release = %v\", got)\n+\t}\n+}\n+\n+func TestReorderStopsAtTheFirstWriteError(t *testing.T) {\n+\tt.Parallel()\n+\n+\tsink := &reorderSink{failAt: 2}\n+\tfailed := 0\n+\tq := NewReorder(time.Millisecond, sink.write, func() { failed++ })\n+\tstop := runReorder(q)\n+\n+\tvar err error\n+\tfor ts := int64(1); ts < 50 && err == nil; ts++ {\n+\t\terr = q.Push(0, &Packet{Timestamp: ts})\n+\t\ttime.Sleep(2 * time.Millisecond)\n+\t}\n+\tstop()\n+\n+\tif err == nil || failed != 1 || len(sink.timestamps()) != 2 {\n+\t\tt.Fatalf(\n+\t\t\t\"push error = %v, onFail calls %d, written %d\",\n+\t\t\terr,\n+\t\t\tfailed,\n+\t\t\tlen(sink.timestamps()),\n+\t\t)\n+\t}\n+}\n+\n+func TestReorderWithoutWindowWritesThrough(t *testing.T) {\n+\tt.Parallel()\n+\n+\tsink := &reorderSink{}\n+\tq := NewReorder(0, sink.write, nil)\n+\tfor _, ts := range []int64{30, 10, 20} {\n+\t\tif err := q.Push(0, &Packet{Timestamp: ts}); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t}\n+\tif got := sink.timestamps(); !slices.Equal(got, []int64{30, 10, 20}) {\n+\t\tt.Fatalf(\"written = %v, want arrival order\", got)\n+\t}\n+}\ndiff --git a/cmd/capture.go b/cmd/capture.go\nnew file mode 100644\nindex 0000000..20117bc\n--- /dev/null\n+++ b/cmd/capture.go",
        "lineStart": 1676,
        "lineEnd": 2165,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523412648,
      "end": 1793523412661
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196536eb7001dwQOWfWI47BMOC",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965363cb001Jt6GT07TwpYY9F",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 81706,
    "input": 7132,
    "output": 27,
    "reasoning": 51,
    "cache": {
      "read": 74496,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1965363cb001Jt6GT07TwpYY9F",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523409867,
    "completed": 1793523412666
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 81706,
    "input": 7132,
    "output": 27,
    "reasoning": 51,
    "cache": {
      "read": 74496,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 40
step-start
{
  "type": "step-start",
  "id": "prt_1965377da001yjxJEvE1r121PF",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196536ec3001DYhMjZBrLlaEIj"
}
Reasoning
I've now covered the reorder implementation and its tests. Now let me look at the pcapng_test.go and local_test.go (diff lines ~200-1676 area). Let me read the diff regions I haven't: 401-1676 (rest of local.go + local_test.go + pcapng.go + pcapng_test.go).
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 700,
  "offset": 401
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
401: +	snapLength int,
402: +) ([]packetSource, error) {
403: +	sources := make([]packetSource, 0, len(interfaces))
404: +	err := exec(ctx, func(ns.NetNS) error {
405: +		for _, name := range interfaces {
406: +			source, err := openPacketSocket(name, snapLength)
407: +			if err != nil {
408: +				return fmt.Errorf("interface %q: %w", name, err)
409: +			}
410: +			sources = append(sources, source)
411: +		}
412: +
413: +		return nil
414: +	})
415: +	if err != nil {
416: +		for _, source := range sources {
417: +			source.Close()
418: +		}
419: +
420: +		return nil, err
421: +	}
422: +
423: +	return sources, nil
424: +}
425: +
426: +// afpacketSource is a TPACKET_V3 receive ring on one interface.
427: +type afpacketSource struct {
428: +	handle *afpacket.TPacket
429: +}
430: +
431: +func openPacketSocket(name string, snapLength int) (*afpacketSource, error) {
432: +	// A TPACKET_V3 block holds whole frames: it must be larger than the snap length, plus the
433: +	// block and frame headers, and a multiple of the page size.
434: +	pageSize := os.Getpagesize()
435: +	blockSize := max(localMinBlockSize, snapLength+pageSize)
436: +	blockSize = (blockSize + pageSize - 1) / pageSize * pageSize
437: +
438: +	handle, err := afpacket.NewTPacket(
439: +		afpacket.OptInterface(name),
440: +		afpacket.OptTPacketVersion(afpacket.TPacketVersion3),
441: +		afpacket.OptFrameSize(blockSize),
442: +		afpacket.OptBlockSize(blockSize),
443: +		afpacket.OptNumBlocks(localRingBlocks),
444: +		afpacket.OptBlockTimeout(localBlockTimeout),
445: +		afpacket.OptPollTimeout(localPollTimeout),
446: +		// the kernel moves 802.1Q tags out of the frame; captures show them in place
447: +		afpacket.OptAddVLANHeader(true),
448: +	)
449: +	if err != nil {
450: +		return nil, err
451: +	}
452: +	// promiscuous mode is a membership of this socket and ends with it
453: +	if err := handle.SetPromiscuous(true); err != nil {
454: +		handle.Close()
455: +		return nil, fmt.Errorf("failed to enable promiscuous mode: %w", err)
456: +	}
457: +
458: +	return &afpacketSource{handle: handle}, nil
459: +}
460: +
461: +func (s *afpacketSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {
462: +	data, info, err := s.handle.ZeroCopyReadPacketData()
463: +	if errors.Is(err, afpacket.ErrTimeout) {
464: +		return nil, info, errReadTimeout
465: +	}
466: +
467: +	return data, info, err
468: +}
469: +
470: +func (s *afpacketSource) Close() {
471: +	s.handle.Close()
472: +}
473: diff --git a/capture/local_test.go b/capture/local_test.go
474: new file mode 100644
475: index 0000000..f91bb00
476: --- /dev/null
477: +++ b/capture/local_test.go
478: @@ -0,0 +1,476 @@
479: +package capture
480: +
481: +import (
482: +	"bytes"
483: +	"context"
484: +	"errors"
485: +	"fmt"
486: +	"io"
487: +	"slices"
488: +	"strings"
489: +	"sync"
490: +	"testing"
491: +	"time"
492: +
493: +	"github.com/containernetworking/plugins/pkg/ns"
494: +	"github.com/gopacket/gopacket"
495: +	"github.com/gopacket/gopacket/afpacket"
496: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
497: +)
498: +
499: +// fakeFrame is one packet a fake source returns.
500: +type fakeFrame struct {
501: +	data   []byte
502: +	stamp  time.Time
503: +	length int
504: +	vlan   bool
505: +	// visible delays the frame like a ring block the kernel has not handed over yet.
506: +	visible time.Time
507: +	// err ends the source with this error instead of a packet.
508: +	err error
509: +}
510: +
511: +// fakeSource returns frames from a channel, errReadTimeout while none is queued.
512: +type fakeSource struct {
513: +	frames  chan fakeFrame
514: +	closed  chan struct{}
515: +	once    sync.Once
516: +	pending *fakeFrame
517: +}
518: +
519: +func newFakeSource() *fakeSource {
520: +	return &fakeSource{frames: make(chan fakeFrame, 64), closed: make(chan struct{})}
521: +}
522: +
523: +func (s *fakeSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {
524: +	if s.pending == nil {
525: +		select {
526: +		case frame := <-s.frames:
527: +			s.pending = &frame
528: +		case <-time.After(5 * time.Millisecond):
529: +			return nil, gopacket.CaptureInfo{}, errReadTimeout
530: +		}
531: +	}
532: +	if wait := time.Until(s.pending.visible); wait > 0 {
533: +		time.Sleep(min(wait, 5*time.Millisecond))
534: +		if time.Now().Before(s.pending.visible) {
535: +			return nil, gopacket.CaptureInfo{}, errReadTimeout
536: +		}
537: +	}
538: +
539: +	{
540: +		frame := *s.pending
541: +		s.pending = nil
542: +		if frame.err != nil {
543: +			return nil, gopacket.CaptureInfo{}, frame.err
544: +		}
545: +		info := gopacket.CaptureInfo{
546: +			Timestamp: frame.stamp, CaptureLength: len(frame.data), Length: frame.length,
547: +		}
548: +		if frame.vlan {
549: +			info.AncillaryData = []any{afpacket.AncillaryVLAN{VLAN: 10}}
550: +		}
551: +
552: +		return frame.data, info, nil
553: +	}
554: +}
555: +
556: +func (s *fakeSource) Close() {
557: +	s.once.Do(func() { close(s.closed) })
558: +}
559: +
560: +// fakeHost hands out fake sources per node and interface. Opening an interface listed in
561: +// missing fails, like an interface whose node does not run.
562: +type fakeHost struct {
563: +	mu      sync.Mutex
564: +	opened  map[string][]*fakeSource
565: +	missing map[string]bool
566: +	ready   chan string
567: +}
568: +
569: +func newFakeHost() *fakeHost {
570: +	return &fakeHost{
571: +		opened: map[string][]*fakeSource{}, missing: map[string]bool{},
572: +		ready: make(chan string, 64),
573: +	}
574: +}
575: +
576: +func (h *fakeHost) exec(node string) ExecFunc {
577: +	return func(_ context.Context, f func(ns.NetNS) error) error {
578: +		h.mu.Lock()
579: +		missing := h.missing[node]
580: +		h.mu.Unlock()
581: +		if missing {
582: +			return fmt.Errorf("node %q: container network namespace is not available", node)
583: +		}
584: +
585: +		return f(nil)
586: +	}
587: +}
588: +
589: +func (h *fakeHost) open(
590: +	ctx context.Context,
591: +	exec ExecFunc,
592: +	interfaces []string,
593: +	_ int,
594: +) ([]packetSource, error) {
595: +	var node string
596: +	err := exec(ctx, func(ns.NetNS) error { return nil })
597: +	if err != nil {
598: +		return nil, err
599: +	}
600: +
601: +	h.mu.Lock()
602: +	defer h.mu.Unlock()
603: +	sources := make([]packetSource, 0, len(interfaces))
604: +	for _, name := range interfaces {
605: +		if h.missing[name] {
606: +			return nil, fmt.Errorf("interface %q: no such network interface", name)
607: +		}
608: +		node = name
609: +		source := newFakeSource()
610: +		h.opened[name] = append(h.opened[name], source)
611: +		sources = append(sources, source)
612: +		h.ready <- node
613: +	}
614: +
615: +	return sources, nil
616: +}
617: +
618: +func (h *fakeHost) source(name string, generation int) *fakeSource {
619: +	h.mu.Lock()
620: +	defer h.mu.Unlock()
621: +
622: +	return h.opened[name][generation]
623: +}
624: +
625: +func (h *fakeHost) setMissing(name string, missing bool) {
626: +	h.mu.Lock()
627: +	defer h.mu.Unlock()
628: +	h.missing[name] = missing
629: +}
630: +
631: +func (h *fakeHost) capture() localCapture {
632: +	return localCapture{
633: +		open:           h.open,
634: +		window:         20 * time.Millisecond,
635: +		reopenInterval: time.Millisecond,
636: +	}
637: +}
638: +
639: +// waitOpened waits until n sources were opened.
640: +func (h *fakeHost) waitOpened(t *testing.T, n int) {
641: +	t.Helper()
642: +	for range n {
643: +		select {
644: +		case <-h.ready:
645: +		case <-time.After(2 * time.Second):
646: +			t.Fatal("source was not opened")
647: +		}
648: +	}
649: +}
650: +
651: +type parsedLocalCapture struct {
652: +	interfaces []string
653: +	packets    []Packet
654: +}
655: +
656: +func parseLocalCapture(t *testing.T, data []byte) parsedLocalCapture {
657: +	t.Helper()
658: +
659: +	var parsed parsedLocalCapture
660: +	reader := NewReader(bytes.NewReader(data))
661: +	for {
662: +		event, err := reader.Next()
663: +		if errors.Is(err, io.EOF) {
664: +			break
665: +		}
666: +		if err != nil {
667: +			t.Fatalf("invalid capture: %v", err)
668: +		}
669: +		if event.Interface != nil {
670: +			parsed.interfaces = append(parsed.interfaces, event.Interface.Name)
671: +		}
672: +		if event.Packet != nil {
673: +			parsed.packets = append(parsed.packets, *event.Packet)
674: +		}
675: +	}
676: +	if reader.Sections() != 1 {
677: +		t.Fatalf("capture has %d sections", reader.Sections())
678: +	}
679: +
680: +	return parsed
681: +}
682: +
683: +func localRequest(packetLimit int, duration time.Duration) clablabruntime.CaptureRequest {
684: +	return clablabruntime.CaptureRequest{
685: +		Name: "lab",
686: +		Targets: []clablabruntime.CaptureTarget{
687: +			{Node: "r1", Interface: "eth1"}, {Node: "r2", Interface: "eth1"},
688: +		},
689: +		PacketLimit: packetLimit,
690: +		Duration:    duration,
691: +		SnapLength:  64,
692: +	}
693: +}
694: +
695: +func TestCaptureLocalMergesInterfacesInTimestampOrder(t *testing.T) {
696: +	t.Parallel()
697: +
698: +	host := newFakeHost()
699: +	// the sources are keyed by interface name in the fake host, so the two nodes use distinct
700: +	// names behind the requested ones
701: +	targets := []LocalTarget{
702: +		{Node: "r1", Interface: "e1", Exec: host.exec("r1")},
703: +		{Node: "r2", Interface: "e2", Exec: host.exec("r2")},
704: +	}
705: +
706: +	var out bytes.Buffer
707: +	done := make(chan error, 1)
708: +	go func() {
709: +		done <- host.capture().run(context.Background(), localRequest(4, 0), targets, &out)
710: +	}()
711: +	host.waitOpened(t, 2)
712: +
713: +	base := time.Unix(1_761_559_200, 0)
714: +	// r2's packets reach containerlab first although r1 stamped one of them earlier
715: +	host.source("e2", 0).frames <- fakeFrame{
716: +		data: []byte("r2-a"), stamp: base.Add(2 * time.Millisecond), length: 4,
717: +	}
718: +	host.source("e2", 0).frames <- fakeFrame{
719: +		data: bytes.Repeat([]byte{7}, 100), stamp: base.Add(4 * time.Millisecond), length: 100,
720: +	}
721: +	host.source("e1", 0).frames <- fakeFrame{
722: +		data: []byte("r1-a"), stamp: base.Add(1 * time.Millisecond), length: 4,
723: +	}
724: +	host.source("e1", 0).frames <- fakeFrame{
725: +		data: []byte("r1-v"), stamp: base.Add(3 * time.Millisecond), length: 60, vlan: true,
726: +	}
727: +
728: +	select {
729: +	case err := <-done:
730: +		if err != nil {
731: +			t.Fatal(err)
732: +		}
733: +	case <-time.After(5 * time.Second):
734: +		t.Fatal("capture did not stop at the packet limit")
735: +	}
736: +
737: +	parsed := parseLocalCapture(t, out.Bytes())
738: +	if want := []string{"r1:e1", "r2:e2"}; !slices.Equal(parsed.interfaces, want) {
739: +		t.Fatalf("interfaces = %v, want %v", parsed.interfaces, want)
740: +	}
741: +	if len(parsed.packets) != 4 {
742: +		t.Fatalf("captured %d packets, want 4", len(parsed.packets))
743: +	}
744: +	var ids []uint32
745: +	for idx, packet := range parsed.packets {
746: +		ids = append(ids, packet.InterfaceID)
747: +		if want := base.Add(time.Duration(idx+1) * time.Millisecond).
748: +			UnixNano(); packet.Timestamp != want {
749: +			t.Fatalf("packet %d stamped %d, want %d", idx, packet.Timestamp, want)
750: +		}
751: +	}
752: +	if !slices.Equal(ids, []uint32{0, 1, 0, 1}) {
753: +		t.Fatalf("interface IDs = %v", ids)
754: +	}
755: +	// a re-inserted VLAN tag counts toward the frame length
756: +	if parsed.packets[2].OriginalLength != 64 {
757: +		t.Fatalf("VLAN frame length = %d, want 64", parsed.packets[2].OriginalLength)
758: +	}
759: +	// frames are cut to the snap length
760: +	if last := parsed.packets[3]; len(last.Data) != 64 || last.OriginalLength != 100 {
761: +		t.Fatalf("long frame kept %d of %d bytes", len(last.Data), last.OriginalLength)
762: +	}
763: +	for _, name := range []string{"e1", "e2"} {
764: +		select {
765: +		case <-host.source(name, 0).closed:
766: +		default:
767: +			t.Fatalf("source %s was not closed", name)
768: +		}
769: +	}
770: +}
771: +
772: +func TestCaptureLocalEndsAfterTheDurationOrWhenCanceled(t *testing.T) {
773: +	t.Parallel()
774: +
775: +	host := newFakeHost()
776: +	targets := []LocalTarget{
777: +		{Node: "r1", Interface: "e1", Exec: host.exec("r1")},
778: +		{Node: "r1", Interface: "e2", Exec: host.exec("r1")},
779: +	}
780: +
781: +	var out bytes.Buffer
782: +	start := time.Now()
783: +	if err := host.capture().run(context.Background(), localRequest(0, 50*time.Millisecond),
784: +		targets, &out); err != nil {
785: +		t.Fatal(err)
786: +	}
787: +	if elapsed := time.Since(start); elapsed < 50*time.Millisecond || elapsed > 2*time.Second {
788: +		t.Fatalf("capture ran %s for a 50ms duration", elapsed)
789: +	}
790: +	if parsed := parseLocalCapture(t, out.Bytes()); len(parsed.interfaces) != 2 {
791: +		t.Fatalf("interfaces = %v", parsed.interfaces)
792: +	}
793: +
794: +	ctx, cancel := context.WithCancel(context.Background())
795: +	done := make(chan error, 1)
796: +	go func() {
797: +		done <- host.capture().run(ctx, localRequest(0, 0), targets, io.Discard)
798: +	}()
799: +	host.waitOpened(t, 4)
800: +	cancel()
801: +	select {
802: +	case err := <-done:
803: +		if err != nil {
804: +			t.Fatalf("canceled capture returned %v", err)
805: +		}
806: +	case <-time.After(2 * time.Second):
807: +		t.Fatal("canceled capture did not end")
808: +	}
809: +}
810: +
811: +func TestCaptureLocalWritesPacketsStillInTheRingWhenItEnds(t *testing.T) {
812: +	t.Parallel()
813: +
814: +	host := newFakeHost()
815: +	targets := []LocalTarget{{Node: "r1", Interface: "e1", Exec: host.exec("r1")}}
816: +	req := localRequest(0, 0)
817: +	req.Targets = req.Targets[:1]
818: +
819: +	ctx, cancel := context.WithCancel(context.Background())
820: +	var out bytes.Buffer
821: +	done := make(chan error, 1)
822: +	go func() {
823: +		done <- host.capture().run(ctx, req, targets, &out)
824: +	}()
825: +	host.waitOpened(t, 1)
826: +
827: +	now := time.Now()
828: +	// stamped before the end, handed over by the kernel only after it
829: +	host.source("e1", 0).frames <- fakeFrame{
830: +		data: []byte("before"), stamp: now, length: 6, visible: now.Add(30 * time.Millisecond),
831: +	}
832: +	// stamped after the end: not part of the capture
833: +	host.source("e1", 0).frames <- fakeFrame{
834: +		data: []byte("after"), stamp: now.Add(time.Hour), length: 5,
835: +		visible: now.Add(40 * time.Millisecond),
836: +	}
837: +	cancel()
838: +
839: +	if err := <-done; err != nil {
840: +		t.Fatal(err)
841: +	}
842: +	parsed := parseLocalCapture(t, out.Bytes())
843: +	if len(parsed.packets) != 1 || string(parsed.packets[0].Data) != "before" {
844: +		t.Fatalf("packets = %+v, want only the one stamped before the end", parsed.packets)
845: +	}
846: +}
847: +
848: +func TestCaptureLocalFailsWithoutOutputWhenAnInterfaceCannotBeOpened(t *testing.T) {
849: +	t.Parallel()
850: +
851: +	host := newFakeHost()
852: +	host.setMissing("r2", true)
853: +	targets := []LocalTarget{
854: +		{Node: "r1", Interface: "e1", Exec: host.exec("r1")},
855: +		{Node: "r2", Interface: "e2", Exec: host.exec("r2")},
856: +	}
857: +
858: +	var out bytes.Buffer
859: +	err := host.capture().run(context.Background(), localRequest(0, 0), targets, &out)
860: +	if err == nil || !strings.Contains(err.Error(), `failed to start the capture on node "r2"`) {
861: +		t.Fatalf("error = %v", err)
862: +	}
863: +	if out.Len() != 0 {
864: +		t.Fatalf("wrote %d bytes before failing", out.Len())
865: +	}
866: +	select {
867: +	case <-host.source("e1", 0).closed:
868: +	default:
869: +		t.Fatal("the source opened before the failure was not closed")
870: +	}
871: +}
872: +
873: +func TestCaptureLocalReopensInterfacesAndReportsWhileTheyWereGone(t *testing.T) {
874: +	t.Parallel()
875: +
876: +	host := newFakeHost()
877: +	targets := []LocalTarget{{Node: "r1", Interface: "e1", Exec: host.exec("r1")}}
878: +	req := localRequest(2, 0)
879: +	req.Targets = req.Targets[:1]
880: +
881: +	var mu sync.Mutex
882: +	var gaps []clablabruntime.CaptureGap
883: +	req.OnGap = func(gap clablabruntime.CaptureGap) {
884: +		mu.Lock()
885: +		defer mu.Unlock()
886: +		gaps = append(gaps, gap)
887: +	}
888: +
889: +	var out bytes.Buffer
890: +	done := make(chan error, 1)
891: +	go func() {
892: +		done <- host.capture().run(context.Background(), req, targets, &out)
893: +	}()
894: +	host.waitOpened(t, 1)
895: +
896: +	base := time.Unix(1_761_559_200, 0)
897: +	host.source("e1", 0).frames <- fakeFrame{data: []byte("a"), stamp: base, length: 1}
898: +
899: +	// the interface goes down: the socket fails and is reopened at once, without a gap
900: +	host.source("e1", 0).frames <- fakeFrame{err: afpacket.ErrPoll}
901: +	host.waitOpened(t, 1)
902: +
903: +	// the node restarts: the interface is gone for a while, then back
904: +	host.setMissing("r1", true)
905: +	host.source("e1", 1).frames <- fakeFrame{err: afpacket.ErrPoll}
906: +	time.Sleep(20 * time.Millisecond)
907: +	host.setMissing("r1", false)
908: +	host.waitOpened(t, 1)
909: +	host.source("e1", 2).frames <- fakeFrame{
910: +		data: []byte("b"), stamp: base.Add(time.Second), length: 1,
911: +	}
912: +
913: +	select {
914: +	case err := <-done:
915: +		if err != nil {
916: +			t.Fatal(err)
917: +		}
918: +	case <-time.After(5 * time.Second):
919: +		t.Fatal("capture did not stop at the packet limit")
920: +	}
921: +
922: +	if parsed := parseLocalCapture(t, out.Bytes()); len(parsed.packets) != 2 {
923: +		t.Fatalf("captured %d packets across the reopen, want 2", len(parsed.packets))
924: +	}
925: +	mu.Lock()
926: +	defer mu.Unlock()
927: +	if len(gaps) != 1 {
928: +		t.Fatalf("gaps = %+v, want one for the restart", gaps)
929: +	}
930: +	gap := gaps[0]
931: +	if gap.Node != "r1" || !slices.Equal(gap.Interfaces, []string{"e1"}) || gap.To.IsZero() ||
932: +		!gap.To.After(gap.From) || !strings.Contains(gap.Reason, "not available") {
933: +		t.Fatalf("gap = %+v", gap)
934: +	}
935: +}
936: +
937: +func TestCaptureLocalChecksTheRequest(t *testing.T) {
938: +	t.Parallel()
939: +
940: +	host := newFakeHost()
941: +	targets := []LocalTarget{{Node: "r1", Interface: "e1", Exec: host.exec("r1")}}
942: +
943: +	req := localRequest(0, 0)
944: +	req.SnapLength = 10
945: +	if err := host.capture().run(context.Background(), req, targets[:1], io.Discard); err == nil ||
946: +		!strings.Contains(err.Error(), "snap length 10") {
947: +		t.Fatalf("small snap length: error = %v", err)
948: +	}
949: +
950: +	if err := host.capture().run(context.Background(), localRequest(0, 0), targets,
951: +		io.Discard); err == nil || !strings.Contains(err.Error(), "1 resolved targets for 2") {
952: +		t.Fatalf("target mismatch: error = %v", err)
953: +	}
954: +}
955: diff --git a/capture/output.go b/capture/output.go
956: new file mode 100644
957: index 0000000..574c33a
958: --- /dev/null
959: +++ b/capture/output.go
960: @@ -0,0 +1,203 @@
961: +package capture
962: +
963: +import (
964: +	"context"
965: +	"fmt"
966: +	"io"
967: +	"strings"
968: +	"sync/atomic"
969: +	"time"
970: +
971: +	"github.com/charmbracelet/log"
972: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
973: +)
974: +
975: +// Snap length bounds of a capture.
976: +const (
977: +	// DefaultSnapLength is the snap length of a request without one.
978: +	DefaultSnapLength = 256 << 10
979: +	MinSnapLength     = 64
980: +	MaxSnapLength     = 1 << 20
981: +)
982: +
983: +// ValidateRequest checks the bounds of a capture request and fills the default snap length.
984: +func ValidateRequest(req *clablabruntime.CaptureRequest) error {
985: +	if req.Name == "" {
986: +		return fmt.Errorf("topology name is required")
987: +	}
988: +	if len(req.Targets) == 0 {
989: +		return fmt.Errorf("at least one capture target (node and interface) is required")
990: +	}
991: +	for _, target := range req.Targets {
992: +		if target.Node == "" || target.Interface == "" {
993: +			return fmt.Errorf("capture target %+v needs a node and an interface", target)
994: +		}
995: +	}
996: +	if req.Duration < 0 {
997: +		return fmt.Errorf("capture duration must not be negative")
998: +	}
999: +	if req.PacketLimit < 0 {
1000: +		return fmt.Errorf("capture packet limit must not be negative")
1001: +	}
1002: +	if req.SnapLength == 0 {
1003: +		req.SnapLength = DefaultSnapLength
1004: +	}
1005: +	if req.SnapLength < MinSnapLength || req.SnapLength > MaxSnapLength {
1006: +		return fmt.Errorf("capture snap length %d is outside %d to %d bytes", req.SnapLength,
1007: +			MinSnapLength, MaxSnapLength)
1008: +	}
1009: +
1010: +	return nil
1011: +}
1012: +
1013: +// FindInterface matches a requested interface by its name, then by its alias.
1014: +func FindInterface(
1015: +	entries []clablabruntime.CaptureInterface,
1016: +	name string,
1017: +) (clablabruntime.CaptureInterface, bool) {
1018: +	for _, entry := range entries {
1019: +		if entry.Interface == name {
1020: +			return entry, true
1021: +		}
1022: +	}
1023: +	for _, entry := range entries {
1024: +		if entry.Alias != "" && entry.Alias == name {
1025: +			return entry, true
1026: +		}
1027: +	}
1028: +
1029: +	return clablabruntime.CaptureInterface{}, false
1030: +}
1031: +
1032: +// DescribeInterfaces lists interfaces for an error message: name (alias), ...
1033: +func DescribeInterfaces(entries []clablabruntime.CaptureInterface) string {
1034: +	if len(entries) == 0 {
1035: +		return "none"
1036: +	}
1037: +
1038: +	names := make([]string, 0, len(entries))
1039: +	for _, entry := range entries {
1040: +		name := entry.Interface
1041: +		if entry.Alias != "" {
1042: +			name += " (" + entry.Alias + ")"
1043: +		}
1044: +		names = append(names, name)
1045: +	}
1046: +
1047: +	return strings.Join(names, ", ")
1048: +}
1049: +
1050: +// ReportGap hands a gap to onGap, or logs it as a warning when onGap is nil.
1051: +func ReportGap(onGap func(clablabruntime.CaptureGap), gap clablabruntime.CaptureGap) {
1052: +	if onGap != nil {
1053: +		onGap(gap)
1054: +		return
1055: +	}
1056: +
1057: +	to := "unknown"
1058: +	if !gap.To.IsZero() {
1059: +		to = gap.To.Format(time.RFC3339Nano)
1060: +	}
1061: +	log.Warn("Capture has a gap", "node", gap.Node, "interfaces", strings.Join(gap.Interfaces, ","),
1062: +		"from", gap.From.Format(time.RFC3339Nano), "to", to, "reason", gap.Reason)
1063: +}
1064: +
1065: +// Output is the merged pcapng stream of one capture: the section header with one interface per
1066: +// capture target, then the packets of every target in timestamp order (through a Reorder), up
1067: +// to an optional packet limit.
1068: +type Output struct {
1069: +	writer  *Writer
1070: +	reorder *Reorder
1071: +	limit   int64
1072: +	written atomic.Int64
1073: +	stop    func()
1074: +
1075: +	cancelRun context.CancelFunc
1076: +	runDone   chan struct{}
1077: +}
1078: +
1079: +// NewOutput writes the section header and one Interface Description Block per name to w, then
1080: +// starts the reorder buffer with the given window (zero or less writes packets as they come).
1081: +// stop is called once the packet limit is reached or a write failed. Close must be called.
1082: +func NewOutput(
1083: +	w io.Writer,
1084: +	names []string,
1085: +	snapLength, packetLimit int,
1086: +	window time.Duration,
1087: +	stop func(),
1088: +) (*Output, error) {
1089: +	writer := NewWriter(w)
1090: +	if err := writer.WriteHeader(
1091: +		names,
1092: +		uint32(snapLength),
1093: +	); err != nil { //nolint:gosec // validated
1094: +		return nil, err
1095: +	}
1096: +
1097: +	out := &Output{
1098: +		writer:  writer,
1099: +		reorder: NewReorder(window, writer.WritePacket, stop),
1100: +		limit:   int64(packetLimit),

(Showing lines 401-1100 of 7018. Use offset=1101 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1965379f0001Jl6OnVCUoMONZ7",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196536ec3001DYhMjZBrLlaEIj",
  "callID": "call_109229f0a96b498293b9b286",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 700,
      "offset": 401
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n401: +\tsnapLength int,\n402: +) ([]packetSource, error) {\n403: +\tsources := make([]packetSource, 0, len(interfaces))\n404: +\terr := exec(ctx, func(ns.NetNS) error {\n405: +\t\tfor _, name := range interfaces {\n406: +\t\t\tsource, err := openPacketSocket(name, snapLength)\n407: +\t\t\tif err != nil {\n408: +\t\t\t\treturn fmt.Errorf(\"interface %q: %w\", name, err)\n409: +\t\t\t}\n410: +\t\t\tsources = append(sources, source)\n411: +\t\t}\n412: +\n413: +\t\treturn nil\n414: +\t})\n415: +\tif err != nil {\n416: +\t\tfor _, source := range sources {\n417: +\t\t\tsource.Close()\n418: +\t\t}\n419: +\n420: +\t\treturn nil, err\n421: +\t}\n422: +\n423: +\treturn sources, nil\n424: +}\n425: +\n426: +// afpacketSource is a TPACKET_V3 receive ring on one interface.\n427: +type afpacketSource struct {\n428: +\thandle *afpacket.TPacket\n429: +}\n430: +\n431: +func openPacketSocket(name string, snapLength int) (*afpacketSource, error) {\n432: +\t// A TPACKET_V3 block holds whole frames: it must be larger than the snap length, plus the\n433: +\t// block and frame headers, and a multiple of the page size.\n434: +\tpageSize := os.Getpagesize()\n435: +\tblockSize := max(localMinBlockSize, snapLength+pageSize)\n436: +\tblockSize = (blockSize + pageSize - 1) / pageSize * pageSize\n437: +\n438: +\thandle, err := afpacket.NewTPacket(\n439: +\t\tafpacket.OptInterface(name),\n440: +\t\tafpacket.OptTPacketVersion(afpacket.TPacketVersion3),\n441: +\t\tafpacket.OptFrameSize(blockSize),\n442: +\t\tafpacket.OptBlockSize(blockSize),\n443: +\t\tafpacket.OptNumBlocks(localRingBlocks),\n444: +\t\tafpacket.OptBlockTimeout(localBlockTimeout),\n445: +\t\tafpacket.OptPollTimeout(localPollTimeout),\n446: +\t\t// the kernel moves 802.1Q tags out of the frame; captures show them in place\n447: +\t\tafpacket.OptAddVLANHeader(true),\n448: +\t)\n449: +\tif err != nil {\n450: +\t\treturn nil, err\n451: +\t}\n452: +\t// promiscuous mode is a membership of this socket and ends with it\n453: +\tif err := handle.SetPromiscuous(true); err != nil {\n454: +\t\thandle.Close()\n455: +\t\treturn nil, fmt.Errorf(\"failed to enable promiscuous mode: %w\", err)\n456: +\t}\n457: +\n458: +\treturn &afpacketSource{handle: handle}, nil\n459: +}\n460: +\n461: +func (s *afpacketSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {\n462: +\tdata, info, err := s.handle.ZeroCopyReadPacketData()\n463: +\tif errors.Is(err, afpacket.ErrTimeout) {\n464: +\t\treturn nil, info, errReadTimeout\n465: +\t}\n466: +\n467: +\treturn data, info, err\n468: +}\n469: +\n470: +func (s *afpacketSource) Close() {\n471: +\ts.handle.Close()\n472: +}\n473: diff --git a/capture/local_test.go b/capture/local_test.go\n474: new file mode 100644\n475: index 0000000..f91bb00\n476: --- /dev/null\n477: +++ b/capture/local_test.go\n478: @@ -0,0 +1,476 @@\n479: +package capture\n480: +\n481: +import (\n482: +\t\"bytes\"\n483: +\t\"context\"\n484: +\t\"errors\"\n485: +\t\"fmt\"\n486: +\t\"io\"\n487: +\t\"slices\"\n488: +\t\"strings\"\n489: +\t\"sync\"\n490: +\t\"testing\"\n491: +\t\"time\"\n492: +\n493: +\t\"github.com/containernetworking/plugins/pkg/ns\"\n494: +\t\"github.com/gopacket/gopacket\"\n495: +\t\"github.com/gopacket/gopacket/afpacket\"\n496: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n497: +)\n498: +\n499: +// fakeFrame is one packet a fake source returns.\n500: +type fakeFrame struct {\n501: +\tdata   []byte\n502: +\tstamp  time.Time\n503: +\tlength int\n504: +\tvlan   bool\n505: +\t// visible delays the frame like a ring block the kernel has not handed over yet.\n506: +\tvisible time.Time\n507: +\t// err ends the source with this error instead of a packet.\n508: +\terr error\n509: +}\n510: +\n511: +// fakeSource returns frames from a channel, errReadTimeout while none is queued.\n512: +type fakeSource struct {\n513: +\tframes  chan fakeFrame\n514: +\tclosed  chan struct{}\n515: +\tonce    sync.Once\n516: +\tpending *fakeFrame\n517: +}\n518: +\n519: +func newFakeSource() *fakeSource {\n520: +\treturn &fakeSource{frames: make(chan fakeFrame, 64), closed: make(chan struct{})}\n521: +}\n522: +\n523: +func (s *fakeSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {\n524: +\tif s.pending == nil {\n525: +\t\tselect {\n526: +\t\tcase frame := <-s.frames:\n527: +\t\t\ts.pending = &frame\n528: +\t\tcase <-time.After(5 * time.Millisecond):\n529: +\t\t\treturn nil, gopacket.CaptureInfo{}, errReadTimeout\n530: +\t\t}\n531: +\t}\n532: +\tif wait := time.Until(s.pending.visible); wait > 0 {\n533: +\t\ttime.Sleep(min(wait, 5*time.Millisecond))\n534: +\t\tif time.Now().Before(s.pending.visible) {\n535: +\t\t\treturn nil, gopacket.CaptureInfo{}, errReadTimeout\n536: +\t\t}\n537: +\t}\n538: +\n539: +\t{\n540: +\t\tframe := *s.pending\n541: +\t\ts.pending = nil\n542: +\t\tif frame.err != nil {\n543: +\t\t\treturn nil, gopacket.CaptureInfo{}, frame.err\n544: +\t\t}\n545: +\t\tinfo := gopacket.CaptureInfo{\n546: +\t\t\tTimestamp: frame.stamp, CaptureLength: len(frame.data), Length: frame.length,\n547: +\t\t}\n548: +\t\tif frame.vlan {\n549: +\t\t\tinfo.AncillaryData = []any{afpacket.AncillaryVLAN{VLAN: 10}}\n550: +\t\t}\n551: +\n552: +\t\treturn frame.data, info, nil\n553: +\t}\n554: +}\n555: +\n556: +func (s *fakeSource) Close() {\n557: +\ts.once.Do(func() { close(s.closed) })\n558: +}\n559: +\n560: +// fakeHost hands out fake sources per node and interface. Opening an interface listed in\n561: +// missing fails, like an interface whose node does not run.\n562: +type fakeHost struct {\n563: +\tmu      sync.Mutex\n564: +\topened  map[string][]*fakeSource\n565: +\tmissing map[string]bool\n566: +\tready   chan string\n567: +}\n568: +\n569: +func newFakeHost() *fakeHost {\n570: +\treturn &fakeHost{\n571: +\t\topened: map[string][]*fakeSource{}, missing: map[string]bool{},\n572: +\t\tready: make(chan string, 64),\n573: +\t}\n574: +}\n575: +\n576: +func (h *fakeHost) exec(node string) ExecFunc {\n577: +\treturn func(_ context.Context, f func(ns.NetNS) error) error {\n578: +\t\th.mu.Lock()\n579: +\t\tmissing := h.missing[node]\n580: +\t\th.mu.Unlock()\n581: +\t\tif missing {\n582: +\t\t\treturn fmt.Errorf(\"node %q: container network namespace is not available\", node)\n583: +\t\t}\n584: +\n585: +\t\treturn f(nil)\n586: +\t}\n587: +}\n588: +\n589: +func (h *fakeHost) open(\n590: +\tctx context.Context,\n591: +\texec ExecFunc,\n592: +\tinterfaces []string,\n593: +\t_ int,\n594: +) ([]packetSource, error) {\n595: +\tvar node string\n596: +\terr := exec(ctx, func(ns.NetNS) error { return nil })\n597: +\tif err != nil {\n598: +\t\treturn nil, err\n599: +\t}\n600: +\n601: +\th.mu.Lock()\n602: +\tdefer h.mu.Unlock()\n603: +\tsources := make([]packetSource, 0, len(interfaces))\n604: +\tfor _, name := range interfaces {\n605: +\t\tif h.missing[name] {\n606: +\t\t\treturn nil, fmt.Errorf(\"interface %q: no such network interface\", name)\n607: +\t\t}\n608: +\t\tnode = name\n609: +\t\tsource := newFakeSource()\n610: +\t\th.opened[name] = append(h.opened[name], source)\n611: +\t\tsources = append(sources, source)\n612: +\t\th.ready <- node\n613: +\t}\n614: +\n615: +\treturn sources, nil\n616: +}\n617: +\n618: +func (h *fakeHost) source(name string, generation int) *fakeSource {\n619: +\th.mu.Lock()\n620: +\tdefer h.mu.Unlock()\n621: +\n622: +\treturn h.opened[name][generation]\n623: +}\n624: +\n625: +func (h *fakeHost) setMissing(name string, missing bool) {\n626: +\th.mu.Lock()\n627: +\tdefer h.mu.Unlock()\n628: +\th.missing[name] = missing\n629: +}\n630: +\n631: +func (h *fakeHost) capture() localCapture {\n632: +\treturn localCapture{\n633: +\t\topen:           h.open,\n634: +\t\twindow:         20 * time.Millisecond,\n635: +\t\treopenInterval: time.Millisecond,\n636: +\t}\n637: +}\n638: +\n639: +// waitOpened waits until n sources were opened.\n640: +func (h *fakeHost) waitOpened(t *testing.T, n int) {\n641: +\tt.Helper()\n642: +\tfor range n {\n643: +\t\tselect {\n644: +\t\tcase <-h.ready:\n645: +\t\tcase <-time.After(2 * time.Second):\n646: +\t\t\tt.Fatal(\"source was not opened\")\n647: +\t\t}\n648: +\t}\n649: +}\n650: +\n651: +type parsedLocalCapture struct {\n652: +\tinterfaces []string\n653: +\tpackets    []Packet\n654: +}\n655: +\n656: +func parseLocalCapture(t *testing.T, data []byte) parsedLocalCapture {\n657: +\tt.Helper()\n658: +\n659: +\tvar parsed parsedLocalCapture\n660: +\treader := NewReader(bytes.NewReader(data))\n661: +\tfor {\n662: +\t\tevent, err := reader.Next()\n663: +\t\tif errors.Is(err, io.EOF) {\n664: +\t\t\tbreak\n665: +\t\t}\n666: +\t\tif err != nil {\n667: +\t\t\tt.Fatalf(\"invalid capture: %v\", err)\n668: +\t\t}\n669: +\t\tif event.Interface != nil {\n670: +\t\t\tparsed.interfaces = append(parsed.interfaces, event.Interface.Name)\n671: +\t\t}\n672: +\t\tif event.Packet != nil {\n673: +\t\t\tparsed.packets = append(parsed.packets, *event.Packet)\n674: +\t\t}\n675: +\t}\n676: +\tif reader.Sections() != 1 {\n677: +\t\tt.Fatalf(\"capture has %d sections\", reader.Sections())\n678: +\t}\n679: +\n680: +\treturn parsed\n681: +}\n682: +\n683: +func localRequest(packetLimit int, duration time.Duration) clablabruntime.CaptureRequest {\n684: +\treturn clablabruntime.CaptureRequest{\n685: +\t\tName: \"lab\",\n686: +\t\tTargets: []clablabruntime.CaptureTarget{\n687: +\t\t\t{Node: \"r1\", Interface: \"eth1\"}, {Node: \"r2\", Interface: \"eth1\"},\n688: +\t\t},\n689: +\t\tPacketLimit: packetLimit,\n690: +\t\tDuration:    duration,\n691: +\t\tSnapLength:  64,\n692: +\t}\n693: +}\n694: +\n695: +func TestCaptureLocalMergesInterfacesInTimestampOrder(t *testing.T) {\n696: +\tt.Parallel()\n697: +\n698: +\thost := newFakeHost()\n699: +\t// the sources are keyed by interface name in the fake host, so the two nodes use distinct\n700: +\t// names behind the requested ones\n701: +\ttargets := []LocalTarget{\n702: +\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n703: +\t\t{Node: \"r2\", Interface: \"e2\", Exec: host.exec(\"r2\")},\n704: +\t}\n705: +\n706: +\tvar out bytes.Buffer\n707: +\tdone := make(chan error, 1)\n708: +\tgo func() {\n709: +\t\tdone <- host.capture().run(context.Background(), localRequest(4, 0), targets, &out)\n710: +\t}()\n711: +\thost.waitOpened(t, 2)\n712: +\n713: +\tbase := time.Unix(1_761_559_200, 0)\n714: +\t// r2's packets reach containerlab first although r1 stamped one of them earlier\n715: +\thost.source(\"e2\", 0).frames <- fakeFrame{\n716: +\t\tdata: []byte(\"r2-a\"), stamp: base.Add(2 * time.Millisecond), length: 4,\n717: +\t}\n718: +\thost.source(\"e2\", 0).frames <- fakeFrame{\n719: +\t\tdata: bytes.Repeat([]byte{7}, 100), stamp: base.Add(4 * time.Millisecond), length: 100,\n720: +\t}\n721: +\thost.source(\"e1\", 0).frames <- fakeFrame{\n722: +\t\tdata: []byte(\"r1-a\"), stamp: base.Add(1 * time.Millisecond), length: 4,\n723: +\t}\n724: +\thost.source(\"e1\", 0).frames <- fakeFrame{\n725: +\t\tdata: []byte(\"r1-v\"), stamp: base.Add(3 * time.Millisecond), length: 60, vlan: true,\n726: +\t}\n727: +\n728: +\tselect {\n729: +\tcase err := <-done:\n730: +\t\tif err != nil {\n731: +\t\t\tt.Fatal(err)\n732: +\t\t}\n733: +\tcase <-time.After(5 * time.Second):\n734: +\t\tt.Fatal(\"capture did not stop at the packet limit\")\n735: +\t}\n736: +\n737: +\tparsed := parseLocalCapture(t, out.Bytes())\n738: +\tif want := []string{\"r1:e1\", \"r2:e2\"}; !slices.Equal(parsed.interfaces, want) {\n739: +\t\tt.Fatalf(\"interfaces = %v, want %v\", parsed.interfaces, want)\n740: +\t}\n741: +\tif len(parsed.packets) != 4 {\n742: +\t\tt.Fatalf(\"captured %d packets, want 4\", len(parsed.packets))\n743: +\t}\n744: +\tvar ids []uint32\n745: +\tfor idx, packet := range parsed.packets {\n746: +\t\tids = append(ids, packet.InterfaceID)\n747: +\t\tif want := base.Add(time.Duration(idx+1) * time.Millisecond).\n748: +\t\t\tUnixNano(); packet.Timestamp != want {\n749: +\t\t\tt.Fatalf(\"packet %d stamped %d, want %d\", idx, packet.Timestamp, want)\n750: +\t\t}\n751: +\t}\n752: +\tif !slices.Equal(ids, []uint32{0, 1, 0, 1}) {\n753: +\t\tt.Fatalf(\"interface IDs = %v\", ids)\n754: +\t}\n755: +\t// a re-inserted VLAN tag counts toward the frame length\n756: +\tif parsed.packets[2].OriginalLength != 64 {\n757: +\t\tt.Fatalf(\"VLAN frame length = %d, want 64\", parsed.packets[2].OriginalLength)\n758: +\t}\n759: +\t// frames are cut to the snap length\n760: +\tif last := parsed.packets[3]; len(last.Data) != 64 || last.OriginalLength != 100 {\n761: +\t\tt.Fatalf(\"long frame kept %d of %d bytes\", len(last.Data), last.OriginalLength)\n762: +\t}\n763: +\tfor _, name := range []string{\"e1\", \"e2\"} {\n764: +\t\tselect {\n765: +\t\tcase <-host.source(name, 0).closed:\n766: +\t\tdefault:\n767: +\t\t\tt.Fatalf(\"source %s was not closed\", name)\n768: +\t\t}\n769: +\t}\n770: +}\n771: +\n772: +func TestCaptureLocalEndsAfterTheDurationOrWhenCanceled(t *testing.T) {\n773: +\tt.Parallel()\n774: +\n775: +\thost := newFakeHost()\n776: +\ttargets := []LocalTarget{\n777: +\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n778: +\t\t{Node: \"r1\", Interface: \"e2\", Exec: host.exec(\"r1\")},\n779: +\t}\n780: +\n781: +\tvar out bytes.Buffer\n782: +\tstart := time.Now()\n783: +\tif err := host.capture().run(context.Background(), localRequest(0, 50*time.Millisecond),\n784: +\t\ttargets, &out); err != nil {\n785: +\t\tt.Fatal(err)\n786: +\t}\n787: +\tif elapsed := time.Since(start); elapsed < 50*time.Millisecond || elapsed > 2*time.Second {\n788: +\t\tt.Fatalf(\"capture ran %s for a 50ms duration\", elapsed)\n789: +\t}\n790: +\tif parsed := parseLocalCapture(t, out.Bytes()); len(parsed.interfaces) != 2 {\n791: +\t\tt.Fatalf(\"interfaces = %v\", parsed.interfaces)\n792: +\t}\n793: +\n794: +\tctx, cancel := context.WithCancel(context.Background())\n795: +\tdone := make(chan error, 1)\n796: +\tgo func() {\n797: +\t\tdone <- host.capture().run(ctx, localRequest(0, 0), targets, io.Discard)\n798: +\t}()\n799: +\thost.waitOpened(t, 4)\n800: +\tcancel()\n801: +\tselect {\n802: +\tcase err := <-done:\n803: +\t\tif err != nil {\n804: +\t\t\tt.Fatalf(\"canceled capture returned %v\", err)\n805: +\t\t}\n806: +\tcase <-time.After(2 * time.Second):\n807: +\t\tt.Fatal(\"canceled capture did not end\")\n808: +\t}\n809: +}\n810: +\n811: +func TestCaptureLocalWritesPacketsStillInTheRingWhenItEnds(t *testing.T) {\n812: +\tt.Parallel()\n813: +\n814: +\thost := newFakeHost()\n815: +\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n816: +\treq := localRequest(0, 0)\n817: +\treq.Targets = req.Targets[:1]\n818: +\n819: +\tctx, cancel := context.WithCancel(context.Background())\n820: +\tvar out bytes.Buffer\n821: +\tdone := make(chan error, 1)\n822: +\tgo func() {\n823: +\t\tdone <- host.capture().run(ctx, req, targets, &out)\n824: +\t}()\n825: +\thost.waitOpened(t, 1)\n826: +\n827: +\tnow := time.Now()\n828: +\t// stamped before the end, handed over by the kernel only after it\n829: +\thost.source(\"e1\", 0).frames <- fakeFrame{\n830: +\t\tdata: []byte(\"before\"), stamp: now, length: 6, visible: now.Add(30 * time.Millisecond),\n831: +\t}\n832: +\t// stamped after the end: not part of the capture\n833: +\thost.source(\"e1\", 0).frames <- fakeFrame{\n834: +\t\tdata: []byte(\"after\"), stamp: now.Add(time.Hour), length: 5,\n835: +\t\tvisible: now.Add(40 * time.Millisecond),\n836: +\t}\n837: +\tcancel()\n838: +\n839: +\tif err := <-done; err != nil {\n840: +\t\tt.Fatal(err)\n841: +\t}\n842: +\tparsed := parseLocalCapture(t, out.Bytes())\n843: +\tif len(parsed.packets) != 1 || string(parsed.packets[0].Data) != \"before\" {\n844: +\t\tt.Fatalf(\"packets = %+v, want only the one stamped before the end\", parsed.packets)\n845: +\t}\n846: +}\n847: +\n848: +func TestCaptureLocalFailsWithoutOutputWhenAnInterfaceCannotBeOpened(t *testing.T) {\n849: +\tt.Parallel()\n850: +\n851: +\thost := newFakeHost()\n852: +\thost.setMissing(\"r2\", true)\n853: +\ttargets := []LocalTarget{\n854: +\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n855: +\t\t{Node: \"r2\", Interface: \"e2\", Exec: host.exec(\"r2\")},\n856: +\t}\n857: +\n858: +\tvar out bytes.Buffer\n859: +\terr := host.capture().run(context.Background(), localRequest(0, 0), targets, &out)\n860: +\tif err == nil || !strings.Contains(err.Error(), `failed to start the capture on node \"r2\"`) {\n861: +\t\tt.Fatalf(\"error = %v\", err)\n862: +\t}\n863: +\tif out.Len() != 0 {\n864: +\t\tt.Fatalf(\"wrote %d bytes before failing\", out.Len())\n865: +\t}\n866: +\tselect {\n867: +\tcase <-host.source(\"e1\", 0).closed:\n868: +\tdefault:\n869: +\t\tt.Fatal(\"the source opened before the failure was not closed\")\n870: +\t}\n871: +}\n872: +\n873: +func TestCaptureLocalReopensInterfacesAndReportsWhileTheyWereGone(t *testing.T) {\n874: +\tt.Parallel()\n875: +\n876: +\thost := newFakeHost()\n877: +\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n878: +\treq := localRequest(2, 0)\n879: +\treq.Targets = req.Targets[:1]\n880: +\n881: +\tvar mu sync.Mutex\n882: +\tvar gaps []clablabruntime.CaptureGap\n883: +\treq.OnGap = func(gap clablabruntime.CaptureGap) {\n884: +\t\tmu.Lock()\n885: +\t\tdefer mu.Unlock()\n886: +\t\tgaps = append(gaps, gap)\n887: +\t}\n888: +\n889: +\tvar out bytes.Buffer\n890: +\tdone := make(chan error, 1)\n891: +\tgo func() {\n892: +\t\tdone <- host.capture().run(context.Background(), req, targets, &out)\n893: +\t}()\n894: +\thost.waitOpened(t, 1)\n895: +\n896: +\tbase := time.Unix(1_761_559_200, 0)\n897: +\thost.source(\"e1\", 0).frames <- fakeFrame{data: []byte(\"a\"), stamp: base, length: 1}\n898: +\n899: +\t// the interface goes down: the socket fails and is reopened at once, without a gap\n900: +\thost.source(\"e1\", 0).frames <- fakeFrame{err: afpacket.ErrPoll}\n901: +\thost.waitOpened(t, 1)\n902: +\n903: +\t// the node restarts: the interface is gone for a while, then back\n904: +\thost.setMissing(\"r1\", true)\n905: +\thost.source(\"e1\", 1).frames <- fakeFrame{err: afpacket.ErrPoll}\n906: +\ttime.Sleep(20 * time.Millisecond)\n907: +\thost.setMissing(\"r1\", false)\n908: +\thost.waitOpened(t, 1)\n909: +\thost.source(\"e1\", 2).frames <- fakeFrame{\n910: +\t\tdata: []byte(\"b\"), stamp: base.Add(time.Second), length: 1,\n911: +\t}\n912: +\n913: +\tselect {\n914: +\tcase err := <-done:\n915: +\t\tif err != nil {\n916: +\t\t\tt.Fatal(err)\n917: +\t\t}\n918: +\tcase <-time.After(5 * time.Second):\n919: +\t\tt.Fatal(\"capture did not stop at the packet limit\")\n920: +\t}\n921: +\n922: +\tif parsed := parseLocalCapture(t, out.Bytes()); len(parsed.packets) != 2 {\n923: +\t\tt.Fatalf(\"captured %d packets across the reopen, want 2\", len(parsed.packets))\n924: +\t}\n925: +\tmu.Lock()\n926: +\tdefer mu.Unlock()\n927: +\tif len(gaps) != 1 {\n928: +\t\tt.Fatalf(\"gaps = %+v, want one for the restart\", gaps)\n929: +\t}\n930: +\tgap := gaps[0]\n931: +\tif gap.Node != \"r1\" || !slices.Equal(gap.Interfaces, []string{\"e1\"}) || gap.To.IsZero() ||\n932: +\t\t!gap.To.After(gap.From) || !strings.Contains(gap.Reason, \"not available\") {\n933: +\t\tt.Fatalf(\"gap = %+v\", gap)\n934: +\t}\n935: +}\n936: +\n937: +func TestCaptureLocalChecksTheRequest(t *testing.T) {\n938: +\tt.Parallel()\n939: +\n940: +\thost := newFakeHost()\n941: +\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n942: +\n943: +\treq := localRequest(0, 0)\n944: +\treq.SnapLength = 10\n945: +\tif err := host.capture().run(context.Background(), req, targets[:1], io.Discard); err == nil ||\n946: +\t\t!strings.Contains(err.Error(), \"snap length 10\") {\n947: +\t\tt.Fatalf(\"small snap length: error = %v\", err)\n948: +\t}\n949: +\n950: +\tif err := host.capture().run(context.Background(), localRequest(0, 0), targets,\n951: +\t\tio.Discard); err == nil || !strings.Contains(err.Error(), \"1 resolved targets for 2\") {\n952: +\t\tt.Fatalf(\"target mismatch: error = %v\", err)\n953: +\t}\n954: +}\n955: diff --git a/capture/output.go b/capture/output.go\n956: new file mode 100644\n957: index 0000000..574c33a\n958: --- /dev/null\n959: +++ b/capture/output.go\n960: @@ -0,0 +1,203 @@\n961: +package capture\n962: +\n963: +import (\n964: +\t\"context\"\n965: +\t\"fmt\"\n966: +\t\"io\"\n967: +\t\"strings\"\n968: +\t\"sync/atomic\"\n969: +\t\"time\"\n970: +\n971: +\t\"github.com/charmbracelet/log\"\n972: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n973: +)\n974: +\n975: +// Snap length bounds of a capture.\n976: +const (\n977: +\t// DefaultSnapLength is the snap length of a request without one.\n978: +\tDefaultSnapLength = 256 << 10\n979: +\tMinSnapLength     = 64\n980: +\tMaxSnapLength     = 1 << 20\n981: +)\n982: +\n983: +// ValidateRequest checks the bounds of a capture request and fills the default snap length.\n984: +func ValidateRequest(req *clablabruntime.CaptureRequest) error {\n985: +\tif req.Name == \"\" {\n986: +\t\treturn fmt.Errorf(\"topology name is required\")\n987: +\t}\n988: +\tif len(req.Targets) == 0 {\n989: +\t\treturn fmt.Errorf(\"at least one capture target (node and interface) is required\")\n990: +\t}\n991: +\tfor _, target := range req.Targets {\n992: +\t\tif target.Node == \"\" || target.Interface == \"\" {\n993: +\t\t\treturn fmt.Errorf(\"capture target %+v needs a node and an interface\", target)\n994: +\t\t}\n995: +\t}\n996: +\tif req.Duration < 0 {\n997: +\t\treturn fmt.Errorf(\"capture duration must not be negative\")\n998: +\t}\n999: +\tif req.PacketLimit < 0 {\n1000: +\t\treturn fmt.Errorf(\"capture packet limit must not be negative\")\n1001: +\t}\n1002: +\tif req.SnapLength == 0 {\n1003: +\t\treq.SnapLength = DefaultSnapLength\n1004: +\t}\n1005: +\tif req.SnapLength < MinSnapLength || req.SnapLength > MaxSnapLength {\n1006: +\t\treturn fmt.Errorf(\"capture snap length %d is outside %d to %d bytes\", req.SnapLength,\n1007: +\t\t\tMinSnapLength, MaxSnapLength)\n1008: +\t}\n1009: +\n1010: +\treturn nil\n1011: +}\n1012: +\n1013: +// FindInterface matches a requested interface by its name, then by its alias.\n1014: +func FindInterface(\n1015: +\tentries []clablabruntime.CaptureInterface,\n1016: +\tname string,\n1017: +) (clablabruntime.CaptureInterface, bool) {\n1018: +\tfor _, entry := range entries {\n1019: +\t\tif entry.Interface == name {\n1020: +\t\t\treturn entry, true\n1021: +\t\t}\n1022: +\t}\n1023: +\tfor _, entry := range entries {\n1024: +\t\tif entry.Alias != \"\" && entry.Alias == name {\n1025: +\t\t\treturn entry, true\n1026: +\t\t}\n1027: +\t}\n1028: +\n1029: +\treturn clablabruntime.CaptureInterface{}, false\n1030: +}\n1031: +\n1032: +// DescribeInterfaces lists interfaces for an error message: name (alias), ...\n1033: +func DescribeInterfaces(entries []clablabruntime.CaptureInterface) string {\n1034: +\tif len(entries) == 0 {\n1035: +\t\treturn \"none\"\n1036: +\t}\n1037: +\n1038: +\tnames := make([]string, 0, len(entries))\n1039: +\tfor _, entry := range entries {\n1040: +\t\tname := entry.Interface\n1041: +\t\tif entry.Alias != \"\" {\n1042: +\t\t\tname += \" (\" + entry.Alias + \")\"\n1043: +\t\t}\n1044: +\t\tnames = append(names, name)\n1045: +\t}\n1046: +\n1047: +\treturn strings.Join(names, \", \")\n1048: +}\n1049: +\n1050: +// ReportGap hands a gap to onGap, or logs it as a warning when onGap is nil.\n1051: +func ReportGap(onGap func(clablabruntime.CaptureGap), gap clablabruntime.CaptureGap) {\n1052: +\tif onGap != nil {\n1053: +\t\tonGap(gap)\n1054: +\t\treturn\n1055: +\t}\n1056: +\n1057: +\tto := \"unknown\"\n1058: +\tif !gap.To.IsZero() {\n1059: +\t\tto = gap.To.Format(time.RFC3339Nano)\n1060: +\t}\n1061: +\tlog.Warn(\"Capture has a gap\", \"node\", gap.Node, \"interfaces\", strings.Join(gap.Interfaces, \",\"),\n1062: +\t\t\"from\", gap.From.Format(time.RFC3339Nano), \"to\", to, \"reason\", gap.Reason)\n1063: +}\n1064: +\n1065: +// Output is the merged pcapng stream of one capture: the section header with one interface per\n1066: +// capture target, then the packets of every target in timestamp order (through a Reorder), up\n1067: +// to an optional packet limit.\n1068: +type Output struct {\n1069: +\twriter  *Writer\n1070: +\treorder *Reorder\n1071: +\tlimit   int64\n1072: +\twritten atomic.Int64\n1073: +\tstop    func()\n1074: +\n1075: +\tcancelRun context.CancelFunc\n1076: +\trunDone   chan struct{}\n1077: +}\n1078: +\n1079: +// NewOutput writes the section header and one Interface Description Block per name to w, then\n1080: +// starts the reorder buffer with the given window (zero or less writes packets as they come).\n1081: +// stop is called once the packet limit is reached or a write failed. Close must be called.\n1082: +func NewOutput(\n1083: +\tw io.Writer,\n1084: +\tnames []string,\n1085: +\tsnapLength, packetLimit int,\n1086: +\twindow time.Duration,\n1087: +\tstop func(),\n1088: +) (*Output, error) {\n1089: +\twriter := NewWriter(w)\n1090: +\tif err := writer.WriteHeader(\n1091: +\t\tnames,\n1092: +\t\tuint32(snapLength),\n1093: +\t); err != nil { //nolint:gosec // validated\n1094: +\t\treturn nil, err\n1095: +\t}\n1096: +\n1097: +\tout := &Output{\n1098: +\t\twriter:  writer,\n1099: +\t\treorder: NewReorder(window, writer.WritePacket, stop),\n1100: +\t\tlimit:   int64(packetLimit),\n\n(Showing lines 401-1100 of 7018. Use offset=1101 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+\tsnapLength int,\n+) ([]packetSource, error) {\n+\tsources := make([]packetSource, 0, len(interfaces))\n+\terr := exec(ctx, func(ns.NetNS) error {\n+\t\tfor _, name := range interfaces {\n+\t\t\tsource, err := openPacketSocket(name, snapLength)\n+\t\t\tif err != nil {\n+\t\t\t\treturn fmt.Errorf(\"interface %q: %w\", name, err)\n+\t\t\t}\n+\t\t\tsources = append(sources, source)\n+\t\t}\n+\n+\t\treturn nil\n+\t})\n+\tif err != nil {\n+\t\tfor _, source := range sources {\n+\t\t\tsource.Close()\n+\t\t}\n+\n+\t\treturn nil, err",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+\tsnapLength int,\n+) ([]packetSource, error) {\n+\tsources := make([]packetSource, 0, len(interfaces))\n+\terr := exec(ctx, func(ns.NetNS) error {\n+\t\tfor _, name := range interfaces {\n+\t\t\tsource, err := openPacketSocket(name, snapLength)\n+\t\t\tif err != nil {\n+\t\t\t\treturn fmt.Errorf(\"interface %q: %w\", name, err)\n+\t\t\t}\n+\t\t\tsources = append(sources, source)\n+\t\t}\n+\n+\t\treturn nil\n+\t})\n+\tif err != nil {\n+\t\tfor _, source := range sources {\n+\t\t\tsource.Close()\n+\t\t}\n+\n+\t\treturn nil, err\n+\t}\n+\n+\treturn sources, nil\n+}\n+\n+// afpacketSource is a TPACKET_V3 receive ring on one interface.\n+type afpacketSource struct {\n+\thandle *afpacket.TPacket\n+}\n+\n+func openPacketSocket(name string, snapLength int) (*afpacketSource, error) {\n+\t// A TPACKET_V3 block holds whole frames: it must be larger than the snap length, plus the\n+\t// block and frame headers, and a multiple of the page size.\n+\tpageSize := os.Getpagesize()\n+\tblockSize := max(localMinBlockSize, snapLength+pageSize)\n+\tblockSize = (blockSize + pageSize - 1) / pageSize * pageSize\n+\n+\thandle, err := afpacket.NewTPacket(\n+\t\tafpacket.OptInterface(name),\n+\t\tafpacket.OptTPacketVersion(afpacket.TPacketVersion3),\n+\t\tafpacket.OptFrameSize(blockSize),\n+\t\tafpacket.OptBlockSize(blockSize),\n+\t\tafpacket.OptNumBlocks(localRingBlocks),\n+\t\tafpacket.OptBlockTimeout(localBlockTimeout),\n+\t\tafpacket.OptPollTimeout(localPollTimeout),\n+\t\t// the kernel moves 802.1Q tags out of the frame; captures show them in place\n+\t\tafpacket.OptAddVLANHeader(true),\n+\t)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\t// promiscuous mode is a membership of this socket and ends with it\n+\tif err := handle.SetPromiscuous(true); err != nil {\n+\t\thandle.Close()\n+\t\treturn nil, fmt.Errorf(\"failed to enable promiscuous mode: %w\", err)\n+\t}\n+\n+\treturn &afpacketSource{handle: handle}, nil\n+}\n+\n+func (s *afpacketSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {\n+\tdata, info, err := s.handle.ZeroCopyReadPacketData()\n+\tif errors.Is(err, afpacket.ErrTimeout) {\n+\t\treturn nil, info, errReadTimeout\n+\t}\n+\n+\treturn data, info, err\n+}\n+\n+func (s *afpacketSource) Close() {\n+\ts.handle.Close()\n+}\ndiff --git a/capture/local_test.go b/capture/local_test.go\nnew file mode 100644\nindex 0000000..f91bb00\n--- /dev/null\n+++ b/capture/local_test.go\n@@ -0,0 +1,476 @@\n+package capture\n+\n+import (\n+\t\"bytes\"\n+\t\"context\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"slices\"\n+\t\"strings\"\n+\t\"sync\"\n+\t\"testing\"\n+\t\"time\"\n+\n+\t\"github.com/containernetworking/plugins/pkg/ns\"\n+\t\"github.com/gopacket/gopacket\"\n+\t\"github.com/gopacket/gopacket/afpacket\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+)\n+\n+// fakeFrame is one packet a fake source returns.\n+type fakeFrame struct {\n+\tdata   []byte\n+\tstamp  time.Time\n+\tlength int\n+\tvlan   bool\n+\t// visible delays the frame like a ring block the kernel has not handed over yet.\n+\tvisible time.Time\n+\t// err ends the source with this error instead of a packet.\n+\terr error\n+}\n+\n+// fakeSource returns frames from a channel, errReadTimeout while none is queued.\n+type fakeSource struct {\n+\tframes  chan fakeFrame\n+\tclosed  chan struct{}\n+\tonce    sync.Once\n+\tpending *fakeFrame\n+}\n+\n+func newFakeSource() *fakeSource {\n+\treturn &fakeSource{frames: make(chan fakeFrame, 64), closed: make(chan struct{})}\n+}\n+\n+func (s *fakeSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {\n+\tif s.pending == nil {\n+\t\tselect {\n+\t\tcase frame := <-s.frames:\n+\t\t\ts.pending = &frame\n+\t\tcase <-time.After(5 * time.Millisecond):\n+\t\t\treturn nil, gopacket.CaptureInfo{}, errReadTimeout\n+\t\t}\n+\t}\n+\tif wait := time.Until(s.pending.visible); wait > 0 {\n+\t\ttime.Sleep(min(wait, 5*time.Millisecond))\n+\t\tif time.Now().Before(s.pending.visible) {\n+\t\t\treturn nil, gopacket.CaptureInfo{}, errReadTimeout\n+\t\t}\n+\t}\n+\n+\t{\n+\t\tframe := *s.pending\n+\t\ts.pending = nil\n+\t\tif frame.err != nil {\n+\t\t\treturn nil, gopacket.CaptureInfo{}, frame.err\n+\t\t}\n+\t\tinfo := gopacket.CaptureInfo{\n+\t\t\tTimestamp: frame.stamp, CaptureLength: len(frame.data), Length: frame.length,\n+\t\t}\n+\t\tif frame.vlan {\n+\t\t\tinfo.AncillaryData = []any{afpacket.AncillaryVLAN{VLAN: 10}}\n+\t\t}\n+\n+\t\treturn frame.data, info, nil\n+\t}\n+}\n+\n+func (s *fakeSource) Close() {\n+\ts.once.Do(func() { close(s.closed) })\n+}\n+\n+// fakeHost hands out fake sources per node and interface. Opening an interface listed in\n+// missing fails, like an interface whose node does not run.\n+type fakeHost struct {\n+\tmu      sync.Mutex\n+\topened  map[string][]*fakeSource\n+\tmissing map[string]bool\n+\tready   chan string\n+}\n+\n+func newFakeHost() *fakeHost {\n+\treturn &fakeHost{\n+\t\topened: map[string][]*fakeSource{}, missing: map[string]bool{},\n+\t\tready: make(chan string, 64),\n+\t}\n+}\n+\n+func (h *fakeHost) exec(node string) ExecFunc {\n+\treturn func(_ context.Context, f func(ns.NetNS) error) error {\n+\t\th.mu.Lock()\n+\t\tmissing := h.missing[node]\n+\t\th.mu.Unlock()\n+\t\tif missing {\n+\t\t\treturn fmt.Errorf(\"node %q: container network namespace is not available\", node)\n+\t\t}\n+\n+\t\treturn f(nil)\n+\t}\n+}\n+\n+func (h *fakeHost) open(\n+\tctx context.Context,\n+\texec ExecFunc,\n+\tinterfaces []string,\n+\t_ int,\n+) ([]packetSource, error) {\n+\tvar node string\n+\terr := exec(ctx, func(ns.NetNS) error { return nil })\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\th.mu.Lock()\n+\tdefer h.mu.Unlock()\n+\tsources := make([]packetSource, 0, len(interfaces))\n+\tfor _, name := range interfaces {\n+\t\tif h.missing[name] {\n+\t\t\treturn nil, fmt.Errorf(\"interface %q: no such network interface\", name)\n+\t\t}\n+\t\tnode = name\n+\t\tsource := newFakeSource()\n+\t\th.opened[name] = append(h.opened[name], source)\n+\t\tsources = append(sources, source)\n+\t\th.ready <- node\n+\t}\n+\n+\treturn sources, nil\n+}\n+\n+func (h *fakeHost) source(name string, generation int) *fakeSource {\n+\th.mu.Lock()\n+\tdefer h.mu.Unlock()\n+\n+\treturn h.opened[name][generation]\n+}\n+\n+func (h *fakeHost) setMissing(name string, missing bool) {\n+\th.mu.Lock()\n+\tdefer h.mu.Unlock()\n+\th.missing[name] = missing\n+}\n+\n+func (h *fakeHost) capture() localCapture {\n+\treturn localCapture{\n+\t\topen:           h.open,\n+\t\twindow:         20 * time.Millisecond,\n+\t\treopenInterval: time.Millisecond,\n+\t}\n+}\n+\n+// waitOpened waits until n sources were opened.\n+func (h *fakeHost) waitOpened(t *testing.T, n int) {\n+\tt.Helper()\n+\tfor range n {\n+\t\tselect {\n+\t\tcase <-h.ready:\n+\t\tcase <-time.After(2 * time.Second):\n+\t\t\tt.Fatal(\"source was not opened\")\n+\t\t}\n+\t}\n+}\n+\n+type parsedLocalCapture struct {\n+\tinterfaces []string\n+\tpackets    []Packet\n+}\n+\n+func parseLocalCapture(t *testing.T, data []byte) parsedLocalCapture {\n+\tt.Helper()\n+\n+\tvar parsed parsedLocalCapture\n+\treader := NewReader(bytes.NewReader(data))\n+\tfor {\n+\t\tevent, err := reader.Next()\n+\t\tif errors.Is(err, io.EOF) {\n+\t\t\tbreak\n+\t\t}\n+\t\tif err != nil {\n+\t\t\tt.Fatalf(\"invalid capture: %v\", err)\n+\t\t}\n+\t\tif event.Interface != nil {\n+\t\t\tparsed.interfaces = append(parsed.interfaces, event.Interface.Name)\n+\t\t}\n+\t\tif event.Packet != nil {\n+\t\t\tparsed.packets = append(parsed.packets, *event.Packet)\n+\t\t}\n+\t}\n+\tif reader.Sections() != 1 {\n+\t\tt.Fatalf(\"capture has %d sections\", reader.Sections())\n+\t}\n+\n+\treturn parsed\n+}\n+\n+func localRequest(packetLimit int, duration time.Duration) clablabruntime.CaptureRequest {\n+\treturn clablabruntime.CaptureRequest{\n+\t\tName: \"lab\",\n+\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t{Node: \"r1\", Interface: \"eth1\"}, {Node: \"r2\", Interface: \"eth1\"},\n+\t\t},\n+\t\tPacketLimit: packetLimit,\n+\t\tDuration:    duration,\n+\t\tSnapLength:  64,\n+\t}\n+}\n+\n+func TestCaptureLocalMergesInterfacesInTimestampOrder(t *testing.T) {\n+\tt.Parallel()\n+\n+\thost := newFakeHost()\n+\t// the sources are keyed by interface name in the fake host, so the two nodes use distinct\n+\t// names behind the requested ones\n+\ttargets := []LocalTarget{\n+\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n+\t\t{Node: \"r2\", Interface: \"e2\", Exec: host.exec(\"r2\")},\n+\t}\n+\n+\tvar out bytes.Buffer\n+\tdone := make(chan error, 1)\n+\tgo func() {\n+\t\tdone <- host.capture().run(context.Background(), localRequest(4, 0), targets, &out)\n+\t}()\n+\thost.waitOpened(t, 2)\n+\n+\tbase := time.Unix(1_761_559_200, 0)\n+\t// r2's packets reach containerlab first although r1 stamped one of them earlier\n+\thost.source(\"e2\", 0).frames <- fakeFrame{\n+\t\tdata: []byte(\"r2-a\"), stamp: base.Add(2 * time.Millisecond), length: 4,\n+\t}\n+\thost.source(\"e2\", 0).frames <- fakeFrame{\n+\t\tdata: bytes.Repeat([]byte{7}, 100), stamp: base.Add(4 * time.Millisecond), length: 100,\n+\t}\n+\thost.source(\"e1\", 0).frames <- fakeFrame{\n+\t\tdata: []byte(\"r1-a\"), stamp: base.Add(1 * time.Millisecond), length: 4,\n+\t}\n+\thost.source(\"e1\", 0).frames <- fakeFrame{\n+\t\tdata: []byte(\"r1-v\"), stamp: base.Add(3 * time.Millisecond), length: 60, vlan: true,\n+\t}\n+\n+\tselect {\n+\tcase err := <-done:\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\tcase <-time.After(5 * time.Second):\n+\t\tt.Fatal(\"capture did not stop at the packet limit\")\n+\t}\n+\n+\tparsed := parseLocalCapture(t, out.Bytes())\n+\tif want := []string{\"r1:e1\", \"r2:e2\"}; !slices.Equal(parsed.interfaces, want) {\n+\t\tt.Fatalf(\"interfaces = %v, want %v\", parsed.interfaces, want)\n+\t}\n+\tif len(parsed.packets) != 4 {\n+\t\tt.Fatalf(\"captured %d packets, want 4\", len(parsed.packets))\n+\t}\n+\tvar ids []uint32\n+\tfor idx, packet := range parsed.packets {\n+\t\tids = append(ids, packet.InterfaceID)\n+\t\tif want := base.Add(time.Duration(idx+1) * time.Millisecond).\n+\t\t\tUnixNano(); packet.Timestamp != want {\n+\t\t\tt.Fatalf(\"packet %d stamped %d, want %d\", idx, packet.Timestamp, want)\n+\t\t}\n+\t}\n+\tif !slices.Equal(ids, []uint32{0, 1, 0, 1}) {\n+\t\tt.Fatalf(\"interface IDs = %v\", ids)\n+\t}\n+\t// a re-inserted VLAN tag counts toward the frame length\n+\tif parsed.packets[2].OriginalLength != 64 {\n+\t\tt.Fatalf(\"VLAN frame length = %d, want 64\", parsed.packets[2].OriginalLength)\n+\t}\n+\t// frames are cut to the snap length\n+\tif last := parsed.packets[3]; len(last.Data) != 64 || last.OriginalLength != 100 {\n+\t\tt.Fatalf(\"long frame kept %d of %d bytes\", len(last.Data), last.OriginalLength)\n+\t}\n+\tfor _, name := range []string{\"e1\", \"e2\"} {\n+\t\tselect {\n+\t\tcase <-host.source(name, 0).closed:\n+\t\tdefault:\n+\t\t\tt.Fatalf(\"source %s was not closed\", name)\n+\t\t}\n+\t}\n+}\n+\n+func TestCaptureLocalEndsAfterTheDurationOrWhenCanceled(t *testing.T) {\n+\tt.Parallel()\n+\n+\thost := newFakeHost()\n+\ttargets := []LocalTarget{\n+\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n+\t\t{Node: \"r1\", Interface: \"e2\", Exec: host.exec(\"r1\")},\n+\t}\n+\n+\tvar out bytes.Buffer\n+\tstart := time.Now()\n+\tif err := host.capture().run(context.Background(), localRequest(0, 50*time.Millisecond),\n+\t\ttargets, &out); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif elapsed := time.Since(start); elapsed < 50*time.Millisecond || elapsed > 2*time.Second {\n+\t\tt.Fatalf(\"capture ran %s for a 50ms duration\", elapsed)\n+\t}\n+\tif parsed := parseLocalCapture(t, out.Bytes()); len(parsed.interfaces) != 2 {\n+\t\tt.Fatalf(\"interfaces = %v\", parsed.interfaces)\n+\t}\n+\n+\tctx, cancel := context.WithCancel(context.Background())\n+\tdone := make(chan error, 1)\n+\tgo func() {\n+\t\tdone <- host.capture().run(ctx, localRequest(0, 0), targets, io.Discard)\n+\t}()\n+\thost.waitOpened(t, 4)\n+\tcancel()\n+\tselect {\n+\tcase err := <-done:\n+\t\tif err != nil {\n+\t\t\tt.Fatalf(\"canceled capture returned %v\", err)\n+\t\t}\n+\tcase <-time.After(2 * time.Second):\n+\t\tt.Fatal(\"canceled capture did not end\")\n+\t}\n+}\n+\n+func TestCaptureLocalWritesPacketsStillInTheRingWhenItEnds(t *testing.T) {\n+\tt.Parallel()\n+\n+\thost := newFakeHost()\n+\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n+\treq := localRequest(0, 0)\n+\treq.Targets = req.Targets[:1]\n+\n+\tctx, cancel := context.WithCancel(context.Background())\n+\tvar out bytes.Buffer\n+\tdone := make(chan error, 1)\n+\tgo func() {\n+\t\tdone <- host.capture().run(ctx, req, targets, &out)\n+\t}()\n+\thost.waitOpened(t, 1)\n+\n+\tnow := time.Now()\n+\t// stamped before the end, handed over by the kernel only after it\n+\thost.source(\"e1\", 0).frames <- fakeFrame{\n+\t\tdata: []byte(\"before\"), stamp: now, length: 6, visible: now.Add(30 * time.Millisecond),\n+\t}\n+\t// stamped after the end: not part of the capture\n+\thost.source(\"e1\", 0).frames <- fakeFrame{\n+\t\tdata: []byte(\"after\"), stamp: now.Add(time.Hour), length: 5,\n+\t\tvisible: now.Add(40 * time.Millisecond),\n+\t}\n+\tcancel()\n+\n+\tif err := <-done; err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tparsed := parseLocalCapture(t, out.Bytes())\n+\tif len(parsed.packets) != 1 || string(parsed.packets[0].Data) != \"before\" {\n+\t\tt.Fatalf(\"packets = %+v, want only the one stamped before the end\", parsed.packets)\n+\t}\n+}\n+\n+func TestCaptureLocalFailsWithoutOutputWhenAnInterfaceCannotBeOpened(t *testing.T) {\n+\tt.Parallel()\n+\n+\thost := newFakeHost()\n+\thost.setMissing(\"r2\", true)\n+\ttargets := []LocalTarget{\n+\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n+\t\t{Node: \"r2\", Interface: \"e2\", Exec: host.exec(\"r2\")},\n+\t}\n+\n+\tvar out bytes.Buffer\n+\terr := host.capture().run(context.Background(), localRequest(0, 0), targets, &out)\n+\tif err == nil || !strings.Contains(err.Error(), `failed to start the capture on node \"r2\"`) {\n+\t\tt.Fatalf(\"error = %v\", err)\n+\t}\n+\tif out.Len() != 0 {\n+\t\tt.Fatalf(\"wrote %d bytes before failing\", out.Len())\n+\t}\n+\tselect {\n+\tcase <-host.source(\"e1\", 0).closed:\n+\tdefault:\n+\t\tt.Fatal(\"the source opened before the failure was not closed\")\n+\t}\n+}\n+\n+func TestCaptureLocalReopensInterfacesAndReportsWhileTheyWereGone(t *testing.T) {\n+\tt.Parallel()\n+\n+\thost := newFakeHost()\n+\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n+\treq := localRequest(2, 0)\n+\treq.Targets = req.Targets[:1]\n+\n+\tvar mu sync.Mutex\n+\tvar gaps []clablabruntime.CaptureGap\n+\treq.OnGap = func(gap clablabruntime.CaptureGap) {\n+\t\tmu.Lock()\n+\t\tdefer mu.Unlock()\n+\t\tgaps = append(gaps, gap)\n+\t}\n+\n+\tvar out bytes.Buffer\n+\tdone := make(chan error, 1)\n+\tgo func() {\n+\t\tdone <- host.capture().run(context.Background(), req, targets, &out)\n+\t}()\n+\thost.waitOpened(t, 1)\n+\n+\tbase := time.Unix(1_761_559_200, 0)\n+\thost.source(\"e1\", 0).frames <- fakeFrame{data: []byte(\"a\"), stamp: base, length: 1}\n+\n+\t// the interface goes down: the socket fails and is reopened at once, without a gap\n+\thost.source(\"e1\", 0).frames <- fakeFrame{err: afpacket.ErrPoll}\n+\thost.waitOpened(t, 1)\n+\n+\t// the node restarts: the interface is gone for a while, then back\n+\thost.setMissing(\"r1\", true)\n+\thost.source(\"e1\", 1).frames <- fakeFrame{err: afpacket.ErrPoll}\n+\ttime.Sleep(20 * time.Millisecond)\n+\thost.setMissing(\"r1\", false)\n+\thost.waitOpened(t, 1)\n+\thost.source(\"e1\", 2).frames <- fakeFrame{\n+\t\tdata: []byte(\"b\"), stamp: base.Add(time.Second), length: 1,\n+\t}\n+\n+\tselect {\n+\tcase err := <-done:\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\tcase <-time.After(5 * time.Second):\n+\t\tt.Fatal(\"capture did not stop at the packet limit\")\n+\t}\n+\n+\tif parsed := parseLocalCapture(t, out.Bytes()); len(parsed.packets) != 2 {\n+\t\tt.Fatalf(\"captured %d packets across the reopen, want 2\", len(parsed.packets))\n+\t}\n+\tmu.Lock()\n+\tdefer mu.Unlock()\n+\tif len(gaps) != 1 {\n+\t\tt.Fatalf(\"gaps = %+v, want one for the restart\", gaps)\n+\t}\n+\tgap := gaps[0]\n+\tif gap.Node != \"r1\" || !slices.Equal(gap.Interfaces, []string{\"e1\"}) || gap.To.IsZero() ||\n+\t\t!gap.To.After(gap.From) || !strings.Contains(gap.Reason, \"not available\") {\n+\t\tt.Fatalf(\"gap = %+v\", gap)\n+\t}\n+}\n+\n+func TestCaptureLocalChecksTheRequest(t *testing.T) {\n+\tt.Parallel()\n+\n+\thost := newFakeHost()\n+\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n+\n+\treq := localRequest(0, 0)\n+\treq.SnapLength = 10\n+\tif err := host.capture().run(context.Background(), req, targets[:1], io.Discard); err == nil ||\n+\t\t!strings.Contains(err.Error(), \"snap length 10\") {\n+\t\tt.Fatalf(\"small snap length: error = %v\", err)\n+\t}\n+\n+\tif err := host.capture().run(context.Background(), localRequest(0, 0), targets,\n+\t\tio.Discard); err == nil || !strings.Contains(err.Error(), \"1 resolved targets for 2\") {\n+\t\tt.Fatalf(\"target mismatch: error = %v\", err)\n+\t}\n+}\ndiff --git a/capture/output.go b/capture/output.go\nnew file mode 100644\nindex 0000000..574c33a\n--- /dev/null\n+++ b/capture/output.go\n@@ -0,0 +1,203 @@\n+package capture\n+\n+import (\n+\t\"context\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"strings\"\n+\t\"sync/atomic\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+)\n+\n+// Snap length bounds of a capture.\n+const (\n+\t// DefaultSnapLength is the snap length of a request without one.\n+\tDefaultSnapLength = 256 << 10\n+\tMinSnapLength     = 64\n+\tMaxSnapLength     = 1 << 20\n+)\n+\n+// ValidateRequest checks the bounds of a capture request and fills the default snap length.\n+func ValidateRequest(req *clablabruntime.CaptureRequest) error {\n+\tif req.Name == \"\" {\n+\t\treturn fmt.Errorf(\"topology name is required\")\n+\t}\n+\tif len(req.Targets) == 0 {\n+\t\treturn fmt.Errorf(\"at least one capture target (node and interface) is required\")\n+\t}\n+\tfor _, target := range req.Targets {\n+\t\tif target.Node == \"\" || target.Interface == \"\" {\n+\t\t\treturn fmt.Errorf(\"capture target %+v needs a node and an interface\", target)\n+\t\t}\n+\t}\n+\tif req.Duration < 0 {\n+\t\treturn fmt.Errorf(\"capture duration must not be negative\")\n+\t}\n+\tif req.PacketLimit < 0 {\n+\t\treturn fmt.Errorf(\"capture packet limit must not be negative\")\n+\t}\n+\tif req.SnapLength == 0 {\n+\t\treq.SnapLength = DefaultSnapLength\n+\t}\n+\tif req.SnapLength < MinSnapLength || req.SnapLength > MaxSnapLength {\n+\t\treturn fmt.Errorf(\"capture snap length %d is outside %d to %d bytes\", req.SnapLength,\n+\t\t\tMinSnapLength, MaxSnapLength)\n+\t}\n+\n+\treturn nil\n+}\n+\n+// FindInterface matches a requested interface by its name, then by its alias.\n+func FindInterface(\n+\tentries []clablabruntime.CaptureInterface,\n+\tname string,\n+) (clablabruntime.CaptureInterface, bool) {\n+\tfor _, entry := range entries {\n+\t\tif entry.Interface == name {\n+\t\t\treturn entry, true\n+\t\t}\n+\t}\n+\tfor _, entry := range entries {\n+\t\tif entry.Alias != \"\" && entry.Alias == name {\n+\t\t\treturn entry, true\n+\t\t}\n+\t}\n+\n+\treturn clablabruntime.CaptureInterface{}, false\n+}\n+\n+// DescribeInterfaces lists interfaces for an error message: name (alias), ...\n+func DescribeInterfaces(entries []clablabruntime.CaptureInterface) string {\n+\tif len(entries) == 0 {\n+\t\treturn \"none\"\n+\t}\n+\n+\tnames := make([]string, 0, len(entries))\n+\tfor _, entry := range entries {\n+\t\tname := entry.Interface\n+\t\tif entry.Alias != \"\" {\n+\t\t\tname += \" (\" + entry.Alias + \")\"\n+\t\t}\n+\t\tnames = append(names, name)\n+\t}\n+\n+\treturn strings.Join(names, \", \")\n+}\n+\n+// ReportGap hands a gap to onGap, or logs it as a warning when onGap is nil.\n+func ReportGap(onGap func(clablabruntime.CaptureGap), gap clablabruntime.CaptureGap) {\n+\tif onGap != nil {\n+\t\tonGap(gap)\n+\t\treturn\n+\t}\n+\n+\tto := \"unknown\"\n+\tif !gap.To.IsZero() {\n+\t\tto = gap.To.Format(time.RFC3339Nano)\n+\t}\n+\tlog.Warn(\"Capture has a gap\", \"node\", gap.Node, \"interfaces\", strings.Join(gap.Interfaces, \",\"),\n+\t\t\"from\", gap.From.Format(time.RFC3339Nano), \"to\", to, \"reason\", gap.Reason)\n+}\n+\n+// Output is the merged pcapng stream of one capture: the section header with one interface per\n+// capture target, then the packets of every target in timestamp order (through a Reorder), up\n+// to an optional packet limit.\n+type Output struct {\n+\twriter  *Writer\n+\treorder *Reorder\n+\tlimit   int64\n+\twritten atomic.Int64\n+\tstop    func()\n+\n+\tcancelRun context.CancelFunc\n+\trunDone   chan struct{}\n+}\n+\n+// NewOutput writes the section header and one Interface Description Block per name to w, then\n+// starts the reorder buffer with the given window (zero or less writes packets as they come).\n+// stop is called once the packet limit is reached or a write failed. Close must be called.\n+func NewOutput(\n+\tw io.Writer,\n+\tnames []string,\n+\tsnapLength, packetLimit int,\n+\twindow time.Duration,\n+\tstop func(),\n+) (*Output, error) {\n+\twriter := NewWriter(w)\n+\tif err := writer.WriteHeader(\n+\t\tnames,\n+\t\tuint32(snapLength),\n+\t); err != nil { //nolint:gosec // validated\n+\t\treturn nil, err\n+\t}\n+\n+\tout := &Output{\n+\t\twriter:  writer,\n+\t\treorder: NewReorder(window, writer.WritePacket, stop),\n+\t\tlimit:   int64(packetLimit),",
        "lineStart": 401,
        "lineEnd": 1100,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523415539,
      "end": 1793523415555
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196537a05001EBfZ45GwggdOn3",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196536ec3001DYhMjZBrLlaEIj",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 87274,
    "input": 5513,
    "output": 26,
    "reasoning": 71,
    "cache": {
      "read": 81664,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196536ec3001DYhMjZBrLlaEIj",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523412675,
    "completed": 1793523415561
  },
  "parentID": "msg_19652455c001bTBRfavhAuXSsP",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 87274,
    "input": 5513,
    "output": 26,
    "reasoning": 71,
    "cache": {
      "read": 81664,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
User · 41
compaction
{
  "type": "compaction",
  "id": "prt_196537a0b001R92mMVVaplpkHa",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196537a0a0019rqr0jWnsviNLW",
  "auto": true,
  "overflow": false,
  "tail_start_id": "msg_196534de3001UGgBavNO6PpMwe"
}
Message metadata
{
  "role": "user",
  "id": "msg_196537a0a0019rqr0jWnsviNLW",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523415562
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 42
step-start
{
  "type": "step-start",
  "id": "prt_1965382d2001cz7FLq6F54T9RZ",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196537a1e00101MSdjyJmQE5e5"
}
Reasoning
Merge prior summary with the new conversation progress. Key new work: verified cmd/context.go signal handling (FinishOnCancel), checked root.go log output (log.SetOutput(os.Stderr) → stdout purity for `-w -` confirmed), read docs/cmd/capture.md, read diff hunks 2161-2761 (cmd/capture.go), 2761-3520 (core capture), 3521-3900 (docs), read c9s capture.go chunks (60-680 truncated, 680-1210), reorder.go, output.go, local.go, pcapng.go (partially shown), LocateNode order preservation verified (access.go lines 49-91), capture_interfaces.go streamPodExec read, commandSkipsRoot verified in root.go.

Refined analysis notes:
- setCut cut==0 duplication case effectively unreachable with computed overlap/window values (window = min(500ms, overlap/4) → 2*window < overlap always) — defensive only.
- Audit error (Failed/Denied) propagates as error even when stopping — potential issue: Ctrl+C may produce error if clabwire writes Failed on stdin close (speculative, note).
- Reorder/Output analysis: backpressure chain OK, Emit counts before limit check correctly, late packet cursor benign.
- pcapng codec verified sound (SHB min body 16, EPB timestamp layout correct, padding handled).
- Local.go: openAll count assumption safe, drain deadline logic OK, reopen 200ms.
- `held`/`emitted` growth during 10s overlap at high packet rates — potential P4 unbounded memory (bounded by clabwire 1M packet limit per segment but memory could be large).
- Remaining: cmd/options.go, cmd/root.go diff hunk, cmd/root_test.go, core/labruntime_cluster_test.go, capture tests skim, clabernetes/capture_test.go, docs manual files, workflows, mkdocs nav, remaining diff paths 3900-7018 enumeration.
## Objective
- Review the read-only PR snapshot at `/source` (srl-labs/containerlab): read `standards.json` + referenced rules, fully review `diff.txt` (7018 lines, 37 changed paths) and head/base files, complete per-path checks (callers, tests, docs, schema), verify candidate defects, then produce the trusted result schema (JSON + findings).

## Important Details
- Head commit: `657b1700664a99c5e12c60b4cfd179eb11889bae`; base/mergeBase: `00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4`.
- Permalink roots: head=`https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/`; base=`https://github.com/srl-labs/containerlab/blob/00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4/`.
- Snapshot incomplete: false; full inventory in `/source/manifest.json`. Source-only review; cannot execute tests — disclose limitation in final result.
- Standards: `.cursor/rules/karpathy-guidelines.mdc` (surgical changes, simplicity) and `.cursor/rules/ponytail.mdc` (YAGNI, reuse, shortest diff).
- **Head files live under `/source/head/...`** (not `/source/capture/...`). Direct read of `/source` dir itself denied; read individual files.
- PR adds packet-capture feature: new `capture` package (`local.go`, `reorder.go`, `pcapng.go`, `output.go` + tests), new `cmd/capture.go` (+test), new `core/capture.go`/`core/capture_local.go` (+test), c9s runtime capture (`labruntime/clabernetes/capture.go` ~1202 lines, `capture_interfaces.go`), chained segments (1h max, 10s overlap, 500ms cut window), `CaptureGap` reporting, docs/workflow/CMD changes.
- Diff grep anchors (`^diff --git` lines): workflows (1, 21), capture/* (37–1676), cmd/* (2161–2709), core/* (2744–3320), test_data (3490), docs (3511–3879), `labruntime/clabernetes/` starts at 3900; runtime.go interface additions at 6390–6474; remaining 3900–7018 paths (tests, clabernetes.go) partially enumerated.
- cmd context facts: `log.SetOutput(os.Stderr)` in `cmd/root.go:163` → stdout stays pure for `-w -` pcapng (verified). `commandSkipsRoot` (`cmd/root.go:211`) returns `IsLabRuntimeName(name)` — capture/inspect PreRunE skip root for c9s. `LocateNode` (`labruntime/clabernetes/access.go:49`) preserves request order for named nodes → `resolveCaptureTargets`'s `byRequest` mapping is safe.
- `cmd/context.go` FinishOnCancel verified: first signal closes `cancellationSignaled`, cancels ctx, logs "Stopping, press Ctrl+C again to abort", waits for second signal then `os.Exit(1)`; goroutine leak on clean exit is benign.

## Work State
### Completed
- Read standards + both rule files; full diff.txt traversed (overlapping reads at offsets 1, 1702, 3478, 4780, 6410, plus 2161, 2761, 3521, 3900, 6357); manifest.json read.
- Detailed review of head files: `capture/local.go` (constants: localReorderWindow=100ms, localBlockTimeout=10ms, localPollTimeout=100ms, localReopenInterval=200ms, localDrainQuiet=5×block, localDrainTimeout=250ms, ring 8×1MiB, vlanHeaderLength=4; openAll count assumption verified safe; drain deadline logic verified correct), `capture/reorder.go` (min-heap, maxReorderBytes=64MiB, holds map, cursor; late-packet cursor non-update verified benign; Push/writeDue mutex backpressure chain verified deadlock-free), `capture/pcapng.go` (codec verified sound: SHB min body 16, EPB timestamp high/low layout correct, padding handled, tsresol semantics verified; Reader.Next ErrUnexpectedEOF only on truncated stream), `capture/output.go` (ValidateRequest: DefaultSnapLength=256KiB bounds 64..1MiB; Emit limit-th packet correctly written; Written() atomic races benign), `cmd/capture.go` (flags --target/--duration/--packet-limit/--snap-length/--write/--list/--format; PreRunE root skip), `core/capture.go` (CLab.Capture/CaptureInterfaces dispatch), `labruntime/clabernetes/capture.go` (full read of captureChain state machine lines 60–1210: stop/drain/segmentDuration/nextStartIn/startNext/handle/switchSegments; audit schema `c9s.direct-packet-capture-audit/v1alpha1`; events chan buf 256), `labruntime/clabernetes/capture_interfaces.go` (streamPodExec via StreamWithContext, ExitError → CommandExitError), `labruntime/clabernetes/access.go` LocateNode ordering, `cmd/context.go`, `cmd/root.go` (root-skip logic, log stderr), `docs/cmd/capture.md`.
- Verified analysis conclusions:
  - `setCut` cut==0 duplicate-packet case is effectively unreachable in production: window = min(500ms, overlap/4) always satisfies 2*window < overlap; only a defensive branch.
  - Audit Failed/Denied errors propagate as chain errors even when `c.stopping` — if clabwire writes Failed on stdin-close during Ctrl+C stop, an error could surface despite the doc's clean-exit promise (speculative, clabwire behavior unverifiable).
  - Potential P4: `held`/`emitted` in captureChain grow unbounded during the ≤10s overlap at very high packet rates (bounded only by clabwire's 1M-packet segment limit; memory could be large in pathological cases).
  - `packetKey` truncates InterfaceID to 16 bits (fnv over `id[0]`/`id[1]`) — fine for small interface counts.
  - c9s `Capture` wraps `captureCtx` with `WithTimeout(req.Duration+overlap+captureEndGrace)`; `defer stop()` cancels original ctx which propagates — OK.

### Active
- Remaining to review: diff hunks for `cmd/options.go`, `cmd/root_test.go`, `core/labruntime_cluster_test.go` (3320), `labruntime/clabernetes/clabernetes.go` (6357–6390, seen), `labruntime/runtime.go` (6390+; PacketCapturer interface at 6410–6474 seen), `labruntime/clabernetes/capture_test.go` (~1050 lines), capture package tests (local_test/pcapng_test/reorder_test), `cmd/capture_test.go`, docs (`docs/manual/clabernetes/runtime.md`, `docs/manual/wireshark.md`, `docs/cmd/inspect/interfaces.md`), `.github/workflows` (partially seen: tshark install, `"33*.robot"` glob), `mkdocs.yml` nav entry, `core/test_data/capture.clab.yml`, `cmd/inspect_interfaces.go` full.
- Final deliverable: trusted result with per-path verdicts, findings (incl. the audit-error-while-stopping and held/emitted-memory notes), permalink references, and test-execution limitation disclosed.

### Blocked
- Cannot execute tests (read-only snapshot) — must be disclosed in final result.
- manifest.json truncated in tool output; remaining changed paths must be enumerated from diff headers (lines 3900–7018 mapping incomplete).

## Next Move
1. Read remaining diff hunks: `cmd/options.go` (2618), `cmd/root_test.go` (2709), `core/labruntime_cluster_test.go` (3320), docs manual files (3511–3879 remaining), and enumerate + review all `labruntime/` paths from headers 3900–7018 (capture_test.go, capture_interfaces changes, runtime.go, clabernetes.go).
2. Skim capture package tests and `cmd/capture_test.go` for coverage gaps; check `mkdocs.yml` nav; then assemble final result schema with per-path verdicts and permalink references.

## Relevant Files
- `/source/standards.json`, `/source/standards/karpathy-guidelines.mdc`, `/source/standards/ponytail.mdc` — review standards (read).
- `/source/diff.txt` — full 7018-line PR diff (traversed; targeted re-reads done; 3900–7018 path mapping incomplete).
- `/source/manifest.json` — inventory (head hash `657b1700664a99c5e12c60b4cfd179eb11889bae`).
- `/source/head/capture/{local.go, local_test.go, output.go, pcapng.go, pcapng_test.go, reorder.go, reorder_test.go}` — new capture package (non-test files read & verified; tests not yet read).
- `/source/head/cmd/{capture.go, capture_test.go, context.go, inspect.go, inspect_interfaces.go, options.go, root.go, root_test.go}` — command layer (capture.go, context.go, root.go verified; options.go/root_test.go/inspect_interfaces.go diff-only).
- `/source/head/core/{capture.go, capture_local.go, capture_test.go, labruntime_cluster_test.go}` — core integration (capture.go, capture_local.go verified).
- `/source/head/labruntime/clabernetes/{capture.go, capture_interfaces.go, access.go, clabernetes.go}` — c9s capture implementation (read & verified); `capture_test.go` not yet read.
- `/source/head/labruntime/runtime.go` — PacketCapturer/CaptureRequest/NodeRequest interface additions (diff tail 6410–6474 seen).
- `/source/cmd/root.go:163` — `log.SetOutput(os.Stderr)` (stdout purity for `-w -`).
- `/source/core/test_data/capture.clab.yml` — new test topology (seen in diff 3490–3510).
- `/source/docs/cmd/capture.md`, `/source/docs/cmd/inspect/interfaces.md`, `/source/docs/manual/clabernetes/runtime.md`, `/source/docs/manual/wireshark.md` — docs (capture.md read; others pending).
- `/source/.github/workflows/{clabernetes-tests.yml, smoke-tests.yml}` — CI changes (partially seen).
- `/source/mkdocs.yml` — nav entry for capture docs (not yet checked).
step-finish
{
  "type": "step-finish",
  "id": "prt_19653b1210016TsvV762Le1RKd",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196537a1e00101MSdjyJmQE5e5",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 25806,
    "input": 22993,
    "output": 2392,
    "reasoning": 421,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196537a1e00101MSdjyJmQE5e5",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523415582,
    "completed": 1793523429670
  },
  "parentID": "msg_196537a0a0019rqr0jWnsviNLW",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "compaction",
  "agent": "compaction",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "summary": true,
  "cost": 0,
  "tokens": {
    "total": 25806,
    "input": 22993,
    "output": 2392,
    "reasoning": 421,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "stop"
}
User · 43
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_19653b129001cj4QAfxRVtxTFM",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523429673
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 44
step-start
{
  "type": "step-start",
  "id": "prt_19653b8f3001Ajdj8ireQVK0ex",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653b137001Ukh1qsEi71RUoZ"
}
Reasoning
I have unfinished review work. Let me continue reading the remaining diff regions: 1101-1676 (rest of output.go + pcapng.go + pcapng_test.go start), 2166-2161... Actually I've covered 1-1100 and 1676-2165. Need 1101-1676 (output.go rest, output_test?, pcapng.go, pcapng_test.go), 2166-2761 (cmd/capture.go, capture_test, inspect changes, options.go, root.go changes), 3320-3490, 3879-3900, and labruntime region 3900-7018. Let me continue.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 580,
  "offset": 1101
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1101: +		stop:    stop,
1102: +		runDone: make(chan struct{}),
1103: +	}
1104: +
1105: +	var runCtx context.Context
1106: +	runCtx, out.cancelRun = context.WithCancel(context.Background())
1107: +	go func() {
1108: +		defer close(out.runDone)
1109: +		out.reorder.Run(runCtx)
1110: +	}()
1111: +
1112: +	return out, nil
1113: +}
1114: +
1115: +// Emit hands a packet of the interface with the given index to the stream. It reports false
1116: +// once the packet limit is reached and the capture stops, and returns the error of a failed
1117: +// write.
1118: +func (o *Output) Emit(id uint32, packet *Packet) (bool, error) {
1119: +	if o.limit > 0 {
1120: +		count := o.written.Add(1)
1121: +		if count > o.limit {
1122: +			o.stop()
1123: +			return false, nil
1124: +		}
1125: +		if err := o.reorder.Push(id, packet); err != nil {
1126: +			return false, err
1127: +		}
1128: +		if count == o.limit {
1129: +			o.stop()
1130: +			return false, nil
1131: +		}
1132: +
1133: +		return true, nil
1134: +	}
1135: +
1136: +	o.written.Add(1)
1137: +
1138: +	return true, o.reorder.Push(id, packet)
1139: +}
1140: +
1141: +// Written returns the number of packets handed to the stream so far.
1142: +func (o *Output) Written() int64 {
1143: +	return o.written.Load()
1144: +}
1145: +
1146: +// Hold keeps packets stamped after timestamp back until Release(key).
1147: +func (o *Output) Hold(key any, timestamp int64) {
1148: +	o.reorder.Hold(key, timestamp)
1149: +}
1150: +
1151: +// Release removes the hold of key.
1152: +func (o *Output) Release(key any) {
1153: +	o.reorder.Release(key)
1154: +}
1155: +
1156: +// Close writes the packets still held back and returns the first write error.
1157: +func (o *Output) Close() error {
1158: +	o.cancelRun()
1159: +	<-o.runDone
1160: +	o.reorder.Flush()
1161: +
1162: +	return o.writer.Err()
1163: +}
1164: diff --git a/capture/pcapng.go b/capture/pcapng.go
1165: new file mode 100644
1166: index 0000000..246ac84
1167: --- /dev/null
1168: +++ b/capture/pcapng.go
1169: @@ -0,0 +1,333 @@
1170: +// Package capture writes the pcapng streams of `containerlab capture`: one section with one
1171: +// interface per capture target, packets merged across targets in timestamp order. The local
1172: +// capturer reads lab link interfaces of Docker and Podman nodes through packet sockets; the c9s
1173: +// lab runtime feeds the same writer from clabwire streams.
1174: +package capture
1175: +
1176: +import (
1177: +	"bufio"
1178: +	"encoding/binary"
1179: +	"errors"
1180: +	"fmt"
1181: +	"io"
1182: +	"math"
1183: +	"sync"
1184: +)
1185: +
1186: +// pcapng block layout (https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html). clabwire
1187: +// writes little-endian sections, and so does the merged stream containerlab writes.
1188: +const (
1189: +	pcapngSectionHeaderType  = 0x0a0d0d0a
1190: +	pcapngInterfaceType      = 0x00000001
1191: +	pcapngEnhancedPacketType = 0x00000006
1192: +	pcapngByteOrderMagic     = 0x1a2b3c4d
1193: +	pcapngOptionEnd          = 0
1194: +	pcapngOptionUserAppl     = 4
1195: +	pcapngOptionIfName       = 2
1196: +	pcapngOptionIfTSResol    = 9
1197: +	pcapngLinkTypeEthernet   = 1
1198: +	// pcapngNanoseconds is the if_tsresol value for 10^-9 s resolution.
1199: +	pcapngNanoseconds = 9
1200: +	// pcapngMaxBlockLength bounds a block read from a capture stream: a packet of the largest
1201: +	// clabwire snap length (1 MiB) plus framing.
1202: +	pcapngMaxBlockLength = 1<<20 + 1024
1203: +	// captureUserApplication names the writer in the merged section header.
1204: +	captureUserApplication = "containerlab"
1205: +)
1206: +
1207: +var errPCAPNGByteOrder = errors.New("pcapng section is not little-endian")
1208: +
1209: +// InterfaceDescription is an Interface Description Block.
1210: +type InterfaceDescription struct {
1211: +	LinkType   uint16
1212: +	SnapLength uint32
1213: +	Name       string
1214: +	// TSResol is the raw if_tsresol value; 6 (microseconds) when the block has none.
1215: +	TSResol byte
1216: +}
1217: +
1218: +// Packet is an Enhanced Packet Block with its timestamp in nanoseconds.
1219: +type Packet struct {
1220: +	InterfaceID    uint32
1221: +	Timestamp      int64
1222: +	OriginalLength uint32
1223: +	Data           []byte
1224: +}
1225: +
1226: +// Reader reads the blocks of a pcapng stream as clabwire writes it: one or more
1227: +// little-endian sections, each with its Interface Description Blocks before its packets.
1228: +type Reader struct {
1229: +	r          *bufio.Reader
1230: +	interfaces []InterfaceDescription
1231: +	// sections counts the Section Header Blocks read so far.
1232: +	sections int
1233: +}
1234: +
1235: +// NewReader returns a reader of the pcapng stream r.
1236: +func NewReader(r io.Reader) *Reader {
1237: +	return &Reader{r: bufio.NewReaderSize(r, 64<<10)}
1238: +}
1239: +
1240: +// Sections returns the number of Section Header Blocks read so far.
1241: +func (p *Reader) Sections() int {
1242: +	return p.sections
1243: +}
1244: +
1245: +// Event is one block of interest: a new interface or a packet.
1246: +type Event struct {
1247: +	Interface *InterfaceDescription
1248: +	Packet    *Packet
1249: +}
1250: +
1251: +// Next returns the next interface or packet, skipping other block types. It returns io.EOF at
1252: +// the clean end of the stream, and io.ErrUnexpectedEOF for a stream cut inside a block.
1253: +func (p *Reader) Next() (Event, error) {
1254: +	for {
1255: +		var header [8]byte
1256: +		if _, err := io.ReadFull(p.r, header[:]); err != nil {
1257: +			if errors.Is(err, io.EOF) {
1258: +				return Event{}, io.EOF
1259: +			}
1260: +
1261: +			return Event{}, io.ErrUnexpectedEOF
1262: +		}
1263: +
1264: +		blockType := binary.LittleEndian.Uint32(header[0:4])
1265: +		length := binary.LittleEndian.Uint32(header[4:8])
1266: +		if blockType == pcapngSectionHeaderType {
1267: +			// the byte-order magic tells a big-endian section apart before its length is
1268: +			// trusted: that length reads byte swapped
1269: +			magic, err := p.r.Peek(4)
1270: +			if err != nil {
1271: +				return Event{}, io.ErrUnexpectedEOF
1272: +			}
1273: +			if binary.BigEndian.Uint32(magic) == pcapngByteOrderMagic {
1274: +				return Event{}, errPCAPNGByteOrder
1275: +			}
1276: +		}
1277: +		if length < 12 || length%4 != 0 || length > pcapngMaxBlockLength {
1278: +			return Event{}, fmt.Errorf("invalid pcapng block length %d (at most %d)", length,
1279: +				pcapngMaxBlockLength)
1280: +		}
1281: +
1282: +		body := make([]byte, length-8)
1283: +		if _, err := io.ReadFull(p.r, body); err != nil {
1284: +			return Event{}, io.ErrUnexpectedEOF
1285: +		}
1286: +		if binary.LittleEndian.Uint32(body[len(body)-4:]) != length {
1287: +			return Event{}, fmt.Errorf("pcapng block lengths do not match")
1288: +		}
1289: +		body = body[:len(body)-4]
1290: +
1291: +		switch blockType {
1292: +		case pcapngSectionHeaderType:
1293: +			if len(body) < 16 {
1294: +				return Event{}, fmt.Errorf("short pcapng section header")
1295: +			}
1296: +			if binary.LittleEndian.Uint32(body[0:4]) != pcapngByteOrderMagic {
1297: +				return Event{}, errPCAPNGByteOrder
1298: +			}
1299: +			p.sections++
1300: +			p.interfaces = nil
1301: +		case pcapngInterfaceType:
1302: +			if p.sections == 0 {
1303: +				return Event{}, fmt.Errorf("pcapng interface before a section header")
1304: +			}
1305: +			intf, err := parsePCAPNGInterface(body)
1306: +			if err != nil {
1307: +				return Event{}, err
1308: +			}
1309: +			p.interfaces = append(p.interfaces, intf)
1310: +
1311: +			return Event{Interface: &p.interfaces[len(p.interfaces)-1]}, nil
1312: +		case pcapngEnhancedPacketType:
1313: +			packet, err := p.parsePacket(body)
1314: +			if err != nil {
1315: +				return Event{}, err
1316: +			}
1317: +
1318: +			return Event{Packet: &packet}, nil
1319: +		}
1320: +	}
1321: +}
1322: +
1323: +func parsePCAPNGInterface(body []byte) (InterfaceDescription, error) {
1324: +	if len(body) < 8 {
1325: +		return InterfaceDescription{}, fmt.Errorf("short pcapng interface description")
1326: +	}
1327: +	intf := InterfaceDescription{
1328: +		LinkType:   binary.LittleEndian.Uint16(body[0:2]),
1329: +		SnapLength: binary.LittleEndian.Uint32(body[4:8]),
1330: +		TSResol:    6,
1331: +	}
1332: +
1333: +	options := body[8:]
1334: +	for len(options) >= 4 {
1335: +		code := binary.LittleEndian.Uint16(options[0:2])
1336: +		size := int(binary.LittleEndian.Uint16(options[2:4]))
1337: +		if code == pcapngOptionEnd {
1338: +			break
1339: +		}
1340: +		padded := size + pcapngPadding(size)
1341: +		if 4+padded > len(options) {
1342: +			return InterfaceDescription{}, fmt.Errorf("truncated pcapng interface option")
1343: +		}
1344: +		value := options[4 : 4+size]
1345: +		switch code {
1346: +		case pcapngOptionIfName:
1347: +			intf.Name = string(value)
1348: +		case pcapngOptionIfTSResol:
1349: +			if size == 1 {
1350: +				intf.TSResol = value[0]
1351: +			}
1352: +		}
1353: +		options = options[4+padded:]
1354: +	}
1355: +
1356: +	return intf, nil
1357: +}
1358: +
1359: +func (p *Reader) parsePacket(body []byte) (Packet, error) {
1360: +	if len(body) < 20 {
1361: +		return Packet{}, fmt.Errorf("short pcapng enhanced packet")
1362: +	}
1363: +	packet := Packet{
1364: +		InterfaceID:    binary.LittleEndian.Uint32(body[0:4]),
1365: +		OriginalLength: binary.LittleEndian.Uint32(body[16:20]),
1366: +	}
1367: +	if int(packet.InterfaceID) >= len(p.interfaces) {
1368: +		return Packet{}, fmt.Errorf("pcapng packet for undeclared interface %d",
1369: +			packet.InterfaceID)
1370: +	}
1371: +	captured := binary.LittleEndian.Uint32(body[12:16])
1372: +	if int(captured) > len(body)-20 {
1373: +		return Packet{}, fmt.Errorf("pcapng packet data exceeds its block")
1374: +	}
1375: +	packet.Data = body[20 : 20+captured]
1376: +
1377: +	raw := uint64(binary.LittleEndian.Uint32(body[4:8]))<<32 |
1378: +		uint64(binary.LittleEndian.Uint32(body[8:12]))
1379: +	timestamp, err := pcapngNanosecondsFrom(raw, p.interfaces[packet.InterfaceID].TSResol)
1380: +	if err != nil {
1381: +		return Packet{}, err
1382: +	}
1383: +	packet.Timestamp = timestamp
1384: +
1385: +	return packet, nil
1386: +}
1387: +
1388: +// pcapngNanosecondsFrom converts a timestamp in an interface's resolution to nanoseconds.
1389: +// Only decimal resolutions up to nanoseconds occur in clabwire streams.
1390: +func pcapngNanosecondsFrom(raw uint64, tsresol byte) (int64, error) {
1391: +	if tsresol&0x80 != 0 || tsresol > pcapngNanoseconds {
1392: +		return 0, fmt.Errorf("unsupported pcapng timestamp resolution %#x", tsresol)
1393: +	}
1394: +	scale := uint64(1)
1395: +	for range pcapngNanoseconds - int(tsresol) {
1396: +		scale *= 10
1397: +	}
1398: +	if raw > math.MaxInt64/scale {
1399: +		return 0, fmt.Errorf("pcapng timestamp out of range")
1400: +	}
1401: +
1402: +	return int64(raw * scale), nil //nolint:gosec // bounded above
1403: +}
1404: +
1405: +// Writer writes one little-endian section with nanosecond timestamps. Every block goes out
1406: +// in one Write under a lock, so concurrent writers never interleave blocks and a stream cut
1407: +// between writes is still a valid capture.
1408: +type Writer struct {
1409: +	mu  sync.Mutex
1410: +	w   io.Writer
1411: +	err error
1412: +}
1413: +
1414: +// NewWriter returns a writer of one pcapng section to w.
1415: +func NewWriter(w io.Writer) *Writer {
1416: +	return &Writer{w: w}
1417: +}
1418: +
1419: +// WriteHeader writes the Section Header Block and one Interface Description Block per name, in
1420: +// order; packets refer to the interfaces by that index.
1421: +func (p *Writer) WriteHeader(names []string, snapLength uint32) error {
1422: +	section := make([]byte, 16)
1423: +	binary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)
1424: +	binary.LittleEndian.PutUint16(section[4:], 1)
1425: +	binary.LittleEndian.PutUint16(section[6:], 0)
1426: +	binary.LittleEndian.PutUint64(section[8:], math.MaxUint64)
1427: +	section = appendPCAPNGOption(section, pcapngOptionUserAppl, []byte(captureUserApplication))
1428: +	section = appendPCAPNGOption(section, pcapngOptionEnd, nil)
1429: +
1430: +	header := pcapngBlock(pcapngSectionHeaderType, section)
1431: +	for _, name := range names {
1432: +		description := make([]byte, 8)
1433: +		binary.LittleEndian.PutUint16(description[0:], pcapngLinkTypeEthernet)
1434: +		binary.LittleEndian.PutUint32(description[4:], snapLength)
1435: +		description = appendPCAPNGOption(description, pcapngOptionIfName, []byte(name))
1436: +		description = appendPCAPNGOption(description, pcapngOptionIfTSResol,
1437: +			[]byte{pcapngNanoseconds})
1438: +		description = appendPCAPNGOption(description, pcapngOptionEnd, nil)
1439: +		header = append(header, pcapngBlock(pcapngInterfaceType, description)...)
1440: +	}
1441: +
1442: +	return p.write(header)
1443: +}
1444: +
1445: +// WritePacket writes an Enhanced Packet Block for the interface with the given index.
1446: +func (p *Writer) WritePacket(interfaceID uint32, packet *Packet) error {
1447: +	timestamp := uint64(packet.Timestamp) //nolint:gosec // capture timestamps are positive
1448: +	body := make([]byte, 20, 20+len(packet.Data)+3)
1449: +	binary.LittleEndian.PutUint32(body[0:], interfaceID)
1450: +	binary.LittleEndian.PutUint32(body[4:], uint32(timestamp>>32))
1451: +	binary.LittleEndian.PutUint32(body[8:], uint32(timestamp)) //nolint:gosec // low 32 bits
1452: +	binary.LittleEndian.PutUint32(body[12:], uint32(len(packet.Data)))
1453: +	binary.LittleEndian.PutUint32(body[16:], packet.OriginalLength)
1454: +	body = append(body, packet.Data...)
1455: +	body = append(body, make([]byte, pcapngPadding(len(packet.Data)))...)
1456: +
1457: +	return p.write(pcapngBlock(pcapngEnhancedPacketType, body))
1458: +}
1459: +
1460: +// Err returns the first write error, or nil.
1461: +func (p *Writer) Err() error {
1462: +	p.mu.Lock()
1463: +	defer p.mu.Unlock()
1464: +
1465: +	return p.err
1466: +}
1467: +
1468: +func (p *Writer) write(block []byte) error {
1469: +	p.mu.Lock()
1470: +	defer p.mu.Unlock()
1471: +
1472: +	if p.err != nil {
1473: +		return p.err
1474: +	}
1475: +	if _, err := p.w.Write(block); err != nil {
1476: +		p.err = fmt.Errorf("failed to write the capture: %w", err)
1477: +	}
1478: +
1479: +	return p.err
1480: +}
1481: +
1482: +func pcapngBlock(blockType uint32, body []byte) []byte {
1483: +	total := uint32(12 + len(body)) //nolint:gosec // bounded by the snap length
1484: +	block := make([]byte, 8, total)
1485: +	binary.LittleEndian.PutUint32(block[0:], blockType)
1486: +	binary.LittleEndian.PutUint32(block[4:], total)
1487: +	block = append(block, body...)
1488: +
1489: +	return binary.LittleEndian.AppendUint32(block, total)
1490: +}
1491: +
1492: +func appendPCAPNGOption(body []byte, code uint16, value []byte) []byte {
1493: +	body = binary.LittleEndian.AppendUint16(body, code)
1494: +	body = binary.LittleEndian.AppendUint16(body, uint16(len(value))) //nolint:gosec // short
1495: +	body = append(body, value...)
1496: +
1497: +	return append(body, make([]byte, pcapngPadding(len(value)))...)
1498: +}
1499: +
1500: +func pcapngPadding(length int) int {
1501: +	return (4 - length%4) % 4
1502: +}
1503: diff --git a/capture/pcapng_test.go b/capture/pcapng_test.go
1504: new file mode 100644
1505: index 0000000..0917d16
1506: --- /dev/null
1507: +++ b/capture/pcapng_test.go
1508: @@ -0,0 +1,167 @@
1509: +package capture
1510: +
1511: +import (
1512: +	"bytes"
1513: +	"encoding/binary"
1514: +	"errors"
1515: +	"io"
1516: +	"strings"
1517: +	"testing"
1518: +)
1519: +
1520: +func TestPCAPNGWriterAndReaderRoundTrip(t *testing.T) {
1521: +	t.Parallel()
1522: +
1523: +	var out bytes.Buffer
1524: +	writer := NewWriter(&out)
1525: +	if err := writer.WriteHeader([]string{"r1:e1-1", "r2:eth1"}, 1500); err != nil {
1526: +		t.Fatal(err)
1527: +	}
1528: +	packets := []Packet{
1529: +		{
1530: +			InterfaceID:    1,
1531: +			Timestamp:      1_761_559_200_123_456_789,
1532: +			OriginalLength: 98,
1533: +			Data:           []byte("abcde"),
1534: +		},
1535: +		{
1536: +			InterfaceID:    0,
1537: +			Timestamp:      1_761_559_200_123_456_790,
1538: +			OriginalLength: 4,
1539: +			Data:           []byte("wxyz"),
1540: +		},
1541: +	}
1542: +	for idx := range packets {
1543: +		if err := writer.WritePacket(packets[idx].InterfaceID, &packets[idx]); err != nil {
1544: +			t.Fatal(err)
1545: +		}
1546: +	}
1547: +
1548: +	data := out.Bytes()
1549: +	// the section header names the writer
1550: +	if !bytes.Contains(data[:64], []byte(captureUserApplication)) {
1551: +		t.Fatal("section header has no shb_userappl")
1552: +	}
1553: +	if len(data)%4 != 0 {
1554: +		t.Fatalf("stream length %d is not 32-bit aligned", len(data))
1555: +	}
1556: +
1557: +	reader := NewReader(bytes.NewReader(data))
1558: +	var names []string
1559: +	var read []Packet
1560: +	for {
1561: +		event, err := reader.Next()
1562: +		if errors.Is(err, io.EOF) {
1563: +			break
1564: +		}
1565: +		if err != nil {
1566: +			t.Fatal(err)
1567: +		}
1568: +		if event.Interface != nil {
1569: +			names = append(names, event.Interface.Name)
1570: +			if event.Interface.SnapLength != 1500 || event.Interface.LinkType != 1 {
1571: +				t.Fatalf("interface = %+v", event.Interface)
1572: +			}
1573: +		}
1574: +		if event.Packet != nil {
1575: +			read = append(read, *event.Packet)
1576: +		}
1577: +	}
1578: +	if len(names) != 2 || names[0] != "r1:e1-1" || names[1] != "r2:eth1" {
1579: +		t.Fatalf("names = %v", names)
1580: +	}
1581: +	for idx := range packets {
1582: +		if read[idx].InterfaceID != packets[idx].InterfaceID ||
1583: +			read[idx].Timestamp != packets[idx].Timestamp ||
1584: +			read[idx].OriginalLength != packets[idx].OriginalLength ||
1585: +			!bytes.Equal(read[idx].Data, packets[idx].Data) {
1586: +			t.Fatalf("packet %d = %+v, want %+v", idx, read[idx], packets[idx])
1587: +		}
1588: +	}
1589: +}
1590: +
1591: +func TestPCAPNGReaderHandlesRepeatedSectionsAndResolutions(t *testing.T) {
1592: +	t.Parallel()
1593: +
1594: +	var out bytes.Buffer
1595: +	first := NewWriter(&out)
1596: +	_ = first.WriteHeader([]string{"eth1"}, 64)
1597: +	_ = first.WritePacket(0, &Packet{Timestamp: 5, Data: []byte{1}})
1598: +
1599: +	// a second section whose interface has microsecond timestamps (no if_tsresol)
1600: +	section := make([]byte, 16)
1601: +	binary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)
1602: +	binary.LittleEndian.PutUint16(section[4:], 1)
1603: +	out.Write(pcapngBlock(pcapngSectionHeaderType, section))
1604: +	description := make([]byte, 8)
1605: +	binary.LittleEndian.PutUint16(description[0:], 1)
1606: +	description = appendPCAPNGOption(description, pcapngOptionIfName, []byte("eth2"))
1607: +	out.Write(pcapngBlock(pcapngInterfaceType, description))
1608: +	body := make([]byte, 20)
1609: +	binary.LittleEndian.PutUint32(body[8:], 7) // 7 microseconds
1610: +	out.Write(pcapngBlock(pcapngEnhancedPacketType, body))
1611: +
1612: +	reader := NewReader(&out)
1613: +	var timestamps []int64
1614: +	for {
1615: +		event, err := reader.Next()
1616: +		if errors.Is(err, io.EOF) {
1617: +			break
1618: +		}
1619: +		if err != nil {
1620: +			t.Fatal(err)
1621: +		}
1622: +		if event.Packet != nil {
1623: +			timestamps = append(timestamps, event.Packet.Timestamp)
1624: +		}
1625: +	}
1626: +	if reader.sections != 2 || len(timestamps) != 2 || timestamps[0] != 5 || timestamps[1] != 7000 {
1627: +		t.Fatalf("sections %d, timestamps %v", reader.sections, timestamps)
1628: +	}
1629: +}
1630: +
1631: +func TestPCAPNGReaderRejectsInvalidStreams(t *testing.T) {
1632: +	t.Parallel()
1633: +
1634: +	var valid bytes.Buffer
1635: +	writer := NewWriter(&valid)
1636: +	_ = writer.WriteHeader([]string{"eth1"}, 64)
1637: +	_ = writer.WritePacket(0, &Packet{Timestamp: 1, Data: []byte("data")})
1638: +
1639: +	readAll := func(data []byte) error {
1640: +		reader := NewReader(bytes.NewReader(data))
1641: +		for {
1642: +			_, err := reader.Next()
1643: +			if errors.Is(err, io.EOF) {
1644: +				return nil
1645: +			}
1646: +			if err != nil {
1647: +				return err
1648: +			}
1649: +		}
1650: +	}
1651: +
1652: +	if err := readAll(valid.Bytes()[:valid.Len()-6]); !errors.Is(err, io.ErrUnexpectedEOF) {
1653: +		t.Fatalf("truncated stream: %v", err)
1654: +	}
1655: +
1656: +	bigEndian := append([]byte(nil), valid.Bytes()...)
1657: +	binary.BigEndian.PutUint32(bigEndian[4:], binary.LittleEndian.Uint32(bigEndian[4:]))
1658: +	binary.BigEndian.PutUint32(bigEndian[8:], pcapngByteOrderMagic)
1659: +	if err := readAll(bigEndian); !errors.Is(err, errPCAPNGByteOrder) {
1660: +		t.Fatalf("big-endian section: %v", err)
1661: +	}
1662: +
1663: +	// a little-endian section header longer than the reader accepts is not a byte-order error
1664: +	oversized := append([]byte(nil), valid.Bytes()...)
1665: +	binary.LittleEndian.PutUint32(oversized[4:], 2<<20)
1666: +	if err := readAll(oversized); err == nil || errors.Is(err, errPCAPNGByteOrder) ||
1667: +		!strings.Contains(err.Error(), "invalid pcapng block length") {
1668: +		t.Fatalf("oversized little-endian section: %v", err)
1669: +	}
1670: +
1671: +	packetFirst := pcapngBlock(pcapngEnhancedPacketType, make([]byte, 20))
1672: +	if err := readAll(packetFirst); err == nil {
1673: +		t.Fatal("packet before any interface accepted")
1674: +	}
1675: +}
1676: diff --git a/capture/reorder.go b/capture/reorder.go
1677: new file mode 100644
1678: index 0000000..277ba1a
1679: --- /dev/null
1680: +++ b/capture/reorder.go

(Showing lines 1101-1680 of 7018. Use offset=1681 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19653bcba0016v1bYnszi9QSs2",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653b137001Ukh1qsEi71RUoZ",
  "callID": "call_c2a24afafd10411981988621",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 580,
      "offset": 1101
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n1101: +\t\tstop:    stop,\n1102: +\t\trunDone: make(chan struct{}),\n1103: +\t}\n1104: +\n1105: +\tvar runCtx context.Context\n1106: +\trunCtx, out.cancelRun = context.WithCancel(context.Background())\n1107: +\tgo func() {\n1108: +\t\tdefer close(out.runDone)\n1109: +\t\tout.reorder.Run(runCtx)\n1110: +\t}()\n1111: +\n1112: +\treturn out, nil\n1113: +}\n1114: +\n1115: +// Emit hands a packet of the interface with the given index to the stream. It reports false\n1116: +// once the packet limit is reached and the capture stops, and returns the error of a failed\n1117: +// write.\n1118: +func (o *Output) Emit(id uint32, packet *Packet) (bool, error) {\n1119: +\tif o.limit > 0 {\n1120: +\t\tcount := o.written.Add(1)\n1121: +\t\tif count > o.limit {\n1122: +\t\t\to.stop()\n1123: +\t\t\treturn false, nil\n1124: +\t\t}\n1125: +\t\tif err := o.reorder.Push(id, packet); err != nil {\n1126: +\t\t\treturn false, err\n1127: +\t\t}\n1128: +\t\tif count == o.limit {\n1129: +\t\t\to.stop()\n1130: +\t\t\treturn false, nil\n1131: +\t\t}\n1132: +\n1133: +\t\treturn true, nil\n1134: +\t}\n1135: +\n1136: +\to.written.Add(1)\n1137: +\n1138: +\treturn true, o.reorder.Push(id, packet)\n1139: +}\n1140: +\n1141: +// Written returns the number of packets handed to the stream so far.\n1142: +func (o *Output) Written() int64 {\n1143: +\treturn o.written.Load()\n1144: +}\n1145: +\n1146: +// Hold keeps packets stamped after timestamp back until Release(key).\n1147: +func (o *Output) Hold(key any, timestamp int64) {\n1148: +\to.reorder.Hold(key, timestamp)\n1149: +}\n1150: +\n1151: +// Release removes the hold of key.\n1152: +func (o *Output) Release(key any) {\n1153: +\to.reorder.Release(key)\n1154: +}\n1155: +\n1156: +// Close writes the packets still held back and returns the first write error.\n1157: +func (o *Output) Close() error {\n1158: +\to.cancelRun()\n1159: +\t<-o.runDone\n1160: +\to.reorder.Flush()\n1161: +\n1162: +\treturn o.writer.Err()\n1163: +}\n1164: diff --git a/capture/pcapng.go b/capture/pcapng.go\n1165: new file mode 100644\n1166: index 0000000..246ac84\n1167: --- /dev/null\n1168: +++ b/capture/pcapng.go\n1169: @@ -0,0 +1,333 @@\n1170: +// Package capture writes the pcapng streams of `containerlab capture`: one section with one\n1171: +// interface per capture target, packets merged across targets in timestamp order. The local\n1172: +// capturer reads lab link interfaces of Docker and Podman nodes through packet sockets; the c9s\n1173: +// lab runtime feeds the same writer from clabwire streams.\n1174: +package capture\n1175: +\n1176: +import (\n1177: +\t\"bufio\"\n1178: +\t\"encoding/binary\"\n1179: +\t\"errors\"\n1180: +\t\"fmt\"\n1181: +\t\"io\"\n1182: +\t\"math\"\n1183: +\t\"sync\"\n1184: +)\n1185: +\n1186: +// pcapng block layout (https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html). clabwire\n1187: +// writes little-endian sections, and so does the merged stream containerlab writes.\n1188: +const (\n1189: +\tpcapngSectionHeaderType  = 0x0a0d0d0a\n1190: +\tpcapngInterfaceType      = 0x00000001\n1191: +\tpcapngEnhancedPacketType = 0x00000006\n1192: +\tpcapngByteOrderMagic     = 0x1a2b3c4d\n1193: +\tpcapngOptionEnd          = 0\n1194: +\tpcapngOptionUserAppl     = 4\n1195: +\tpcapngOptionIfName       = 2\n1196: +\tpcapngOptionIfTSResol    = 9\n1197: +\tpcapngLinkTypeEthernet   = 1\n1198: +\t// pcapngNanoseconds is the if_tsresol value for 10^-9 s resolution.\n1199: +\tpcapngNanoseconds = 9\n1200: +\t// pcapngMaxBlockLength bounds a block read from a capture stream: a packet of the largest\n1201: +\t// clabwire snap length (1 MiB) plus framing.\n1202: +\tpcapngMaxBlockLength = 1<<20 + 1024\n1203: +\t// captureUserApplication names the writer in the merged section header.\n1204: +\tcaptureUserApplication = \"containerlab\"\n1205: +)\n1206: +\n1207: +var errPCAPNGByteOrder = errors.New(\"pcapng section is not little-endian\")\n1208: +\n1209: +// InterfaceDescription is an Interface Description Block.\n1210: +type InterfaceDescription struct {\n1211: +\tLinkType   uint16\n1212: +\tSnapLength uint32\n1213: +\tName       string\n1214: +\t// TSResol is the raw if_tsresol value; 6 (microseconds) when the block has none.\n1215: +\tTSResol byte\n1216: +}\n1217: +\n1218: +// Packet is an Enhanced Packet Block with its timestamp in nanoseconds.\n1219: +type Packet struct {\n1220: +\tInterfaceID    uint32\n1221: +\tTimestamp      int64\n1222: +\tOriginalLength uint32\n1223: +\tData           []byte\n1224: +}\n1225: +\n1226: +// Reader reads the blocks of a pcapng stream as clabwire writes it: one or more\n1227: +// little-endian sections, each with its Interface Description Blocks before its packets.\n1228: +type Reader struct {\n1229: +\tr          *bufio.Reader\n1230: +\tinterfaces []InterfaceDescription\n1231: +\t// sections counts the Section Header Blocks read so far.\n1232: +\tsections int\n1233: +}\n1234: +\n1235: +// NewReader returns a reader of the pcapng stream r.\n1236: +func NewReader(r io.Reader) *Reader {\n1237: +\treturn &Reader{r: bufio.NewReaderSize(r, 64<<10)}\n1238: +}\n1239: +\n1240: +// Sections returns the number of Section Header Blocks read so far.\n1241: +func (p *Reader) Sections() int {\n1242: +\treturn p.sections\n1243: +}\n1244: +\n1245: +// Event is one block of interest: a new interface or a packet.\n1246: +type Event struct {\n1247: +\tInterface *InterfaceDescription\n1248: +\tPacket    *Packet\n1249: +}\n1250: +\n1251: +// Next returns the next interface or packet, skipping other block types. It returns io.EOF at\n1252: +// the clean end of the stream, and io.ErrUnexpectedEOF for a stream cut inside a block.\n1253: +func (p *Reader) Next() (Event, error) {\n1254: +\tfor {\n1255: +\t\tvar header [8]byte\n1256: +\t\tif _, err := io.ReadFull(p.r, header[:]); err != nil {\n1257: +\t\t\tif errors.Is(err, io.EOF) {\n1258: +\t\t\t\treturn Event{}, io.EOF\n1259: +\t\t\t}\n1260: +\n1261: +\t\t\treturn Event{}, io.ErrUnexpectedEOF\n1262: +\t\t}\n1263: +\n1264: +\t\tblockType := binary.LittleEndian.Uint32(header[0:4])\n1265: +\t\tlength := binary.LittleEndian.Uint32(header[4:8])\n1266: +\t\tif blockType == pcapngSectionHeaderType {\n1267: +\t\t\t// the byte-order magic tells a big-endian section apart before its length is\n1268: +\t\t\t// trusted: that length reads byte swapped\n1269: +\t\t\tmagic, err := p.r.Peek(4)\n1270: +\t\t\tif err != nil {\n1271: +\t\t\t\treturn Event{}, io.ErrUnexpectedEOF\n1272: +\t\t\t}\n1273: +\t\t\tif binary.BigEndian.Uint32(magic) == pcapngByteOrderMagic {\n1274: +\t\t\t\treturn Event{}, errPCAPNGByteOrder\n1275: +\t\t\t}\n1276: +\t\t}\n1277: +\t\tif length < 12 || length%4 != 0 || length > pcapngMaxBlockLength {\n1278: +\t\t\treturn Event{}, fmt.Errorf(\"invalid pcapng block length %d (at most %d)\", length,\n1279: +\t\t\t\tpcapngMaxBlockLength)\n1280: +\t\t}\n1281: +\n1282: +\t\tbody := make([]byte, length-8)\n1283: +\t\tif _, err := io.ReadFull(p.r, body); err != nil {\n1284: +\t\t\treturn Event{}, io.ErrUnexpectedEOF\n1285: +\t\t}\n1286: +\t\tif binary.LittleEndian.Uint32(body[len(body)-4:]) != length {\n1287: +\t\t\treturn Event{}, fmt.Errorf(\"pcapng block lengths do not match\")\n1288: +\t\t}\n1289: +\t\tbody = body[:len(body)-4]\n1290: +\n1291: +\t\tswitch blockType {\n1292: +\t\tcase pcapngSectionHeaderType:\n1293: +\t\t\tif len(body) < 16 {\n1294: +\t\t\t\treturn Event{}, fmt.Errorf(\"short pcapng section header\")\n1295: +\t\t\t}\n1296: +\t\t\tif binary.LittleEndian.Uint32(body[0:4]) != pcapngByteOrderMagic {\n1297: +\t\t\t\treturn Event{}, errPCAPNGByteOrder\n1298: +\t\t\t}\n1299: +\t\t\tp.sections++\n1300: +\t\t\tp.interfaces = nil\n1301: +\t\tcase pcapngInterfaceType:\n1302: +\t\t\tif p.sections == 0 {\n1303: +\t\t\t\treturn Event{}, fmt.Errorf(\"pcapng interface before a section header\")\n1304: +\t\t\t}\n1305: +\t\t\tintf, err := parsePCAPNGInterface(body)\n1306: +\t\t\tif err != nil {\n1307: +\t\t\t\treturn Event{}, err\n1308: +\t\t\t}\n1309: +\t\t\tp.interfaces = append(p.interfaces, intf)\n1310: +\n1311: +\t\t\treturn Event{Interface: &p.interfaces[len(p.interfaces)-1]}, nil\n1312: +\t\tcase pcapngEnhancedPacketType:\n1313: +\t\t\tpacket, err := p.parsePacket(body)\n1314: +\t\t\tif err != nil {\n1315: +\t\t\t\treturn Event{}, err\n1316: +\t\t\t}\n1317: +\n1318: +\t\t\treturn Event{Packet: &packet}, nil\n1319: +\t\t}\n1320: +\t}\n1321: +}\n1322: +\n1323: +func parsePCAPNGInterface(body []byte) (InterfaceDescription, error) {\n1324: +\tif len(body) < 8 {\n1325: +\t\treturn InterfaceDescription{}, fmt.Errorf(\"short pcapng interface description\")\n1326: +\t}\n1327: +\tintf := InterfaceDescription{\n1328: +\t\tLinkType:   binary.LittleEndian.Uint16(body[0:2]),\n1329: +\t\tSnapLength: binary.LittleEndian.Uint32(body[4:8]),\n1330: +\t\tTSResol:    6,\n1331: +\t}\n1332: +\n1333: +\toptions := body[8:]\n1334: +\tfor len(options) >= 4 {\n1335: +\t\tcode := binary.LittleEndian.Uint16(options[0:2])\n1336: +\t\tsize := int(binary.LittleEndian.Uint16(options[2:4]))\n1337: +\t\tif code == pcapngOptionEnd {\n1338: +\t\t\tbreak\n1339: +\t\t}\n1340: +\t\tpadded := size + pcapngPadding(size)\n1341: +\t\tif 4+padded > len(options) {\n1342: +\t\t\treturn InterfaceDescription{}, fmt.Errorf(\"truncated pcapng interface option\")\n1343: +\t\t}\n1344: +\t\tvalue := options[4 : 4+size]\n1345: +\t\tswitch code {\n1346: +\t\tcase pcapngOptionIfName:\n1347: +\t\t\tintf.Name = string(value)\n1348: +\t\tcase pcapngOptionIfTSResol:\n1349: +\t\t\tif size == 1 {\n1350: +\t\t\t\tintf.TSResol = value[0]\n1351: +\t\t\t}\n1352: +\t\t}\n1353: +\t\toptions = options[4+padded:]\n1354: +\t}\n1355: +\n1356: +\treturn intf, nil\n1357: +}\n1358: +\n1359: +func (p *Reader) parsePacket(body []byte) (Packet, error) {\n1360: +\tif len(body) < 20 {\n1361: +\t\treturn Packet{}, fmt.Errorf(\"short pcapng enhanced packet\")\n1362: +\t}\n1363: +\tpacket := Packet{\n1364: +\t\tInterfaceID:    binary.LittleEndian.Uint32(body[0:4]),\n1365: +\t\tOriginalLength: binary.LittleEndian.Uint32(body[16:20]),\n1366: +\t}\n1367: +\tif int(packet.InterfaceID) >= len(p.interfaces) {\n1368: +\t\treturn Packet{}, fmt.Errorf(\"pcapng packet for undeclared interface %d\",\n1369: +\t\t\tpacket.InterfaceID)\n1370: +\t}\n1371: +\tcaptured := binary.LittleEndian.Uint32(body[12:16])\n1372: +\tif int(captured) > len(body)-20 {\n1373: +\t\treturn Packet{}, fmt.Errorf(\"pcapng packet data exceeds its block\")\n1374: +\t}\n1375: +\tpacket.Data = body[20 : 20+captured]\n1376: +\n1377: +\traw := uint64(binary.LittleEndian.Uint32(body[4:8]))<<32 |\n1378: +\t\tuint64(binary.LittleEndian.Uint32(body[8:12]))\n1379: +\ttimestamp, err := pcapngNanosecondsFrom(raw, p.interfaces[packet.InterfaceID].TSResol)\n1380: +\tif err != nil {\n1381: +\t\treturn Packet{}, err\n1382: +\t}\n1383: +\tpacket.Timestamp = timestamp\n1384: +\n1385: +\treturn packet, nil\n1386: +}\n1387: +\n1388: +// pcapngNanosecondsFrom converts a timestamp in an interface's resolution to nanoseconds.\n1389: +// Only decimal resolutions up to nanoseconds occur in clabwire streams.\n1390: +func pcapngNanosecondsFrom(raw uint64, tsresol byte) (int64, error) {\n1391: +\tif tsresol&0x80 != 0 || tsresol > pcapngNanoseconds {\n1392: +\t\treturn 0, fmt.Errorf(\"unsupported pcapng timestamp resolution %#x\", tsresol)\n1393: +\t}\n1394: +\tscale := uint64(1)\n1395: +\tfor range pcapngNanoseconds - int(tsresol) {\n1396: +\t\tscale *= 10\n1397: +\t}\n1398: +\tif raw > math.MaxInt64/scale {\n1399: +\t\treturn 0, fmt.Errorf(\"pcapng timestamp out of range\")\n1400: +\t}\n1401: +\n1402: +\treturn int64(raw * scale), nil //nolint:gosec // bounded above\n1403: +}\n1404: +\n1405: +// Writer writes one little-endian section with nanosecond timestamps. Every block goes out\n1406: +// in one Write under a lock, so concurrent writers never interleave blocks and a stream cut\n1407: +// between writes is still a valid capture.\n1408: +type Writer struct {\n1409: +\tmu  sync.Mutex\n1410: +\tw   io.Writer\n1411: +\terr error\n1412: +}\n1413: +\n1414: +// NewWriter returns a writer of one pcapng section to w.\n1415: +func NewWriter(w io.Writer) *Writer {\n1416: +\treturn &Writer{w: w}\n1417: +}\n1418: +\n1419: +// WriteHeader writes the Section Header Block and one Interface Description Block per name, in\n1420: +// order; packets refer to the interfaces by that index.\n1421: +func (p *Writer) WriteHeader(names []string, snapLength uint32) error {\n1422: +\tsection := make([]byte, 16)\n1423: +\tbinary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)\n1424: +\tbinary.LittleEndian.PutUint16(section[4:], 1)\n1425: +\tbinary.LittleEndian.PutUint16(section[6:], 0)\n1426: +\tbinary.LittleEndian.PutUint64(section[8:], math.MaxUint64)\n1427: +\tsection = appendPCAPNGOption(section, pcapngOptionUserAppl, []byte(captureUserApplication))\n1428: +\tsection = appendPCAPNGOption(section, pcapngOptionEnd, nil)\n1429: +\n1430: +\theader := pcapngBlock(pcapngSectionHeaderType, section)\n1431: +\tfor _, name := range names {\n1432: +\t\tdescription := make([]byte, 8)\n1433: +\t\tbinary.LittleEndian.PutUint16(description[0:], pcapngLinkTypeEthernet)\n1434: +\t\tbinary.LittleEndian.PutUint32(description[4:], snapLength)\n1435: +\t\tdescription = appendPCAPNGOption(description, pcapngOptionIfName, []byte(name))\n1436: +\t\tdescription = appendPCAPNGOption(description, pcapngOptionIfTSResol,\n1437: +\t\t\t[]byte{pcapngNanoseconds})\n1438: +\t\tdescription = appendPCAPNGOption(description, pcapngOptionEnd, nil)\n1439: +\t\theader = append(header, pcapngBlock(pcapngInterfaceType, description)...)\n1440: +\t}\n1441: +\n1442: +\treturn p.write(header)\n1443: +}\n1444: +\n1445: +// WritePacket writes an Enhanced Packet Block for the interface with the given index.\n1446: +func (p *Writer) WritePacket(interfaceID uint32, packet *Packet) error {\n1447: +\ttimestamp := uint64(packet.Timestamp) //nolint:gosec // capture timestamps are positive\n1448: +\tbody := make([]byte, 20, 20+len(packet.Data)+3)\n1449: +\tbinary.LittleEndian.PutUint32(body[0:], interfaceID)\n1450: +\tbinary.LittleEndian.PutUint32(body[4:], uint32(timestamp>>32))\n1451: +\tbinary.LittleEndian.PutUint32(body[8:], uint32(timestamp)) //nolint:gosec // low 32 bits\n1452: +\tbinary.LittleEndian.PutUint32(body[12:], uint32(len(packet.Data)))\n1453: +\tbinary.LittleEndian.PutUint32(body[16:], packet.OriginalLength)\n1454: +\tbody = append(body, packet.Data...)\n1455: +\tbody = append(body, make([]byte, pcapngPadding(len(packet.Data)))...)\n1456: +\n1457: +\treturn p.write(pcapngBlock(pcapngEnhancedPacketType, body))\n1458: +}\n1459: +\n1460: +// Err returns the first write error, or nil.\n1461: +func (p *Writer) Err() error {\n1462: +\tp.mu.Lock()\n1463: +\tdefer p.mu.Unlock()\n1464: +\n1465: +\treturn p.err\n1466: +}\n1467: +\n1468: +func (p *Writer) write(block []byte) error {\n1469: +\tp.mu.Lock()\n1470: +\tdefer p.mu.Unlock()\n1471: +\n1472: +\tif p.err != nil {\n1473: +\t\treturn p.err\n1474: +\t}\n1475: +\tif _, err := p.w.Write(block); err != nil {\n1476: +\t\tp.err = fmt.Errorf(\"failed to write the capture: %w\", err)\n1477: +\t}\n1478: +\n1479: +\treturn p.err\n1480: +}\n1481: +\n1482: +func pcapngBlock(blockType uint32, body []byte) []byte {\n1483: +\ttotal := uint32(12 + len(body)) //nolint:gosec // bounded by the snap length\n1484: +\tblock := make([]byte, 8, total)\n1485: +\tbinary.LittleEndian.PutUint32(block[0:], blockType)\n1486: +\tbinary.LittleEndian.PutUint32(block[4:], total)\n1487: +\tblock = append(block, body...)\n1488: +\n1489: +\treturn binary.LittleEndian.AppendUint32(block, total)\n1490: +}\n1491: +\n1492: +func appendPCAPNGOption(body []byte, code uint16, value []byte) []byte {\n1493: +\tbody = binary.LittleEndian.AppendUint16(body, code)\n1494: +\tbody = binary.LittleEndian.AppendUint16(body, uint16(len(value))) //nolint:gosec // short\n1495: +\tbody = append(body, value...)\n1496: +\n1497: +\treturn append(body, make([]byte, pcapngPadding(len(value)))...)\n1498: +}\n1499: +\n1500: +func pcapngPadding(length int) int {\n1501: +\treturn (4 - length%4) % 4\n1502: +}\n1503: diff --git a/capture/pcapng_test.go b/capture/pcapng_test.go\n1504: new file mode 100644\n1505: index 0000000..0917d16\n1506: --- /dev/null\n1507: +++ b/capture/pcapng_test.go\n1508: @@ -0,0 +1,167 @@\n1509: +package capture\n1510: +\n1511: +import (\n1512: +\t\"bytes\"\n1513: +\t\"encoding/binary\"\n1514: +\t\"errors\"\n1515: +\t\"io\"\n1516: +\t\"strings\"\n1517: +\t\"testing\"\n1518: +)\n1519: +\n1520: +func TestPCAPNGWriterAndReaderRoundTrip(t *testing.T) {\n1521: +\tt.Parallel()\n1522: +\n1523: +\tvar out bytes.Buffer\n1524: +\twriter := NewWriter(&out)\n1525: +\tif err := writer.WriteHeader([]string{\"r1:e1-1\", \"r2:eth1\"}, 1500); err != nil {\n1526: +\t\tt.Fatal(err)\n1527: +\t}\n1528: +\tpackets := []Packet{\n1529: +\t\t{\n1530: +\t\t\tInterfaceID:    1,\n1531: +\t\t\tTimestamp:      1_761_559_200_123_456_789,\n1532: +\t\t\tOriginalLength: 98,\n1533: +\t\t\tData:           []byte(\"abcde\"),\n1534: +\t\t},\n1535: +\t\t{\n1536: +\t\t\tInterfaceID:    0,\n1537: +\t\t\tTimestamp:      1_761_559_200_123_456_790,\n1538: +\t\t\tOriginalLength: 4,\n1539: +\t\t\tData:           []byte(\"wxyz\"),\n1540: +\t\t},\n1541: +\t}\n1542: +\tfor idx := range packets {\n1543: +\t\tif err := writer.WritePacket(packets[idx].InterfaceID, &packets[idx]); err != nil {\n1544: +\t\t\tt.Fatal(err)\n1545: +\t\t}\n1546: +\t}\n1547: +\n1548: +\tdata := out.Bytes()\n1549: +\t// the section header names the writer\n1550: +\tif !bytes.Contains(data[:64], []byte(captureUserApplication)) {\n1551: +\t\tt.Fatal(\"section header has no shb_userappl\")\n1552: +\t}\n1553: +\tif len(data)%4 != 0 {\n1554: +\t\tt.Fatalf(\"stream length %d is not 32-bit aligned\", len(data))\n1555: +\t}\n1556: +\n1557: +\treader := NewReader(bytes.NewReader(data))\n1558: +\tvar names []string\n1559: +\tvar read []Packet\n1560: +\tfor {\n1561: +\t\tevent, err := reader.Next()\n1562: +\t\tif errors.Is(err, io.EOF) {\n1563: +\t\t\tbreak\n1564: +\t\t}\n1565: +\t\tif err != nil {\n1566: +\t\t\tt.Fatal(err)\n1567: +\t\t}\n1568: +\t\tif event.Interface != nil {\n1569: +\t\t\tnames = append(names, event.Interface.Name)\n1570: +\t\t\tif event.Interface.SnapLength != 1500 || event.Interface.LinkType != 1 {\n1571: +\t\t\t\tt.Fatalf(\"interface = %+v\", event.Interface)\n1572: +\t\t\t}\n1573: +\t\t}\n1574: +\t\tif event.Packet != nil {\n1575: +\t\t\tread = append(read, *event.Packet)\n1576: +\t\t}\n1577: +\t}\n1578: +\tif len(names) != 2 || names[0] != \"r1:e1-1\" || names[1] != \"r2:eth1\" {\n1579: +\t\tt.Fatalf(\"names = %v\", names)\n1580: +\t}\n1581: +\tfor idx := range packets {\n1582: +\t\tif read[idx].InterfaceID != packets[idx].InterfaceID ||\n1583: +\t\t\tread[idx].Timestamp != packets[idx].Timestamp ||\n1584: +\t\t\tread[idx].OriginalLength != packets[idx].OriginalLength ||\n1585: +\t\t\t!bytes.Equal(read[idx].Data, packets[idx].Data) {\n1586: +\t\t\tt.Fatalf(\"packet %d = %+v, want %+v\", idx, read[idx], packets[idx])\n1587: +\t\t}\n1588: +\t}\n1589: +}\n1590: +\n1591: +func TestPCAPNGReaderHandlesRepeatedSectionsAndResolutions(t *testing.T) {\n1592: +\tt.Parallel()\n1593: +\n1594: +\tvar out bytes.Buffer\n1595: +\tfirst := NewWriter(&out)\n1596: +\t_ = first.WriteHeader([]string{\"eth1\"}, 64)\n1597: +\t_ = first.WritePacket(0, &Packet{Timestamp: 5, Data: []byte{1}})\n1598: +\n1599: +\t// a second section whose interface has microsecond timestamps (no if_tsresol)\n1600: +\tsection := make([]byte, 16)\n1601: +\tbinary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)\n1602: +\tbinary.LittleEndian.PutUint16(section[4:], 1)\n1603: +\tout.Write(pcapngBlock(pcapngSectionHeaderType, section))\n1604: +\tdescription := make([]byte, 8)\n1605: +\tbinary.LittleEndian.PutUint16(description[0:], 1)\n1606: +\tdescription = appendPCAPNGOption(description, pcapngOptionIfName, []byte(\"eth2\"))\n1607: +\tout.Write(pcapngBlock(pcapngInterfaceType, description))\n1608: +\tbody := make([]byte, 20)\n1609: +\tbinary.LittleEndian.PutUint32(body[8:], 7) // 7 microseconds\n1610: +\tout.Write(pcapngBlock(pcapngEnhancedPacketType, body))\n1611: +\n1612: +\treader := NewReader(&out)\n1613: +\tvar timestamps []int64\n1614: +\tfor {\n1615: +\t\tevent, err := reader.Next()\n1616: +\t\tif errors.Is(err, io.EOF) {\n1617: +\t\t\tbreak\n1618: +\t\t}\n1619: +\t\tif err != nil {\n1620: +\t\t\tt.Fatal(err)\n1621: +\t\t}\n1622: +\t\tif event.Packet != nil {\n1623: +\t\t\ttimestamps = append(timestamps, event.Packet.Timestamp)\n1624: +\t\t}\n1625: +\t}\n1626: +\tif reader.sections != 2 || len(timestamps) != 2 || timestamps[0] != 5 || timestamps[1] != 7000 {\n1627: +\t\tt.Fatalf(\"sections %d, timestamps %v\", reader.sections, timestamps)\n1628: +\t}\n1629: +}\n1630: +\n1631: +func TestPCAPNGReaderRejectsInvalidStreams(t *testing.T) {\n1632: +\tt.Parallel()\n1633: +\n1634: +\tvar valid bytes.Buffer\n1635: +\twriter := NewWriter(&valid)\n1636: +\t_ = writer.WriteHeader([]string{\"eth1\"}, 64)\n1637: +\t_ = writer.WritePacket(0, &Packet{Timestamp: 1, Data: []byte(\"data\")})\n1638: +\n1639: +\treadAll := func(data []byte) error {\n1640: +\t\treader := NewReader(bytes.NewReader(data))\n1641: +\t\tfor {\n1642: +\t\t\t_, err := reader.Next()\n1643: +\t\t\tif errors.Is(err, io.EOF) {\n1644: +\t\t\t\treturn nil\n1645: +\t\t\t}\n1646: +\t\t\tif err != nil {\n1647: +\t\t\t\treturn err\n1648: +\t\t\t}\n1649: +\t\t}\n1650: +\t}\n1651: +\n1652: +\tif err := readAll(valid.Bytes()[:valid.Len()-6]); !errors.Is(err, io.ErrUnexpectedEOF) {\n1653: +\t\tt.Fatalf(\"truncated stream: %v\", err)\n1654: +\t}\n1655: +\n1656: +\tbigEndian := append([]byte(nil), valid.Bytes()...)\n1657: +\tbinary.BigEndian.PutUint32(bigEndian[4:], binary.LittleEndian.Uint32(bigEndian[4:]))\n1658: +\tbinary.BigEndian.PutUint32(bigEndian[8:], pcapngByteOrderMagic)\n1659: +\tif err := readAll(bigEndian); !errors.Is(err, errPCAPNGByteOrder) {\n1660: +\t\tt.Fatalf(\"big-endian section: %v\", err)\n1661: +\t}\n1662: +\n1663: +\t// a little-endian section header longer than the reader accepts is not a byte-order error\n1664: +\toversized := append([]byte(nil), valid.Bytes()...)\n1665: +\tbinary.LittleEndian.PutUint32(oversized[4:], 2<<20)\n1666: +\tif err := readAll(oversized); err == nil || errors.Is(err, errPCAPNGByteOrder) ||\n1667: +\t\t!strings.Contains(err.Error(), \"invalid pcapng block length\") {\n1668: +\t\tt.Fatalf(\"oversized little-endian section: %v\", err)\n1669: +\t}\n1670: +\n1671: +\tpacketFirst := pcapngBlock(pcapngEnhancedPacketType, make([]byte, 20))\n1672: +\tif err := readAll(packetFirst); err == nil {\n1673: +\t\tt.Fatal(\"packet before any interface accepted\")\n1674: +\t}\n1675: +}\n1676: diff --git a/capture/reorder.go b/capture/reorder.go\n1677: new file mode 100644\n1678: index 0000000..277ba1a\n1679: --- /dev/null\n1680: +++ b/capture/reorder.go\n\n(Showing lines 1101-1680 of 7018. Use offset=1681 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+\t\tstop:    stop,\n+\t\trunDone: make(chan struct{}),\n+\t}\n+\n+\tvar runCtx context.Context\n+\trunCtx, out.cancelRun = context.WithCancel(context.Background())\n+\tgo func() {\n+\t\tdefer close(out.runDone)\n+\t\tout.reorder.Run(runCtx)\n+\t}()\n+\n+\treturn out, nil\n+}\n+\n+// Emit hands a packet of the interface with the given index to the stream. It reports false\n+// once the packet limit is reached and the capture stops, and returns the error of a failed\n+// write.\n+func (o *Output) Emit(id uint32, packet *Packet) (bool, error) {\n+\tif o.limit > 0 {\n+\t\tcount := o.written.Add(1)",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+\t\tstop:    stop,\n+\t\trunDone: make(chan struct{}),\n+\t}\n+\n+\tvar runCtx context.Context\n+\trunCtx, out.cancelRun = context.WithCancel(context.Background())\n+\tgo func() {\n+\t\tdefer close(out.runDone)\n+\t\tout.reorder.Run(runCtx)\n+\t}()\n+\n+\treturn out, nil\n+}\n+\n+// Emit hands a packet of the interface with the given index to the stream. It reports false\n+// once the packet limit is reached and the capture stops, and returns the error of a failed\n+// write.\n+func (o *Output) Emit(id uint32, packet *Packet) (bool, error) {\n+\tif o.limit > 0 {\n+\t\tcount := o.written.Add(1)\n+\t\tif count > o.limit {\n+\t\t\to.stop()\n+\t\t\treturn false, nil\n+\t\t}\n+\t\tif err := o.reorder.Push(id, packet); err != nil {\n+\t\t\treturn false, err\n+\t\t}\n+\t\tif count == o.limit {\n+\t\t\to.stop()\n+\t\t\treturn false, nil\n+\t\t}\n+\n+\t\treturn true, nil\n+\t}\n+\n+\to.written.Add(1)\n+\n+\treturn true, o.reorder.Push(id, packet)\n+}\n+\n+// Written returns the number of packets handed to the stream so far.\n+func (o *Output) Written() int64 {\n+\treturn o.written.Load()\n+}\n+\n+// Hold keeps packets stamped after timestamp back until Release(key).\n+func (o *Output) Hold(key any, timestamp int64) {\n+\to.reorder.Hold(key, timestamp)\n+}\n+\n+// Release removes the hold of key.\n+func (o *Output) Release(key any) {\n+\to.reorder.Release(key)\n+}\n+\n+// Close writes the packets still held back and returns the first write error.\n+func (o *Output) Close() error {\n+\to.cancelRun()\n+\t<-o.runDone\n+\to.reorder.Flush()\n+\n+\treturn o.writer.Err()\n+}\ndiff --git a/capture/pcapng.go b/capture/pcapng.go\nnew file mode 100644\nindex 0000000..246ac84\n--- /dev/null\n+++ b/capture/pcapng.go\n@@ -0,0 +1,333 @@\n+// Package capture writes the pcapng streams of `containerlab capture`: one section with one\n+// interface per capture target, packets merged across targets in timestamp order. The local\n+// capturer reads lab link interfaces of Docker and Podman nodes through packet sockets; the c9s\n+// lab runtime feeds the same writer from clabwire streams.\n+package capture\n+\n+import (\n+\t\"bufio\"\n+\t\"encoding/binary\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"math\"\n+\t\"sync\"\n+)\n+\n+// pcapng block layout (https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html). clabwire\n+// writes little-endian sections, and so does the merged stream containerlab writes.\n+const (\n+\tpcapngSectionHeaderType  = 0x0a0d0d0a\n+\tpcapngInterfaceType      = 0x00000001\n+\tpcapngEnhancedPacketType = 0x00000006\n+\tpcapngByteOrderMagic     = 0x1a2b3c4d\n+\tpcapngOptionEnd          = 0\n+\tpcapngOptionUserAppl     = 4\n+\tpcapngOptionIfName       = 2\n+\tpcapngOptionIfTSResol    = 9\n+\tpcapngLinkTypeEthernet   = 1\n+\t// pcapngNanoseconds is the if_tsresol value for 10^-9 s resolution.\n+\tpcapngNanoseconds = 9\n+\t// pcapngMaxBlockLength bounds a block read from a capture stream: a packet of the largest\n+\t// clabwire snap length (1 MiB) plus framing.\n+\tpcapngMaxBlockLength = 1<<20 + 1024\n+\t// captureUserApplication names the writer in the merged section header.\n+\tcaptureUserApplication = \"containerlab\"\n+)\n+\n+var errPCAPNGByteOrder = errors.New(\"pcapng section is not little-endian\")\n+\n+// InterfaceDescription is an Interface Description Block.\n+type InterfaceDescription struct {\n+\tLinkType   uint16\n+\tSnapLength uint32\n+\tName       string\n+\t// TSResol is the raw if_tsresol value; 6 (microseconds) when the block has none.\n+\tTSResol byte\n+}\n+\n+// Packet is an Enhanced Packet Block with its timestamp in nanoseconds.\n+type Packet struct {\n+\tInterfaceID    uint32\n+\tTimestamp      int64\n+\tOriginalLength uint32\n+\tData           []byte\n+}\n+\n+// Reader reads the blocks of a pcapng stream as clabwire writes it: one or more\n+// little-endian sections, each with its Interface Description Blocks before its packets.\n+type Reader struct {\n+\tr          *bufio.Reader\n+\tinterfaces []InterfaceDescription\n+\t// sections counts the Section Header Blocks read so far.\n+\tsections int\n+}\n+\n+// NewReader returns a reader of the pcapng stream r.\n+func NewReader(r io.Reader) *Reader {\n+\treturn &Reader{r: bufio.NewReaderSize(r, 64<<10)}\n+}\n+\n+// Sections returns the number of Section Header Blocks read so far.\n+func (p *Reader) Sections() int {\n+\treturn p.sections\n+}\n+\n+// Event is one block of interest: a new interface or a packet.\n+type Event struct {\n+\tInterface *InterfaceDescription\n+\tPacket    *Packet\n+}\n+\n+// Next returns the next interface or packet, skipping other block types. It returns io.EOF at\n+// the clean end of the stream, and io.ErrUnexpectedEOF for a stream cut inside a block.\n+func (p *Reader) Next() (Event, error) {\n+\tfor {\n+\t\tvar header [8]byte\n+\t\tif _, err := io.ReadFull(p.r, header[:]); err != nil {\n+\t\t\tif errors.Is(err, io.EOF) {\n+\t\t\t\treturn Event{}, io.EOF\n+\t\t\t}\n+\n+\t\t\treturn Event{}, io.ErrUnexpectedEOF\n+\t\t}\n+\n+\t\tblockType := binary.LittleEndian.Uint32(header[0:4])\n+\t\tlength := binary.LittleEndian.Uint32(header[4:8])\n+\t\tif blockType == pcapngSectionHeaderType {\n+\t\t\t// the byte-order magic tells a big-endian section apart before its length is\n+\t\t\t// trusted: that length reads byte swapped\n+\t\t\tmagic, err := p.r.Peek(4)\n+\t\t\tif err != nil {\n+\t\t\t\treturn Event{}, io.ErrUnexpectedEOF\n+\t\t\t}\n+\t\t\tif binary.BigEndian.Uint32(magic) == pcapngByteOrderMagic {\n+\t\t\t\treturn Event{}, errPCAPNGByteOrder\n+\t\t\t}\n+\t\t}\n+\t\tif length < 12 || length%4 != 0 || length > pcapngMaxBlockLength {\n+\t\t\treturn Event{}, fmt.Errorf(\"invalid pcapng block length %d (at most %d)\", length,\n+\t\t\t\tpcapngMaxBlockLength)\n+\t\t}\n+\n+\t\tbody := make([]byte, length-8)\n+\t\tif _, err := io.ReadFull(p.r, body); err != nil {\n+\t\t\treturn Event{}, io.ErrUnexpectedEOF\n+\t\t}\n+\t\tif binary.LittleEndian.Uint32(body[len(body)-4:]) != length {\n+\t\t\treturn Event{}, fmt.Errorf(\"pcapng block lengths do not match\")\n+\t\t}\n+\t\tbody = body[:len(body)-4]\n+\n+\t\tswitch blockType {\n+\t\tcase pcapngSectionHeaderType:\n+\t\t\tif len(body) < 16 {\n+\t\t\t\treturn Event{}, fmt.Errorf(\"short pcapng section header\")\n+\t\t\t}\n+\t\t\tif binary.LittleEndian.Uint32(body[0:4]) != pcapngByteOrderMagic {\n+\t\t\t\treturn Event{}, errPCAPNGByteOrder\n+\t\t\t}\n+\t\t\tp.sections++\n+\t\t\tp.interfaces = nil\n+\t\tcase pcapngInterfaceType:\n+\t\t\tif p.sections == 0 {\n+\t\t\t\treturn Event{}, fmt.Errorf(\"pcapng interface before a section header\")\n+\t\t\t}\n+\t\t\tintf, err := parsePCAPNGInterface(body)\n+\t\t\tif err != nil {\n+\t\t\t\treturn Event{}, err\n+\t\t\t}\n+\t\t\tp.interfaces = append(p.interfaces, intf)\n+\n+\t\t\treturn Event{Interface: &p.interfaces[len(p.interfaces)-1]}, nil\n+\t\tcase pcapngEnhancedPacketType:\n+\t\t\tpacket, err := p.parsePacket(body)\n+\t\t\tif err != nil {\n+\t\t\t\treturn Event{}, err\n+\t\t\t}\n+\n+\t\t\treturn Event{Packet: &packet}, nil\n+\t\t}\n+\t}\n+}\n+\n+func parsePCAPNGInterface(body []byte) (InterfaceDescription, error) {\n+\tif len(body) < 8 {\n+\t\treturn InterfaceDescription{}, fmt.Errorf(\"short pcapng interface description\")\n+\t}\n+\tintf := InterfaceDescription{\n+\t\tLinkType:   binary.LittleEndian.Uint16(body[0:2]),\n+\t\tSnapLength: binary.LittleEndian.Uint32(body[4:8]),\n+\t\tTSResol:    6,\n+\t}\n+\n+\toptions := body[8:]\n+\tfor len(options) >= 4 {\n+\t\tcode := binary.LittleEndian.Uint16(options[0:2])\n+\t\tsize := int(binary.LittleEndian.Uint16(options[2:4]))\n+\t\tif code == pcapngOptionEnd {\n+\t\t\tbreak\n+\t\t}\n+\t\tpadded := size + pcapngPadding(size)\n+\t\tif 4+padded > len(options) {\n+\t\t\treturn InterfaceDescription{}, fmt.Errorf(\"truncated pcapng interface option\")\n+\t\t}\n+\t\tvalue := options[4 : 4+size]\n+\t\tswitch code {\n+\t\tcase pcapngOptionIfName:\n+\t\t\tintf.Name = string(value)\n+\t\tcase pcapngOptionIfTSResol:\n+\t\t\tif size == 1 {\n+\t\t\t\tintf.TSResol = value[0]\n+\t\t\t}\n+\t\t}\n+\t\toptions = options[4+padded:]\n+\t}\n+\n+\treturn intf, nil\n+}\n+\n+func (p *Reader) parsePacket(body []byte) (Packet, error) {\n+\tif len(body) < 20 {\n+\t\treturn Packet{}, fmt.Errorf(\"short pcapng enhanced packet\")\n+\t}\n+\tpacket := Packet{\n+\t\tInterfaceID:    binary.LittleEndian.Uint32(body[0:4]),\n+\t\tOriginalLength: binary.LittleEndian.Uint32(body[16:20]),\n+\t}\n+\tif int(packet.InterfaceID) >= len(p.interfaces) {\n+\t\treturn Packet{}, fmt.Errorf(\"pcapng packet for undeclared interface %d\",\n+\t\t\tpacket.InterfaceID)\n+\t}\n+\tcaptured := binary.LittleEndian.Uint32(body[12:16])\n+\tif int(captured) > len(body)-20 {\n+\t\treturn Packet{}, fmt.Errorf(\"pcapng packet data exceeds its block\")\n+\t}\n+\tpacket.Data = body[20 : 20+captured]\n+\n+\traw := uint64(binary.LittleEndian.Uint32(body[4:8]))<<32 |\n+\t\tuint64(binary.LittleEndian.Uint32(body[8:12]))\n+\ttimestamp, err := pcapngNanosecondsFrom(raw, p.interfaces[packet.InterfaceID].TSResol)\n+\tif err != nil {\n+\t\treturn Packet{}, err\n+\t}\n+\tpacket.Timestamp = timestamp\n+\n+\treturn packet, nil\n+}\n+\n+// pcapngNanosecondsFrom converts a timestamp in an interface's resolution to nanoseconds.\n+// Only decimal resolutions up to nanoseconds occur in clabwire streams.\n+func pcapngNanosecondsFrom(raw uint64, tsresol byte) (int64, error) {\n+\tif tsresol&0x80 != 0 || tsresol > pcapngNanoseconds {\n+\t\treturn 0, fmt.Errorf(\"unsupported pcapng timestamp resolution %#x\", tsresol)\n+\t}\n+\tscale := uint64(1)\n+\tfor range pcapngNanoseconds - int(tsresol) {\n+\t\tscale *= 10\n+\t}\n+\tif raw > math.MaxInt64/scale {\n+\t\treturn 0, fmt.Errorf(\"pcapng timestamp out of range\")\n+\t}\n+\n+\treturn int64(raw * scale), nil //nolint:gosec // bounded above\n+}\n+\n+// Writer writes one little-endian section with nanosecond timestamps. Every block goes out\n+// in one Write under a lock, so concurrent writers never interleave blocks and a stream cut\n+// between writes is still a valid capture.\n+type Writer struct {\n+\tmu  sync.Mutex\n+\tw   io.Writer\n+\terr error\n+}\n+\n+// NewWriter returns a writer of one pcapng section to w.\n+func NewWriter(w io.Writer) *Writer {\n+\treturn &Writer{w: w}\n+}\n+\n+// WriteHeader writes the Section Header Block and one Interface Description Block per name, in\n+// order; packets refer to the interfaces by that index.\n+func (p *Writer) WriteHeader(names []string, snapLength uint32) error {\n+\tsection := make([]byte, 16)\n+\tbinary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)\n+\tbinary.LittleEndian.PutUint16(section[4:], 1)\n+\tbinary.LittleEndian.PutUint16(section[6:], 0)\n+\tbinary.LittleEndian.PutUint64(section[8:], math.MaxUint64)\n+\tsection = appendPCAPNGOption(section, pcapngOptionUserAppl, []byte(captureUserApplication))\n+\tsection = appendPCAPNGOption(section, pcapngOptionEnd, nil)\n+\n+\theader := pcapngBlock(pcapngSectionHeaderType, section)\n+\tfor _, name := range names {\n+\t\tdescription := make([]byte, 8)\n+\t\tbinary.LittleEndian.PutUint16(description[0:], pcapngLinkTypeEthernet)\n+\t\tbinary.LittleEndian.PutUint32(description[4:], snapLength)\n+\t\tdescription = appendPCAPNGOption(description, pcapngOptionIfName, []byte(name))\n+\t\tdescription = appendPCAPNGOption(description, pcapngOptionIfTSResol,\n+\t\t\t[]byte{pcapngNanoseconds})\n+\t\tdescription = appendPCAPNGOption(description, pcapngOptionEnd, nil)\n+\t\theader = append(header, pcapngBlock(pcapngInterfaceType, description)...)\n+\t}\n+\n+\treturn p.write(header)\n+}\n+\n+// WritePacket writes an Enhanced Packet Block for the interface with the given index.\n+func (p *Writer) WritePacket(interfaceID uint32, packet *Packet) error {\n+\ttimestamp := uint64(packet.Timestamp) //nolint:gosec // capture timestamps are positive\n+\tbody := make([]byte, 20, 20+len(packet.Data)+3)\n+\tbinary.LittleEndian.PutUint32(body[0:], interfaceID)\n+\tbinary.LittleEndian.PutUint32(body[4:], uint32(timestamp>>32))\n+\tbinary.LittleEndian.PutUint32(body[8:], uint32(timestamp)) //nolint:gosec // low 32 bits\n+\tbinary.LittleEndian.PutUint32(body[12:], uint32(len(packet.Data)))\n+\tbinary.LittleEndian.PutUint32(body[16:], packet.OriginalLength)\n+\tbody = append(body, packet.Data...)\n+\tbody = append(body, make([]byte, pcapngPadding(len(packet.Data)))...)\n+\n+\treturn p.write(pcapngBlock(pcapngEnhancedPacketType, body))\n+}\n+\n+// Err returns the first write error, or nil.\n+func (p *Writer) Err() error {\n+\tp.mu.Lock()\n+\tdefer p.mu.Unlock()\n+\n+\treturn p.err\n+}\n+\n+func (p *Writer) write(block []byte) error {\n+\tp.mu.Lock()\n+\tdefer p.mu.Unlock()\n+\n+\tif p.err != nil {\n+\t\treturn p.err\n+\t}\n+\tif _, err := p.w.Write(block); err != nil {\n+\t\tp.err = fmt.Errorf(\"failed to write the capture: %w\", err)\n+\t}\n+\n+\treturn p.err\n+}\n+\n+func pcapngBlock(blockType uint32, body []byte) []byte {\n+\ttotal := uint32(12 + len(body)) //nolint:gosec // bounded by the snap length\n+\tblock := make([]byte, 8, total)\n+\tbinary.LittleEndian.PutUint32(block[0:], blockType)\n+\tbinary.LittleEndian.PutUint32(block[4:], total)\n+\tblock = append(block, body...)\n+\n+\treturn binary.LittleEndian.AppendUint32(block, total)\n+}\n+\n+func appendPCAPNGOption(body []byte, code uint16, value []byte) []byte {\n+\tbody = binary.LittleEndian.AppendUint16(body, code)\n+\tbody = binary.LittleEndian.AppendUint16(body, uint16(len(value))) //nolint:gosec // short\n+\tbody = append(body, value...)\n+\n+\treturn append(body, make([]byte, pcapngPadding(len(value)))...)\n+}\n+\n+func pcapngPadding(length int) int {\n+\treturn (4 - length%4) % 4\n+}\ndiff --git a/capture/pcapng_test.go b/capture/pcapng_test.go\nnew file mode 100644\nindex 0000000..0917d16\n--- /dev/null\n+++ b/capture/pcapng_test.go\n@@ -0,0 +1,167 @@\n+package capture\n+\n+import (\n+\t\"bytes\"\n+\t\"encoding/binary\"\n+\t\"errors\"\n+\t\"io\"\n+\t\"strings\"\n+\t\"testing\"\n+)\n+\n+func TestPCAPNGWriterAndReaderRoundTrip(t *testing.T) {\n+\tt.Parallel()\n+\n+\tvar out bytes.Buffer\n+\twriter := NewWriter(&out)\n+\tif err := writer.WriteHeader([]string{\"r1:e1-1\", \"r2:eth1\"}, 1500); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tpackets := []Packet{\n+\t\t{\n+\t\t\tInterfaceID:    1,\n+\t\t\tTimestamp:      1_761_559_200_123_456_789,\n+\t\t\tOriginalLength: 98,\n+\t\t\tData:           []byte(\"abcde\"),\n+\t\t},\n+\t\t{\n+\t\t\tInterfaceID:    0,\n+\t\t\tTimestamp:      1_761_559_200_123_456_790,\n+\t\t\tOriginalLength: 4,\n+\t\t\tData:           []byte(\"wxyz\"),\n+\t\t},\n+\t}\n+\tfor idx := range packets {\n+\t\tif err := writer.WritePacket(packets[idx].InterfaceID, &packets[idx]); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t}\n+\n+\tdata := out.Bytes()\n+\t// the section header names the writer\n+\tif !bytes.Contains(data[:64], []byte(captureUserApplication)) {\n+\t\tt.Fatal(\"section header has no shb_userappl\")\n+\t}\n+\tif len(data)%4 != 0 {\n+\t\tt.Fatalf(\"stream length %d is not 32-bit aligned\", len(data))\n+\t}\n+\n+\treader := NewReader(bytes.NewReader(data))\n+\tvar names []string\n+\tvar read []Packet\n+\tfor {\n+\t\tevent, err := reader.Next()\n+\t\tif errors.Is(err, io.EOF) {\n+\t\t\tbreak\n+\t\t}\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\tif event.Interface != nil {\n+\t\t\tnames = append(names, event.Interface.Name)\n+\t\t\tif event.Interface.SnapLength != 1500 || event.Interface.LinkType != 1 {\n+\t\t\t\tt.Fatalf(\"interface = %+v\", event.Interface)\n+\t\t\t}\n+\t\t}\n+\t\tif event.Packet != nil {\n+\t\t\tread = append(read, *event.Packet)\n+\t\t}\n+\t}\n+\tif len(names) != 2 || names[0] != \"r1:e1-1\" || names[1] != \"r2:eth1\" {\n+\t\tt.Fatalf(\"names = %v\", names)\n+\t}\n+\tfor idx := range packets {\n+\t\tif read[idx].InterfaceID != packets[idx].InterfaceID ||\n+\t\t\tread[idx].Timestamp != packets[idx].Timestamp ||\n+\t\t\tread[idx].OriginalLength != packets[idx].OriginalLength ||\n+\t\t\t!bytes.Equal(read[idx].Data, packets[idx].Data) {\n+\t\t\tt.Fatalf(\"packet %d = %+v, want %+v\", idx, read[idx], packets[idx])\n+\t\t}\n+\t}\n+}\n+\n+func TestPCAPNGReaderHandlesRepeatedSectionsAndResolutions(t *testing.T) {\n+\tt.Parallel()\n+\n+\tvar out bytes.Buffer\n+\tfirst := NewWriter(&out)\n+\t_ = first.WriteHeader([]string{\"eth1\"}, 64)\n+\t_ = first.WritePacket(0, &Packet{Timestamp: 5, Data: []byte{1}})\n+\n+\t// a second section whose interface has microsecond timestamps (no if_tsresol)\n+\tsection := make([]byte, 16)\n+\tbinary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)\n+\tbinary.LittleEndian.PutUint16(section[4:], 1)\n+\tout.Write(pcapngBlock(pcapngSectionHeaderType, section))\n+\tdescription := make([]byte, 8)\n+\tbinary.LittleEndian.PutUint16(description[0:], 1)\n+\tdescription = appendPCAPNGOption(description, pcapngOptionIfName, []byte(\"eth2\"))\n+\tout.Write(pcapngBlock(pcapngInterfaceType, description))\n+\tbody := make([]byte, 20)\n+\tbinary.LittleEndian.PutUint32(body[8:], 7) // 7 microseconds\n+\tout.Write(pcapngBlock(pcapngEnhancedPacketType, body))\n+\n+\treader := NewReader(&out)\n+\tvar timestamps []int64\n+\tfor {\n+\t\tevent, err := reader.Next()\n+\t\tif errors.Is(err, io.EOF) {\n+\t\t\tbreak\n+\t\t}\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\tif event.Packet != nil {\n+\t\t\ttimestamps = append(timestamps, event.Packet.Timestamp)\n+\t\t}\n+\t}\n+\tif reader.sections != 2 || len(timestamps) != 2 || timestamps[0] != 5 || timestamps[1] != 7000 {\n+\t\tt.Fatalf(\"sections %d, timestamps %v\", reader.sections, timestamps)\n+\t}\n+}\n+\n+func TestPCAPNGReaderRejectsInvalidStreams(t *testing.T) {\n+\tt.Parallel()\n+\n+\tvar valid bytes.Buffer\n+\twriter := NewWriter(&valid)\n+\t_ = writer.WriteHeader([]string{\"eth1\"}, 64)\n+\t_ = writer.WritePacket(0, &Packet{Timestamp: 1, Data: []byte(\"data\")})\n+\n+\treadAll := func(data []byte) error {\n+\t\treader := NewReader(bytes.NewReader(data))\n+\t\tfor {\n+\t\t\t_, err := reader.Next()\n+\t\t\tif errors.Is(err, io.EOF) {\n+\t\t\t\treturn nil\n+\t\t\t}\n+\t\t\tif err != nil {\n+\t\t\t\treturn err\n+\t\t\t}\n+\t\t}\n+\t}\n+\n+\tif err := readAll(valid.Bytes()[:valid.Len()-6]); !errors.Is(err, io.ErrUnexpectedEOF) {\n+\t\tt.Fatalf(\"truncated stream: %v\", err)\n+\t}\n+\n+\tbigEndian := append([]byte(nil), valid.Bytes()...)\n+\tbinary.BigEndian.PutUint32(bigEndian[4:], binary.LittleEndian.Uint32(bigEndian[4:]))\n+\tbinary.BigEndian.PutUint32(bigEndian[8:], pcapngByteOrderMagic)\n+\tif err := readAll(bigEndian); !errors.Is(err, errPCAPNGByteOrder) {\n+\t\tt.Fatalf(\"big-endian section: %v\", err)\n+\t}\n+\n+\t// a little-endian section header longer than the reader accepts is not a byte-order error\n+\toversized := append([]byte(nil), valid.Bytes()...)\n+\tbinary.LittleEndian.PutUint32(oversized[4:], 2<<20)\n+\tif err := readAll(oversized); err == nil || errors.Is(err, errPCAPNGByteOrder) ||\n+\t\t!strings.Contains(err.Error(), \"invalid pcapng block length\") {\n+\t\tt.Fatalf(\"oversized little-endian section: %v\", err)\n+\t}\n+\n+\tpacketFirst := pcapngBlock(pcapngEnhancedPacketType, make([]byte, 20))\n+\tif err := readAll(packetFirst); err == nil {\n+\t\tt.Fatal(\"packet before any interface accepted\")\n+\t}\n+}\ndiff --git a/capture/reorder.go b/capture/reorder.go\nnew file mode 100644\nindex 0000000..277ba1a\n--- /dev/null\n+++ b/capture/reorder.go",
        "lineStart": 1101,
        "lineEnd": 1680,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523432638,
      "end": 1793523432656
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19653bcd2001t2kBN1lQIV2Qga",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653b137001Ukh1qsEi71RUoZ",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 24543,
    "input": 21489,
    "output": 27,
    "reasoning": 147,
    "cache": {
      "read": 2880,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19653b137001Ukh1qsEi71RUoZ",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523429687,
    "completed": 1793523432662
  },
  "parentID": "msg_19653b129001cj4QAfxRVtxTFM",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 24543,
    "input": 21489,
    "output": 27,
    "reasoning": 147,
    "cache": {
      "read": 2880,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 45
step-start
{
  "type": "step-start",
  "id": "prt_19653c45d0011k16q1v1tBwpto",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653bcde001mt4UfEP9687WC6"
}
Reasoning
Now the cmd region: 2166-2744 (cmd/capture.go, cmd/capture_test.go, cmd/inspect*.go, cmd/options.go, cmd/root.go changes). I've seen cmd/capture.go implementation before per the summary (flags verified), but let me re-read the diff region 2166-2744 to capture details and verify the options.go/root.go changes.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 600,
  "offset": 2166
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
2166: @@ -0,0 +1,262 @@
2167: +package cmd
2168: +
2169: +import (
2170: +	"encoding/json"
2171: +	"fmt"
2172: +	"io"
2173: +	"os"
2174: +	"strings"
2175: +	"time"
2176: +
2177: +	"github.com/charmbracelet/log"
2178: +	tableWriter "github.com/jedib0t/go-pretty/v6/table"
2179: +	"github.com/jedib0t/go-pretty/v6/text"
2180: +	"github.com/spf13/cobra"
2181: +	clabconstants "github.com/srl-labs/containerlab/constants"
2182: +	clabcore "github.com/srl-labs/containerlab/core"
2183: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2184: +	clabutils "github.com/srl-labs/containerlab/utils"
2185: +)
2186: +
2187: +// CaptureOptions are the flags of the capture command.
2188: +type CaptureOptions struct {
2189: +	Targets     []string
2190: +	Duration    time.Duration
2191: +	PacketLimit int
2192: +	SnapLength  int
2193: +	Write       string
2194: +	List        bool
2195: +	Format      string
2196: +}
2197: +
2198: +func captureCmd(o *Options) (*cobra.Command, error) {
2199: +	c := &cobra.Command{
2200: +		Use:   "capture",
2201: +		Short: "capture packets on lab link interfaces",
2202: +		Long: "capture packets on lab link interfaces of one or more nodes into one pcapng " +
2203: +			"stream\nreference: https://containerlab.dev/cmd/capture/",
2204: +		PreRunE: func(_ *cobra.Command, _ []string) error {
2205: +			if commandSkipsRoot(o.Global.Runtime) {
2206: +				return nil
2207: +			}
2208: +
2209: +			// Docker and Podman captures open packet sockets in the nodes' namespaces
2210: +			return clabutils.CheckAndGetRootPrivs()
2211: +		},
2212: +		SilenceUsage: true,
2213: +		RunE: func(cmd *cobra.Command, _ []string) error {
2214: +			return captureFn(cmd, o)
2215: +		},
2216: +	}
2217: +
2218: +	c.Flags().StringArrayVar(
2219: +		&o.Capture.Targets,
2220: +		"target",
2221: +		o.Capture.Targets,
2222: +		"node and interfaces to capture, as <node>:<interface>[,<interface>...]; repeatable",
2223: +	)
2224: +	c.Flags().DurationVar(
2225: +		&o.Capture.Duration,
2226: +		"duration",
2227: +		o.Capture.Duration,
2228: +		"stop after this duration; 0 captures until interrupted",
2229: +	)
2230: +	c.Flags().IntVar(
2231: +		&o.Capture.PacketLimit,
2232: +		"packet-limit",
2233: +		o.Capture.PacketLimit,
2234: +		"stop after this many packets across all targets; 0 means no limit",
2235: +	)
2236: +	c.Flags().IntVar(
2237: +		&o.Capture.SnapLength,
2238: +		"snap-length",
2239: +		o.Capture.SnapLength,
2240: +		"bytes kept of each packet (64 to 1048576); 0 uses the runtime default",
2241: +	)
2242: +	c.Flags().StringVarP(
2243: +		&o.Capture.Write,
2244: +		"write",
2245: +		"w",
2246: +		o.Capture.Write,
2247: +		"pcapng output file; - writes to stdout",
2248: +	)
2249: +	c.Flags().BoolVar(
2250: +		&o.Capture.List,
2251: +		"list",
2252: +		o.Capture.List,
2253: +		"list the capturable interfaces instead of capturing",
2254: +	)
2255: +	c.Flags().StringVarP(
2256: +		&o.Capture.Format,
2257: +		"format",
2258: +		"f",
2259: +		o.Capture.Format,
2260: +		"output format of --list: table or json",
2261: +	)
2262: +
2263: +	c.Example = `# Capture e1-1 of srl1 and e1-1 of srl2 for 30 seconds into one file
2264: +containerlab capture -t srl.clab.yml --target srl1:e1-1 --target srl2:e1-1 \
2265: +  --duration 30s -w srl.pcapng
2266: +
2267: +# Capture two interfaces of one node and watch them live in Wireshark
2268: +containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -
2269: +
2270: +# List the interfaces capture accepts
2271: +containerlab capture --name srl --list -f json
2272: +
2273: +# Capture a lab running on the c9s runtime
2274: +containerlab -r c9s capture --name srl --target srl1:e1-1 -w srl.pcapng`
2275: +
2276: +	return c, nil
2277: +}
2278: +
2279: +func captureFn(cmd *cobra.Command, o *Options) error {
2280: +	if o.Global.TopologyName == "" && o.Global.TopologyFile == "" {
2281: +		return fmt.Errorf("provide either a lab name (--name) or a topology file path (--topo)")
2282: +	}
2283: +
2284: +	if o.Capture.List {
2285: +		return captureListFn(cmd, o)
2286: +	}
2287: +
2288: +	targets, err := parseCaptureTargets(o.Capture.Targets)
2289: +	if err != nil {
2290: +		return err
2291: +	}
2292: +
2293: +	c, err := clabcore.NewContainerLab(o.ToClabOptions()...)
2294: +	if err != nil {
2295: +		return err
2296: +	}
2297: +
2298: +	// An interrupt ends the capture; the command still finishes the file and exits cleanly.
2299: +	// Armed before the file is created, so an interrupt never leaves it empty.
2300: +	o.Global.FinishOnCancel.Store(true)
2301: +	defer o.Global.FinishOnCancel.Store(false)
2302: +
2303: +	output := cmd.OutOrStdout()
2304: +	if o.Capture.Write != "" && o.Capture.Write != "-" {
2305: +		file, err := os.Create(o.Capture.Write)
2306: +		if err != nil {
2307: +			return fmt.Errorf("failed to create the capture file: %w", err)
2308: +		}
2309: +		defer file.Close()
2310: +		output = file
2311: +
2312: +		// the file belongs to the user who ran the command, also through sudo or setuid
2313: +		if err := clabutils.SetUIDAndGID(o.Capture.Write); err != nil {
2314: +			log.Debug("Cannot hand the capture file to the user", "file", o.Capture.Write,
2315: +				"error", err)
2316: +		}
2317: +	}
2318: +
2319: +	err = c.Capture(cmd.Context(), clablabruntime.CaptureRequest{
2320: +		Targets:     targets,
2321: +		Duration:    o.Capture.Duration,
2322: +		PacketLimit: o.Capture.PacketLimit,
2323: +		SnapLength:  o.Capture.SnapLength,
2324: +	}, output)
2325: +	if err != nil {
2326: +		return err
2327: +	}
2328: +
2329: +	if file, ok := output.(*os.File); ok && output != cmd.OutOrStdout() {
2330: +		if err := file.Sync(); err != nil {
2331: +			return fmt.Errorf("failed to write the capture file: %w", err)
2332: +		}
2333: +	}
2334: +
2335: +	return nil
2336: +}
2337: +
2338: +// parseCaptureTargets parses --target values: <node>:<interface>[,<interface>...]. The node name
2339: +// ends at the first colon, so interface names may contain colons or slashes.
2340: +func parseCaptureTargets(values []string) ([]clablabruntime.CaptureTarget, error) {
2341: +	if len(values) == 0 {
2342: +		return nil, fmt.Errorf("provide at least one --target <node>:<interface>[,<interface>...]")
2343: +	}
2344: +
2345: +	targets := make([]clablabruntime.CaptureTarget, 0, len(values))
2346: +	for _, value := range values {
2347: +		node, interfaces, ok := strings.Cut(strings.TrimSpace(value), ":")
2348: +		node = strings.TrimSpace(node)
2349: +		if !ok || node == "" || strings.TrimSpace(interfaces) == "" {
2350: +			return nil, fmt.Errorf("invalid --target %q: use <node>:<interface>[,<interface>...]",
2351: +				value)
2352: +		}
2353: +
2354: +		for _, name := range strings.Split(interfaces, ",") {
2355: +			name = strings.TrimSpace(name)
2356: +			if name == "" {
2357: +				return nil, fmt.Errorf("invalid --target %q: empty interface name", value)
2358: +			}
2359: +			targets = append(targets, clablabruntime.CaptureTarget{Node: node, Interface: name})
2360: +		}
2361: +	}
2362: +
2363: +	return targets, nil
2364: +}
2365: +
2366: +func captureListFn(cmd *cobra.Command, o *Options) error {
2367: +	format := o.Capture.Format
2368: +	if format == "" {
2369: +		format = clabconstants.FormatTable
2370: +	}
2371: +	if format != clabconstants.FormatTable && format != clabconstants.FormatJSON {
2372: +		return fmt.Errorf("output format %q is not supported, use 'table' or 'json'", format)
2373: +	}
2374: +	if len(o.Capture.Targets) != 0 {
2375: +		return fmt.Errorf("--list lists every running node's interfaces; it takes no --target")
2376: +	}
2377: +
2378: +	c, err := clabcore.NewContainerLab(o.ToClabOptions()...)
2379: +	if err != nil {
2380: +		return err
2381: +	}
2382: +
2383: +	interfaces, err := c.CaptureInterfaces(cmd.Context())
2384: +	if err != nil {
2385: +		return err
2386: +	}
2387: +
2388: +	return printCaptureInterfaces(cmd.OutOrStdout(), interfaces, format)
2389: +}
2390: +
2391: +func printCaptureInterfaces(
2392: +	w io.Writer,
2393: +	interfaces []clablabruntime.CaptureInterface,
2394: +	format string,
2395: +) error {
2396: +	if format == clabconstants.FormatJSON {
2397: +		if interfaces == nil {
2398: +			interfaces = []clablabruntime.CaptureInterface{}
2399: +		}
2400: +		data, err := json.MarshalIndent(interfaces, "", "  ")
2401: +		if err != nil {
2402: +			return err
2403: +		}
2404: +		_, err = fmt.Fprintln(w, string(data))
2405: +
2406: +		return err
2407: +	}
2408: +
2409: +	table := tableWriter.NewWriter()
2410: +	table.SetOutputMirror(w)
2411: +	table.SetStyle(tableWriter.StyleRounded)
2412: +	table.Style().Format.Header = text.FormatTitle
2413: +	table.Style().Format.HeaderAlign = text.AlignCenter
2414: +	table.AppendHeader(tableWriter.Row{"Node", "Interface", "Alias", "Peer Node", "Peer Interface"})
2415: +	table.SetColumnConfigs([]tableWriter.ColumnConfig{{Number: 1, AutoMerge: true}})
2416: +	for _, intf := range interfaces {
2417: +		alias := intf.Alias
2418: +		if alias == "" {
2419: +			alias = clabconstants.NotApplicable
2420: +		}
2421: +		table.AppendRow(tableWriter.Row{
2422: +			intf.Node, intf.Interface, alias, intf.PeerNode, intf.PeerInterface,
2423: +		})
2424: +	}
2425: +	table.Render()
2426: +
2427: +	return nil
2428: +}
2429: diff --git a/cmd/capture_test.go b/cmd/capture_test.go
2430: new file mode 100644
2431: index 0000000..da12d66
2432: --- /dev/null
2433: +++ b/cmd/capture_test.go
2434: @@ -0,0 +1,109 @@
2435: +package cmd
2436: +
2437: +import (
2438: +	"bytes"
2439: +	"encoding/json"
2440: +	"slices"
2441: +	"strings"
2442: +	"testing"
2443: +
2444: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2445: +)
2446: +
2447: +func TestParseCaptureTargets(t *testing.T) {
2448: +	t.Parallel()
2449: +
2450: +	targets, err := parseCaptureTargets([]string{
2451: +		"srl1:e1-1,ethernet-1/2", " sros : 1/1/3 ", "r1:eth1",
2452: +	})
2453: +	if err != nil {
2454: +		t.Fatal(err)
2455: +	}
2456: +	want := []clablabruntime.CaptureTarget{
2457: +		{Node: "srl1", Interface: "e1-1"},
2458: +		{Node: "srl1", Interface: "ethernet-1/2"},
2459: +		{Node: "sros", Interface: "1/1/3"},
2460: +		{Node: "r1", Interface: "eth1"},
2461: +	}
2462: +	if !slices.Equal(targets, want) {
2463: +		t.Fatalf("targets = %+v, want %+v", targets, want)
2464: +	}
2465: +
2466: +	for _, bad := range [][]string{nil, {"srl1"}, {":e1-1"}, {"srl1:"}, {"srl1:e1-1,,e1-2"}} {
2467: +		if _, err := parseCaptureTargets(bad); err == nil {
2468: +			t.Errorf("parseCaptureTargets(%q) succeeded", bad)
2469: +		}
2470: +	}
2471: +}
2472: +
2473: +func TestCaptureCommandFlags(t *testing.T) {
2474: +	o := GetOptions()
2475: +	cmd, err := captureCmd(o)
2476: +	if err != nil {
2477: +		t.Fatal(err)
2478: +	}
2479: +	if err := cmd.ParseFlags([]string{
2480: +		"--target", "srl1:e1-1", "--target", "srl2:e1-1,e1-2", "--duration", "90m",
2481: +		"--packet-limit", "100", "--snap-length", "128", "-w", "out.pcapng",
2482: +	}); err != nil {
2483: +		t.Fatal(err)
2484: +	}
2485: +	if !slices.Equal(o.Capture.Targets, []string{"srl1:e1-1", "srl2:e1-1,e1-2"}) ||
2486: +		o.Capture.Duration.Minutes() != 90 || o.Capture.PacketLimit != 100 ||
2487: +		o.Capture.SnapLength != 128 || o.Capture.Write != "out.pcapng" {
2488: +		t.Fatalf("capture options = %+v", o.Capture)
2489: +	}
2490: +	if def := cmd.Flag("write").DefValue; def != "-" {
2491: +		t.Fatalf("--write default = %q, want stdout", def)
2492: +	}
2493: +}
2494: +
2495: +func TestPrintCaptureInterfaces(t *testing.T) {
2496: +	t.Parallel()
2497: +
2498: +	interfaces := []clablabruntime.CaptureInterface{
2499: +		{
2500: +			Node:          "srl1",
2501: +			Interface:     "e1-1",
2502: +			Alias:         "ethernet-1/1",
2503: +			PeerNode:      "srl2",
2504: +			PeerInterface: "ethernet-1/1",
2505: +		},
2506: +		{Node: "srl1", Interface: "e1-2", PeerNode: "host", PeerInterface: "srl1-e1-2"},
2507: +	}
2508: +
2509: +	var out bytes.Buffer
2510: +	if err := printCaptureInterfaces(&out, interfaces, "json"); err != nil {
2511: +		t.Fatal(err)
2512: +	}
2513: +	var decoded []map[string]any
2514: +	if err := json.Unmarshal(out.Bytes(), &decoded); err != nil {
2515: +		t.Fatal(err)
2516: +	}
2517: +	if decoded[0]["peer_node"] != "srl2" || decoded[0]["alias"] != "ethernet-1/1" {
2518: +		t.Fatalf("json = %s", out.String())
2519: +	}
2520: +	if _, hasAlias := decoded[1]["alias"]; hasAlias {
2521: +		t.Fatalf("an empty alias is printed: %s", out.String())
2522: +	}
2523: +
2524: +	out.Reset()
2525: +	if err := printCaptureInterfaces(
2526: +		&out,
2527: +		nil,
2528: +		"json",
2529: +	); err != nil ||
2530: +		strings.TrimSpace(out.String()) != "[]" {
2531: +		t.Fatalf("empty json = %q, %v", out.String(), err)
2532: +	}
2533: +
2534: +	out.Reset()
2535: +	if err := printCaptureInterfaces(&out, interfaces, "table"); err != nil {
2536: +		t.Fatal(err)
2537: +	}
2538: +	for _, want := range []string{"Peer Interface", "ethernet-1/1", "srl1-e1-2", "N/A"} {
2539: +		if !strings.Contains(out.String(), want) {
2540: +			t.Fatalf("table does not contain %q:\n%s", want, out.String())
2541: +		}
2542: +	}
2543: +}
2544: diff --git a/cmd/context.go b/cmd/context.go
2545: index 223cb1d..21d5bea 100644
2546: --- a/cmd/context.go
2547: +++ b/cmd/context.go
2548: @@ -51,10 +51,20 @@ func SignalHandledContext() (context.Context, context.CancelFunc) {
2549:  
2550:  		cancel()
2551:  
2552:  		options := GetOptions()
2553:  
2554: +		if options.Global.FinishOnCancel.Load() {
2555: +			log.Info("Stopping, press Ctrl+C again to abort")
2556: +
2557: +			sig = <-sigs
2558: +
2559: +			log.Errorf("received signal %q while stopping, exiting", sig)
2560: +
2561: +			os.Exit(1)
2562: +		}
2563: +
2564:  		if !options.Global.CleanOnCancel.Load() {
2565:  			log.Debug("clean on cancel is not true, exiting")
2566:  
2567:  			os.Exit(1)
2568:  		}
2569: diff --git a/cmd/inspect.go b/cmd/inspect.go
2570: index 1b6f41d..55fb61f 100644
2571: --- a/cmd/inspect.go
2572: +++ b/cmd/inspect.go
2573: @@ -70,10 +70,14 @@ func inspectCmd(o *Options) (*cobra.Command, error) {
2574:  		Short: "inspect interfaces of one or multiple nodes in a lab",
2575:  		Long: "show interfaces and their attributes in a specific deployed lab\n" +
2576:  			"reference: https://containerlab.dev/cmd/inspect/interfaces/",
2577:  		Aliases: []string{"int", "intf"},
2578:  		PreRunE: func(_ *cobra.Command, _ []string) error {
2579: +			if commandSkipsRoot(o.Global.Runtime) {
2580: +				return nil
2581: +			}
2582: +
2583:  			return clabutils.CheckAndGetRootPrivs()
2584:  		},
2585:  		RunE: func(cobraCmd *cobra.Command, _ []string) error {
2586:  			return inspectInterfacesFn(cobraCmd, o)
2587:  		},
2588: diff --git a/cmd/inspect_interfaces.go b/cmd/inspect_interfaces.go
2589: index 0f64f03..91035c2 100644
2590: --- a/cmd/inspect_interfaces.go
2591: +++ b/cmd/inspect_interfaces.go
2592: @@ -33,10 +33,25 @@ func inspectInterfacesFn(cobraCmd *cobra.Command, o *Options) error {
2593:  	c, err := clabcore.NewContainerLab(o.ToClabOptions()...)
2594:  	if err != nil {
2595:  		return fmt.Errorf("could not parse the topology file: %v", err)
2596:  	}
2597:  
2598: +	if c.LabRuntime != nil {
2599: +		// lab runtimes list the link interfaces packet capture accepts, with their state
2600: +		containerInterfaces, err := c.LabRuntimeInterfaces(cobraCmd.Context(),
2601: +			o.Inspect.InterfacesNode)
2602: +		if err != nil {
2603: +			return fmt.Errorf("failed to list node interfaces: %w", err)
2604: +		}
2605: +		if len(containerInterfaces) == 0 {
2606: +			log.Info("no running nodes found")
2607: +			return nil
2608: +		}
2609: +
2610: +		return printContainerInterfaces(containerInterfaces, o.Inspect.InterfacesFormat)
2611: +	}
2612: +
2613:  	var labNameFilterLabel string
2614:  
2615:  	switch {
2616:  	case o.Global.TopologyName != "":
2617:  		labNameFilterLabel = o.Global.TopologyName
2618: diff --git a/cmd/options.go b/cmd/options.go
2619: index 8717d3b..6037551 100644
2620: --- a/cmd/options.go
2621: +++ b/cmd/options.go
2622: @@ -53,10 +53,14 @@ func GetOptions() *Options {
2623:  				InterfacesFormat: "table",
2624:  			},
2625:  			Logs: &LogsOptions{
2626:  				Tail: -1,
2627:  			},
2628: +			Capture: &CaptureOptions{
2629: +				Write:  "-",
2630: +				Format: "table",
2631: +			},
2632:  			Graph: &GraphOptions{
2633:  				Server:           "0.0.0.0:50080",
2634:  				MermaidDirection: "TD",
2635:  				DrawIOVersion:    "latest",
2636:  			},
2637: @@ -142,10 +146,11 @@ type Options struct {
2638:  	Exec           *ExecOptions
2639:  	Inspect        *InspectOptions
2640:  	Graph          *GraphOptions
2641:  	Events         *EventsOptions
2642:  	Logs           *LogsOptions
2643: +	Capture        *CaptureOptions
2644:  	ToolsAPI       *ToolsApiOptions
2645:  	ToolsCert      *ToolsCertOptions
2646:  	ToolsTxOffload *ToolsDisableTxOffloadOptions
2647:  	ToolsGoTTY     *ToolsGoTTYOptions
2648:  	ToolsNetem     *ToolsNetemOptions
2649: @@ -257,10 +262,15 @@ type GlobalOptions struct {
2650:  	// special flag that should only be set by deploy, informs the context handler to destroy
2651:  	// (or not) when root context is canceled. The signal handler goroutine reads it while
2652:  	// deploy is running, so it is atomic.
2653:  	CleanOnCancel atomic.Bool
2654:  
2655: +	// FinishOnCancel informs the context handler that the running command ends cleanly on its
2656: +	// own once the root context is canceled (capture finishes its output), so the handler
2657: +	// waits for it instead of exiting.
2658: +	FinishOnCancel atomic.Bool
2659: +
2660:  	// special flag that is only set on deploy,
2661:  	// if true, the topology file backup is created at /tmp/.clab/bak
2662:  	BackupTopologyFile bool
2663:  }
2664:  
2665: diff --git a/cmd/root.go b/cmd/root.go
2666: index 0baf203..a9b1c8b 100644
2667: --- a/cmd/root.go
2668: +++ b/cmd/root.go
2669: @@ -35,10 +35,11 @@ func subcommandRegisterFuncs() []func(*Options) (*cobra.Command, error) {
2670:  		generateCmd,
2671:  		graphCmd,
2672:  		eventsCmd,
2673:  		inspectCmd,
2674:  		logsCmd,
2675: +		captureCmd,
2676:  		redeployCmd,
2677:  		saveCmd,
2678:  		toolsCmd,
2679:  		validateCmd,
2680:  	}
2681: @@ -263,15 +264,10 @@ func checkLabRuntimeCommandSupport(cobraCmd *cobra.Command, runtimeName string)
2682:  			"the %q command needs running containers with lab runtime %q unless it renders "+
2683:  				"from the topology file alone; use --offline, --dot, --mermaid or --drawio",
2684:  			"graph", runtimeName)
2685:  	}
2686:  
2687: -	if getCommandPath(cobraCmd) == "inspect.interfaces" {
2688: -		return fmt.Errorf("the %q command is not supported with lab runtime %q",
2689: -			"inspect interfaces", runtimeName)
2690: -	}
2691: -
2692:  	var unsupported []string
2693:  	for _, flagName := range labRuntimeUnsupportedFlags[getCommandPath(cobraCmd)] {
2694:  		if labRuntimeFlagWasSet(cobraCmd, flagName) {
2695:  			unsupported = append(unsupported, "--"+flagName)
2696:  		}
2697: @@ -339,10 +335,11 @@ func getTopoFilePath(cobraCmd *cobra.Command, o *Options) error { // skipcq: GO-
2698:  		cobraCmd.Name() != "inspect" &&
2699:  		cobraCmd.Name() != "save" &&
2700:  		cobraCmd.Name() != "graph" &&
2701:  		cobraCmd.Name() != "validate" &&
2702:  		cobraCmd.Name() != "logs" &&
2703: +		cobraCmd.Name() != "capture" &&
2704:  		cobraCmd.Name() != "interfaces" {
2705:  		return nil
2706:  	}
2707:  
2708:  	// start/stop/restart topology lookup applies only to top-level lifecycle commands.
2709: diff --git a/cmd/root_test.go b/cmd/root_test.go
2710: index 418a947..af02e34 100644
2711: --- a/cmd/root_test.go
2712: +++ b/cmd/root_test.go
2713: @@ -289,20 +289,23 @@ func TestCheckLabRuntimeFlagAndNestedCommandSupport(t *testing.T) {
2714:  				t.Fatalf("checkLabRuntimeCommandSupport() error = %v, wantErr %v", err, tt.wantErr)
2715:  			}
2716:  		})
2717:  	}
2718:  
2719: -	t.Run("inspect interfaces rejected", func(t *testing.T) {
2720: +	t.Run("inspect interfaces and capture accepted", func(t *testing.T) {
2721:  		root := &cobra.Command{Use: "containerlab"}
2722:  		inspect := &cobra.Command{Use: "inspect"}
2723:  		interfaces := &cobra.Command{Use: "interfaces"}
2724: -		root.AddCommand(inspect)
2725: +		capture := &cobra.Command{Use: "capture"}
2726: +		root.AddCommand(inspect, capture)
2727:  		inspect.AddCommand(interfaces)
2728:  
2729: -		if err := checkLabRuntimeCommandSupport(
2730: -			interfaces,
2731: -			clablabruntime.ClabernetesRuntimeName,
2732: -		); err == nil {
2733: -			t.Fatal("inspect interfaces was accepted for clabernetes")
2734: +		for _, cmd := range []*cobra.Command{interfaces, capture} {
2735: +			if err := checkLabRuntimeCommandSupport(
2736: +				cmd,
2737: +				clablabruntime.ClabernetesRuntimeName,
2738: +			); err != nil {
2739: +				t.Fatalf("%s rejected for clabernetes: %v", cmd.Name(), err)
2740: +			}
2741:  		}
2742:  	})
2743:  }
2744: diff --git a/core/capture.go b/core/capture.go
2745: new file mode 100644
2746: index 0000000..2e12fc2
2747: --- /dev/null
2748: +++ b/core/capture.go
2749: @@ -0,0 +1,93 @@
2750: +package core
2751: +
2752: +import (
2753: +	"context"
2754: +	"io"
2755: +
2756: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2757: +	clabtypes "github.com/srl-labs/containerlab/types"
2758: +)
2759: +
2760: +// CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for
2761: +// every running node, with the peer at the other end of each link. With Docker and Podman, the
2762: +// interfaces come from the topology's links; lab runtimes list them through their packet
2763: +// capturer.
2764: +func (c *CLab) CaptureInterfaces(
2765: +	ctx context.Context,

(Showing lines 2166-2765 of 7018. Use offset=2766 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19653c6ad001x0ayXxSn5KexTc",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653bcde001mt4UfEP9687WC6",
  "callID": "call_1c201bef32824499ac19c23a",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 600,
      "offset": 2166
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n2166: @@ -0,0 +1,262 @@\n2167: +package cmd\n2168: +\n2169: +import (\n2170: +\t\"encoding/json\"\n2171: +\t\"fmt\"\n2172: +\t\"io\"\n2173: +\t\"os\"\n2174: +\t\"strings\"\n2175: +\t\"time\"\n2176: +\n2177: +\t\"github.com/charmbracelet/log\"\n2178: +\ttableWriter \"github.com/jedib0t/go-pretty/v6/table\"\n2179: +\t\"github.com/jedib0t/go-pretty/v6/text\"\n2180: +\t\"github.com/spf13/cobra\"\n2181: +\tclabconstants \"github.com/srl-labs/containerlab/constants\"\n2182: +\tclabcore \"github.com/srl-labs/containerlab/core\"\n2183: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2184: +\tclabutils \"github.com/srl-labs/containerlab/utils\"\n2185: +)\n2186: +\n2187: +// CaptureOptions are the flags of the capture command.\n2188: +type CaptureOptions struct {\n2189: +\tTargets     []string\n2190: +\tDuration    time.Duration\n2191: +\tPacketLimit int\n2192: +\tSnapLength  int\n2193: +\tWrite       string\n2194: +\tList        bool\n2195: +\tFormat      string\n2196: +}\n2197: +\n2198: +func captureCmd(o *Options) (*cobra.Command, error) {\n2199: +\tc := &cobra.Command{\n2200: +\t\tUse:   \"capture\",\n2201: +\t\tShort: \"capture packets on lab link interfaces\",\n2202: +\t\tLong: \"capture packets on lab link interfaces of one or more nodes into one pcapng \" +\n2203: +\t\t\t\"stream\\nreference: https://containerlab.dev/cmd/capture/\",\n2204: +\t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n2205: +\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n2206: +\t\t\t\treturn nil\n2207: +\t\t\t}\n2208: +\n2209: +\t\t\t// Docker and Podman captures open packet sockets in the nodes' namespaces\n2210: +\t\t\treturn clabutils.CheckAndGetRootPrivs()\n2211: +\t\t},\n2212: +\t\tSilenceUsage: true,\n2213: +\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n2214: +\t\t\treturn captureFn(cmd, o)\n2215: +\t\t},\n2216: +\t}\n2217: +\n2218: +\tc.Flags().StringArrayVar(\n2219: +\t\t&o.Capture.Targets,\n2220: +\t\t\"target\",\n2221: +\t\to.Capture.Targets,\n2222: +\t\t\"node and interfaces to capture, as <node>:<interface>[,<interface>...]; repeatable\",\n2223: +\t)\n2224: +\tc.Flags().DurationVar(\n2225: +\t\t&o.Capture.Duration,\n2226: +\t\t\"duration\",\n2227: +\t\to.Capture.Duration,\n2228: +\t\t\"stop after this duration; 0 captures until interrupted\",\n2229: +\t)\n2230: +\tc.Flags().IntVar(\n2231: +\t\t&o.Capture.PacketLimit,\n2232: +\t\t\"packet-limit\",\n2233: +\t\to.Capture.PacketLimit,\n2234: +\t\t\"stop after this many packets across all targets; 0 means no limit\",\n2235: +\t)\n2236: +\tc.Flags().IntVar(\n2237: +\t\t&o.Capture.SnapLength,\n2238: +\t\t\"snap-length\",\n2239: +\t\to.Capture.SnapLength,\n2240: +\t\t\"bytes kept of each packet (64 to 1048576); 0 uses the runtime default\",\n2241: +\t)\n2242: +\tc.Flags().StringVarP(\n2243: +\t\t&o.Capture.Write,\n2244: +\t\t\"write\",\n2245: +\t\t\"w\",\n2246: +\t\to.Capture.Write,\n2247: +\t\t\"pcapng output file; - writes to stdout\",\n2248: +\t)\n2249: +\tc.Flags().BoolVar(\n2250: +\t\t&o.Capture.List,\n2251: +\t\t\"list\",\n2252: +\t\to.Capture.List,\n2253: +\t\t\"list the capturable interfaces instead of capturing\",\n2254: +\t)\n2255: +\tc.Flags().StringVarP(\n2256: +\t\t&o.Capture.Format,\n2257: +\t\t\"format\",\n2258: +\t\t\"f\",\n2259: +\t\to.Capture.Format,\n2260: +\t\t\"output format of --list: table or json\",\n2261: +\t)\n2262: +\n2263: +\tc.Example = `# Capture e1-1 of srl1 and e1-1 of srl2 for 30 seconds into one file\n2264: +containerlab capture -t srl.clab.yml --target srl1:e1-1 --target srl2:e1-1 \\\n2265: +  --duration 30s -w srl.pcapng\n2266: +\n2267: +# Capture two interfaces of one node and watch them live in Wireshark\n2268: +containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n2269: +\n2270: +# List the interfaces capture accepts\n2271: +containerlab capture --name srl --list -f json\n2272: +\n2273: +# Capture a lab running on the c9s runtime\n2274: +containerlab -r c9s capture --name srl --target srl1:e1-1 -w srl.pcapng`\n2275: +\n2276: +\treturn c, nil\n2277: +}\n2278: +\n2279: +func captureFn(cmd *cobra.Command, o *Options) error {\n2280: +\tif o.Global.TopologyName == \"\" && o.Global.TopologyFile == \"\" {\n2281: +\t\treturn fmt.Errorf(\"provide either a lab name (--name) or a topology file path (--topo)\")\n2282: +\t}\n2283: +\n2284: +\tif o.Capture.List {\n2285: +\t\treturn captureListFn(cmd, o)\n2286: +\t}\n2287: +\n2288: +\ttargets, err := parseCaptureTargets(o.Capture.Targets)\n2289: +\tif err != nil {\n2290: +\t\treturn err\n2291: +\t}\n2292: +\n2293: +\tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n2294: +\tif err != nil {\n2295: +\t\treturn err\n2296: +\t}\n2297: +\n2298: +\t// An interrupt ends the capture; the command still finishes the file and exits cleanly.\n2299: +\t// Armed before the file is created, so an interrupt never leaves it empty.\n2300: +\to.Global.FinishOnCancel.Store(true)\n2301: +\tdefer o.Global.FinishOnCancel.Store(false)\n2302: +\n2303: +\toutput := cmd.OutOrStdout()\n2304: +\tif o.Capture.Write != \"\" && o.Capture.Write != \"-\" {\n2305: +\t\tfile, err := os.Create(o.Capture.Write)\n2306: +\t\tif err != nil {\n2307: +\t\t\treturn fmt.Errorf(\"failed to create the capture file: %w\", err)\n2308: +\t\t}\n2309: +\t\tdefer file.Close()\n2310: +\t\toutput = file\n2311: +\n2312: +\t\t// the file belongs to the user who ran the command, also through sudo or setuid\n2313: +\t\tif err := clabutils.SetUIDAndGID(o.Capture.Write); err != nil {\n2314: +\t\t\tlog.Debug(\"Cannot hand the capture file to the user\", \"file\", o.Capture.Write,\n2315: +\t\t\t\t\"error\", err)\n2316: +\t\t}\n2317: +\t}\n2318: +\n2319: +\terr = c.Capture(cmd.Context(), clablabruntime.CaptureRequest{\n2320: +\t\tTargets:     targets,\n2321: +\t\tDuration:    o.Capture.Duration,\n2322: +\t\tPacketLimit: o.Capture.PacketLimit,\n2323: +\t\tSnapLength:  o.Capture.SnapLength,\n2324: +\t}, output)\n2325: +\tif err != nil {\n2326: +\t\treturn err\n2327: +\t}\n2328: +\n2329: +\tif file, ok := output.(*os.File); ok && output != cmd.OutOrStdout() {\n2330: +\t\tif err := file.Sync(); err != nil {\n2331: +\t\t\treturn fmt.Errorf(\"failed to write the capture file: %w\", err)\n2332: +\t\t}\n2333: +\t}\n2334: +\n2335: +\treturn nil\n2336: +}\n2337: +\n2338: +// parseCaptureTargets parses --target values: <node>:<interface>[,<interface>...]. The node name\n2339: +// ends at the first colon, so interface names may contain colons or slashes.\n2340: +func parseCaptureTargets(values []string) ([]clablabruntime.CaptureTarget, error) {\n2341: +\tif len(values) == 0 {\n2342: +\t\treturn nil, fmt.Errorf(\"provide at least one --target <node>:<interface>[,<interface>...]\")\n2343: +\t}\n2344: +\n2345: +\ttargets := make([]clablabruntime.CaptureTarget, 0, len(values))\n2346: +\tfor _, value := range values {\n2347: +\t\tnode, interfaces, ok := strings.Cut(strings.TrimSpace(value), \":\")\n2348: +\t\tnode = strings.TrimSpace(node)\n2349: +\t\tif !ok || node == \"\" || strings.TrimSpace(interfaces) == \"\" {\n2350: +\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: use <node>:<interface>[,<interface>...]\",\n2351: +\t\t\t\tvalue)\n2352: +\t\t}\n2353: +\n2354: +\t\tfor _, name := range strings.Split(interfaces, \",\") {\n2355: +\t\t\tname = strings.TrimSpace(name)\n2356: +\t\t\tif name == \"\" {\n2357: +\t\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: empty interface name\", value)\n2358: +\t\t\t}\n2359: +\t\t\ttargets = append(targets, clablabruntime.CaptureTarget{Node: node, Interface: name})\n2360: +\t\t}\n2361: +\t}\n2362: +\n2363: +\treturn targets, nil\n2364: +}\n2365: +\n2366: +func captureListFn(cmd *cobra.Command, o *Options) error {\n2367: +\tformat := o.Capture.Format\n2368: +\tif format == \"\" {\n2369: +\t\tformat = clabconstants.FormatTable\n2370: +\t}\n2371: +\tif format != clabconstants.FormatTable && format != clabconstants.FormatJSON {\n2372: +\t\treturn fmt.Errorf(\"output format %q is not supported, use 'table' or 'json'\", format)\n2373: +\t}\n2374: +\tif len(o.Capture.Targets) != 0 {\n2375: +\t\treturn fmt.Errorf(\"--list lists every running node's interfaces; it takes no --target\")\n2376: +\t}\n2377: +\n2378: +\tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n2379: +\tif err != nil {\n2380: +\t\treturn err\n2381: +\t}\n2382: +\n2383: +\tinterfaces, err := c.CaptureInterfaces(cmd.Context())\n2384: +\tif err != nil {\n2385: +\t\treturn err\n2386: +\t}\n2387: +\n2388: +\treturn printCaptureInterfaces(cmd.OutOrStdout(), interfaces, format)\n2389: +}\n2390: +\n2391: +func printCaptureInterfaces(\n2392: +\tw io.Writer,\n2393: +\tinterfaces []clablabruntime.CaptureInterface,\n2394: +\tformat string,\n2395: +) error {\n2396: +\tif format == clabconstants.FormatJSON {\n2397: +\t\tif interfaces == nil {\n2398: +\t\t\tinterfaces = []clablabruntime.CaptureInterface{}\n2399: +\t\t}\n2400: +\t\tdata, err := json.MarshalIndent(interfaces, \"\", \"  \")\n2401: +\t\tif err != nil {\n2402: +\t\t\treturn err\n2403: +\t\t}\n2404: +\t\t_, err = fmt.Fprintln(w, string(data))\n2405: +\n2406: +\t\treturn err\n2407: +\t}\n2408: +\n2409: +\ttable := tableWriter.NewWriter()\n2410: +\ttable.SetOutputMirror(w)\n2411: +\ttable.SetStyle(tableWriter.StyleRounded)\n2412: +\ttable.Style().Format.Header = text.FormatTitle\n2413: +\ttable.Style().Format.HeaderAlign = text.AlignCenter\n2414: +\ttable.AppendHeader(tableWriter.Row{\"Node\", \"Interface\", \"Alias\", \"Peer Node\", \"Peer Interface\"})\n2415: +\ttable.SetColumnConfigs([]tableWriter.ColumnConfig{{Number: 1, AutoMerge: true}})\n2416: +\tfor _, intf := range interfaces {\n2417: +\t\talias := intf.Alias\n2418: +\t\tif alias == \"\" {\n2419: +\t\t\talias = clabconstants.NotApplicable\n2420: +\t\t}\n2421: +\t\ttable.AppendRow(tableWriter.Row{\n2422: +\t\t\tintf.Node, intf.Interface, alias, intf.PeerNode, intf.PeerInterface,\n2423: +\t\t})\n2424: +\t}\n2425: +\ttable.Render()\n2426: +\n2427: +\treturn nil\n2428: +}\n2429: diff --git a/cmd/capture_test.go b/cmd/capture_test.go\n2430: new file mode 100644\n2431: index 0000000..da12d66\n2432: --- /dev/null\n2433: +++ b/cmd/capture_test.go\n2434: @@ -0,0 +1,109 @@\n2435: +package cmd\n2436: +\n2437: +import (\n2438: +\t\"bytes\"\n2439: +\t\"encoding/json\"\n2440: +\t\"slices\"\n2441: +\t\"strings\"\n2442: +\t\"testing\"\n2443: +\n2444: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2445: +)\n2446: +\n2447: +func TestParseCaptureTargets(t *testing.T) {\n2448: +\tt.Parallel()\n2449: +\n2450: +\ttargets, err := parseCaptureTargets([]string{\n2451: +\t\t\"srl1:e1-1,ethernet-1/2\", \" sros : 1/1/3 \", \"r1:eth1\",\n2452: +\t})\n2453: +\tif err != nil {\n2454: +\t\tt.Fatal(err)\n2455: +\t}\n2456: +\twant := []clablabruntime.CaptureTarget{\n2457: +\t\t{Node: \"srl1\", Interface: \"e1-1\"},\n2458: +\t\t{Node: \"srl1\", Interface: \"ethernet-1/2\"},\n2459: +\t\t{Node: \"sros\", Interface: \"1/1/3\"},\n2460: +\t\t{Node: \"r1\", Interface: \"eth1\"},\n2461: +\t}\n2462: +\tif !slices.Equal(targets, want) {\n2463: +\t\tt.Fatalf(\"targets = %+v, want %+v\", targets, want)\n2464: +\t}\n2465: +\n2466: +\tfor _, bad := range [][]string{nil, {\"srl1\"}, {\":e1-1\"}, {\"srl1:\"}, {\"srl1:e1-1,,e1-2\"}} {\n2467: +\t\tif _, err := parseCaptureTargets(bad); err == nil {\n2468: +\t\t\tt.Errorf(\"parseCaptureTargets(%q) succeeded\", bad)\n2469: +\t\t}\n2470: +\t}\n2471: +}\n2472: +\n2473: +func TestCaptureCommandFlags(t *testing.T) {\n2474: +\to := GetOptions()\n2475: +\tcmd, err := captureCmd(o)\n2476: +\tif err != nil {\n2477: +\t\tt.Fatal(err)\n2478: +\t}\n2479: +\tif err := cmd.ParseFlags([]string{\n2480: +\t\t\"--target\", \"srl1:e1-1\", \"--target\", \"srl2:e1-1,e1-2\", \"--duration\", \"90m\",\n2481: +\t\t\"--packet-limit\", \"100\", \"--snap-length\", \"128\", \"-w\", \"out.pcapng\",\n2482: +\t}); err != nil {\n2483: +\t\tt.Fatal(err)\n2484: +\t}\n2485: +\tif !slices.Equal(o.Capture.Targets, []string{\"srl1:e1-1\", \"srl2:e1-1,e1-2\"}) ||\n2486: +\t\to.Capture.Duration.Minutes() != 90 || o.Capture.PacketLimit != 100 ||\n2487: +\t\to.Capture.SnapLength != 128 || o.Capture.Write != \"out.pcapng\" {\n2488: +\t\tt.Fatalf(\"capture options = %+v\", o.Capture)\n2489: +\t}\n2490: +\tif def := cmd.Flag(\"write\").DefValue; def != \"-\" {\n2491: +\t\tt.Fatalf(\"--write default = %q, want stdout\", def)\n2492: +\t}\n2493: +}\n2494: +\n2495: +func TestPrintCaptureInterfaces(t *testing.T) {\n2496: +\tt.Parallel()\n2497: +\n2498: +\tinterfaces := []clablabruntime.CaptureInterface{\n2499: +\t\t{\n2500: +\t\t\tNode:          \"srl1\",\n2501: +\t\t\tInterface:     \"e1-1\",\n2502: +\t\t\tAlias:         \"ethernet-1/1\",\n2503: +\t\t\tPeerNode:      \"srl2\",\n2504: +\t\t\tPeerInterface: \"ethernet-1/1\",\n2505: +\t\t},\n2506: +\t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"srl1-e1-2\"},\n2507: +\t}\n2508: +\n2509: +\tvar out bytes.Buffer\n2510: +\tif err := printCaptureInterfaces(&out, interfaces, \"json\"); err != nil {\n2511: +\t\tt.Fatal(err)\n2512: +\t}\n2513: +\tvar decoded []map[string]any\n2514: +\tif err := json.Unmarshal(out.Bytes(), &decoded); err != nil {\n2515: +\t\tt.Fatal(err)\n2516: +\t}\n2517: +\tif decoded[0][\"peer_node\"] != \"srl2\" || decoded[0][\"alias\"] != \"ethernet-1/1\" {\n2518: +\t\tt.Fatalf(\"json = %s\", out.String())\n2519: +\t}\n2520: +\tif _, hasAlias := decoded[1][\"alias\"]; hasAlias {\n2521: +\t\tt.Fatalf(\"an empty alias is printed: %s\", out.String())\n2522: +\t}\n2523: +\n2524: +\tout.Reset()\n2525: +\tif err := printCaptureInterfaces(\n2526: +\t\t&out,\n2527: +\t\tnil,\n2528: +\t\t\"json\",\n2529: +\t); err != nil ||\n2530: +\t\tstrings.TrimSpace(out.String()) != \"[]\" {\n2531: +\t\tt.Fatalf(\"empty json = %q, %v\", out.String(), err)\n2532: +\t}\n2533: +\n2534: +\tout.Reset()\n2535: +\tif err := printCaptureInterfaces(&out, interfaces, \"table\"); err != nil {\n2536: +\t\tt.Fatal(err)\n2537: +\t}\n2538: +\tfor _, want := range []string{\"Peer Interface\", \"ethernet-1/1\", \"srl1-e1-2\", \"N/A\"} {\n2539: +\t\tif !strings.Contains(out.String(), want) {\n2540: +\t\t\tt.Fatalf(\"table does not contain %q:\\n%s\", want, out.String())\n2541: +\t\t}\n2542: +\t}\n2543: +}\n2544: diff --git a/cmd/context.go b/cmd/context.go\n2545: index 223cb1d..21d5bea 100644\n2546: --- a/cmd/context.go\n2547: +++ b/cmd/context.go\n2548: @@ -51,10 +51,20 @@ func SignalHandledContext() (context.Context, context.CancelFunc) {\n2549:  \n2550:  \t\tcancel()\n2551:  \n2552:  \t\toptions := GetOptions()\n2553:  \n2554: +\t\tif options.Global.FinishOnCancel.Load() {\n2555: +\t\t\tlog.Info(\"Stopping, press Ctrl+C again to abort\")\n2556: +\n2557: +\t\t\tsig = <-sigs\n2558: +\n2559: +\t\t\tlog.Errorf(\"received signal %q while stopping, exiting\", sig)\n2560: +\n2561: +\t\t\tos.Exit(1)\n2562: +\t\t}\n2563: +\n2564:  \t\tif !options.Global.CleanOnCancel.Load() {\n2565:  \t\t\tlog.Debug(\"clean on cancel is not true, exiting\")\n2566:  \n2567:  \t\t\tos.Exit(1)\n2568:  \t\t}\n2569: diff --git a/cmd/inspect.go b/cmd/inspect.go\n2570: index 1b6f41d..55fb61f 100644\n2571: --- a/cmd/inspect.go\n2572: +++ b/cmd/inspect.go\n2573: @@ -70,10 +70,14 @@ func inspectCmd(o *Options) (*cobra.Command, error) {\n2574:  \t\tShort: \"inspect interfaces of one or multiple nodes in a lab\",\n2575:  \t\tLong: \"show interfaces and their attributes in a specific deployed lab\\n\" +\n2576:  \t\t\t\"reference: https://containerlab.dev/cmd/inspect/interfaces/\",\n2577:  \t\tAliases: []string{\"int\", \"intf\"},\n2578:  \t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n2579: +\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n2580: +\t\t\t\treturn nil\n2581: +\t\t\t}\n2582: +\n2583:  \t\t\treturn clabutils.CheckAndGetRootPrivs()\n2584:  \t\t},\n2585:  \t\tRunE: func(cobraCmd *cobra.Command, _ []string) error {\n2586:  \t\t\treturn inspectInterfacesFn(cobraCmd, o)\n2587:  \t\t},\n2588: diff --git a/cmd/inspect_interfaces.go b/cmd/inspect_interfaces.go\n2589: index 0f64f03..91035c2 100644\n2590: --- a/cmd/inspect_interfaces.go\n2591: +++ b/cmd/inspect_interfaces.go\n2592: @@ -33,10 +33,25 @@ func inspectInterfacesFn(cobraCmd *cobra.Command, o *Options) error {\n2593:  \tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n2594:  \tif err != nil {\n2595:  \t\treturn fmt.Errorf(\"could not parse the topology file: %v\", err)\n2596:  \t}\n2597:  \n2598: +\tif c.LabRuntime != nil {\n2599: +\t\t// lab runtimes list the link interfaces packet capture accepts, with their state\n2600: +\t\tcontainerInterfaces, err := c.LabRuntimeInterfaces(cobraCmd.Context(),\n2601: +\t\t\to.Inspect.InterfacesNode)\n2602: +\t\tif err != nil {\n2603: +\t\t\treturn fmt.Errorf(\"failed to list node interfaces: %w\", err)\n2604: +\t\t}\n2605: +\t\tif len(containerInterfaces) == 0 {\n2606: +\t\t\tlog.Info(\"no running nodes found\")\n2607: +\t\t\treturn nil\n2608: +\t\t}\n2609: +\n2610: +\t\treturn printContainerInterfaces(containerInterfaces, o.Inspect.InterfacesFormat)\n2611: +\t}\n2612: +\n2613:  \tvar labNameFilterLabel string\n2614:  \n2615:  \tswitch {\n2616:  \tcase o.Global.TopologyName != \"\":\n2617:  \t\tlabNameFilterLabel = o.Global.TopologyName\n2618: diff --git a/cmd/options.go b/cmd/options.go\n2619: index 8717d3b..6037551 100644\n2620: --- a/cmd/options.go\n2621: +++ b/cmd/options.go\n2622: @@ -53,10 +53,14 @@ func GetOptions() *Options {\n2623:  \t\t\t\tInterfacesFormat: \"table\",\n2624:  \t\t\t},\n2625:  \t\t\tLogs: &LogsOptions{\n2626:  \t\t\t\tTail: -1,\n2627:  \t\t\t},\n2628: +\t\t\tCapture: &CaptureOptions{\n2629: +\t\t\t\tWrite:  \"-\",\n2630: +\t\t\t\tFormat: \"table\",\n2631: +\t\t\t},\n2632:  \t\t\tGraph: &GraphOptions{\n2633:  \t\t\t\tServer:           \"0.0.0.0:50080\",\n2634:  \t\t\t\tMermaidDirection: \"TD\",\n2635:  \t\t\t\tDrawIOVersion:    \"latest\",\n2636:  \t\t\t},\n2637: @@ -142,10 +146,11 @@ type Options struct {\n2638:  \tExec           *ExecOptions\n2639:  \tInspect        *InspectOptions\n2640:  \tGraph          *GraphOptions\n2641:  \tEvents         *EventsOptions\n2642:  \tLogs           *LogsOptions\n2643: +\tCapture        *CaptureOptions\n2644:  \tToolsAPI       *ToolsApiOptions\n2645:  \tToolsCert      *ToolsCertOptions\n2646:  \tToolsTxOffload *ToolsDisableTxOffloadOptions\n2647:  \tToolsGoTTY     *ToolsGoTTYOptions\n2648:  \tToolsNetem     *ToolsNetemOptions\n2649: @@ -257,10 +262,15 @@ type GlobalOptions struct {\n2650:  \t// special flag that should only be set by deploy, informs the context handler to destroy\n2651:  \t// (or not) when root context is canceled. The signal handler goroutine reads it while\n2652:  \t// deploy is running, so it is atomic.\n2653:  \tCleanOnCancel atomic.Bool\n2654:  \n2655: +\t// FinishOnCancel informs the context handler that the running command ends cleanly on its\n2656: +\t// own once the root context is canceled (capture finishes its output), so the handler\n2657: +\t// waits for it instead of exiting.\n2658: +\tFinishOnCancel atomic.Bool\n2659: +\n2660:  \t// special flag that is only set on deploy,\n2661:  \t// if true, the topology file backup is created at /tmp/.clab/bak\n2662:  \tBackupTopologyFile bool\n2663:  }\n2664:  \n2665: diff --git a/cmd/root.go b/cmd/root.go\n2666: index 0baf203..a9b1c8b 100644\n2667: --- a/cmd/root.go\n2668: +++ b/cmd/root.go\n2669: @@ -35,10 +35,11 @@ func subcommandRegisterFuncs() []func(*Options) (*cobra.Command, error) {\n2670:  \t\tgenerateCmd,\n2671:  \t\tgraphCmd,\n2672:  \t\teventsCmd,\n2673:  \t\tinspectCmd,\n2674:  \t\tlogsCmd,\n2675: +\t\tcaptureCmd,\n2676:  \t\tredeployCmd,\n2677:  \t\tsaveCmd,\n2678:  \t\ttoolsCmd,\n2679:  \t\tvalidateCmd,\n2680:  \t}\n2681: @@ -263,15 +264,10 @@ func checkLabRuntimeCommandSupport(cobraCmd *cobra.Command, runtimeName string)\n2682:  \t\t\t\"the %q command needs running containers with lab runtime %q unless it renders \"+\n2683:  \t\t\t\t\"from the topology file alone; use --offline, --dot, --mermaid or --drawio\",\n2684:  \t\t\t\"graph\", runtimeName)\n2685:  \t}\n2686:  \n2687: -\tif getCommandPath(cobraCmd) == \"inspect.interfaces\" {\n2688: -\t\treturn fmt.Errorf(\"the %q command is not supported with lab runtime %q\",\n2689: -\t\t\t\"inspect interfaces\", runtimeName)\n2690: -\t}\n2691: -\n2692:  \tvar unsupported []string\n2693:  \tfor _, flagName := range labRuntimeUnsupportedFlags[getCommandPath(cobraCmd)] {\n2694:  \t\tif labRuntimeFlagWasSet(cobraCmd, flagName) {\n2695:  \t\t\tunsupported = append(unsupported, \"--\"+flagName)\n2696:  \t\t}\n2697: @@ -339,10 +335,11 @@ func getTopoFilePath(cobraCmd *cobra.Command, o *Options) error { // skipcq: GO-\n2698:  \t\tcobraCmd.Name() != \"inspect\" &&\n2699:  \t\tcobraCmd.Name() != \"save\" &&\n2700:  \t\tcobraCmd.Name() != \"graph\" &&\n2701:  \t\tcobraCmd.Name() != \"validate\" &&\n2702:  \t\tcobraCmd.Name() != \"logs\" &&\n2703: +\t\tcobraCmd.Name() != \"capture\" &&\n2704:  \t\tcobraCmd.Name() != \"interfaces\" {\n2705:  \t\treturn nil\n2706:  \t}\n2707:  \n2708:  \t// start/stop/restart topology lookup applies only to top-level lifecycle commands.\n2709: diff --git a/cmd/root_test.go b/cmd/root_test.go\n2710: index 418a947..af02e34 100644\n2711: --- a/cmd/root_test.go\n2712: +++ b/cmd/root_test.go\n2713: @@ -289,20 +289,23 @@ func TestCheckLabRuntimeFlagAndNestedCommandSupport(t *testing.T) {\n2714:  \t\t\t\tt.Fatalf(\"checkLabRuntimeCommandSupport() error = %v, wantErr %v\", err, tt.wantErr)\n2715:  \t\t\t}\n2716:  \t\t})\n2717:  \t}\n2718:  \n2719: -\tt.Run(\"inspect interfaces rejected\", func(t *testing.T) {\n2720: +\tt.Run(\"inspect interfaces and capture accepted\", func(t *testing.T) {\n2721:  \t\troot := &cobra.Command{Use: \"containerlab\"}\n2722:  \t\tinspect := &cobra.Command{Use: \"inspect\"}\n2723:  \t\tinterfaces := &cobra.Command{Use: \"interfaces\"}\n2724: -\t\troot.AddCommand(inspect)\n2725: +\t\tcapture := &cobra.Command{Use: \"capture\"}\n2726: +\t\troot.AddCommand(inspect, capture)\n2727:  \t\tinspect.AddCommand(interfaces)\n2728:  \n2729: -\t\tif err := checkLabRuntimeCommandSupport(\n2730: -\t\t\tinterfaces,\n2731: -\t\t\tclablabruntime.ClabernetesRuntimeName,\n2732: -\t\t); err == nil {\n2733: -\t\t\tt.Fatal(\"inspect interfaces was accepted for clabernetes\")\n2734: +\t\tfor _, cmd := range []*cobra.Command{interfaces, capture} {\n2735: +\t\t\tif err := checkLabRuntimeCommandSupport(\n2736: +\t\t\t\tcmd,\n2737: +\t\t\t\tclablabruntime.ClabernetesRuntimeName,\n2738: +\t\t\t); err != nil {\n2739: +\t\t\t\tt.Fatalf(\"%s rejected for clabernetes: %v\", cmd.Name(), err)\n2740: +\t\t\t}\n2741:  \t\t}\n2742:  \t})\n2743:  }\n2744: diff --git a/core/capture.go b/core/capture.go\n2745: new file mode 100644\n2746: index 0000000..2e12fc2\n2747: --- /dev/null\n2748: +++ b/core/capture.go\n2749: @@ -0,0 +1,93 @@\n2750: +package core\n2751: +\n2752: +import (\n2753: +\t\"context\"\n2754: +\t\"io\"\n2755: +\n2756: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2757: +\tclabtypes \"github.com/srl-labs/containerlab/types\"\n2758: +)\n2759: +\n2760: +// CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for\n2761: +// every running node, with the peer at the other end of each link. With Docker and Podman, the\n2762: +// interfaces come from the topology's links; lab runtimes list them through their packet\n2763: +// capturer.\n2764: +func (c *CLab) CaptureInterfaces(\n2765: +\tctx context.Context,\n\n(Showing lines 2166-2765 of 7018. Use offset=2766 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "@@ -0,0 +1,262 @@\n+package cmd\n+\n+import (\n+\t\"encoding/json\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"os\"\n+\t\"strings\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\ttableWriter \"github.com/jedib0t/go-pretty/v6/table\"\n+\t\"github.com/jedib0t/go-pretty/v6/text\"\n+\t\"github.com/spf13/cobra\"\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+\tclabutils \"github.com/srl-labs/containerlab/utils\"\n+)",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "@@ -0,0 +1,262 @@\n+package cmd\n+\n+import (\n+\t\"encoding/json\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"os\"\n+\t\"strings\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\ttableWriter \"github.com/jedib0t/go-pretty/v6/table\"\n+\t\"github.com/jedib0t/go-pretty/v6/text\"\n+\t\"github.com/spf13/cobra\"\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+\tclabutils \"github.com/srl-labs/containerlab/utils\"\n+)\n+\n+// CaptureOptions are the flags of the capture command.\n+type CaptureOptions struct {\n+\tTargets     []string\n+\tDuration    time.Duration\n+\tPacketLimit int\n+\tSnapLength  int\n+\tWrite       string\n+\tList        bool\n+\tFormat      string\n+}\n+\n+func captureCmd(o *Options) (*cobra.Command, error) {\n+\tc := &cobra.Command{\n+\t\tUse:   \"capture\",\n+\t\tShort: \"capture packets on lab link interfaces\",\n+\t\tLong: \"capture packets on lab link interfaces of one or more nodes into one pcapng \" +\n+\t\t\t\"stream\\nreference: https://containerlab.dev/cmd/capture/\",\n+\t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n+\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n+\t\t\t\treturn nil\n+\t\t\t}\n+\n+\t\t\t// Docker and Podman captures open packet sockets in the nodes' namespaces\n+\t\t\treturn clabutils.CheckAndGetRootPrivs()\n+\t\t},\n+\t\tSilenceUsage: true,\n+\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n+\t\t\treturn captureFn(cmd, o)\n+\t\t},\n+\t}\n+\n+\tc.Flags().StringArrayVar(\n+\t\t&o.Capture.Targets,\n+\t\t\"target\",\n+\t\to.Capture.Targets,\n+\t\t\"node and interfaces to capture, as <node>:<interface>[,<interface>...]; repeatable\",\n+\t)\n+\tc.Flags().DurationVar(\n+\t\t&o.Capture.Duration,\n+\t\t\"duration\",\n+\t\to.Capture.Duration,\n+\t\t\"stop after this duration; 0 captures until interrupted\",\n+\t)\n+\tc.Flags().IntVar(\n+\t\t&o.Capture.PacketLimit,\n+\t\t\"packet-limit\",\n+\t\to.Capture.PacketLimit,\n+\t\t\"stop after this many packets across all targets; 0 means no limit\",\n+\t)\n+\tc.Flags().IntVar(\n+\t\t&o.Capture.SnapLength,\n+\t\t\"snap-length\",\n+\t\to.Capture.SnapLength,\n+\t\t\"bytes kept of each packet (64 to 1048576); 0 uses the runtime default\",\n+\t)\n+\tc.Flags().StringVarP(\n+\t\t&o.Capture.Write,\n+\t\t\"write\",\n+\t\t\"w\",\n+\t\to.Capture.Write,\n+\t\t\"pcapng output file; - writes to stdout\",\n+\t)\n+\tc.Flags().BoolVar(\n+\t\t&o.Capture.List,\n+\t\t\"list\",\n+\t\to.Capture.List,\n+\t\t\"list the capturable interfaces instead of capturing\",\n+\t)\n+\tc.Flags().StringVarP(\n+\t\t&o.Capture.Format,\n+\t\t\"format\",\n+\t\t\"f\",\n+\t\to.Capture.Format,\n+\t\t\"output format of --list: table or json\",\n+\t)\n+\n+\tc.Example = `# Capture e1-1 of srl1 and e1-1 of srl2 for 30 seconds into one file\n+containerlab capture -t srl.clab.yml --target srl1:e1-1 --target srl2:e1-1 \\\n+  --duration 30s -w srl.pcapng\n+\n+# Capture two interfaces of one node and watch them live in Wireshark\n+containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n+\n+# List the interfaces capture accepts\n+containerlab capture --name srl --list -f json\n+\n+# Capture a lab running on the c9s runtime\n+containerlab -r c9s capture --name srl --target srl1:e1-1 -w srl.pcapng`\n+\n+\treturn c, nil\n+}\n+\n+func captureFn(cmd *cobra.Command, o *Options) error {\n+\tif o.Global.TopologyName == \"\" && o.Global.TopologyFile == \"\" {\n+\t\treturn fmt.Errorf(\"provide either a lab name (--name) or a topology file path (--topo)\")\n+\t}\n+\n+\tif o.Capture.List {\n+\t\treturn captureListFn(cmd, o)\n+\t}\n+\n+\ttargets, err := parseCaptureTargets(o.Capture.Targets)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\t// An interrupt ends the capture; the command still finishes the file and exits cleanly.\n+\t// Armed before the file is created, so an interrupt never leaves it empty.\n+\to.Global.FinishOnCancel.Store(true)\n+\tdefer o.Global.FinishOnCancel.Store(false)\n+\n+\toutput := cmd.OutOrStdout()\n+\tif o.Capture.Write != \"\" && o.Capture.Write != \"-\" {\n+\t\tfile, err := os.Create(o.Capture.Write)\n+\t\tif err != nil {\n+\t\t\treturn fmt.Errorf(\"failed to create the capture file: %w\", err)\n+\t\t}\n+\t\tdefer file.Close()\n+\t\toutput = file\n+\n+\t\t// the file belongs to the user who ran the command, also through sudo or setuid\n+\t\tif err := clabutils.SetUIDAndGID(o.Capture.Write); err != nil {\n+\t\t\tlog.Debug(\"Cannot hand the capture file to the user\", \"file\", o.Capture.Write,\n+\t\t\t\t\"error\", err)\n+\t\t}\n+\t}\n+\n+\terr = c.Capture(cmd.Context(), clablabruntime.CaptureRequest{\n+\t\tTargets:     targets,\n+\t\tDuration:    o.Capture.Duration,\n+\t\tPacketLimit: o.Capture.PacketLimit,\n+\t\tSnapLength:  o.Capture.SnapLength,\n+\t}, output)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tif file, ok := output.(*os.File); ok && output != cmd.OutOrStdout() {\n+\t\tif err := file.Sync(); err != nil {\n+\t\t\treturn fmt.Errorf(\"failed to write the capture file: %w\", err)\n+\t\t}\n+\t}\n+\n+\treturn nil\n+}\n+\n+// parseCaptureTargets parses --target values: <node>:<interface>[,<interface>...]. The node name\n+// ends at the first colon, so interface names may contain colons or slashes.\n+func parseCaptureTargets(values []string) ([]clablabruntime.CaptureTarget, error) {\n+\tif len(values) == 0 {\n+\t\treturn nil, fmt.Errorf(\"provide at least one --target <node>:<interface>[,<interface>...]\")\n+\t}\n+\n+\ttargets := make([]clablabruntime.CaptureTarget, 0, len(values))\n+\tfor _, value := range values {\n+\t\tnode, interfaces, ok := strings.Cut(strings.TrimSpace(value), \":\")\n+\t\tnode = strings.TrimSpace(node)\n+\t\tif !ok || node == \"\" || strings.TrimSpace(interfaces) == \"\" {\n+\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: use <node>:<interface>[,<interface>...]\",\n+\t\t\t\tvalue)\n+\t\t}\n+\n+\t\tfor _, name := range strings.Split(interfaces, \",\") {\n+\t\t\tname = strings.TrimSpace(name)\n+\t\t\tif name == \"\" {\n+\t\t\t\treturn nil, fmt.Errorf(\"invalid --target %q: empty interface name\", value)\n+\t\t\t}\n+\t\t\ttargets = append(targets, clablabruntime.CaptureTarget{Node: node, Interface: name})\n+\t\t}\n+\t}\n+\n+\treturn targets, nil\n+}\n+\n+func captureListFn(cmd *cobra.Command, o *Options) error {\n+\tformat := o.Capture.Format\n+\tif format == \"\" {\n+\t\tformat = clabconstants.FormatTable\n+\t}\n+\tif format != clabconstants.FormatTable && format != clabconstants.FormatJSON {\n+\t\treturn fmt.Errorf(\"output format %q is not supported, use 'table' or 'json'\", format)\n+\t}\n+\tif len(o.Capture.Targets) != 0 {\n+\t\treturn fmt.Errorf(\"--list lists every running node's interfaces; it takes no --target\")\n+\t}\n+\n+\tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tinterfaces, err := c.CaptureInterfaces(cmd.Context())\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\treturn printCaptureInterfaces(cmd.OutOrStdout(), interfaces, format)\n+}\n+\n+func printCaptureInterfaces(\n+\tw io.Writer,\n+\tinterfaces []clablabruntime.CaptureInterface,\n+\tformat string,\n+) error {\n+\tif format == clabconstants.FormatJSON {\n+\t\tif interfaces == nil {\n+\t\t\tinterfaces = []clablabruntime.CaptureInterface{}\n+\t\t}\n+\t\tdata, err := json.MarshalIndent(interfaces, \"\", \"  \")\n+\t\tif err != nil {\n+\t\t\treturn err\n+\t\t}\n+\t\t_, err = fmt.Fprintln(w, string(data))\n+\n+\t\treturn err\n+\t}\n+\n+\ttable := tableWriter.NewWriter()\n+\ttable.SetOutputMirror(w)\n+\ttable.SetStyle(tableWriter.StyleRounded)\n+\ttable.Style().Format.Header = text.FormatTitle\n+\ttable.Style().Format.HeaderAlign = text.AlignCenter\n+\ttable.AppendHeader(tableWriter.Row{\"Node\", \"Interface\", \"Alias\", \"Peer Node\", \"Peer Interface\"})\n+\ttable.SetColumnConfigs([]tableWriter.ColumnConfig{{Number: 1, AutoMerge: true}})\n+\tfor _, intf := range interfaces {\n+\t\talias := intf.Alias\n+\t\tif alias == \"\" {\n+\t\t\talias = clabconstants.NotApplicable\n+\t\t}\n+\t\ttable.AppendRow(tableWriter.Row{\n+\t\t\tintf.Node, intf.Interface, alias, intf.PeerNode, intf.PeerInterface,\n+\t\t})\n+\t}\n+\ttable.Render()\n+\n+\treturn nil\n+}\ndiff --git a/cmd/capture_test.go b/cmd/capture_test.go\nnew file mode 100644\nindex 0000000..da12d66\n--- /dev/null\n+++ b/cmd/capture_test.go\n@@ -0,0 +1,109 @@\n+package cmd\n+\n+import (\n+\t\"bytes\"\n+\t\"encoding/json\"\n+\t\"slices\"\n+\t\"strings\"\n+\t\"testing\"\n+\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+)\n+\n+func TestParseCaptureTargets(t *testing.T) {\n+\tt.Parallel()\n+\n+\ttargets, err := parseCaptureTargets([]string{\n+\t\t\"srl1:e1-1,ethernet-1/2\", \" sros : 1/1/3 \", \"r1:eth1\",\n+\t})\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\twant := []clablabruntime.CaptureTarget{\n+\t\t{Node: \"srl1\", Interface: \"e1-1\"},\n+\t\t{Node: \"srl1\", Interface: \"ethernet-1/2\"},\n+\t\t{Node: \"sros\", Interface: \"1/1/3\"},\n+\t\t{Node: \"r1\", Interface: \"eth1\"},\n+\t}\n+\tif !slices.Equal(targets, want) {\n+\t\tt.Fatalf(\"targets = %+v, want %+v\", targets, want)\n+\t}\n+\n+\tfor _, bad := range [][]string{nil, {\"srl1\"}, {\":e1-1\"}, {\"srl1:\"}, {\"srl1:e1-1,,e1-2\"}} {\n+\t\tif _, err := parseCaptureTargets(bad); err == nil {\n+\t\t\tt.Errorf(\"parseCaptureTargets(%q) succeeded\", bad)\n+\t\t}\n+\t}\n+}\n+\n+func TestCaptureCommandFlags(t *testing.T) {\n+\to := GetOptions()\n+\tcmd, err := captureCmd(o)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif err := cmd.ParseFlags([]string{\n+\t\t\"--target\", \"srl1:e1-1\", \"--target\", \"srl2:e1-1,e1-2\", \"--duration\", \"90m\",\n+\t\t\"--packet-limit\", \"100\", \"--snap-length\", \"128\", \"-w\", \"out.pcapng\",\n+\t}); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif !slices.Equal(o.Capture.Targets, []string{\"srl1:e1-1\", \"srl2:e1-1,e1-2\"}) ||\n+\t\to.Capture.Duration.Minutes() != 90 || o.Capture.PacketLimit != 100 ||\n+\t\to.Capture.SnapLength != 128 || o.Capture.Write != \"out.pcapng\" {\n+\t\tt.Fatalf(\"capture options = %+v\", o.Capture)\n+\t}\n+\tif def := cmd.Flag(\"write\").DefValue; def != \"-\" {\n+\t\tt.Fatalf(\"--write default = %q, want stdout\", def)\n+\t}\n+}\n+\n+func TestPrintCaptureInterfaces(t *testing.T) {\n+\tt.Parallel()\n+\n+\tinterfaces := []clablabruntime.CaptureInterface{\n+\t\t{\n+\t\t\tNode:          \"srl1\",\n+\t\t\tInterface:     \"e1-1\",\n+\t\t\tAlias:         \"ethernet-1/1\",\n+\t\t\tPeerNode:      \"srl2\",\n+\t\t\tPeerInterface: \"ethernet-1/1\",\n+\t\t},\n+\t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"srl1-e1-2\"},\n+\t}\n+\n+\tvar out bytes.Buffer\n+\tif err := printCaptureInterfaces(&out, interfaces, \"json\"); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tvar decoded []map[string]any\n+\tif err := json.Unmarshal(out.Bytes(), &decoded); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif decoded[0][\"peer_node\"] != \"srl2\" || decoded[0][\"alias\"] != \"ethernet-1/1\" {\n+\t\tt.Fatalf(\"json = %s\", out.String())\n+\t}\n+\tif _, hasAlias := decoded[1][\"alias\"]; hasAlias {\n+\t\tt.Fatalf(\"an empty alias is printed: %s\", out.String())\n+\t}\n+\n+\tout.Reset()\n+\tif err := printCaptureInterfaces(\n+\t\t&out,\n+\t\tnil,\n+\t\t\"json\",\n+\t); err != nil ||\n+\t\tstrings.TrimSpace(out.String()) != \"[]\" {\n+\t\tt.Fatalf(\"empty json = %q, %v\", out.String(), err)\n+\t}\n+\n+\tout.Reset()\n+\tif err := printCaptureInterfaces(&out, interfaces, \"table\"); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tfor _, want := range []string{\"Peer Interface\", \"ethernet-1/1\", \"srl1-e1-2\", \"N/A\"} {\n+\t\tif !strings.Contains(out.String(), want) {\n+\t\t\tt.Fatalf(\"table does not contain %q:\\n%s\", want, out.String())\n+\t\t}\n+\t}\n+}\ndiff --git a/cmd/context.go b/cmd/context.go\nindex 223cb1d..21d5bea 100644\n--- a/cmd/context.go\n+++ b/cmd/context.go\n@@ -51,10 +51,20 @@ func SignalHandledContext() (context.Context, context.CancelFunc) {\n \n \t\tcancel()\n \n \t\toptions := GetOptions()\n \n+\t\tif options.Global.FinishOnCancel.Load() {\n+\t\t\tlog.Info(\"Stopping, press Ctrl+C again to abort\")\n+\n+\t\t\tsig = <-sigs\n+\n+\t\t\tlog.Errorf(\"received signal %q while stopping, exiting\", sig)\n+\n+\t\t\tos.Exit(1)\n+\t\t}\n+\n \t\tif !options.Global.CleanOnCancel.Load() {\n \t\t\tlog.Debug(\"clean on cancel is not true, exiting\")\n \n \t\t\tos.Exit(1)\n \t\t}\ndiff --git a/cmd/inspect.go b/cmd/inspect.go\nindex 1b6f41d..55fb61f 100644\n--- a/cmd/inspect.go\n+++ b/cmd/inspect.go\n@@ -70,10 +70,14 @@ func inspectCmd(o *Options) (*cobra.Command, error) {\n \t\tShort: \"inspect interfaces of one or multiple nodes in a lab\",\n \t\tLong: \"show interfaces and their attributes in a specific deployed lab\\n\" +\n \t\t\t\"reference: https://containerlab.dev/cmd/inspect/interfaces/\",\n \t\tAliases: []string{\"int\", \"intf\"},\n \t\tPreRunE: func(_ *cobra.Command, _ []string) error {\n+\t\t\tif commandSkipsRoot(o.Global.Runtime) {\n+\t\t\t\treturn nil\n+\t\t\t}\n+\n \t\t\treturn clabutils.CheckAndGetRootPrivs()\n \t\t},\n \t\tRunE: func(cobraCmd *cobra.Command, _ []string) error {\n \t\t\treturn inspectInterfacesFn(cobraCmd, o)\n \t\t},\ndiff --git a/cmd/inspect_interfaces.go b/cmd/inspect_interfaces.go\nindex 0f64f03..91035c2 100644\n--- a/cmd/inspect_interfaces.go\n+++ b/cmd/inspect_interfaces.go\n@@ -33,10 +33,25 @@ func inspectInterfacesFn(cobraCmd *cobra.Command, o *Options) error {\n \tc, err := clabcore.NewContainerLab(o.ToClabOptions()...)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"could not parse the topology file: %v\", err)\n \t}\n \n+\tif c.LabRuntime != nil {\n+\t\t// lab runtimes list the link interfaces packet capture accepts, with their state\n+\t\tcontainerInterfaces, err := c.LabRuntimeInterfaces(cobraCmd.Context(),\n+\t\t\to.Inspect.InterfacesNode)\n+\t\tif err != nil {\n+\t\t\treturn fmt.Errorf(\"failed to list node interfaces: %w\", err)\n+\t\t}\n+\t\tif len(containerInterfaces) == 0 {\n+\t\t\tlog.Info(\"no running nodes found\")\n+\t\t\treturn nil\n+\t\t}\n+\n+\t\treturn printContainerInterfaces(containerInterfaces, o.Inspect.InterfacesFormat)\n+\t}\n+\n \tvar labNameFilterLabel string\n \n \tswitch {\n \tcase o.Global.TopologyName != \"\":\n \t\tlabNameFilterLabel = o.Global.TopologyName\ndiff --git a/cmd/options.go b/cmd/options.go\nindex 8717d3b..6037551 100644\n--- a/cmd/options.go\n+++ b/cmd/options.go\n@@ -53,10 +53,14 @@ func GetOptions() *Options {\n \t\t\t\tInterfacesFormat: \"table\",\n \t\t\t},\n \t\t\tLogs: &LogsOptions{\n \t\t\t\tTail: -1,\n \t\t\t},\n+\t\t\tCapture: &CaptureOptions{\n+\t\t\t\tWrite:  \"-\",\n+\t\t\t\tFormat: \"table\",\n+\t\t\t},\n \t\t\tGraph: &GraphOptions{\n \t\t\t\tServer:           \"0.0.0.0:50080\",\n \t\t\t\tMermaidDirection: \"TD\",\n \t\t\t\tDrawIOVersion:    \"latest\",\n \t\t\t},\n@@ -142,10 +146,11 @@ type Options struct {\n \tExec           *ExecOptions\n \tInspect        *InspectOptions\n \tGraph          *GraphOptions\n \tEvents         *EventsOptions\n \tLogs           *LogsOptions\n+\tCapture        *CaptureOptions\n \tToolsAPI       *ToolsApiOptions\n \tToolsCert      *ToolsCertOptions\n \tToolsTxOffload *ToolsDisableTxOffloadOptions\n \tToolsGoTTY     *ToolsGoTTYOptions\n \tToolsNetem     *ToolsNetemOptions\n@@ -257,10 +262,15 @@ type GlobalOptions struct {\n \t// special flag that should only be set by deploy, informs the context handler to destroy\n \t// (or not) when root context is canceled. The signal handler goroutine reads it while\n \t// deploy is running, so it is atomic.\n \tCleanOnCancel atomic.Bool\n \n+\t// FinishOnCancel informs the context handler that the running command ends cleanly on its\n+\t// own once the root context is canceled (capture finishes its output), so the handler\n+\t// waits for it instead of exiting.\n+\tFinishOnCancel atomic.Bool\n+\n \t// special flag that is only set on deploy,\n \t// if true, the topology file backup is created at /tmp/.clab/bak\n \tBackupTopologyFile bool\n }\n \ndiff --git a/cmd/root.go b/cmd/root.go\nindex 0baf203..a9b1c8b 100644\n--- a/cmd/root.go\n+++ b/cmd/root.go\n@@ -35,10 +35,11 @@ func subcommandRegisterFuncs() []func(*Options) (*cobra.Command, error) {\n \t\tgenerateCmd,\n \t\tgraphCmd,\n \t\teventsCmd,\n \t\tinspectCmd,\n \t\tlogsCmd,\n+\t\tcaptureCmd,\n \t\tredeployCmd,\n \t\tsaveCmd,\n \t\ttoolsCmd,\n \t\tvalidateCmd,\n \t}\n@@ -263,15 +264,10 @@ func checkLabRuntimeCommandSupport(cobraCmd *cobra.Command, runtimeName string)\n \t\t\t\"the %q command needs running containers with lab runtime %q unless it renders \"+\n \t\t\t\t\"from the topology file alone; use --offline, --dot, --mermaid or --drawio\",\n \t\t\t\"graph\", runtimeName)\n \t}\n \n-\tif getCommandPath(cobraCmd) == \"inspect.interfaces\" {\n-\t\treturn fmt.Errorf(\"the %q command is not supported with lab runtime %q\",\n-\t\t\t\"inspect interfaces\", runtimeName)\n-\t}\n-\n \tvar unsupported []string\n \tfor _, flagName := range labRuntimeUnsupportedFlags[getCommandPath(cobraCmd)] {\n \t\tif labRuntimeFlagWasSet(cobraCmd, flagName) {\n \t\t\tunsupported = append(unsupported, \"--\"+flagName)\n \t\t}\n@@ -339,10 +335,11 @@ func getTopoFilePath(cobraCmd *cobra.Command, o *Options) error { // skipcq: GO-\n \t\tcobraCmd.Name() != \"inspect\" &&\n \t\tcobraCmd.Name() != \"save\" &&\n \t\tcobraCmd.Name() != \"graph\" &&\n \t\tcobraCmd.Name() != \"validate\" &&\n \t\tcobraCmd.Name() != \"logs\" &&\n+\t\tcobraCmd.Name() != \"capture\" &&\n \t\tcobraCmd.Name() != \"interfaces\" {\n \t\treturn nil\n \t}\n \n \t// start/stop/restart topology lookup applies only to top-level lifecycle commands.\ndiff --git a/cmd/root_test.go b/cmd/root_test.go\nindex 418a947..af02e34 100644\n--- a/cmd/root_test.go\n+++ b/cmd/root_test.go\n@@ -289,20 +289,23 @@ func TestCheckLabRuntimeFlagAndNestedCommandSupport(t *testing.T) {\n \t\t\t\tt.Fatalf(\"checkLabRuntimeCommandSupport() error = %v, wantErr %v\", err, tt.wantErr)\n \t\t\t}\n \t\t})\n \t}\n \n-\tt.Run(\"inspect interfaces rejected\", func(t *testing.T) {\n+\tt.Run(\"inspect interfaces and capture accepted\", func(t *testing.T) {\n \t\troot := &cobra.Command{Use: \"containerlab\"}\n \t\tinspect := &cobra.Command{Use: \"inspect\"}\n \t\tinterfaces := &cobra.Command{Use: \"interfaces\"}\n-\t\troot.AddCommand(inspect)\n+\t\tcapture := &cobra.Command{Use: \"capture\"}\n+\t\troot.AddCommand(inspect, capture)\n \t\tinspect.AddCommand(interfaces)\n \n-\t\tif err := checkLabRuntimeCommandSupport(\n-\t\t\tinterfaces,\n-\t\t\tclablabruntime.ClabernetesRuntimeName,\n-\t\t); err == nil {\n-\t\t\tt.Fatal(\"inspect interfaces was accepted for clabernetes\")\n+\t\tfor _, cmd := range []*cobra.Command{interfaces, capture} {\n+\t\t\tif err := checkLabRuntimeCommandSupport(\n+\t\t\t\tcmd,\n+\t\t\t\tclablabruntime.ClabernetesRuntimeName,\n+\t\t\t); err != nil {\n+\t\t\t\tt.Fatalf(\"%s rejected for clabernetes: %v\", cmd.Name(), err)\n+\t\t\t}\n \t\t}\n \t})\n }\ndiff --git a/core/capture.go b/core/capture.go\nnew file mode 100644\nindex 0000000..2e12fc2\n--- /dev/null\n+++ b/core/capture.go\n@@ -0,0 +1,93 @@\n+package core\n+\n+import (\n+\t\"context\"\n+\t\"io\"\n+\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tclabtypes \"github.com/srl-labs/containerlab/types\"\n+)\n+\n+// CaptureInterfaces lists the lab link interfaces Capture accepts for the given nodes, or for\n+// every running node, with the peer at the other end of each link. With Docker and Podman, the\n+// interfaces come from the topology's links; lab runtimes list them through their packet\n+// capturer.\n+func (c *CLab) CaptureInterfaces(\n+\tctx context.Context,",
        "lineStart": 2166,
        "lineEnd": 2765,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523435186,
      "end": 1793523435204
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19653c6c7001ZRZ4rnYaNS0qQr",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653bcde001mt4UfEP9687WC6",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 31935,
    "input": 7506,
    "output": 26,
    "reasoning": 83,
    "cache": {
      "read": 24320,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19653bcde001mt4UfEP9687WC6",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523432670,
    "completed": 1793523435210
  },
  "parentID": "msg_19653b129001cj4QAfxRVtxTFM",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 31935,
    "input": 7506,
    "output": 26,
    "reasoning": 83,
    "cache": {
      "read": 24320,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 46
step-start
{
  "type": "step-start",
  "id": "prt_19653cdf90017a3bT5TFVdiey8",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653c6d2001LmjgFru5WWr30l"
}
Reasoning
I've seen cmd/capture.go in the diff now. Note one detail: `captureFn` — the `--write` default is "-" per options, and test checks DefValue "-". But flag help says "pcapng output file; - writes to stdout". Default "-" means stdout — good.

One thing to check: `o.Capture.Write` default "-" but in captureFn: `if o.Capture.Write != "" && o.Capture.Write != "-"` — fine.

Also `parseCaptureTargets` allows `srl1:e1-1,ethernet-1/2` — good.

Now let me continue reading the diff: 2766-3490 (core/capture.go, capture_local.go, capture_test.go, labruntime_cluster_test.go, test_data).
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 630,
  "offset": 2766
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
2766: +	nodeNames ...string,
2767: +) ([]clablabruntime.CaptureInterface, error) {
2768: +	if c.LabRuntime == nil {
2769: +		return c.localCaptureInterfacesOf(ctx, nodeNames)
2770: +	}
2771: +
2772: +	capturer, err := c.packetCapturer()
2773: +	if err != nil {
2774: +		return nil, err
2775: +	}
2776: +
2777: +	return capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{
2778: +		Name:     c.Config.Name,
2779: +		Nodes:    nodeNames,
2780: +		Identity: c.labRuntimeIdentity,
2781: +	})
2782: +}
2783: +
2784: +// Capture streams pcapng from lab link interfaces to w until req.Duration passed,
2785: +// req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name
2786: +// and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces
2787: +// itself through packet sockets in the nodes' network namespaces, which needs root; lab
2788: +// runtimes capture through their packet capturer.
2789: +func (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {
2790: +	if c.LabRuntime == nil {
2791: +		return c.captureLocal(ctx, req, w)
2792: +	}
2793: +
2794: +	capturer, err := c.packetCapturer()
2795: +	if err != nil {
2796: +		return err
2797: +	}
2798: +
2799: +	if req.Name == "" {
2800: +		req.Name = c.Config.Name
2801: +	}
2802: +	if req.Identity.IsZero() {
2803: +		req.Identity = c.labRuntimeIdentity
2804: +	}
2805: +
2806: +	return capturer.Capture(ctx, req, w)
2807: +}
2808: +
2809: +// LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their
2810: +// state, in the shape ListContainersInterfaces reports for local containers.
2811: +func (c *CLab) LabRuntimeInterfaces(
2812: +	ctx context.Context,
2813: +	nodeName string,
2814: +) ([]*clabtypes.ContainerInterfaces, error) {
2815: +	inspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](
2816: +		c, "inspecting interfaces")
2817: +	if err != nil {
2818: +		return nil, err
2819: +	}
2820: +	if err := c.requireLabName(); err != nil {
2821: +		return nil, err
2822: +	}
2823: +
2824: +	req := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}
2825: +	if nodeName != "" {
2826: +		req.Nodes = []string{nodeName}
2827: +	}
2828: +
2829: +	return inspector.InspectInterfaces(ctx, req)
2830: +}
2831: +
2832: +func (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {
2833: +	capturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, "packet capture")
2834: +	if err != nil {
2835: +		return nil, err
2836: +	}
2837: +	if err := c.requireLabName(); err != nil {
2838: +		return nil, err
2839: +	}
2840: +
2841: +	return capturer, nil
2842: +}
2843: diff --git a/core/capture_local.go b/core/capture_local.go
2844: new file mode 100644
2845: index 0000000..fada0bf
2846: --- /dev/null
2847: +++ b/core/capture_local.go
2848: @@ -0,0 +1,255 @@
2849: +package core
2850: +
2851: +import (
2852: +	"context"
2853: +	"fmt"
2854: +	"io"
2855: +	"slices"
2856: +	"sort"
2857: +	"strings"
2858: +
2859: +	clabcapture "github.com/srl-labs/containerlab/capture"
2860: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2861: +	clablinks "github.com/srl-labs/containerlab/links"
2862: +	clabnodes "github.com/srl-labs/containerlab/nodes"
2863: +	clabruntime "github.com/srl-labs/containerlab/runtime"
2864: +)
2865: +
2866: +// localCaptureInterface is a lab link interface of a node on this machine.
2867: +type localCaptureInterface struct {
2868: +	node clabnodes.Node
2869: +	info clablabruntime.CaptureInterface
2870: +}
2871: +
2872: +// localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with
2873: +// the far end of each link, per node name. Host and management network endpoints are the far
2874: +// ends of links, not nodes to capture on.
2875: +func (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {
2876: +	if len(c.Nodes) == 0 {
2877: +		return nil, fmt.Errorf("the topology of lab %q is not available; capture reads the "+
2878: +			"lab's links from it, pass it with --topo", c.Config.Name)
2879: +	}
2880: +	if len(c.Links) == 0 {
2881: +		if err := c.ResolveLinks(); err != nil {
2882: +			return nil, fmt.Errorf("failed to resolve the links of lab %q: %w", c.Config.Name, err)
2883: +		}
2884: +	}
2885: +
2886: +	indexes := make([]int, 0, len(c.Links))
2887: +	for idx := range c.Links {
2888: +		indexes = append(indexes, idx)
2889: +	}
2890: +	sort.Ints(indexes)
2891: +
2892: +	result := map[string][]localCaptureInterface{}
2893: +	for _, idx := range indexes {
2894: +		endpoints := c.Links[idx].GetEndpoints()
2895: +		for epIdx, endpoint := range endpoints {
2896: +			if endpoint.IsNodeless() || endpoint.IsRuntimeDiscovered() ||
2897: +				endpoint.GetNode() == nil {
2898: +				continue
2899: +			}
2900: +			name := endpoint.GetNode().GetShortName()
2901: +			node, ok := c.Nodes[name]
2902: +			if !ok {
2903: +				continue
2904: +			}
2905: +
2906: +			info := clablabruntime.CaptureInterface{
2907: +				Node:      name,
2908: +				Interface: endpoint.GetIfaceName(),
2909: +			}
2910: +			if alias := endpoint.GetIfaceAlias(); alias != info.Interface {
2911: +				info.Alias = alias
2912: +			}
2913: +			if len(endpoints) == 2 {
2914: +				peer := endpoints[1-epIdx]
2915: +				info.PeerNode = capturePeerNode(peer)
2916: +				info.PeerInterface = peer.GetIfaceDisplayName()
2917: +			}
2918: +
2919: +			result[name] = append(result[name], localCaptureInterface{node: node, info: info})
2920: +		}
2921: +	}
2922: +
2923: +	return result, nil
2924: +}
2925: +
2926: +// capturePeerNode names the node at the far end of a link: "host" for a host endpoint and
2927: +// "mgmt-net" for the management network, whose shared link nodes carry other names once a lab
2928: +// was deployed.
2929: +func capturePeerNode(peer clablinks.Endpoint) string {
2930: +	if peer.IsNodeless() {
2931: +		if _, ok := peer.(*clablinks.EndpointBridge); ok {
2932: +			return string(clablinks.LinkTypeMgmtNet)
2933: +		}
2934: +
2935: +		return string(clablinks.LinkTypeHost)
2936: +	}
2937: +	if peer.GetNode() == nil {
2938: +		return ""
2939: +	}
2940: +
2941: +	return peer.GetNode().GetShortName()
2942: +}
2943: +
2944: +// lookupLocalNode finds a lab node by its topology name or its container name.
2945: +func (c *CLab) lookupLocalNode(name string) (clabnodes.Node, error) {
2946: +	if node, ok := c.Nodes[name]; ok {
2947: +		return node, nil
2948: +	}
2949: +	for _, node := range c.Nodes {
2950: +		if node.Config().LongName == name {
2951: +			return node, nil
2952: +		}
2953: +	}
2954: +
2955: +	names := make([]string, 0, len(c.Nodes))
2956: +	for nodeName := range c.Nodes {
2957: +		names = append(names, nodeName)
2958: +	}
2959: +	slices.Sort(names)
2960: +
2961: +	return nil, fmt.Errorf("node %q is not part of lab %q; nodes: %s", name, c.Config.Name,
2962: +		strings.Join(names, ", "))
2963: +}
2964: +
2965: +// nodeRuns reports whether a node's network namespace can be entered.
2966: +func nodeRuns(ctx context.Context, node clabnodes.Node) bool {
2967: +	if node.Config().IsRootNamespaceBased {
2968: +		return true
2969: +	}
2970: +
2971: +	return clabruntime.ContainerHasJoinableNetns(node.GetContainerStatus(ctx))
2972: +}
2973: +
2974: +// localCaptureInterfacesOf implements CaptureInterfaces for Docker and Podman: the requested
2975: +// nodes, or every running node.
2976: +func (c *CLab) localCaptureInterfacesOf(
2977: +	ctx context.Context,
2978: +	nodeNames []string,
2979: +) ([]clablabruntime.CaptureInterface, error) {
2980: +	if err := c.requireLabName(); err != nil {
2981: +		return nil, err
2982: +	}
2983: +	byNode, err := c.localCaptureInterfaces()
2984: +	if err != nil {
2985: +		return nil, err
2986: +	}
2987: +
2988: +	var nodes []clabnodes.Node
2989: +	if len(nodeNames) == 0 {
2990: +		for _, node := range c.Nodes {
2991: +			if nodeRuns(ctx, node) {
2992: +				nodes = append(nodes, node)
2993: +			}
2994: +		}
2995: +	} else {
2996: +		for _, name := range nodeNames {
2997: +			node, err := c.lookupLocalNode(name)
2998: +			if err != nil {
2999: +				return nil, err
3000: +			}
3001: +			nodes = append(nodes, node)
3002: +		}
3003: +	}
3004: +
3005: +	result := make([]clablabruntime.CaptureInterface, 0)
3006: +	seen := map[string]bool{}
3007: +	for _, node := range nodes {
3008: +		name := node.Config().ShortName
3009: +		if seen[name] {
3010: +			continue
3011: +		}
3012: +		seen[name] = true
3013: +		for _, entry := range byNode[name] {
3014: +			result = append(result, entry.info)
3015: +		}
3016: +	}
3017: +	sortCaptureInterfaces(result)
3018: +
3019: +	return result, nil
3020: +}
3021: +
3022: +func sortCaptureInterfaces(interfaces []clablabruntime.CaptureInterface) {
3023: +	sort.SliceStable(interfaces, func(i, j int) bool {
3024: +		if interfaces[i].Node != interfaces[j].Node {
3025: +			return interfaces[i].Node < interfaces[j].Node
3026: +		}
3027: +
3028: +		return interfaces[i].Interface < interfaces[j].Interface
3029: +	})
3030: +}
3031: +
3032: +// resolveLocalCaptureTargets checks every target against the node's link interfaces, by name or
3033: +// alias, and returns them in request order.
3034: +func (c *CLab) resolveLocalCaptureTargets(
3035: +	targets []clablabruntime.CaptureTarget,
3036: +) ([]clabcapture.LocalTarget, error) {
3037: +	byNode, err := c.localCaptureInterfaces()
3038: +	if err != nil {
3039: +		return nil, err
3040: +	}
3041: +
3042: +	resolved := make([]clabcapture.LocalTarget, 0, len(targets))
3043: +	seen := map[string]bool{}
3044: +	for _, target := range targets {
3045: +		node, err := c.lookupLocalNode(target.Node)
3046: +		if err != nil {
3047: +			return nil, err
3048: +		}
3049: +		name := node.Config().ShortName
3050: +
3051: +		infos := make([]clablabruntime.CaptureInterface, 0, len(byNode[name]))
3052: +		for _, entry := range byNode[name] {
3053: +			infos = append(infos, entry.info)
3054: +		}
3055: +		sortCaptureInterfaces(infos)
3056: +		info, ok := clabcapture.FindInterface(infos, target.Interface)
3057: +		if !ok {
3058: +			return nil, fmt.Errorf("interface %q of node %q is not a capturable link "+
3059: +				"interface; capturable: %s", target.Interface, target.Node,
3060: +				clabcapture.DescribeInterfaces(infos))
3061: +		}
3062: +
3063: +		key := name + "\x00" + info.Interface
3064: +		if seen[key] {
3065: +			return nil, fmt.Errorf("interface %q of node %q is requested more than once",
3066: +				info.Interface, target.Node)
3067: +		}
3068: +		seen[key] = true
3069: +
3070: +		resolved = append(resolved, clabcapture.LocalTarget{
3071: +			Node:      name,
3072: +			Interface: info.Interface,
3073: +			Exec:      node.ExecFunction,
3074: +		})
3075: +	}
3076: +
3077: +	return resolved, nil
3078: +}
3079: +
3080: +// captureLocal implements Capture for Docker and Podman through packet sockets in the nodes'
3081: +// network namespaces.
3082: +func (c *CLab) captureLocal(
3083: +	ctx context.Context,
3084: +	req clablabruntime.CaptureRequest,
3085: +	w io.Writer,
3086: +) error {
3087: +	if err := c.requireLabName(); err != nil {
3088: +		return err
3089: +	}
3090: +	if req.Name == "" {
3091: +		req.Name = c.Config.Name
3092: +	}
3093: +	if err := clabcapture.ValidateRequest(&req); err != nil {
3094: +		return err
3095: +	}
3096: +
3097: +	targets, err := c.resolveLocalCaptureTargets(req.Targets)
3098: +	if err != nil {
3099: +		return err
3100: +	}
3101: +
3102: +	return clabcapture.CaptureLocal(ctx, req, targets, w)
3103: +}
3104: diff --git a/core/capture_test.go b/core/capture_test.go
3105: new file mode 100644
3106: index 0000000..b5d34b0
3107: --- /dev/null
3108: +++ b/core/capture_test.go
3109: @@ -0,0 +1,210 @@
3110: +package core
3111: +
3112: +import (
3113: +	"bytes"
3114: +	"context"
3115: +	"io"
3116: +	"slices"
3117: +	"strings"
3118: +	"testing"
3119: +
3120: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
3121: +	clabtypes "github.com/srl-labs/containerlab/types"
3122: +)
3123: +
3124: +// captureLabRuntime records the capture requests core sends.
3125: +type captureLabRuntime struct {
3126: +	clablabruntime.LabRuntime
3127: +
3128: +	nodeRequest    clablabruntime.NodeRequest
3129: +	captureRequest clablabruntime.CaptureRequest
3130: +}
3131: +
3132: +func (r *captureLabRuntime) CaptureInterfaces(
3133: +	_ context.Context,
3134: +	req clablabruntime.NodeRequest,
3135: +) ([]clablabruntime.CaptureInterface, error) {
3136: +	r.nodeRequest = req
3137: +
3138: +	return []clablabruntime.CaptureInterface{{Node: "r1", Interface: "eth1"}}, nil
3139: +}
3140: +
3141: +func (r *captureLabRuntime) Capture(
3142: +	_ context.Context,
3143: +	req clablabruntime.CaptureRequest,
3144: +	w io.Writer,
3145: +) error {
3146: +	r.captureRequest = req
3147: +	_, err := io.WriteString(w, "pcapng")
3148: +
3149: +	return err
3150: +}
3151: +
3152: +func (r *captureLabRuntime) InspectInterfaces(
3153: +	_ context.Context,
3154: +	req clablabruntime.NodeRequest,
3155: +) ([]*clabtypes.ContainerInterfaces, error) {
3156: +	r.nodeRequest = req
3157: +
3158: +	return []*clabtypes.ContainerInterfaces{{ContainerName: "lab1-r1"}}, nil
3159: +}
3160: +
3161: +func TestCaptureHelpersFillLabAndIdentity(t *testing.T) {
3162: +	t.Parallel()
3163: +
3164: +	lr := &captureLabRuntime{}
3165: +	c := newAccessTestCLab(lr)
3166: +	ctx := context.Background()
3167: +
3168: +	interfaces, err := c.CaptureInterfaces(ctx, "R1")
3169: +	if err != nil || len(interfaces) != 1 {
3170: +		t.Fatalf("CaptureInterfaces() = %+v, %v", interfaces, err)
3171: +	}
3172: +	if lr.nodeRequest.Name != "lab1" || lr.nodeRequest.Nodes[0] != "R1" ||
3173: +		!lr.nodeRequest.Identity.Equal(testIdentity) {
3174: +		t.Fatalf("interfaces request = %+v", lr.nodeRequest)
3175: +	}
3176: +
3177: +	var out bytes.Buffer
3178: +	if err := c.Capture(ctx, clablabruntime.CaptureRequest{
3179: +		Targets: []clablabruntime.CaptureTarget{{Node: "r1", Interface: "eth1"}},
3180: +	}, &out); err != nil {
3181: +		t.Fatal(err)
3182: +	}
3183: +	if out.String() != "pcapng" || lr.captureRequest.Name != "lab1" ||
3184: +		!lr.captureRequest.Identity.Equal(testIdentity) {
3185: +		t.Fatalf("capture request = %+v, output %q", lr.captureRequest, out.String())
3186: +	}
3187: +
3188: +	ifaces, err := c.LabRuntimeInterfaces(ctx, "r1")
3189: +	if err != nil || len(ifaces) != 1 || lr.nodeRequest.Nodes[0] != "r1" {
3190: +		t.Fatalf("LabRuntimeInterfaces() = %+v, %v, request %+v", ifaces, err, lr.nodeRequest)
3191: +	}
3192: +	if _, err := c.LabRuntimeInterfaces(ctx, ""); err != nil || lr.nodeRequest.Nodes != nil {
3193: +		t.Fatalf("all nodes request = %+v, %v", lr.nodeRequest, err)
3194: +	}
3195: +}
3196: +
3197: +// newLocalCaptureCLab loads the capture test topology. Its host and mgmt-net links register
3198: +// endpoints on link nodes the whole process shares, so the tests using it do not run in
3199: +// parallel and release the endpoints when they end.
3200: +func newLocalCaptureCLab(t *testing.T) *CLab {
3201: +	t.Helper()
3202: +
3203: +	c, err := NewContainerLab(WithTopoPath("test_data/capture.clab.yml", nil))
3204: +	if err != nil {
3205: +		t.Fatal(err)
3206: +	}
3207: +	t.Cleanup(c.resetResolvedLinks)
3208: +
3209: +	return c
3210: +}
3211: +
3212: +func TestLocalCaptureInterfacesComeFromTheTopologyLinks(t *testing.T) {
3213: +	c := newLocalCaptureCLab(t)
3214: +
3215: +	got, err := c.CaptureInterfaces(context.Background(), "srl1", "client")
3216: +	if err != nil {
3217: +		t.Fatal(err)
3218: +	}
3219: +	want := []clablabruntime.CaptureInterface{
3220: +		{Node: "client", Interface: "eth1", PeerNode: "srl1", PeerInterface: "e1-2"},
3221: +		{Node: "client", Interface: "eth2", PeerNode: "host", PeerInterface: "client-eth2"},
3222: +		{Node: "client", Interface: "eth3", PeerNode: "mgmt-net", PeerInterface: "client-eth3"},
3223: +		{
3224: +			Node: "srl1", Interface: "e1-1", Alias: "ethernet-1/1",
3225: +			PeerNode: "srl2", PeerInterface: "e1-1",
3226: +		},
3227: +		{Node: "srl1", Interface: "e1-2", PeerNode: "client", PeerInterface: "eth1"},
3228: +	}
3229: +	if !slices.Equal(got, want) {
3230: +		t.Fatalf("CaptureInterfaces() =\n%+v\nwant\n%+v", got, want)
3231: +	}
3232: +
3233: +	if _, err := c.CaptureInterfaces(context.Background(), "r9"); err == nil ||
3234: +		!strings.Contains(err.Error(), `node "r9" is not part of lab "capture"`) {
3235: +		t.Fatalf("unknown node: error = %v", err)
3236: +	}
3237: +}
3238: +
3239: +func TestLocalCaptureTargetsResolveByNameOrAlias(t *testing.T) {
3240: +	c := newLocalCaptureCLab(t)
3241: +
3242: +	targets, err := c.resolveLocalCaptureTargets([]clablabruntime.CaptureTarget{
3243: +		{Node: "srl2", Interface: "e1-1"},
3244: +		{Node: "srl1", Interface: "ethernet-1/1"},
3245: +		{Node: "clab-capture-client", Interface: "eth2"},
3246: +	})
3247: +	if err != nil {
3248: +		t.Fatal(err)
3249: +	}
3250: +	var got []string
3251: +	for _, target := range targets {
3252: +		if target.Exec == nil {
3253: +			t.Fatalf("target %s:%s has no namespace exec", target.Node, target.Interface)
3254: +		}
3255: +		got = append(got, target.Node+":"+target.Interface)
3256: +	}
3257: +	if want := []string{"srl2:e1-1", "srl1:e1-1", "client:eth2"}; !slices.Equal(got, want) {
3258: +		t.Fatalf("targets = %v, want %v", got, want)
3259: +	}
3260: +
3261: +	for _, tc := range []struct {
3262: +		name    string
3263: +		targets []clablabruntime.CaptureTarget
3264: +		want    string
3265: +	}{
3266: +		{
3267: +			name:    "management interface",
3268: +			targets: []clablabruntime.CaptureTarget{{Node: "client", Interface: "eth0"}},
3269: +			want: `interface "eth0" of node "client" is not a capturable link interface; ` +
3270: +				"capturable: eth1, eth2, eth3",
3271: +		},
3272: +		{
3273: +			name: "same interface twice",
3274: +			targets: []clablabruntime.CaptureTarget{
3275: +				{Node: "srl1", Interface: "e1-1"}, {Node: "srl1", Interface: "ethernet-1/1"},
3276: +			},
3277: +			want: `interface "e1-1" of node "srl1" is requested more than once`,
3278: +		},
3279: +		{
3280: +			name:    "unknown node",
3281: +			targets: []clablabruntime.CaptureTarget{{Node: "r9", Interface: "eth1"}},
3282: +			want:    `node "r9" is not part of lab "capture"`,
3283: +		},
3284: +	} {
3285: +		if _, err := c.resolveLocalCaptureTargets(tc.targets); err == nil ||
3286: +			!strings.Contains(err.Error(), tc.want) {
3287: +			t.Errorf("%s: error = %v, want %q", tc.name, err, tc.want)
3288: +		}
3289: +	}
3290: +}
3291: +
3292: +func TestLocalCaptureNeedsTheTopology(t *testing.T) {
3293: +	t.Parallel()
3294: +
3295: +	c := &CLab{Config: &Config{Name: "lab1"}, globalRuntimeName: "docker"}
3296: +	err := c.Capture(context.Background(), clablabruntime.CaptureRequest{
3297: +		Targets: []clablabruntime.CaptureTarget{{Node: "r1", Interface: "eth1"}},
3298: +	}, io.Discard)
3299: +	if err == nil || !strings.Contains(err.Error(), `the topology of lab "lab1" is not available`) {
3300: +		t.Fatalf("error = %v", err)
3301: +	}
3302: +	if err := c.Capture(context.Background(), clablabruntime.CaptureRequest{},
3303: +		io.Discard); err == nil || !strings.Contains(err.Error(), "at least one capture target") {
3304: +		t.Fatalf("no targets: error = %v", err)
3305: +	}
3306: +}
3307: +
3308: +func TestLabRuntimeWithoutCaptureFails(t *testing.T) {
3309: +	t.Parallel()
3310: +
3311: +	unsupported := newAccessTestCLab(&recordingDestroyLabRuntime{})
3312: +	if err := unsupported.Capture(
3313: +		context.Background(),
3314: +		clablabruntime.CaptureRequest{},
3315: +		io.Discard,
3316: +	); err == nil || !strings.Contains(err.Error(), "does not support packet capture") {
3317: +		t.Fatalf("lab runtime without capture: error = %v", err)
3318: +	}
3319: +}
3320: diff --git a/core/labruntime_cluster_test.go b/core/labruntime_cluster_test.go
3321: index 06ecf57..981a302 100644
3322: --- a/core/labruntime_cluster_test.go
3323: +++ b/core/labruntime_cluster_test.go
3324: @@ -1,10 +1,11 @@
3325:  package core
3326:  
3327:  import (
3328:  	"bytes"
3329:  	"context"
3330: +	"encoding/binary"
3331:  	"errors"
3332:  	"io"
3333:  	"net"
3334:  	"net/http"
3335:  	"os"
3336: @@ -175,5 +176,153 @@ func TestC9sClusterNodeAccess(t *testing.T) {
3337:  		if err == nil || !strings.Contains(err.Error(), "forbidden") {
3338:  			t.Fatalf("impersonated user without rights: error = %v, want forbidden", err)
3339:  		}
3340:  	})
3341:  }
3342: +
3343: +// TestC9sClusterCapture captures through the library against a deployed c9s lab, as an identity
3344: +// that holds only the clabernetes-lab-editor role in the lab namespace. It runs only when
3345: +// CLAB_C9S_TEST_LAB names the lab and CLAB_C9S_TEST_CAPTURE_USER the identity (tests/14-clabernetes
3346: +// sets both). The lab must have linux nodes "client" (10.10.10.1) and "server" (10.10.10.2)
3347: +// linked by eth1. CLAB_C9S_TEST_FORBIDDEN_USER names an identity without a binding.
3348: +func TestC9sClusterCapture(t *testing.T) {
3349: +	lab := os.Getenv("CLAB_C9S_TEST_LAB")
3350: +	user := os.Getenv("CLAB_C9S_TEST_CAPTURE_USER")
3351: +	if lab == "" || user == "" {
3352: +		t.Skip("CLAB_C9S_TEST_LAB or CLAB_C9S_TEST_CAPTURE_USER is not set")
3353: +	}
3354: +
3355: +	newCLab := func(t *testing.T, user string) *CLab {
3356: +		t.Helper()
3357: +
3358: +		c, err := NewContainerLab(
3359: +			WithRuntime(clablabruntime.ClabernetesRuntimeName, nil),
3360: +			WithTopologyName(lab),
3361: +			WithLabRuntimeIdentity(clablabruntime.Identity{User: user}),
3362: +		)
3363: +		if err != nil {
3364: +			t.Fatal(err)
3365: +		}
3366: +
3367: +		return c
3368: +	}
3369: +	c := newCLab(t, user)
3370: +
3371: +	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
3372: +	defer cancel()
3373: +
3374: +	t.Run("version check", func(t *testing.T) {
3375: +		if err := c.CheckLabRuntimeSupport(ctx); err != nil {
3376: +			t.Fatal(err)
3377: +		}
3378: +	})
3379: +
3380: +	t.Run("capture interfaces", func(t *testing.T) {
3381: +		interfaces, err := c.CaptureInterfaces(ctx)
3382: +		if err != nil {
3383: +			t.Fatal(err)
3384: +		}
3385: +		want := []clablabruntime.CaptureInterface{
3386: +			{Node: "client", Interface: "eth1", PeerNode: "server", PeerInterface: "eth1"},
3387: +			{Node: "server", Interface: "eth1", PeerNode: "client", PeerInterface: "eth1"},
3388: +		}
3389: +		if len(interfaces) != 2 || interfaces[0] != want[0] || interfaces[1] != want[1] {
3390: +			t.Fatalf("interfaces = %+v", interfaces)
3391: +		}
3392: +	})
3393: +
3394: +	t.Run("capture both ends of a link", func(t *testing.T) {
3395: +		pinged := make(chan error, 1)

(Showing lines 2766-3395 of 7018. Use offset=3396 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19653d1e3001L3zfMijMe34wEq",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653c6d2001LmjgFru5WWr30l",
  "callID": "call_d0f36a50e26942f984c43d1b",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 630,
      "offset": 2766
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n2766: +\tnodeNames ...string,\n2767: +) ([]clablabruntime.CaptureInterface, error) {\n2768: +\tif c.LabRuntime == nil {\n2769: +\t\treturn c.localCaptureInterfacesOf(ctx, nodeNames)\n2770: +\t}\n2771: +\n2772: +\tcapturer, err := c.packetCapturer()\n2773: +\tif err != nil {\n2774: +\t\treturn nil, err\n2775: +\t}\n2776: +\n2777: +\treturn capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{\n2778: +\t\tName:     c.Config.Name,\n2779: +\t\tNodes:    nodeNames,\n2780: +\t\tIdentity: c.labRuntimeIdentity,\n2781: +\t})\n2782: +}\n2783: +\n2784: +// Capture streams pcapng from lab link interfaces to w until req.Duration passed,\n2785: +// req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name\n2786: +// and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces\n2787: +// itself through packet sockets in the nodes' network namespaces, which needs root; lab\n2788: +// runtimes capture through their packet capturer.\n2789: +func (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {\n2790: +\tif c.LabRuntime == nil {\n2791: +\t\treturn c.captureLocal(ctx, req, w)\n2792: +\t}\n2793: +\n2794: +\tcapturer, err := c.packetCapturer()\n2795: +\tif err != nil {\n2796: +\t\treturn err\n2797: +\t}\n2798: +\n2799: +\tif req.Name == \"\" {\n2800: +\t\treq.Name = c.Config.Name\n2801: +\t}\n2802: +\tif req.Identity.IsZero() {\n2803: +\t\treq.Identity = c.labRuntimeIdentity\n2804: +\t}\n2805: +\n2806: +\treturn capturer.Capture(ctx, req, w)\n2807: +}\n2808: +\n2809: +// LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their\n2810: +// state, in the shape ListContainersInterfaces reports for local containers.\n2811: +func (c *CLab) LabRuntimeInterfaces(\n2812: +\tctx context.Context,\n2813: +\tnodeName string,\n2814: +) ([]*clabtypes.ContainerInterfaces, error) {\n2815: +\tinspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](\n2816: +\t\tc, \"inspecting interfaces\")\n2817: +\tif err != nil {\n2818: +\t\treturn nil, err\n2819: +\t}\n2820: +\tif err := c.requireLabName(); err != nil {\n2821: +\t\treturn nil, err\n2822: +\t}\n2823: +\n2824: +\treq := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}\n2825: +\tif nodeName != \"\" {\n2826: +\t\treq.Nodes = []string{nodeName}\n2827: +\t}\n2828: +\n2829: +\treturn inspector.InspectInterfaces(ctx, req)\n2830: +}\n2831: +\n2832: +func (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {\n2833: +\tcapturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, \"packet capture\")\n2834: +\tif err != nil {\n2835: +\t\treturn nil, err\n2836: +\t}\n2837: +\tif err := c.requireLabName(); err != nil {\n2838: +\t\treturn nil, err\n2839: +\t}\n2840: +\n2841: +\treturn capturer, nil\n2842: +}\n2843: diff --git a/core/capture_local.go b/core/capture_local.go\n2844: new file mode 100644\n2845: index 0000000..fada0bf\n2846: --- /dev/null\n2847: +++ b/core/capture_local.go\n2848: @@ -0,0 +1,255 @@\n2849: +package core\n2850: +\n2851: +import (\n2852: +\t\"context\"\n2853: +\t\"fmt\"\n2854: +\t\"io\"\n2855: +\t\"slices\"\n2856: +\t\"sort\"\n2857: +\t\"strings\"\n2858: +\n2859: +\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n2860: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2861: +\tclablinks \"github.com/srl-labs/containerlab/links\"\n2862: +\tclabnodes \"github.com/srl-labs/containerlab/nodes\"\n2863: +\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n2864: +)\n2865: +\n2866: +// localCaptureInterface is a lab link interface of a node on this machine.\n2867: +type localCaptureInterface struct {\n2868: +\tnode clabnodes.Node\n2869: +\tinfo clablabruntime.CaptureInterface\n2870: +}\n2871: +\n2872: +// localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with\n2873: +// the far end of each link, per node name. Host and management network endpoints are the far\n2874: +// ends of links, not nodes to capture on.\n2875: +func (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {\n2876: +\tif len(c.Nodes) == 0 {\n2877: +\t\treturn nil, fmt.Errorf(\"the topology of lab %q is not available; capture reads the \"+\n2878: +\t\t\t\"lab's links from it, pass it with --topo\", c.Config.Name)\n2879: +\t}\n2880: +\tif len(c.Links) == 0 {\n2881: +\t\tif err := c.ResolveLinks(); err != nil {\n2882: +\t\t\treturn nil, fmt.Errorf(\"failed to resolve the links of lab %q: %w\", c.Config.Name, err)\n2883: +\t\t}\n2884: +\t}\n2885: +\n2886: +\tindexes := make([]int, 0, len(c.Links))\n2887: +\tfor idx := range c.Links {\n2888: +\t\tindexes = append(indexes, idx)\n2889: +\t}\n2890: +\tsort.Ints(indexes)\n2891: +\n2892: +\tresult := map[string][]localCaptureInterface{}\n2893: +\tfor _, idx := range indexes {\n2894: +\t\tendpoints := c.Links[idx].GetEndpoints()\n2895: +\t\tfor epIdx, endpoint := range endpoints {\n2896: +\t\t\tif endpoint.IsNodeless() || endpoint.IsRuntimeDiscovered() ||\n2897: +\t\t\t\tendpoint.GetNode() == nil {\n2898: +\t\t\t\tcontinue\n2899: +\t\t\t}\n2900: +\t\t\tname := endpoint.GetNode().GetShortName()\n2901: +\t\t\tnode, ok := c.Nodes[name]\n2902: +\t\t\tif !ok {\n2903: +\t\t\t\tcontinue\n2904: +\t\t\t}\n2905: +\n2906: +\t\t\tinfo := clablabruntime.CaptureInterface{\n2907: +\t\t\t\tNode:      name,\n2908: +\t\t\t\tInterface: endpoint.GetIfaceName(),\n2909: +\t\t\t}\n2910: +\t\t\tif alias := endpoint.GetIfaceAlias(); alias != info.Interface {\n2911: +\t\t\t\tinfo.Alias = alias\n2912: +\t\t\t}\n2913: +\t\t\tif len(endpoints) == 2 {\n2914: +\t\t\t\tpeer := endpoints[1-epIdx]\n2915: +\t\t\t\tinfo.PeerNode = capturePeerNode(peer)\n2916: +\t\t\t\tinfo.PeerInterface = peer.GetIfaceDisplayName()\n2917: +\t\t\t}\n2918: +\n2919: +\t\t\tresult[name] = append(result[name], localCaptureInterface{node: node, info: info})\n2920: +\t\t}\n2921: +\t}\n2922: +\n2923: +\treturn result, nil\n2924: +}\n2925: +\n2926: +// capturePeerNode names the node at the far end of a link: \"host\" for a host endpoint and\n2927: +// \"mgmt-net\" for the management network, whose shared link nodes carry other names once a lab\n2928: +// was deployed.\n2929: +func capturePeerNode(peer clablinks.Endpoint) string {\n2930: +\tif peer.IsNodeless() {\n2931: +\t\tif _, ok := peer.(*clablinks.EndpointBridge); ok {\n2932: +\t\t\treturn string(clablinks.LinkTypeMgmtNet)\n2933: +\t\t}\n2934: +\n2935: +\t\treturn string(clablinks.LinkTypeHost)\n2936: +\t}\n2937: +\tif peer.GetNode() == nil {\n2938: +\t\treturn \"\"\n2939: +\t}\n2940: +\n2941: +\treturn peer.GetNode().GetShortName()\n2942: +}\n2943: +\n2944: +// lookupLocalNode finds a lab node by its topology name or its container name.\n2945: +func (c *CLab) lookupLocalNode(name string) (clabnodes.Node, error) {\n2946: +\tif node, ok := c.Nodes[name]; ok {\n2947: +\t\treturn node, nil\n2948: +\t}\n2949: +\tfor _, node := range c.Nodes {\n2950: +\t\tif node.Config().LongName == name {\n2951: +\t\t\treturn node, nil\n2952: +\t\t}\n2953: +\t}\n2954: +\n2955: +\tnames := make([]string, 0, len(c.Nodes))\n2956: +\tfor nodeName := range c.Nodes {\n2957: +\t\tnames = append(names, nodeName)\n2958: +\t}\n2959: +\tslices.Sort(names)\n2960: +\n2961: +\treturn nil, fmt.Errorf(\"node %q is not part of lab %q; nodes: %s\", name, c.Config.Name,\n2962: +\t\tstrings.Join(names, \", \"))\n2963: +}\n2964: +\n2965: +// nodeRuns reports whether a node's network namespace can be entered.\n2966: +func nodeRuns(ctx context.Context, node clabnodes.Node) bool {\n2967: +\tif node.Config().IsRootNamespaceBased {\n2968: +\t\treturn true\n2969: +\t}\n2970: +\n2971: +\treturn clabruntime.ContainerHasJoinableNetns(node.GetContainerStatus(ctx))\n2972: +}\n2973: +\n2974: +// localCaptureInterfacesOf implements CaptureInterfaces for Docker and Podman: the requested\n2975: +// nodes, or every running node.\n2976: +func (c *CLab) localCaptureInterfacesOf(\n2977: +\tctx context.Context,\n2978: +\tnodeNames []string,\n2979: +) ([]clablabruntime.CaptureInterface, error) {\n2980: +\tif err := c.requireLabName(); err != nil {\n2981: +\t\treturn nil, err\n2982: +\t}\n2983: +\tbyNode, err := c.localCaptureInterfaces()\n2984: +\tif err != nil {\n2985: +\t\treturn nil, err\n2986: +\t}\n2987: +\n2988: +\tvar nodes []clabnodes.Node\n2989: +\tif len(nodeNames) == 0 {\n2990: +\t\tfor _, node := range c.Nodes {\n2991: +\t\t\tif nodeRuns(ctx, node) {\n2992: +\t\t\t\tnodes = append(nodes, node)\n2993: +\t\t\t}\n2994: +\t\t}\n2995: +\t} else {\n2996: +\t\tfor _, name := range nodeNames {\n2997: +\t\t\tnode, err := c.lookupLocalNode(name)\n2998: +\t\t\tif err != nil {\n2999: +\t\t\t\treturn nil, err\n3000: +\t\t\t}\n3001: +\t\t\tnodes = append(nodes, node)\n3002: +\t\t}\n3003: +\t}\n3004: +\n3005: +\tresult := make([]clablabruntime.CaptureInterface, 0)\n3006: +\tseen := map[string]bool{}\n3007: +\tfor _, node := range nodes {\n3008: +\t\tname := node.Config().ShortName\n3009: +\t\tif seen[name] {\n3010: +\t\t\tcontinue\n3011: +\t\t}\n3012: +\t\tseen[name] = true\n3013: +\t\tfor _, entry := range byNode[name] {\n3014: +\t\t\tresult = append(result, entry.info)\n3015: +\t\t}\n3016: +\t}\n3017: +\tsortCaptureInterfaces(result)\n3018: +\n3019: +\treturn result, nil\n3020: +}\n3021: +\n3022: +func sortCaptureInterfaces(interfaces []clablabruntime.CaptureInterface) {\n3023: +\tsort.SliceStable(interfaces, func(i, j int) bool {\n3024: +\t\tif interfaces[i].Node != interfaces[j].Node {\n3025: +\t\t\treturn interfaces[i].Node < interfaces[j].Node\n3026: +\t\t}\n3027: +\n3028: +\t\treturn interfaces[i].Interface < interfaces[j].Interface\n3029: +\t})\n3030: +}\n3031: +\n3032: +// resolveLocalCaptureTargets checks every target against the node's link interfaces, by name or\n3033: +// alias, and returns them in request order.\n3034: +func (c *CLab) resolveLocalCaptureTargets(\n3035: +\ttargets []clablabruntime.CaptureTarget,\n3036: +) ([]clabcapture.LocalTarget, error) {\n3037: +\tbyNode, err := c.localCaptureInterfaces()\n3038: +\tif err != nil {\n3039: +\t\treturn nil, err\n3040: +\t}\n3041: +\n3042: +\tresolved := make([]clabcapture.LocalTarget, 0, len(targets))\n3043: +\tseen := map[string]bool{}\n3044: +\tfor _, target := range targets {\n3045: +\t\tnode, err := c.lookupLocalNode(target.Node)\n3046: +\t\tif err != nil {\n3047: +\t\t\treturn nil, err\n3048: +\t\t}\n3049: +\t\tname := node.Config().ShortName\n3050: +\n3051: +\t\tinfos := make([]clablabruntime.CaptureInterface, 0, len(byNode[name]))\n3052: +\t\tfor _, entry := range byNode[name] {\n3053: +\t\t\tinfos = append(infos, entry.info)\n3054: +\t\t}\n3055: +\t\tsortCaptureInterfaces(infos)\n3056: +\t\tinfo, ok := clabcapture.FindInterface(infos, target.Interface)\n3057: +\t\tif !ok {\n3058: +\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n3059: +\t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n3060: +\t\t\t\tclabcapture.DescribeInterfaces(infos))\n3061: +\t\t}\n3062: +\n3063: +\t\tkey := name + \"\\x00\" + info.Interface\n3064: +\t\tif seen[key] {\n3065: +\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n3066: +\t\t\t\tinfo.Interface, target.Node)\n3067: +\t\t}\n3068: +\t\tseen[key] = true\n3069: +\n3070: +\t\tresolved = append(resolved, clabcapture.LocalTarget{\n3071: +\t\t\tNode:      name,\n3072: +\t\t\tInterface: info.Interface,\n3073: +\t\t\tExec:      node.ExecFunction,\n3074: +\t\t})\n3075: +\t}\n3076: +\n3077: +\treturn resolved, nil\n3078: +}\n3079: +\n3080: +// captureLocal implements Capture for Docker and Podman through packet sockets in the nodes'\n3081: +// network namespaces.\n3082: +func (c *CLab) captureLocal(\n3083: +\tctx context.Context,\n3084: +\treq clablabruntime.CaptureRequest,\n3085: +\tw io.Writer,\n3086: +) error {\n3087: +\tif err := c.requireLabName(); err != nil {\n3088: +\t\treturn err\n3089: +\t}\n3090: +\tif req.Name == \"\" {\n3091: +\t\treq.Name = c.Config.Name\n3092: +\t}\n3093: +\tif err := clabcapture.ValidateRequest(&req); err != nil {\n3094: +\t\treturn err\n3095: +\t}\n3096: +\n3097: +\ttargets, err := c.resolveLocalCaptureTargets(req.Targets)\n3098: +\tif err != nil {\n3099: +\t\treturn err\n3100: +\t}\n3101: +\n3102: +\treturn clabcapture.CaptureLocal(ctx, req, targets, w)\n3103: +}\n3104: diff --git a/core/capture_test.go b/core/capture_test.go\n3105: new file mode 100644\n3106: index 0000000..b5d34b0\n3107: --- /dev/null\n3108: +++ b/core/capture_test.go\n3109: @@ -0,0 +1,210 @@\n3110: +package core\n3111: +\n3112: +import (\n3113: +\t\"bytes\"\n3114: +\t\"context\"\n3115: +\t\"io\"\n3116: +\t\"slices\"\n3117: +\t\"strings\"\n3118: +\t\"testing\"\n3119: +\n3120: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n3121: +\tclabtypes \"github.com/srl-labs/containerlab/types\"\n3122: +)\n3123: +\n3124: +// captureLabRuntime records the capture requests core sends.\n3125: +type captureLabRuntime struct {\n3126: +\tclablabruntime.LabRuntime\n3127: +\n3128: +\tnodeRequest    clablabruntime.NodeRequest\n3129: +\tcaptureRequest clablabruntime.CaptureRequest\n3130: +}\n3131: +\n3132: +func (r *captureLabRuntime) CaptureInterfaces(\n3133: +\t_ context.Context,\n3134: +\treq clablabruntime.NodeRequest,\n3135: +) ([]clablabruntime.CaptureInterface, error) {\n3136: +\tr.nodeRequest = req\n3137: +\n3138: +\treturn []clablabruntime.CaptureInterface{{Node: \"r1\", Interface: \"eth1\"}}, nil\n3139: +}\n3140: +\n3141: +func (r *captureLabRuntime) Capture(\n3142: +\t_ context.Context,\n3143: +\treq clablabruntime.CaptureRequest,\n3144: +\tw io.Writer,\n3145: +) error {\n3146: +\tr.captureRequest = req\n3147: +\t_, err := io.WriteString(w, \"pcapng\")\n3148: +\n3149: +\treturn err\n3150: +}\n3151: +\n3152: +func (r *captureLabRuntime) InspectInterfaces(\n3153: +\t_ context.Context,\n3154: +\treq clablabruntime.NodeRequest,\n3155: +) ([]*clabtypes.ContainerInterfaces, error) {\n3156: +\tr.nodeRequest = req\n3157: +\n3158: +\treturn []*clabtypes.ContainerInterfaces{{ContainerName: \"lab1-r1\"}}, nil\n3159: +}\n3160: +\n3161: +func TestCaptureHelpersFillLabAndIdentity(t *testing.T) {\n3162: +\tt.Parallel()\n3163: +\n3164: +\tlr := &captureLabRuntime{}\n3165: +\tc := newAccessTestCLab(lr)\n3166: +\tctx := context.Background()\n3167: +\n3168: +\tinterfaces, err := c.CaptureInterfaces(ctx, \"R1\")\n3169: +\tif err != nil || len(interfaces) != 1 {\n3170: +\t\tt.Fatalf(\"CaptureInterfaces() = %+v, %v\", interfaces, err)\n3171: +\t}\n3172: +\tif lr.nodeRequest.Name != \"lab1\" || lr.nodeRequest.Nodes[0] != \"R1\" ||\n3173: +\t\t!lr.nodeRequest.Identity.Equal(testIdentity) {\n3174: +\t\tt.Fatalf(\"interfaces request = %+v\", lr.nodeRequest)\n3175: +\t}\n3176: +\n3177: +\tvar out bytes.Buffer\n3178: +\tif err := c.Capture(ctx, clablabruntime.CaptureRequest{\n3179: +\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n3180: +\t}, &out); err != nil {\n3181: +\t\tt.Fatal(err)\n3182: +\t}\n3183: +\tif out.String() != \"pcapng\" || lr.captureRequest.Name != \"lab1\" ||\n3184: +\t\t!lr.captureRequest.Identity.Equal(testIdentity) {\n3185: +\t\tt.Fatalf(\"capture request = %+v, output %q\", lr.captureRequest, out.String())\n3186: +\t}\n3187: +\n3188: +\tifaces, err := c.LabRuntimeInterfaces(ctx, \"r1\")\n3189: +\tif err != nil || len(ifaces) != 1 || lr.nodeRequest.Nodes[0] != \"r1\" {\n3190: +\t\tt.Fatalf(\"LabRuntimeInterfaces() = %+v, %v, request %+v\", ifaces, err, lr.nodeRequest)\n3191: +\t}\n3192: +\tif _, err := c.LabRuntimeInterfaces(ctx, \"\"); err != nil || lr.nodeRequest.Nodes != nil {\n3193: +\t\tt.Fatalf(\"all nodes request = %+v, %v\", lr.nodeRequest, err)\n3194: +\t}\n3195: +}\n3196: +\n3197: +// newLocalCaptureCLab loads the capture test topology. Its host and mgmt-net links register\n3198: +// endpoints on link nodes the whole process shares, so the tests using it do not run in\n3199: +// parallel and release the endpoints when they end.\n3200: +func newLocalCaptureCLab(t *testing.T) *CLab {\n3201: +\tt.Helper()\n3202: +\n3203: +\tc, err := NewContainerLab(WithTopoPath(\"test_data/capture.clab.yml\", nil))\n3204: +\tif err != nil {\n3205: +\t\tt.Fatal(err)\n3206: +\t}\n3207: +\tt.Cleanup(c.resetResolvedLinks)\n3208: +\n3209: +\treturn c\n3210: +}\n3211: +\n3212: +func TestLocalCaptureInterfacesComeFromTheTopologyLinks(t *testing.T) {\n3213: +\tc := newLocalCaptureCLab(t)\n3214: +\n3215: +\tgot, err := c.CaptureInterfaces(context.Background(), \"srl1\", \"client\")\n3216: +\tif err != nil {\n3217: +\t\tt.Fatal(err)\n3218: +\t}\n3219: +\twant := []clablabruntime.CaptureInterface{\n3220: +\t\t{Node: \"client\", Interface: \"eth1\", PeerNode: \"srl1\", PeerInterface: \"e1-2\"},\n3221: +\t\t{Node: \"client\", Interface: \"eth2\", PeerNode: \"host\", PeerInterface: \"client-eth2\"},\n3222: +\t\t{Node: \"client\", Interface: \"eth3\", PeerNode: \"mgmt-net\", PeerInterface: \"client-eth3\"},\n3223: +\t\t{\n3224: +\t\t\tNode: \"srl1\", Interface: \"e1-1\", Alias: \"ethernet-1/1\",\n3225: +\t\t\tPeerNode: \"srl2\", PeerInterface: \"e1-1\",\n3226: +\t\t},\n3227: +\t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"client\", PeerInterface: \"eth1\"},\n3228: +\t}\n3229: +\tif !slices.Equal(got, want) {\n3230: +\t\tt.Fatalf(\"CaptureInterfaces() =\\n%+v\\nwant\\n%+v\", got, want)\n3231: +\t}\n3232: +\n3233: +\tif _, err := c.CaptureInterfaces(context.Background(), \"r9\"); err == nil ||\n3234: +\t\t!strings.Contains(err.Error(), `node \"r9\" is not part of lab \"capture\"`) {\n3235: +\t\tt.Fatalf(\"unknown node: error = %v\", err)\n3236: +\t}\n3237: +}\n3238: +\n3239: +func TestLocalCaptureTargetsResolveByNameOrAlias(t *testing.T) {\n3240: +\tc := newLocalCaptureCLab(t)\n3241: +\n3242: +\ttargets, err := c.resolveLocalCaptureTargets([]clablabruntime.CaptureTarget{\n3243: +\t\t{Node: \"srl2\", Interface: \"e1-1\"},\n3244: +\t\t{Node: \"srl1\", Interface: \"ethernet-1/1\"},\n3245: +\t\t{Node: \"clab-capture-client\", Interface: \"eth2\"},\n3246: +\t})\n3247: +\tif err != nil {\n3248: +\t\tt.Fatal(err)\n3249: +\t}\n3250: +\tvar got []string\n3251: +\tfor _, target := range targets {\n3252: +\t\tif target.Exec == nil {\n3253: +\t\t\tt.Fatalf(\"target %s:%s has no namespace exec\", target.Node, target.Interface)\n3254: +\t\t}\n3255: +\t\tgot = append(got, target.Node+\":\"+target.Interface)\n3256: +\t}\n3257: +\tif want := []string{\"srl2:e1-1\", \"srl1:e1-1\", \"client:eth2\"}; !slices.Equal(got, want) {\n3258: +\t\tt.Fatalf(\"targets = %v, want %v\", got, want)\n3259: +\t}\n3260: +\n3261: +\tfor _, tc := range []struct {\n3262: +\t\tname    string\n3263: +\t\ttargets []clablabruntime.CaptureTarget\n3264: +\t\twant    string\n3265: +\t}{\n3266: +\t\t{\n3267: +\t\t\tname:    \"management interface\",\n3268: +\t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"client\", Interface: \"eth0\"}},\n3269: +\t\t\twant: `interface \"eth0\" of node \"client\" is not a capturable link interface; ` +\n3270: +\t\t\t\t\"capturable: eth1, eth2, eth3\",\n3271: +\t\t},\n3272: +\t\t{\n3273: +\t\t\tname: \"same interface twice\",\n3274: +\t\t\ttargets: []clablabruntime.CaptureTarget{\n3275: +\t\t\t\t{Node: \"srl1\", Interface: \"e1-1\"}, {Node: \"srl1\", Interface: \"ethernet-1/1\"},\n3276: +\t\t\t},\n3277: +\t\t\twant: `interface \"e1-1\" of node \"srl1\" is requested more than once`,\n3278: +\t\t},\n3279: +\t\t{\n3280: +\t\t\tname:    \"unknown node\",\n3281: +\t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"r9\", Interface: \"eth1\"}},\n3282: +\t\t\twant:    `node \"r9\" is not part of lab \"capture\"`,\n3283: +\t\t},\n3284: +\t} {\n3285: +\t\tif _, err := c.resolveLocalCaptureTargets(tc.targets); err == nil ||\n3286: +\t\t\t!strings.Contains(err.Error(), tc.want) {\n3287: +\t\t\tt.Errorf(\"%s: error = %v, want %q\", tc.name, err, tc.want)\n3288: +\t\t}\n3289: +\t}\n3290: +}\n3291: +\n3292: +func TestLocalCaptureNeedsTheTopology(t *testing.T) {\n3293: +\tt.Parallel()\n3294: +\n3295: +\tc := &CLab{Config: &Config{Name: \"lab1\"}, globalRuntimeName: \"docker\"}\n3296: +\terr := c.Capture(context.Background(), clablabruntime.CaptureRequest{\n3297: +\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n3298: +\t}, io.Discard)\n3299: +\tif err == nil || !strings.Contains(err.Error(), `the topology of lab \"lab1\" is not available`) {\n3300: +\t\tt.Fatalf(\"error = %v\", err)\n3301: +\t}\n3302: +\tif err := c.Capture(context.Background(), clablabruntime.CaptureRequest{},\n3303: +\t\tio.Discard); err == nil || !strings.Contains(err.Error(), \"at least one capture target\") {\n3304: +\t\tt.Fatalf(\"no targets: error = %v\", err)\n3305: +\t}\n3306: +}\n3307: +\n3308: +func TestLabRuntimeWithoutCaptureFails(t *testing.T) {\n3309: +\tt.Parallel()\n3310: +\n3311: +\tunsupported := newAccessTestCLab(&recordingDestroyLabRuntime{})\n3312: +\tif err := unsupported.Capture(\n3313: +\t\tcontext.Background(),\n3314: +\t\tclablabruntime.CaptureRequest{},\n3315: +\t\tio.Discard,\n3316: +\t); err == nil || !strings.Contains(err.Error(), \"does not support packet capture\") {\n3317: +\t\tt.Fatalf(\"lab runtime without capture: error = %v\", err)\n3318: +\t}\n3319: +}\n3320: diff --git a/core/labruntime_cluster_test.go b/core/labruntime_cluster_test.go\n3321: index 06ecf57..981a302 100644\n3322: --- a/core/labruntime_cluster_test.go\n3323: +++ b/core/labruntime_cluster_test.go\n3324: @@ -1,10 +1,11 @@\n3325:  package core\n3326:  \n3327:  import (\n3328:  \t\"bytes\"\n3329:  \t\"context\"\n3330: +\t\"encoding/binary\"\n3331:  \t\"errors\"\n3332:  \t\"io\"\n3333:  \t\"net\"\n3334:  \t\"net/http\"\n3335:  \t\"os\"\n3336: @@ -175,5 +176,153 @@ func TestC9sClusterNodeAccess(t *testing.T) {\n3337:  \t\tif err == nil || !strings.Contains(err.Error(), \"forbidden\") {\n3338:  \t\t\tt.Fatalf(\"impersonated user without rights: error = %v, want forbidden\", err)\n3339:  \t\t}\n3340:  \t})\n3341:  }\n3342: +\n3343: +// TestC9sClusterCapture captures through the library against a deployed c9s lab, as an identity\n3344: +// that holds only the clabernetes-lab-editor role in the lab namespace. It runs only when\n3345: +// CLAB_C9S_TEST_LAB names the lab and CLAB_C9S_TEST_CAPTURE_USER the identity (tests/14-clabernetes\n3346: +// sets both). The lab must have linux nodes \"client\" (10.10.10.1) and \"server\" (10.10.10.2)\n3347: +// linked by eth1. CLAB_C9S_TEST_FORBIDDEN_USER names an identity without a binding.\n3348: +func TestC9sClusterCapture(t *testing.T) {\n3349: +\tlab := os.Getenv(\"CLAB_C9S_TEST_LAB\")\n3350: +\tuser := os.Getenv(\"CLAB_C9S_TEST_CAPTURE_USER\")\n3351: +\tif lab == \"\" || user == \"\" {\n3352: +\t\tt.Skip(\"CLAB_C9S_TEST_LAB or CLAB_C9S_TEST_CAPTURE_USER is not set\")\n3353: +\t}\n3354: +\n3355: +\tnewCLab := func(t *testing.T, user string) *CLab {\n3356: +\t\tt.Helper()\n3357: +\n3358: +\t\tc, err := NewContainerLab(\n3359: +\t\t\tWithRuntime(clablabruntime.ClabernetesRuntimeName, nil),\n3360: +\t\t\tWithTopologyName(lab),\n3361: +\t\t\tWithLabRuntimeIdentity(clablabruntime.Identity{User: user}),\n3362: +\t\t)\n3363: +\t\tif err != nil {\n3364: +\t\t\tt.Fatal(err)\n3365: +\t\t}\n3366: +\n3367: +\t\treturn c\n3368: +\t}\n3369: +\tc := newCLab(t, user)\n3370: +\n3371: +\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)\n3372: +\tdefer cancel()\n3373: +\n3374: +\tt.Run(\"version check\", func(t *testing.T) {\n3375: +\t\tif err := c.CheckLabRuntimeSupport(ctx); err != nil {\n3376: +\t\t\tt.Fatal(err)\n3377: +\t\t}\n3378: +\t})\n3379: +\n3380: +\tt.Run(\"capture interfaces\", func(t *testing.T) {\n3381: +\t\tinterfaces, err := c.CaptureInterfaces(ctx)\n3382: +\t\tif err != nil {\n3383: +\t\t\tt.Fatal(err)\n3384: +\t\t}\n3385: +\t\twant := []clablabruntime.CaptureInterface{\n3386: +\t\t\t{Node: \"client\", Interface: \"eth1\", PeerNode: \"server\", PeerInterface: \"eth1\"},\n3387: +\t\t\t{Node: \"server\", Interface: \"eth1\", PeerNode: \"client\", PeerInterface: \"eth1\"},\n3388: +\t\t}\n3389: +\t\tif len(interfaces) != 2 || interfaces[0] != want[0] || interfaces[1] != want[1] {\n3390: +\t\t\tt.Fatalf(\"interfaces = %+v\", interfaces)\n3391: +\t\t}\n3392: +\t})\n3393: +\n3394: +\tt.Run(\"capture both ends of a link\", func(t *testing.T) {\n3395: +\t\tpinged := make(chan error, 1)\n\n(Showing lines 2766-3395 of 7018. Use offset=3396 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+\tnodeNames ...string,\n+) ([]clablabruntime.CaptureInterface, error) {\n+\tif c.LabRuntime == nil {\n+\t\treturn c.localCaptureInterfacesOf(ctx, nodeNames)\n+\t}\n+\n+\tcapturer, err := c.packetCapturer()\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treturn capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{\n+\t\tName:     c.Config.Name,\n+\t\tNodes:    nodeNames,\n+\t\tIdentity: c.labRuntimeIdentity,\n+\t})\n+}\n+\n+// Capture streams pcapng from lab link interfaces to w until req.Duration passed,\n+// req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+\tnodeNames ...string,\n+) ([]clablabruntime.CaptureInterface, error) {\n+\tif c.LabRuntime == nil {\n+\t\treturn c.localCaptureInterfacesOf(ctx, nodeNames)\n+\t}\n+\n+\tcapturer, err := c.packetCapturer()\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treturn capturer.CaptureInterfaces(ctx, clablabruntime.NodeRequest{\n+\t\tName:     c.Config.Name,\n+\t\tNodes:    nodeNames,\n+\t\tIdentity: c.labRuntimeIdentity,\n+\t})\n+}\n+\n+// Capture streams pcapng from lab link interfaces to w until req.Duration passed,\n+// req.PacketLimit packets were written or ctx ends; an ended ctx is not an error. The lab name\n+// and identity default to the CLab's. With Docker and Podman, containerlab reads the interfaces\n+// itself through packet sockets in the nodes' network namespaces, which needs root; lab\n+// runtimes capture through their packet capturer.\n+func (c *CLab) Capture(ctx context.Context, req clablabruntime.CaptureRequest, w io.Writer) error {\n+\tif c.LabRuntime == nil {\n+\t\treturn c.captureLocal(ctx, req, w)\n+\t}\n+\n+\tcapturer, err := c.packetCapturer()\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tif req.Name == \"\" {\n+\t\treq.Name = c.Config.Name\n+\t}\n+\tif req.Identity.IsZero() {\n+\t\treq.Identity = c.labRuntimeIdentity\n+\t}\n+\n+\treturn capturer.Capture(ctx, req, w)\n+}\n+\n+// LabRuntimeInterfaces lists the link interfaces of the lab's nodes, or of one node, with their\n+// state, in the shape ListContainersInterfaces reports for local containers.\n+func (c *CLab) LabRuntimeInterfaces(\n+\tctx context.Context,\n+\tnodeName string,\n+) ([]*clabtypes.ContainerInterfaces, error) {\n+\tinspector, err := labRuntimeCapability[clablabruntime.InterfaceInspector](\n+\t\tc, \"inspecting interfaces\")\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tif err := c.requireLabName(); err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treq := clablabruntime.NodeRequest{Name: c.Config.Name, Identity: c.labRuntimeIdentity}\n+\tif nodeName != \"\" {\n+\t\treq.Nodes = []string{nodeName}\n+\t}\n+\n+\treturn inspector.InspectInterfaces(ctx, req)\n+}\n+\n+func (c *CLab) packetCapturer() (clablabruntime.PacketCapturer, error) {\n+\tcapturer, err := labRuntimeCapability[clablabruntime.PacketCapturer](c, \"packet capture\")\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tif err := c.requireLabName(); err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treturn capturer, nil\n+}\ndiff --git a/core/capture_local.go b/core/capture_local.go\nnew file mode 100644\nindex 0000000..fada0bf\n--- /dev/null\n+++ b/core/capture_local.go\n@@ -0,0 +1,255 @@\n+package core\n+\n+import (\n+\t\"context\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"slices\"\n+\t\"sort\"\n+\t\"strings\"\n+\n+\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tclablinks \"github.com/srl-labs/containerlab/links\"\n+\tclabnodes \"github.com/srl-labs/containerlab/nodes\"\n+\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n+)\n+\n+// localCaptureInterface is a lab link interface of a node on this machine.\n+type localCaptureInterface struct {\n+\tnode clabnodes.Node\n+\tinfo clablabruntime.CaptureInterface\n+}\n+\n+// localCaptureInterfaces lists the link interfaces of the lab's nodes the topology defines, with\n+// the far end of each link, per node name. Host and management network endpoints are the far\n+// ends of links, not nodes to capture on.\n+func (c *CLab) localCaptureInterfaces() (map[string][]localCaptureInterface, error) {\n+\tif len(c.Nodes) == 0 {\n+\t\treturn nil, fmt.Errorf(\"the topology of lab %q is not available; capture reads the \"+\n+\t\t\t\"lab's links from it, pass it with --topo\", c.Config.Name)\n+\t}\n+\tif len(c.Links) == 0 {\n+\t\tif err := c.ResolveLinks(); err != nil {\n+\t\t\treturn nil, fmt.Errorf(\"failed to resolve the links of lab %q: %w\", c.Config.Name, err)\n+\t\t}\n+\t}\n+\n+\tindexes := make([]int, 0, len(c.Links))\n+\tfor idx := range c.Links {\n+\t\tindexes = append(indexes, idx)\n+\t}\n+\tsort.Ints(indexes)\n+\n+\tresult := map[string][]localCaptureInterface{}\n+\tfor _, idx := range indexes {\n+\t\tendpoints := c.Links[idx].GetEndpoints()\n+\t\tfor epIdx, endpoint := range endpoints {\n+\t\t\tif endpoint.IsNodeless() || endpoint.IsRuntimeDiscovered() ||\n+\t\t\t\tendpoint.GetNode() == nil {\n+\t\t\t\tcontinue\n+\t\t\t}\n+\t\t\tname := endpoint.GetNode().GetShortName()\n+\t\t\tnode, ok := c.Nodes[name]\n+\t\t\tif !ok {\n+\t\t\t\tcontinue\n+\t\t\t}\n+\n+\t\t\tinfo := clablabruntime.CaptureInterface{\n+\t\t\t\tNode:      name,\n+\t\t\t\tInterface: endpoint.GetIfaceName(),\n+\t\t\t}\n+\t\t\tif alias := endpoint.GetIfaceAlias(); alias != info.Interface {\n+\t\t\t\tinfo.Alias = alias\n+\t\t\t}\n+\t\t\tif len(endpoints) == 2 {\n+\t\t\t\tpeer := endpoints[1-epIdx]\n+\t\t\t\tinfo.PeerNode = capturePeerNode(peer)\n+\t\t\t\tinfo.PeerInterface = peer.GetIfaceDisplayName()\n+\t\t\t}\n+\n+\t\t\tresult[name] = append(result[name], localCaptureInterface{node: node, info: info})\n+\t\t}\n+\t}\n+\n+\treturn result, nil\n+}\n+\n+// capturePeerNode names the node at the far end of a link: \"host\" for a host endpoint and\n+// \"mgmt-net\" for the management network, whose shared link nodes carry other names once a lab\n+// was deployed.\n+func capturePeerNode(peer clablinks.Endpoint) string {\n+\tif peer.IsNodeless() {\n+\t\tif _, ok := peer.(*clablinks.EndpointBridge); ok {\n+\t\t\treturn string(clablinks.LinkTypeMgmtNet)\n+\t\t}\n+\n+\t\treturn string(clablinks.LinkTypeHost)\n+\t}\n+\tif peer.GetNode() == nil {\n+\t\treturn \"\"\n+\t}\n+\n+\treturn peer.GetNode().GetShortName()\n+}\n+\n+// lookupLocalNode finds a lab node by its topology name or its container name.\n+func (c *CLab) lookupLocalNode(name string) (clabnodes.Node, error) {\n+\tif node, ok := c.Nodes[name]; ok {\n+\t\treturn node, nil\n+\t}\n+\tfor _, node := range c.Nodes {\n+\t\tif node.Config().LongName == name {\n+\t\t\treturn node, nil\n+\t\t}\n+\t}\n+\n+\tnames := make([]string, 0, len(c.Nodes))\n+\tfor nodeName := range c.Nodes {\n+\t\tnames = append(names, nodeName)\n+\t}\n+\tslices.Sort(names)\n+\n+\treturn nil, fmt.Errorf(\"node %q is not part of lab %q; nodes: %s\", name, c.Config.Name,\n+\t\tstrings.Join(names, \", \"))\n+}\n+\n+// nodeRuns reports whether a node's network namespace can be entered.\n+func nodeRuns(ctx context.Context, node clabnodes.Node) bool {\n+\tif node.Config().IsRootNamespaceBased {\n+\t\treturn true\n+\t}\n+\n+\treturn clabruntime.ContainerHasJoinableNetns(node.GetContainerStatus(ctx))\n+}\n+\n+// localCaptureInterfacesOf implements CaptureInterfaces for Docker and Podman: the requested\n+// nodes, or every running node.\n+func (c *CLab) localCaptureInterfacesOf(\n+\tctx context.Context,\n+\tnodeNames []string,\n+) ([]clablabruntime.CaptureInterface, error) {\n+\tif err := c.requireLabName(); err != nil {\n+\t\treturn nil, err\n+\t}\n+\tbyNode, err := c.localCaptureInterfaces()\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\tvar nodes []clabnodes.Node\n+\tif len(nodeNames) == 0 {\n+\t\tfor _, node := range c.Nodes {\n+\t\t\tif nodeRuns(ctx, node) {\n+\t\t\t\tnodes = append(nodes, node)\n+\t\t\t}\n+\t\t}\n+\t} else {\n+\t\tfor _, name := range nodeNames {\n+\t\t\tnode, err := c.lookupLocalNode(name)\n+\t\t\tif err != nil {\n+\t\t\t\treturn nil, err\n+\t\t\t}\n+\t\t\tnodes = append(nodes, node)\n+\t\t}\n+\t}\n+\n+\tresult := make([]clablabruntime.CaptureInterface, 0)\n+\tseen := map[string]bool{}\n+\tfor _, node := range nodes {\n+\t\tname := node.Config().ShortName\n+\t\tif seen[name] {\n+\t\t\tcontinue\n+\t\t}\n+\t\tseen[name] = true\n+\t\tfor _, entry := range byNode[name] {\n+\t\t\tresult = append(result, entry.info)\n+\t\t}\n+\t}\n+\tsortCaptureInterfaces(result)\n+\n+\treturn result, nil\n+}\n+\n+func sortCaptureInterfaces(interfaces []clablabruntime.CaptureInterface) {\n+\tsort.SliceStable(interfaces, func(i, j int) bool {\n+\t\tif interfaces[i].Node != interfaces[j].Node {\n+\t\t\treturn interfaces[i].Node < interfaces[j].Node\n+\t\t}\n+\n+\t\treturn interfaces[i].Interface < interfaces[j].Interface\n+\t})\n+}\n+\n+// resolveLocalCaptureTargets checks every target against the node's link interfaces, by name or\n+// alias, and returns them in request order.\n+func (c *CLab) resolveLocalCaptureTargets(\n+\ttargets []clablabruntime.CaptureTarget,\n+) ([]clabcapture.LocalTarget, error) {\n+\tbyNode, err := c.localCaptureInterfaces()\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\tresolved := make([]clabcapture.LocalTarget, 0, len(targets))\n+\tseen := map[string]bool{}\n+\tfor _, target := range targets {\n+\t\tnode, err := c.lookupLocalNode(target.Node)\n+\t\tif err != nil {\n+\t\t\treturn nil, err\n+\t\t}\n+\t\tname := node.Config().ShortName\n+\n+\t\tinfos := make([]clablabruntime.CaptureInterface, 0, len(byNode[name]))\n+\t\tfor _, entry := range byNode[name] {\n+\t\t\tinfos = append(infos, entry.info)\n+\t\t}\n+\t\tsortCaptureInterfaces(infos)\n+\t\tinfo, ok := clabcapture.FindInterface(infos, target.Interface)\n+\t\tif !ok {\n+\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n+\t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n+\t\t\t\tclabcapture.DescribeInterfaces(infos))\n+\t\t}\n+\n+\t\tkey := name + \"\\x00\" + info.Interface\n+\t\tif seen[key] {\n+\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n+\t\t\t\tinfo.Interface, target.Node)\n+\t\t}\n+\t\tseen[key] = true\n+\n+\t\tresolved = append(resolved, clabcapture.LocalTarget{\n+\t\t\tNode:      name,\n+\t\t\tInterface: info.Interface,\n+\t\t\tExec:      node.ExecFunction,\n+\t\t})\n+\t}\n+\n+\treturn resolved, nil\n+}\n+\n+// captureLocal implements Capture for Docker and Podman through packet sockets in the nodes'\n+// network namespaces.\n+func (c *CLab) captureLocal(\n+\tctx context.Context,\n+\treq clablabruntime.CaptureRequest,\n+\tw io.Writer,\n+) error {\n+\tif err := c.requireLabName(); err != nil {\n+\t\treturn err\n+\t}\n+\tif req.Name == \"\" {\n+\t\treq.Name = c.Config.Name\n+\t}\n+\tif err := clabcapture.ValidateRequest(&req); err != nil {\n+\t\treturn err\n+\t}\n+\n+\ttargets, err := c.resolveLocalCaptureTargets(req.Targets)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\treturn clabcapture.CaptureLocal(ctx, req, targets, w)\n+}\ndiff --git a/core/capture_test.go b/core/capture_test.go\nnew file mode 100644\nindex 0000000..b5d34b0\n--- /dev/null\n+++ b/core/capture_test.go\n@@ -0,0 +1,210 @@\n+package core\n+\n+import (\n+\t\"bytes\"\n+\t\"context\"\n+\t\"io\"\n+\t\"slices\"\n+\t\"strings\"\n+\t\"testing\"\n+\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tclabtypes \"github.com/srl-labs/containerlab/types\"\n+)\n+\n+// captureLabRuntime records the capture requests core sends.\n+type captureLabRuntime struct {\n+\tclablabruntime.LabRuntime\n+\n+\tnodeRequest    clablabruntime.NodeRequest\n+\tcaptureRequest clablabruntime.CaptureRequest\n+}\n+\n+func (r *captureLabRuntime) CaptureInterfaces(\n+\t_ context.Context,\n+\treq clablabruntime.NodeRequest,\n+) ([]clablabruntime.CaptureInterface, error) {\n+\tr.nodeRequest = req\n+\n+\treturn []clablabruntime.CaptureInterface{{Node: \"r1\", Interface: \"eth1\"}}, nil\n+}\n+\n+func (r *captureLabRuntime) Capture(\n+\t_ context.Context,\n+\treq clablabruntime.CaptureRequest,\n+\tw io.Writer,\n+) error {\n+\tr.captureRequest = req\n+\t_, err := io.WriteString(w, \"pcapng\")\n+\n+\treturn err\n+}\n+\n+func (r *captureLabRuntime) InspectInterfaces(\n+\t_ context.Context,\n+\treq clablabruntime.NodeRequest,\n+) ([]*clabtypes.ContainerInterfaces, error) {\n+\tr.nodeRequest = req\n+\n+\treturn []*clabtypes.ContainerInterfaces{{ContainerName: \"lab1-r1\"}}, nil\n+}\n+\n+func TestCaptureHelpersFillLabAndIdentity(t *testing.T) {\n+\tt.Parallel()\n+\n+\tlr := &captureLabRuntime{}\n+\tc := newAccessTestCLab(lr)\n+\tctx := context.Background()\n+\n+\tinterfaces, err := c.CaptureInterfaces(ctx, \"R1\")\n+\tif err != nil || len(interfaces) != 1 {\n+\t\tt.Fatalf(\"CaptureInterfaces() = %+v, %v\", interfaces, err)\n+\t}\n+\tif lr.nodeRequest.Name != \"lab1\" || lr.nodeRequest.Nodes[0] != \"R1\" ||\n+\t\t!lr.nodeRequest.Identity.Equal(testIdentity) {\n+\t\tt.Fatalf(\"interfaces request = %+v\", lr.nodeRequest)\n+\t}\n+\n+\tvar out bytes.Buffer\n+\tif err := c.Capture(ctx, clablabruntime.CaptureRequest{\n+\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n+\t}, &out); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif out.String() != \"pcapng\" || lr.captureRequest.Name != \"lab1\" ||\n+\t\t!lr.captureRequest.Identity.Equal(testIdentity) {\n+\t\tt.Fatalf(\"capture request = %+v, output %q\", lr.captureRequest, out.String())\n+\t}\n+\n+\tifaces, err := c.LabRuntimeInterfaces(ctx, \"r1\")\n+\tif err != nil || len(ifaces) != 1 || lr.nodeRequest.Nodes[0] != \"r1\" {\n+\t\tt.Fatalf(\"LabRuntimeInterfaces() = %+v, %v, request %+v\", ifaces, err, lr.nodeRequest)\n+\t}\n+\tif _, err := c.LabRuntimeInterfaces(ctx, \"\"); err != nil || lr.nodeRequest.Nodes != nil {\n+\t\tt.Fatalf(\"all nodes request = %+v, %v\", lr.nodeRequest, err)\n+\t}\n+}\n+\n+// newLocalCaptureCLab loads the capture test topology. Its host and mgmt-net links register\n+// endpoints on link nodes the whole process shares, so the tests using it do not run in\n+// parallel and release the endpoints when they end.\n+func newLocalCaptureCLab(t *testing.T) *CLab {\n+\tt.Helper()\n+\n+\tc, err := NewContainerLab(WithTopoPath(\"test_data/capture.clab.yml\", nil))\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tt.Cleanup(c.resetResolvedLinks)\n+\n+\treturn c\n+}\n+\n+func TestLocalCaptureInterfacesComeFromTheTopologyLinks(t *testing.T) {\n+\tc := newLocalCaptureCLab(t)\n+\n+\tgot, err := c.CaptureInterfaces(context.Background(), \"srl1\", \"client\")\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\twant := []clablabruntime.CaptureInterface{\n+\t\t{Node: \"client\", Interface: \"eth1\", PeerNode: \"srl1\", PeerInterface: \"e1-2\"},\n+\t\t{Node: \"client\", Interface: \"eth2\", PeerNode: \"host\", PeerInterface: \"client-eth2\"},\n+\t\t{Node: \"client\", Interface: \"eth3\", PeerNode: \"mgmt-net\", PeerInterface: \"client-eth3\"},\n+\t\t{\n+\t\t\tNode: \"srl1\", Interface: \"e1-1\", Alias: \"ethernet-1/1\",\n+\t\t\tPeerNode: \"srl2\", PeerInterface: \"e1-1\",\n+\t\t},\n+\t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"client\", PeerInterface: \"eth1\"},\n+\t}\n+\tif !slices.Equal(got, want) {\n+\t\tt.Fatalf(\"CaptureInterfaces() =\\n%+v\\nwant\\n%+v\", got, want)\n+\t}\n+\n+\tif _, err := c.CaptureInterfaces(context.Background(), \"r9\"); err == nil ||\n+\t\t!strings.Contains(err.Error(), `node \"r9\" is not part of lab \"capture\"`) {\n+\t\tt.Fatalf(\"unknown node: error = %v\", err)\n+\t}\n+}\n+\n+func TestLocalCaptureTargetsResolveByNameOrAlias(t *testing.T) {\n+\tc := newLocalCaptureCLab(t)\n+\n+\ttargets, err := c.resolveLocalCaptureTargets([]clablabruntime.CaptureTarget{\n+\t\t{Node: \"srl2\", Interface: \"e1-1\"},\n+\t\t{Node: \"srl1\", Interface: \"ethernet-1/1\"},\n+\t\t{Node: \"clab-capture-client\", Interface: \"eth2\"},\n+\t})\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tvar got []string\n+\tfor _, target := range targets {\n+\t\tif target.Exec == nil {\n+\t\t\tt.Fatalf(\"target %s:%s has no namespace exec\", target.Node, target.Interface)\n+\t\t}\n+\t\tgot = append(got, target.Node+\":\"+target.Interface)\n+\t}\n+\tif want := []string{\"srl2:e1-1\", \"srl1:e1-1\", \"client:eth2\"}; !slices.Equal(got, want) {\n+\t\tt.Fatalf(\"targets = %v, want %v\", got, want)\n+\t}\n+\n+\tfor _, tc := range []struct {\n+\t\tname    string\n+\t\ttargets []clablabruntime.CaptureTarget\n+\t\twant    string\n+\t}{\n+\t\t{\n+\t\t\tname:    \"management interface\",\n+\t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"client\", Interface: \"eth0\"}},\n+\t\t\twant: `interface \"eth0\" of node \"client\" is not a capturable link interface; ` +\n+\t\t\t\t\"capturable: eth1, eth2, eth3\",\n+\t\t},\n+\t\t{\n+\t\t\tname: \"same interface twice\",\n+\t\t\ttargets: []clablabruntime.CaptureTarget{\n+\t\t\t\t{Node: \"srl1\", Interface: \"e1-1\"}, {Node: \"srl1\", Interface: \"ethernet-1/1\"},\n+\t\t\t},\n+\t\t\twant: `interface \"e1-1\" of node \"srl1\" is requested more than once`,\n+\t\t},\n+\t\t{\n+\t\t\tname:    \"unknown node\",\n+\t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"r9\", Interface: \"eth1\"}},\n+\t\t\twant:    `node \"r9\" is not part of lab \"capture\"`,\n+\t\t},\n+\t} {\n+\t\tif _, err := c.resolveLocalCaptureTargets(tc.targets); err == nil ||\n+\t\t\t!strings.Contains(err.Error(), tc.want) {\n+\t\t\tt.Errorf(\"%s: error = %v, want %q\", tc.name, err, tc.want)\n+\t\t}\n+\t}\n+}\n+\n+func TestLocalCaptureNeedsTheTopology(t *testing.T) {\n+\tt.Parallel()\n+\n+\tc := &CLab{Config: &Config{Name: \"lab1\"}, globalRuntimeName: \"docker\"}\n+\terr := c.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n+\t}, io.Discard)\n+\tif err == nil || !strings.Contains(err.Error(), `the topology of lab \"lab1\" is not available`) {\n+\t\tt.Fatalf(\"error = %v\", err)\n+\t}\n+\tif err := c.Capture(context.Background(), clablabruntime.CaptureRequest{},\n+\t\tio.Discard); err == nil || !strings.Contains(err.Error(), \"at least one capture target\") {\n+\t\tt.Fatalf(\"no targets: error = %v\", err)\n+\t}\n+}\n+\n+func TestLabRuntimeWithoutCaptureFails(t *testing.T) {\n+\tt.Parallel()\n+\n+\tunsupported := newAccessTestCLab(&recordingDestroyLabRuntime{})\n+\tif err := unsupported.Capture(\n+\t\tcontext.Background(),\n+\t\tclablabruntime.CaptureRequest{},\n+\t\tio.Discard,\n+\t); err == nil || !strings.Contains(err.Error(), \"does not support packet capture\") {\n+\t\tt.Fatalf(\"lab runtime without capture: error = %v\", err)\n+\t}\n+}\ndiff --git a/core/labruntime_cluster_test.go b/core/labruntime_cluster_test.go\nindex 06ecf57..981a302 100644\n--- a/core/labruntime_cluster_test.go\n+++ b/core/labruntime_cluster_test.go\n@@ -1,10 +1,11 @@\n package core\n \n import (\n \t\"bytes\"\n \t\"context\"\n+\t\"encoding/binary\"\n \t\"errors\"\n \t\"io\"\n \t\"net\"\n \t\"net/http\"\n \t\"os\"\n@@ -175,5 +176,153 @@ func TestC9sClusterNodeAccess(t *testing.T) {\n \t\tif err == nil || !strings.Contains(err.Error(), \"forbidden\") {\n \t\t\tt.Fatalf(\"impersonated user without rights: error = %v, want forbidden\", err)\n \t\t}\n \t})\n }\n+\n+// TestC9sClusterCapture captures through the library against a deployed c9s lab, as an identity\n+// that holds only the clabernetes-lab-editor role in the lab namespace. It runs only when\n+// CLAB_C9S_TEST_LAB names the lab and CLAB_C9S_TEST_CAPTURE_USER the identity (tests/14-clabernetes\n+// sets both). The lab must have linux nodes \"client\" (10.10.10.1) and \"server\" (10.10.10.2)\n+// linked by eth1. CLAB_C9S_TEST_FORBIDDEN_USER names an identity without a binding.\n+func TestC9sClusterCapture(t *testing.T) {\n+\tlab := os.Getenv(\"CLAB_C9S_TEST_LAB\")\n+\tuser := os.Getenv(\"CLAB_C9S_TEST_CAPTURE_USER\")\n+\tif lab == \"\" || user == \"\" {\n+\t\tt.Skip(\"CLAB_C9S_TEST_LAB or CLAB_C9S_TEST_CAPTURE_USER is not set\")\n+\t}\n+\n+\tnewCLab := func(t *testing.T, user string) *CLab {\n+\t\tt.Helper()\n+\n+\t\tc, err := NewContainerLab(\n+\t\t\tWithRuntime(clablabruntime.ClabernetesRuntimeName, nil),\n+\t\t\tWithTopologyName(lab),\n+\t\t\tWithLabRuntimeIdentity(clablabruntime.Identity{User: user}),\n+\t\t)\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\n+\t\treturn c\n+\t}\n+\tc := newCLab(t, user)\n+\n+\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)\n+\tdefer cancel()\n+\n+\tt.Run(\"version check\", func(t *testing.T) {\n+\t\tif err := c.CheckLabRuntimeSupport(ctx); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t})\n+\n+\tt.Run(\"capture interfaces\", func(t *testing.T) {\n+\t\tinterfaces, err := c.CaptureInterfaces(ctx)\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\twant := []clablabruntime.CaptureInterface{\n+\t\t\t{Node: \"client\", Interface: \"eth1\", PeerNode: \"server\", PeerInterface: \"eth1\"},\n+\t\t\t{Node: \"server\", Interface: \"eth1\", PeerNode: \"client\", PeerInterface: \"eth1\"},\n+\t\t}\n+\t\tif len(interfaces) != 2 || interfaces[0] != want[0] || interfaces[1] != want[1] {\n+\t\t\tt.Fatalf(\"interfaces = %+v\", interfaces)\n+\t\t}\n+\t})\n+\n+\tt.Run(\"capture both ends of a link\", func(t *testing.T) {\n+\t\tpinged := make(chan error, 1)",
        "lineStart": 2766,
        "lineEnd": 3395,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523438055,
      "end": 1793523438073
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19653d1fc001Xbe9Gyts6KFCfZ",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653c6d2001LmjgFru5WWr30l",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 40011,
    "input": 8010,
    "output": 28,
    "reasoning": 165,
    "cache": {
      "read": 31808,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19653c6d2001LmjgFru5WWr30l",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523435218,
    "completed": 1793523438079
  },
  "parentID": "msg_19653b129001cj4QAfxRVtxTFM",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 40011,
    "input": 8010,
    "output": 28,
    "reasoning": 165,
    "cache": {
      "read": 31808,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 47
step-start
{
  "type": "step-start",
  "id": "prt_19653d92c001k7MtqkKOPekgfe",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653d207001b0N0fJzxFIZN83"
}
Reasoning
Continue with the diff: 3396-3520 (rest of labruntime_cluster_test.go + test_data + docs start), then docs 3511-3900, then the big labruntime region 3900-7018. Let me read 3396-3960.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 580,
  "offset": 3396
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
3396: +		go func() {
3397: +			time.Sleep(time.Second)
3398: +			pinged <- c.AttachLabRuntimeNode(ctx, clablabruntime.AttachRequest{
3399: +				NodeName: "client",
3400: +				Command:  []string{"ping", "-c", "4", "-i", "0.3", "10.10.10.2"},
3401: +			}, clablabruntime.AttachStreams{Stdout: io.Discard})
3402: +		}()
3403: +
3404: +		var out bytes.Buffer
3405: +		err := c.Capture(ctx, clablabruntime.CaptureRequest{
3406: +			Targets: []clablabruntime.CaptureTarget{
3407: +				{Node: "client", Interface: "eth1"}, {Node: "server", Interface: "eth1"},
3408: +			},
3409: +			Duration: 5 * time.Second,
3410: +		}, &out)
3411: +		if err != nil {
3412: +			t.Fatal(err)
3413: +		}
3414: +		if err := <-pinged; err != nil {
3415: +			t.Fatalf("ping: %v", err)
3416: +		}
3417: +
3418: +		names, icmp := summarizePCAPNG(t, out.Bytes())
3419: +		if len(names) != 2 || names[0] != "client:eth1" || names[1] != "server:eth1" {
3420: +			t.Fatalf("interfaces = %v", names)
3421: +		}
3422: +		// every echo request and reply crosses both ends
3423: +		if icmp[0] < 8 || icmp[1] < 8 {
3424: +			t.Fatalf("ICMP packets per interface = %v, want at least 8 on each", icmp)
3425: +		}
3426: +	})
3427: +
3428: +	t.Run("restart as lab editor", func(t *testing.T) {
3429: +		if err := c.RestartNodes(ctx, []string{"server"}); err != nil {
3430: +			t.Fatal(err)
3431: +		}
3432: +	})
3433: +
3434: +	t.Run("forbidden identity", func(t *testing.T) {
3435: +		forbidden := os.Getenv("CLAB_C9S_TEST_FORBIDDEN_USER")
3436: +		if forbidden == "" {
3437: +			t.Skip("CLAB_C9S_TEST_FORBIDDEN_USER is not set")
3438: +		}
3439: +
3440: +		err := newCLab(t, forbidden).Capture(ctx, clablabruntime.CaptureRequest{
3441: +			Targets:  []clablabruntime.CaptureTarget{{Node: "client", Interface: "eth1"}},
3442: +			Duration: time.Second,
3443: +		}, io.Discard)
3444: +		if err == nil || !strings.Contains(err.Error(), "forbidden") {
3445: +			t.Fatalf("capture as %s = %v, want forbidden", forbidden, err)
3446: +		}
3447: +	})
3448: +}
3449: +
3450: +// summarizePCAPNG returns the interface names of a little-endian pcapng stream and its IPv4 ICMP
3451: +// packets per interface ID.
3452: +func summarizePCAPNG(t *testing.T, data []byte) ([]string, map[uint32]int) {
3453: +	t.Helper()
3454: +
3455: +	var names []string
3456: +	icmp := map[uint32]int{}
3457: +	for len(data) >= 12 {
3458: +		blockType := binary.LittleEndian.Uint32(data[0:4])
3459: +		length := int(binary.LittleEndian.Uint32(data[4:8]))
3460: +		if length < 12 || length > len(data) {
3461: +			t.Fatalf("invalid block length %d", length)
3462: +		}
3463: +		body := data[8 : length-4]
3464: +		switch blockType {
3465: +		case 1: // Interface Description Block
3466: +			options := body[8:]
3467: +			for len(options) >= 4 {
3468: +				code := binary.LittleEndian.Uint16(options[0:2])
3469: +				size := int(binary.LittleEndian.Uint16(options[2:4]))
3470: +				if code == 0 {
3471: +					break
3472: +				}
3473: +				if code == 2 {
3474: +					names = append(names, string(options[4:4+size]))
3475: +				}
3476: +				options = options[4+size+(4-size%4)%4:]
3477: +			}
3478: +		case 6: // Enhanced Packet Block
3479: +			id := binary.LittleEndian.Uint32(body[0:4])
3480: +			frame := body[20 : 20+binary.LittleEndian.Uint32(body[12:16])]
3481: +			if len(frame) > 23 && frame[12] == 0x08 && frame[13] == 0x00 && frame[23] == 1 {
3482: +				icmp[id]++
3483: +			}
3484: +		}
3485: +		data = data[length:]
3486: +	}
3487: +
3488: +	return names, icmp
3489: +}
3490: diff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml
3491: new file mode 100644
3492: index 0000000..0422c22
3493: --- /dev/null
3494: +++ b/core/test_data/capture.clab.yml
3495: @@ -0,0 +1,15 @@
3496: +name: capture
3497: +topology:
3498: +  nodes:
3499: +    srl1:
3500: +      kind: nokia_srlinux
3501: +    srl2:
3502: +      kind: nokia_srlinux
3503: +    client:
3504: +      kind: linux
3505: +      image: alpine:3
3506: +  links:
3507: +    - endpoints: ["srl1:ethernet-1/1", "srl2:e1-1"]
3508: +    - endpoints: ["srl1:e1-2", "client:eth1"]
3509: +    - endpoints: ["client:eth2", "host:client-eth2"]
3510: +    - endpoints: ["client:eth3", "mgmt-net:client-eth3"]
3511: diff --git a/docs/cmd/capture.md b/docs/cmd/capture.md
3512: new file mode 100644
3513: index 0000000..15006ff
3514: --- /dev/null
3515: +++ b/docs/cmd/capture.md
3516: @@ -0,0 +1,134 @@
3517: +# capture command
3518: +
3519: +### Description
3520: +
3521: +The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.
3522: +
3523: +It works with every runtime:
3524: +
3525: +- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).
3526: +- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).
3527: +
3528: +The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.
3529: +
3530: +--8<-- "docs/cmd/deploy.md:env-vars-flags"
3531: +
3532: +### Usage
3533: +
3534: +`containerlab [global-flags] capture [local-flags]`
3535: +
3536: +### Flags
3537: +
3538: +#### topology | name
3539: +
3540: +Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.
3541: +
3542: +With Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.
3543: +
3544: +#### target
3545: +
3546: +The local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:
3547: +
3548: +```text
3549: +--target srl1:e1-1,e1-2 --target srl2:e1-1
3550: +```
3551: +
3552: +The node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.
3553: +
3554: +Only lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.
3555: +
3556: +#### duration
3557: +
3558: +The local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).
3559: +
3560: +#### packet-limit
3561: +
3562: +The local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.
3563: +
3564: +#### snap-length
3565: +
3566: +The local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.
3567: +
3568: +#### write
3569: +
3570: +The local `--write | -w` flag names the output file. The default `-` writes to stdout.
3571: +
3572: +#### list
3573: +
3574: +The local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.
3575: +
3576: +### Output
3577: +
3578: +The output is one pcapng section:
3579: +
3580: +- a Section Header Block with `shb_userappl` set to `containerlab`
3581: +- one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it
3582: +- Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes
3583: +
3584: +The interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.
3585: +
3586: +When the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.
3587: +
3588: +`--list -f json` prints an array:
3589: +
3590: +```json
3591: +[
3592: +  {
3593: +    "node": "srl1",
3594: +    "interface": "e1-1",
3595: +    "alias": "ethernet-1/1",
3596: +    "peer_node": "srl2",
3597: +    "peer_interface": "ethernet-1/1"
3598: +  }
3599: +]
3600: +```
3601: +
3602: +`alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.
3603: +
3604: +### How Docker and Podman captures work
3605: +
3606: +For each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.
3607: +
3608: +- Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.
3609: +- 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.
3610: +- Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.
3611: +- An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.
3612: +
3613: +The command needs root (to open packet sockets and enter network namespaces), as other lab commands do.
3614: +
3615: +### Long captures
3616: +
3617: +Docker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.
3618: +
3619: +### Examples
3620: +
3621: +#### Capture two nodes for 30 seconds into one file
3622: +
3623: +```bash
3624: +containerlab capture -t srl.clab.yml \
3625: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng
3626: +```
3627: +
3628: +#### Watch a capture live in Wireshark
3629: +
3630: +```bash
3631: +containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -
3632: +```
3633: +
3634: +#### Capture the first 100 packets with tshark
3635: +
3636: +```bash
3637: +containerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -
3638: +```
3639: +
3640: +#### List the capturable interfaces
3641: +
3642: +```bash
3643: +containerlab capture --name srl --list
3644: +```
3645: +
3646: +#### Capture a c9s lab
3647: +
3648: +```bash
3649: +containerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng
3650: +```
3651: diff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md
3652: index 3dc8e27..2354dc1 100644
3653: --- a/docs/cmd/inspect/interfaces.md
3654: +++ b/docs/cmd/inspect/interfaces.md
3655: @@ -3,10 +3,12 @@
3656:  ### Description
3657:  
3658:  The `inspect interfaces` subcommand provides information about the network interfaces of deployed nodes of a deployed lab.
3659:  The subcommand gathers information directly from deployed containers, and displays information about their operational state, network interface type, and if applicable, the applied network interface alias.
3660:  
3661: +With the [c9s runtime](../../manual/clabernetes/runtime.md#packet-capture), the listing covers the lab link interfaces of each running node, the ones [`capture`](../capture.md) accepts, with the alias the topology used, and the MAC address, index, MTU and operational state read in the node's device container. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields are the same as with Docker.
3662: +
3663:  ### Usage
3664:  
3665:  `containerlab [global-flags] inspect interfaces [local-flags]`
3666:  
3667:  A shorthand can be used for this subcommand: `int` or `intf`.
3668: diff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md
3669: index 0ce708d..8174c98 100644
3670: --- a/docs/manual/clabernetes/runtime.md
3671: +++ b/docs/manual/clabernetes/runtime.md
3672: @@ -110,10 +110,13 @@ The c9s runtime currently supports the main lab lifecycle and node operations:
3673:  | `start` | sets the node's `spec.runState` to `Running` |
3674:  | `stop` | sets the node's `spec.runState` to `Stopped` |
3675:  | `restart` | requests a Pod replacement with a `c9s.run/restart-requested` token |
3676:  | `save` | runs the node's save lifecycle inside its device container |
3677:  | `events` | watches Clabernetes resources and pods |
3678: +| `logs` | streams the device container log |
3679: +| `capture` | captures lab link interfaces through the `clabwire` sidecar into one pcapng stream |
3680: +| `inspect interfaces` | lists the capturable link interfaces with their sysfs state |
3681:  | `validate` | checks c9s compatibility without creating Kubernetes resources |
3682:  | `deploy --dry-run` | compiles and diffs Namespace, ConfigMap, NodeProfile, Link, and Node resources without changing them |
3683:  | `deploy --emit-crs` | prints the Namespace, ConfigMap, and Topology (or NodeProfile, Link, and Node) manifests deploy would create, without contacting the cluster |
3684:  
3685:  ## Requirements
3686: @@ -141,11 +144,11 @@ Containerlab needs a clabernetes release that has:
3687:  
3688:  - Node run state: `nodes.c9s.run` `spec.runState` (`Running` | `Stopped`), the
3689:    `Stopped` condition, and restart requests through the
3690:    `c9s.run/restart-requested` annotation
3691:  - the clabwire packet capture contract: `--nodeName`, repeated `--interface`,
3692: -  `--format pcapng` and `--list-interfaces`
3693: +  `--format pcapng`, `--list-interfaces` and `--stop-on-stdin-close`
3694:  - the namespace-bindable `clabernetes-lab-viewer` and `clabernetes-lab-editor`
3695:    roles
3696:  
3697:  Both features ship in the same release, so containerlab checks one field: the
3698:  published OpenAPI schema of `nodes.c9s.run` (`/openapi/v3/apis/c9s.run/v1alpha1`)
3699: @@ -159,10 +162,21 @@ an older release every other command fails like this:
3700:  the clabernetes release on this cluster is not supported: nodes.c9s.run has no
3701:  spec.runState (Node run state); the c9s runtime needs clabernetes with Node run
3702:  state and the clabwire capture contract (0.11 or newer)
3703:  ```
3704:  
3705: +A cluster that passes this check but runs a `clabwire` without
3706: +`--stop-on-stdin-close` (a development build between the two features) fails
3707: +the first capture with the same kind of error, naming the pod:
3708: +
3709: +```text
3710: +the clabernetes release on this cluster is not supported: clabwire in pod
3711: +<namespace>/<pod> does not accept packet-capture --stop-on-stdin-close; the c9s
3712: +runtime needs clabernetes with Node run state and the clabwire capture contract
3713: +(0.11 or newer)
3714: +```
3715: +
3716:  Library users can run the check up front with
3717:  `(*core.CLab).CheckLabRuntimeSupport(ctx)` or the optional
3718:  `labruntime.SupportChecker` interface; the error wraps
3719:  `labruntime.ErrUnsupportedRuntimeVersion`.
3720:  
3721: @@ -579,10 +593,82 @@ containerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timest
3722:  
3723:  It reads the `pods/log` subresource of the node's pod, so RBAC must allow
3724:  `get` on `pods/log`. Kubernetes returns stdout and stderr as one stream. See
3725:  the [`logs` command](../../cmd/logs.md) for the flags.
3726:  
3727: +## Packet capture
3728: +
3729: +[`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of
3730: +one or more nodes into one pcapng stream. Each node's pod runs the `clabwire`
3731: +sidecar, which realized the node's links; containerlab execs its capture
3732: +command (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.
3733: +No capture service runs in the cluster, and nothing is captured outside the
3734: +lab's planned link interfaces.
3735: +
3736: +```bash
3737: +# both ends of a link, for 30 seconds
3738: +containerlab -r c9s capture -t clos.clab.yml \
3739: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng
3740: +
3741: +# live in Wireshark until Wireshark or Ctrl+C ends it
3742: +containerlab -r c9s capture --name clos --target srl1:e1-1,e1-2 -w - | wireshark -k -i -
3743: +
3744: +# what can be captured, with the peer of each link
3745: +containerlab -r c9s capture --name clos --list
3746: +```
3747: +
3748: +How it works:
3749: +
3750: +- containerlab locates each target node's pod and runs one `clabwire` capture
3751: +  per node, with `--nodeName`, every requested interface of that node,
3752: +  `--format pcapng` and `--stop-on-stdin-close`, with stdin attached.
3753: +- The streams are merged into one section: one Interface Description Block per
3754: +  target named `<node>:<interface>` (the node as the topology spells it),
3755: +  written before the first packet, and the packets of every target with their
3756: +  interface IDs remapped.
3757: +- Packets are written in timestamp order. Each node's stream arrives over its
3758: +  own exec stream, so the merged stream holds every packet for 250 ms and
3759: +  writes the held packets ordered by timestamp. A packet that arrives later
3760: +  than that, stamped before a packet already written, is written as it comes;
3761: +  the number of such packets goes to the debug log.
3762: +- `clabwire` limits one capture to one hour. Longer captures, and captures
3763: +  without `--duration`, chain captures with a few seconds of overlap and switch
3764: +  in the middle of it; packets near the switch are matched by content so each
3765: +  is written once. A follow-up that does not start in time is reported as a
3766: +  gap, with its time span.
3767: +- `clabwire` audit records (JSON on its stderr, schema
3768: +  `c9s.direct-packet-capture-audit/v1alpha1`) with status `Denied` or `Failed`
3769: +  end the command with their reason. `Started` and `Succeeded` go to the debug
3770: +  log.
3771: +
3772: +Interface names are the names inside the node; targets may also use the alias
3773: +the topology used for an interface:
3774: +
3775: +| Kind | Interface | Alias |
3776: +| ---- | --------- | ----- |
3777: +| linux | `eth1` | |
3778: +| SR Linux | `e1-1` | `ethernet-1/1` |
3779: +| vr-sros / nokia_sros | `eth3` | `1/1/3` |
3780: +
3781: +The management interface and the pod's `c9s0` interface cannot be captured.
3782: +
3783: +Ctrl+C or SIGTERM ends a capture cleanly: the output stays a valid pcapng
3784: +file and the command exits with code 0. Kubernetes does not stop a command
3785: +when its exec stream closes, but it closes the command's stdin. containerlab
3786: +closes the stdin of every `clabwire` capture when the capture ends for any
3787: +reason (the duration or packet limit, Ctrl+C, an error, a failed write of the
3788: +output such as a closed Wireshark, or a newer segment taking over), and
3789: +`clabwire` then ends the capture within milliseconds. If the process does not
3790: +end within three seconds, containerlab cuts the exec stream. A killed
3791: +containerlab drops the connection, which closes stdin as well.
3792: +
3793: +Capturing needs `get` and `create` on `pods/exec` in the lab namespace, which
3794: +`clabernetes-lab-editor` grants. `inspect interfaces -r c9s` lists the same
3795: +interfaces, with the MAC address, index, MTU and operational state read from
3796: +sysfs in the device container (type `veth`, which is how `clabwire` realizes
3797: +lab links).
3798: +
3799:  ## Start, stop, and restart
3800:  
3801:  Node lifecycle commands ask the clabernetes controllers for a run state; they
3802:  never touch Deployments or Pods.
3803:  
3804: @@ -863,16 +949,22 @@ implemented by the c9s runtime:
3805:  | `NodeLocator` | `LocateNode(ctx, NodeRequest) ([]NodeLocation, error)` | the namespace, pod, primary device container, Node UID, exposed ports and LoadBalancer address of nodes |
3806:  | `NodeAttacher` | `Attach(ctx, AttachRequest, AttachStreams) error` | an interactive exec with stdin, an optional TTY and a resize channel, in the device container or a chosen container |
3807:  | `NodeLogStreamer` | `StreamLogs(ctx, LogRequest, io.Writer) error` | the device container log, with tail, follow and timestamps |
3808:  | `NodePortForwarder` | `DialPort(ctx, NodeRequest, port) (net.Conn, error)` | a connection to a TCP port of the node's pod through `pods/portforward` (SSH, web UIs) |
3809:  | `NodeStatsSampler` | `SampleStats(ctx, InspectRequest) ([]NodeStats, error)` | CPU and memory per node from `metrics.k8s.io` PodMetrics, summing the node's device containers; without the metrics API the error wraps `labruntime.ErrMetricsUnavailable` |
3810: +| `PacketCapturer` | `CaptureInterfaces(ctx, NodeRequest) ([]CaptureInterface, error)` | the capturable link interfaces of nodes, with alias, peer node and peer interface |
3811: +| `PacketCapturer` | `Capture(ctx, CaptureRequest, io.Writer) error` | one pcapng stream of the request's targets, for `Duration` (0: until ctx ends), `PacketLimit` and `SnapLength`; gaps go to `OnGap` |
3812: +| `InterfaceInspector` | `InspectInterfaces(ctx, NodeRequest) ([]*types.ContainerInterfaces, error)` | the `inspect interfaces` view of the link interfaces |
3813: +| `SupportChecker` | `CheckSupport(ctx, Identity) error` | the clabernetes release check |
3814:  
3815:  The `core` package wraps them per lab and node name, accepting the node name
3816:  as the topology file spells it or as it was sanitized:
3817:  `CLab.LocateLabRuntimeNodes`, `CLab.AttachLabRuntimeNode`,
3818: -`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats` and
3819: -`CLab.NodeLogs`, which also serves Docker and Podman.
3820: +`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats`,
3821: +`CLab.CaptureInterfaces`, `CLab.Capture`, `CLab.LabRuntimeInterfaces`,
3822: +`CLab.CheckLabRuntimeSupport` and `CLab.NodeLogs`, which also serves Docker and
3823: +Podman.
3824:  
3825:  ```go
3826:  c, err := clabcore.NewContainerLab(
3827:  	clabcore.WithRuntime("c9s", nil),
3828:  	clabcore.WithTopologyName("clos"),
3829: @@ -884,10 +976,18 @@ c, err := clabcore.NewContainerLab(
3830:  if err != nil {
3831:  	return err
3832:  }
3833:  
3834:  conn, err := c.DialLabRuntimeNodePort(ctx, "srl1", 22)
3835: +
3836: +// stream pcapng to a websocket, a file or Wireshark until ctx ends
3837: +err = c.Capture(ctx, clablabruntime.CaptureRequest{
3838: +	Targets: []clablabruntime.CaptureTarget{
3839: +		{Node: "srl1", Interface: "ethernet-1/1"},
3840: +		{Node: "srl2", Interface: "e1-1"},
3841: +	},
3842: +}, w)
3843:  ```
3844:  
3845:  ### Acting as a user
3846:  
3847:  A server that runs labs for many users acts as each user, so the cluster's RBAC
3848: @@ -936,11 +1036,12 @@ to:
3849:  - create, get, list, watch, and delete c9s `Link` and `NodeProfile` resources
3850:  - get, list, watch, and delete `Topology` resources when Topology-based labs
3851:    must remain manageable
3852:  - list and watch Pods
3853:  - create, get, list, update, and delete ConfigMaps used for local files
3854: -- exec into device Pods with `pods/exec`
3855: +- exec into device Pods with `pods/exec`, also for `capture` and `inspect
3856: +  interfaces` (in the `clabwire` and device containers)
3857:  - list and delete PersistentVolumeClaims for `destroy --cleanup`
3858:  - read container logs with `pods/log` for `logs`
3859:  - port-forward with `pods/portforward` for `NodePortForwarder`
3860:  - list `pods.metrics.k8s.io` for `NodeStatsSampler`
3861:  
3862: @@ -1152,12 +1253,14 @@ Known command differences:
3863:    `--export-template`, `--restore`, and `--restore-all` are rejected.
3864:  - Destroy flags `--graceful` and `--keep-mgmt-net` are rejected. `--cleanup`
3865:    also deletes the lab's persistent claims (saved device state) and removes
3866:    the local lab directory; a plain destroy keeps the claims.
3867:  - Local Docker commands on the outer host are not authoritative for c9s labs.
3868: -- `inspect interfaces` is rejected. Host-side `tc` or netem operations do not
3869: -  have the same local namespace access they have with Docker labs.
3870: +- `inspect interfaces` lists only the lab link interfaces (those `capture`
3871: +  accepts), not the management or pod interfaces. Host-side `tc` or netem
3872: +  operations do not have the same local namespace access they have with Docker
3873: +  labs.
3874:  - `graph` renders from the topology file only: `--mermaid`, `--dot`, `--drawio`
3875:    and `--offline` work, the default mode that reads running containers is
3876:    rejected, and so is `--node-filter`. `--drawio` runs the clab-io-draw
3877:    container, so it needs Docker or Podman on the outer host.
3878:  - `tools` commands operate on local containers and host networking and are
3879: diff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md
3880: index b194b29..4654128 100644
3881: --- a/docs/manual/wireshark.md
3882: +++ b/docs/manual/wireshark.md
3883: @@ -15,10 +15,16 @@ Every lab emulation software must provide its users with the packet capturing ab
3884:  
3885:  Containerlab offers a simple way to capture the packets from any interface of any node in the lab. This article will explain how to do that.
3886:  
3887:  ///tip
3888:  
3889: +The [`containerlab capture`](../cmd/capture.md) command captures one or more lab link interfaces, of one or more nodes, into one pcapng file or stream, with nothing to install in the nodes or on the host:
3890: +
3891: +```bash
3892: +containerlab capture --name quickstart --target srl:e1-1 -w - | wireshark -k -i -
3893: +```
3894: +
3895:  If you are looking for a free Web UI for packet capture with Wireshark, check out our [Edgeshark integration](#edgeshark-integration).
3896:  ///
3897:  
3898:  Consider the following lab topology which highlights the typical points of packet capture.
3899:  
3900: diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go
3901: new file mode 100644
3902: index 0000000..69d4072
3903: --- /dev/null
3904: +++ b/labruntime/clabernetes/capture.go
3905: @@ -0,0 +1,1202 @@
3906: +package clabernetes
3907: +
3908: +import (
3909: +	"bytes"
3910: +	"context"
3911: +	"encoding/json"
3912: +	"errors"
3913: +	"fmt"
3914: +	"hash/fnv"
3915: +	"io"
3916: +	"os"
3917: +	"sort"
3918: +	"strconv"
3919: +	"strings"
3920: +	"sync"
3921: +	"time"
3922: +
3923: +	"github.com/charmbracelet/log"
3924: +	clabcapture "github.com/srl-labs/containerlab/capture"
3925: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
3926: +	"golang.org/x/sync/errgroup"
3927: +)
3928: +
3929: +// The clabwire packet capture contract (clabernetes 0.11 or newer).
3930: +const (
3931: +	clabwireContainer = "clabwire"
3932: +	clabwireManager   = "/clabernetes/manager"
3933: +	// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.
3934: +	captureAuditSchema = "c9s.direct-packet-capture-audit/v1alpha1"
3935: +
3936: +	captureAuditStarted   = "Started"
3937: +	captureAuditSucceeded = "Succeeded"
3938: +	captureAuditFailed    = "Failed"
3939: +	captureAuditDenied    = "Denied"
3940: +
3941: +	// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.
3942: +	maxCaptureSegment = time.Hour
3943: +	// maxClabwirePackets is the packet limit of a single clabwire capture.
3944: +	maxClabwirePackets = 1_000_000
3945: +	// maxCaptureOverlap is how long two chained segments run side by side.
3946: +	maxCaptureOverlap = 10 * time.Second
3947: +	// maxCaptureCutWindow is the half-width of the window around the cut in which packets of
3948: +	// two segments are matched by content; it covers the difference between the timestamps
3949: +	// two clabwire processes give the same packet.
3950: +	maxCaptureCutWindow = 500 * time.Millisecond
3951: +	// minCaptureSegment is the shortest segment the chain requests.
3952: +	minCaptureSegment = 100 * time.Millisecond
3953: +	// captureEndGrace is how long a capture with a duration waits for its last clabwire
3954: +	// process to end after the duration passed.
3955: +	captureEndGrace = 30 * time.Second
3956: +	// captureStartRetries bounds the attempts to start a follow-up segment.
3957: +	captureStartRetries = 3
3958: +	// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was
3959: +	// closed before the stream is cut.
3960: +	captureStdinCloseGrace = 3 * time.Second
3961: +	// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A
3962: +	// Kubernetes exec does not stop its process when the stream ends, but it closes the
3963: +	// process's stdin, so every capture runs with stdin attached and this flag.
3964: +	clabwireStopOnStdinClose = "--stop-on-stdin-close"
3965: +
3966: +	// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests
3967: +	// without hour-long captures.
3968: +	envCaptureSegment = "CLAB_C9S_CAPTURE_SEGMENT"
3969: +	// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets
3970: +	// of other nodes stamped earlier but delivered later still go out before it.
3971: +	defaultCaptureReorderWindow = 250 * time.Millisecond
3972: +	// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.
3973: +	// It is an internal knob, not a supported setting.
3974: +	envCaptureReorderWindow = "CLAB_C9S_CAPTURE_REORDER_WINDOW"
3975: +)

(Showing lines 3396-3975 of 7018. Use offset=3976 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19653dabb001uaf6ZZbJdVdBs5",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653d207001b0N0fJzxFIZN83",
  "callID": "call_19acde4ddfaf463aaff75a1f",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 580,
      "offset": 3396
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n3396: +\t\tgo func() {\n3397: +\t\t\ttime.Sleep(time.Second)\n3398: +\t\t\tpinged <- c.AttachLabRuntimeNode(ctx, clablabruntime.AttachRequest{\n3399: +\t\t\t\tNodeName: \"client\",\n3400: +\t\t\t\tCommand:  []string{\"ping\", \"-c\", \"4\", \"-i\", \"0.3\", \"10.10.10.2\"},\n3401: +\t\t\t}, clablabruntime.AttachStreams{Stdout: io.Discard})\n3402: +\t\t}()\n3403: +\n3404: +\t\tvar out bytes.Buffer\n3405: +\t\terr := c.Capture(ctx, clablabruntime.CaptureRequest{\n3406: +\t\t\tTargets: []clablabruntime.CaptureTarget{\n3407: +\t\t\t\t{Node: \"client\", Interface: \"eth1\"}, {Node: \"server\", Interface: \"eth1\"},\n3408: +\t\t\t},\n3409: +\t\t\tDuration: 5 * time.Second,\n3410: +\t\t}, &out)\n3411: +\t\tif err != nil {\n3412: +\t\t\tt.Fatal(err)\n3413: +\t\t}\n3414: +\t\tif err := <-pinged; err != nil {\n3415: +\t\t\tt.Fatalf(\"ping: %v\", err)\n3416: +\t\t}\n3417: +\n3418: +\t\tnames, icmp := summarizePCAPNG(t, out.Bytes())\n3419: +\t\tif len(names) != 2 || names[0] != \"client:eth1\" || names[1] != \"server:eth1\" {\n3420: +\t\t\tt.Fatalf(\"interfaces = %v\", names)\n3421: +\t\t}\n3422: +\t\t// every echo request and reply crosses both ends\n3423: +\t\tif icmp[0] < 8 || icmp[1] < 8 {\n3424: +\t\t\tt.Fatalf(\"ICMP packets per interface = %v, want at least 8 on each\", icmp)\n3425: +\t\t}\n3426: +\t})\n3427: +\n3428: +\tt.Run(\"restart as lab editor\", func(t *testing.T) {\n3429: +\t\tif err := c.RestartNodes(ctx, []string{\"server\"}); err != nil {\n3430: +\t\t\tt.Fatal(err)\n3431: +\t\t}\n3432: +\t})\n3433: +\n3434: +\tt.Run(\"forbidden identity\", func(t *testing.T) {\n3435: +\t\tforbidden := os.Getenv(\"CLAB_C9S_TEST_FORBIDDEN_USER\")\n3436: +\t\tif forbidden == \"\" {\n3437: +\t\t\tt.Skip(\"CLAB_C9S_TEST_FORBIDDEN_USER is not set\")\n3438: +\t\t}\n3439: +\n3440: +\t\terr := newCLab(t, forbidden).Capture(ctx, clablabruntime.CaptureRequest{\n3441: +\t\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"client\", Interface: \"eth1\"}},\n3442: +\t\t\tDuration: time.Second,\n3443: +\t\t}, io.Discard)\n3444: +\t\tif err == nil || !strings.Contains(err.Error(), \"forbidden\") {\n3445: +\t\t\tt.Fatalf(\"capture as %s = %v, want forbidden\", forbidden, err)\n3446: +\t\t}\n3447: +\t})\n3448: +}\n3449: +\n3450: +// summarizePCAPNG returns the interface names of a little-endian pcapng stream and its IPv4 ICMP\n3451: +// packets per interface ID.\n3452: +func summarizePCAPNG(t *testing.T, data []byte) ([]string, map[uint32]int) {\n3453: +\tt.Helper()\n3454: +\n3455: +\tvar names []string\n3456: +\ticmp := map[uint32]int{}\n3457: +\tfor len(data) >= 12 {\n3458: +\t\tblockType := binary.LittleEndian.Uint32(data[0:4])\n3459: +\t\tlength := int(binary.LittleEndian.Uint32(data[4:8]))\n3460: +\t\tif length < 12 || length > len(data) {\n3461: +\t\t\tt.Fatalf(\"invalid block length %d\", length)\n3462: +\t\t}\n3463: +\t\tbody := data[8 : length-4]\n3464: +\t\tswitch blockType {\n3465: +\t\tcase 1: // Interface Description Block\n3466: +\t\t\toptions := body[8:]\n3467: +\t\t\tfor len(options) >= 4 {\n3468: +\t\t\t\tcode := binary.LittleEndian.Uint16(options[0:2])\n3469: +\t\t\t\tsize := int(binary.LittleEndian.Uint16(options[2:4]))\n3470: +\t\t\t\tif code == 0 {\n3471: +\t\t\t\t\tbreak\n3472: +\t\t\t\t}\n3473: +\t\t\t\tif code == 2 {\n3474: +\t\t\t\t\tnames = append(names, string(options[4:4+size]))\n3475: +\t\t\t\t}\n3476: +\t\t\t\toptions = options[4+size+(4-size%4)%4:]\n3477: +\t\t\t}\n3478: +\t\tcase 6: // Enhanced Packet Block\n3479: +\t\t\tid := binary.LittleEndian.Uint32(body[0:4])\n3480: +\t\t\tframe := body[20 : 20+binary.LittleEndian.Uint32(body[12:16])]\n3481: +\t\t\tif len(frame) > 23 && frame[12] == 0x08 && frame[13] == 0x00 && frame[23] == 1 {\n3482: +\t\t\t\ticmp[id]++\n3483: +\t\t\t}\n3484: +\t\t}\n3485: +\t\tdata = data[length:]\n3486: +\t}\n3487: +\n3488: +\treturn names, icmp\n3489: +}\n3490: diff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml\n3491: new file mode 100644\n3492: index 0000000..0422c22\n3493: --- /dev/null\n3494: +++ b/core/test_data/capture.clab.yml\n3495: @@ -0,0 +1,15 @@\n3496: +name: capture\n3497: +topology:\n3498: +  nodes:\n3499: +    srl1:\n3500: +      kind: nokia_srlinux\n3501: +    srl2:\n3502: +      kind: nokia_srlinux\n3503: +    client:\n3504: +      kind: linux\n3505: +      image: alpine:3\n3506: +  links:\n3507: +    - endpoints: [\"srl1:ethernet-1/1\", \"srl2:e1-1\"]\n3508: +    - endpoints: [\"srl1:e1-2\", \"client:eth1\"]\n3509: +    - endpoints: [\"client:eth2\", \"host:client-eth2\"]\n3510: +    - endpoints: [\"client:eth3\", \"mgmt-net:client-eth3\"]\n3511: diff --git a/docs/cmd/capture.md b/docs/cmd/capture.md\n3512: new file mode 100644\n3513: index 0000000..15006ff\n3514: --- /dev/null\n3515: +++ b/docs/cmd/capture.md\n3516: @@ -0,0 +1,134 @@\n3517: +# capture command\n3518: +\n3519: +### Description\n3520: +\n3521: +The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.\n3522: +\n3523: +It works with every runtime:\n3524: +\n3525: +- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).\n3526: +- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).\n3527: +\n3528: +The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.\n3529: +\n3530: +--8<-- \"docs/cmd/deploy.md:env-vars-flags\"\n3531: +\n3532: +### Usage\n3533: +\n3534: +`containerlab [global-flags] capture [local-flags]`\n3535: +\n3536: +### Flags\n3537: +\n3538: +#### topology | name\n3539: +\n3540: +Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.\n3541: +\n3542: +With Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.\n3543: +\n3544: +#### target\n3545: +\n3546: +The local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:\n3547: +\n3548: +```text\n3549: +--target srl1:e1-1,e1-2 --target srl2:e1-1\n3550: +```\n3551: +\n3552: +The node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.\n3553: +\n3554: +Only lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.\n3555: +\n3556: +#### duration\n3557: +\n3558: +The local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).\n3559: +\n3560: +#### packet-limit\n3561: +\n3562: +The local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.\n3563: +\n3564: +#### snap-length\n3565: +\n3566: +The local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.\n3567: +\n3568: +#### write\n3569: +\n3570: +The local `--write | -w` flag names the output file. The default `-` writes to stdout.\n3571: +\n3572: +#### list\n3573: +\n3574: +The local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.\n3575: +\n3576: +### Output\n3577: +\n3578: +The output is one pcapng section:\n3579: +\n3580: +- a Section Header Block with `shb_userappl` set to `containerlab`\n3581: +- one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it\n3582: +- Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes\n3583: +\n3584: +The interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.\n3585: +\n3586: +When the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.\n3587: +\n3588: +`--list -f json` prints an array:\n3589: +\n3590: +```json\n3591: +[\n3592: +  {\n3593: +    \"node\": \"srl1\",\n3594: +    \"interface\": \"e1-1\",\n3595: +    \"alias\": \"ethernet-1/1\",\n3596: +    \"peer_node\": \"srl2\",\n3597: +    \"peer_interface\": \"ethernet-1/1\"\n3598: +  }\n3599: +]\n3600: +```\n3601: +\n3602: +`alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.\n3603: +\n3604: +### How Docker and Podman captures work\n3605: +\n3606: +For each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.\n3607: +\n3608: +- Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.\n3609: +- 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.\n3610: +- Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.\n3611: +- An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.\n3612: +\n3613: +The command needs root (to open packet sockets and enter network namespaces), as other lab commands do.\n3614: +\n3615: +### Long captures\n3616: +\n3617: +Docker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.\n3618: +\n3619: +### Examples\n3620: +\n3621: +#### Capture two nodes for 30 seconds into one file\n3622: +\n3623: +```bash\n3624: +containerlab capture -t srl.clab.yml \\\n3625: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n3626: +```\n3627: +\n3628: +#### Watch a capture live in Wireshark\n3629: +\n3630: +```bash\n3631: +containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n3632: +```\n3633: +\n3634: +#### Capture the first 100 packets with tshark\n3635: +\n3636: +```bash\n3637: +containerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -\n3638: +```\n3639: +\n3640: +#### List the capturable interfaces\n3641: +\n3642: +```bash\n3643: +containerlab capture --name srl --list\n3644: +```\n3645: +\n3646: +#### Capture a c9s lab\n3647: +\n3648: +```bash\n3649: +containerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng\n3650: +```\n3651: diff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md\n3652: index 3dc8e27..2354dc1 100644\n3653: --- a/docs/cmd/inspect/interfaces.md\n3654: +++ b/docs/cmd/inspect/interfaces.md\n3655: @@ -3,10 +3,12 @@\n3656:  ### Description\n3657:  \n3658:  The `inspect interfaces` subcommand provides information about the network interfaces of deployed nodes of a deployed lab.\n3659:  The subcommand gathers information directly from deployed containers, and displays information about their operational state, network interface type, and if applicable, the applied network interface alias.\n3660:  \n3661: +With the [c9s runtime](../../manual/clabernetes/runtime.md#packet-capture), the listing covers the lab link interfaces of each running node, the ones [`capture`](../capture.md) accepts, with the alias the topology used, and the MAC address, index, MTU and operational state read in the node's device container. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields are the same as with Docker.\n3662: +\n3663:  ### Usage\n3664:  \n3665:  `containerlab [global-flags] inspect interfaces [local-flags]`\n3666:  \n3667:  A shorthand can be used for this subcommand: `int` or `intf`.\n3668: diff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md\n3669: index 0ce708d..8174c98 100644\n3670: --- a/docs/manual/clabernetes/runtime.md\n3671: +++ b/docs/manual/clabernetes/runtime.md\n3672: @@ -110,10 +110,13 @@ The c9s runtime currently supports the main lab lifecycle and node operations:\n3673:  | `start` | sets the node's `spec.runState` to `Running` |\n3674:  | `stop` | sets the node's `spec.runState` to `Stopped` |\n3675:  | `restart` | requests a Pod replacement with a `c9s.run/restart-requested` token |\n3676:  | `save` | runs the node's save lifecycle inside its device container |\n3677:  | `events` | watches Clabernetes resources and pods |\n3678: +| `logs` | streams the device container log |\n3679: +| `capture` | captures lab link interfaces through the `clabwire` sidecar into one pcapng stream |\n3680: +| `inspect interfaces` | lists the capturable link interfaces with their sysfs state |\n3681:  | `validate` | checks c9s compatibility without creating Kubernetes resources |\n3682:  | `deploy --dry-run` | compiles and diffs Namespace, ConfigMap, NodeProfile, Link, and Node resources without changing them |\n3683:  | `deploy --emit-crs` | prints the Namespace, ConfigMap, and Topology (or NodeProfile, Link, and Node) manifests deploy would create, without contacting the cluster |\n3684:  \n3685:  ## Requirements\n3686: @@ -141,11 +144,11 @@ Containerlab needs a clabernetes release that has:\n3687:  \n3688:  - Node run state: `nodes.c9s.run` `spec.runState` (`Running` | `Stopped`), the\n3689:    `Stopped` condition, and restart requests through the\n3690:    `c9s.run/restart-requested` annotation\n3691:  - the clabwire packet capture contract: `--nodeName`, repeated `--interface`,\n3692: -  `--format pcapng` and `--list-interfaces`\n3693: +  `--format pcapng`, `--list-interfaces` and `--stop-on-stdin-close`\n3694:  - the namespace-bindable `clabernetes-lab-viewer` and `clabernetes-lab-editor`\n3695:    roles\n3696:  \n3697:  Both features ship in the same release, so containerlab checks one field: the\n3698:  published OpenAPI schema of `nodes.c9s.run` (`/openapi/v3/apis/c9s.run/v1alpha1`)\n3699: @@ -159,10 +162,21 @@ an older release every other command fails like this:\n3700:  the clabernetes release on this cluster is not supported: nodes.c9s.run has no\n3701:  spec.runState (Node run state); the c9s runtime needs clabernetes with Node run\n3702:  state and the clabwire capture contract (0.11 or newer)\n3703:  ```\n3704:  \n3705: +A cluster that passes this check but runs a `clabwire` without\n3706: +`--stop-on-stdin-close` (a development build between the two features) fails\n3707: +the first capture with the same kind of error, naming the pod:\n3708: +\n3709: +```text\n3710: +the clabernetes release on this cluster is not supported: clabwire in pod\n3711: +<namespace>/<pod> does not accept packet-capture --stop-on-stdin-close; the c9s\n3712: +runtime needs clabernetes with Node run state and the clabwire capture contract\n3713: +(0.11 or newer)\n3714: +```\n3715: +\n3716:  Library users can run the check up front with\n3717:  `(*core.CLab).CheckLabRuntimeSupport(ctx)` or the optional\n3718:  `labruntime.SupportChecker` interface; the error wraps\n3719:  `labruntime.ErrUnsupportedRuntimeVersion`.\n3720:  \n3721: @@ -579,10 +593,82 @@ containerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timest\n3722:  \n3723:  It reads the `pods/log` subresource of the node's pod, so RBAC must allow\n3724:  `get` on `pods/log`. Kubernetes returns stdout and stderr as one stream. See\n3725:  the [`logs` command](../../cmd/logs.md) for the flags.\n3726:  \n3727: +## Packet capture\n3728: +\n3729: +[`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of\n3730: +one or more nodes into one pcapng stream. Each node's pod runs the `clabwire`\n3731: +sidecar, which realized the node's links; containerlab execs its capture\n3732: +command (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.\n3733: +No capture service runs in the cluster, and nothing is captured outside the\n3734: +lab's planned link interfaces.\n3735: +\n3736: +```bash\n3737: +# both ends of a link, for 30 seconds\n3738: +containerlab -r c9s capture -t clos.clab.yml \\\n3739: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n3740: +\n3741: +# live in Wireshark until Wireshark or Ctrl+C ends it\n3742: +containerlab -r c9s capture --name clos --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n3743: +\n3744: +# what can be captured, with the peer of each link\n3745: +containerlab -r c9s capture --name clos --list\n3746: +```\n3747: +\n3748: +How it works:\n3749: +\n3750: +- containerlab locates each target node's pod and runs one `clabwire` capture\n3751: +  per node, with `--nodeName`, every requested interface of that node,\n3752: +  `--format pcapng` and `--stop-on-stdin-close`, with stdin attached.\n3753: +- The streams are merged into one section: one Interface Description Block per\n3754: +  target named `<node>:<interface>` (the node as the topology spells it),\n3755: +  written before the first packet, and the packets of every target with their\n3756: +  interface IDs remapped.\n3757: +- Packets are written in timestamp order. Each node's stream arrives over its\n3758: +  own exec stream, so the merged stream holds every packet for 250 ms and\n3759: +  writes the held packets ordered by timestamp. A packet that arrives later\n3760: +  than that, stamped before a packet already written, is written as it comes;\n3761: +  the number of such packets goes to the debug log.\n3762: +- `clabwire` limits one capture to one hour. Longer captures, and captures\n3763: +  without `--duration`, chain captures with a few seconds of overlap and switch\n3764: +  in the middle of it; packets near the switch are matched by content so each\n3765: +  is written once. A follow-up that does not start in time is reported as a\n3766: +  gap, with its time span.\n3767: +- `clabwire` audit records (JSON on its stderr, schema\n3768: +  `c9s.direct-packet-capture-audit/v1alpha1`) with status `Denied` or `Failed`\n3769: +  end the command with their reason. `Started` and `Succeeded` go to the debug\n3770: +  log.\n3771: +\n3772: +Interface names are the names inside the node; targets may also use the alias\n3773: +the topology used for an interface:\n3774: +\n3775: +| Kind | Interface | Alias |\n3776: +| ---- | --------- | ----- |\n3777: +| linux | `eth1` | |\n3778: +| SR Linux | `e1-1` | `ethernet-1/1` |\n3779: +| vr-sros / nokia_sros | `eth3` | `1/1/3` |\n3780: +\n3781: +The management interface and the pod's `c9s0` interface cannot be captured.\n3782: +\n3783: +Ctrl+C or SIGTERM ends a capture cleanly: the output stays a valid pcapng\n3784: +file and the command exits with code 0. Kubernetes does not stop a command\n3785: +when its exec stream closes, but it closes the command's stdin. containerlab\n3786: +closes the stdin of every `clabwire` capture when the capture ends for any\n3787: +reason (the duration or packet limit, Ctrl+C, an error, a failed write of the\n3788: +output such as a closed Wireshark, or a newer segment taking over), and\n3789: +`clabwire` then ends the capture within milliseconds. If the process does not\n3790: +end within three seconds, containerlab cuts the exec stream. A killed\n3791: +containerlab drops the connection, which closes stdin as well.\n3792: +\n3793: +Capturing needs `get` and `create` on `pods/exec` in the lab namespace, which\n3794: +`clabernetes-lab-editor` grants. `inspect interfaces -r c9s` lists the same\n3795: +interfaces, with the MAC address, index, MTU and operational state read from\n3796: +sysfs in the device container (type `veth`, which is how `clabwire` realizes\n3797: +lab links).\n3798: +\n3799:  ## Start, stop, and restart\n3800:  \n3801:  Node lifecycle commands ask the clabernetes controllers for a run state; they\n3802:  never touch Deployments or Pods.\n3803:  \n3804: @@ -863,16 +949,22 @@ implemented by the c9s runtime:\n3805:  | `NodeLocator` | `LocateNode(ctx, NodeRequest) ([]NodeLocation, error)` | the namespace, pod, primary device container, Node UID, exposed ports and LoadBalancer address of nodes |\n3806:  | `NodeAttacher` | `Attach(ctx, AttachRequest, AttachStreams) error` | an interactive exec with stdin, an optional TTY and a resize channel, in the device container or a chosen container |\n3807:  | `NodeLogStreamer` | `StreamLogs(ctx, LogRequest, io.Writer) error` | the device container log, with tail, follow and timestamps |\n3808:  | `NodePortForwarder` | `DialPort(ctx, NodeRequest, port) (net.Conn, error)` | a connection to a TCP port of the node's pod through `pods/portforward` (SSH, web UIs) |\n3809:  | `NodeStatsSampler` | `SampleStats(ctx, InspectRequest) ([]NodeStats, error)` | CPU and memory per node from `metrics.k8s.io` PodMetrics, summing the node's device containers; without the metrics API the error wraps `labruntime.ErrMetricsUnavailable` |\n3810: +| `PacketCapturer` | `CaptureInterfaces(ctx, NodeRequest) ([]CaptureInterface, error)` | the capturable link interfaces of nodes, with alias, peer node and peer interface |\n3811: +| `PacketCapturer` | `Capture(ctx, CaptureRequest, io.Writer) error` | one pcapng stream of the request's targets, for `Duration` (0: until ctx ends), `PacketLimit` and `SnapLength`; gaps go to `OnGap` |\n3812: +| `InterfaceInspector` | `InspectInterfaces(ctx, NodeRequest) ([]*types.ContainerInterfaces, error)` | the `inspect interfaces` view of the link interfaces |\n3813: +| `SupportChecker` | `CheckSupport(ctx, Identity) error` | the clabernetes release check |\n3814:  \n3815:  The `core` package wraps them per lab and node name, accepting the node name\n3816:  as the topology file spells it or as it was sanitized:\n3817:  `CLab.LocateLabRuntimeNodes`, `CLab.AttachLabRuntimeNode`,\n3818: -`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats` and\n3819: -`CLab.NodeLogs`, which also serves Docker and Podman.\n3820: +`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats`,\n3821: +`CLab.CaptureInterfaces`, `CLab.Capture`, `CLab.LabRuntimeInterfaces`,\n3822: +`CLab.CheckLabRuntimeSupport` and `CLab.NodeLogs`, which also serves Docker and\n3823: +Podman.\n3824:  \n3825:  ```go\n3826:  c, err := clabcore.NewContainerLab(\n3827:  \tclabcore.WithRuntime(\"c9s\", nil),\n3828:  \tclabcore.WithTopologyName(\"clos\"),\n3829: @@ -884,10 +976,18 @@ c, err := clabcore.NewContainerLab(\n3830:  if err != nil {\n3831:  \treturn err\n3832:  }\n3833:  \n3834:  conn, err := c.DialLabRuntimeNodePort(ctx, \"srl1\", 22)\n3835: +\n3836: +// stream pcapng to a websocket, a file or Wireshark until ctx ends\n3837: +err = c.Capture(ctx, clablabruntime.CaptureRequest{\n3838: +\tTargets: []clablabruntime.CaptureTarget{\n3839: +\t\t{Node: \"srl1\", Interface: \"ethernet-1/1\"},\n3840: +\t\t{Node: \"srl2\", Interface: \"e1-1\"},\n3841: +\t},\n3842: +}, w)\n3843:  ```\n3844:  \n3845:  ### Acting as a user\n3846:  \n3847:  A server that runs labs for many users acts as each user, so the cluster's RBAC\n3848: @@ -936,11 +1036,12 @@ to:\n3849:  - create, get, list, watch, and delete c9s `Link` and `NodeProfile` resources\n3850:  - get, list, watch, and delete `Topology` resources when Topology-based labs\n3851:    must remain manageable\n3852:  - list and watch Pods\n3853:  - create, get, list, update, and delete ConfigMaps used for local files\n3854: -- exec into device Pods with `pods/exec`\n3855: +- exec into device Pods with `pods/exec`, also for `capture` and `inspect\n3856: +  interfaces` (in the `clabwire` and device containers)\n3857:  - list and delete PersistentVolumeClaims for `destroy --cleanup`\n3858:  - read container logs with `pods/log` for `logs`\n3859:  - port-forward with `pods/portforward` for `NodePortForwarder`\n3860:  - list `pods.metrics.k8s.io` for `NodeStatsSampler`\n3861:  \n3862: @@ -1152,12 +1253,14 @@ Known command differences:\n3863:    `--export-template`, `--restore`, and `--restore-all` are rejected.\n3864:  - Destroy flags `--graceful` and `--keep-mgmt-net` are rejected. `--cleanup`\n3865:    also deletes the lab's persistent claims (saved device state) and removes\n3866:    the local lab directory; a plain destroy keeps the claims.\n3867:  - Local Docker commands on the outer host are not authoritative for c9s labs.\n3868: -- `inspect interfaces` is rejected. Host-side `tc` or netem operations do not\n3869: -  have the same local namespace access they have with Docker labs.\n3870: +- `inspect interfaces` lists only the lab link interfaces (those `capture`\n3871: +  accepts), not the management or pod interfaces. Host-side `tc` or netem\n3872: +  operations do not have the same local namespace access they have with Docker\n3873: +  labs.\n3874:  - `graph` renders from the topology file only: `--mermaid`, `--dot`, `--drawio`\n3875:    and `--offline` work, the default mode that reads running containers is\n3876:    rejected, and so is `--node-filter`. `--drawio` runs the clab-io-draw\n3877:    container, so it needs Docker or Podman on the outer host.\n3878:  - `tools` commands operate on local containers and host networking and are\n3879: diff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md\n3880: index b194b29..4654128 100644\n3881: --- a/docs/manual/wireshark.md\n3882: +++ b/docs/manual/wireshark.md\n3883: @@ -15,10 +15,16 @@ Every lab emulation software must provide its users with the packet capturing ab\n3884:  \n3885:  Containerlab offers a simple way to capture the packets from any interface of any node in the lab. This article will explain how to do that.\n3886:  \n3887:  ///tip\n3888:  \n3889: +The [`containerlab capture`](../cmd/capture.md) command captures one or more lab link interfaces, of one or more nodes, into one pcapng file or stream, with nothing to install in the nodes or on the host:\n3890: +\n3891: +```bash\n3892: +containerlab capture --name quickstart --target srl:e1-1 -w - | wireshark -k -i -\n3893: +```\n3894: +\n3895:  If you are looking for a free Web UI for packet capture with Wireshark, check out our [Edgeshark integration](#edgeshark-integration).\n3896:  ///\n3897:  \n3898:  Consider the following lab topology which highlights the typical points of packet capture.\n3899:  \n3900: diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go\n3901: new file mode 100644\n3902: index 0000000..69d4072\n3903: --- /dev/null\n3904: +++ b/labruntime/clabernetes/capture.go\n3905: @@ -0,0 +1,1202 @@\n3906: +package clabernetes\n3907: +\n3908: +import (\n3909: +\t\"bytes\"\n3910: +\t\"context\"\n3911: +\t\"encoding/json\"\n3912: +\t\"errors\"\n3913: +\t\"fmt\"\n3914: +\t\"hash/fnv\"\n3915: +\t\"io\"\n3916: +\t\"os\"\n3917: +\t\"sort\"\n3918: +\t\"strconv\"\n3919: +\t\"strings\"\n3920: +\t\"sync\"\n3921: +\t\"time\"\n3922: +\n3923: +\t\"github.com/charmbracelet/log\"\n3924: +\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n3925: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n3926: +\t\"golang.org/x/sync/errgroup\"\n3927: +)\n3928: +\n3929: +// The clabwire packet capture contract (clabernetes 0.11 or newer).\n3930: +const (\n3931: +\tclabwireContainer = \"clabwire\"\n3932: +\tclabwireManager   = \"/clabernetes/manager\"\n3933: +\t// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.\n3934: +\tcaptureAuditSchema = \"c9s.direct-packet-capture-audit/v1alpha1\"\n3935: +\n3936: +\tcaptureAuditStarted   = \"Started\"\n3937: +\tcaptureAuditSucceeded = \"Succeeded\"\n3938: +\tcaptureAuditFailed    = \"Failed\"\n3939: +\tcaptureAuditDenied    = \"Denied\"\n3940: +\n3941: +\t// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.\n3942: +\tmaxCaptureSegment = time.Hour\n3943: +\t// maxClabwirePackets is the packet limit of a single clabwire capture.\n3944: +\tmaxClabwirePackets = 1_000_000\n3945: +\t// maxCaptureOverlap is how long two chained segments run side by side.\n3946: +\tmaxCaptureOverlap = 10 * time.Second\n3947: +\t// maxCaptureCutWindow is the half-width of the window around the cut in which packets of\n3948: +\t// two segments are matched by content; it covers the difference between the timestamps\n3949: +\t// two clabwire processes give the same packet.\n3950: +\tmaxCaptureCutWindow = 500 * time.Millisecond\n3951: +\t// minCaptureSegment is the shortest segment the chain requests.\n3952: +\tminCaptureSegment = 100 * time.Millisecond\n3953: +\t// captureEndGrace is how long a capture with a duration waits for its last clabwire\n3954: +\t// process to end after the duration passed.\n3955: +\tcaptureEndGrace = 30 * time.Second\n3956: +\t// captureStartRetries bounds the attempts to start a follow-up segment.\n3957: +\tcaptureStartRetries = 3\n3958: +\t// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was\n3959: +\t// closed before the stream is cut.\n3960: +\tcaptureStdinCloseGrace = 3 * time.Second\n3961: +\t// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A\n3962: +\t// Kubernetes exec does not stop its process when the stream ends, but it closes the\n3963: +\t// process's stdin, so every capture runs with stdin attached and this flag.\n3964: +\tclabwireStopOnStdinClose = \"--stop-on-stdin-close\"\n3965: +\n3966: +\t// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests\n3967: +\t// without hour-long captures.\n3968: +\tenvCaptureSegment = \"CLAB_C9S_CAPTURE_SEGMENT\"\n3969: +\t// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets\n3970: +\t// of other nodes stamped earlier but delivered later still go out before it.\n3971: +\tdefaultCaptureReorderWindow = 250 * time.Millisecond\n3972: +\t// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.\n3973: +\t// It is an internal knob, not a supported setting.\n3974: +\tenvCaptureReorderWindow = \"CLAB_C9S_CAPTURE_REORDER_WINDOW\"\n3975: +)\n\n(Showing lines 3396-3975 of 7018. Use offset=3976 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+\t\tgo func() {\n+\t\t\ttime.Sleep(time.Second)\n+\t\t\tpinged <- c.AttachLabRuntimeNode(ctx, clablabruntime.AttachRequest{\n+\t\t\t\tNodeName: \"client\",\n+\t\t\t\tCommand:  []string{\"ping\", \"-c\", \"4\", \"-i\", \"0.3\", \"10.10.10.2\"},\n+\t\t\t}, clablabruntime.AttachStreams{Stdout: io.Discard})\n+\t\t}()\n+\n+\t\tvar out bytes.Buffer\n+\t\terr := c.Capture(ctx, clablabruntime.CaptureRequest{\n+\t\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t\t{Node: \"client\", Interface: \"eth1\"}, {Node: \"server\", Interface: \"eth1\"},\n+\t\t\t},\n+\t\t\tDuration: 5 * time.Second,\n+\t\t}, &out)\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\tif err := <-pinged; err != nil {\n+\t\t\tt.Fatalf(\"ping: %v\", err)",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+\t\tgo func() {\n+\t\t\ttime.Sleep(time.Second)\n+\t\t\tpinged <- c.AttachLabRuntimeNode(ctx, clablabruntime.AttachRequest{\n+\t\t\t\tNodeName: \"client\",\n+\t\t\t\tCommand:  []string{\"ping\", \"-c\", \"4\", \"-i\", \"0.3\", \"10.10.10.2\"},\n+\t\t\t}, clablabruntime.AttachStreams{Stdout: io.Discard})\n+\t\t}()\n+\n+\t\tvar out bytes.Buffer\n+\t\terr := c.Capture(ctx, clablabruntime.CaptureRequest{\n+\t\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t\t{Node: \"client\", Interface: \"eth1\"}, {Node: \"server\", Interface: \"eth1\"},\n+\t\t\t},\n+\t\t\tDuration: 5 * time.Second,\n+\t\t}, &out)\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\tif err := <-pinged; err != nil {\n+\t\t\tt.Fatalf(\"ping: %v\", err)\n+\t\t}\n+\n+\t\tnames, icmp := summarizePCAPNG(t, out.Bytes())\n+\t\tif len(names) != 2 || names[0] != \"client:eth1\" || names[1] != \"server:eth1\" {\n+\t\t\tt.Fatalf(\"interfaces = %v\", names)\n+\t\t}\n+\t\t// every echo request and reply crosses both ends\n+\t\tif icmp[0] < 8 || icmp[1] < 8 {\n+\t\t\tt.Fatalf(\"ICMP packets per interface = %v, want at least 8 on each\", icmp)\n+\t\t}\n+\t})\n+\n+\tt.Run(\"restart as lab editor\", func(t *testing.T) {\n+\t\tif err := c.RestartNodes(ctx, []string{\"server\"}); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t})\n+\n+\tt.Run(\"forbidden identity\", func(t *testing.T) {\n+\t\tforbidden := os.Getenv(\"CLAB_C9S_TEST_FORBIDDEN_USER\")\n+\t\tif forbidden == \"\" {\n+\t\t\tt.Skip(\"CLAB_C9S_TEST_FORBIDDEN_USER is not set\")\n+\t\t}\n+\n+\t\terr := newCLab(t, forbidden).Capture(ctx, clablabruntime.CaptureRequest{\n+\t\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"client\", Interface: \"eth1\"}},\n+\t\t\tDuration: time.Second,\n+\t\t}, io.Discard)\n+\t\tif err == nil || !strings.Contains(err.Error(), \"forbidden\") {\n+\t\t\tt.Fatalf(\"capture as %s = %v, want forbidden\", forbidden, err)\n+\t\t}\n+\t})\n+}\n+\n+// summarizePCAPNG returns the interface names of a little-endian pcapng stream and its IPv4 ICMP\n+// packets per interface ID.\n+func summarizePCAPNG(t *testing.T, data []byte) ([]string, map[uint32]int) {\n+\tt.Helper()\n+\n+\tvar names []string\n+\ticmp := map[uint32]int{}\n+\tfor len(data) >= 12 {\n+\t\tblockType := binary.LittleEndian.Uint32(data[0:4])\n+\t\tlength := int(binary.LittleEndian.Uint32(data[4:8]))\n+\t\tif length < 12 || length > len(data) {\n+\t\t\tt.Fatalf(\"invalid block length %d\", length)\n+\t\t}\n+\t\tbody := data[8 : length-4]\n+\t\tswitch blockType {\n+\t\tcase 1: // Interface Description Block\n+\t\t\toptions := body[8:]\n+\t\t\tfor len(options) >= 4 {\n+\t\t\t\tcode := binary.LittleEndian.Uint16(options[0:2])\n+\t\t\t\tsize := int(binary.LittleEndian.Uint16(options[2:4]))\n+\t\t\t\tif code == 0 {\n+\t\t\t\t\tbreak\n+\t\t\t\t}\n+\t\t\t\tif code == 2 {\n+\t\t\t\t\tnames = append(names, string(options[4:4+size]))\n+\t\t\t\t}\n+\t\t\t\toptions = options[4+size+(4-size%4)%4:]\n+\t\t\t}\n+\t\tcase 6: // Enhanced Packet Block\n+\t\t\tid := binary.LittleEndian.Uint32(body[0:4])\n+\t\t\tframe := body[20 : 20+binary.LittleEndian.Uint32(body[12:16])]\n+\t\t\tif len(frame) > 23 && frame[12] == 0x08 && frame[13] == 0x00 && frame[23] == 1 {\n+\t\t\t\ticmp[id]++\n+\t\t\t}\n+\t\t}\n+\t\tdata = data[length:]\n+\t}\n+\n+\treturn names, icmp\n+}\ndiff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml\nnew file mode 100644\nindex 0000000..0422c22\n--- /dev/null\n+++ b/core/test_data/capture.clab.yml\n@@ -0,0 +1,15 @@\n+name: capture\n+topology:\n+  nodes:\n+    srl1:\n+      kind: nokia_srlinux\n+    srl2:\n+      kind: nokia_srlinux\n+    client:\n+      kind: linux\n+      image: alpine:3\n+  links:\n+    - endpoints: [\"srl1:ethernet-1/1\", \"srl2:e1-1\"]\n+    - endpoints: [\"srl1:e1-2\", \"client:eth1\"]\n+    - endpoints: [\"client:eth2\", \"host:client-eth2\"]\n+    - endpoints: [\"client:eth3\", \"mgmt-net:client-eth3\"]\ndiff --git a/docs/cmd/capture.md b/docs/cmd/capture.md\nnew file mode 100644\nindex 0000000..15006ff\n--- /dev/null\n+++ b/docs/cmd/capture.md\n@@ -0,0 +1,134 @@\n+# capture command\n+\n+### Description\n+\n+The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.\n+\n+It works with every runtime:\n+\n+- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).\n+- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).\n+\n+The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.\n+\n+--8<-- \"docs/cmd/deploy.md:env-vars-flags\"\n+\n+### Usage\n+\n+`containerlab [global-flags] capture [local-flags]`\n+\n+### Flags\n+\n+#### topology | name\n+\n+Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.\n+\n+With Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.\n+\n+#### target\n+\n+The local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:\n+\n+```text\n+--target srl1:e1-1,e1-2 --target srl2:e1-1\n+```\n+\n+The node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.\n+\n+Only lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.\n+\n+#### duration\n+\n+The local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).\n+\n+#### packet-limit\n+\n+The local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.\n+\n+#### snap-length\n+\n+The local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.\n+\n+#### write\n+\n+The local `--write | -w` flag names the output file. The default `-` writes to stdout.\n+\n+#### list\n+\n+The local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.\n+\n+### Output\n+\n+The output is one pcapng section:\n+\n+- a Section Header Block with `shb_userappl` set to `containerlab`\n+- one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it\n+- Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes\n+\n+The interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.\n+\n+When the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.\n+\n+`--list -f json` prints an array:\n+\n+```json\n+[\n+  {\n+    \"node\": \"srl1\",\n+    \"interface\": \"e1-1\",\n+    \"alias\": \"ethernet-1/1\",\n+    \"peer_node\": \"srl2\",\n+    \"peer_interface\": \"ethernet-1/1\"\n+  }\n+]\n+```\n+\n+`alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.\n+\n+### How Docker and Podman captures work\n+\n+For each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.\n+\n+- Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.\n+- 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.\n+- Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.\n+- An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.\n+\n+The command needs root (to open packet sockets and enter network namespaces), as other lab commands do.\n+\n+### Long captures\n+\n+Docker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.\n+\n+### Examples\n+\n+#### Capture two nodes for 30 seconds into one file\n+\n+```bash\n+containerlab capture -t srl.clab.yml \\\n+  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n+```\n+\n+#### Watch a capture live in Wireshark\n+\n+```bash\n+containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n+```\n+\n+#### Capture the first 100 packets with tshark\n+\n+```bash\n+containerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -\n+```\n+\n+#### List the capturable interfaces\n+\n+```bash\n+containerlab capture --name srl --list\n+```\n+\n+#### Capture a c9s lab\n+\n+```bash\n+containerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng\n+```\ndiff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md\nindex 3dc8e27..2354dc1 100644\n--- a/docs/cmd/inspect/interfaces.md\n+++ b/docs/cmd/inspect/interfaces.md\n@@ -3,10 +3,12 @@\n ### Description\n \n The `inspect interfaces` subcommand provides information about the network interfaces of deployed nodes of a deployed lab.\n The subcommand gathers information directly from deployed containers, and displays information about their operational state, network interface type, and if applicable, the applied network interface alias.\n \n+With the [c9s runtime](../../manual/clabernetes/runtime.md#packet-capture), the listing covers the lab link interfaces of each running node, the ones [`capture`](../capture.md) accepts, with the alias the topology used, and the MAC address, index, MTU and operational state read in the node's device container. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields are the same as with Docker.\n+\n ### Usage\n \n `containerlab [global-flags] inspect interfaces [local-flags]`\n \n A shorthand can be used for this subcommand: `int` or `intf`.\ndiff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md\nindex 0ce708d..8174c98 100644\n--- a/docs/manual/clabernetes/runtime.md\n+++ b/docs/manual/clabernetes/runtime.md\n@@ -110,10 +110,13 @@ The c9s runtime currently supports the main lab lifecycle and node operations:\n | `start` | sets the node's `spec.runState` to `Running` |\n | `stop` | sets the node's `spec.runState` to `Stopped` |\n | `restart` | requests a Pod replacement with a `c9s.run/restart-requested` token |\n | `save` | runs the node's save lifecycle inside its device container |\n | `events` | watches Clabernetes resources and pods |\n+| `logs` | streams the device container log |\n+| `capture` | captures lab link interfaces through the `clabwire` sidecar into one pcapng stream |\n+| `inspect interfaces` | lists the capturable link interfaces with their sysfs state |\n | `validate` | checks c9s compatibility without creating Kubernetes resources |\n | `deploy --dry-run` | compiles and diffs Namespace, ConfigMap, NodeProfile, Link, and Node resources without changing them |\n | `deploy --emit-crs` | prints the Namespace, ConfigMap, and Topology (or NodeProfile, Link, and Node) manifests deploy would create, without contacting the cluster |\n \n ## Requirements\n@@ -141,11 +144,11 @@ Containerlab needs a clabernetes release that has:\n \n - Node run state: `nodes.c9s.run` `spec.runState` (`Running` | `Stopped`), the\n   `Stopped` condition, and restart requests through the\n   `c9s.run/restart-requested` annotation\n - the clabwire packet capture contract: `--nodeName`, repeated `--interface`,\n-  `--format pcapng` and `--list-interfaces`\n+  `--format pcapng`, `--list-interfaces` and `--stop-on-stdin-close`\n - the namespace-bindable `clabernetes-lab-viewer` and `clabernetes-lab-editor`\n   roles\n \n Both features ship in the same release, so containerlab checks one field: the\n published OpenAPI schema of `nodes.c9s.run` (`/openapi/v3/apis/c9s.run/v1alpha1`)\n@@ -159,10 +162,21 @@ an older release every other command fails like this:\n the clabernetes release on this cluster is not supported: nodes.c9s.run has no\n spec.runState (Node run state); the c9s runtime needs clabernetes with Node run\n state and the clabwire capture contract (0.11 or newer)\n ```\n \n+A cluster that passes this check but runs a `clabwire` without\n+`--stop-on-stdin-close` (a development build between the two features) fails\n+the first capture with the same kind of error, naming the pod:\n+\n+```text\n+the clabernetes release on this cluster is not supported: clabwire in pod\n+<namespace>/<pod> does not accept packet-capture --stop-on-stdin-close; the c9s\n+runtime needs clabernetes with Node run state and the clabwire capture contract\n+(0.11 or newer)\n+```\n+\n Library users can run the check up front with\n `(*core.CLab).CheckLabRuntimeSupport(ctx)` or the optional\n `labruntime.SupportChecker` interface; the error wraps\n `labruntime.ErrUnsupportedRuntimeVersion`.\n \n@@ -579,10 +593,82 @@ containerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timest\n \n It reads the `pods/log` subresource of the node's pod, so RBAC must allow\n `get` on `pods/log`. Kubernetes returns stdout and stderr as one stream. See\n the [`logs` command](../../cmd/logs.md) for the flags.\n \n+## Packet capture\n+\n+[`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of\n+one or more nodes into one pcapng stream. Each node's pod runs the `clabwire`\n+sidecar, which realized the node's links; containerlab execs its capture\n+command (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.\n+No capture service runs in the cluster, and nothing is captured outside the\n+lab's planned link interfaces.\n+\n+```bash\n+# both ends of a link, for 30 seconds\n+containerlab -r c9s capture -t clos.clab.yml \\\n+  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n+\n+# live in Wireshark until Wireshark or Ctrl+C ends it\n+containerlab -r c9s capture --name clos --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n+\n+# what can be captured, with the peer of each link\n+containerlab -r c9s capture --name clos --list\n+```\n+\n+How it works:\n+\n+- containerlab locates each target node's pod and runs one `clabwire` capture\n+  per node, with `--nodeName`, every requested interface of that node,\n+  `--format pcapng` and `--stop-on-stdin-close`, with stdin attached.\n+- The streams are merged into one section: one Interface Description Block per\n+  target named `<node>:<interface>` (the node as the topology spells it),\n+  written before the first packet, and the packets of every target with their\n+  interface IDs remapped.\n+- Packets are written in timestamp order. Each node's stream arrives over its\n+  own exec stream, so the merged stream holds every packet for 250 ms and\n+  writes the held packets ordered by timestamp. A packet that arrives later\n+  than that, stamped before a packet already written, is written as it comes;\n+  the number of such packets goes to the debug log.\n+- `clabwire` limits one capture to one hour. Longer captures, and captures\n+  without `--duration`, chain captures with a few seconds of overlap and switch\n+  in the middle of it; packets near the switch are matched by content so each\n+  is written once. A follow-up that does not start in time is reported as a\n+  gap, with its time span.\n+- `clabwire` audit records (JSON on its stderr, schema\n+  `c9s.direct-packet-capture-audit/v1alpha1`) with status `Denied` or `Failed`\n+  end the command with their reason. `Started` and `Succeeded` go to the debug\n+  log.\n+\n+Interface names are the names inside the node; targets may also use the alias\n+the topology used for an interface:\n+\n+| Kind | Interface | Alias |\n+| ---- | --------- | ----- |\n+| linux | `eth1` | |\n+| SR Linux | `e1-1` | `ethernet-1/1` |\n+| vr-sros / nokia_sros | `eth3` | `1/1/3` |\n+\n+The management interface and the pod's `c9s0` interface cannot be captured.\n+\n+Ctrl+C or SIGTERM ends a capture cleanly: the output stays a valid pcapng\n+file and the command exits with code 0. Kubernetes does not stop a command\n+when its exec stream closes, but it closes the command's stdin. containerlab\n+closes the stdin of every `clabwire` capture when the capture ends for any\n+reason (the duration or packet limit, Ctrl+C, an error, a failed write of the\n+output such as a closed Wireshark, or a newer segment taking over), and\n+`clabwire` then ends the capture within milliseconds. If the process does not\n+end within three seconds, containerlab cuts the exec stream. A killed\n+containerlab drops the connection, which closes stdin as well.\n+\n+Capturing needs `get` and `create` on `pods/exec` in the lab namespace, which\n+`clabernetes-lab-editor` grants. `inspect interfaces -r c9s` lists the same\n+interfaces, with the MAC address, index, MTU and operational state read from\n+sysfs in the device container (type `veth`, which is how `clabwire` realizes\n+lab links).\n+\n ## Start, stop, and restart\n \n Node lifecycle commands ask the clabernetes controllers for a run state; they\n never touch Deployments or Pods.\n \n@@ -863,16 +949,22 @@ implemented by the c9s runtime:\n | `NodeLocator` | `LocateNode(ctx, NodeRequest) ([]NodeLocation, error)` | the namespace, pod, primary device container, Node UID, exposed ports and LoadBalancer address of nodes |\n | `NodeAttacher` | `Attach(ctx, AttachRequest, AttachStreams) error` | an interactive exec with stdin, an optional TTY and a resize channel, in the device container or a chosen container |\n | `NodeLogStreamer` | `StreamLogs(ctx, LogRequest, io.Writer) error` | the device container log, with tail, follow and timestamps |\n | `NodePortForwarder` | `DialPort(ctx, NodeRequest, port) (net.Conn, error)` | a connection to a TCP port of the node's pod through `pods/portforward` (SSH, web UIs) |\n | `NodeStatsSampler` | `SampleStats(ctx, InspectRequest) ([]NodeStats, error)` | CPU and memory per node from `metrics.k8s.io` PodMetrics, summing the node's device containers; without the metrics API the error wraps `labruntime.ErrMetricsUnavailable` |\n+| `PacketCapturer` | `CaptureInterfaces(ctx, NodeRequest) ([]CaptureInterface, error)` | the capturable link interfaces of nodes, with alias, peer node and peer interface |\n+| `PacketCapturer` | `Capture(ctx, CaptureRequest, io.Writer) error` | one pcapng stream of the request's targets, for `Duration` (0: until ctx ends), `PacketLimit` and `SnapLength`; gaps go to `OnGap` |\n+| `InterfaceInspector` | `InspectInterfaces(ctx, NodeRequest) ([]*types.ContainerInterfaces, error)` | the `inspect interfaces` view of the link interfaces |\n+| `SupportChecker` | `CheckSupport(ctx, Identity) error` | the clabernetes release check |\n \n The `core` package wraps them per lab and node name, accepting the node name\n as the topology file spells it or as it was sanitized:\n `CLab.LocateLabRuntimeNodes`, `CLab.AttachLabRuntimeNode`,\n-`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats` and\n-`CLab.NodeLogs`, which also serves Docker and Podman.\n+`CLab.DialLabRuntimeNodePort`, `CLab.SampleLabRuntimeNodeStats`,\n+`CLab.CaptureInterfaces`, `CLab.Capture`, `CLab.LabRuntimeInterfaces`,\n+`CLab.CheckLabRuntimeSupport` and `CLab.NodeLogs`, which also serves Docker and\n+Podman.\n \n ```go\n c, err := clabcore.NewContainerLab(\n \tclabcore.WithRuntime(\"c9s\", nil),\n \tclabcore.WithTopologyName(\"clos\"),\n@@ -884,10 +976,18 @@ c, err := clabcore.NewContainerLab(\n if err != nil {\n \treturn err\n }\n \n conn, err := c.DialLabRuntimeNodePort(ctx, \"srl1\", 22)\n+\n+// stream pcapng to a websocket, a file or Wireshark until ctx ends\n+err = c.Capture(ctx, clablabruntime.CaptureRequest{\n+\tTargets: []clablabruntime.CaptureTarget{\n+\t\t{Node: \"srl1\", Interface: \"ethernet-1/1\"},\n+\t\t{Node: \"srl2\", Interface: \"e1-1\"},\n+\t},\n+}, w)\n ```\n \n ### Acting as a user\n \n A server that runs labs for many users acts as each user, so the cluster's RBAC\n@@ -936,11 +1036,12 @@ to:\n - create, get, list, watch, and delete c9s `Link` and `NodeProfile` resources\n - get, list, watch, and delete `Topology` resources when Topology-based labs\n   must remain manageable\n - list and watch Pods\n - create, get, list, update, and delete ConfigMaps used for local files\n-- exec into device Pods with `pods/exec`\n+- exec into device Pods with `pods/exec`, also for `capture` and `inspect\n+  interfaces` (in the `clabwire` and device containers)\n - list and delete PersistentVolumeClaims for `destroy --cleanup`\n - read container logs with `pods/log` for `logs`\n - port-forward with `pods/portforward` for `NodePortForwarder`\n - list `pods.metrics.k8s.io` for `NodeStatsSampler`\n \n@@ -1152,12 +1253,14 @@ Known command differences:\n   `--export-template`, `--restore`, and `--restore-all` are rejected.\n - Destroy flags `--graceful` and `--keep-mgmt-net` are rejected. `--cleanup`\n   also deletes the lab's persistent claims (saved device state) and removes\n   the local lab directory; a plain destroy keeps the claims.\n - Local Docker commands on the outer host are not authoritative for c9s labs.\n-- `inspect interfaces` is rejected. Host-side `tc` or netem operations do not\n-  have the same local namespace access they have with Docker labs.\n+- `inspect interfaces` lists only the lab link interfaces (those `capture`\n+  accepts), not the management or pod interfaces. Host-side `tc` or netem\n+  operations do not have the same local namespace access they have with Docker\n+  labs.\n - `graph` renders from the topology file only: `--mermaid`, `--dot`, `--drawio`\n   and `--offline` work, the default mode that reads running containers is\n   rejected, and so is `--node-filter`. `--drawio` runs the clab-io-draw\n   container, so it needs Docker or Podman on the outer host.\n - `tools` commands operate on local containers and host networking and are\ndiff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md\nindex b194b29..4654128 100644\n--- a/docs/manual/wireshark.md\n+++ b/docs/manual/wireshark.md\n@@ -15,10 +15,16 @@ Every lab emulation software must provide its users with the packet capturing ab\n \n Containerlab offers a simple way to capture the packets from any interface of any node in the lab. This article will explain how to do that.\n \n ///tip\n \n+The [`containerlab capture`](../cmd/capture.md) command captures one or more lab link interfaces, of one or more nodes, into one pcapng file or stream, with nothing to install in the nodes or on the host:\n+\n+```bash\n+containerlab capture --name quickstart --target srl:e1-1 -w - | wireshark -k -i -\n+```\n+\n If you are looking for a free Web UI for packet capture with Wireshark, check out our [Edgeshark integration](#edgeshark-integration).\n ///\n \n Consider the following lab topology which highlights the typical points of packet capture.\n \ndiff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go\nnew file mode 100644\nindex 0000000..69d4072\n--- /dev/null\n+++ b/labruntime/clabernetes/capture.go\n@@ -0,0 +1,1202 @@\n+package clabernetes\n+\n+import (\n+\t\"bytes\"\n+\t\"context\"\n+\t\"encoding/json\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"hash/fnv\"\n+\t\"io\"\n+\t\"os\"\n+\t\"sort\"\n+\t\"strconv\"\n+\t\"strings\"\n+\t\"sync\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\t\"golang.org/x/sync/errgroup\"\n+)\n+\n+// The clabwire packet capture contract (clabernetes 0.11 or newer).\n+const (\n+\tclabwireContainer = \"clabwire\"\n+\tclabwireManager   = \"/clabernetes/manager\"\n+\t// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.\n+\tcaptureAuditSchema = \"c9s.direct-packet-capture-audit/v1alpha1\"\n+\n+\tcaptureAuditStarted   = \"Started\"\n+\tcaptureAuditSucceeded = \"Succeeded\"\n+\tcaptureAuditFailed    = \"Failed\"\n+\tcaptureAuditDenied    = \"Denied\"\n+\n+\t// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.\n+\tmaxCaptureSegment = time.Hour\n+\t// maxClabwirePackets is the packet limit of a single clabwire capture.\n+\tmaxClabwirePackets = 1_000_000\n+\t// maxCaptureOverlap is how long two chained segments run side by side.\n+\tmaxCaptureOverlap = 10 * time.Second\n+\t// maxCaptureCutWindow is the half-width of the window around the cut in which packets of\n+\t// two segments are matched by content; it covers the difference between the timestamps\n+\t// two clabwire processes give the same packet.\n+\tmaxCaptureCutWindow = 500 * time.Millisecond\n+\t// minCaptureSegment is the shortest segment the chain requests.\n+\tminCaptureSegment = 100 * time.Millisecond\n+\t// captureEndGrace is how long a capture with a duration waits for its last clabwire\n+\t// process to end after the duration passed.\n+\tcaptureEndGrace = 30 * time.Second\n+\t// captureStartRetries bounds the attempts to start a follow-up segment.\n+\tcaptureStartRetries = 3\n+\t// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was\n+\t// closed before the stream is cut.\n+\tcaptureStdinCloseGrace = 3 * time.Second\n+\t// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A\n+\t// Kubernetes exec does not stop its process when the stream ends, but it closes the\n+\t// process's stdin, so every capture runs with stdin attached and this flag.\n+\tclabwireStopOnStdinClose = \"--stop-on-stdin-close\"\n+\n+\t// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests\n+\t// without hour-long captures.\n+\tenvCaptureSegment = \"CLAB_C9S_CAPTURE_SEGMENT\"\n+\t// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets\n+\t// of other nodes stamped earlier but delivered later still go out before it.\n+\tdefaultCaptureReorderWindow = 250 * time.Millisecond\n+\t// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.\n+\t// It is an internal knob, not a supported setting.\n+\tenvCaptureReorderWindow = \"CLAB_C9S_CAPTURE_REORDER_WINDOW\"\n+)",
        "lineStart": 3396,
        "lineEnd": 3975,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523440319,
      "end": 1793523440337
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19653dad4001z0Z0rx2bwtpL01",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653d207001b0N0fJzxFIZN83",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 48347,
    "input": 8316,
    "output": 28,
    "reasoning": 67,
    "cache": {
      "read": 39936,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19653d207001b0N0fJzxFIZN83",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523438087,
    "completed": 1793523440343
  },
  "parentID": "msg_19653b129001cj4QAfxRVtxTFM",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 48347,
    "input": 8316,
    "output": 28,
    "reasoning": 67,
    "cache": {
      "read": 39936,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 48
step-start
{
  "type": "step-start",
  "id": "prt_19653e29d001Q1NMpiqQNMEhIL",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653dadf001LqnYSf5AYwEOrw"
}
Reasoning
Now the big clabernetes capture.go region 3976-6357 remains (~2380 lines), then capture_interfaces.go, clabernetes.go changes, runtime.go, capture_test.go, workflows. Let me read in chunks of ~700.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 700,
  "offset": 3976
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
3976: +
3977: +// podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns
3978: +// a *labruntime.CommandExitError.
3979: +type podExecFunc func(
3980: +	ctx context.Context,
3981: +	namespace, pod, container string,
3982: +	command []string,
3983: +	stdin io.Reader,
3984: +	stdout, stderr io.Writer,
3985: +) error
3986: +
3987: +// clabwireInterface is one entry of `packet-capture --list-interfaces`.
3988: +type clabwireInterface struct {
3989: +	Node          string `json:"node"`
3990: +	Interface     string `json:"interface"`
3991: +	Alias         string `json:"alias,omitempty"`
3992: +	PeerNode      string `json:"peerNode"`
3993: +	PeerInterface string `json:"peerInterface"`
3994: +}
3995: +
3996: +// captureAudit is one clabwire audit line.
3997: +type captureAudit struct {
3998: +	SchemaVersion string    `json:"schemaVersion"`
3999: +	Time          time.Time `json:"time"`
4000: +	Status        string    `json:"status"`
4001: +	NodeName      string    `json:"nodeName"`
4002: +	Format        string    `json:"format"`
4003: +	Reason        string    `json:"reason"`
4004: +	Packets       int       `json:"packets"`
4005: +	Interfaces    []struct {
4006: +		Name    string `json:"name"`
4007: +		ID      string `json:"id"`
4008: +		Packets int    `json:"packets"`
4009: +	} `json:"interfaces"`
4010: +}
4011: +
4012: +func (r *Runtime) execInPodContainer() podExecFunc {
4013: +	if r.podExec != nil {
4014: +		return r.podExec
4015: +	}
4016: +
4017: +	return r.streamPodExec
4018: +}
4019: +
4020: +// captureSegmentLength is the length of one clabwire capture before the next takes over.
4021: +func (r *Runtime) captureSegmentLength() time.Duration {
4022: +	if r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {
4023: +		return r.captureSegment
4024: +	}
4025: +
4026: +	return maxCaptureSegment
4027: +}
4028: +
4029: +// captureReorderWindowLength is the reorder window of the merged stream; zero disables
4030: +// reordering.
4031: +func (r *Runtime) captureReorderWindowLength() time.Duration {
4032: +	switch {
4033: +	case r.captureReorderWindow < 0:
4034: +		return 0
4035: +	case r.captureReorderWindow > 0:
4036: +		return r.captureReorderWindow
4037: +	}
4038: +
4039: +	return defaultCaptureReorderWindow
4040: +}
4041: +
4042: +// captureReorderWindowFromEnv reads the reorder window knob: unset or invalid keeps the
4043: +// default (0), "0" disables reordering (-1).
4044: +func captureReorderWindowFromEnv() time.Duration {
4045: +	value, err := time.ParseDuration(os.Getenv(envCaptureReorderWindow))
4046: +	switch {
4047: +	case err != nil || value < 0:
4048: +		return 0
4049: +	case value == 0:
4050: +		return -1
4051: +	}
4052: +
4053: +	return value
4054: +}
4055: +
4056: +func captureSegmentFromEnv() time.Duration {
4057: +	value, err := time.ParseDuration(os.Getenv(envCaptureSegment))
4058: +	if err != nil || value <= 0 {
4059: +		return 0
4060: +	}
4061: +
4062: +	return value
4063: +}
4064: +
4065: +// CaptureInterfaces lists the capturable lab link interfaces of the requested nodes, or of every
4066: +// node, as clabwire reports them, with their peers. Node names are reported as the topology
4067: +// spells them.
4068: +func (r *Runtime) CaptureInterfaces(
4069: +	ctx context.Context,
4070: +	req clablabruntime.NodeRequest,
4071: +) ([]clablabruntime.CaptureInterface, error) {
4072: +	r, err := r.connect(ctx, req.Identity)
4073: +	if err != nil {
4074: +		return nil, err
4075: +	}
4076: +
4077: +	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{
4078: +		Name: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,
4079: +	})
4080: +	if err != nil {
4081: +		return nil, err
4082: +	}
4083: +	if len(req.Nodes) == 0 {
4084: +		// a lab-wide listing skips nodes that do not run
4085: +		running := locations[:0]
4086: +		for _, location := range locations {
4087: +			if location.Pod != "" {
4088: +				running = append(running, location)
4089: +			}
4090: +		}
4091: +		locations = running
4092: +	}
4093: +
4094: +	listed, err := r.listCaptureInterfaces(ctx, req.Name, locations)
4095: +	if err != nil {
4096: +		return nil, err
4097: +	}
4098: +	names, err := r.nodeDisplayNames(ctx, req.Name, locations)
4099: +	if err != nil {
4100: +		return nil, err
4101: +	}
4102: +
4103: +	result := make([]clablabruntime.CaptureInterface, 0)
4104: +	for _, location := range locations {
4105: +		for _, entry := range listed[location.NodeName] {
4106: +			result = append(result, clablabruntime.CaptureInterface{
4107: +				Node:          names.display(entry.Node),
4108: +				Interface:     entry.Interface,
4109: +				Alias:         entry.Alias,
4110: +				PeerNode:      names.display(entry.PeerNode),
4111: +				PeerInterface: entry.PeerInterface,
4112: +			})
4113: +		}
4114: +	}
4115: +	sort.SliceStable(result, func(i, j int) bool {
4116: +		if result[i].Node != result[j].Node {
4117: +			return result[i].Node < result[j].Node
4118: +		}
4119: +
4120: +		return result[i].Interface < result[j].Interface
4121: +	})
4122: +
4123: +	return result, nil
4124: +}
4125: +
4126: +// listCaptureInterfaces runs one --list-interfaces per pod and returns the entries per Node.
4127: +func (r *Runtime) listCaptureInterfaces(
4128: +	ctx context.Context,
4129: +	lab string,
4130: +	locations []clablabruntime.NodeLocation,
4131: +) (map[string][]clabwireInterface, error) {
4132: +	pods := map[string]clablabruntime.NodeLocation{}
4133: +	wanted := map[string]bool{}
4134: +	for _, location := range locations {
4135: +		if location.Pod == "" {
4136: +			return nil, fmt.Errorf("c9s node %s/%s/%s has no pod; is it running?",
4137: +				location.Namespace, lab, location.NodeName)
4138: +		}
4139: +		pods[location.Namespace+"/"+location.Pod] = location
4140: +		wanted[location.NodeName] = true
4141: +	}
4142: +
4143: +	var mu sync.Mutex
4144: +	result := map[string][]clabwireInterface{}
4145: +	group, groupCtx := errgroup.WithContext(ctx)
4146: +	group.SetLimit(interfaceSampleWorkers)
4147: +	exec := r.execInPodContainer()
4148: +	for _, location := range pods {
4149: +		group.Go(func() error {
4150: +			var stdout, stderr bytes.Buffer
4151: +			err := exec(groupCtx, location.Namespace, location.Pod, clabwireContainer,
4152: +				[]string{clabwireManager, "node-runtime", "packet-capture", "--list-interfaces"},
4153: +				nil, &stdout, &stderr)
4154: +			if err != nil {
4155: +				return fmt.Errorf("failed to list the capturable interfaces of pod %s/%s: %w%s",
4156: +					location.Namespace, location.Pod, err, stderrSuffix(stderr.Bytes()))
4157: +			}
4158: +
4159: +			var entries []clabwireInterface
4160: +			if err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {
4161: +				return fmt.Errorf("failed to parse the capturable interfaces of pod %s/%s: %w",
4162: +					location.Namespace, location.Pod, err)
4163: +			}
4164: +
4165: +			mu.Lock()
4166: +			defer mu.Unlock()
4167: +			for _, entry := range entries {
4168: +				if wanted[entry.Node] {
4169: +					result[entry.Node] = append(result[entry.Node], entry)
4170: +				}
4171: +			}
4172: +
4173: +			return nil
4174: +		})
4175: +	}
4176: +	if err := group.Wait(); err != nil {
4177: +		return nil, err
4178: +	}
4179: +
4180: +	return result, nil
4181: +}
4182: +
4183: +func stderrSuffix(stderr []byte) string {
4184: +	text := strings.TrimSpace(string(stderr))
4185: +	if text == "" {
4186: +		return ""
4187: +	}
4188: +
4189: +	return ": " + text
4190: +}
4191: +
4192: +// nodeNames maps the node names the cluster carries to the names the topology file uses.
4193: +type nodeNames map[string]string
4194: +
4195: +func (n nodeNames) display(name string) string {
4196: +	if original := n[name]; original != "" {
4197: +		return original
4198: +	}
4199: +
4200: +	return name
4201: +}
4202: +
4203: +// nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the
4204: +// lab's Nodes.
4205: +func (r *Runtime) nodeDisplayNames(
4206: +	ctx context.Context,
4207: +	lab string,
4208: +	locations []clablabruntime.NodeLocation,
4209: +) (nodeNames, error) {
4210: +	names := nodeNames{}
4211: +	if len(locations) == 0 {
4212: +		return names, nil
4213: +	}
4214: +
4215: +	nodes, err := r.nodesForTopology(ctx, lab, locations[0].Namespace)
4216: +	if err != nil {
4217: +		return nil, err
4218: +	}
4219: +	for idx := range nodes.Items {
4220: +		if original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != "" {
4221: +			names[nodes.Items[idx].GetName()] = original
4222: +		}
4223: +	}
4224: +
4225: +	return names, nil
4226: +}
4227: +
4228: +// captureGroup is the part of a capture one clabwire process serves: the requested interfaces of
4229: +// one node, in one pod.
4230: +type captureGroup struct {
4231: +	location clablabruntime.NodeLocation
4232: +	display  string
4233: +	// interfaces are the planned interface names, in the order the merged stream lists them.
4234: +	interfaces []string
4235: +	// ids are the merged interface IDs of interfaces.
4236: +	ids []uint32
4237: +}
4238: +
4239: +// resolvedCapture is a validated capture request.
4240: +type resolvedCapture struct {
4241: +	groups []*captureGroup
4242: +	// names are the merged interface names (<node>:<interface>), indexed by merged ID.
4243: +	names []string
4244: +}
4245: +
4246: +// resolveCaptureTargets locates every target node, checks every interface against the
4247: +// interfaces clabwire allows, and groups the targets per node.
4248: +func (r *Runtime) resolveCaptureTargets(
4249: +	ctx context.Context,
4250: +	req clablabruntime.CaptureRequest,
4251: +) (*resolvedCapture, error) {
4252: +	nodeOrder := make([]string, 0, len(req.Targets))
4253: +	seenNodes := map[string]bool{}
4254: +	for _, target := range req.Targets {
4255: +		if !seenNodes[target.Node] {
4256: +			seenNodes[target.Node] = true
4257: +			nodeOrder = append(nodeOrder, target.Node)
4258: +		}
4259: +	}
4260: +
4261: +	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{
4262: +		Name: req.Name, Namespace: req.Namespace, Nodes: nodeOrder, Identity: req.Identity,
4263: +	})
4264: +	if err != nil {
4265: +		return nil, err
4266: +	}
4267: +	byRequest := make(map[string]clablabruntime.NodeLocation, len(nodeOrder))
4268: +	for idx, name := range nodeOrder {
4269: +		byRequest[name] = locations[idx]
4270: +	}
4271: +
4272: +	listed, err := r.listCaptureInterfaces(ctx, req.Name, locations)
4273: +	if err != nil {
4274: +		return nil, err
4275: +	}
4276: +	names, err := r.nodeDisplayNames(ctx, req.Name, locations)
4277: +	if err != nil {
4278: +		return nil, err
4279: +	}
4280: +
4281: +	resolved := &resolvedCapture{}
4282: +	groups := map[string]*captureGroup{}
4283: +	seen := map[string]bool{}
4284: +	for _, target := range req.Targets {
4285: +		location := byRequest[target.Node]
4286: +		entry, ok := findCaptureInterface(listed[location.NodeName], target.Interface)
4287: +		if !ok {
4288: +			return nil, fmt.Errorf("interface %q of node %q is not a capturable link "+
4289: +				"interface; capturable: %s", target.Interface, target.Node,
4290: +				describeCaptureInterfaces(listed[location.NodeName]))
4291: +		}
4292: +
4293: +		key := location.NodeName + "\x00" + entry.Interface
4294: +		if seen[key] {
4295: +			return nil, fmt.Errorf("interface %q of node %q is requested more than once",
4296: +				entry.Interface, target.Node)
4297: +		}
4298: +		seen[key] = true
4299: +
4300: +		group := groups[location.NodeName]
4301: +		if group == nil {
4302: +			group = &captureGroup{
4303: +				location: location,
4304: +				display:  names.display(location.NodeName),
4305: +			}
4306: +			groups[location.NodeName] = group
4307: +			resolved.groups = append(resolved.groups, group)
4308: +		}
4309: +
4310: +		id := uint32(len(resolved.names)) //nolint:gosec // bounded by the targets
4311: +		group.interfaces = append(group.interfaces, entry.Interface)
4312: +		group.ids = append(group.ids, id)
4313: +		resolved.names = append(resolved.names, group.display+":"+entry.Interface)
4314: +	}
4315: +
4316: +	return resolved, nil
4317: +}
4318: +
4319: +// findCaptureInterface matches a requested interface by its planned name or its alias.
4320: +func findCaptureInterface(entries []clabwireInterface, name string) (clabwireInterface, bool) {
4321: +	for _, entry := range entries {
4322: +		if entry.Interface == name {
4323: +			return entry, true
4324: +		}
4325: +	}
4326: +	for _, entry := range entries {
4327: +		if entry.Alias != "" && entry.Alias == name {
4328: +			return entry, true
4329: +		}
4330: +	}
4331: +
4332: +	return clabwireInterface{}, false
4333: +}
4334: +
4335: +func describeCaptureInterfaces(entries []clabwireInterface) string {
4336: +	if len(entries) == 0 {
4337: +		return "none"
4338: +	}
4339: +
4340: +	names := make([]string, 0, len(entries))
4341: +	for _, entry := range entries {
4342: +		name := entry.Interface
4343: +		if entry.Alias != "" {
4344: +			name += " (" + entry.Alias + ")"
4345: +		}
4346: +		names = append(names, name)
4347: +	}
4348: +
4349: +	return strings.Join(names, ", ")
4350: +}
4351: +
4352: +// Capture streams pcapng from lab link interfaces to w: one section, one Interface Description
4353: +// Block per target in request order named <node>:<interface>, then the packets of every target.
4354: +//
4355: +// Each node's interfaces are captured by one clabwire process in the node's pod. clabwire limits
4356: +// a capture to one hour, so a longer capture (or one without Duration) chains captures: the next
4357: +// one starts before the current one ends, and the stream switches at a cut in the overlap. See
4358: +// captureChain for how packets of the overlap are kept once.
4359: +//
4360: +// Packets go out in timestamp order across nodes, through a reorder buffer (captureReorder).
4361: +//
4362: +// Every clabwire process runs with stdin attached and --stop-on-stdin-close: a Kubernetes exec
4363: +// does not stop its process when the stream closes, so containerlab closes stdin whenever a
4364: +// segment ends (the capture ends, fails, its output fails, or a newer segment took over) and
4365: +// clabwire ends the capture itself.
4366: +//
4367: +// Capture returns when Duration has passed, PacketLimit packets were written, or ctx ends; an
4368: +// ended ctx is not an error. Every block reaches w in one write, so the stream is a valid capture
4369: +// whenever it stops. A clabwire Denied or Failed audit record is returned as an error.
4370: +func (r *Runtime) Capture(
4371: +	ctx context.Context,
4372: +	req clablabruntime.CaptureRequest,
4373: +	w io.Writer,
4374: +) error {
4375: +	if err := clabcapture.ValidateRequest(&req); err != nil {
4376: +		return err
4377: +	}
4378: +
4379: +	r, err := r.connect(ctx, req.Identity)
4380: +	if err != nil {
4381: +		return err
4382: +	}
4383: +
4384: +	resolved, err := r.resolveCaptureTargets(ctx, req)
4385: +	if err != nil {
4386: +		return err
4387: +	}
4388: +
4389: +	captureCtx, stop := context.WithCancel(ctx)
4390: +	defer stop()
4391: +
4392: +	out, err := clabcapture.NewOutput(w, resolved.names, req.SnapLength, req.PacketLimit,
4393: +		r.captureReorderWindowLength(), stop)
4394: +	if err != nil {
4395: +		return err
4396: +	}
4397: +
4398: +	run := &captureRun{
4399: +		r:       r,
4400: +		req:     req,
4401: +		out:     out,
4402: +		segment: r.captureSegmentLength(),
4403: +	}
4404: +	if req.Duration > 0 {
4405: +		run.deadline = time.Now().Add(req.Duration)
4406: +	}
4407: +	run.overlap = min(maxCaptureOverlap, run.segment/3)
4408: +	run.window = min(maxCaptureCutWindow, run.overlap/4)
4409: +
4410: +	if req.Duration > 0 {
4411: +		// a clabwire process that does not end on its own does not hold the capture open
4412: +		var cancelTimeout context.CancelFunc
4413: +		captureCtx, cancelTimeout = context.WithTimeout(captureCtx,
4414: +			req.Duration+run.overlap+captureEndGrace)
4415: +		defer cancelTimeout()
4416: +	}
4417: +
4418: +	group, groupCtx := errgroup.WithContext(captureCtx)
4419: +	for _, captureGroup := range resolved.groups {
4420: +		chain := &captureChain{capture: run, group: captureGroup}
4421: +		group.Go(func() error {
4422: +			return chain.run(groupCtx)
4423: +		})
4424: +	}
4425: +
4426: +	err = group.Wait()
4427: +	if writeErr := out.Close(); writeErr != nil {
4428: +		return writeErr
4429: +	}
4430: +	if err != nil && !(errors.Is(err, context.Canceled) && captureCtx.Err() != nil) {
4431: +		return err
4432: +	}
4433: +
4434: +	return nil
4435: +}
4436: +
4437: +// captureRun is the state a capture's chains share.
4438: +type captureRun struct {
4439: +	r   *Runtime
4440: +	req clablabruntime.CaptureRequest
4441: +	// out is the merged stream; it writes the packets of every chain in timestamp order and
4442: +	// stops every chain once the packet limit is reached.
4443: +	out *clabcapture.Output
4444: +
4445: +	segment  time.Duration
4446: +	overlap  time.Duration
4447: +	window   time.Duration
4448: +	deadline time.Time
4449: +}
4450: +
4451: +// emit writes a packet under its merged interface ID. It reports false once the packet limit is
4452: +// reached and the capture stops.
4453: +func (run *captureRun) emit(id uint32, packet *clabcapture.Packet) (bool, error) {
4454: +	return run.out.Emit(id, packet)
4455: +}
4456: +
4457: +func (run *captureRun) reportGap(gap clablabruntime.CaptureGap) {
4458: +	clabcapture.ReportGap(run.req.OnGap, gap)
4459: +}
4460: +
4461: +// captureSegment is one clabwire capture process of a chain.
4462: +type captureSegment struct {
4463: +	index      int
4464: +	localStart time.Time
4465: +	duration   time.Duration
4466: +	cancel     context.CancelFunc
4467: +	// closeStdin closes the stdin of the segment's clabwire process, which ends it; it may be
4468: +	// called any number of times.
4469: +	closeStdin func()
4470: +	// stopTimer closes stdin once the segment is no longer needed after a switch-over.
4471: +	stopTimer *time.Timer
4472: +	// started and ended are the pod-clock times of the Started and Succeeded audit records.
4473: +	started time.Time
4474: +	ended   time.Time
4475: +	done    bool
4476: +}
4477: +
4478: +func (s *captureSegment) plannedEnd() time.Time {
4479: +	return s.started.Add(s.duration)
4480: +}
4481: +
4482: +// segmentEvent is something a segment reported: a packet, an audit record, or its end.
4483: +type segmentEvent struct {
4484: +	segment *captureSegment
4485: +	packet  *clabcapture.Packet
4486: +	audit   *captureAudit
4487: +	done    bool
4488: +	err     error
4489: +}
4490: +
4491: +// captureChain runs the chained clabwire captures of one group.
4492: +//
4493: +// Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both
4494: +// capture the same packets for a while. clabwire stamps packets when it reads them, so two
4495: +// processes give the same packet timestamps a few microseconds apart, and timestamps alone
4496: +// cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by
4497: +// content close to the cut:
4498: +//
4499: +//  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is
4500: +//     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.
4501: +//  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the
4502: +//     content of what it wrote since segment k+1 started.
4503: +//  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped
4504: +//     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped
4505: +//     when segment k wrote the same bytes on the same interface, and every other one is written.
4506: +//     From then on segment k+1 streams live.
4507: +//
4508: +// Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its
4509: +// planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other
4510: +// nodes' later packets do not overtake them in the merged stream.
4511: +//
4512: +// W (500 ms, less for short test segments) covers the stamping difference. Identical frames on
4513: +// the same interface within W of the cut can be paired with each other, which can drop a true
4514: +// repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves
4515: +// a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.
4516: +type captureChain struct {
4517: +	capture *captureRun
4518: +	group   *captureGroup
4519: +
4520: +	events chan segmentEvent
4521: +	wg     sync.WaitGroup
4522: +
4523: +	active *captureSegment
4524: +	next   *captureSegment
4525: +	// cut is the switch time between active and next, in nanoseconds; zero until known.
4526: +	cut int64
4527: +	// emitted remembers the content of the packets active wrote while next runs.
4528: +	emitted map[uint64]int
4529: +	// held are the packets of next until active ends.
4530: +	held     []*clabcapture.Packet
4531: +	segments int
4532: +	retries  int
4533: +	// final is set once no further segment is due.
4534: +	final bool
4535: +	// stopping is set once ctx ended: the segments are asked to end and what they still
4536: +	// deliver is written.
4537: +	stopping bool
4538: +}
4539: +
4540: +// run runs the chain until its last segment ended. When ctx ends, it stops the segments and
4541: +// keeps writing the packets they read until then; a segment that does not end within
4542: +// captureStdinCloseGrace is cut.
4543: +func (c *captureChain) run(ctx context.Context) error {
4544: +	c.events = make(chan segmentEvent, 256)
4545: +	// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them
4546: +	segmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
4547: +	var abort *time.Timer
4548: +	defer func() {
4549: +		if abort != nil {
4550: +			abort.Stop()
4551: +		}
4552: +		cancel()
4553: +		c.drain()
4554: +		c.capture.out.Release(c)
4555: +	}()
4556: +
4557: +	c.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))
4558: +	timer := time.NewTimer(c.nextStartIn())
4559: +	defer timer.Stop()
4560: +
4561: +	done := ctx.Done()
4562: +	for {
4563: +		select {
4564: +		case <-done:
4565: +			done = nil
4566: +			c.stop(timer)
4567: +			abort = time.AfterFunc(captureStdinCloseGrace, cancel)
4568: +		case <-segmentsCtx.Done():
4569: +			return nil
4570: +		case <-timer.C:
4571: +			if c.next == nil && !c.final {
4572: +				c.startNext(segmentsCtx)
4573: +			}
4574: +		case event := <-c.events:
4575: +			stop, err := c.handle(segmentsCtx, event, timer)
4576: +			if err != nil || stop {
4577: +				return err
4578: +			}
4579: +		}
4580: +	}
4581: +}
4582: +
4583: +// stop ends the chain early, like a deadline would: no further segment starts and the running
4584: +// ones are asked to end. The chain then writes what they deliver until they ended.
4585: +func (c *captureChain) stop(timer *time.Timer) {
4586: +	c.stopping = true
4587: +	c.final = true
4588: +	timer.Stop()
4589: +	c.active.closeStdin()
4590: +	if c.next != nil {
4591: +		c.next.closeStdin()
4592: +	}
4593: +}
4594: +
4595: +// drain waits for the segment goroutines after the chain ended.
4596: +func (c *captureChain) drain() {
4597: +	done := make(chan struct{})
4598: +	go func() {
4599: +		c.wg.Wait()
4600: +		close(done)
4601: +	}()
4602: +	for {
4603: +		select {
4604: +		case <-done:
4605: +			return
4606: +		case <-c.events:
4607: +		}
4608: +	}
4609: +}
4610: +
4611: +// segmentDuration is the requested duration of a segment starting now.
4612: +func (c *captureChain) segmentDuration(now time.Time) time.Duration {
4613: +	duration := c.capture.segment
4614: +	if !c.capture.deadline.IsZero() {
4615: +		duration = min(duration, c.capture.deadline.Sub(now))
4616: +	}
4617: +
4618: +	return max(duration, minCaptureSegment)
4619: +}
4620: +
4621: +// nextStartIn is the time until the follow-up of the active segment is due. It marks the chain
4622: +// final when none is due.
4623: +func (c *captureChain) nextStartIn() time.Duration {
4624: +	if c.stopping {
4625: +		c.final = true
4626: +		return maxCaptureSegment
4627: +	}
4628: +	activeEnd := c.active.localStart.Add(c.active.duration)
4629: +	if !c.capture.deadline.IsZero() &&
4630: +		!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {
4631: +		c.final = true
4632: +		return maxCaptureSegment
4633: +	}
4634: +	c.final = false
4635: +
4636: +	return max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)
4637: +}
4638: +
4639: +func (c *captureChain) startNext(ctx context.Context) {
4640: +	c.next = c.start(ctx, c.segmentDuration(time.Now()))
4641: +	c.emitted = map[uint64]int{}
4642: +	c.held = nil
4643: +	c.cut = 0
4644: +}
4645: +
4646: +func (c *captureChain) handle(
4647: +	ctx context.Context,
4648: +	event segmentEvent,
4649: +	timer *time.Timer,
4650: +) (bool, error) {
4651: +	segment := event.segment
4652: +
4653: +	switch {
4654: +	case event.audit != nil:
4655: +		return false, c.handleAudit(segment, event.audit)
4656: +	case event.packet != nil:
4657: +		return c.handlePacket(segment, event.packet)
4658: +	case event.done:
4659: +		segment.done = true
4660: +		if segment.stopTimer != nil {
4661: +			segment.stopTimer.Stop()
4662: +		}
4663: +		if event.err != nil && !c.stopping {
4664: +			if segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {
4665: +				// the follow-up did not start; try again while the active one still runs
4666: +				c.retries++
4667: +				log.Warn("Capture follow-up segment failed to start, retrying",
4668: +					"node", c.group.display, "error", event.err)
4669: +				c.next = nil
4670: +				resetTimer(timer, time.Second)
4671: +
4672: +				return false, nil
4673: +			}
4674: +
4675: +			return true, fmt.Errorf("capture on c9s node %s/%s/%s failed: %w",

(Showing lines 3976-4675 of 7018. Use offset=4676 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19653e41d001HjKPeyc3J1kNKY",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653dadf001LqnYSf5AYwEOrw",
  "callID": "call_0a4953ef254d4a7691face4b",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 700,
      "offset": 3976
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n3976: +\n3977: +// podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns\n3978: +// a *labruntime.CommandExitError.\n3979: +type podExecFunc func(\n3980: +\tctx context.Context,\n3981: +\tnamespace, pod, container string,\n3982: +\tcommand []string,\n3983: +\tstdin io.Reader,\n3984: +\tstdout, stderr io.Writer,\n3985: +) error\n3986: +\n3987: +// clabwireInterface is one entry of `packet-capture --list-interfaces`.\n3988: +type clabwireInterface struct {\n3989: +\tNode          string `json:\"node\"`\n3990: +\tInterface     string `json:\"interface\"`\n3991: +\tAlias         string `json:\"alias,omitempty\"`\n3992: +\tPeerNode      string `json:\"peerNode\"`\n3993: +\tPeerInterface string `json:\"peerInterface\"`\n3994: +}\n3995: +\n3996: +// captureAudit is one clabwire audit line.\n3997: +type captureAudit struct {\n3998: +\tSchemaVersion string    `json:\"schemaVersion\"`\n3999: +\tTime          time.Time `json:\"time\"`\n4000: +\tStatus        string    `json:\"status\"`\n4001: +\tNodeName      string    `json:\"nodeName\"`\n4002: +\tFormat        string    `json:\"format\"`\n4003: +\tReason        string    `json:\"reason\"`\n4004: +\tPackets       int       `json:\"packets\"`\n4005: +\tInterfaces    []struct {\n4006: +\t\tName    string `json:\"name\"`\n4007: +\t\tID      string `json:\"id\"`\n4008: +\t\tPackets int    `json:\"packets\"`\n4009: +\t} `json:\"interfaces\"`\n4010: +}\n4011: +\n4012: +func (r *Runtime) execInPodContainer() podExecFunc {\n4013: +\tif r.podExec != nil {\n4014: +\t\treturn r.podExec\n4015: +\t}\n4016: +\n4017: +\treturn r.streamPodExec\n4018: +}\n4019: +\n4020: +// captureSegmentLength is the length of one clabwire capture before the next takes over.\n4021: +func (r *Runtime) captureSegmentLength() time.Duration {\n4022: +\tif r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {\n4023: +\t\treturn r.captureSegment\n4024: +\t}\n4025: +\n4026: +\treturn maxCaptureSegment\n4027: +}\n4028: +\n4029: +// captureReorderWindowLength is the reorder window of the merged stream; zero disables\n4030: +// reordering.\n4031: +func (r *Runtime) captureReorderWindowLength() time.Duration {\n4032: +\tswitch {\n4033: +\tcase r.captureReorderWindow < 0:\n4034: +\t\treturn 0\n4035: +\tcase r.captureReorderWindow > 0:\n4036: +\t\treturn r.captureReorderWindow\n4037: +\t}\n4038: +\n4039: +\treturn defaultCaptureReorderWindow\n4040: +}\n4041: +\n4042: +// captureReorderWindowFromEnv reads the reorder window knob: unset or invalid keeps the\n4043: +// default (0), \"0\" disables reordering (-1).\n4044: +func captureReorderWindowFromEnv() time.Duration {\n4045: +\tvalue, err := time.ParseDuration(os.Getenv(envCaptureReorderWindow))\n4046: +\tswitch {\n4047: +\tcase err != nil || value < 0:\n4048: +\t\treturn 0\n4049: +\tcase value == 0:\n4050: +\t\treturn -1\n4051: +\t}\n4052: +\n4053: +\treturn value\n4054: +}\n4055: +\n4056: +func captureSegmentFromEnv() time.Duration {\n4057: +\tvalue, err := time.ParseDuration(os.Getenv(envCaptureSegment))\n4058: +\tif err != nil || value <= 0 {\n4059: +\t\treturn 0\n4060: +\t}\n4061: +\n4062: +\treturn value\n4063: +}\n4064: +\n4065: +// CaptureInterfaces lists the capturable lab link interfaces of the requested nodes, or of every\n4066: +// node, as clabwire reports them, with their peers. Node names are reported as the topology\n4067: +// spells them.\n4068: +func (r *Runtime) CaptureInterfaces(\n4069: +\tctx context.Context,\n4070: +\treq clablabruntime.NodeRequest,\n4071: +) ([]clablabruntime.CaptureInterface, error) {\n4072: +\tr, err := r.connect(ctx, req.Identity)\n4073: +\tif err != nil {\n4074: +\t\treturn nil, err\n4075: +\t}\n4076: +\n4077: +\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n4078: +\t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n4079: +\t})\n4080: +\tif err != nil {\n4081: +\t\treturn nil, err\n4082: +\t}\n4083: +\tif len(req.Nodes) == 0 {\n4084: +\t\t// a lab-wide listing skips nodes that do not run\n4085: +\t\trunning := locations[:0]\n4086: +\t\tfor _, location := range locations {\n4087: +\t\t\tif location.Pod != \"\" {\n4088: +\t\t\t\trunning = append(running, location)\n4089: +\t\t\t}\n4090: +\t\t}\n4091: +\t\tlocations = running\n4092: +\t}\n4093: +\n4094: +\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n4095: +\tif err != nil {\n4096: +\t\treturn nil, err\n4097: +\t}\n4098: +\tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n4099: +\tif err != nil {\n4100: +\t\treturn nil, err\n4101: +\t}\n4102: +\n4103: +\tresult := make([]clablabruntime.CaptureInterface, 0)\n4104: +\tfor _, location := range locations {\n4105: +\t\tfor _, entry := range listed[location.NodeName] {\n4106: +\t\t\tresult = append(result, clablabruntime.CaptureInterface{\n4107: +\t\t\t\tNode:          names.display(entry.Node),\n4108: +\t\t\t\tInterface:     entry.Interface,\n4109: +\t\t\t\tAlias:         entry.Alias,\n4110: +\t\t\t\tPeerNode:      names.display(entry.PeerNode),\n4111: +\t\t\t\tPeerInterface: entry.PeerInterface,\n4112: +\t\t\t})\n4113: +\t\t}\n4114: +\t}\n4115: +\tsort.SliceStable(result, func(i, j int) bool {\n4116: +\t\tif result[i].Node != result[j].Node {\n4117: +\t\t\treturn result[i].Node < result[j].Node\n4118: +\t\t}\n4119: +\n4120: +\t\treturn result[i].Interface < result[j].Interface\n4121: +\t})\n4122: +\n4123: +\treturn result, nil\n4124: +}\n4125: +\n4126: +// listCaptureInterfaces runs one --list-interfaces per pod and returns the entries per Node.\n4127: +func (r *Runtime) listCaptureInterfaces(\n4128: +\tctx context.Context,\n4129: +\tlab string,\n4130: +\tlocations []clablabruntime.NodeLocation,\n4131: +) (map[string][]clabwireInterface, error) {\n4132: +\tpods := map[string]clablabruntime.NodeLocation{}\n4133: +\twanted := map[string]bool{}\n4134: +\tfor _, location := range locations {\n4135: +\t\tif location.Pod == \"\" {\n4136: +\t\t\treturn nil, fmt.Errorf(\"c9s node %s/%s/%s has no pod; is it running?\",\n4137: +\t\t\t\tlocation.Namespace, lab, location.NodeName)\n4138: +\t\t}\n4139: +\t\tpods[location.Namespace+\"/\"+location.Pod] = location\n4140: +\t\twanted[location.NodeName] = true\n4141: +\t}\n4142: +\n4143: +\tvar mu sync.Mutex\n4144: +\tresult := map[string][]clabwireInterface{}\n4145: +\tgroup, groupCtx := errgroup.WithContext(ctx)\n4146: +\tgroup.SetLimit(interfaceSampleWorkers)\n4147: +\texec := r.execInPodContainer()\n4148: +\tfor _, location := range pods {\n4149: +\t\tgroup.Go(func() error {\n4150: +\t\t\tvar stdout, stderr bytes.Buffer\n4151: +\t\t\terr := exec(groupCtx, location.Namespace, location.Pod, clabwireContainer,\n4152: +\t\t\t\t[]string{clabwireManager, \"node-runtime\", \"packet-capture\", \"--list-interfaces\"},\n4153: +\t\t\t\tnil, &stdout, &stderr)\n4154: +\t\t\tif err != nil {\n4155: +\t\t\t\treturn fmt.Errorf(\"failed to list the capturable interfaces of pod %s/%s: %w%s\",\n4156: +\t\t\t\t\tlocation.Namespace, location.Pod, err, stderrSuffix(stderr.Bytes()))\n4157: +\t\t\t}\n4158: +\n4159: +\t\t\tvar entries []clabwireInterface\n4160: +\t\t\tif err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {\n4161: +\t\t\t\treturn fmt.Errorf(\"failed to parse the capturable interfaces of pod %s/%s: %w\",\n4162: +\t\t\t\t\tlocation.Namespace, location.Pod, err)\n4163: +\t\t\t}\n4164: +\n4165: +\t\t\tmu.Lock()\n4166: +\t\t\tdefer mu.Unlock()\n4167: +\t\t\tfor _, entry := range entries {\n4168: +\t\t\t\tif wanted[entry.Node] {\n4169: +\t\t\t\t\tresult[entry.Node] = append(result[entry.Node], entry)\n4170: +\t\t\t\t}\n4171: +\t\t\t}\n4172: +\n4173: +\t\t\treturn nil\n4174: +\t\t})\n4175: +\t}\n4176: +\tif err := group.Wait(); err != nil {\n4177: +\t\treturn nil, err\n4178: +\t}\n4179: +\n4180: +\treturn result, nil\n4181: +}\n4182: +\n4183: +func stderrSuffix(stderr []byte) string {\n4184: +\ttext := strings.TrimSpace(string(stderr))\n4185: +\tif text == \"\" {\n4186: +\t\treturn \"\"\n4187: +\t}\n4188: +\n4189: +\treturn \": \" + text\n4190: +}\n4191: +\n4192: +// nodeNames maps the node names the cluster carries to the names the topology file uses.\n4193: +type nodeNames map[string]string\n4194: +\n4195: +func (n nodeNames) display(name string) string {\n4196: +\tif original := n[name]; original != \"\" {\n4197: +\t\treturn original\n4198: +\t}\n4199: +\n4200: +\treturn name\n4201: +}\n4202: +\n4203: +// nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the\n4204: +// lab's Nodes.\n4205: +func (r *Runtime) nodeDisplayNames(\n4206: +\tctx context.Context,\n4207: +\tlab string,\n4208: +\tlocations []clablabruntime.NodeLocation,\n4209: +) (nodeNames, error) {\n4210: +\tnames := nodeNames{}\n4211: +\tif len(locations) == 0 {\n4212: +\t\treturn names, nil\n4213: +\t}\n4214: +\n4215: +\tnodes, err := r.nodesForTopology(ctx, lab, locations[0].Namespace)\n4216: +\tif err != nil {\n4217: +\t\treturn nil, err\n4218: +\t}\n4219: +\tfor idx := range nodes.Items {\n4220: +\t\tif original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != \"\" {\n4221: +\t\t\tnames[nodes.Items[idx].GetName()] = original\n4222: +\t\t}\n4223: +\t}\n4224: +\n4225: +\treturn names, nil\n4226: +}\n4227: +\n4228: +// captureGroup is the part of a capture one clabwire process serves: the requested interfaces of\n4229: +// one node, in one pod.\n4230: +type captureGroup struct {\n4231: +\tlocation clablabruntime.NodeLocation\n4232: +\tdisplay  string\n4233: +\t// interfaces are the planned interface names, in the order the merged stream lists them.\n4234: +\tinterfaces []string\n4235: +\t// ids are the merged interface IDs of interfaces.\n4236: +\tids []uint32\n4237: +}\n4238: +\n4239: +// resolvedCapture is a validated capture request.\n4240: +type resolvedCapture struct {\n4241: +\tgroups []*captureGroup\n4242: +\t// names are the merged interface names (<node>:<interface>), indexed by merged ID.\n4243: +\tnames []string\n4244: +}\n4245: +\n4246: +// resolveCaptureTargets locates every target node, checks every interface against the\n4247: +// interfaces clabwire allows, and groups the targets per node.\n4248: +func (r *Runtime) resolveCaptureTargets(\n4249: +\tctx context.Context,\n4250: +\treq clablabruntime.CaptureRequest,\n4251: +) (*resolvedCapture, error) {\n4252: +\tnodeOrder := make([]string, 0, len(req.Targets))\n4253: +\tseenNodes := map[string]bool{}\n4254: +\tfor _, target := range req.Targets {\n4255: +\t\tif !seenNodes[target.Node] {\n4256: +\t\t\tseenNodes[target.Node] = true\n4257: +\t\t\tnodeOrder = append(nodeOrder, target.Node)\n4258: +\t\t}\n4259: +\t}\n4260: +\n4261: +\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n4262: +\t\tName: req.Name, Namespace: req.Namespace, Nodes: nodeOrder, Identity: req.Identity,\n4263: +\t})\n4264: +\tif err != nil {\n4265: +\t\treturn nil, err\n4266: +\t}\n4267: +\tbyRequest := make(map[string]clablabruntime.NodeLocation, len(nodeOrder))\n4268: +\tfor idx, name := range nodeOrder {\n4269: +\t\tbyRequest[name] = locations[idx]\n4270: +\t}\n4271: +\n4272: +\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n4273: +\tif err != nil {\n4274: +\t\treturn nil, err\n4275: +\t}\n4276: +\tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n4277: +\tif err != nil {\n4278: +\t\treturn nil, err\n4279: +\t}\n4280: +\n4281: +\tresolved := &resolvedCapture{}\n4282: +\tgroups := map[string]*captureGroup{}\n4283: +\tseen := map[string]bool{}\n4284: +\tfor _, target := range req.Targets {\n4285: +\t\tlocation := byRequest[target.Node]\n4286: +\t\tentry, ok := findCaptureInterface(listed[location.NodeName], target.Interface)\n4287: +\t\tif !ok {\n4288: +\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n4289: +\t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n4290: +\t\t\t\tdescribeCaptureInterfaces(listed[location.NodeName]))\n4291: +\t\t}\n4292: +\n4293: +\t\tkey := location.NodeName + \"\\x00\" + entry.Interface\n4294: +\t\tif seen[key] {\n4295: +\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n4296: +\t\t\t\tentry.Interface, target.Node)\n4297: +\t\t}\n4298: +\t\tseen[key] = true\n4299: +\n4300: +\t\tgroup := groups[location.NodeName]\n4301: +\t\tif group == nil {\n4302: +\t\t\tgroup = &captureGroup{\n4303: +\t\t\t\tlocation: location,\n4304: +\t\t\t\tdisplay:  names.display(location.NodeName),\n4305: +\t\t\t}\n4306: +\t\t\tgroups[location.NodeName] = group\n4307: +\t\t\tresolved.groups = append(resolved.groups, group)\n4308: +\t\t}\n4309: +\n4310: +\t\tid := uint32(len(resolved.names)) //nolint:gosec // bounded by the targets\n4311: +\t\tgroup.interfaces = append(group.interfaces, entry.Interface)\n4312: +\t\tgroup.ids = append(group.ids, id)\n4313: +\t\tresolved.names = append(resolved.names, group.display+\":\"+entry.Interface)\n4314: +\t}\n4315: +\n4316: +\treturn resolved, nil\n4317: +}\n4318: +\n4319: +// findCaptureInterface matches a requested interface by its planned name or its alias.\n4320: +func findCaptureInterface(entries []clabwireInterface, name string) (clabwireInterface, bool) {\n4321: +\tfor _, entry := range entries {\n4322: +\t\tif entry.Interface == name {\n4323: +\t\t\treturn entry, true\n4324: +\t\t}\n4325: +\t}\n4326: +\tfor _, entry := range entries {\n4327: +\t\tif entry.Alias != \"\" && entry.Alias == name {\n4328: +\t\t\treturn entry, true\n4329: +\t\t}\n4330: +\t}\n4331: +\n4332: +\treturn clabwireInterface{}, false\n4333: +}\n4334: +\n4335: +func describeCaptureInterfaces(entries []clabwireInterface) string {\n4336: +\tif len(entries) == 0 {\n4337: +\t\treturn \"none\"\n4338: +\t}\n4339: +\n4340: +\tnames := make([]string, 0, len(entries))\n4341: +\tfor _, entry := range entries {\n4342: +\t\tname := entry.Interface\n4343: +\t\tif entry.Alias != \"\" {\n4344: +\t\t\tname += \" (\" + entry.Alias + \")\"\n4345: +\t\t}\n4346: +\t\tnames = append(names, name)\n4347: +\t}\n4348: +\n4349: +\treturn strings.Join(names, \", \")\n4350: +}\n4351: +\n4352: +// Capture streams pcapng from lab link interfaces to w: one section, one Interface Description\n4353: +// Block per target in request order named <node>:<interface>, then the packets of every target.\n4354: +//\n4355: +// Each node's interfaces are captured by one clabwire process in the node's pod. clabwire limits\n4356: +// a capture to one hour, so a longer capture (or one without Duration) chains captures: the next\n4357: +// one starts before the current one ends, and the stream switches at a cut in the overlap. See\n4358: +// captureChain for how packets of the overlap are kept once.\n4359: +//\n4360: +// Packets go out in timestamp order across nodes, through a reorder buffer (captureReorder).\n4361: +//\n4362: +// Every clabwire process runs with stdin attached and --stop-on-stdin-close: a Kubernetes exec\n4363: +// does not stop its process when the stream closes, so containerlab closes stdin whenever a\n4364: +// segment ends (the capture ends, fails, its output fails, or a newer segment took over) and\n4365: +// clabwire ends the capture itself.\n4366: +//\n4367: +// Capture returns when Duration has passed, PacketLimit packets were written, or ctx ends; an\n4368: +// ended ctx is not an error. Every block reaches w in one write, so the stream is a valid capture\n4369: +// whenever it stops. A clabwire Denied or Failed audit record is returned as an error.\n4370: +func (r *Runtime) Capture(\n4371: +\tctx context.Context,\n4372: +\treq clablabruntime.CaptureRequest,\n4373: +\tw io.Writer,\n4374: +) error {\n4375: +\tif err := clabcapture.ValidateRequest(&req); err != nil {\n4376: +\t\treturn err\n4377: +\t}\n4378: +\n4379: +\tr, err := r.connect(ctx, req.Identity)\n4380: +\tif err != nil {\n4381: +\t\treturn err\n4382: +\t}\n4383: +\n4384: +\tresolved, err := r.resolveCaptureTargets(ctx, req)\n4385: +\tif err != nil {\n4386: +\t\treturn err\n4387: +\t}\n4388: +\n4389: +\tcaptureCtx, stop := context.WithCancel(ctx)\n4390: +\tdefer stop()\n4391: +\n4392: +\tout, err := clabcapture.NewOutput(w, resolved.names, req.SnapLength, req.PacketLimit,\n4393: +\t\tr.captureReorderWindowLength(), stop)\n4394: +\tif err != nil {\n4395: +\t\treturn err\n4396: +\t}\n4397: +\n4398: +\trun := &captureRun{\n4399: +\t\tr:       r,\n4400: +\t\treq:     req,\n4401: +\t\tout:     out,\n4402: +\t\tsegment: r.captureSegmentLength(),\n4403: +\t}\n4404: +\tif req.Duration > 0 {\n4405: +\t\trun.deadline = time.Now().Add(req.Duration)\n4406: +\t}\n4407: +\trun.overlap = min(maxCaptureOverlap, run.segment/3)\n4408: +\trun.window = min(maxCaptureCutWindow, run.overlap/4)\n4409: +\n4410: +\tif req.Duration > 0 {\n4411: +\t\t// a clabwire process that does not end on its own does not hold the capture open\n4412: +\t\tvar cancelTimeout context.CancelFunc\n4413: +\t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx,\n4414: +\t\t\treq.Duration+run.overlap+captureEndGrace)\n4415: +\t\tdefer cancelTimeout()\n4416: +\t}\n4417: +\n4418: +\tgroup, groupCtx := errgroup.WithContext(captureCtx)\n4419: +\tfor _, captureGroup := range resolved.groups {\n4420: +\t\tchain := &captureChain{capture: run, group: captureGroup}\n4421: +\t\tgroup.Go(func() error {\n4422: +\t\t\treturn chain.run(groupCtx)\n4423: +\t\t})\n4424: +\t}\n4425: +\n4426: +\terr = group.Wait()\n4427: +\tif writeErr := out.Close(); writeErr != nil {\n4428: +\t\treturn writeErr\n4429: +\t}\n4430: +\tif err != nil && !(errors.Is(err, context.Canceled) && captureCtx.Err() != nil) {\n4431: +\t\treturn err\n4432: +\t}\n4433: +\n4434: +\treturn nil\n4435: +}\n4436: +\n4437: +// captureRun is the state a capture's chains share.\n4438: +type captureRun struct {\n4439: +\tr   *Runtime\n4440: +\treq clablabruntime.CaptureRequest\n4441: +\t// out is the merged stream; it writes the packets of every chain in timestamp order and\n4442: +\t// stops every chain once the packet limit is reached.\n4443: +\tout *clabcapture.Output\n4444: +\n4445: +\tsegment  time.Duration\n4446: +\toverlap  time.Duration\n4447: +\twindow   time.Duration\n4448: +\tdeadline time.Time\n4449: +}\n4450: +\n4451: +// emit writes a packet under its merged interface ID. It reports false once the packet limit is\n4452: +// reached and the capture stops.\n4453: +func (run *captureRun) emit(id uint32, packet *clabcapture.Packet) (bool, error) {\n4454: +\treturn run.out.Emit(id, packet)\n4455: +}\n4456: +\n4457: +func (run *captureRun) reportGap(gap clablabruntime.CaptureGap) {\n4458: +\tclabcapture.ReportGap(run.req.OnGap, gap)\n4459: +}\n4460: +\n4461: +// captureSegment is one clabwire capture process of a chain.\n4462: +type captureSegment struct {\n4463: +\tindex      int\n4464: +\tlocalStart time.Time\n4465: +\tduration   time.Duration\n4466: +\tcancel     context.CancelFunc\n4467: +\t// closeStdin closes the stdin of the segment's clabwire process, which ends it; it may be\n4468: +\t// called any number of times.\n4469: +\tcloseStdin func()\n4470: +\t// stopTimer closes stdin once the segment is no longer needed after a switch-over.\n4471: +\tstopTimer *time.Timer\n4472: +\t// started and ended are the pod-clock times of the Started and Succeeded audit records.\n4473: +\tstarted time.Time\n4474: +\tended   time.Time\n4475: +\tdone    bool\n4476: +}\n4477: +\n4478: +func (s *captureSegment) plannedEnd() time.Time {\n4479: +\treturn s.started.Add(s.duration)\n4480: +}\n4481: +\n4482: +// segmentEvent is something a segment reported: a packet, an audit record, or its end.\n4483: +type segmentEvent struct {\n4484: +\tsegment *captureSegment\n4485: +\tpacket  *clabcapture.Packet\n4486: +\taudit   *captureAudit\n4487: +\tdone    bool\n4488: +\terr     error\n4489: +}\n4490: +\n4491: +// captureChain runs the chained clabwire captures of one group.\n4492: +//\n4493: +// Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both\n4494: +// capture the same packets for a while. clabwire stamps packets when it reads them, so two\n4495: +// processes give the same packet timestamps a few microseconds apart, and timestamps alone\n4496: +// cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by\n4497: +// content close to the cut:\n4498: +//\n4499: +//  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is\n4500: +//     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.\n4501: +//  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the\n4502: +//     content of what it wrote since segment k+1 started.\n4503: +//  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped\n4504: +//     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped\n4505: +//     when segment k wrote the same bytes on the same interface, and every other one is written.\n4506: +//     From then on segment k+1 streams live.\n4507: +//\n4508: +// Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its\n4509: +// planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other\n4510: +// nodes' later packets do not overtake them in the merged stream.\n4511: +//\n4512: +// W (500 ms, less for short test segments) covers the stamping difference. Identical frames on\n4513: +// the same interface within W of the cut can be paired with each other, which can drop a true\n4514: +// repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves\n4515: +// a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.\n4516: +type captureChain struct {\n4517: +\tcapture *captureRun\n4518: +\tgroup   *captureGroup\n4519: +\n4520: +\tevents chan segmentEvent\n4521: +\twg     sync.WaitGroup\n4522: +\n4523: +\tactive *captureSegment\n4524: +\tnext   *captureSegment\n4525: +\t// cut is the switch time between active and next, in nanoseconds; zero until known.\n4526: +\tcut int64\n4527: +\t// emitted remembers the content of the packets active wrote while next runs.\n4528: +\temitted map[uint64]int\n4529: +\t// held are the packets of next until active ends.\n4530: +\theld     []*clabcapture.Packet\n4531: +\tsegments int\n4532: +\tretries  int\n4533: +\t// final is set once no further segment is due.\n4534: +\tfinal bool\n4535: +\t// stopping is set once ctx ended: the segments are asked to end and what they still\n4536: +\t// deliver is written.\n4537: +\tstopping bool\n4538: +}\n4539: +\n4540: +// run runs the chain until its last segment ended. When ctx ends, it stops the segments and\n4541: +// keeps writing the packets they read until then; a segment that does not end within\n4542: +// captureStdinCloseGrace is cut.\n4543: +func (c *captureChain) run(ctx context.Context) error {\n4544: +\tc.events = make(chan segmentEvent, 256)\n4545: +\t// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them\n4546: +\tsegmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))\n4547: +\tvar abort *time.Timer\n4548: +\tdefer func() {\n4549: +\t\tif abort != nil {\n4550: +\t\t\tabort.Stop()\n4551: +\t\t}\n4552: +\t\tcancel()\n4553: +\t\tc.drain()\n4554: +\t\tc.capture.out.Release(c)\n4555: +\t}()\n4556: +\n4557: +\tc.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))\n4558: +\ttimer := time.NewTimer(c.nextStartIn())\n4559: +\tdefer timer.Stop()\n4560: +\n4561: +\tdone := ctx.Done()\n4562: +\tfor {\n4563: +\t\tselect {\n4564: +\t\tcase <-done:\n4565: +\t\t\tdone = nil\n4566: +\t\t\tc.stop(timer)\n4567: +\t\t\tabort = time.AfterFunc(captureStdinCloseGrace, cancel)\n4568: +\t\tcase <-segmentsCtx.Done():\n4569: +\t\t\treturn nil\n4570: +\t\tcase <-timer.C:\n4571: +\t\t\tif c.next == nil && !c.final {\n4572: +\t\t\t\tc.startNext(segmentsCtx)\n4573: +\t\t\t}\n4574: +\t\tcase event := <-c.events:\n4575: +\t\t\tstop, err := c.handle(segmentsCtx, event, timer)\n4576: +\t\t\tif err != nil || stop {\n4577: +\t\t\t\treturn err\n4578: +\t\t\t}\n4579: +\t\t}\n4580: +\t}\n4581: +}\n4582: +\n4583: +// stop ends the chain early, like a deadline would: no further segment starts and the running\n4584: +// ones are asked to end. The chain then writes what they deliver until they ended.\n4585: +func (c *captureChain) stop(timer *time.Timer) {\n4586: +\tc.stopping = true\n4587: +\tc.final = true\n4588: +\ttimer.Stop()\n4589: +\tc.active.closeStdin()\n4590: +\tif c.next != nil {\n4591: +\t\tc.next.closeStdin()\n4592: +\t}\n4593: +}\n4594: +\n4595: +// drain waits for the segment goroutines after the chain ended.\n4596: +func (c *captureChain) drain() {\n4597: +\tdone := make(chan struct{})\n4598: +\tgo func() {\n4599: +\t\tc.wg.Wait()\n4600: +\t\tclose(done)\n4601: +\t}()\n4602: +\tfor {\n4603: +\t\tselect {\n4604: +\t\tcase <-done:\n4605: +\t\t\treturn\n4606: +\t\tcase <-c.events:\n4607: +\t\t}\n4608: +\t}\n4609: +}\n4610: +\n4611: +// segmentDuration is the requested duration of a segment starting now.\n4612: +func (c *captureChain) segmentDuration(now time.Time) time.Duration {\n4613: +\tduration := c.capture.segment\n4614: +\tif !c.capture.deadline.IsZero() {\n4615: +\t\tduration = min(duration, c.capture.deadline.Sub(now))\n4616: +\t}\n4617: +\n4618: +\treturn max(duration, minCaptureSegment)\n4619: +}\n4620: +\n4621: +// nextStartIn is the time until the follow-up of the active segment is due. It marks the chain\n4622: +// final when none is due.\n4623: +func (c *captureChain) nextStartIn() time.Duration {\n4624: +\tif c.stopping {\n4625: +\t\tc.final = true\n4626: +\t\treturn maxCaptureSegment\n4627: +\t}\n4628: +\tactiveEnd := c.active.localStart.Add(c.active.duration)\n4629: +\tif !c.capture.deadline.IsZero() &&\n4630: +\t\t!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {\n4631: +\t\tc.final = true\n4632: +\t\treturn maxCaptureSegment\n4633: +\t}\n4634: +\tc.final = false\n4635: +\n4636: +\treturn max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)\n4637: +}\n4638: +\n4639: +func (c *captureChain) startNext(ctx context.Context) {\n4640: +\tc.next = c.start(ctx, c.segmentDuration(time.Now()))\n4641: +\tc.emitted = map[uint64]int{}\n4642: +\tc.held = nil\n4643: +\tc.cut = 0\n4644: +}\n4645: +\n4646: +func (c *captureChain) handle(\n4647: +\tctx context.Context,\n4648: +\tevent segmentEvent,\n4649: +\ttimer *time.Timer,\n4650: +) (bool, error) {\n4651: +\tsegment := event.segment\n4652: +\n4653: +\tswitch {\n4654: +\tcase event.audit != nil:\n4655: +\t\treturn false, c.handleAudit(segment, event.audit)\n4656: +\tcase event.packet != nil:\n4657: +\t\treturn c.handlePacket(segment, event.packet)\n4658: +\tcase event.done:\n4659: +\t\tsegment.done = true\n4660: +\t\tif segment.stopTimer != nil {\n4661: +\t\t\tsegment.stopTimer.Stop()\n4662: +\t\t}\n4663: +\t\tif event.err != nil && !c.stopping {\n4664: +\t\t\tif segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {\n4665: +\t\t\t\t// the follow-up did not start; try again while the active one still runs\n4666: +\t\t\t\tc.retries++\n4667: +\t\t\t\tlog.Warn(\"Capture follow-up segment failed to start, retrying\",\n4668: +\t\t\t\t\t\"node\", c.group.display, \"error\", event.err)\n4669: +\t\t\t\tc.next = nil\n4670: +\t\t\t\tresetTimer(timer, time.Second)\n4671: +\n4672: +\t\t\t\treturn false, nil\n4673: +\t\t\t}\n4674: +\n4675: +\t\t\treturn true, fmt.Errorf(\"capture on c9s node %s/%s/%s failed: %w\",\n\n(Showing lines 3976-4675 of 7018. Use offset=4676 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+\n+// podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns\n+// a *labruntime.CommandExitError.\n+type podExecFunc func(\n+\tctx context.Context,\n+\tnamespace, pod, container string,\n+\tcommand []string,\n+\tstdin io.Reader,\n+\tstdout, stderr io.Writer,\n+) error\n+\n+// clabwireInterface is one entry of `packet-capture --list-interfaces`.\n+type clabwireInterface struct {\n+\tNode          string `json:\"node\"`\n+\tInterface     string `json:\"interface\"`\n+\tAlias         string `json:\"alias,omitempty\"`\n+\tPeerNode      string `json:\"peerNode\"`\n+\tPeerInterface string `json:\"peerInterface\"`\n+}\n+",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+\n+// podExecFunc runs a command in a pod container and streams its output. A nonzero exit returns\n+// a *labruntime.CommandExitError.\n+type podExecFunc func(\n+\tctx context.Context,\n+\tnamespace, pod, container string,\n+\tcommand []string,\n+\tstdin io.Reader,\n+\tstdout, stderr io.Writer,\n+) error\n+\n+// clabwireInterface is one entry of `packet-capture --list-interfaces`.\n+type clabwireInterface struct {\n+\tNode          string `json:\"node\"`\n+\tInterface     string `json:\"interface\"`\n+\tAlias         string `json:\"alias,omitempty\"`\n+\tPeerNode      string `json:\"peerNode\"`\n+\tPeerInterface string `json:\"peerInterface\"`\n+}\n+\n+// captureAudit is one clabwire audit line.\n+type captureAudit struct {\n+\tSchemaVersion string    `json:\"schemaVersion\"`\n+\tTime          time.Time `json:\"time\"`\n+\tStatus        string    `json:\"status\"`\n+\tNodeName      string    `json:\"nodeName\"`\n+\tFormat        string    `json:\"format\"`\n+\tReason        string    `json:\"reason\"`\n+\tPackets       int       `json:\"packets\"`\n+\tInterfaces    []struct {\n+\t\tName    string `json:\"name\"`\n+\t\tID      string `json:\"id\"`\n+\t\tPackets int    `json:\"packets\"`\n+\t} `json:\"interfaces\"`\n+}\n+\n+func (r *Runtime) execInPodContainer() podExecFunc {\n+\tif r.podExec != nil {\n+\t\treturn r.podExec\n+\t}\n+\n+\treturn r.streamPodExec\n+}\n+\n+// captureSegmentLength is the length of one clabwire capture before the next takes over.\n+func (r *Runtime) captureSegmentLength() time.Duration {\n+\tif r.captureSegment > 0 && r.captureSegment <= maxCaptureSegment {\n+\t\treturn r.captureSegment\n+\t}\n+\n+\treturn maxCaptureSegment\n+}\n+\n+// captureReorderWindowLength is the reorder window of the merged stream; zero disables\n+// reordering.\n+func (r *Runtime) captureReorderWindowLength() time.Duration {\n+\tswitch {\n+\tcase r.captureReorderWindow < 0:\n+\t\treturn 0\n+\tcase r.captureReorderWindow > 0:\n+\t\treturn r.captureReorderWindow\n+\t}\n+\n+\treturn defaultCaptureReorderWindow\n+}\n+\n+// captureReorderWindowFromEnv reads the reorder window knob: unset or invalid keeps the\n+// default (0), \"0\" disables reordering (-1).\n+func captureReorderWindowFromEnv() time.Duration {\n+\tvalue, err := time.ParseDuration(os.Getenv(envCaptureReorderWindow))\n+\tswitch {\n+\tcase err != nil || value < 0:\n+\t\treturn 0\n+\tcase value == 0:\n+\t\treturn -1\n+\t}\n+\n+\treturn value\n+}\n+\n+func captureSegmentFromEnv() time.Duration {\n+\tvalue, err := time.ParseDuration(os.Getenv(envCaptureSegment))\n+\tif err != nil || value <= 0 {\n+\t\treturn 0\n+\t}\n+\n+\treturn value\n+}\n+\n+// CaptureInterfaces lists the capturable lab link interfaces of the requested nodes, or of every\n+// node, as clabwire reports them, with their peers. Node names are reported as the topology\n+// spells them.\n+func (r *Runtime) CaptureInterfaces(\n+\tctx context.Context,\n+\treq clablabruntime.NodeRequest,\n+) ([]clablabruntime.CaptureInterface, error) {\n+\tr, err := r.connect(ctx, req.Identity)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n+\t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n+\t})\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tif len(req.Nodes) == 0 {\n+\t\t// a lab-wide listing skips nodes that do not run\n+\t\trunning := locations[:0]\n+\t\tfor _, location := range locations {\n+\t\t\tif location.Pod != \"\" {\n+\t\t\t\trunning = append(running, location)\n+\t\t\t}\n+\t\t}\n+\t\tlocations = running\n+\t}\n+\n+\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\tresult := make([]clablabruntime.CaptureInterface, 0)\n+\tfor _, location := range locations {\n+\t\tfor _, entry := range listed[location.NodeName] {\n+\t\t\tresult = append(result, clablabruntime.CaptureInterface{\n+\t\t\t\tNode:          names.display(entry.Node),\n+\t\t\t\tInterface:     entry.Interface,\n+\t\t\t\tAlias:         entry.Alias,\n+\t\t\t\tPeerNode:      names.display(entry.PeerNode),\n+\t\t\t\tPeerInterface: entry.PeerInterface,\n+\t\t\t})\n+\t\t}\n+\t}\n+\tsort.SliceStable(result, func(i, j int) bool {\n+\t\tif result[i].Node != result[j].Node {\n+\t\t\treturn result[i].Node < result[j].Node\n+\t\t}\n+\n+\t\treturn result[i].Interface < result[j].Interface\n+\t})\n+\n+\treturn result, nil\n+}\n+\n+// listCaptureInterfaces runs one --list-interfaces per pod and returns the entries per Node.\n+func (r *Runtime) listCaptureInterfaces(\n+\tctx context.Context,\n+\tlab string,\n+\tlocations []clablabruntime.NodeLocation,\n+) (map[string][]clabwireInterface, error) {\n+\tpods := map[string]clablabruntime.NodeLocation{}\n+\twanted := map[string]bool{}\n+\tfor _, location := range locations {\n+\t\tif location.Pod == \"\" {\n+\t\t\treturn nil, fmt.Errorf(\"c9s node %s/%s/%s has no pod; is it running?\",\n+\t\t\t\tlocation.Namespace, lab, location.NodeName)\n+\t\t}\n+\t\tpods[location.Namespace+\"/\"+location.Pod] = location\n+\t\twanted[location.NodeName] = true\n+\t}\n+\n+\tvar mu sync.Mutex\n+\tresult := map[string][]clabwireInterface{}\n+\tgroup, groupCtx := errgroup.WithContext(ctx)\n+\tgroup.SetLimit(interfaceSampleWorkers)\n+\texec := r.execInPodContainer()\n+\tfor _, location := range pods {\n+\t\tgroup.Go(func() error {\n+\t\t\tvar stdout, stderr bytes.Buffer\n+\t\t\terr := exec(groupCtx, location.Namespace, location.Pod, clabwireContainer,\n+\t\t\t\t[]string{clabwireManager, \"node-runtime\", \"packet-capture\", \"--list-interfaces\"},\n+\t\t\t\tnil, &stdout, &stderr)\n+\t\t\tif err != nil {\n+\t\t\t\treturn fmt.Errorf(\"failed to list the capturable interfaces of pod %s/%s: %w%s\",\n+\t\t\t\t\tlocation.Namespace, location.Pod, err, stderrSuffix(stderr.Bytes()))\n+\t\t\t}\n+\n+\t\t\tvar entries []clabwireInterface\n+\t\t\tif err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {\n+\t\t\t\treturn fmt.Errorf(\"failed to parse the capturable interfaces of pod %s/%s: %w\",\n+\t\t\t\t\tlocation.Namespace, location.Pod, err)\n+\t\t\t}\n+\n+\t\t\tmu.Lock()\n+\t\t\tdefer mu.Unlock()\n+\t\t\tfor _, entry := range entries {\n+\t\t\t\tif wanted[entry.Node] {\n+\t\t\t\t\tresult[entry.Node] = append(result[entry.Node], entry)\n+\t\t\t\t}\n+\t\t\t}\n+\n+\t\t\treturn nil\n+\t\t})\n+\t}\n+\tif err := group.Wait(); err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\treturn result, nil\n+}\n+\n+func stderrSuffix(stderr []byte) string {\n+\ttext := strings.TrimSpace(string(stderr))\n+\tif text == \"\" {\n+\t\treturn \"\"\n+\t}\n+\n+\treturn \": \" + text\n+}\n+\n+// nodeNames maps the node names the cluster carries to the names the topology file uses.\n+type nodeNames map[string]string\n+\n+func (n nodeNames) display(name string) string {\n+\tif original := n[name]; original != \"\" {\n+\t\treturn original\n+\t}\n+\n+\treturn name\n+}\n+\n+// nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the\n+// lab's Nodes.\n+func (r *Runtime) nodeDisplayNames(\n+\tctx context.Context,\n+\tlab string,\n+\tlocations []clablabruntime.NodeLocation,\n+) (nodeNames, error) {\n+\tnames := nodeNames{}\n+\tif len(locations) == 0 {\n+\t\treturn names, nil\n+\t}\n+\n+\tnodes, err := r.nodesForTopology(ctx, lab, locations[0].Namespace)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tfor idx := range nodes.Items {\n+\t\tif original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != \"\" {\n+\t\t\tnames[nodes.Items[idx].GetName()] = original\n+\t\t}\n+\t}\n+\n+\treturn names, nil\n+}\n+\n+// captureGroup is the part of a capture one clabwire process serves: the requested interfaces of\n+// one node, in one pod.\n+type captureGroup struct {\n+\tlocation clablabruntime.NodeLocation\n+\tdisplay  string\n+\t// interfaces are the planned interface names, in the order the merged stream lists them.\n+\tinterfaces []string\n+\t// ids are the merged interface IDs of interfaces.\n+\tids []uint32\n+}\n+\n+// resolvedCapture is a validated capture request.\n+type resolvedCapture struct {\n+\tgroups []*captureGroup\n+\t// names are the merged interface names (<node>:<interface>), indexed by merged ID.\n+\tnames []string\n+}\n+\n+// resolveCaptureTargets locates every target node, checks every interface against the\n+// interfaces clabwire allows, and groups the targets per node.\n+func (r *Runtime) resolveCaptureTargets(\n+\tctx context.Context,\n+\treq clablabruntime.CaptureRequest,\n+) (*resolvedCapture, error) {\n+\tnodeOrder := make([]string, 0, len(req.Targets))\n+\tseenNodes := map[string]bool{}\n+\tfor _, target := range req.Targets {\n+\t\tif !seenNodes[target.Node] {\n+\t\t\tseenNodes[target.Node] = true\n+\t\t\tnodeOrder = append(nodeOrder, target.Node)\n+\t\t}\n+\t}\n+\n+\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n+\t\tName: req.Name, Namespace: req.Namespace, Nodes: nodeOrder, Identity: req.Identity,\n+\t})\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tbyRequest := make(map[string]clablabruntime.NodeLocation, len(nodeOrder))\n+\tfor idx, name := range nodeOrder {\n+\t\tbyRequest[name] = locations[idx]\n+\t}\n+\n+\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\tresolved := &resolvedCapture{}\n+\tgroups := map[string]*captureGroup{}\n+\tseen := map[string]bool{}\n+\tfor _, target := range req.Targets {\n+\t\tlocation := byRequest[target.Node]\n+\t\tentry, ok := findCaptureInterface(listed[location.NodeName], target.Interface)\n+\t\tif !ok {\n+\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n+\t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n+\t\t\t\tdescribeCaptureInterfaces(listed[location.NodeName]))\n+\t\t}\n+\n+\t\tkey := location.NodeName + \"\\x00\" + entry.Interface\n+\t\tif seen[key] {\n+\t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n+\t\t\t\tentry.Interface, target.Node)\n+\t\t}\n+\t\tseen[key] = true\n+\n+\t\tgroup := groups[location.NodeName]\n+\t\tif group == nil {\n+\t\t\tgroup = &captureGroup{\n+\t\t\t\tlocation: location,\n+\t\t\t\tdisplay:  names.display(location.NodeName),\n+\t\t\t}\n+\t\t\tgroups[location.NodeName] = group\n+\t\t\tresolved.groups = append(resolved.groups, group)\n+\t\t}\n+\n+\t\tid := uint32(len(resolved.names)) //nolint:gosec // bounded by the targets\n+\t\tgroup.interfaces = append(group.interfaces, entry.Interface)\n+\t\tgroup.ids = append(group.ids, id)\n+\t\tresolved.names = append(resolved.names, group.display+\":\"+entry.Interface)\n+\t}\n+\n+\treturn resolved, nil\n+}\n+\n+// findCaptureInterface matches a requested interface by its planned name or its alias.\n+func findCaptureInterface(entries []clabwireInterface, name string) (clabwireInterface, bool) {\n+\tfor _, entry := range entries {\n+\t\tif entry.Interface == name {\n+\t\t\treturn entry, true\n+\t\t}\n+\t}\n+\tfor _, entry := range entries {\n+\t\tif entry.Alias != \"\" && entry.Alias == name {\n+\t\t\treturn entry, true\n+\t\t}\n+\t}\n+\n+\treturn clabwireInterface{}, false\n+}\n+\n+func describeCaptureInterfaces(entries []clabwireInterface) string {\n+\tif len(entries) == 0 {\n+\t\treturn \"none\"\n+\t}\n+\n+\tnames := make([]string, 0, len(entries))\n+\tfor _, entry := range entries {\n+\t\tname := entry.Interface\n+\t\tif entry.Alias != \"\" {\n+\t\t\tname += \" (\" + entry.Alias + \")\"\n+\t\t}\n+\t\tnames = append(names, name)\n+\t}\n+\n+\treturn strings.Join(names, \", \")\n+}\n+\n+// Capture streams pcapng from lab link interfaces to w: one section, one Interface Description\n+// Block per target in request order named <node>:<interface>, then the packets of every target.\n+//\n+// Each node's interfaces are captured by one clabwire process in the node's pod. clabwire limits\n+// a capture to one hour, so a longer capture (or one without Duration) chains captures: the next\n+// one starts before the current one ends, and the stream switches at a cut in the overlap. See\n+// captureChain for how packets of the overlap are kept once.\n+//\n+// Packets go out in timestamp order across nodes, through a reorder buffer (captureReorder).\n+//\n+// Every clabwire process runs with stdin attached and --stop-on-stdin-close: a Kubernetes exec\n+// does not stop its process when the stream closes, so containerlab closes stdin whenever a\n+// segment ends (the capture ends, fails, its output fails, or a newer segment took over) and\n+// clabwire ends the capture itself.\n+//\n+// Capture returns when Duration has passed, PacketLimit packets were written, or ctx ends; an\n+// ended ctx is not an error. Every block reaches w in one write, so the stream is a valid capture\n+// whenever it stops. A clabwire Denied or Failed audit record is returned as an error.\n+func (r *Runtime) Capture(\n+\tctx context.Context,\n+\treq clablabruntime.CaptureRequest,\n+\tw io.Writer,\n+) error {\n+\tif err := clabcapture.ValidateRequest(&req); err != nil {\n+\t\treturn err\n+\t}\n+\n+\tr, err := r.connect(ctx, req.Identity)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tresolved, err := r.resolveCaptureTargets(ctx, req)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\tcaptureCtx, stop := context.WithCancel(ctx)\n+\tdefer stop()\n+\n+\tout, err := clabcapture.NewOutput(w, resolved.names, req.SnapLength, req.PacketLimit,\n+\t\tr.captureReorderWindowLength(), stop)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\trun := &captureRun{\n+\t\tr:       r,\n+\t\treq:     req,\n+\t\tout:     out,\n+\t\tsegment: r.captureSegmentLength(),\n+\t}\n+\tif req.Duration > 0 {\n+\t\trun.deadline = time.Now().Add(req.Duration)\n+\t}\n+\trun.overlap = min(maxCaptureOverlap, run.segment/3)\n+\trun.window = min(maxCaptureCutWindow, run.overlap/4)\n+\n+\tif req.Duration > 0 {\n+\t\t// a clabwire process that does not end on its own does not hold the capture open\n+\t\tvar cancelTimeout context.CancelFunc\n+\t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx,\n+\t\t\treq.Duration+run.overlap+captureEndGrace)\n+\t\tdefer cancelTimeout()\n+\t}\n+\n+\tgroup, groupCtx := errgroup.WithContext(captureCtx)\n+\tfor _, captureGroup := range resolved.groups {\n+\t\tchain := &captureChain{capture: run, group: captureGroup}\n+\t\tgroup.Go(func() error {\n+\t\t\treturn chain.run(groupCtx)\n+\t\t})\n+\t}\n+\n+\terr = group.Wait()\n+\tif writeErr := out.Close(); writeErr != nil {\n+\t\treturn writeErr\n+\t}\n+\tif err != nil && !(errors.Is(err, context.Canceled) && captureCtx.Err() != nil) {\n+\t\treturn err\n+\t}\n+\n+\treturn nil\n+}\n+\n+// captureRun is the state a capture's chains share.\n+type captureRun struct {\n+\tr   *Runtime\n+\treq clablabruntime.CaptureRequest\n+\t// out is the merged stream; it writes the packets of every chain in timestamp order and\n+\t// stops every chain once the packet limit is reached.\n+\tout *clabcapture.Output\n+\n+\tsegment  time.Duration\n+\toverlap  time.Duration\n+\twindow   time.Duration\n+\tdeadline time.Time\n+}\n+\n+// emit writes a packet under its merged interface ID. It reports false once the packet limit is\n+// reached and the capture stops.\n+func (run *captureRun) emit(id uint32, packet *clabcapture.Packet) (bool, error) {\n+\treturn run.out.Emit(id, packet)\n+}\n+\n+func (run *captureRun) reportGap(gap clablabruntime.CaptureGap) {\n+\tclabcapture.ReportGap(run.req.OnGap, gap)\n+}\n+\n+// captureSegment is one clabwire capture process of a chain.\n+type captureSegment struct {\n+\tindex      int\n+\tlocalStart time.Time\n+\tduration   time.Duration\n+\tcancel     context.CancelFunc\n+\t// closeStdin closes the stdin of the segment's clabwire process, which ends it; it may be\n+\t// called any number of times.\n+\tcloseStdin func()\n+\t// stopTimer closes stdin once the segment is no longer needed after a switch-over.\n+\tstopTimer *time.Timer\n+\t// started and ended are the pod-clock times of the Started and Succeeded audit records.\n+\tstarted time.Time\n+\tended   time.Time\n+\tdone    bool\n+}\n+\n+func (s *captureSegment) plannedEnd() time.Time {\n+\treturn s.started.Add(s.duration)\n+}\n+\n+// segmentEvent is something a segment reported: a packet, an audit record, or its end.\n+type segmentEvent struct {\n+\tsegment *captureSegment\n+\tpacket  *clabcapture.Packet\n+\taudit   *captureAudit\n+\tdone    bool\n+\terr     error\n+}\n+\n+// captureChain runs the chained clabwire captures of one group.\n+//\n+// Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both\n+// capture the same packets for a while. clabwire stamps packets when it reads them, so two\n+// processes give the same packet timestamps a few microseconds apart, and timestamps alone\n+// cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by\n+// content close to the cut:\n+//\n+//  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is\n+//     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.\n+//  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the\n+//     content of what it wrote since segment k+1 started.\n+//  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped\n+//     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped\n+//     when segment k wrote the same bytes on the same interface, and every other one is written.\n+//     From then on segment k+1 streams live.\n+//\n+// Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its\n+// planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other\n+// nodes' later packets do not overtake them in the merged stream.\n+//\n+// W (500 ms, less for short test segments) covers the stamping difference. Identical frames on\n+// the same interface within W of the cut can be paired with each other, which can drop a true\n+// repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves\n+// a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.\n+type captureChain struct {\n+\tcapture *captureRun\n+\tgroup   *captureGroup\n+\n+\tevents chan segmentEvent\n+\twg     sync.WaitGroup\n+\n+\tactive *captureSegment\n+\tnext   *captureSegment\n+\t// cut is the switch time between active and next, in nanoseconds; zero until known.\n+\tcut int64\n+\t// emitted remembers the content of the packets active wrote while next runs.\n+\temitted map[uint64]int\n+\t// held are the packets of next until active ends.\n+\theld     []*clabcapture.Packet\n+\tsegments int\n+\tretries  int\n+\t// final is set once no further segment is due.\n+\tfinal bool\n+\t// stopping is set once ctx ended: the segments are asked to end and what they still\n+\t// deliver is written.\n+\tstopping bool\n+}\n+\n+// run runs the chain until its last segment ended. When ctx ends, it stops the segments and\n+// keeps writing the packets they read until then; a segment that does not end within\n+// captureStdinCloseGrace is cut.\n+func (c *captureChain) run(ctx context.Context) error {\n+\tc.events = make(chan segmentEvent, 256)\n+\t// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them\n+\tsegmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))\n+\tvar abort *time.Timer\n+\tdefer func() {\n+\t\tif abort != nil {\n+\t\t\tabort.Stop()\n+\t\t}\n+\t\tcancel()\n+\t\tc.drain()\n+\t\tc.capture.out.Release(c)\n+\t}()\n+\n+\tc.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))\n+\ttimer := time.NewTimer(c.nextStartIn())\n+\tdefer timer.Stop()\n+\n+\tdone := ctx.Done()\n+\tfor {\n+\t\tselect {\n+\t\tcase <-done:\n+\t\t\tdone = nil\n+\t\t\tc.stop(timer)\n+\t\t\tabort = time.AfterFunc(captureStdinCloseGrace, cancel)\n+\t\tcase <-segmentsCtx.Done():\n+\t\t\treturn nil\n+\t\tcase <-timer.C:\n+\t\t\tif c.next == nil && !c.final {\n+\t\t\t\tc.startNext(segmentsCtx)\n+\t\t\t}\n+\t\tcase event := <-c.events:\n+\t\t\tstop, err := c.handle(segmentsCtx, event, timer)\n+\t\t\tif err != nil || stop {\n+\t\t\t\treturn err\n+\t\t\t}\n+\t\t}\n+\t}\n+}\n+\n+// stop ends the chain early, like a deadline would: no further segment starts and the running\n+// ones are asked to end. The chain then writes what they deliver until they ended.\n+func (c *captureChain) stop(timer *time.Timer) {\n+\tc.stopping = true\n+\tc.final = true\n+\ttimer.Stop()\n+\tc.active.closeStdin()\n+\tif c.next != nil {\n+\t\tc.next.closeStdin()\n+\t}\n+}\n+\n+// drain waits for the segment goroutines after the chain ended.\n+func (c *captureChain) drain() {\n+\tdone := make(chan struct{})\n+\tgo func() {\n+\t\tc.wg.Wait()\n+\t\tclose(done)\n+\t}()\n+\tfor {\n+\t\tselect {\n+\t\tcase <-done:\n+\t\t\treturn\n+\t\tcase <-c.events:\n+\t\t}\n+\t}\n+}\n+\n+// segmentDuration is the requested duration of a segment starting now.\n+func (c *captureChain) segmentDuration(now time.Time) time.Duration {\n+\tduration := c.capture.segment\n+\tif !c.capture.deadline.IsZero() {\n+\t\tduration = min(duration, c.capture.deadline.Sub(now))\n+\t}\n+\n+\treturn max(duration, minCaptureSegment)\n+}\n+\n+// nextStartIn is the time until the follow-up of the active segment is due. It marks the chain\n+// final when none is due.\n+func (c *captureChain) nextStartIn() time.Duration {\n+\tif c.stopping {\n+\t\tc.final = true\n+\t\treturn maxCaptureSegment\n+\t}\n+\tactiveEnd := c.active.localStart.Add(c.active.duration)\n+\tif !c.capture.deadline.IsZero() &&\n+\t\t!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {\n+\t\tc.final = true\n+\t\treturn maxCaptureSegment\n+\t}\n+\tc.final = false\n+\n+\treturn max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)\n+}\n+\n+func (c *captureChain) startNext(ctx context.Context) {\n+\tc.next = c.start(ctx, c.segmentDuration(time.Now()))\n+\tc.emitted = map[uint64]int{}\n+\tc.held = nil\n+\tc.cut = 0\n+}\n+\n+func (c *captureChain) handle(\n+\tctx context.Context,\n+\tevent segmentEvent,\n+\ttimer *time.Timer,\n+) (bool, error) {\n+\tsegment := event.segment\n+\n+\tswitch {\n+\tcase event.audit != nil:\n+\t\treturn false, c.handleAudit(segment, event.audit)\n+\tcase event.packet != nil:\n+\t\treturn c.handlePacket(segment, event.packet)\n+\tcase event.done:\n+\t\tsegment.done = true\n+\t\tif segment.stopTimer != nil {\n+\t\t\tsegment.stopTimer.Stop()\n+\t\t}\n+\t\tif event.err != nil && !c.stopping {\n+\t\t\tif segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {\n+\t\t\t\t// the follow-up did not start; try again while the active one still runs\n+\t\t\t\tc.retries++\n+\t\t\t\tlog.Warn(\"Capture follow-up segment failed to start, retrying\",\n+\t\t\t\t\t\"node\", c.group.display, \"error\", event.err)\n+\t\t\t\tc.next = nil\n+\t\t\t\tresetTimer(timer, time.Second)\n+\n+\t\t\t\treturn false, nil\n+\t\t\t}\n+\n+\t\t\treturn true, fmt.Errorf(\"capture on c9s node %s/%s/%s failed: %w\",",
        "lineStart": 3976,
        "lineEnd": 4675,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523442722,
      "end": 1793523442742
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19653e439001C4rKt3aLJ1MB1u",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653dadf001LqnYSf5AYwEOrw",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 58689,
    "input": 10416,
    "output": 27,
    "reasoning": 54,
    "cache": {
      "read": 48192,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19653dadf001LqnYSf5AYwEOrw",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523440351,
    "completed": 1793523442748
  },
  "parentID": "msg_19653b129001cj4QAfxRVtxTFM",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 58689,
    "input": 10416,
    "output": 27,
    "reasoning": 54,
    "cache": {
      "read": 48192,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 49
step-start
{
  "type": "step-start",
  "id": "prt_19653ecfb0015VYKo2vJbgMOtO",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653e445001J6rvVNoreYHJnq"
}
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 700,
  "offset": 4676
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
4676: +				c.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)
4677: +		}
4678: +		if segment != c.active {
4679: +			return false, nil
4680: +		}
4681: +
4682: +		return c.switchSegments(ctx, timer)
4683: +	}
4684: +
4685: +	return false, nil
4686: +}
4687: +
4688: +func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {
4689: +	switch audit.Status {
4690: +	case captureAuditStarted:
4691: +		segment.started = audit.Time
4692: +		log.Debug("Capture segment started", "node", c.group.display, "segment", segment.index,
4693: +			"interfaces", strings.Join(c.group.interfaces, ","), "duration", segment.duration)
4694: +		if segment == c.next && !c.active.started.IsZero() {
4695: +			c.setCut()
4696: +		}
4697: +		if segment == c.next {
4698: +			c.retries = 0
4699: +		}
4700: +	case captureAuditSucceeded:
4701: +		segment.ended = audit.Time
4702: +		log.Debug("Capture segment succeeded", "node", c.group.display,
4703: +			"segment", segment.index, "packets", audit.Packets)
4704: +	case captureAuditDenied, captureAuditFailed:
4705: +		return captureAuditError(c.group.display, audit)
4706: +	}
4707: +
4708: +	return nil
4709: +}
4710: +
4711: +// captureAuditError turns a Denied or Failed clabwire audit record into an error.
4712: +func captureAuditError(node string, audit *captureAudit) error {
4713: +	verb := "failed"
4714: +	if audit.Status == captureAuditDenied {
4715: +		verb = "was denied"
4716: +	}
4717: +	interfaces := make([]string, 0, len(audit.Interfaces))
4718: +	for _, intf := range audit.Interfaces {
4719: +		interfaces = append(interfaces, intf.Name)
4720: +	}
4721: +
4722: +	return fmt.Errorf("capture of %s on node %s %s by clabwire: %s",
4723: +		strings.Join(interfaces, ","), node, verb, audit.Reason)
4724: +}
4725: +
4726: +// setCut places the cut in the middle of the overlap of the active and the next segment, both
4727: +// measured on the pod clock.
4728: +func (c *captureChain) setCut() {
4729: +	overlapStart := c.next.started
4730: +	overlapEnd := c.active.plannedEnd()
4731: +	if overlapEnd.Sub(overlapStart) < 2*c.capture.window {
4732: +		// the overlap is too short to match packets around a cut: the switch is reported as a
4733: +		// gap once the active segment ended
4734: +		c.cut = 0
4735: +		return
4736: +	}
4737: +	c.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()
4738: +
4739: +	window := c.capture.window.Nanoseconds()
4740: +	// Packets the next segment holds back are stamped from T-W on: other chains' packets after
4741: +	// that wait in the reorder buffer until the switch, so the merged stream stays in order.
4742: +	c.capture.out.Hold(c, c.cut-window)
4743: +
4744: +	// The active segment only matters for packets stamped before T. Once the pod clock passed
4745: +	// T+W, it is closed: packets it read until then are still delivered, and the ones it reads
4746: +	// later are stamped after T and dropped anyway. The next segment's Started record was
4747: +	// written on the pod clock no later than now, so the pod clock passes T+W no later than
4748: +	// (T - Started + W) from now.
4749: +	active := c.active
4750: +	active.stopTimer = time.AfterFunc(
4751: +		time.Duration(c.cut-c.next.started.UnixNano()+window), active.closeStdin)
4752: +}
4753: +
4754: +func (c *captureChain) handlePacket(
4755: +	segment *captureSegment,
4756: +	packet *clabcapture.Packet,
4757: +) (bool, error) {
4758: +	switch segment {
4759: +	case c.active:
4760: +		if c.cut != 0 && packet.Timestamp >= c.cut {
4761: +			return false, nil
4762: +		}
4763: +		if c.next != nil {
4764: +			c.emitted[packetKey(packet)]++
4765: +		}
4766: +
4767: +		return c.emit(packet)
4768: +	case c.next:
4769: +		c.held = append(c.held, packet)
4770: +	}
4771: +
4772: +	return false, nil
4773: +}
4774: +
4775: +func (c *captureChain) emit(packet *clabcapture.Packet) (bool, error) {
4776: +	if int(packet.InterfaceID) >= len(c.group.ids) {
4777: +		return true, fmt.Errorf("clabwire wrote a packet for interface %d of %d",
4778: +			packet.InterfaceID, len(c.group.ids))
4779: +	}
4780: +	more, err := c.capture.emit(c.group.ids[packet.InterfaceID], packet)
4781: +
4782: +	return !more, err
4783: +}
4784: +
4785: +// switchSegments makes the next segment the active one after the active one ended, writing the
4786: +// held packets of the next one that the active one did not write.
4787: +func (c *captureChain) switchSegments(ctx context.Context, timer *time.Timer) (bool, error) {
4788: +	// the held packets are in the reorder buffer once this returns
4789: +	defer c.capture.out.Release(c)
4790: +
4791: +	ended := c.active
4792: +	if c.stopping && c.next != nil && c.next.started.IsZero() {
4793: +		// the chain is stopping: a follow-up that has not started takes nothing over
4794: +		c.next, c.held, c.emitted, c.cut = nil, nil, nil, 0
4795: +	}
4796: +	if c.final && c.next == nil {
4797: +		return true, nil
4798: +	}
4799: +
4800: +	if c.next == nil || c.next.started.IsZero() || c.cut == 0 {
4801: +		from := ended.ended
4802: +		if from.IsZero() {
4803: +			from = ended.plannedEnd()
4804: +		}
4805: +		gap := clablabruntime.CaptureGap{
4806: +			Node: c.group.display, Interfaces: c.group.interfaces, From: from,
4807: +			Reason: "the follow-up capture did not overlap the previous one",
4808: +		}
4809: +		if c.next != nil && !c.next.started.IsZero() {
4810: +			gap.To = c.next.started
4811: +		}
4812: +		c.capture.reportGap(gap)
4813: +	}
4814: +
4815: +	if c.next != nil && c.next.done && !c.stopping {
4816: +		// the follow-up already ended (it started too late to take over): keep what it
4817: +		// captured and continue with a fresh segment
4818: +		for _, packet := range c.held {
4819: +			if stop, err := c.emit(packet); stop || err != nil {
4820: +				return true, err
4821: +			}
4822: +		}
4823: +		c.next, c.held, c.emitted, c.cut = nil, nil, nil, 0
4824: +	}
4825: +
4826: +	if c.next == nil {
4827: +		if !c.capture.deadline.IsZero() &&
4828: +			!time.Now().Before(c.capture.deadline.Add(-c.capture.window)) {
4829: +			return true, nil
4830: +		}
4831: +		c.active = c.start(ctx, c.segmentDuration(time.Now()))
4832: +		resetTimer(timer, c.nextStartIn())
4833: +
4834: +		return false, nil
4835: +	}
4836: +
4837: +	window := c.capture.window.Nanoseconds()
4838: +	for _, packet := range c.held {
4839: +		if c.cut != 0 {
4840: +			if packet.Timestamp < c.cut-window {
4841: +				continue
4842: +			}
4843: +			if packet.Timestamp < c.cut+window {
4844: +				key := packetKey(packet)
4845: +				if c.emitted[key] > 0 {
4846: +					c.emitted[key]--
4847: +					continue
4848: +				}
4849: +			}
4850: +		}
4851: +		if stop, err := c.emit(packet); stop || err != nil {
4852: +			return true, err
4853: +		}
4854: +	}
4855: +
4856: +	c.active, c.next = c.next, nil
4857: +	c.held, c.emitted, c.cut = nil, nil, 0
4858: +	if c.active.done {
4859: +		// the chain is stopping and the follow-up ended before the active one
4860: +		return true, nil
4861: +	}
4862: +	resetTimer(timer, c.nextStartIn())
4863: +
4864: +	return false, nil
4865: +}
4866: +
4867: +func resetTimer(timer *time.Timer, d time.Duration) {
4868: +	if !timer.Stop() {
4869: +		select {
4870: +		case <-timer.C:
4871: +		default:
4872: +		}
4873: +	}
4874: +	timer.Reset(d)
4875: +}
4876: +
4877: +// packetKey identifies a packet by its interface and content.
4878: +func packetKey(packet *clabcapture.Packet) uint64 {
4879: +	hash := fnv.New64a()
4880: +	var id [4]byte
4881: +	id[0] = byte(packet.InterfaceID)
4882: +	id[1] = byte(packet.InterfaceID >> 8)
4883: +	_, _ = hash.Write(id[:])
4884: +	_, _ = hash.Write(packet.Data)
4885: +
4886: +	return hash.Sum64()
4887: +}
4888: +
4889: +// start runs one clabwire capture and reports its packets, audit records and end as events.
4890: +func (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {
4891: +	segmentCtx, cancel := context.WithCancel(ctx)
4892: +	stdinReader, stdinWriter := io.Pipe()
4893: +	segment := &captureSegment{
4894: +		index: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,
4895: +		closeStdin: func() { _ = stdinWriter.Close() },
4896: +	}
4897: +	c.segments++
4898: +
4899: +	command := []string{
4900: +		clabwireManager, "node-runtime", "packet-capture",
4901: +		"--nodeName", c.group.location.NodeName,
4902: +		"--format", "pcapng",
4903: +		"--snapLength", strconv.Itoa(c.capture.req.SnapLength),
4904: +		"--duration", duration.String(),
4905: +		clabwireStopOnStdinClose,
4906: +	}
4907: +	for _, name := range c.group.interfaces {
4908: +		command = append(command, "--interface", name)
4909: +	}
4910: +	if c.capture.req.PacketLimit > 0 {
4911: +		remaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()
4912: +		command = append(command, "--packetLimit",
4913: +			strconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))
4914: +	}
4915: +
4916: +	send := func(event segmentEvent) {
4917: +		event.segment = segment
4918: +		select {
4919: +		case c.events <- event:
4920: +		case <-segmentCtx.Done():
4921: +		}
4922: +	}
4923: +
4924: +	stdoutReader, stdoutWriter := io.Pipe()
4925: +	stderr := &auditLineWriter{send: func(audit *captureAudit) { send(segmentEvent{audit: audit}) }}
4926: +
4927: +	// The exec outlives the segment's context by up to captureStdinCloseGrace: when the segment
4928: +	// ends for any reason (the capture is cancelled or failed, the output failed, or a newer
4929: +	// segment took over), its stdin is closed first so clabwire ends on its own, and the stream
4930: +	// is cut only if it does not.
4931: +	execCtx, cancelExec := context.WithCancel(context.WithoutCancel(segmentCtx))
4932: +	execDone := make(chan struct{})
4933: +
4934: +	c.wg.Add(3)
4935: +	readDone := make(chan error, 1)
4936: +	go func() {
4937: +		defer c.wg.Done()
4938: +		readDone <- c.readSegment(stdoutReader, func(packet *clabcapture.Packet) {
4939: +			send(segmentEvent{packet: packet})
4940: +		})
4941: +		_, _ = io.Copy(io.Discard, stdoutReader)
4942: +	}()
4943: +	go func() {
4944: +		defer c.wg.Done()
4945: +		select {
4946: +		case <-execDone:
4947: +			return
4948: +		case <-segmentCtx.Done():
4949: +		}
4950: +		segment.closeStdin()
4951: +		grace := time.NewTimer(captureStdinCloseGrace)
4952: +		defer grace.Stop()
4953: +		select {
4954: +		case <-execDone:
4955: +		case <-grace.C:
4956: +			log.Debug("Capture segment did not end after its stdin closed, cutting the stream",
4957: +				"node", c.group.display, "segment", segment.index)
4958: +			cancelExec()
4959: +		}
4960: +	}()
4961: +	go func() {
4962: +		defer c.wg.Done()
4963: +		defer cancel()
4964: +		defer cancelExec()
4965: +
4966: +		err := c.capture.r.execInPodContainer()(execCtx, c.group.location.Namespace,
4967: +			c.group.location.Pod, clabwireContainer, command, stdinReader, stdoutWriter, stderr)
4968: +		close(execDone)
4969: +		// the process ended: release the stdin copy of the exec stream
4970: +		segment.closeStdin()
4971: +		_ = stdoutWriter.Close()
4972: +		readErr := <-readDone
4973: +		stderr.flush()
4974: +		if err == nil && readErr != nil {
4975: +			err = readErr
4976: +		}
4977: +		if err != nil && stderr.text() != "" {
4978: +			if unsupported := unsupportedClabwire(
4979: +				c.group.location,
4980: +				stderr.text(),
4981: +			); unsupported != nil {
4982: +				err = unsupported
4983: +			} else {
4984: +				err = fmt.Errorf("%w: %s", err, stderr.text())
4985: +			}
4986: +		}
4987: +		send(segmentEvent{done: true, err: err})
4988: +	}()
4989: +
4990: +	return segment
4991: +}
4992: +
4993: +// unsupportedClabwire recognizes a clabwire that rejects --stop-on-stdin-close, which every
4994: +// capture passes: its release predates the capture contract the runtime needs.
4995: +func unsupportedClabwire(location clablabruntime.NodeLocation, stderr string) error {
4996: +	if !strings.Contains(stderr, "flag provided but not defined") ||
4997: +		!strings.Contains(stderr, strings.TrimPrefix(clabwireStopOnStdinClose, "-")) {
4998: +		return nil
4999: +	}
5000: +
5001: +	return &unsupportedClabernetesError{reason: fmt.Sprintf(
5002: +		"clabwire in pod %s/%s does not accept packet-capture %s",
5003: +		location.Namespace, location.Pod, clabwireStopOnStdinClose)}
5004: +}
5005: +
5006: +// readSegment checks that a segment's interfaces are the requested ones and passes its packets
5007: +// on with the segment's interface index.
5008: +func (c *captureChain) readSegment(stdout io.Reader, packet func(*clabcapture.Packet)) error {
5009: +	reader := clabcapture.NewReader(stdout)
5010: +	interfaces := 0
5011: +	for {
5012: +		event, err := reader.Next()
5013: +		if errors.Is(err, io.EOF) {
5014: +			return nil
5015: +		}
5016: +		if errors.Is(err, io.ErrUnexpectedEOF) {
5017: +			// the process was stopped inside a block
5018: +			return nil
5019: +		}
5020: +		if err != nil {
5021: +			return fmt.Errorf("failed to read the clabwire capture: %w", err)
5022: +		}
5023: +		if event.Interface != nil {
5024: +			if interfaces >= len(c.group.interfaces) ||
5025: +				event.Interface.Name != c.group.interfaces[interfaces] {
5026: +				return fmt.Errorf("clabwire described interface %q, want %s in order",
5027: +					event.Interface.Name, strings.Join(c.group.interfaces, ", "))
5028: +			}
5029: +			interfaces++
5030: +			continue
5031: +		}
5032: +		if event.Packet != nil {
5033: +			packet(event.Packet)
5034: +		}
5035: +	}
5036: +}
5037: +
5038: +// auditLineWriter parses clabwire's stderr: audit records go to send, other lines are kept for
5039: +// error messages.
5040: +type auditLineWriter struct {
5041: +	send func(*captureAudit)
5042: +
5043: +	mu      sync.Mutex
5044: +	partial []byte
5045: +	other   []string
5046: +}
5047: +
5048: +func (w *auditLineWriter) Write(data []byte) (int, error) {
5049: +	w.mu.Lock()
5050: +	w.partial = append(w.partial, data...)
5051: +	var lines [][]byte
5052: +	for {
5053: +		idx := bytes.IndexByte(w.partial, '\n')
5054: +		if idx < 0 {
5055: +			break
5056: +		}
5057: +		lines = append(lines, append([]byte(nil), w.partial[:idx]...))
5058: +		w.partial = w.partial[idx+1:]
5059: +	}
5060: +	w.mu.Unlock()
5061: +
5062: +	for _, line := range lines {
5063: +		w.line(line)
5064: +	}
5065: +
5066: +	return len(data), nil
5067: +}
5068: +
5069: +func (w *auditLineWriter) flush() {
5070: +	w.mu.Lock()
5071: +	line := w.partial
5072: +	w.partial = nil
5073: +	w.mu.Unlock()
5074: +	if len(bytes.TrimSpace(line)) != 0 {
5075: +		w.line(line)
5076: +	}
5077: +}
5078: +
5079: +func (w *auditLineWriter) line(line []byte) {
5080: +	line = bytes.TrimSpace(line)
5081: +	if len(line) == 0 {
5082: +		return
5083: +	}
5084: +
5085: +	var audit captureAudit
5086: +	if err := json.Unmarshal(
5087: +		line,
5088: +		&audit,
5089: +	); err == nil &&
5090: +		audit.SchemaVersion == captureAuditSchema {
5091: +		w.send(&audit)
5092: +		return
5093: +	}
5094: +
5095: +	w.mu.Lock()
5096: +	defer w.mu.Unlock()
5097: +	if len(w.other) < 20 {
5098: +		w.other = append(w.other, string(line))
5099: +	}
5100: +}
5101: +
5102: +func (w *auditLineWriter) text() string {
5103: +	w.mu.Lock()
5104: +	defer w.mu.Unlock()
5105: +
5106: +	return strings.Join(w.other, "; ")
5107: +}
5108: diff --git a/labruntime/clabernetes/capture_interfaces.go b/labruntime/clabernetes/capture_interfaces.go
5109: new file mode 100644
5110: index 0000000..21029ed
5111: --- /dev/null
5112: +++ b/labruntime/clabernetes/capture_interfaces.go
5113: @@ -0,0 +1,187 @@
5114: +package clabernetes
5115: +
5116: +import (
5117: +	"bytes"
5118: +	"context"
5119: +	"errors"
5120: +	"fmt"
5121: +	"io"
5122: +	"sort"
5123: +	"sync"
5124: +
5125: +	"github.com/charmbracelet/log"
5126: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
5127: +	clabtypes "github.com/srl-labs/containerlab/types"
5128: +	corev1 "k8s.io/api/core/v1"
5129: +	"k8s.io/client-go/kubernetes/scheme"
5130: +	"k8s.io/client-go/tools/remotecommand"
5131: +	kubeexec "k8s.io/client-go/util/exec"
5132: +)
5133: +
5134: +// streamPodExec runs a command in a pod container without a terminal and streams its stdout
5135: +// and stderr. A non-nil stdin is attached: when it ends, the process's stdin is closed (the
5136: +// websocket v5 close signal, or a half-closed SPDY stream). A nonzero exit returns a
5137: +// *labruntime.CommandExitError.
5138: +func (r *Runtime) streamPodExec(
5139: +	ctx context.Context,
5140: +	namespace, pod, container string,
5141: +	command []string,
5142: +	stdin io.Reader,
5143: +	stdout, stderr io.Writer,
5144: +) error {
5145: +	execURL := r.kubeClient.CoreV1().RESTClient().Post().
5146: +		Resource("pods").
5147: +		Name(pod).
5148: +		Namespace(namespace).
5149: +		SubResource("exec").
5150: +		VersionedParams(&corev1.PodExecOptions{
5151: +			Container: container,
5152: +			Command:   command,
5153: +			Stdin:     stdin != nil,
5154: +			Stdout:    stdout != nil,
5155: +			Stderr:    stderr != nil,
5156: +		}, scheme.ParameterCodec).URL()
5157: +
5158: +	executor, err := r.newExecutor(execURL)
5159: +	if err != nil {
5160: +		return err
5161: +	}
5162: +
5163: +	// client-go reports streams cut by a cancelled context through the context's logger; a
5164: +	// capture ends that way on purpose, so it goes to the debug log
5165: +	err = executor.StreamWithContext(withKubernetesClientDebugLogs(ctx),
5166: +		remotecommand.StreamOptions{
5167: +			Stdin:  stdin,
5168: +			Stdout: stdout,
5169: +			Stderr: stderr,
5170: +		})
5171: +
5172: +	var exitErr kubeexec.ExitError
5173: +	if errors.As(err, &exitErr) {
5174: +		return &clablabruntime.CommandExitError{Code: exitErr.ExitStatus()}
5175: +	}
5176: +	if err != nil {
5177: +		return fmt.Errorf("failed to execute command in pod %s/%s container %s: %w",
5178: +			namespace, pod, container, err)
5179: +	}
5180: +
5181: +	return nil
5182: +}
5183: +
5184: +// InspectInterfaces lists the capturable link interfaces of the requested nodes, or of every
5185: +// running node, in the shape of `inspect interfaces`: per node (named <lab>-<node> like in
5186: +// inspect), the interface and its alias as clabwire reports them, and the MAC address, index,
5187: +// MTU and operational state read from sysfs in the device container. A node whose device
5188: +// container has no shell reports its interfaces without these attributes.
5189: +func (r *Runtime) InspectInterfaces(
5190: +	ctx context.Context,
5191: +	req clablabruntime.NodeRequest,
5192: +) ([]*clabtypes.ContainerInterfaces, error) {
5193: +	r, err := r.connect(ctx, req.Identity)
5194: +	if err != nil {
5195: +		return nil, err
5196: +	}
5197: +
5198: +	locations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{
5199: +		Name: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,
5200: +	})
5201: +	if err != nil {
5202: +		return nil, err
5203: +	}
5204: +
5205: +	running := make([]clablabruntime.NodeLocation, 0, len(locations))
5206: +	for _, location := range locations {
5207: +		if location.Pod == "" {
5208: +			log.Warn("Skipping interface detection of a node that does not run",
5209: +				"node", location.NodeName)
5210: +			continue
5211: +		}
5212: +		running = append(running, location)
5213: +	}
5214: +
5215: +	listed, err := r.listCaptureInterfaces(ctx, req.Name, running)
5216: +	if err != nil {
5217: +		return nil, err
5218: +	}
5219: +	states := r.sampleInterfaceStates(ctx, running)
5220: +
5221: +	result := make([]*clabtypes.ContainerInterfaces, 0, len(running))
5222: +	for _, location := range running {
5223: +		container := &clabtypes.ContainerInterfaces{
5224: +			ContainerName: req.Name + "-" + location.NodeName,
5225: +			Interfaces:    []*clabtypes.ContainerInterfaceDetails{},
5226: +		}
5227: +		for _, entry := range listed[location.NodeName] {
5228: +			details := &clabtypes.ContainerInterfaceDetails{
5229: +				InterfaceName:  entry.Interface,
5230: +				InterfaceAlias: entry.Alias,
5231: +				// clabwire realizes every lab link interface as a veth pair
5232: +				InterfaceType: "veth",
5233: +			}
5234: +			if state, ok := states[location.NodeName][entry.Interface]; ok {
5235: +				details.InterfaceMAC = state.MAC
5236: +				details.InterfaceIndex = state.Index
5237: +				details.InterfaceMTU = state.MTU
5238: +				details.InterfaceState = state.OperState
5239: +			}
5240: +			container.Interfaces = append(container.Interfaces, details)
5241: +		}
5242: +		sort.Slice(container.Interfaces, func(i, j int) bool {
5243: +			return container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName
5244: +		})
5245: +		result = append(result, container)
5246: +	}
5247: +	sort.Slice(result, func(i, j int) bool {
5248: +		return result[i].ContainerName < result[j].ContainerName
5249: +	})
5250: +
5251: +	return result, nil
5252: +}
5253: +
5254: +// sampleInterfaceStates reads the sysfs interface attributes of every node's device container,
5255: +// one exec per node, with the script the interface events use.
5256: +func (r *Runtime) sampleInterfaceStates(
5257: +	ctx context.Context,
5258: +	locations []clablabruntime.NodeLocation,
5259: +) map[string]map[string]c9sIfaceState {
5260: +	var mu sync.Mutex
5261: +	result := map[string]map[string]c9sIfaceState{}
5262: +
5263: +	var wg sync.WaitGroup
5264: +	workers := make(chan struct{}, interfaceSampleWorkers)
5265: +	exec := r.execInPodContainer()
5266: +	for _, location := range locations {
5267: +		wg.Add(1)
5268: +		go func() {
5269: +			defer wg.Done()
5270: +			workers <- struct{}{}
5271: +			defer func() { <-workers }()
5272: +
5273: +			var stdout, stderr bytes.Buffer
5274: +			err := exec(ctx, location.Namespace, location.Pod, location.Container,
5275: +				[]string{"sh", "-c", interfaceSampleScript}, nil, &stdout, &stderr)
5276: +			if err != nil {
5277: +				log.Debug("Cannot read the interface state of a c9s node",
5278: +					"node", location.NodeName, "error", err)
5279: +				return
5280: +			}
5281: +			_, ifaces, _, err := parseInterfaceSample(stdout.Bytes())
5282: +			if err != nil {
5283: +				log.Debug("Cannot parse the interface state of a c9s node",
5284: +					"node", location.NodeName, "error", err)
5285: +				return
5286: +			}
5287: +
5288: +			byName := make(map[string]c9sIfaceState, len(ifaces))
5289: +			for _, iface := range ifaces {
5290: +				byName[iface.Name] = iface
5291: +			}
5292: +			mu.Lock()
5293: +			result[location.NodeName] = byName
5294: +			mu.Unlock()
5295: +		}()
5296: +	}
5297: +	wg.Wait()
5298: +
5299: +	return result
5300: +}
5301: diff --git a/labruntime/clabernetes/capture_test.go b/labruntime/clabernetes/capture_test.go
5302: new file mode 100644
5303: index 0000000..16628b5
5304: --- /dev/null
5305: +++ b/labruntime/clabernetes/capture_test.go
5306: @@ -0,0 +1,1050 @@
5307: +package clabernetes
5308: +
5309: +import (
5310: +	"bytes"
5311: +	"context"
5312: +	"encoding/binary"
5313: +	"encoding/json"
5314: +	"errors"
5315: +	"fmt"
5316: +	"io"
5317: +	"slices"
5318: +	"strings"
5319: +	"sync"
5320: +	"testing"
5321: +	"time"
5322: +
5323: +	clabcapture "github.com/srl-labs/containerlab/capture"
5324: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
5325: +	corev1 "k8s.io/api/core/v1"
5326: +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
5327: +	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
5328: +	k8sruntime "k8s.io/apimachinery/pkg/runtime"
5329: +)
5330: +
5331: +func captureTestNode(name, original, container string) *unstructured.Unstructured {
5332: +	labels := map[string]any{labelTopologyOwner: "lab1"}
5333: +	if original != "" {
5334: +		labels[labelOriginalNodeName] = original
5335: +	}
5336: +
5337: +	return &unstructured.Unstructured{Object: map[string]any{
5338: +		"apiVersion": c9sAPIVersion,
5339: +		"kind":       "Node",
5340: +		"metadata": map[string]any{
5341: +			"name": name, "namespace": "lab-ns", "uid": "uid-" + name, "labels": labels,
5342: +		},
5343: +		"spec": map[string]any{"kind": "srl", "runState": nodeRunStateRunning},
5344: +		"status": map[string]any{
5345: +			"readiness":        "ready",
5346: +			"directContainers": []any{map[string]any{"name": container, "id": name}},
5347: +		},
5348: +	}}
5349: +}
5350: +
5351: +func captureTestPod(name, node string) *corev1.Pod {
5352: +	return &corev1.Pod{
5353: +		ObjectMeta: metav1.ObjectMeta{
5354: +			Name: name, Namespace: "lab-ns",
5355: +			Labels: map[string]string{
5356: +				labelApp: clabernetesAppValue, labelTopologyOwner: "lab1", labelTopologyNode: node,
5357: +			},
5358: +		},
5359: +		Status: corev1.PodStatus{Phase: corev1.PodRunning},
5360: +	}
5361: +}
5362: +
5363: +// captureListing is the --list-interfaces output of each pod.
5364: +var captureListing = map[string][]clabwireInterface{ //nolint:gochecknoglobals
5365: +	"lab1-r1-abc": {
5366: +		{
5367: +			Node:          "r1",
5368: +			Interface:     "e1-1",
5369: +			Alias:         "ethernet-1/1",
5370: +			PeerNode:      "r2",
5371: +			PeerInterface: "ethernet-1/1",
5372: +		},
5373: +		{Node: "r1", Interface: "e1-2", PeerNode: "host", PeerInterface: "r1-e1-2"},
5374: +	},
5375: +	"lab1-r2-def": {

(Showing lines 4676-5375 of 7018. Use offset=5376 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19653ed3a001HTYyGrFhk1fHXA",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653e445001J6rvVNoreYHJnq",
  "callID": "call_feab8abb329d46bda3df4e73",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 700,
      "offset": 4676
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n4676: +\t\t\t\tc.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)\n4677: +\t\t}\n4678: +\t\tif segment != c.active {\n4679: +\t\t\treturn false, nil\n4680: +\t\t}\n4681: +\n4682: +\t\treturn c.switchSegments(ctx, timer)\n4683: +\t}\n4684: +\n4685: +\treturn false, nil\n4686: +}\n4687: +\n4688: +func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {\n4689: +\tswitch audit.Status {\n4690: +\tcase captureAuditStarted:\n4691: +\t\tsegment.started = audit.Time\n4692: +\t\tlog.Debug(\"Capture segment started\", \"node\", c.group.display, \"segment\", segment.index,\n4693: +\t\t\t\"interfaces\", strings.Join(c.group.interfaces, \",\"), \"duration\", segment.duration)\n4694: +\t\tif segment == c.next && !c.active.started.IsZero() {\n4695: +\t\t\tc.setCut()\n4696: +\t\t}\n4697: +\t\tif segment == c.next {\n4698: +\t\t\tc.retries = 0\n4699: +\t\t}\n4700: +\tcase captureAuditSucceeded:\n4701: +\t\tsegment.ended = audit.Time\n4702: +\t\tlog.Debug(\"Capture segment succeeded\", \"node\", c.group.display,\n4703: +\t\t\t\"segment\", segment.index, \"packets\", audit.Packets)\n4704: +\tcase captureAuditDenied, captureAuditFailed:\n4705: +\t\treturn captureAuditError(c.group.display, audit)\n4706: +\t}\n4707: +\n4708: +\treturn nil\n4709: +}\n4710: +\n4711: +// captureAuditError turns a Denied or Failed clabwire audit record into an error.\n4712: +func captureAuditError(node string, audit *captureAudit) error {\n4713: +\tverb := \"failed\"\n4714: +\tif audit.Status == captureAuditDenied {\n4715: +\t\tverb = \"was denied\"\n4716: +\t}\n4717: +\tinterfaces := make([]string, 0, len(audit.Interfaces))\n4718: +\tfor _, intf := range audit.Interfaces {\n4719: +\t\tinterfaces = append(interfaces, intf.Name)\n4720: +\t}\n4721: +\n4722: +\treturn fmt.Errorf(\"capture of %s on node %s %s by clabwire: %s\",\n4723: +\t\tstrings.Join(interfaces, \",\"), node, verb, audit.Reason)\n4724: +}\n4725: +\n4726: +// setCut places the cut in the middle of the overlap of the active and the next segment, both\n4727: +// measured on the pod clock.\n4728: +func (c *captureChain) setCut() {\n4729: +\toverlapStart := c.next.started\n4730: +\toverlapEnd := c.active.plannedEnd()\n4731: +\tif overlapEnd.Sub(overlapStart) < 2*c.capture.window {\n4732: +\t\t// the overlap is too short to match packets around a cut: the switch is reported as a\n4733: +\t\t// gap once the active segment ended\n4734: +\t\tc.cut = 0\n4735: +\t\treturn\n4736: +\t}\n4737: +\tc.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()\n4738: +\n4739: +\twindow := c.capture.window.Nanoseconds()\n4740: +\t// Packets the next segment holds back are stamped from T-W on: other chains' packets after\n4741: +\t// that wait in the reorder buffer until the switch, so the merged stream stays in order.\n4742: +\tc.capture.out.Hold(c, c.cut-window)\n4743: +\n4744: +\t// The active segment only matters for packets stamped before T. Once the pod clock passed\n4745: +\t// T+W, it is closed: packets it read until then are still delivered, and the ones it reads\n4746: +\t// later are stamped after T and dropped anyway. The next segment's Started record was\n4747: +\t// written on the pod clock no later than now, so the pod clock passes T+W no later than\n4748: +\t// (T - Started + W) from now.\n4749: +\tactive := c.active\n4750: +\tactive.stopTimer = time.AfterFunc(\n4751: +\t\ttime.Duration(c.cut-c.next.started.UnixNano()+window), active.closeStdin)\n4752: +}\n4753: +\n4754: +func (c *captureChain) handlePacket(\n4755: +\tsegment *captureSegment,\n4756: +\tpacket *clabcapture.Packet,\n4757: +) (bool, error) {\n4758: +\tswitch segment {\n4759: +\tcase c.active:\n4760: +\t\tif c.cut != 0 && packet.Timestamp >= c.cut {\n4761: +\t\t\treturn false, nil\n4762: +\t\t}\n4763: +\t\tif c.next != nil {\n4764: +\t\t\tc.emitted[packetKey(packet)]++\n4765: +\t\t}\n4766: +\n4767: +\t\treturn c.emit(packet)\n4768: +\tcase c.next:\n4769: +\t\tc.held = append(c.held, packet)\n4770: +\t}\n4771: +\n4772: +\treturn false, nil\n4773: +}\n4774: +\n4775: +func (c *captureChain) emit(packet *clabcapture.Packet) (bool, error) {\n4776: +\tif int(packet.InterfaceID) >= len(c.group.ids) {\n4777: +\t\treturn true, fmt.Errorf(\"clabwire wrote a packet for interface %d of %d\",\n4778: +\t\t\tpacket.InterfaceID, len(c.group.ids))\n4779: +\t}\n4780: +\tmore, err := c.capture.emit(c.group.ids[packet.InterfaceID], packet)\n4781: +\n4782: +\treturn !more, err\n4783: +}\n4784: +\n4785: +// switchSegments makes the next segment the active one after the active one ended, writing the\n4786: +// held packets of the next one that the active one did not write.\n4787: +func (c *captureChain) switchSegments(ctx context.Context, timer *time.Timer) (bool, error) {\n4788: +\t// the held packets are in the reorder buffer once this returns\n4789: +\tdefer c.capture.out.Release(c)\n4790: +\n4791: +\tended := c.active\n4792: +\tif c.stopping && c.next != nil && c.next.started.IsZero() {\n4793: +\t\t// the chain is stopping: a follow-up that has not started takes nothing over\n4794: +\t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n4795: +\t}\n4796: +\tif c.final && c.next == nil {\n4797: +\t\treturn true, nil\n4798: +\t}\n4799: +\n4800: +\tif c.next == nil || c.next.started.IsZero() || c.cut == 0 {\n4801: +\t\tfrom := ended.ended\n4802: +\t\tif from.IsZero() {\n4803: +\t\t\tfrom = ended.plannedEnd()\n4804: +\t\t}\n4805: +\t\tgap := clablabruntime.CaptureGap{\n4806: +\t\t\tNode: c.group.display, Interfaces: c.group.interfaces, From: from,\n4807: +\t\t\tReason: \"the follow-up capture did not overlap the previous one\",\n4808: +\t\t}\n4809: +\t\tif c.next != nil && !c.next.started.IsZero() {\n4810: +\t\t\tgap.To = c.next.started\n4811: +\t\t}\n4812: +\t\tc.capture.reportGap(gap)\n4813: +\t}\n4814: +\n4815: +\tif c.next != nil && c.next.done && !c.stopping {\n4816: +\t\t// the follow-up already ended (it started too late to take over): keep what it\n4817: +\t\t// captured and continue with a fresh segment\n4818: +\t\tfor _, packet := range c.held {\n4819: +\t\t\tif stop, err := c.emit(packet); stop || err != nil {\n4820: +\t\t\t\treturn true, err\n4821: +\t\t\t}\n4822: +\t\t}\n4823: +\t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n4824: +\t}\n4825: +\n4826: +\tif c.next == nil {\n4827: +\t\tif !c.capture.deadline.IsZero() &&\n4828: +\t\t\t!time.Now().Before(c.capture.deadline.Add(-c.capture.window)) {\n4829: +\t\t\treturn true, nil\n4830: +\t\t}\n4831: +\t\tc.active = c.start(ctx, c.segmentDuration(time.Now()))\n4832: +\t\tresetTimer(timer, c.nextStartIn())\n4833: +\n4834: +\t\treturn false, nil\n4835: +\t}\n4836: +\n4837: +\twindow := c.capture.window.Nanoseconds()\n4838: +\tfor _, packet := range c.held {\n4839: +\t\tif c.cut != 0 {\n4840: +\t\t\tif packet.Timestamp < c.cut-window {\n4841: +\t\t\t\tcontinue\n4842: +\t\t\t}\n4843: +\t\t\tif packet.Timestamp < c.cut+window {\n4844: +\t\t\t\tkey := packetKey(packet)\n4845: +\t\t\t\tif c.emitted[key] > 0 {\n4846: +\t\t\t\t\tc.emitted[key]--\n4847: +\t\t\t\t\tcontinue\n4848: +\t\t\t\t}\n4849: +\t\t\t}\n4850: +\t\t}\n4851: +\t\tif stop, err := c.emit(packet); stop || err != nil {\n4852: +\t\t\treturn true, err\n4853: +\t\t}\n4854: +\t}\n4855: +\n4856: +\tc.active, c.next = c.next, nil\n4857: +\tc.held, c.emitted, c.cut = nil, nil, 0\n4858: +\tif c.active.done {\n4859: +\t\t// the chain is stopping and the follow-up ended before the active one\n4860: +\t\treturn true, nil\n4861: +\t}\n4862: +\tresetTimer(timer, c.nextStartIn())\n4863: +\n4864: +\treturn false, nil\n4865: +}\n4866: +\n4867: +func resetTimer(timer *time.Timer, d time.Duration) {\n4868: +\tif !timer.Stop() {\n4869: +\t\tselect {\n4870: +\t\tcase <-timer.C:\n4871: +\t\tdefault:\n4872: +\t\t}\n4873: +\t}\n4874: +\ttimer.Reset(d)\n4875: +}\n4876: +\n4877: +// packetKey identifies a packet by its interface and content.\n4878: +func packetKey(packet *clabcapture.Packet) uint64 {\n4879: +\thash := fnv.New64a()\n4880: +\tvar id [4]byte\n4881: +\tid[0] = byte(packet.InterfaceID)\n4882: +\tid[1] = byte(packet.InterfaceID >> 8)\n4883: +\t_, _ = hash.Write(id[:])\n4884: +\t_, _ = hash.Write(packet.Data)\n4885: +\n4886: +\treturn hash.Sum64()\n4887: +}\n4888: +\n4889: +// start runs one clabwire capture and reports its packets, audit records and end as events.\n4890: +func (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {\n4891: +\tsegmentCtx, cancel := context.WithCancel(ctx)\n4892: +\tstdinReader, stdinWriter := io.Pipe()\n4893: +\tsegment := &captureSegment{\n4894: +\t\tindex: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,\n4895: +\t\tcloseStdin: func() { _ = stdinWriter.Close() },\n4896: +\t}\n4897: +\tc.segments++\n4898: +\n4899: +\tcommand := []string{\n4900: +\t\tclabwireManager, \"node-runtime\", \"packet-capture\",\n4901: +\t\t\"--nodeName\", c.group.location.NodeName,\n4902: +\t\t\"--format\", \"pcapng\",\n4903: +\t\t\"--snapLength\", strconv.Itoa(c.capture.req.SnapLength),\n4904: +\t\t\"--duration\", duration.String(),\n4905: +\t\tclabwireStopOnStdinClose,\n4906: +\t}\n4907: +\tfor _, name := range c.group.interfaces {\n4908: +\t\tcommand = append(command, \"--interface\", name)\n4909: +\t}\n4910: +\tif c.capture.req.PacketLimit > 0 {\n4911: +\t\tremaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()\n4912: +\t\tcommand = append(command, \"--packetLimit\",\n4913: +\t\t\tstrconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))\n4914: +\t}\n4915: +\n4916: +\tsend := func(event segmentEvent) {\n4917: +\t\tevent.segment = segment\n4918: +\t\tselect {\n4919: +\t\tcase c.events <- event:\n4920: +\t\tcase <-segmentCtx.Done():\n4921: +\t\t}\n4922: +\t}\n4923: +\n4924: +\tstdoutReader, stdoutWriter := io.Pipe()\n4925: +\tstderr := &auditLineWriter{send: func(audit *captureAudit) { send(segmentEvent{audit: audit}) }}\n4926: +\n4927: +\t// The exec outlives the segment's context by up to captureStdinCloseGrace: when the segment\n4928: +\t// ends for any reason (the capture is cancelled or failed, the output failed, or a newer\n4929: +\t// segment took over), its stdin is closed first so clabwire ends on its own, and the stream\n4930: +\t// is cut only if it does not.\n4931: +\texecCtx, cancelExec := context.WithCancel(context.WithoutCancel(segmentCtx))\n4932: +\texecDone := make(chan struct{})\n4933: +\n4934: +\tc.wg.Add(3)\n4935: +\treadDone := make(chan error, 1)\n4936: +\tgo func() {\n4937: +\t\tdefer c.wg.Done()\n4938: +\t\treadDone <- c.readSegment(stdoutReader, func(packet *clabcapture.Packet) {\n4939: +\t\t\tsend(segmentEvent{packet: packet})\n4940: +\t\t})\n4941: +\t\t_, _ = io.Copy(io.Discard, stdoutReader)\n4942: +\t}()\n4943: +\tgo func() {\n4944: +\t\tdefer c.wg.Done()\n4945: +\t\tselect {\n4946: +\t\tcase <-execDone:\n4947: +\t\t\treturn\n4948: +\t\tcase <-segmentCtx.Done():\n4949: +\t\t}\n4950: +\t\tsegment.closeStdin()\n4951: +\t\tgrace := time.NewTimer(captureStdinCloseGrace)\n4952: +\t\tdefer grace.Stop()\n4953: +\t\tselect {\n4954: +\t\tcase <-execDone:\n4955: +\t\tcase <-grace.C:\n4956: +\t\t\tlog.Debug(\"Capture segment did not end after its stdin closed, cutting the stream\",\n4957: +\t\t\t\t\"node\", c.group.display, \"segment\", segment.index)\n4958: +\t\t\tcancelExec()\n4959: +\t\t}\n4960: +\t}()\n4961: +\tgo func() {\n4962: +\t\tdefer c.wg.Done()\n4963: +\t\tdefer cancel()\n4964: +\t\tdefer cancelExec()\n4965: +\n4966: +\t\terr := c.capture.r.execInPodContainer()(execCtx, c.group.location.Namespace,\n4967: +\t\t\tc.group.location.Pod, clabwireContainer, command, stdinReader, stdoutWriter, stderr)\n4968: +\t\tclose(execDone)\n4969: +\t\t// the process ended: release the stdin copy of the exec stream\n4970: +\t\tsegment.closeStdin()\n4971: +\t\t_ = stdoutWriter.Close()\n4972: +\t\treadErr := <-readDone\n4973: +\t\tstderr.flush()\n4974: +\t\tif err == nil && readErr != nil {\n4975: +\t\t\terr = readErr\n4976: +\t\t}\n4977: +\t\tif err != nil && stderr.text() != \"\" {\n4978: +\t\t\tif unsupported := unsupportedClabwire(\n4979: +\t\t\t\tc.group.location,\n4980: +\t\t\t\tstderr.text(),\n4981: +\t\t\t); unsupported != nil {\n4982: +\t\t\t\terr = unsupported\n4983: +\t\t\t} else {\n4984: +\t\t\t\terr = fmt.Errorf(\"%w: %s\", err, stderr.text())\n4985: +\t\t\t}\n4986: +\t\t}\n4987: +\t\tsend(segmentEvent{done: true, err: err})\n4988: +\t}()\n4989: +\n4990: +\treturn segment\n4991: +}\n4992: +\n4993: +// unsupportedClabwire recognizes a clabwire that rejects --stop-on-stdin-close, which every\n4994: +// capture passes: its release predates the capture contract the runtime needs.\n4995: +func unsupportedClabwire(location clablabruntime.NodeLocation, stderr string) error {\n4996: +\tif !strings.Contains(stderr, \"flag provided but not defined\") ||\n4997: +\t\t!strings.Contains(stderr, strings.TrimPrefix(clabwireStopOnStdinClose, \"-\")) {\n4998: +\t\treturn nil\n4999: +\t}\n5000: +\n5001: +\treturn &unsupportedClabernetesError{reason: fmt.Sprintf(\n5002: +\t\t\"clabwire in pod %s/%s does not accept packet-capture %s\",\n5003: +\t\tlocation.Namespace, location.Pod, clabwireStopOnStdinClose)}\n5004: +}\n5005: +\n5006: +// readSegment checks that a segment's interfaces are the requested ones and passes its packets\n5007: +// on with the segment's interface index.\n5008: +func (c *captureChain) readSegment(stdout io.Reader, packet func(*clabcapture.Packet)) error {\n5009: +\treader := clabcapture.NewReader(stdout)\n5010: +\tinterfaces := 0\n5011: +\tfor {\n5012: +\t\tevent, err := reader.Next()\n5013: +\t\tif errors.Is(err, io.EOF) {\n5014: +\t\t\treturn nil\n5015: +\t\t}\n5016: +\t\tif errors.Is(err, io.ErrUnexpectedEOF) {\n5017: +\t\t\t// the process was stopped inside a block\n5018: +\t\t\treturn nil\n5019: +\t\t}\n5020: +\t\tif err != nil {\n5021: +\t\t\treturn fmt.Errorf(\"failed to read the clabwire capture: %w\", err)\n5022: +\t\t}\n5023: +\t\tif event.Interface != nil {\n5024: +\t\t\tif interfaces >= len(c.group.interfaces) ||\n5025: +\t\t\t\tevent.Interface.Name != c.group.interfaces[interfaces] {\n5026: +\t\t\t\treturn fmt.Errorf(\"clabwire described interface %q, want %s in order\",\n5027: +\t\t\t\t\tevent.Interface.Name, strings.Join(c.group.interfaces, \", \"))\n5028: +\t\t\t}\n5029: +\t\t\tinterfaces++\n5030: +\t\t\tcontinue\n5031: +\t\t}\n5032: +\t\tif event.Packet != nil {\n5033: +\t\t\tpacket(event.Packet)\n5034: +\t\t}\n5035: +\t}\n5036: +}\n5037: +\n5038: +// auditLineWriter parses clabwire's stderr: audit records go to send, other lines are kept for\n5039: +// error messages.\n5040: +type auditLineWriter struct {\n5041: +\tsend func(*captureAudit)\n5042: +\n5043: +\tmu      sync.Mutex\n5044: +\tpartial []byte\n5045: +\tother   []string\n5046: +}\n5047: +\n5048: +func (w *auditLineWriter) Write(data []byte) (int, error) {\n5049: +\tw.mu.Lock()\n5050: +\tw.partial = append(w.partial, data...)\n5051: +\tvar lines [][]byte\n5052: +\tfor {\n5053: +\t\tidx := bytes.IndexByte(w.partial, '\\n')\n5054: +\t\tif idx < 0 {\n5055: +\t\t\tbreak\n5056: +\t\t}\n5057: +\t\tlines = append(lines, append([]byte(nil), w.partial[:idx]...))\n5058: +\t\tw.partial = w.partial[idx+1:]\n5059: +\t}\n5060: +\tw.mu.Unlock()\n5061: +\n5062: +\tfor _, line := range lines {\n5063: +\t\tw.line(line)\n5064: +\t}\n5065: +\n5066: +\treturn len(data), nil\n5067: +}\n5068: +\n5069: +func (w *auditLineWriter) flush() {\n5070: +\tw.mu.Lock()\n5071: +\tline := w.partial\n5072: +\tw.partial = nil\n5073: +\tw.mu.Unlock()\n5074: +\tif len(bytes.TrimSpace(line)) != 0 {\n5075: +\t\tw.line(line)\n5076: +\t}\n5077: +}\n5078: +\n5079: +func (w *auditLineWriter) line(line []byte) {\n5080: +\tline = bytes.TrimSpace(line)\n5081: +\tif len(line) == 0 {\n5082: +\t\treturn\n5083: +\t}\n5084: +\n5085: +\tvar audit captureAudit\n5086: +\tif err := json.Unmarshal(\n5087: +\t\tline,\n5088: +\t\t&audit,\n5089: +\t); err == nil &&\n5090: +\t\taudit.SchemaVersion == captureAuditSchema {\n5091: +\t\tw.send(&audit)\n5092: +\t\treturn\n5093: +\t}\n5094: +\n5095: +\tw.mu.Lock()\n5096: +\tdefer w.mu.Unlock()\n5097: +\tif len(w.other) < 20 {\n5098: +\t\tw.other = append(w.other, string(line))\n5099: +\t}\n5100: +}\n5101: +\n5102: +func (w *auditLineWriter) text() string {\n5103: +\tw.mu.Lock()\n5104: +\tdefer w.mu.Unlock()\n5105: +\n5106: +\treturn strings.Join(w.other, \"; \")\n5107: +}\n5108: diff --git a/labruntime/clabernetes/capture_interfaces.go b/labruntime/clabernetes/capture_interfaces.go\n5109: new file mode 100644\n5110: index 0000000..21029ed\n5111: --- /dev/null\n5112: +++ b/labruntime/clabernetes/capture_interfaces.go\n5113: @@ -0,0 +1,187 @@\n5114: +package clabernetes\n5115: +\n5116: +import (\n5117: +\t\"bytes\"\n5118: +\t\"context\"\n5119: +\t\"errors\"\n5120: +\t\"fmt\"\n5121: +\t\"io\"\n5122: +\t\"sort\"\n5123: +\t\"sync\"\n5124: +\n5125: +\t\"github.com/charmbracelet/log\"\n5126: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n5127: +\tclabtypes \"github.com/srl-labs/containerlab/types\"\n5128: +\tcorev1 \"k8s.io/api/core/v1\"\n5129: +\t\"k8s.io/client-go/kubernetes/scheme\"\n5130: +\t\"k8s.io/client-go/tools/remotecommand\"\n5131: +\tkubeexec \"k8s.io/client-go/util/exec\"\n5132: +)\n5133: +\n5134: +// streamPodExec runs a command in a pod container without a terminal and streams its stdout\n5135: +// and stderr. A non-nil stdin is attached: when it ends, the process's stdin is closed (the\n5136: +// websocket v5 close signal, or a half-closed SPDY stream). A nonzero exit returns a\n5137: +// *labruntime.CommandExitError.\n5138: +func (r *Runtime) streamPodExec(\n5139: +\tctx context.Context,\n5140: +\tnamespace, pod, container string,\n5141: +\tcommand []string,\n5142: +\tstdin io.Reader,\n5143: +\tstdout, stderr io.Writer,\n5144: +) error {\n5145: +\texecURL := r.kubeClient.CoreV1().RESTClient().Post().\n5146: +\t\tResource(\"pods\").\n5147: +\t\tName(pod).\n5148: +\t\tNamespace(namespace).\n5149: +\t\tSubResource(\"exec\").\n5150: +\t\tVersionedParams(&corev1.PodExecOptions{\n5151: +\t\t\tContainer: container,\n5152: +\t\t\tCommand:   command,\n5153: +\t\t\tStdin:     stdin != nil,\n5154: +\t\t\tStdout:    stdout != nil,\n5155: +\t\t\tStderr:    stderr != nil,\n5156: +\t\t}, scheme.ParameterCodec).URL()\n5157: +\n5158: +\texecutor, err := r.newExecutor(execURL)\n5159: +\tif err != nil {\n5160: +\t\treturn err\n5161: +\t}\n5162: +\n5163: +\t// client-go reports streams cut by a cancelled context through the context's logger; a\n5164: +\t// capture ends that way on purpose, so it goes to the debug log\n5165: +\terr = executor.StreamWithContext(withKubernetesClientDebugLogs(ctx),\n5166: +\t\tremotecommand.StreamOptions{\n5167: +\t\t\tStdin:  stdin,\n5168: +\t\t\tStdout: stdout,\n5169: +\t\t\tStderr: stderr,\n5170: +\t\t})\n5171: +\n5172: +\tvar exitErr kubeexec.ExitError\n5173: +\tif errors.As(err, &exitErr) {\n5174: +\t\treturn &clablabruntime.CommandExitError{Code: exitErr.ExitStatus()}\n5175: +\t}\n5176: +\tif err != nil {\n5177: +\t\treturn fmt.Errorf(\"failed to execute command in pod %s/%s container %s: %w\",\n5178: +\t\t\tnamespace, pod, container, err)\n5179: +\t}\n5180: +\n5181: +\treturn nil\n5182: +}\n5183: +\n5184: +// InspectInterfaces lists the capturable link interfaces of the requested nodes, or of every\n5185: +// running node, in the shape of `inspect interfaces`: per node (named <lab>-<node> like in\n5186: +// inspect), the interface and its alias as clabwire reports them, and the MAC address, index,\n5187: +// MTU and operational state read from sysfs in the device container. A node whose device\n5188: +// container has no shell reports its interfaces without these attributes.\n5189: +func (r *Runtime) InspectInterfaces(\n5190: +\tctx context.Context,\n5191: +\treq clablabruntime.NodeRequest,\n5192: +) ([]*clabtypes.ContainerInterfaces, error) {\n5193: +\tr, err := r.connect(ctx, req.Identity)\n5194: +\tif err != nil {\n5195: +\t\treturn nil, err\n5196: +\t}\n5197: +\n5198: +\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n5199: +\t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n5200: +\t})\n5201: +\tif err != nil {\n5202: +\t\treturn nil, err\n5203: +\t}\n5204: +\n5205: +\trunning := make([]clablabruntime.NodeLocation, 0, len(locations))\n5206: +\tfor _, location := range locations {\n5207: +\t\tif location.Pod == \"\" {\n5208: +\t\t\tlog.Warn(\"Skipping interface detection of a node that does not run\",\n5209: +\t\t\t\t\"node\", location.NodeName)\n5210: +\t\t\tcontinue\n5211: +\t\t}\n5212: +\t\trunning = append(running, location)\n5213: +\t}\n5214: +\n5215: +\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, running)\n5216: +\tif err != nil {\n5217: +\t\treturn nil, err\n5218: +\t}\n5219: +\tstates := r.sampleInterfaceStates(ctx, running)\n5220: +\n5221: +\tresult := make([]*clabtypes.ContainerInterfaces, 0, len(running))\n5222: +\tfor _, location := range running {\n5223: +\t\tcontainer := &clabtypes.ContainerInterfaces{\n5224: +\t\t\tContainerName: req.Name + \"-\" + location.NodeName,\n5225: +\t\t\tInterfaces:    []*clabtypes.ContainerInterfaceDetails{},\n5226: +\t\t}\n5227: +\t\tfor _, entry := range listed[location.NodeName] {\n5228: +\t\t\tdetails := &clabtypes.ContainerInterfaceDetails{\n5229: +\t\t\t\tInterfaceName:  entry.Interface,\n5230: +\t\t\t\tInterfaceAlias: entry.Alias,\n5231: +\t\t\t\t// clabwire realizes every lab link interface as a veth pair\n5232: +\t\t\t\tInterfaceType: \"veth\",\n5233: +\t\t\t}\n5234: +\t\t\tif state, ok := states[location.NodeName][entry.Interface]; ok {\n5235: +\t\t\t\tdetails.InterfaceMAC = state.MAC\n5236: +\t\t\t\tdetails.InterfaceIndex = state.Index\n5237: +\t\t\t\tdetails.InterfaceMTU = state.MTU\n5238: +\t\t\t\tdetails.InterfaceState = state.OperState\n5239: +\t\t\t}\n5240: +\t\t\tcontainer.Interfaces = append(container.Interfaces, details)\n5241: +\t\t}\n5242: +\t\tsort.Slice(container.Interfaces, func(i, j int) bool {\n5243: +\t\t\treturn container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName\n5244: +\t\t})\n5245: +\t\tresult = append(result, container)\n5246: +\t}\n5247: +\tsort.Slice(result, func(i, j int) bool {\n5248: +\t\treturn result[i].ContainerName < result[j].ContainerName\n5249: +\t})\n5250: +\n5251: +\treturn result, nil\n5252: +}\n5253: +\n5254: +// sampleInterfaceStates reads the sysfs interface attributes of every node's device container,\n5255: +// one exec per node, with the script the interface events use.\n5256: +func (r *Runtime) sampleInterfaceStates(\n5257: +\tctx context.Context,\n5258: +\tlocations []clablabruntime.NodeLocation,\n5259: +) map[string]map[string]c9sIfaceState {\n5260: +\tvar mu sync.Mutex\n5261: +\tresult := map[string]map[string]c9sIfaceState{}\n5262: +\n5263: +\tvar wg sync.WaitGroup\n5264: +\tworkers := make(chan struct{}, interfaceSampleWorkers)\n5265: +\texec := r.execInPodContainer()\n5266: +\tfor _, location := range locations {\n5267: +\t\twg.Add(1)\n5268: +\t\tgo func() {\n5269: +\t\t\tdefer wg.Done()\n5270: +\t\t\tworkers <- struct{}{}\n5271: +\t\t\tdefer func() { <-workers }()\n5272: +\n5273: +\t\t\tvar stdout, stderr bytes.Buffer\n5274: +\t\t\terr := exec(ctx, location.Namespace, location.Pod, location.Container,\n5275: +\t\t\t\t[]string{\"sh\", \"-c\", interfaceSampleScript}, nil, &stdout, &stderr)\n5276: +\t\t\tif err != nil {\n5277: +\t\t\t\tlog.Debug(\"Cannot read the interface state of a c9s node\",\n5278: +\t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n5279: +\t\t\t\treturn\n5280: +\t\t\t}\n5281: +\t\t\t_, ifaces, _, err := parseInterfaceSample(stdout.Bytes())\n5282: +\t\t\tif err != nil {\n5283: +\t\t\t\tlog.Debug(\"Cannot parse the interface state of a c9s node\",\n5284: +\t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n5285: +\t\t\t\treturn\n5286: +\t\t\t}\n5287: +\n5288: +\t\t\tbyName := make(map[string]c9sIfaceState, len(ifaces))\n5289: +\t\t\tfor _, iface := range ifaces {\n5290: +\t\t\t\tbyName[iface.Name] = iface\n5291: +\t\t\t}\n5292: +\t\t\tmu.Lock()\n5293: +\t\t\tresult[location.NodeName] = byName\n5294: +\t\t\tmu.Unlock()\n5295: +\t\t}()\n5296: +\t}\n5297: +\twg.Wait()\n5298: +\n5299: +\treturn result\n5300: +}\n5301: diff --git a/labruntime/clabernetes/capture_test.go b/labruntime/clabernetes/capture_test.go\n5302: new file mode 100644\n5303: index 0000000..16628b5\n5304: --- /dev/null\n5305: +++ b/labruntime/clabernetes/capture_test.go\n5306: @@ -0,0 +1,1050 @@\n5307: +package clabernetes\n5308: +\n5309: +import (\n5310: +\t\"bytes\"\n5311: +\t\"context\"\n5312: +\t\"encoding/binary\"\n5313: +\t\"encoding/json\"\n5314: +\t\"errors\"\n5315: +\t\"fmt\"\n5316: +\t\"io\"\n5317: +\t\"slices\"\n5318: +\t\"strings\"\n5319: +\t\"sync\"\n5320: +\t\"testing\"\n5321: +\t\"time\"\n5322: +\n5323: +\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n5324: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n5325: +\tcorev1 \"k8s.io/api/core/v1\"\n5326: +\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n5327: +\t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n5328: +\tk8sruntime \"k8s.io/apimachinery/pkg/runtime\"\n5329: +)\n5330: +\n5331: +func captureTestNode(name, original, container string) *unstructured.Unstructured {\n5332: +\tlabels := map[string]any{labelTopologyOwner: \"lab1\"}\n5333: +\tif original != \"\" {\n5334: +\t\tlabels[labelOriginalNodeName] = original\n5335: +\t}\n5336: +\n5337: +\treturn &unstructured.Unstructured{Object: map[string]any{\n5338: +\t\t\"apiVersion\": c9sAPIVersion,\n5339: +\t\t\"kind\":       \"Node\",\n5340: +\t\t\"metadata\": map[string]any{\n5341: +\t\t\t\"name\": name, \"namespace\": \"lab-ns\", \"uid\": \"uid-\" + name, \"labels\": labels,\n5342: +\t\t},\n5343: +\t\t\"spec\": map[string]any{\"kind\": \"srl\", \"runState\": nodeRunStateRunning},\n5344: +\t\t\"status\": map[string]any{\n5345: +\t\t\t\"readiness\":        \"ready\",\n5346: +\t\t\t\"directContainers\": []any{map[string]any{\"name\": container, \"id\": name}},\n5347: +\t\t},\n5348: +\t}}\n5349: +}\n5350: +\n5351: +func captureTestPod(name, node string) *corev1.Pod {\n5352: +\treturn &corev1.Pod{\n5353: +\t\tObjectMeta: metav1.ObjectMeta{\n5354: +\t\t\tName: name, Namespace: \"lab-ns\",\n5355: +\t\t\tLabels: map[string]string{\n5356: +\t\t\t\tlabelApp: clabernetesAppValue, labelTopologyOwner: \"lab1\", labelTopologyNode: node,\n5357: +\t\t\t},\n5358: +\t\t},\n5359: +\t\tStatus: corev1.PodStatus{Phase: corev1.PodRunning},\n5360: +\t}\n5361: +}\n5362: +\n5363: +// captureListing is the --list-interfaces output of each pod.\n5364: +var captureListing = map[string][]clabwireInterface{ //nolint:gochecknoglobals\n5365: +\t\"lab1-r1-abc\": {\n5366: +\t\t{\n5367: +\t\t\tNode:          \"r1\",\n5368: +\t\t\tInterface:     \"e1-1\",\n5369: +\t\t\tAlias:         \"ethernet-1/1\",\n5370: +\t\t\tPeerNode:      \"r2\",\n5371: +\t\t\tPeerInterface: \"ethernet-1/1\",\n5372: +\t\t},\n5373: +\t\t{Node: \"r1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"r1-e1-2\"},\n5374: +\t},\n5375: +\t\"lab1-r2-def\": {\n\n(Showing lines 4676-5375 of 7018. Use offset=5376 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+\t\t\t\tc.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)\n+\t\t}\n+\t\tif segment != c.active {\n+\t\t\treturn false, nil\n+\t\t}\n+\n+\t\treturn c.switchSegments(ctx, timer)\n+\t}\n+\n+\treturn false, nil\n+}\n+\n+func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {\n+\tswitch audit.Status {\n+\tcase captureAuditStarted:\n+\t\tsegment.started = audit.Time\n+\t\tlog.Debug(\"Capture segment started\", \"node\", c.group.display, \"segment\", segment.index,\n+\t\t\t\"interfaces\", strings.Join(c.group.interfaces, \",\"), \"duration\", segment.duration)\n+\t\tif segment == c.next && !c.active.started.IsZero() {\n+\t\t\tc.setCut()",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+\t\t\t\tc.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)\n+\t\t}\n+\t\tif segment != c.active {\n+\t\t\treturn false, nil\n+\t\t}\n+\n+\t\treturn c.switchSegments(ctx, timer)\n+\t}\n+\n+\treturn false, nil\n+}\n+\n+func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {\n+\tswitch audit.Status {\n+\tcase captureAuditStarted:\n+\t\tsegment.started = audit.Time\n+\t\tlog.Debug(\"Capture segment started\", \"node\", c.group.display, \"segment\", segment.index,\n+\t\t\t\"interfaces\", strings.Join(c.group.interfaces, \",\"), \"duration\", segment.duration)\n+\t\tif segment == c.next && !c.active.started.IsZero() {\n+\t\t\tc.setCut()\n+\t\t}\n+\t\tif segment == c.next {\n+\t\t\tc.retries = 0\n+\t\t}\n+\tcase captureAuditSucceeded:\n+\t\tsegment.ended = audit.Time\n+\t\tlog.Debug(\"Capture segment succeeded\", \"node\", c.group.display,\n+\t\t\t\"segment\", segment.index, \"packets\", audit.Packets)\n+\tcase captureAuditDenied, captureAuditFailed:\n+\t\treturn captureAuditError(c.group.display, audit)\n+\t}\n+\n+\treturn nil\n+}\n+\n+// captureAuditError turns a Denied or Failed clabwire audit record into an error.\n+func captureAuditError(node string, audit *captureAudit) error {\n+\tverb := \"failed\"\n+\tif audit.Status == captureAuditDenied {\n+\t\tverb = \"was denied\"\n+\t}\n+\tinterfaces := make([]string, 0, len(audit.Interfaces))\n+\tfor _, intf := range audit.Interfaces {\n+\t\tinterfaces = append(interfaces, intf.Name)\n+\t}\n+\n+\treturn fmt.Errorf(\"capture of %s on node %s %s by clabwire: %s\",\n+\t\tstrings.Join(interfaces, \",\"), node, verb, audit.Reason)\n+}\n+\n+// setCut places the cut in the middle of the overlap of the active and the next segment, both\n+// measured on the pod clock.\n+func (c *captureChain) setCut() {\n+\toverlapStart := c.next.started\n+\toverlapEnd := c.active.plannedEnd()\n+\tif overlapEnd.Sub(overlapStart) < 2*c.capture.window {\n+\t\t// the overlap is too short to match packets around a cut: the switch is reported as a\n+\t\t// gap once the active segment ended\n+\t\tc.cut = 0\n+\t\treturn\n+\t}\n+\tc.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()\n+\n+\twindow := c.capture.window.Nanoseconds()\n+\t// Packets the next segment holds back are stamped from T-W on: other chains' packets after\n+\t// that wait in the reorder buffer until the switch, so the merged stream stays in order.\n+\tc.capture.out.Hold(c, c.cut-window)\n+\n+\t// The active segment only matters for packets stamped before T. Once the pod clock passed\n+\t// T+W, it is closed: packets it read until then are still delivered, and the ones it reads\n+\t// later are stamped after T and dropped anyway. The next segment's Started record was\n+\t// written on the pod clock no later than now, so the pod clock passes T+W no later than\n+\t// (T - Started + W) from now.\n+\tactive := c.active\n+\tactive.stopTimer = time.AfterFunc(\n+\t\ttime.Duration(c.cut-c.next.started.UnixNano()+window), active.closeStdin)\n+}\n+\n+func (c *captureChain) handlePacket(\n+\tsegment *captureSegment,\n+\tpacket *clabcapture.Packet,\n+) (bool, error) {\n+\tswitch segment {\n+\tcase c.active:\n+\t\tif c.cut != 0 && packet.Timestamp >= c.cut {\n+\t\t\treturn false, nil\n+\t\t}\n+\t\tif c.next != nil {\n+\t\t\tc.emitted[packetKey(packet)]++\n+\t\t}\n+\n+\t\treturn c.emit(packet)\n+\tcase c.next:\n+\t\tc.held = append(c.held, packet)\n+\t}\n+\n+\treturn false, nil\n+}\n+\n+func (c *captureChain) emit(packet *clabcapture.Packet) (bool, error) {\n+\tif int(packet.InterfaceID) >= len(c.group.ids) {\n+\t\treturn true, fmt.Errorf(\"clabwire wrote a packet for interface %d of %d\",\n+\t\t\tpacket.InterfaceID, len(c.group.ids))\n+\t}\n+\tmore, err := c.capture.emit(c.group.ids[packet.InterfaceID], packet)\n+\n+\treturn !more, err\n+}\n+\n+// switchSegments makes the next segment the active one after the active one ended, writing the\n+// held packets of the next one that the active one did not write.\n+func (c *captureChain) switchSegments(ctx context.Context, timer *time.Timer) (bool, error) {\n+\t// the held packets are in the reorder buffer once this returns\n+\tdefer c.capture.out.Release(c)\n+\n+\tended := c.active\n+\tif c.stopping && c.next != nil && c.next.started.IsZero() {\n+\t\t// the chain is stopping: a follow-up that has not started takes nothing over\n+\t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n+\t}\n+\tif c.final && c.next == nil {\n+\t\treturn true, nil\n+\t}\n+\n+\tif c.next == nil || c.next.started.IsZero() || c.cut == 0 {\n+\t\tfrom := ended.ended\n+\t\tif from.IsZero() {\n+\t\t\tfrom = ended.plannedEnd()\n+\t\t}\n+\t\tgap := clablabruntime.CaptureGap{\n+\t\t\tNode: c.group.display, Interfaces: c.group.interfaces, From: from,\n+\t\t\tReason: \"the follow-up capture did not overlap the previous one\",\n+\t\t}\n+\t\tif c.next != nil && !c.next.started.IsZero() {\n+\t\t\tgap.To = c.next.started\n+\t\t}\n+\t\tc.capture.reportGap(gap)\n+\t}\n+\n+\tif c.next != nil && c.next.done && !c.stopping {\n+\t\t// the follow-up already ended (it started too late to take over): keep what it\n+\t\t// captured and continue with a fresh segment\n+\t\tfor _, packet := range c.held {\n+\t\t\tif stop, err := c.emit(packet); stop || err != nil {\n+\t\t\t\treturn true, err\n+\t\t\t}\n+\t\t}\n+\t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n+\t}\n+\n+\tif c.next == nil {\n+\t\tif !c.capture.deadline.IsZero() &&\n+\t\t\t!time.Now().Before(c.capture.deadline.Add(-c.capture.window)) {\n+\t\t\treturn true, nil\n+\t\t}\n+\t\tc.active = c.start(ctx, c.segmentDuration(time.Now()))\n+\t\tresetTimer(timer, c.nextStartIn())\n+\n+\t\treturn false, nil\n+\t}\n+\n+\twindow := c.capture.window.Nanoseconds()\n+\tfor _, packet := range c.held {\n+\t\tif c.cut != 0 {\n+\t\t\tif packet.Timestamp < c.cut-window {\n+\t\t\t\tcontinue\n+\t\t\t}\n+\t\t\tif packet.Timestamp < c.cut+window {\n+\t\t\t\tkey := packetKey(packet)\n+\t\t\t\tif c.emitted[key] > 0 {\n+\t\t\t\t\tc.emitted[key]--\n+\t\t\t\t\tcontinue\n+\t\t\t\t}\n+\t\t\t}\n+\t\t}\n+\t\tif stop, err := c.emit(packet); stop || err != nil {\n+\t\t\treturn true, err\n+\t\t}\n+\t}\n+\n+\tc.active, c.next = c.next, nil\n+\tc.held, c.emitted, c.cut = nil, nil, 0\n+\tif c.active.done {\n+\t\t// the chain is stopping and the follow-up ended before the active one\n+\t\treturn true, nil\n+\t}\n+\tresetTimer(timer, c.nextStartIn())\n+\n+\treturn false, nil\n+}\n+\n+func resetTimer(timer *time.Timer, d time.Duration) {\n+\tif !timer.Stop() {\n+\t\tselect {\n+\t\tcase <-timer.C:\n+\t\tdefault:\n+\t\t}\n+\t}\n+\ttimer.Reset(d)\n+}\n+\n+// packetKey identifies a packet by its interface and content.\n+func packetKey(packet *clabcapture.Packet) uint64 {\n+\thash := fnv.New64a()\n+\tvar id [4]byte\n+\tid[0] = byte(packet.InterfaceID)\n+\tid[1] = byte(packet.InterfaceID >> 8)\n+\t_, _ = hash.Write(id[:])\n+\t_, _ = hash.Write(packet.Data)\n+\n+\treturn hash.Sum64()\n+}\n+\n+// start runs one clabwire capture and reports its packets, audit records and end as events.\n+func (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {\n+\tsegmentCtx, cancel := context.WithCancel(ctx)\n+\tstdinReader, stdinWriter := io.Pipe()\n+\tsegment := &captureSegment{\n+\t\tindex: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,\n+\t\tcloseStdin: func() { _ = stdinWriter.Close() },\n+\t}\n+\tc.segments++\n+\n+\tcommand := []string{\n+\t\tclabwireManager, \"node-runtime\", \"packet-capture\",\n+\t\t\"--nodeName\", c.group.location.NodeName,\n+\t\t\"--format\", \"pcapng\",\n+\t\t\"--snapLength\", strconv.Itoa(c.capture.req.SnapLength),\n+\t\t\"--duration\", duration.String(),\n+\t\tclabwireStopOnStdinClose,\n+\t}\n+\tfor _, name := range c.group.interfaces {\n+\t\tcommand = append(command, \"--interface\", name)\n+\t}\n+\tif c.capture.req.PacketLimit > 0 {\n+\t\tremaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()\n+\t\tcommand = append(command, \"--packetLimit\",\n+\t\t\tstrconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))\n+\t}\n+\n+\tsend := func(event segmentEvent) {\n+\t\tevent.segment = segment\n+\t\tselect {\n+\t\tcase c.events <- event:\n+\t\tcase <-segmentCtx.Done():\n+\t\t}\n+\t}\n+\n+\tstdoutReader, stdoutWriter := io.Pipe()\n+\tstderr := &auditLineWriter{send: func(audit *captureAudit) { send(segmentEvent{audit: audit}) }}\n+\n+\t// The exec outlives the segment's context by up to captureStdinCloseGrace: when the segment\n+\t// ends for any reason (the capture is cancelled or failed, the output failed, or a newer\n+\t// segment took over), its stdin is closed first so clabwire ends on its own, and the stream\n+\t// is cut only if it does not.\n+\texecCtx, cancelExec := context.WithCancel(context.WithoutCancel(segmentCtx))\n+\texecDone := make(chan struct{})\n+\n+\tc.wg.Add(3)\n+\treadDone := make(chan error, 1)\n+\tgo func() {\n+\t\tdefer c.wg.Done()\n+\t\treadDone <- c.readSegment(stdoutReader, func(packet *clabcapture.Packet) {\n+\t\t\tsend(segmentEvent{packet: packet})\n+\t\t})\n+\t\t_, _ = io.Copy(io.Discard, stdoutReader)\n+\t}()\n+\tgo func() {\n+\t\tdefer c.wg.Done()\n+\t\tselect {\n+\t\tcase <-execDone:\n+\t\t\treturn\n+\t\tcase <-segmentCtx.Done():\n+\t\t}\n+\t\tsegment.closeStdin()\n+\t\tgrace := time.NewTimer(captureStdinCloseGrace)\n+\t\tdefer grace.Stop()\n+\t\tselect {\n+\t\tcase <-execDone:\n+\t\tcase <-grace.C:\n+\t\t\tlog.Debug(\"Capture segment did not end after its stdin closed, cutting the stream\",\n+\t\t\t\t\"node\", c.group.display, \"segment\", segment.index)\n+\t\t\tcancelExec()\n+\t\t}\n+\t}()\n+\tgo func() {\n+\t\tdefer c.wg.Done()\n+\t\tdefer cancel()\n+\t\tdefer cancelExec()\n+\n+\t\terr := c.capture.r.execInPodContainer()(execCtx, c.group.location.Namespace,\n+\t\t\tc.group.location.Pod, clabwireContainer, command, stdinReader, stdoutWriter, stderr)\n+\t\tclose(execDone)\n+\t\t// the process ended: release the stdin copy of the exec stream\n+\t\tsegment.closeStdin()\n+\t\t_ = stdoutWriter.Close()\n+\t\treadErr := <-readDone\n+\t\tstderr.flush()\n+\t\tif err == nil && readErr != nil {\n+\t\t\terr = readErr\n+\t\t}\n+\t\tif err != nil && stderr.text() != \"\" {\n+\t\t\tif unsupported := unsupportedClabwire(\n+\t\t\t\tc.group.location,\n+\t\t\t\tstderr.text(),\n+\t\t\t); unsupported != nil {\n+\t\t\t\terr = unsupported\n+\t\t\t} else {\n+\t\t\t\terr = fmt.Errorf(\"%w: %s\", err, stderr.text())\n+\t\t\t}\n+\t\t}\n+\t\tsend(segmentEvent{done: true, err: err})\n+\t}()\n+\n+\treturn segment\n+}\n+\n+// unsupportedClabwire recognizes a clabwire that rejects --stop-on-stdin-close, which every\n+// capture passes: its release predates the capture contract the runtime needs.\n+func unsupportedClabwire(location clablabruntime.NodeLocation, stderr string) error {\n+\tif !strings.Contains(stderr, \"flag provided but not defined\") ||\n+\t\t!strings.Contains(stderr, strings.TrimPrefix(clabwireStopOnStdinClose, \"-\")) {\n+\t\treturn nil\n+\t}\n+\n+\treturn &unsupportedClabernetesError{reason: fmt.Sprintf(\n+\t\t\"clabwire in pod %s/%s does not accept packet-capture %s\",\n+\t\tlocation.Namespace, location.Pod, clabwireStopOnStdinClose)}\n+}\n+\n+// readSegment checks that a segment's interfaces are the requested ones and passes its packets\n+// on with the segment's interface index.\n+func (c *captureChain) readSegment(stdout io.Reader, packet func(*clabcapture.Packet)) error {\n+\treader := clabcapture.NewReader(stdout)\n+\tinterfaces := 0\n+\tfor {\n+\t\tevent, err := reader.Next()\n+\t\tif errors.Is(err, io.EOF) {\n+\t\t\treturn nil\n+\t\t}\n+\t\tif errors.Is(err, io.ErrUnexpectedEOF) {\n+\t\t\t// the process was stopped inside a block\n+\t\t\treturn nil\n+\t\t}\n+\t\tif err != nil {\n+\t\t\treturn fmt.Errorf(\"failed to read the clabwire capture: %w\", err)\n+\t\t}\n+\t\tif event.Interface != nil {\n+\t\t\tif interfaces >= len(c.group.interfaces) ||\n+\t\t\t\tevent.Interface.Name != c.group.interfaces[interfaces] {\n+\t\t\t\treturn fmt.Errorf(\"clabwire described interface %q, want %s in order\",\n+\t\t\t\t\tevent.Interface.Name, strings.Join(c.group.interfaces, \", \"))\n+\t\t\t}\n+\t\t\tinterfaces++\n+\t\t\tcontinue\n+\t\t}\n+\t\tif event.Packet != nil {\n+\t\t\tpacket(event.Packet)\n+\t\t}\n+\t}\n+}\n+\n+// auditLineWriter parses clabwire's stderr: audit records go to send, other lines are kept for\n+// error messages.\n+type auditLineWriter struct {\n+\tsend func(*captureAudit)\n+\n+\tmu      sync.Mutex\n+\tpartial []byte\n+\tother   []string\n+}\n+\n+func (w *auditLineWriter) Write(data []byte) (int, error) {\n+\tw.mu.Lock()\n+\tw.partial = append(w.partial, data...)\n+\tvar lines [][]byte\n+\tfor {\n+\t\tidx := bytes.IndexByte(w.partial, '\\n')\n+\t\tif idx < 0 {\n+\t\t\tbreak\n+\t\t}\n+\t\tlines = append(lines, append([]byte(nil), w.partial[:idx]...))\n+\t\tw.partial = w.partial[idx+1:]\n+\t}\n+\tw.mu.Unlock()\n+\n+\tfor _, line := range lines {\n+\t\tw.line(line)\n+\t}\n+\n+\treturn len(data), nil\n+}\n+\n+func (w *auditLineWriter) flush() {\n+\tw.mu.Lock()\n+\tline := w.partial\n+\tw.partial = nil\n+\tw.mu.Unlock()\n+\tif len(bytes.TrimSpace(line)) != 0 {\n+\t\tw.line(line)\n+\t}\n+}\n+\n+func (w *auditLineWriter) line(line []byte) {\n+\tline = bytes.TrimSpace(line)\n+\tif len(line) == 0 {\n+\t\treturn\n+\t}\n+\n+\tvar audit captureAudit\n+\tif err := json.Unmarshal(\n+\t\tline,\n+\t\t&audit,\n+\t); err == nil &&\n+\t\taudit.SchemaVersion == captureAuditSchema {\n+\t\tw.send(&audit)\n+\t\treturn\n+\t}\n+\n+\tw.mu.Lock()\n+\tdefer w.mu.Unlock()\n+\tif len(w.other) < 20 {\n+\t\tw.other = append(w.other, string(line))\n+\t}\n+}\n+\n+func (w *auditLineWriter) text() string {\n+\tw.mu.Lock()\n+\tdefer w.mu.Unlock()\n+\n+\treturn strings.Join(w.other, \"; \")\n+}\ndiff --git a/labruntime/clabernetes/capture_interfaces.go b/labruntime/clabernetes/capture_interfaces.go\nnew file mode 100644\nindex 0000000..21029ed\n--- /dev/null\n+++ b/labruntime/clabernetes/capture_interfaces.go\n@@ -0,0 +1,187 @@\n+package clabernetes\n+\n+import (\n+\t\"bytes\"\n+\t\"context\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"sort\"\n+\t\"sync\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tclabtypes \"github.com/srl-labs/containerlab/types\"\n+\tcorev1 \"k8s.io/api/core/v1\"\n+\t\"k8s.io/client-go/kubernetes/scheme\"\n+\t\"k8s.io/client-go/tools/remotecommand\"\n+\tkubeexec \"k8s.io/client-go/util/exec\"\n+)\n+\n+// streamPodExec runs a command in a pod container without a terminal and streams its stdout\n+// and stderr. A non-nil stdin is attached: when it ends, the process's stdin is closed (the\n+// websocket v5 close signal, or a half-closed SPDY stream). A nonzero exit returns a\n+// *labruntime.CommandExitError.\n+func (r *Runtime) streamPodExec(\n+\tctx context.Context,\n+\tnamespace, pod, container string,\n+\tcommand []string,\n+\tstdin io.Reader,\n+\tstdout, stderr io.Writer,\n+) error {\n+\texecURL := r.kubeClient.CoreV1().RESTClient().Post().\n+\t\tResource(\"pods\").\n+\t\tName(pod).\n+\t\tNamespace(namespace).\n+\t\tSubResource(\"exec\").\n+\t\tVersionedParams(&corev1.PodExecOptions{\n+\t\t\tContainer: container,\n+\t\t\tCommand:   command,\n+\t\t\tStdin:     stdin != nil,\n+\t\t\tStdout:    stdout != nil,\n+\t\t\tStderr:    stderr != nil,\n+\t\t}, scheme.ParameterCodec).URL()\n+\n+\texecutor, err := r.newExecutor(execURL)\n+\tif err != nil {\n+\t\treturn err\n+\t}\n+\n+\t// client-go reports streams cut by a cancelled context through the context's logger; a\n+\t// capture ends that way on purpose, so it goes to the debug log\n+\terr = executor.StreamWithContext(withKubernetesClientDebugLogs(ctx),\n+\t\tremotecommand.StreamOptions{\n+\t\t\tStdin:  stdin,\n+\t\t\tStdout: stdout,\n+\t\t\tStderr: stderr,\n+\t\t})\n+\n+\tvar exitErr kubeexec.ExitError\n+\tif errors.As(err, &exitErr) {\n+\t\treturn &clablabruntime.CommandExitError{Code: exitErr.ExitStatus()}\n+\t}\n+\tif err != nil {\n+\t\treturn fmt.Errorf(\"failed to execute command in pod %s/%s container %s: %w\",\n+\t\t\tnamespace, pod, container, err)\n+\t}\n+\n+\treturn nil\n+}\n+\n+// InspectInterfaces lists the capturable link interfaces of the requested nodes, or of every\n+// running node, in the shape of `inspect interfaces`: per node (named <lab>-<node> like in\n+// inspect), the interface and its alias as clabwire reports them, and the MAC address, index,\n+// MTU and operational state read from sysfs in the device container. A node whose device\n+// container has no shell reports its interfaces without these attributes.\n+func (r *Runtime) InspectInterfaces(\n+\tctx context.Context,\n+\treq clablabruntime.NodeRequest,\n+) ([]*clabtypes.ContainerInterfaces, error) {\n+\tr, err := r.connect(ctx, req.Identity)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n+\t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n+\t})\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\n+\trunning := make([]clablabruntime.NodeLocation, 0, len(locations))\n+\tfor _, location := range locations {\n+\t\tif location.Pod == \"\" {\n+\t\t\tlog.Warn(\"Skipping interface detection of a node that does not run\",\n+\t\t\t\t\"node\", location.NodeName)\n+\t\t\tcontinue\n+\t\t}\n+\t\trunning = append(running, location)\n+\t}\n+\n+\tlisted, err := r.listCaptureInterfaces(ctx, req.Name, running)\n+\tif err != nil {\n+\t\treturn nil, err\n+\t}\n+\tstates := r.sampleInterfaceStates(ctx, running)\n+\n+\tresult := make([]*clabtypes.ContainerInterfaces, 0, len(running))\n+\tfor _, location := range running {\n+\t\tcontainer := &clabtypes.ContainerInterfaces{\n+\t\t\tContainerName: req.Name + \"-\" + location.NodeName,\n+\t\t\tInterfaces:    []*clabtypes.ContainerInterfaceDetails{},\n+\t\t}\n+\t\tfor _, entry := range listed[location.NodeName] {\n+\t\t\tdetails := &clabtypes.ContainerInterfaceDetails{\n+\t\t\t\tInterfaceName:  entry.Interface,\n+\t\t\t\tInterfaceAlias: entry.Alias,\n+\t\t\t\t// clabwire realizes every lab link interface as a veth pair\n+\t\t\t\tInterfaceType: \"veth\",\n+\t\t\t}\n+\t\t\tif state, ok := states[location.NodeName][entry.Interface]; ok {\n+\t\t\t\tdetails.InterfaceMAC = state.MAC\n+\t\t\t\tdetails.InterfaceIndex = state.Index\n+\t\t\t\tdetails.InterfaceMTU = state.MTU\n+\t\t\t\tdetails.InterfaceState = state.OperState\n+\t\t\t}\n+\t\t\tcontainer.Interfaces = append(container.Interfaces, details)\n+\t\t}\n+\t\tsort.Slice(container.Interfaces, func(i, j int) bool {\n+\t\t\treturn container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName\n+\t\t})\n+\t\tresult = append(result, container)\n+\t}\n+\tsort.Slice(result, func(i, j int) bool {\n+\t\treturn result[i].ContainerName < result[j].ContainerName\n+\t})\n+\n+\treturn result, nil\n+}\n+\n+// sampleInterfaceStates reads the sysfs interface attributes of every node's device container,\n+// one exec per node, with the script the interface events use.\n+func (r *Runtime) sampleInterfaceStates(\n+\tctx context.Context,\n+\tlocations []clablabruntime.NodeLocation,\n+) map[string]map[string]c9sIfaceState {\n+\tvar mu sync.Mutex\n+\tresult := map[string]map[string]c9sIfaceState{}\n+\n+\tvar wg sync.WaitGroup\n+\tworkers := make(chan struct{}, interfaceSampleWorkers)\n+\texec := r.execInPodContainer()\n+\tfor _, location := range locations {\n+\t\twg.Add(1)\n+\t\tgo func() {\n+\t\t\tdefer wg.Done()\n+\t\t\tworkers <- struct{}{}\n+\t\t\tdefer func() { <-workers }()\n+\n+\t\t\tvar stdout, stderr bytes.Buffer\n+\t\t\terr := exec(ctx, location.Namespace, location.Pod, location.Container,\n+\t\t\t\t[]string{\"sh\", \"-c\", interfaceSampleScript}, nil, &stdout, &stderr)\n+\t\t\tif err != nil {\n+\t\t\t\tlog.Debug(\"Cannot read the interface state of a c9s node\",\n+\t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n+\t\t\t\treturn\n+\t\t\t}\n+\t\t\t_, ifaces, _, err := parseInterfaceSample(stdout.Bytes())\n+\t\t\tif err != nil {\n+\t\t\t\tlog.Debug(\"Cannot parse the interface state of a c9s node\",\n+\t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n+\t\t\t\treturn\n+\t\t\t}\n+\n+\t\t\tbyName := make(map[string]c9sIfaceState, len(ifaces))\n+\t\t\tfor _, iface := range ifaces {\n+\t\t\t\tbyName[iface.Name] = iface\n+\t\t\t}\n+\t\t\tmu.Lock()\n+\t\t\tresult[location.NodeName] = byName\n+\t\t\tmu.Unlock()\n+\t\t}()\n+\t}\n+\twg.Wait()\n+\n+\treturn result\n+}\ndiff --git a/labruntime/clabernetes/capture_test.go b/labruntime/clabernetes/capture_test.go\nnew file mode 100644\nindex 0000000..16628b5\n--- /dev/null\n+++ b/labruntime/clabernetes/capture_test.go\n@@ -0,0 +1,1050 @@\n+package clabernetes\n+\n+import (\n+\t\"bytes\"\n+\t\"context\"\n+\t\"encoding/binary\"\n+\t\"encoding/json\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"io\"\n+\t\"slices\"\n+\t\"strings\"\n+\t\"sync\"\n+\t\"testing\"\n+\t\"time\"\n+\n+\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tcorev1 \"k8s.io/api/core/v1\"\n+\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n+\t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n+\tk8sruntime \"k8s.io/apimachinery/pkg/runtime\"\n+)\n+\n+func captureTestNode(name, original, container string) *unstructured.Unstructured {\n+\tlabels := map[string]any{labelTopologyOwner: \"lab1\"}\n+\tif original != \"\" {\n+\t\tlabels[labelOriginalNodeName] = original\n+\t}\n+\n+\treturn &unstructured.Unstructured{Object: map[string]any{\n+\t\t\"apiVersion\": c9sAPIVersion,\n+\t\t\"kind\":       \"Node\",\n+\t\t\"metadata\": map[string]any{\n+\t\t\t\"name\": name, \"namespace\": \"lab-ns\", \"uid\": \"uid-\" + name, \"labels\": labels,\n+\t\t},\n+\t\t\"spec\": map[string]any{\"kind\": \"srl\", \"runState\": nodeRunStateRunning},\n+\t\t\"status\": map[string]any{\n+\t\t\t\"readiness\":        \"ready\",\n+\t\t\t\"directContainers\": []any{map[string]any{\"name\": container, \"id\": name}},\n+\t\t},\n+\t}}\n+}\n+\n+func captureTestPod(name, node string) *corev1.Pod {\n+\treturn &corev1.Pod{\n+\t\tObjectMeta: metav1.ObjectMeta{\n+\t\t\tName: name, Namespace: \"lab-ns\",\n+\t\t\tLabels: map[string]string{\n+\t\t\t\tlabelApp: clabernetesAppValue, labelTopologyOwner: \"lab1\", labelTopologyNode: node,\n+\t\t\t},\n+\t\t},\n+\t\tStatus: corev1.PodStatus{Phase: corev1.PodRunning},\n+\t}\n+}\n+\n+// captureListing is the --list-interfaces output of each pod.\n+var captureListing = map[string][]clabwireInterface{ //nolint:gochecknoglobals\n+\t\"lab1-r1-abc\": {\n+\t\t{\n+\t\t\tNode:          \"r1\",\n+\t\t\tInterface:     \"e1-1\",\n+\t\t\tAlias:         \"ethernet-1/1\",\n+\t\t\tPeerNode:      \"r2\",\n+\t\t\tPeerInterface: \"ethernet-1/1\",\n+\t\t},\n+\t\t{Node: \"r1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"r1-e1-2\"},\n+\t},\n+\t\"lab1-r2-def\": {",
        "lineStart": 4676,
        "lineEnd": 5375,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523445054,
      "end": 1793523445067
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19653ed4d001BPclrBtk4y0mwe",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653e445001J6rvVNoreYHJnq",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 67546,
    "input": 8894,
    "output": 27,
    "reasoning": 1,
    "cache": {
      "read": 58624,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19653e445001J6rvVNoreYHJnq",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523442757,
    "completed": 1793523445072
  },
  "parentID": "msg_19653b129001cj4QAfxRVtxTFM",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 67546,
    "input": 8894,
    "output": 27,
    "reasoning": 1,
    "cache": {
      "read": 58624,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 50
step-start
{
  "type": "step-start",
  "id": "prt_19653f622001EOcX9VYZ1hTET1",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653ed5a001JQ2uENCIAXE6MW"
}
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 700,
  "offset": 5376
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
5376: +		{
5377: +			Node:          "r2",
5378: +			Interface:     "e1-1",
5379: +			Alias:         "ethernet-1/1",
5380: +			PeerNode:      "r1",
5381: +			PeerInterface: "ethernet-1/1",
5382: +		},
5383: +	},
5384: +}
5385: +
5386: +// fakeClabwire plays clabwire packet-capture and --list-interfaces in the fake pod exec. Every
5387: +// capture process sees the same traffic: one packet per tick on each requested interface,
5388: +// carrying the tick number, stamped with the tick time plus a per-process jitter (clabwire stamps
5389: +// packets when it reads them).
5390: +type fakeClabwire struct {
5391: +	t     *testing.T
5392: +	epoch time.Time
5393: +	tick  time.Duration
5394: +
5395: +	mu       sync.Mutex
5396: +	commands [][]string
5397: +	// processes counts the capture processes started per node
5398: +	processes map[string]int
5399: +
5400: +	// startDelay delays the Started record of the given process index (all nodes).
5401: +	startDelay map[int]time.Duration
5402: +	// firstStartDelay delays the Started record of a node's first process.
5403: +	firstStartDelay map[string]time.Duration
5404: +	// fail makes a process write this audit status and exit 1.
5405: +	fail string
5406: +	// stderrOnly makes a process write this text to stderr and exit 1, like a clabwire that
5407: +	// rejects a flag.
5408: +	stderrOnly string
5409: +	// stampSkew stamps the packets of a node this much earlier, as if its stream reached
5410: +	// containerlab this much later than the others.
5411: +	stampSkew map[string]time.Duration
5412: +	// stdinClosed counts the processes that ended because their stdin closed, per node.
5413: +	stdinClosed map[string]int
5414: +	// written counts the packets written to stdout, per node.
5415: +	written map[string]int
5416: +	// sysfs is the device container's interface sample.
5417: +	sysfs string
5418: +}
5419: +
5420: +func newFakeClabwire(t *testing.T, tick time.Duration) *fakeClabwire {
5421: +	t.Helper()
5422: +
5423: +	return &fakeClabwire{
5424: +		t: t, epoch: time.Now(), tick: tick, processes: map[string]int{},
5425: +		startDelay: map[int]time.Duration{}, stampSkew: map[string]time.Duration{},
5426: +		firstStartDelay: map[string]time.Duration{},
5427: +		stdinClosed:     map[string]int{},
5428: +		written:         map[string]int{},
5429: +	}
5430: +}
5431: +
5432: +func (f *fakeClabwire) exec(
5433: +	ctx context.Context,
5434: +	namespace, pod, container string,
5435: +	command []string,
5436: +	stdin io.Reader,
5437: +	stdout, stderr io.Writer,
5438: +) error {
5439: +	f.mu.Lock()
5440: +	f.commands = append(
5441: +		f.commands,
5442: +		append([]string{namespace + "/" + pod + "/" + container}, command...),
5443: +	)
5444: +	f.mu.Unlock()
5445: +
5446: +	if container != clabwireContainer {
5447: +		_, _ = io.WriteString(stdout, f.sysfs)
5448: +		return nil
5449: +	}
5450: +	if slices.Contains(command, "--list-interfaces") {
5451: +		return json.NewEncoder(stdout).Encode(captureListing[pod])
5452: +	}
5453: +
5454: +	return f.capture(ctx, command, stdin, stdout, stderr)
5455: +}
5456: +
5457: +func flagValues(command []string, name string) []string {
5458: +	var values []string
5459: +	for idx := 0; idx+1 < len(command); idx++ {
5460: +		if command[idx] == name {
5461: +			values = append(values, command[idx+1])
5462: +		}
5463: +	}
5464: +
5465: +	return values
5466: +}
5467: +
5468: +func (f *fakeClabwire) audit(
5469: +	stderr io.Writer,
5470: +	status, node string,
5471: +	interfaces []string,
5472: +	reason string,
5473: +) {
5474: +	record := map[string]any{
5475: +		"schemaVersion": captureAuditSchema, "time": time.Now().UTC(), "operation": "PacketCapture",
5476: +		"status": status, "nodeName": node, "format": "pcapng", "reason": reason,
5477: +	}
5478: +	entries := []map[string]any{}
5479: +	for _, name := range interfaces {
5480: +		entries = append(entries, map[string]any{"name": name})
5481: +	}
5482: +	record["interfaces"] = entries
5483: +	data, _ := json.Marshal(record)
5484: +	_, _ = stderr.Write(append(data, '\n'))
5485: +}
5486: +
5487: +func (f *fakeClabwire) capture(
5488: +	ctx context.Context,
5489: +	command []string,
5490: +	stdin io.Reader,
5491: +	stdout, stderr io.Writer,
5492: +) error {
5493: +	f.mu.Lock()
5494: +	rejected := f.stderrOnly
5495: +	f.mu.Unlock()
5496: +	if rejected != "" {
5497: +		_, _ = io.WriteString(stdout, "Incorrect Usage: "+rejected+"\n\nNAME:\n   manager\n")
5498: +		_, _ = io.WriteString(stderr, rejected+"\n")
5499: +		return &clablabruntime.CommandExitError{Code: 1}
5500: +	}
5501: +
5502: +	// clabwire ends the capture when stdin closes (--stop-on-stdin-close)
5503: +	if !slices.Contains(command, clabwireStopOnStdinClose) || stdin == nil {
5504: +		f.t.Errorf("capture without stdin and %s: %v", clabwireStopOnStdinClose, command)
5505: +		return fmt.Errorf("no stdin")
5506: +	}
5507: +	stdinClosed := make(chan struct{})
5508: +	go func() {
5509: +		_, _ = io.Copy(io.Discard, stdin)
5510: +		close(stdinClosed)
5511: +	}()
5512: +
5513: +	node := flagValues(command, "--nodeName")[0]
5514: +	interfaces := flagValues(command, "--interface")
5515: +	duration, err := time.ParseDuration(flagValues(command, "--duration")[0])
5516: +	if err != nil {
5517: +		f.t.Errorf("duration: %v", err)
5518: +	}
5519: +	if !slices.Equal(flagValues(command, "--format"), []string{"pcapng"}) {
5520: +		f.t.Errorf("capture without --format pcapng: %v", command)
5521: +	}
5522: +
5523: +	f.mu.Lock()
5524: +	index := f.processes[node]
5525: +	f.processes[node]++
5526: +	delay := f.startDelay[index]
5527: +	if index == 0 {
5528: +		delay += f.firstStartDelay[node]
5529: +	}
5530: +	failure := f.fail
5531: +	skew := f.stampSkew[node]
5532: +	f.mu.Unlock()
5533: +
5534: +	if failure != "" {
5535: +		f.audit(stderr, failure, node, interfaces, "interface \"eth9\" is not uniquely planned")
5536: +		return &clablabruntime.CommandExitError{Code: 1}
5537: +	}
5538: +
5539: +	select {
5540: +	case <-time.After(delay):
5541: +	case <-ctx.Done():
5542: +		return ctx.Err()
5543: +	case <-stdinClosed:
5544: +		f.audit(stderr, captureAuditStarted, node, interfaces, "")
5545: +		f.audit(stderr, captureAuditSucceeded, node, interfaces, "client closed: stdin reached EOF")
5546: +		return nil
5547: +	}
5548: +
5549: +	writer := clabcapture.NewWriter(stdout)
5550: +	f.audit(stderr, captureAuditStarted, node, interfaces, "")
5551: +	if err := writer.WriteHeader(interfaces, clabcapture.DefaultSnapLength); err != nil {
5552: +		return err
5553: +	}
5554: +
5555: +	// clabwire's own section header names it
5556: +	end := time.Now().Add(duration)
5557: +	jitter := time.Duration(index%3) * 7 * time.Microsecond
5558: +	next := time.Now().Sub(f.epoch)/f.tick + 1
5559: +	for {
5560: +		at := f.epoch.Add(next * f.tick)
5561: +		if at.After(end) {
5562: +			break
5563: +		}
5564: +		select {
5565: +		case <-ctx.Done():
5566: +			return ctx.Err()
5567: +		case <-stdinClosed:
5568: +			f.mu.Lock()
5569: +			f.stdinClosed[node]++
5570: +			f.mu.Unlock()
5571: +			f.audit(
5572: +				stderr,
5573: +				captureAuditSucceeded,
5574: +				node,
5575: +				interfaces,
5576: +				"client closed: stdin reached EOF",
5577: +			)
5578: +			return nil
5579: +		case <-time.After(time.Until(at)):
5580: +		}
5581: +		for id := range interfaces {
5582: +			data := make([]byte, 64)
5583: +			binary.BigEndian.PutUint64(data[0:], uint64(next))
5584: +			copy(data[8:], node+":"+interfaces[id])
5585: +			if err := writer.WritePacket(uint32(id), &clabcapture.Packet{ //nolint:gosec // small
5586: +				Timestamp: at.Add(jitter - skew).UnixNano(), OriginalLength: 64, Data: data,
5587: +			}); err != nil {
5588: +				return err
5589: +			}
5590: +			f.mu.Lock()
5591: +			f.written[node]++
5592: +			f.mu.Unlock()
5593: +		}
5594: +		next++
5595: +	}
5596: +	f.audit(stderr, captureAuditSucceeded, node, interfaces, "")
5597: +
5598: +	return nil
5599: +}
5600: +
5601: +func (f *fakeClabwire) captureCommands() [][]string {
5602: +	f.mu.Lock()
5603: +	defer f.mu.Unlock()
5604: +
5605: +	var result [][]string
5606: +	for _, command := range f.commands {
5607: +		if slices.Contains(command, "packet-capture") &&
5608: +			!slices.Contains(command, "--list-interfaces") {
5609: +			result = append(result, command)
5610: +		}
5611: +	}
5612: +
5613: +	return result
5614: +}
5615: +
5616: +// captureTestRuntime is lab1 in lab-ns with nodes r1 (topology name R1) and r2, each in its
5617: +// own pod, and a fake clabwire.
5618: +func captureTestRuntime(t *testing.T, tick time.Duration) (*Runtime, *fakeClabwire) {
5619: +	t.Helper()
5620: +
5621: +	r := newTestRuntimeWithKubeObjects(
5622: +		[]*unstructured.Unstructured{
5623: +			captureTestNode("r1", "R1", "node-r1-x"),
5624: +			captureTestNode("r2", "", "node-r2-x"),
5625: +		},
5626: +		[]k8sruntime.Object{
5627: +			captureTestPod("lab1-r1-abc", "r1"),
5628: +			captureTestPod("lab1-r2-def", "r2"),
5629: +		},
5630: +	)
5631: +	r.labNamespaceOverride = "lab-ns"
5632: +	clabwire := newFakeClabwire(t, tick)
5633: +	r.podExec = clabwire.exec
5634: +
5635: +	return r, clabwire
5636: +}
5637: +
5638: +// parsedCapture is a pcapng stream read back.
5639: +type parsedCapture struct {
5640: +	sections   int
5641: +	interfaces []string
5642: +	packets    []clabcapture.Packet
5643: +}
5644: +
5645: +func parseCapture(t *testing.T, data []byte) parsedCapture {
5646: +	t.Helper()
5647: +
5648: +	reader := clabcapture.NewReader(bytes.NewReader(data))
5649: +	var parsed parsedCapture
5650: +	for {
5651: +		event, err := reader.Next()
5652: +		if errors.Is(err, io.EOF) {
5653: +			break
5654: +		}
5655: +		if err != nil {
5656: +			t.Fatalf("invalid capture: %v", err)
5657: +		}
5658: +		if event.Interface != nil {
5659: +			if len(parsed.packets) != 0 {
5660: +				t.Fatal("interface description after the first packet")
5661: +			}
5662: +			if event.Interface.TSResol != 9 /* nanoseconds */ {
5663: +				t.Fatalf("interface %s tsresol = %d", event.Interface.Name, event.Interface.TSResol)
5664: +			}
5665: +			parsed.interfaces = append(parsed.interfaces, event.Interface.Name)
5666: +		}
5667: +		if event.Packet != nil {
5668: +			parsed.packets = append(parsed.packets, *event.Packet)
5669: +		}
5670: +	}
5671: +	parsed.sections = reader.Sections()
5672: +
5673: +	return parsed
5674: +}
5675: +
5676: +func packetSequence(packet clabcapture.Packet) uint64 {
5677: +	return binary.BigEndian.Uint64(packet.Data[0:8])
5678: +}
5679: +
5680: +func packetOrigin(packet clabcapture.Packet) string {
5681: +	return strings.TrimRight(string(packet.Data[8:]), "\x00")
5682: +}
5683: +
5684: +func TestCaptureInterfacesUsesTopologyNames(t *testing.T) {
5685: +	t.Parallel()
5686: +
5687: +	r, _ := captureTestRuntime(t, time.Millisecond)
5688: +	interfaces, err := r.CaptureInterfaces(
5689: +		context.Background(),
5690: +		clablabruntime.NodeRequest{Name: "lab1"},
5691: +	)
5692: +	if err != nil {
5693: +		t.Fatal(err)
5694: +	}
5695: +	want := []clablabruntime.CaptureInterface{
5696: +		{
5697: +			Node:          "R1",
5698: +			Interface:     "e1-1",
5699: +			Alias:         "ethernet-1/1",
5700: +			PeerNode:      "r2",
5701: +			PeerInterface: "ethernet-1/1",
5702: +		},
5703: +		{Node: "R1", Interface: "e1-2", PeerNode: "host", PeerInterface: "r1-e1-2"},
5704: +		{
5705: +			Node:          "r2",
5706: +			Interface:     "e1-1",
5707: +			Alias:         "ethernet-1/1",
5708: +			PeerNode:      "R1",
5709: +			PeerInterface: "ethernet-1/1",
5710: +		},
5711: +	}
5712: +	if !slices.Equal(interfaces, want) {
5713: +		t.Fatalf("interfaces = %+v\nwant %+v", interfaces, want)
5714: +	}
5715: +
5716: +	one, err := r.CaptureInterfaces(context.Background(), clablabruntime.NodeRequest{
5717: +		Name: "lab1", Nodes: []string{"r2"},
5718: +	})
5719: +	if err != nil || len(one) != 1 || one[0].Node != "r2" {
5720: +		t.Fatalf("r2 interfaces = %+v, %v", one, err)
5721: +	}
5722: +}
5723: +
5724: +func TestCaptureMergesNodesIntoOneSection(t *testing.T) {
5725: +	t.Parallel()
5726: +
5727: +	r, clabwire := captureTestRuntime(t, 10*time.Millisecond)
5728: +	var out bytes.Buffer
5729: +	err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
5730: +		Name: "lab1",
5731: +		// the topology name of r1, an alias, and a second node between two r1 interfaces
5732: +		Targets: []clablabruntime.CaptureTarget{
5733: +			{Node: "R1", Interface: "ethernet-1/1"},
5734: +			{Node: "r2", Interface: "e1-1"},
5735: +			{Node: "r1", Interface: "e1-2"},
5736: +		},
5737: +		Duration: 300 * time.Millisecond,
5738: +	}, &out)
5739: +	if err != nil {
5740: +		t.Fatal(err)
5741: +	}
5742: +
5743: +	parsed := parseCapture(t, out.Bytes())
5744: +	if parsed.sections != 1 {
5745: +		t.Fatalf("sections = %d, want one merged section", parsed.sections)
5746: +	}
5747: +	wantNames := []string{"R1:e1-1", "r2:e1-1", "R1:e1-2"}
5748: +	if !slices.Equal(parsed.interfaces, wantNames) {
5749: +		t.Fatalf("interfaces = %v, want %v", parsed.interfaces, wantNames)
5750: +	}
5751: +
5752: +	// one clabwire process per node, with all of the node's interfaces in request order
5753: +	commands := clabwire.captureCommands()
5754: +	if len(commands) != 2 {
5755: +		t.Fatalf("capture processes = %d, want one per node: %v", len(commands), commands)
5756: +	}
5757: +	for _, command := range commands {
5758: +		node := flagValues(command, "--nodeName")[0]
5759: +		want := map[string][]string{"r1": {"e1-1", "e1-2"}, "r2": {"e1-1"}}[node]
5760: +		if got := flagValues(command, "--interface"); !slices.Equal(got, want) {
5761: +			t.Fatalf("%s interfaces = %v, want %v", node, got, want)
5762: +		}
5763: +		if !strings.HasSuffix(command[0], "/"+clabwireContainer) {
5764: +			t.Fatalf("capture ran in %s, want the clabwire container", command[0])
5765: +		}
5766: +	}
5767: +
5768: +	// every packet carries the merged ID of its interface
5769: +	wantOrigin := map[uint32]string{0: "r1:e1-1", 1: "r2:e1-1", 2: "r1:e1-2"}
5770: +	perInterface := map[uint32]int{}
5771: +	for _, packet := range parsed.packets {
5772: +		if packetOrigin(packet) != wantOrigin[packet.InterfaceID] {
5773: +			t.Fatalf("packet from %s has interface ID %d", packetOrigin(packet), packet.InterfaceID)
5774: +		}
5775: +		perInterface[packet.InterfaceID]++
5776: +	}
5777: +	for id := range uint32(3) {
5778: +		if perInterface[id] == 0 {
5779: +			t.Fatalf("no packets on %s: %v", wantNames[id], perInterface)
5780: +		}
5781: +	}
5782: +}
5783: +
5784: +// TestCaptureChainsSegmentsWithoutDuplicatesOrGaps runs captures longer than one segment: every
5785: +// tick must appear exactly once per interface, across every switch.
5786: +func TestCaptureChainsSegmentsWithoutDuplicatesOrGaps(t *testing.T) {
5787: +	t.Parallel()
5788: +
5789: +	r, clabwire := captureTestRuntime(t, 4*time.Millisecond)
5790: +	r.captureSegment = 300 * time.Millisecond
5791: +
5792: +	var gaps []clablabruntime.CaptureGap
5793: +	var out bytes.Buffer
5794: +	err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
5795: +		Name: "lab1",
5796: +		Targets: []clablabruntime.CaptureTarget{
5797: +			{Node: "r1", Interface: "e1-1"},
5798: +			{Node: "r1", Interface: "e1-2"},
5799: +		},
5800: +		Duration: 1300 * time.Millisecond,
5801: +		OnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },
5802: +	}, &out)
5803: +	if err != nil {
5804: +		t.Fatal(err)
5805: +	}
5806: +	if len(gaps) != 0 {
5807: +		t.Fatalf("gaps = %+v", gaps)
5808: +	}
5809: +	if processes := len(clabwire.captureCommands()); processes < 4 {
5810: +		t.Fatalf("capture processes = %d, want a chain of at least 4 segments", processes)
5811: +	}
5812: +
5813: +	parsed := parseCapture(t, out.Bytes())
5814: +	if parsed.sections != 1 || len(parsed.interfaces) != 2 {
5815: +		t.Fatalf("sections = %d, interfaces = %v; want the follow-up headers dropped",
5816: +			parsed.sections, parsed.interfaces)
5817: +	}
5818: +	for id := range uint32(2) {
5819: +		var sequence []uint64
5820: +		for _, packet := range parsed.packets {
5821: +			if packet.InterfaceID == id {
5822: +				sequence = append(sequence, packetSequence(packet))
5823: +			}
5824: +		}
5825: +		if len(sequence) < 200 {
5826: +			t.Fatalf("interface %d has %d packets", id, len(sequence))
5827: +		}
5828: +		slices.Sort(sequence)
5829: +		for idx := 1; idx < len(sequence); idx++ {
5830: +			switch {
5831: +			case sequence[idx] == sequence[idx-1]:
5832: +				t.Fatalf("interface %d: tick %d written twice", id, sequence[idx])
5833: +			case sequence[idx] != sequence[idx-1]+1:
5834: +				t.Fatalf(
5835: +					"interface %d: ticks %d to %d missing",
5836: +					id,
5837: +					sequence[idx-1]+1,
5838: +					sequence[idx]-1,
5839: +				)
5840: +			}
5841: +		}
5842: +	}
5843: +}
5844: +
5845: +func TestCaptureReportsAGapWhenTheFollowUpStartsLate(t *testing.T) {
5846: +	t.Parallel()
5847: +
5848: +	r, clabwire := captureTestRuntime(t, 5*time.Millisecond)
5849: +	r.captureSegment = 300 * time.Millisecond
5850: +	// the second process starts long after the first one ended
5851: +	clabwire.startDelay[1] = 400 * time.Millisecond
5852: +
5853: +	var gaps []clablabruntime.CaptureGap
5854: +	var out bytes.Buffer
5855: +	err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
5856: +		Name:     "lab1",
5857: +		Targets:  []clablabruntime.CaptureTarget{{Node: "r2", Interface: "e1-1"}},
5858: +		Duration: 800 * time.Millisecond,
5859: +		OnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },
5860: +	}, &out)
5861: +	if err != nil {
5862: +		t.Fatal(err)
5863: +	}
5864: +	if len(gaps) == 0 || gaps[0].Node != "r2" ||
5865: +		!slices.Equal(gaps[0].Interfaces, []string{"e1-1"}) ||
5866: +		gaps[0].From.IsZero() ||
5867: +		gaps[0].Reason == "" {
5868: +		t.Fatalf("gaps = %+v, want the late follow-up reported", gaps)
5869: +	}
5870: +	if !gaps[0].To.IsZero() && !gaps[0].To.After(gaps[0].From) {
5871: +		t.Fatalf("gap ends before it starts: %+v", gaps[0])
5872: +	}
5873: +	parseCapture(t, out.Bytes())
5874: +}
5875: +
5876: +func TestCaptureMapsDeniedAndFailedAuditsToErrors(t *testing.T) {
5877: +	t.Parallel()
5878: +
5879: +	for _, status := range []string{captureAuditDenied, captureAuditFailed} {
5880: +		r, clabwire := captureTestRuntime(t, time.Millisecond)
5881: +		clabwire.fail = status
5882: +
5883: +		var out bytes.Buffer
5884: +		err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
5885: +			Name:     "lab1",
5886: +			Targets:  []clablabruntime.CaptureTarget{{Node: "r2", Interface: "e1-1"}},
5887: +			Duration: time.Second,
5888: +		}, &out)
5889: +		if err == nil || !strings.Contains(err.Error(), "is not uniquely planned") ||
5890: +			!strings.Contains(err.Error(), "node r2") {
5891: +			t.Fatalf("%s: error = %v, want the audit reason", status, err)
5892: +		}
5893: +		if status == captureAuditDenied && !strings.Contains(err.Error(), "was denied") {
5894: +			t.Fatalf("Denied error = %v", err)
5895: +		}
5896: +		// the header is written before the capture starts, so the output stays a valid file
5897: +		parseCapture(t, out.Bytes())
5898: +	}
5899: +}
5900: +
5901: +func TestCaptureAuditLineWriter(t *testing.T) {
5902: +	t.Parallel()
5903: +
5904: +	var audits []*captureAudit
5905: +	writer := &auditLineWriter{send: func(audit *captureAudit) { audits = append(audits, audit) }}
5906: +	started := fmt.Sprintf(`{"schemaVersion":%q,"time":"2026-10-27T10:00:00.123456789Z",`+
5907: +		`"status":"Started","nodeName":"r1","interfaces":[{"name":"e1-1","id":"if1"}]}`,
5908: +		captureAuditSchema)
5909: +	// lines arrive split across writes
5910: +	_, _ = writer.Write([]byte(started[:20]))
5911: +	_, _ = writer.Write([]byte(started[20:] + "\nnot json\n{\"status\":\"Started\"}\n"))
5912: +	_, _ = writer.Write(
5913: +		[]byte(`{"schemaVersion":"` + captureAuditSchema + `","status":"Succeeded","packets":3}`),
5914: +	)
5915: +	writer.flush()
5916: +
5917: +	if len(audits) != 2 || audits[0].Status != captureAuditStarted || audits[1].Packets != 3 ||
5918: +		audits[0].Time.Nanosecond() != 123456789 || audits[0].Interfaces[0].Name != "e1-1" {
5919: +		t.Fatalf("audits = %+v", audits)
5920: +	}
5921: +	if writer.text() != `not json; {"status":"Started"}` {
5922: +		t.Fatalf("other stderr = %q", writer.text())
5923: +	}
5924: +
5925: +	err := captureAuditError("r1", &captureAudit{
5926: +		Status: captureAuditDenied, Reason: "nope",
5927: +		Interfaces: []struct {
5928: +			Name    string `json:"name"`
5929: +			ID      string `json:"id"`
5930: +			Packets int    `json:"packets"`
5931: +		}{{Name: "e1-1"}, {Name: "eth0"}},
5932: +	})
5933: +	if err.Error() != "capture of e1-1,eth0 on node r1 was denied by clabwire: nope" {
5934: +		t.Fatalf("audit error = %q", err)
5935: +	}
5936: +}
5937: +
5938: +func TestCaptureStopsAtThePacketLimit(t *testing.T) {
5939: +	t.Parallel()
5940: +
5941: +	r, clabwire := captureTestRuntime(t, 2*time.Millisecond)
5942: +	var out bytes.Buffer
5943: +	err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
5944: +		Name: "lab1",
5945: +		Targets: []clablabruntime.CaptureTarget{
5946: +			{Node: "r1", Interface: "e1-1"},
5947: +			{Node: "r2", Interface: "e1-1"},
5948: +		},
5949: +		PacketLimit: 7,
5950: +	}, &out)
5951: +	if err != nil {
5952: +		t.Fatal(err)
5953: +	}
5954: +	if got := len(parseCapture(t, out.Bytes()).packets); got != 7 {
5955: +		t.Fatalf("packets = %d, want 7", got)
5956: +	}
5957: +	// each clabwire process gets the limit that remained when it started
5958: +	for _, command := range clabwire.captureCommands() {
5959: +		limit := flagValues(command, "--packetLimit")
5960: +		if len(limit) != 1 || limit[0] < "1" || limit[0] > "7" || len(limit[0]) != 1 {
5961: +			t.Fatalf("clabwire packet limit = %v, want at most 7", limit)
5962: +		}
5963: +	}
5964: +}
5965: +
5966: +func TestCaptureEndsCleanlyWhenTheContextEnds(t *testing.T) {
5967: +	t.Parallel()
5968: +
5969: +	r, _ := captureTestRuntime(t, 2*time.Millisecond)
5970: +	ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
5971: +	defer cancel()
5972: +
5973: +	var out bytes.Buffer
5974: +	if err := r.Capture(ctx, clablabruntime.CaptureRequest{
5975: +		Name:    "lab1",
5976: +		Targets: []clablabruntime.CaptureTarget{{Node: "r1", Interface: "e1-1"}},
5977: +	}, &out); err != nil {
5978: +		t.Fatalf("Capture() after the context ended = %v, want nil", err)
5979: +	}
5980: +	if len(parseCapture(t, out.Bytes()).packets) == 0 {
5981: +		t.Fatal("no packets before the context ended")
5982: +	}
5983: +}
5984: +
5985: +func TestCaptureValidatesTargets(t *testing.T) {
5986: +	t.Parallel()
5987: +
5988: +	r, clabwire := captureTestRuntime(t, time.Millisecond)
5989: +	ctx := context.Background()
5990: +	cases := map[string]clablabruntime.CaptureRequest{
5991: +		"is not a capturable link interface; capturable: e1-1 (ethernet-1/1), e1-2": {
5992: +			Targets: []clablabruntime.CaptureTarget{{Node: "r1", Interface: "eth0"}},
5993: +		},
5994: +		"requested more than once": {
5995: +			Targets: []clablabruntime.CaptureTarget{
5996: +				{Node: "r1", Interface: "e1-1"}, {Node: "R1", Interface: "ethernet-1/1"},
5997: +			},
5998: +		},
5999: +		`node "missing" was not found`: {
6000: +			Targets: []clablabruntime.CaptureTarget{{Node: "missing", Interface: "e1-1"}},
6001: +		},
6002: +		"at least one capture target": {},
6003: +		"snap length 10 is outside": {
6004: +			Targets:    []clablabruntime.CaptureTarget{{Node: "r1", Interface: "e1-1"}},
6005: +			SnapLength: 10,
6006: +		},
6007: +		"duration must not be negative": {
6008: +			Targets:  []clablabruntime.CaptureTarget{{Node: "r1", Interface: "e1-1"}},
6009: +			Duration: -time.Second,
6010: +		},
6011: +	}
6012: +	for want, req := range cases {
6013: +		req.Name = "lab1"
6014: +		err := r.Capture(ctx, req, io.Discard)
6015: +		if err == nil || !strings.Contains(err.Error(), want) {
6016: +			t.Errorf("error = %v, want %q", err, want)
6017: +		}
6018: +	}
6019: +	if commands := clabwire.captureCommands(); len(commands) != 0 {
6020: +		t.Fatalf("invalid requests started captures: %v", commands)
6021: +	}
6022: +}
6023: +
6024: +func TestInspectInterfacesReportsStateFromSysfs(t *testing.T) {
6025: +	t.Parallel()
6026: +
6027: +	r, clabwire := captureTestRuntime(t, time.Millisecond)
6028: +	clabwire.sysfs = "Inter-|   Receive\n face |bytes\n" + interfaceSysfsMarker + "\n" +
6029: +		"e1-1\t12\t9500\taa:c1:ab:00:00:01\tup\t0x1003\t\n" +
6030: +		"e1-2\t13\t1500\taa:c1:ab:00:00:02\tlowerlayerdown\t0x1003\t\n"
6031: +
6032: +	interfaces, err := r.InspectInterfaces(context.Background(), clablabruntime.NodeRequest{
6033: +		Name: "lab1", Nodes: []string{"R1"},
6034: +	})
6035: +	if err != nil {
6036: +		t.Fatal(err)
6037: +	}
6038: +	if len(interfaces) != 1 || interfaces[0].ContainerName != "lab1-r1" ||
6039: +		len(interfaces[0].Interfaces) != 2 {
6040: +		t.Fatalf("interfaces = %+v", interfaces)
6041: +	}
6042: +	first := interfaces[0].Interfaces[0]
6043: +	if first.InterfaceName != "e1-1" || first.InterfaceAlias != "ethernet-1/1" ||
6044: +		first.InterfaceMAC != "aa:c1:ab:00:00:01" || first.InterfaceIndex != 12 ||
6045: +		first.InterfaceMTU != 9500 || first.InterfaceState != "up" {
6046: +		t.Fatalf("e1-1 = %+v", first)
6047: +	}
6048: +	if second := interfaces[0].Interfaces[1]; second.InterfaceState != "lowerlayerdown" {
6049: +		t.Fatalf("e1-2 = %+v", second)
6050: +	}
6051: +}
6052: +
6053: +// TestCaptureClosesStdinWhenItEnds ends every clabwire process through its stdin, whether the
6054: +// caller cancels the capture or the output fails, so no capture is left running in the pod.
6055: +// TestCaptureWritesWhatItReadWhenTheContextEnds stops a capture while the output is slow and
6056: +// the chains have packets queued: every packet clabwire wrote before it ended is in the file.
6057: +func TestCaptureWritesWhatItReadWhenTheContextEnds(t *testing.T) {
6058: +	t.Parallel()
6059: +
6060: +	r, clabwire := captureTestRuntime(t, time.Millisecond)
6061: +	// without a reorder window, a blocked output blocks the chains
6062: +	r.captureReorderWindow = -1
6063: +	ctx, cancel := context.WithCancel(context.Background())
6064: +	defer cancel()
6065: +
6066: +	out := &gatedWriter{open: make(chan struct{})}
6067: +	go func() {
6068: +		time.Sleep(50 * time.Millisecond)
6069: +		out.block()
6070: +		// the segments keep reading while the chains wait for the output
6071: +		time.Sleep(400 * time.Millisecond)
6072: +		cancel()
6073: +		close(out.open)
6074: +	}()
6075: +

(Showing lines 5376-6075 of 7018. Use offset=6076 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19653f64a001HmikXdWhPyk6As",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653ed5a001JQ2uENCIAXE6MW",
  "callID": "call_df5cfd7d40cb4d80a3c220e1",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 700,
      "offset": 5376
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n5376: +\t\t{\n5377: +\t\t\tNode:          \"r2\",\n5378: +\t\t\tInterface:     \"e1-1\",\n5379: +\t\t\tAlias:         \"ethernet-1/1\",\n5380: +\t\t\tPeerNode:      \"r1\",\n5381: +\t\t\tPeerInterface: \"ethernet-1/1\",\n5382: +\t\t},\n5383: +\t},\n5384: +}\n5385: +\n5386: +// fakeClabwire plays clabwire packet-capture and --list-interfaces in the fake pod exec. Every\n5387: +// capture process sees the same traffic: one packet per tick on each requested interface,\n5388: +// carrying the tick number, stamped with the tick time plus a per-process jitter (clabwire stamps\n5389: +// packets when it reads them).\n5390: +type fakeClabwire struct {\n5391: +\tt     *testing.T\n5392: +\tepoch time.Time\n5393: +\ttick  time.Duration\n5394: +\n5395: +\tmu       sync.Mutex\n5396: +\tcommands [][]string\n5397: +\t// processes counts the capture processes started per node\n5398: +\tprocesses map[string]int\n5399: +\n5400: +\t// startDelay delays the Started record of the given process index (all nodes).\n5401: +\tstartDelay map[int]time.Duration\n5402: +\t// firstStartDelay delays the Started record of a node's first process.\n5403: +\tfirstStartDelay map[string]time.Duration\n5404: +\t// fail makes a process write this audit status and exit 1.\n5405: +\tfail string\n5406: +\t// stderrOnly makes a process write this text to stderr and exit 1, like a clabwire that\n5407: +\t// rejects a flag.\n5408: +\tstderrOnly string\n5409: +\t// stampSkew stamps the packets of a node this much earlier, as if its stream reached\n5410: +\t// containerlab this much later than the others.\n5411: +\tstampSkew map[string]time.Duration\n5412: +\t// stdinClosed counts the processes that ended because their stdin closed, per node.\n5413: +\tstdinClosed map[string]int\n5414: +\t// written counts the packets written to stdout, per node.\n5415: +\twritten map[string]int\n5416: +\t// sysfs is the device container's interface sample.\n5417: +\tsysfs string\n5418: +}\n5419: +\n5420: +func newFakeClabwire(t *testing.T, tick time.Duration) *fakeClabwire {\n5421: +\tt.Helper()\n5422: +\n5423: +\treturn &fakeClabwire{\n5424: +\t\tt: t, epoch: time.Now(), tick: tick, processes: map[string]int{},\n5425: +\t\tstartDelay: map[int]time.Duration{}, stampSkew: map[string]time.Duration{},\n5426: +\t\tfirstStartDelay: map[string]time.Duration{},\n5427: +\t\tstdinClosed:     map[string]int{},\n5428: +\t\twritten:         map[string]int{},\n5429: +\t}\n5430: +}\n5431: +\n5432: +func (f *fakeClabwire) exec(\n5433: +\tctx context.Context,\n5434: +\tnamespace, pod, container string,\n5435: +\tcommand []string,\n5436: +\tstdin io.Reader,\n5437: +\tstdout, stderr io.Writer,\n5438: +) error {\n5439: +\tf.mu.Lock()\n5440: +\tf.commands = append(\n5441: +\t\tf.commands,\n5442: +\t\tappend([]string{namespace + \"/\" + pod + \"/\" + container}, command...),\n5443: +\t)\n5444: +\tf.mu.Unlock()\n5445: +\n5446: +\tif container != clabwireContainer {\n5447: +\t\t_, _ = io.WriteString(stdout, f.sysfs)\n5448: +\t\treturn nil\n5449: +\t}\n5450: +\tif slices.Contains(command, \"--list-interfaces\") {\n5451: +\t\treturn json.NewEncoder(stdout).Encode(captureListing[pod])\n5452: +\t}\n5453: +\n5454: +\treturn f.capture(ctx, command, stdin, stdout, stderr)\n5455: +}\n5456: +\n5457: +func flagValues(command []string, name string) []string {\n5458: +\tvar values []string\n5459: +\tfor idx := 0; idx+1 < len(command); idx++ {\n5460: +\t\tif command[idx] == name {\n5461: +\t\t\tvalues = append(values, command[idx+1])\n5462: +\t\t}\n5463: +\t}\n5464: +\n5465: +\treturn values\n5466: +}\n5467: +\n5468: +func (f *fakeClabwire) audit(\n5469: +\tstderr io.Writer,\n5470: +\tstatus, node string,\n5471: +\tinterfaces []string,\n5472: +\treason string,\n5473: +) {\n5474: +\trecord := map[string]any{\n5475: +\t\t\"schemaVersion\": captureAuditSchema, \"time\": time.Now().UTC(), \"operation\": \"PacketCapture\",\n5476: +\t\t\"status\": status, \"nodeName\": node, \"format\": \"pcapng\", \"reason\": reason,\n5477: +\t}\n5478: +\tentries := []map[string]any{}\n5479: +\tfor _, name := range interfaces {\n5480: +\t\tentries = append(entries, map[string]any{\"name\": name})\n5481: +\t}\n5482: +\trecord[\"interfaces\"] = entries\n5483: +\tdata, _ := json.Marshal(record)\n5484: +\t_, _ = stderr.Write(append(data, '\\n'))\n5485: +}\n5486: +\n5487: +func (f *fakeClabwire) capture(\n5488: +\tctx context.Context,\n5489: +\tcommand []string,\n5490: +\tstdin io.Reader,\n5491: +\tstdout, stderr io.Writer,\n5492: +) error {\n5493: +\tf.mu.Lock()\n5494: +\trejected := f.stderrOnly\n5495: +\tf.mu.Unlock()\n5496: +\tif rejected != \"\" {\n5497: +\t\t_, _ = io.WriteString(stdout, \"Incorrect Usage: \"+rejected+\"\\n\\nNAME:\\n   manager\\n\")\n5498: +\t\t_, _ = io.WriteString(stderr, rejected+\"\\n\")\n5499: +\t\treturn &clablabruntime.CommandExitError{Code: 1}\n5500: +\t}\n5501: +\n5502: +\t// clabwire ends the capture when stdin closes (--stop-on-stdin-close)\n5503: +\tif !slices.Contains(command, clabwireStopOnStdinClose) || stdin == nil {\n5504: +\t\tf.t.Errorf(\"capture without stdin and %s: %v\", clabwireStopOnStdinClose, command)\n5505: +\t\treturn fmt.Errorf(\"no stdin\")\n5506: +\t}\n5507: +\tstdinClosed := make(chan struct{})\n5508: +\tgo func() {\n5509: +\t\t_, _ = io.Copy(io.Discard, stdin)\n5510: +\t\tclose(stdinClosed)\n5511: +\t}()\n5512: +\n5513: +\tnode := flagValues(command, \"--nodeName\")[0]\n5514: +\tinterfaces := flagValues(command, \"--interface\")\n5515: +\tduration, err := time.ParseDuration(flagValues(command, \"--duration\")[0])\n5516: +\tif err != nil {\n5517: +\t\tf.t.Errorf(\"duration: %v\", err)\n5518: +\t}\n5519: +\tif !slices.Equal(flagValues(command, \"--format\"), []string{\"pcapng\"}) {\n5520: +\t\tf.t.Errorf(\"capture without --format pcapng: %v\", command)\n5521: +\t}\n5522: +\n5523: +\tf.mu.Lock()\n5524: +\tindex := f.processes[node]\n5525: +\tf.processes[node]++\n5526: +\tdelay := f.startDelay[index]\n5527: +\tif index == 0 {\n5528: +\t\tdelay += f.firstStartDelay[node]\n5529: +\t}\n5530: +\tfailure := f.fail\n5531: +\tskew := f.stampSkew[node]\n5532: +\tf.mu.Unlock()\n5533: +\n5534: +\tif failure != \"\" {\n5535: +\t\tf.audit(stderr, failure, node, interfaces, \"interface \\\"eth9\\\" is not uniquely planned\")\n5536: +\t\treturn &clablabruntime.CommandExitError{Code: 1}\n5537: +\t}\n5538: +\n5539: +\tselect {\n5540: +\tcase <-time.After(delay):\n5541: +\tcase <-ctx.Done():\n5542: +\t\treturn ctx.Err()\n5543: +\tcase <-stdinClosed:\n5544: +\t\tf.audit(stderr, captureAuditStarted, node, interfaces, \"\")\n5545: +\t\tf.audit(stderr, captureAuditSucceeded, node, interfaces, \"client closed: stdin reached EOF\")\n5546: +\t\treturn nil\n5547: +\t}\n5548: +\n5549: +\twriter := clabcapture.NewWriter(stdout)\n5550: +\tf.audit(stderr, captureAuditStarted, node, interfaces, \"\")\n5551: +\tif err := writer.WriteHeader(interfaces, clabcapture.DefaultSnapLength); err != nil {\n5552: +\t\treturn err\n5553: +\t}\n5554: +\n5555: +\t// clabwire's own section header names it\n5556: +\tend := time.Now().Add(duration)\n5557: +\tjitter := time.Duration(index%3) * 7 * time.Microsecond\n5558: +\tnext := time.Now().Sub(f.epoch)/f.tick + 1\n5559: +\tfor {\n5560: +\t\tat := f.epoch.Add(next * f.tick)\n5561: +\t\tif at.After(end) {\n5562: +\t\t\tbreak\n5563: +\t\t}\n5564: +\t\tselect {\n5565: +\t\tcase <-ctx.Done():\n5566: +\t\t\treturn ctx.Err()\n5567: +\t\tcase <-stdinClosed:\n5568: +\t\t\tf.mu.Lock()\n5569: +\t\t\tf.stdinClosed[node]++\n5570: +\t\t\tf.mu.Unlock()\n5571: +\t\t\tf.audit(\n5572: +\t\t\t\tstderr,\n5573: +\t\t\t\tcaptureAuditSucceeded,\n5574: +\t\t\t\tnode,\n5575: +\t\t\t\tinterfaces,\n5576: +\t\t\t\t\"client closed: stdin reached EOF\",\n5577: +\t\t\t)\n5578: +\t\t\treturn nil\n5579: +\t\tcase <-time.After(time.Until(at)):\n5580: +\t\t}\n5581: +\t\tfor id := range interfaces {\n5582: +\t\t\tdata := make([]byte, 64)\n5583: +\t\t\tbinary.BigEndian.PutUint64(data[0:], uint64(next))\n5584: +\t\t\tcopy(data[8:], node+\":\"+interfaces[id])\n5585: +\t\t\tif err := writer.WritePacket(uint32(id), &clabcapture.Packet{ //nolint:gosec // small\n5586: +\t\t\t\tTimestamp: at.Add(jitter - skew).UnixNano(), OriginalLength: 64, Data: data,\n5587: +\t\t\t}); err != nil {\n5588: +\t\t\t\treturn err\n5589: +\t\t\t}\n5590: +\t\t\tf.mu.Lock()\n5591: +\t\t\tf.written[node]++\n5592: +\t\t\tf.mu.Unlock()\n5593: +\t\t}\n5594: +\t\tnext++\n5595: +\t}\n5596: +\tf.audit(stderr, captureAuditSucceeded, node, interfaces, \"\")\n5597: +\n5598: +\treturn nil\n5599: +}\n5600: +\n5601: +func (f *fakeClabwire) captureCommands() [][]string {\n5602: +\tf.mu.Lock()\n5603: +\tdefer f.mu.Unlock()\n5604: +\n5605: +\tvar result [][]string\n5606: +\tfor _, command := range f.commands {\n5607: +\t\tif slices.Contains(command, \"packet-capture\") &&\n5608: +\t\t\t!slices.Contains(command, \"--list-interfaces\") {\n5609: +\t\t\tresult = append(result, command)\n5610: +\t\t}\n5611: +\t}\n5612: +\n5613: +\treturn result\n5614: +}\n5615: +\n5616: +// captureTestRuntime is lab1 in lab-ns with nodes r1 (topology name R1) and r2, each in its\n5617: +// own pod, and a fake clabwire.\n5618: +func captureTestRuntime(t *testing.T, tick time.Duration) (*Runtime, *fakeClabwire) {\n5619: +\tt.Helper()\n5620: +\n5621: +\tr := newTestRuntimeWithKubeObjects(\n5622: +\t\t[]*unstructured.Unstructured{\n5623: +\t\t\tcaptureTestNode(\"r1\", \"R1\", \"node-r1-x\"),\n5624: +\t\t\tcaptureTestNode(\"r2\", \"\", \"node-r2-x\"),\n5625: +\t\t},\n5626: +\t\t[]k8sruntime.Object{\n5627: +\t\t\tcaptureTestPod(\"lab1-r1-abc\", \"r1\"),\n5628: +\t\t\tcaptureTestPod(\"lab1-r2-def\", \"r2\"),\n5629: +\t\t},\n5630: +\t)\n5631: +\tr.labNamespaceOverride = \"lab-ns\"\n5632: +\tclabwire := newFakeClabwire(t, tick)\n5633: +\tr.podExec = clabwire.exec\n5634: +\n5635: +\treturn r, clabwire\n5636: +}\n5637: +\n5638: +// parsedCapture is a pcapng stream read back.\n5639: +type parsedCapture struct {\n5640: +\tsections   int\n5641: +\tinterfaces []string\n5642: +\tpackets    []clabcapture.Packet\n5643: +}\n5644: +\n5645: +func parseCapture(t *testing.T, data []byte) parsedCapture {\n5646: +\tt.Helper()\n5647: +\n5648: +\treader := clabcapture.NewReader(bytes.NewReader(data))\n5649: +\tvar parsed parsedCapture\n5650: +\tfor {\n5651: +\t\tevent, err := reader.Next()\n5652: +\t\tif errors.Is(err, io.EOF) {\n5653: +\t\t\tbreak\n5654: +\t\t}\n5655: +\t\tif err != nil {\n5656: +\t\t\tt.Fatalf(\"invalid capture: %v\", err)\n5657: +\t\t}\n5658: +\t\tif event.Interface != nil {\n5659: +\t\t\tif len(parsed.packets) != 0 {\n5660: +\t\t\t\tt.Fatal(\"interface description after the first packet\")\n5661: +\t\t\t}\n5662: +\t\t\tif event.Interface.TSResol != 9 /* nanoseconds */ {\n5663: +\t\t\t\tt.Fatalf(\"interface %s tsresol = %d\", event.Interface.Name, event.Interface.TSResol)\n5664: +\t\t\t}\n5665: +\t\t\tparsed.interfaces = append(parsed.interfaces, event.Interface.Name)\n5666: +\t\t}\n5667: +\t\tif event.Packet != nil {\n5668: +\t\t\tparsed.packets = append(parsed.packets, *event.Packet)\n5669: +\t\t}\n5670: +\t}\n5671: +\tparsed.sections = reader.Sections()\n5672: +\n5673: +\treturn parsed\n5674: +}\n5675: +\n5676: +func packetSequence(packet clabcapture.Packet) uint64 {\n5677: +\treturn binary.BigEndian.Uint64(packet.Data[0:8])\n5678: +}\n5679: +\n5680: +func packetOrigin(packet clabcapture.Packet) string {\n5681: +\treturn strings.TrimRight(string(packet.Data[8:]), \"\\x00\")\n5682: +}\n5683: +\n5684: +func TestCaptureInterfacesUsesTopologyNames(t *testing.T) {\n5685: +\tt.Parallel()\n5686: +\n5687: +\tr, _ := captureTestRuntime(t, time.Millisecond)\n5688: +\tinterfaces, err := r.CaptureInterfaces(\n5689: +\t\tcontext.Background(),\n5690: +\t\tclablabruntime.NodeRequest{Name: \"lab1\"},\n5691: +\t)\n5692: +\tif err != nil {\n5693: +\t\tt.Fatal(err)\n5694: +\t}\n5695: +\twant := []clablabruntime.CaptureInterface{\n5696: +\t\t{\n5697: +\t\t\tNode:          \"R1\",\n5698: +\t\t\tInterface:     \"e1-1\",\n5699: +\t\t\tAlias:         \"ethernet-1/1\",\n5700: +\t\t\tPeerNode:      \"r2\",\n5701: +\t\t\tPeerInterface: \"ethernet-1/1\",\n5702: +\t\t},\n5703: +\t\t{Node: \"R1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"r1-e1-2\"},\n5704: +\t\t{\n5705: +\t\t\tNode:          \"r2\",\n5706: +\t\t\tInterface:     \"e1-1\",\n5707: +\t\t\tAlias:         \"ethernet-1/1\",\n5708: +\t\t\tPeerNode:      \"R1\",\n5709: +\t\t\tPeerInterface: \"ethernet-1/1\",\n5710: +\t\t},\n5711: +\t}\n5712: +\tif !slices.Equal(interfaces, want) {\n5713: +\t\tt.Fatalf(\"interfaces = %+v\\nwant %+v\", interfaces, want)\n5714: +\t}\n5715: +\n5716: +\tone, err := r.CaptureInterfaces(context.Background(), clablabruntime.NodeRequest{\n5717: +\t\tName: \"lab1\", Nodes: []string{\"r2\"},\n5718: +\t})\n5719: +\tif err != nil || len(one) != 1 || one[0].Node != \"r2\" {\n5720: +\t\tt.Fatalf(\"r2 interfaces = %+v, %v\", one, err)\n5721: +\t}\n5722: +}\n5723: +\n5724: +func TestCaptureMergesNodesIntoOneSection(t *testing.T) {\n5725: +\tt.Parallel()\n5726: +\n5727: +\tr, clabwire := captureTestRuntime(t, 10*time.Millisecond)\n5728: +\tvar out bytes.Buffer\n5729: +\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n5730: +\t\tName: \"lab1\",\n5731: +\t\t// the topology name of r1, an alias, and a second node between two r1 interfaces\n5732: +\t\tTargets: []clablabruntime.CaptureTarget{\n5733: +\t\t\t{Node: \"R1\", Interface: \"ethernet-1/1\"},\n5734: +\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n5735: +\t\t\t{Node: \"r1\", Interface: \"e1-2\"},\n5736: +\t\t},\n5737: +\t\tDuration: 300 * time.Millisecond,\n5738: +\t}, &out)\n5739: +\tif err != nil {\n5740: +\t\tt.Fatal(err)\n5741: +\t}\n5742: +\n5743: +\tparsed := parseCapture(t, out.Bytes())\n5744: +\tif parsed.sections != 1 {\n5745: +\t\tt.Fatalf(\"sections = %d, want one merged section\", parsed.sections)\n5746: +\t}\n5747: +\twantNames := []string{\"R1:e1-1\", \"r2:e1-1\", \"R1:e1-2\"}\n5748: +\tif !slices.Equal(parsed.interfaces, wantNames) {\n5749: +\t\tt.Fatalf(\"interfaces = %v, want %v\", parsed.interfaces, wantNames)\n5750: +\t}\n5751: +\n5752: +\t// one clabwire process per node, with all of the node's interfaces in request order\n5753: +\tcommands := clabwire.captureCommands()\n5754: +\tif len(commands) != 2 {\n5755: +\t\tt.Fatalf(\"capture processes = %d, want one per node: %v\", len(commands), commands)\n5756: +\t}\n5757: +\tfor _, command := range commands {\n5758: +\t\tnode := flagValues(command, \"--nodeName\")[0]\n5759: +\t\twant := map[string][]string{\"r1\": {\"e1-1\", \"e1-2\"}, \"r2\": {\"e1-1\"}}[node]\n5760: +\t\tif got := flagValues(command, \"--interface\"); !slices.Equal(got, want) {\n5761: +\t\t\tt.Fatalf(\"%s interfaces = %v, want %v\", node, got, want)\n5762: +\t\t}\n5763: +\t\tif !strings.HasSuffix(command[0], \"/\"+clabwireContainer) {\n5764: +\t\t\tt.Fatalf(\"capture ran in %s, want the clabwire container\", command[0])\n5765: +\t\t}\n5766: +\t}\n5767: +\n5768: +\t// every packet carries the merged ID of its interface\n5769: +\twantOrigin := map[uint32]string{0: \"r1:e1-1\", 1: \"r2:e1-1\", 2: \"r1:e1-2\"}\n5770: +\tperInterface := map[uint32]int{}\n5771: +\tfor _, packet := range parsed.packets {\n5772: +\t\tif packetOrigin(packet) != wantOrigin[packet.InterfaceID] {\n5773: +\t\t\tt.Fatalf(\"packet from %s has interface ID %d\", packetOrigin(packet), packet.InterfaceID)\n5774: +\t\t}\n5775: +\t\tperInterface[packet.InterfaceID]++\n5776: +\t}\n5777: +\tfor id := range uint32(3) {\n5778: +\t\tif perInterface[id] == 0 {\n5779: +\t\t\tt.Fatalf(\"no packets on %s: %v\", wantNames[id], perInterface)\n5780: +\t\t}\n5781: +\t}\n5782: +}\n5783: +\n5784: +// TestCaptureChainsSegmentsWithoutDuplicatesOrGaps runs captures longer than one segment: every\n5785: +// tick must appear exactly once per interface, across every switch.\n5786: +func TestCaptureChainsSegmentsWithoutDuplicatesOrGaps(t *testing.T) {\n5787: +\tt.Parallel()\n5788: +\n5789: +\tr, clabwire := captureTestRuntime(t, 4*time.Millisecond)\n5790: +\tr.captureSegment = 300 * time.Millisecond\n5791: +\n5792: +\tvar gaps []clablabruntime.CaptureGap\n5793: +\tvar out bytes.Buffer\n5794: +\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n5795: +\t\tName: \"lab1\",\n5796: +\t\tTargets: []clablabruntime.CaptureTarget{\n5797: +\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n5798: +\t\t\t{Node: \"r1\", Interface: \"e1-2\"},\n5799: +\t\t},\n5800: +\t\tDuration: 1300 * time.Millisecond,\n5801: +\t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n5802: +\t}, &out)\n5803: +\tif err != nil {\n5804: +\t\tt.Fatal(err)\n5805: +\t}\n5806: +\tif len(gaps) != 0 {\n5807: +\t\tt.Fatalf(\"gaps = %+v\", gaps)\n5808: +\t}\n5809: +\tif processes := len(clabwire.captureCommands()); processes < 4 {\n5810: +\t\tt.Fatalf(\"capture processes = %d, want a chain of at least 4 segments\", processes)\n5811: +\t}\n5812: +\n5813: +\tparsed := parseCapture(t, out.Bytes())\n5814: +\tif parsed.sections != 1 || len(parsed.interfaces) != 2 {\n5815: +\t\tt.Fatalf(\"sections = %d, interfaces = %v; want the follow-up headers dropped\",\n5816: +\t\t\tparsed.sections, parsed.interfaces)\n5817: +\t}\n5818: +\tfor id := range uint32(2) {\n5819: +\t\tvar sequence []uint64\n5820: +\t\tfor _, packet := range parsed.packets {\n5821: +\t\t\tif packet.InterfaceID == id {\n5822: +\t\t\t\tsequence = append(sequence, packetSequence(packet))\n5823: +\t\t\t}\n5824: +\t\t}\n5825: +\t\tif len(sequence) < 200 {\n5826: +\t\t\tt.Fatalf(\"interface %d has %d packets\", id, len(sequence))\n5827: +\t\t}\n5828: +\t\tslices.Sort(sequence)\n5829: +\t\tfor idx := 1; idx < len(sequence); idx++ {\n5830: +\t\t\tswitch {\n5831: +\t\t\tcase sequence[idx] == sequence[idx-1]:\n5832: +\t\t\t\tt.Fatalf(\"interface %d: tick %d written twice\", id, sequence[idx])\n5833: +\t\t\tcase sequence[idx] != sequence[idx-1]+1:\n5834: +\t\t\t\tt.Fatalf(\n5835: +\t\t\t\t\t\"interface %d: ticks %d to %d missing\",\n5836: +\t\t\t\t\tid,\n5837: +\t\t\t\t\tsequence[idx-1]+1,\n5838: +\t\t\t\t\tsequence[idx]-1,\n5839: +\t\t\t\t)\n5840: +\t\t\t}\n5841: +\t\t}\n5842: +\t}\n5843: +}\n5844: +\n5845: +func TestCaptureReportsAGapWhenTheFollowUpStartsLate(t *testing.T) {\n5846: +\tt.Parallel()\n5847: +\n5848: +\tr, clabwire := captureTestRuntime(t, 5*time.Millisecond)\n5849: +\tr.captureSegment = 300 * time.Millisecond\n5850: +\t// the second process starts long after the first one ended\n5851: +\tclabwire.startDelay[1] = 400 * time.Millisecond\n5852: +\n5853: +\tvar gaps []clablabruntime.CaptureGap\n5854: +\tvar out bytes.Buffer\n5855: +\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n5856: +\t\tName:     \"lab1\",\n5857: +\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"r2\", Interface: \"e1-1\"}},\n5858: +\t\tDuration: 800 * time.Millisecond,\n5859: +\t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n5860: +\t}, &out)\n5861: +\tif err != nil {\n5862: +\t\tt.Fatal(err)\n5863: +\t}\n5864: +\tif len(gaps) == 0 || gaps[0].Node != \"r2\" ||\n5865: +\t\t!slices.Equal(gaps[0].Interfaces, []string{\"e1-1\"}) ||\n5866: +\t\tgaps[0].From.IsZero() ||\n5867: +\t\tgaps[0].Reason == \"\" {\n5868: +\t\tt.Fatalf(\"gaps = %+v, want the late follow-up reported\", gaps)\n5869: +\t}\n5870: +\tif !gaps[0].To.IsZero() && !gaps[0].To.After(gaps[0].From) {\n5871: +\t\tt.Fatalf(\"gap ends before it starts: %+v\", gaps[0])\n5872: +\t}\n5873: +\tparseCapture(t, out.Bytes())\n5874: +}\n5875: +\n5876: +func TestCaptureMapsDeniedAndFailedAuditsToErrors(t *testing.T) {\n5877: +\tt.Parallel()\n5878: +\n5879: +\tfor _, status := range []string{captureAuditDenied, captureAuditFailed} {\n5880: +\t\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n5881: +\t\tclabwire.fail = status\n5882: +\n5883: +\t\tvar out bytes.Buffer\n5884: +\t\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n5885: +\t\t\tName:     \"lab1\",\n5886: +\t\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"r2\", Interface: \"e1-1\"}},\n5887: +\t\t\tDuration: time.Second,\n5888: +\t\t}, &out)\n5889: +\t\tif err == nil || !strings.Contains(err.Error(), \"is not uniquely planned\") ||\n5890: +\t\t\t!strings.Contains(err.Error(), \"node r2\") {\n5891: +\t\t\tt.Fatalf(\"%s: error = %v, want the audit reason\", status, err)\n5892: +\t\t}\n5893: +\t\tif status == captureAuditDenied && !strings.Contains(err.Error(), \"was denied\") {\n5894: +\t\t\tt.Fatalf(\"Denied error = %v\", err)\n5895: +\t\t}\n5896: +\t\t// the header is written before the capture starts, so the output stays a valid file\n5897: +\t\tparseCapture(t, out.Bytes())\n5898: +\t}\n5899: +}\n5900: +\n5901: +func TestCaptureAuditLineWriter(t *testing.T) {\n5902: +\tt.Parallel()\n5903: +\n5904: +\tvar audits []*captureAudit\n5905: +\twriter := &auditLineWriter{send: func(audit *captureAudit) { audits = append(audits, audit) }}\n5906: +\tstarted := fmt.Sprintf(`{\"schemaVersion\":%q,\"time\":\"2026-10-27T10:00:00.123456789Z\",`+\n5907: +\t\t`\"status\":\"Started\",\"nodeName\":\"r1\",\"interfaces\":[{\"name\":\"e1-1\",\"id\":\"if1\"}]}`,\n5908: +\t\tcaptureAuditSchema)\n5909: +\t// lines arrive split across writes\n5910: +\t_, _ = writer.Write([]byte(started[:20]))\n5911: +\t_, _ = writer.Write([]byte(started[20:] + \"\\nnot json\\n{\\\"status\\\":\\\"Started\\\"}\\n\"))\n5912: +\t_, _ = writer.Write(\n5913: +\t\t[]byte(`{\"schemaVersion\":\"` + captureAuditSchema + `\",\"status\":\"Succeeded\",\"packets\":3}`),\n5914: +\t)\n5915: +\twriter.flush()\n5916: +\n5917: +\tif len(audits) != 2 || audits[0].Status != captureAuditStarted || audits[1].Packets != 3 ||\n5918: +\t\taudits[0].Time.Nanosecond() != 123456789 || audits[0].Interfaces[0].Name != \"e1-1\" {\n5919: +\t\tt.Fatalf(\"audits = %+v\", audits)\n5920: +\t}\n5921: +\tif writer.text() != `not json; {\"status\":\"Started\"}` {\n5922: +\t\tt.Fatalf(\"other stderr = %q\", writer.text())\n5923: +\t}\n5924: +\n5925: +\terr := captureAuditError(\"r1\", &captureAudit{\n5926: +\t\tStatus: captureAuditDenied, Reason: \"nope\",\n5927: +\t\tInterfaces: []struct {\n5928: +\t\t\tName    string `json:\"name\"`\n5929: +\t\t\tID      string `json:\"id\"`\n5930: +\t\t\tPackets int    `json:\"packets\"`\n5931: +\t\t}{{Name: \"e1-1\"}, {Name: \"eth0\"}},\n5932: +\t})\n5933: +\tif err.Error() != \"capture of e1-1,eth0 on node r1 was denied by clabwire: nope\" {\n5934: +\t\tt.Fatalf(\"audit error = %q\", err)\n5935: +\t}\n5936: +}\n5937: +\n5938: +func TestCaptureStopsAtThePacketLimit(t *testing.T) {\n5939: +\tt.Parallel()\n5940: +\n5941: +\tr, clabwire := captureTestRuntime(t, 2*time.Millisecond)\n5942: +\tvar out bytes.Buffer\n5943: +\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n5944: +\t\tName: \"lab1\",\n5945: +\t\tTargets: []clablabruntime.CaptureTarget{\n5946: +\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n5947: +\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n5948: +\t\t},\n5949: +\t\tPacketLimit: 7,\n5950: +\t}, &out)\n5951: +\tif err != nil {\n5952: +\t\tt.Fatal(err)\n5953: +\t}\n5954: +\tif got := len(parseCapture(t, out.Bytes()).packets); got != 7 {\n5955: +\t\tt.Fatalf(\"packets = %d, want 7\", got)\n5956: +\t}\n5957: +\t// each clabwire process gets the limit that remained when it started\n5958: +\tfor _, command := range clabwire.captureCommands() {\n5959: +\t\tlimit := flagValues(command, \"--packetLimit\")\n5960: +\t\tif len(limit) != 1 || limit[0] < \"1\" || limit[0] > \"7\" || len(limit[0]) != 1 {\n5961: +\t\t\tt.Fatalf(\"clabwire packet limit = %v, want at most 7\", limit)\n5962: +\t\t}\n5963: +\t}\n5964: +}\n5965: +\n5966: +func TestCaptureEndsCleanlyWhenTheContextEnds(t *testing.T) {\n5967: +\tt.Parallel()\n5968: +\n5969: +\tr, _ := captureTestRuntime(t, 2*time.Millisecond)\n5970: +\tctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)\n5971: +\tdefer cancel()\n5972: +\n5973: +\tvar out bytes.Buffer\n5974: +\tif err := r.Capture(ctx, clablabruntime.CaptureRequest{\n5975: +\t\tName:    \"lab1\",\n5976: +\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"e1-1\"}},\n5977: +\t}, &out); err != nil {\n5978: +\t\tt.Fatalf(\"Capture() after the context ended = %v, want nil\", err)\n5979: +\t}\n5980: +\tif len(parseCapture(t, out.Bytes()).packets) == 0 {\n5981: +\t\tt.Fatal(\"no packets before the context ended\")\n5982: +\t}\n5983: +}\n5984: +\n5985: +func TestCaptureValidatesTargets(t *testing.T) {\n5986: +\tt.Parallel()\n5987: +\n5988: +\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n5989: +\tctx := context.Background()\n5990: +\tcases := map[string]clablabruntime.CaptureRequest{\n5991: +\t\t\"is not a capturable link interface; capturable: e1-1 (ethernet-1/1), e1-2\": {\n5992: +\t\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth0\"}},\n5993: +\t\t},\n5994: +\t\t\"requested more than once\": {\n5995: +\t\t\tTargets: []clablabruntime.CaptureTarget{\n5996: +\t\t\t\t{Node: \"r1\", Interface: \"e1-1\"}, {Node: \"R1\", Interface: \"ethernet-1/1\"},\n5997: +\t\t\t},\n5998: +\t\t},\n5999: +\t\t`node \"missing\" was not found`: {\n6000: +\t\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"missing\", Interface: \"e1-1\"}},\n6001: +\t\t},\n6002: +\t\t\"at least one capture target\": {},\n6003: +\t\t\"snap length 10 is outside\": {\n6004: +\t\t\tTargets:    []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"e1-1\"}},\n6005: +\t\t\tSnapLength: 10,\n6006: +\t\t},\n6007: +\t\t\"duration must not be negative\": {\n6008: +\t\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"e1-1\"}},\n6009: +\t\t\tDuration: -time.Second,\n6010: +\t\t},\n6011: +\t}\n6012: +\tfor want, req := range cases {\n6013: +\t\treq.Name = \"lab1\"\n6014: +\t\terr := r.Capture(ctx, req, io.Discard)\n6015: +\t\tif err == nil || !strings.Contains(err.Error(), want) {\n6016: +\t\t\tt.Errorf(\"error = %v, want %q\", err, want)\n6017: +\t\t}\n6018: +\t}\n6019: +\tif commands := clabwire.captureCommands(); len(commands) != 0 {\n6020: +\t\tt.Fatalf(\"invalid requests started captures: %v\", commands)\n6021: +\t}\n6022: +}\n6023: +\n6024: +func TestInspectInterfacesReportsStateFromSysfs(t *testing.T) {\n6025: +\tt.Parallel()\n6026: +\n6027: +\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n6028: +\tclabwire.sysfs = \"Inter-|   Receive\\n face |bytes\\n\" + interfaceSysfsMarker + \"\\n\" +\n6029: +\t\t\"e1-1\\t12\\t9500\\taa:c1:ab:00:00:01\\tup\\t0x1003\\t\\n\" +\n6030: +\t\t\"e1-2\\t13\\t1500\\taa:c1:ab:00:00:02\\tlowerlayerdown\\t0x1003\\t\\n\"\n6031: +\n6032: +\tinterfaces, err := r.InspectInterfaces(context.Background(), clablabruntime.NodeRequest{\n6033: +\t\tName: \"lab1\", Nodes: []string{\"R1\"},\n6034: +\t})\n6035: +\tif err != nil {\n6036: +\t\tt.Fatal(err)\n6037: +\t}\n6038: +\tif len(interfaces) != 1 || interfaces[0].ContainerName != \"lab1-r1\" ||\n6039: +\t\tlen(interfaces[0].Interfaces) != 2 {\n6040: +\t\tt.Fatalf(\"interfaces = %+v\", interfaces)\n6041: +\t}\n6042: +\tfirst := interfaces[0].Interfaces[0]\n6043: +\tif first.InterfaceName != \"e1-1\" || first.InterfaceAlias != \"ethernet-1/1\" ||\n6044: +\t\tfirst.InterfaceMAC != \"aa:c1:ab:00:00:01\" || first.InterfaceIndex != 12 ||\n6045: +\t\tfirst.InterfaceMTU != 9500 || first.InterfaceState != \"up\" {\n6046: +\t\tt.Fatalf(\"e1-1 = %+v\", first)\n6047: +\t}\n6048: +\tif second := interfaces[0].Interfaces[1]; second.InterfaceState != \"lowerlayerdown\" {\n6049: +\t\tt.Fatalf(\"e1-2 = %+v\", second)\n6050: +\t}\n6051: +}\n6052: +\n6053: +// TestCaptureClosesStdinWhenItEnds ends every clabwire process through its stdin, whether the\n6054: +// caller cancels the capture or the output fails, so no capture is left running in the pod.\n6055: +// TestCaptureWritesWhatItReadWhenTheContextEnds stops a capture while the output is slow and\n6056: +// the chains have packets queued: every packet clabwire wrote before it ended is in the file.\n6057: +func TestCaptureWritesWhatItReadWhenTheContextEnds(t *testing.T) {\n6058: +\tt.Parallel()\n6059: +\n6060: +\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n6061: +\t// without a reorder window, a blocked output blocks the chains\n6062: +\tr.captureReorderWindow = -1\n6063: +\tctx, cancel := context.WithCancel(context.Background())\n6064: +\tdefer cancel()\n6065: +\n6066: +\tout := &gatedWriter{open: make(chan struct{})}\n6067: +\tgo func() {\n6068: +\t\ttime.Sleep(50 * time.Millisecond)\n6069: +\t\tout.block()\n6070: +\t\t// the segments keep reading while the chains wait for the output\n6071: +\t\ttime.Sleep(400 * time.Millisecond)\n6072: +\t\tcancel()\n6073: +\t\tclose(out.open)\n6074: +\t}()\n6075: +\n\n(Showing lines 5376-6075 of 7018. Use offset=6076 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+\t\t{\n+\t\t\tNode:          \"r2\",\n+\t\t\tInterface:     \"e1-1\",\n+\t\t\tAlias:         \"ethernet-1/1\",\n+\t\t\tPeerNode:      \"r1\",\n+\t\t\tPeerInterface: \"ethernet-1/1\",\n+\t\t},\n+\t},\n+}\n+\n+// fakeClabwire plays clabwire packet-capture and --list-interfaces in the fake pod exec. Every\n+// capture process sees the same traffic: one packet per tick on each requested interface,\n+// carrying the tick number, stamped with the tick time plus a per-process jitter (clabwire stamps\n+// packets when it reads them).\n+type fakeClabwire struct {\n+\tt     *testing.T\n+\tepoch time.Time\n+\ttick  time.Duration\n+\n+\tmu       sync.Mutex",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+\t\t{\n+\t\t\tNode:          \"r2\",\n+\t\t\tInterface:     \"e1-1\",\n+\t\t\tAlias:         \"ethernet-1/1\",\n+\t\t\tPeerNode:      \"r1\",\n+\t\t\tPeerInterface: \"ethernet-1/1\",\n+\t\t},\n+\t},\n+}\n+\n+// fakeClabwire plays clabwire packet-capture and --list-interfaces in the fake pod exec. Every\n+// capture process sees the same traffic: one packet per tick on each requested interface,\n+// carrying the tick number, stamped with the tick time plus a per-process jitter (clabwire stamps\n+// packets when it reads them).\n+type fakeClabwire struct {\n+\tt     *testing.T\n+\tepoch time.Time\n+\ttick  time.Duration\n+\n+\tmu       sync.Mutex\n+\tcommands [][]string\n+\t// processes counts the capture processes started per node\n+\tprocesses map[string]int\n+\n+\t// startDelay delays the Started record of the given process index (all nodes).\n+\tstartDelay map[int]time.Duration\n+\t// firstStartDelay delays the Started record of a node's first process.\n+\tfirstStartDelay map[string]time.Duration\n+\t// fail makes a process write this audit status and exit 1.\n+\tfail string\n+\t// stderrOnly makes a process write this text to stderr and exit 1, like a clabwire that\n+\t// rejects a flag.\n+\tstderrOnly string\n+\t// stampSkew stamps the packets of a node this much earlier, as if its stream reached\n+\t// containerlab this much later than the others.\n+\tstampSkew map[string]time.Duration\n+\t// stdinClosed counts the processes that ended because their stdin closed, per node.\n+\tstdinClosed map[string]int\n+\t// written counts the packets written to stdout, per node.\n+\twritten map[string]int\n+\t// sysfs is the device container's interface sample.\n+\tsysfs string\n+}\n+\n+func newFakeClabwire(t *testing.T, tick time.Duration) *fakeClabwire {\n+\tt.Helper()\n+\n+\treturn &fakeClabwire{\n+\t\tt: t, epoch: time.Now(), tick: tick, processes: map[string]int{},\n+\t\tstartDelay: map[int]time.Duration{}, stampSkew: map[string]time.Duration{},\n+\t\tfirstStartDelay: map[string]time.Duration{},\n+\t\tstdinClosed:     map[string]int{},\n+\t\twritten:         map[string]int{},\n+\t}\n+}\n+\n+func (f *fakeClabwire) exec(\n+\tctx context.Context,\n+\tnamespace, pod, container string,\n+\tcommand []string,\n+\tstdin io.Reader,\n+\tstdout, stderr io.Writer,\n+) error {\n+\tf.mu.Lock()\n+\tf.commands = append(\n+\t\tf.commands,\n+\t\tappend([]string{namespace + \"/\" + pod + \"/\" + container}, command...),\n+\t)\n+\tf.mu.Unlock()\n+\n+\tif container != clabwireContainer {\n+\t\t_, _ = io.WriteString(stdout, f.sysfs)\n+\t\treturn nil\n+\t}\n+\tif slices.Contains(command, \"--list-interfaces\") {\n+\t\treturn json.NewEncoder(stdout).Encode(captureListing[pod])\n+\t}\n+\n+\treturn f.capture(ctx, command, stdin, stdout, stderr)\n+}\n+\n+func flagValues(command []string, name string) []string {\n+\tvar values []string\n+\tfor idx := 0; idx+1 < len(command); idx++ {\n+\t\tif command[idx] == name {\n+\t\t\tvalues = append(values, command[idx+1])\n+\t\t}\n+\t}\n+\n+\treturn values\n+}\n+\n+func (f *fakeClabwire) audit(\n+\tstderr io.Writer,\n+\tstatus, node string,\n+\tinterfaces []string,\n+\treason string,\n+) {\n+\trecord := map[string]any{\n+\t\t\"schemaVersion\": captureAuditSchema, \"time\": time.Now().UTC(), \"operation\": \"PacketCapture\",\n+\t\t\"status\": status, \"nodeName\": node, \"format\": \"pcapng\", \"reason\": reason,\n+\t}\n+\tentries := []map[string]any{}\n+\tfor _, name := range interfaces {\n+\t\tentries = append(entries, map[string]any{\"name\": name})\n+\t}\n+\trecord[\"interfaces\"] = entries\n+\tdata, _ := json.Marshal(record)\n+\t_, _ = stderr.Write(append(data, '\\n'))\n+}\n+\n+func (f *fakeClabwire) capture(\n+\tctx context.Context,\n+\tcommand []string,\n+\tstdin io.Reader,\n+\tstdout, stderr io.Writer,\n+) error {\n+\tf.mu.Lock()\n+\trejected := f.stderrOnly\n+\tf.mu.Unlock()\n+\tif rejected != \"\" {\n+\t\t_, _ = io.WriteString(stdout, \"Incorrect Usage: \"+rejected+\"\\n\\nNAME:\\n   manager\\n\")\n+\t\t_, _ = io.WriteString(stderr, rejected+\"\\n\")\n+\t\treturn &clablabruntime.CommandExitError{Code: 1}\n+\t}\n+\n+\t// clabwire ends the capture when stdin closes (--stop-on-stdin-close)\n+\tif !slices.Contains(command, clabwireStopOnStdinClose) || stdin == nil {\n+\t\tf.t.Errorf(\"capture without stdin and %s: %v\", clabwireStopOnStdinClose, command)\n+\t\treturn fmt.Errorf(\"no stdin\")\n+\t}\n+\tstdinClosed := make(chan struct{})\n+\tgo func() {\n+\t\t_, _ = io.Copy(io.Discard, stdin)\n+\t\tclose(stdinClosed)\n+\t}()\n+\n+\tnode := flagValues(command, \"--nodeName\")[0]\n+\tinterfaces := flagValues(command, \"--interface\")\n+\tduration, err := time.ParseDuration(flagValues(command, \"--duration\")[0])\n+\tif err != nil {\n+\t\tf.t.Errorf(\"duration: %v\", err)\n+\t}\n+\tif !slices.Equal(flagValues(command, \"--format\"), []string{\"pcapng\"}) {\n+\t\tf.t.Errorf(\"capture without --format pcapng: %v\", command)\n+\t}\n+\n+\tf.mu.Lock()\n+\tindex := f.processes[node]\n+\tf.processes[node]++\n+\tdelay := f.startDelay[index]\n+\tif index == 0 {\n+\t\tdelay += f.firstStartDelay[node]\n+\t}\n+\tfailure := f.fail\n+\tskew := f.stampSkew[node]\n+\tf.mu.Unlock()\n+\n+\tif failure != \"\" {\n+\t\tf.audit(stderr, failure, node, interfaces, \"interface \\\"eth9\\\" is not uniquely planned\")\n+\t\treturn &clablabruntime.CommandExitError{Code: 1}\n+\t}\n+\n+\tselect {\n+\tcase <-time.After(delay):\n+\tcase <-ctx.Done():\n+\t\treturn ctx.Err()\n+\tcase <-stdinClosed:\n+\t\tf.audit(stderr, captureAuditStarted, node, interfaces, \"\")\n+\t\tf.audit(stderr, captureAuditSucceeded, node, interfaces, \"client closed: stdin reached EOF\")\n+\t\treturn nil\n+\t}\n+\n+\twriter := clabcapture.NewWriter(stdout)\n+\tf.audit(stderr, captureAuditStarted, node, interfaces, \"\")\n+\tif err := writer.WriteHeader(interfaces, clabcapture.DefaultSnapLength); err != nil {\n+\t\treturn err\n+\t}\n+\n+\t// clabwire's own section header names it\n+\tend := time.Now().Add(duration)\n+\tjitter := time.Duration(index%3) * 7 * time.Microsecond\n+\tnext := time.Now().Sub(f.epoch)/f.tick + 1\n+\tfor {\n+\t\tat := f.epoch.Add(next * f.tick)\n+\t\tif at.After(end) {\n+\t\t\tbreak\n+\t\t}\n+\t\tselect {\n+\t\tcase <-ctx.Done():\n+\t\t\treturn ctx.Err()\n+\t\tcase <-stdinClosed:\n+\t\t\tf.mu.Lock()\n+\t\t\tf.stdinClosed[node]++\n+\t\t\tf.mu.Unlock()\n+\t\t\tf.audit(\n+\t\t\t\tstderr,\n+\t\t\t\tcaptureAuditSucceeded,\n+\t\t\t\tnode,\n+\t\t\t\tinterfaces,\n+\t\t\t\t\"client closed: stdin reached EOF\",\n+\t\t\t)\n+\t\t\treturn nil\n+\t\tcase <-time.After(time.Until(at)):\n+\t\t}\n+\t\tfor id := range interfaces {\n+\t\t\tdata := make([]byte, 64)\n+\t\t\tbinary.BigEndian.PutUint64(data[0:], uint64(next))\n+\t\t\tcopy(data[8:], node+\":\"+interfaces[id])\n+\t\t\tif err := writer.WritePacket(uint32(id), &clabcapture.Packet{ //nolint:gosec // small\n+\t\t\t\tTimestamp: at.Add(jitter - skew).UnixNano(), OriginalLength: 64, Data: data,\n+\t\t\t}); err != nil {\n+\t\t\t\treturn err\n+\t\t\t}\n+\t\t\tf.mu.Lock()\n+\t\t\tf.written[node]++\n+\t\t\tf.mu.Unlock()\n+\t\t}\n+\t\tnext++\n+\t}\n+\tf.audit(stderr, captureAuditSucceeded, node, interfaces, \"\")\n+\n+\treturn nil\n+}\n+\n+func (f *fakeClabwire) captureCommands() [][]string {\n+\tf.mu.Lock()\n+\tdefer f.mu.Unlock()\n+\n+\tvar result [][]string\n+\tfor _, command := range f.commands {\n+\t\tif slices.Contains(command, \"packet-capture\") &&\n+\t\t\t!slices.Contains(command, \"--list-interfaces\") {\n+\t\t\tresult = append(result, command)\n+\t\t}\n+\t}\n+\n+\treturn result\n+}\n+\n+// captureTestRuntime is lab1 in lab-ns with nodes r1 (topology name R1) and r2, each in its\n+// own pod, and a fake clabwire.\n+func captureTestRuntime(t *testing.T, tick time.Duration) (*Runtime, *fakeClabwire) {\n+\tt.Helper()\n+\n+\tr := newTestRuntimeWithKubeObjects(\n+\t\t[]*unstructured.Unstructured{\n+\t\t\tcaptureTestNode(\"r1\", \"R1\", \"node-r1-x\"),\n+\t\t\tcaptureTestNode(\"r2\", \"\", \"node-r2-x\"),\n+\t\t},\n+\t\t[]k8sruntime.Object{\n+\t\t\tcaptureTestPod(\"lab1-r1-abc\", \"r1\"),\n+\t\t\tcaptureTestPod(\"lab1-r2-def\", \"r2\"),\n+\t\t},\n+\t)\n+\tr.labNamespaceOverride = \"lab-ns\"\n+\tclabwire := newFakeClabwire(t, tick)\n+\tr.podExec = clabwire.exec\n+\n+\treturn r, clabwire\n+}\n+\n+// parsedCapture is a pcapng stream read back.\n+type parsedCapture struct {\n+\tsections   int\n+\tinterfaces []string\n+\tpackets    []clabcapture.Packet\n+}\n+\n+func parseCapture(t *testing.T, data []byte) parsedCapture {\n+\tt.Helper()\n+\n+\treader := clabcapture.NewReader(bytes.NewReader(data))\n+\tvar parsed parsedCapture\n+\tfor {\n+\t\tevent, err := reader.Next()\n+\t\tif errors.Is(err, io.EOF) {\n+\t\t\tbreak\n+\t\t}\n+\t\tif err != nil {\n+\t\t\tt.Fatalf(\"invalid capture: %v\", err)\n+\t\t}\n+\t\tif event.Interface != nil {\n+\t\t\tif len(parsed.packets) != 0 {\n+\t\t\t\tt.Fatal(\"interface description after the first packet\")\n+\t\t\t}\n+\t\t\tif event.Interface.TSResol != 9 /* nanoseconds */ {\n+\t\t\t\tt.Fatalf(\"interface %s tsresol = %d\", event.Interface.Name, event.Interface.TSResol)\n+\t\t\t}\n+\t\t\tparsed.interfaces = append(parsed.interfaces, event.Interface.Name)\n+\t\t}\n+\t\tif event.Packet != nil {\n+\t\t\tparsed.packets = append(parsed.packets, *event.Packet)\n+\t\t}\n+\t}\n+\tparsed.sections = reader.Sections()\n+\n+\treturn parsed\n+}\n+\n+func packetSequence(packet clabcapture.Packet) uint64 {\n+\treturn binary.BigEndian.Uint64(packet.Data[0:8])\n+}\n+\n+func packetOrigin(packet clabcapture.Packet) string {\n+\treturn strings.TrimRight(string(packet.Data[8:]), \"\\x00\")\n+}\n+\n+func TestCaptureInterfacesUsesTopologyNames(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, _ := captureTestRuntime(t, time.Millisecond)\n+\tinterfaces, err := r.CaptureInterfaces(\n+\t\tcontext.Background(),\n+\t\tclablabruntime.NodeRequest{Name: \"lab1\"},\n+\t)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\twant := []clablabruntime.CaptureInterface{\n+\t\t{\n+\t\t\tNode:          \"R1\",\n+\t\t\tInterface:     \"e1-1\",\n+\t\t\tAlias:         \"ethernet-1/1\",\n+\t\t\tPeerNode:      \"r2\",\n+\t\t\tPeerInterface: \"ethernet-1/1\",\n+\t\t},\n+\t\t{Node: \"R1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"r1-e1-2\"},\n+\t\t{\n+\t\t\tNode:          \"r2\",\n+\t\t\tInterface:     \"e1-1\",\n+\t\t\tAlias:         \"ethernet-1/1\",\n+\t\t\tPeerNode:      \"R1\",\n+\t\t\tPeerInterface: \"ethernet-1/1\",\n+\t\t},\n+\t}\n+\tif !slices.Equal(interfaces, want) {\n+\t\tt.Fatalf(\"interfaces = %+v\\nwant %+v\", interfaces, want)\n+\t}\n+\n+\tone, err := r.CaptureInterfaces(context.Background(), clablabruntime.NodeRequest{\n+\t\tName: \"lab1\", Nodes: []string{\"r2\"},\n+\t})\n+\tif err != nil || len(one) != 1 || one[0].Node != \"r2\" {\n+\t\tt.Fatalf(\"r2 interfaces = %+v, %v\", one, err)\n+\t}\n+}\n+\n+func TestCaptureMergesNodesIntoOneSection(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, 10*time.Millisecond)\n+\tvar out bytes.Buffer\n+\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tName: \"lab1\",\n+\t\t// the topology name of r1, an alias, and a second node between two r1 interfaces\n+\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t{Node: \"R1\", Interface: \"ethernet-1/1\"},\n+\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n+\t\t\t{Node: \"r1\", Interface: \"e1-2\"},\n+\t\t},\n+\t\tDuration: 300 * time.Millisecond,\n+\t}, &out)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\n+\tparsed := parseCapture(t, out.Bytes())\n+\tif parsed.sections != 1 {\n+\t\tt.Fatalf(\"sections = %d, want one merged section\", parsed.sections)\n+\t}\n+\twantNames := []string{\"R1:e1-1\", \"r2:e1-1\", \"R1:e1-2\"}\n+\tif !slices.Equal(parsed.interfaces, wantNames) {\n+\t\tt.Fatalf(\"interfaces = %v, want %v\", parsed.interfaces, wantNames)\n+\t}\n+\n+\t// one clabwire process per node, with all of the node's interfaces in request order\n+\tcommands := clabwire.captureCommands()\n+\tif len(commands) != 2 {\n+\t\tt.Fatalf(\"capture processes = %d, want one per node: %v\", len(commands), commands)\n+\t}\n+\tfor _, command := range commands {\n+\t\tnode := flagValues(command, \"--nodeName\")[0]\n+\t\twant := map[string][]string{\"r1\": {\"e1-1\", \"e1-2\"}, \"r2\": {\"e1-1\"}}[node]\n+\t\tif got := flagValues(command, \"--interface\"); !slices.Equal(got, want) {\n+\t\t\tt.Fatalf(\"%s interfaces = %v, want %v\", node, got, want)\n+\t\t}\n+\t\tif !strings.HasSuffix(command[0], \"/\"+clabwireContainer) {\n+\t\t\tt.Fatalf(\"capture ran in %s, want the clabwire container\", command[0])\n+\t\t}\n+\t}\n+\n+\t// every packet carries the merged ID of its interface\n+\twantOrigin := map[uint32]string{0: \"r1:e1-1\", 1: \"r2:e1-1\", 2: \"r1:e1-2\"}\n+\tperInterface := map[uint32]int{}\n+\tfor _, packet := range parsed.packets {\n+\t\tif packetOrigin(packet) != wantOrigin[packet.InterfaceID] {\n+\t\t\tt.Fatalf(\"packet from %s has interface ID %d\", packetOrigin(packet), packet.InterfaceID)\n+\t\t}\n+\t\tperInterface[packet.InterfaceID]++\n+\t}\n+\tfor id := range uint32(3) {\n+\t\tif perInterface[id] == 0 {\n+\t\t\tt.Fatalf(\"no packets on %s: %v\", wantNames[id], perInterface)\n+\t\t}\n+\t}\n+}\n+\n+// TestCaptureChainsSegmentsWithoutDuplicatesOrGaps runs captures longer than one segment: every\n+// tick must appear exactly once per interface, across every switch.\n+func TestCaptureChainsSegmentsWithoutDuplicatesOrGaps(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, 4*time.Millisecond)\n+\tr.captureSegment = 300 * time.Millisecond\n+\n+\tvar gaps []clablabruntime.CaptureGap\n+\tvar out bytes.Buffer\n+\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tName: \"lab1\",\n+\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n+\t\t\t{Node: \"r1\", Interface: \"e1-2\"},\n+\t\t},\n+\t\tDuration: 1300 * time.Millisecond,\n+\t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n+\t}, &out)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif len(gaps) != 0 {\n+\t\tt.Fatalf(\"gaps = %+v\", gaps)\n+\t}\n+\tif processes := len(clabwire.captureCommands()); processes < 4 {\n+\t\tt.Fatalf(\"capture processes = %d, want a chain of at least 4 segments\", processes)\n+\t}\n+\n+\tparsed := parseCapture(t, out.Bytes())\n+\tif parsed.sections != 1 || len(parsed.interfaces) != 2 {\n+\t\tt.Fatalf(\"sections = %d, interfaces = %v; want the follow-up headers dropped\",\n+\t\t\tparsed.sections, parsed.interfaces)\n+\t}\n+\tfor id := range uint32(2) {\n+\t\tvar sequence []uint64\n+\t\tfor _, packet := range parsed.packets {\n+\t\t\tif packet.InterfaceID == id {\n+\t\t\t\tsequence = append(sequence, packetSequence(packet))\n+\t\t\t}\n+\t\t}\n+\t\tif len(sequence) < 200 {\n+\t\t\tt.Fatalf(\"interface %d has %d packets\", id, len(sequence))\n+\t\t}\n+\t\tslices.Sort(sequence)\n+\t\tfor idx := 1; idx < len(sequence); idx++ {\n+\t\t\tswitch {\n+\t\t\tcase sequence[idx] == sequence[idx-1]:\n+\t\t\t\tt.Fatalf(\"interface %d: tick %d written twice\", id, sequence[idx])\n+\t\t\tcase sequence[idx] != sequence[idx-1]+1:\n+\t\t\t\tt.Fatalf(\n+\t\t\t\t\t\"interface %d: ticks %d to %d missing\",\n+\t\t\t\t\tid,\n+\t\t\t\t\tsequence[idx-1]+1,\n+\t\t\t\t\tsequence[idx]-1,\n+\t\t\t\t)\n+\t\t\t}\n+\t\t}\n+\t}\n+}\n+\n+func TestCaptureReportsAGapWhenTheFollowUpStartsLate(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, 5*time.Millisecond)\n+\tr.captureSegment = 300 * time.Millisecond\n+\t// the second process starts long after the first one ended\n+\tclabwire.startDelay[1] = 400 * time.Millisecond\n+\n+\tvar gaps []clablabruntime.CaptureGap\n+\tvar out bytes.Buffer\n+\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tName:     \"lab1\",\n+\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"r2\", Interface: \"e1-1\"}},\n+\t\tDuration: 800 * time.Millisecond,\n+\t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n+\t}, &out)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif len(gaps) == 0 || gaps[0].Node != \"r2\" ||\n+\t\t!slices.Equal(gaps[0].Interfaces, []string{\"e1-1\"}) ||\n+\t\tgaps[0].From.IsZero() ||\n+\t\tgaps[0].Reason == \"\" {\n+\t\tt.Fatalf(\"gaps = %+v, want the late follow-up reported\", gaps)\n+\t}\n+\tif !gaps[0].To.IsZero() && !gaps[0].To.After(gaps[0].From) {\n+\t\tt.Fatalf(\"gap ends before it starts: %+v\", gaps[0])\n+\t}\n+\tparseCapture(t, out.Bytes())\n+}\n+\n+func TestCaptureMapsDeniedAndFailedAuditsToErrors(t *testing.T) {\n+\tt.Parallel()\n+\n+\tfor _, status := range []string{captureAuditDenied, captureAuditFailed} {\n+\t\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n+\t\tclabwire.fail = status\n+\n+\t\tvar out bytes.Buffer\n+\t\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\t\tName:     \"lab1\",\n+\t\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"r2\", Interface: \"e1-1\"}},\n+\t\t\tDuration: time.Second,\n+\t\t}, &out)\n+\t\tif err == nil || !strings.Contains(err.Error(), \"is not uniquely planned\") ||\n+\t\t\t!strings.Contains(err.Error(), \"node r2\") {\n+\t\t\tt.Fatalf(\"%s: error = %v, want the audit reason\", status, err)\n+\t\t}\n+\t\tif status == captureAuditDenied && !strings.Contains(err.Error(), \"was denied\") {\n+\t\t\tt.Fatalf(\"Denied error = %v\", err)\n+\t\t}\n+\t\t// the header is written before the capture starts, so the output stays a valid file\n+\t\tparseCapture(t, out.Bytes())\n+\t}\n+}\n+\n+func TestCaptureAuditLineWriter(t *testing.T) {\n+\tt.Parallel()\n+\n+\tvar audits []*captureAudit\n+\twriter := &auditLineWriter{send: func(audit *captureAudit) { audits = append(audits, audit) }}\n+\tstarted := fmt.Sprintf(`{\"schemaVersion\":%q,\"time\":\"2026-10-27T10:00:00.123456789Z\",`+\n+\t\t`\"status\":\"Started\",\"nodeName\":\"r1\",\"interfaces\":[{\"name\":\"e1-1\",\"id\":\"if1\"}]}`,\n+\t\tcaptureAuditSchema)\n+\t// lines arrive split across writes\n+\t_, _ = writer.Write([]byte(started[:20]))\n+\t_, _ = writer.Write([]byte(started[20:] + \"\\nnot json\\n{\\\"status\\\":\\\"Started\\\"}\\n\"))\n+\t_, _ = writer.Write(\n+\t\t[]byte(`{\"schemaVersion\":\"` + captureAuditSchema + `\",\"status\":\"Succeeded\",\"packets\":3}`),\n+\t)\n+\twriter.flush()\n+\n+\tif len(audits) != 2 || audits[0].Status != captureAuditStarted || audits[1].Packets != 3 ||\n+\t\taudits[0].Time.Nanosecond() != 123456789 || audits[0].Interfaces[0].Name != \"e1-1\" {\n+\t\tt.Fatalf(\"audits = %+v\", audits)\n+\t}\n+\tif writer.text() != `not json; {\"status\":\"Started\"}` {\n+\t\tt.Fatalf(\"other stderr = %q\", writer.text())\n+\t}\n+\n+\terr := captureAuditError(\"r1\", &captureAudit{\n+\t\tStatus: captureAuditDenied, Reason: \"nope\",\n+\t\tInterfaces: []struct {\n+\t\t\tName    string `json:\"name\"`\n+\t\t\tID      string `json:\"id\"`\n+\t\t\tPackets int    `json:\"packets\"`\n+\t\t}{{Name: \"e1-1\"}, {Name: \"eth0\"}},\n+\t})\n+\tif err.Error() != \"capture of e1-1,eth0 on node r1 was denied by clabwire: nope\" {\n+\t\tt.Fatalf(\"audit error = %q\", err)\n+\t}\n+}\n+\n+func TestCaptureStopsAtThePacketLimit(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, 2*time.Millisecond)\n+\tvar out bytes.Buffer\n+\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tName: \"lab1\",\n+\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n+\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n+\t\t},\n+\t\tPacketLimit: 7,\n+\t}, &out)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif got := len(parseCapture(t, out.Bytes()).packets); got != 7 {\n+\t\tt.Fatalf(\"packets = %d, want 7\", got)\n+\t}\n+\t// each clabwire process gets the limit that remained when it started\n+\tfor _, command := range clabwire.captureCommands() {\n+\t\tlimit := flagValues(command, \"--packetLimit\")\n+\t\tif len(limit) != 1 || limit[0] < \"1\" || limit[0] > \"7\" || len(limit[0]) != 1 {\n+\t\t\tt.Fatalf(\"clabwire packet limit = %v, want at most 7\", limit)\n+\t\t}\n+\t}\n+}\n+\n+func TestCaptureEndsCleanlyWhenTheContextEnds(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, _ := captureTestRuntime(t, 2*time.Millisecond)\n+\tctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)\n+\tdefer cancel()\n+\n+\tvar out bytes.Buffer\n+\tif err := r.Capture(ctx, clablabruntime.CaptureRequest{\n+\t\tName:    \"lab1\",\n+\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"e1-1\"}},\n+\t}, &out); err != nil {\n+\t\tt.Fatalf(\"Capture() after the context ended = %v, want nil\", err)\n+\t}\n+\tif len(parseCapture(t, out.Bytes()).packets) == 0 {\n+\t\tt.Fatal(\"no packets before the context ended\")\n+\t}\n+}\n+\n+func TestCaptureValidatesTargets(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n+\tctx := context.Background()\n+\tcases := map[string]clablabruntime.CaptureRequest{\n+\t\t\"is not a capturable link interface; capturable: e1-1 (ethernet-1/1), e1-2\": {\n+\t\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth0\"}},\n+\t\t},\n+\t\t\"requested more than once\": {\n+\t\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t\t{Node: \"r1\", Interface: \"e1-1\"}, {Node: \"R1\", Interface: \"ethernet-1/1\"},\n+\t\t\t},\n+\t\t},\n+\t\t`node \"missing\" was not found`: {\n+\t\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"missing\", Interface: \"e1-1\"}},\n+\t\t},\n+\t\t\"at least one capture target\": {},\n+\t\t\"snap length 10 is outside\": {\n+\t\t\tTargets:    []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"e1-1\"}},\n+\t\t\tSnapLength: 10,\n+\t\t},\n+\t\t\"duration must not be negative\": {\n+\t\t\tTargets:  []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"e1-1\"}},\n+\t\t\tDuration: -time.Second,\n+\t\t},\n+\t}\n+\tfor want, req := range cases {\n+\t\treq.Name = \"lab1\"\n+\t\terr := r.Capture(ctx, req, io.Discard)\n+\t\tif err == nil || !strings.Contains(err.Error(), want) {\n+\t\t\tt.Errorf(\"error = %v, want %q\", err, want)\n+\t\t}\n+\t}\n+\tif commands := clabwire.captureCommands(); len(commands) != 0 {\n+\t\tt.Fatalf(\"invalid requests started captures: %v\", commands)\n+\t}\n+}\n+\n+func TestInspectInterfacesReportsStateFromSysfs(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n+\tclabwire.sysfs = \"Inter-|   Receive\\n face |bytes\\n\" + interfaceSysfsMarker + \"\\n\" +\n+\t\t\"e1-1\\t12\\t9500\\taa:c1:ab:00:00:01\\tup\\t0x1003\\t\\n\" +\n+\t\t\"e1-2\\t13\\t1500\\taa:c1:ab:00:00:02\\tlowerlayerdown\\t0x1003\\t\\n\"\n+\n+\tinterfaces, err := r.InspectInterfaces(context.Background(), clablabruntime.NodeRequest{\n+\t\tName: \"lab1\", Nodes: []string{\"R1\"},\n+\t})\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif len(interfaces) != 1 || interfaces[0].ContainerName != \"lab1-r1\" ||\n+\t\tlen(interfaces[0].Interfaces) != 2 {\n+\t\tt.Fatalf(\"interfaces = %+v\", interfaces)\n+\t}\n+\tfirst := interfaces[0].Interfaces[0]\n+\tif first.InterfaceName != \"e1-1\" || first.InterfaceAlias != \"ethernet-1/1\" ||\n+\t\tfirst.InterfaceMAC != \"aa:c1:ab:00:00:01\" || first.InterfaceIndex != 12 ||\n+\t\tfirst.InterfaceMTU != 9500 || first.InterfaceState != \"up\" {\n+\t\tt.Fatalf(\"e1-1 = %+v\", first)\n+\t}\n+\tif second := interfaces[0].Interfaces[1]; second.InterfaceState != \"lowerlayerdown\" {\n+\t\tt.Fatalf(\"e1-2 = %+v\", second)\n+\t}\n+}\n+\n+// TestCaptureClosesStdinWhenItEnds ends every clabwire process through its stdin, whether the\n+// caller cancels the capture or the output fails, so no capture is left running in the pod.\n+// TestCaptureWritesWhatItReadWhenTheContextEnds stops a capture while the output is slow and\n+// the chains have packets queued: every packet clabwire wrote before it ended is in the file.\n+func TestCaptureWritesWhatItReadWhenTheContextEnds(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n+\t// without a reorder window, a blocked output blocks the chains\n+\tr.captureReorderWindow = -1\n+\tctx, cancel := context.WithCancel(context.Background())\n+\tdefer cancel()\n+\n+\tout := &gatedWriter{open: make(chan struct{})}\n+\tgo func() {\n+\t\ttime.Sleep(50 * time.Millisecond)\n+\t\tout.block()\n+\t\t// the segments keep reading while the chains wait for the output\n+\t\ttime.Sleep(400 * time.Millisecond)\n+\t\tcancel()\n+\t\tclose(out.open)\n+\t}()\n+",
        "lineStart": 5376,
        "lineEnd": 6075,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523447375,
      "end": 1793523447399
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19653f66a00101qCoyDFzylmAO",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653ed5a001JQ2uENCIAXE6MW",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 76615,
    "input": 9131,
    "output": 27,
    "reasoning": 1,
    "cache": {
      "read": 67456,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19653ed5a001JQ2uENCIAXE6MW",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523445082,
    "completed": 1793523447405
  },
  "parentID": "msg_19653b129001cj4QAfxRVtxTFM",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 76615,
    "input": 9131,
    "output": 27,
    "reasoning": 1,
    "cache": {
      "read": 67456,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 51
step-start
{
  "type": "step-start",
  "id": "prt_19653ff25001h3Lgeare2p9Vw4",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653f6770018dflKPj7YadEFZ"
}
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 700,
  "offset": 6076
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
6076: +	if err := r.Capture(ctx, clablabruntime.CaptureRequest{
6077: +		Name: "lab1",
6078: +		Targets: []clablabruntime.CaptureTarget{
6079: +			{Node: "r1", Interface: "e1-1"},
6080: +			{Node: "r2", Interface: "e1-1"},
6081: +		},
6082: +	}, out); err != nil {
6083: +		t.Fatal(err)
6084: +	}
6085: +
6086: +	parsed := parseCapture(t, out.bytes())
6087: +	got := map[string]int{}
6088: +	for _, packet := range parsed.packets {
6089: +		node, _, _ := strings.Cut(packetOrigin(packet), ":")
6090: +		got[node]++
6091: +	}
6092: +	clabwire.mu.Lock()
6093: +	defer clabwire.mu.Unlock()
6094: +	for _, node := range []string{"r1", "r2"} {
6095: +		if clabwire.written[node] < 300 || got[node] != clabwire.written[node] {
6096: +			t.Fatalf("%s: clabwire wrote %d packets, the capture has %d", node,
6097: +				clabwire.written[node], got[node])
6098: +		}
6099: +	}
6100: +}
6101: +
6102: +// gatedWriter collects writes; once blocked, writes wait until open is closed.
6103: +type gatedWriter struct {
6104: +	open chan struct{}
6105: +
6106: +	mu      sync.Mutex
6107: +	blocked bool
6108: +	data    bytes.Buffer
6109: +}
6110: +
6111: +func (w *gatedWriter) block() {
6112: +	w.mu.Lock()
6113: +	w.blocked = true
6114: +	w.mu.Unlock()
6115: +}
6116: +
6117: +func (w *gatedWriter) Write(data []byte) (int, error) {
6118: +	w.mu.Lock()
6119: +	blocked := w.blocked
6120: +	w.mu.Unlock()
6121: +	if blocked {
6122: +		<-w.open
6123: +	}
6124: +	w.mu.Lock()
6125: +	defer w.mu.Unlock()
6126: +
6127: +	return w.data.Write(data)
6128: +}
6129: +
6130: +func (w *gatedWriter) bytes() []byte {
6131: +	w.mu.Lock()
6132: +	defer w.mu.Unlock()
6133: +
6134: +	return w.data.Bytes()
6135: +}
6136: +
6137: +func TestCaptureClosesStdinWhenItEnds(t *testing.T) {
6138: +	t.Parallel()
6139: +
6140: +	targets := []clablabruntime.CaptureTarget{
6141: +		{Node: "r1", Interface: "e1-1"},
6142: +		{Node: "r2", Interface: "e1-1"},
6143: +	}
6144: +
6145: +	t.Run("cancel", func(t *testing.T) {
6146: +		t.Parallel()
6147: +
6148: +		r, clabwire := captureTestRuntime(t, 2*time.Millisecond)
6149: +		ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
6150: +		defer cancel()
6151: +
6152: +		if err := r.Capture(ctx, clablabruntime.CaptureRequest{Name: "lab1", Targets: targets},
6153: +			io.Discard); err != nil {
6154: +			t.Fatal(err)
6155: +		}
6156: +		requireStdinClosedEverywhere(t, clabwire)
6157: +	})
6158: +
6159: +	t.Run("output fails", func(t *testing.T) {
6160: +		t.Parallel()
6161: +
6162: +		r, clabwire := captureTestRuntime(t, 2*time.Millisecond)
6163: +		output := &failingWriter{accept: 3}
6164: +		err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
6165: +			Name: "lab1", Targets: targets, Duration: time.Hour,
6166: +		}, output)
6167: +		if err == nil || !strings.Contains(err.Error(), "broken pipe") {
6168: +			t.Fatalf("Capture() = %v, want the write error", err)
6169: +		}
6170: +		requireStdinClosedEverywhere(t, clabwire)
6171: +	})
6172: +}
6173: +
6174: +// failingWriter accepts some writes, then fails like a closed pipe.
6175: +type failingWriter struct {
6176: +	mu     sync.Mutex
6177: +	accept int
6178: +}
6179: +
6180: +func (w *failingWriter) Write(data []byte) (int, error) {
6181: +	w.mu.Lock()
6182: +	defer w.mu.Unlock()
6183: +	if w.accept == 0 {
6184: +		return 0, errors.New("write |1: broken pipe")
6185: +	}
6186: +	w.accept--
6187: +
6188: +	return len(data), nil
6189: +}
6190: +
6191: +func requireStdinClosedEverywhere(t *testing.T, clabwire *fakeClabwire) {
6192: +	t.Helper()
6193: +
6194: +	clabwire.mu.Lock()
6195: +	defer clabwire.mu.Unlock()
6196: +	for _, node := range []string{"r1", "r2"} {
6197: +		if clabwire.processes[node] == 0 || clabwire.stdinClosed[node] != clabwire.processes[node] {
6198: +			t.Fatalf("%s: %d processes, %d ended through stdin", node,
6199: +				clabwire.processes[node], clabwire.stdinClosed[node])
6200: +		}
6201: +	}
6202: +}
6203: +
6204: +// TestCaptureRejectsAClabwireWithoutStopOnStdinClose turns the usage error of an older clabwire
6205: +// into the release error.
6206: +func TestCaptureRejectsAClabwireWithoutStopOnStdinClose(t *testing.T) {
6207: +	t.Parallel()
6208: +
6209: +	r, clabwire := captureTestRuntime(t, time.Millisecond)
6210: +	clabwire.stderrOnly = "flag provided but not defined: -stop-on-stdin-close"
6211: +
6212: +	err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
6213: +		Name: "lab1", Targets: []clablabruntime.CaptureTarget{{Node: "r2", Interface: "e1-1"}},
6214: +		Duration: time.Second,
6215: +	}, io.Discard)
6216: +	if !errors.Is(err, clablabruntime.ErrUnsupportedRuntimeVersion) ||
6217: +		!strings.Contains(err.Error(), "clabwire in pod lab-ns/lab1-r2-def does not accept "+
6218: +			"packet-capture --stop-on-stdin-close") ||
6219: +		!strings.Contains(err.Error(), "(0.11 or newer)") {
6220: +		t.Fatalf("Capture() = %v, want the release error", err)
6221: +	}
6222: +}
6223: +
6224: +// requireTimeOrdered checks that the merged stream's timestamps never decrease.
6225: +func requireTimeOrdered(t *testing.T, packets []clabcapture.Packet) {
6226: +	t.Helper()
6227: +
6228: +	for idx := 1; idx < len(packets); idx++ {
6229: +		if packets[idx].Timestamp < packets[idx-1].Timestamp {
6230: +			t.Fatalf("packet %d (%s) at %d precedes packet %d (%s) at %d", idx,
6231: +				packetOrigin(packets[idx]), packets[idx].Timestamp, idx-1,
6232: +				packetOrigin(packets[idx-1]), packets[idx-1].Timestamp)
6233: +		}
6234: +	}
6235: +}
6236: +
6237: +// TestCaptureMergesNodesInTimestampOrder merges two nodes whose streams arrive with different
6238: +// delays: r2's packets are stamped 60 ms before they reach containerlab. The reorder window puts
6239: +// them in order; without it they are not.
6240: +func TestCaptureMergesNodesInTimestampOrder(t *testing.T) {
6241: +	t.Parallel()
6242: +
6243: +	for _, reorder := range []bool{true, false} {
6244: +		t.Run(fmt.Sprintf("reorder=%v", reorder), func(t *testing.T) {
6245: +			t.Parallel()
6246: +
6247: +			r, clabwire := captureTestRuntime(t, 5*time.Millisecond)
6248: +			clabwire.stampSkew["r2"] = 60 * time.Millisecond
6249: +			if !reorder {
6250: +				r.captureReorderWindow = -1
6251: +			}
6252: +
6253: +			var out bytes.Buffer
6254: +			err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
6255: +				Name: "lab1",
6256: +				Targets: []clablabruntime.CaptureTarget{
6257: +					{Node: "r1", Interface: "e1-1"},
6258: +					{Node: "r2", Interface: "e1-1"},
6259: +				},
6260: +				Duration: 500 * time.Millisecond,
6261: +			}, &out)
6262: +			if err != nil {
6263: +				t.Fatal(err)
6264: +			}
6265: +
6266: +			packets := parseCapture(t, out.Bytes()).packets
6267: +			ordered := slices.IsSortedFunc(packets, func(a, b clabcapture.Packet) int {
6268: +				return int(a.Timestamp - b.Timestamp)
6269: +			})
6270: +			if reorder {
6271: +				requireTimeOrdered(t, packets)
6272: +			} else if ordered {
6273: +				t.Fatal("the skewed streams came out ordered without the reorder window")
6274: +			}
6275: +		})
6276: +	}
6277: +}
6278: +
6279: +// TestCaptureChainsSeveralNodesInOrderWithoutDuplicates chains two nodes with skewed streams and a
6280: +// reorder window shorter than a segment switch:
6281: +// every tick appears exactly once per interface and the merged stream stays in timestamp order
6282: +// across every segment switch, while old segments are ended through stdin at the switch.
6283: +func TestCaptureChainsSeveralNodesInOrderWithoutDuplicates(t *testing.T) {
6284: +	t.Parallel()
6285: +
6286: +	r, clabwire := captureTestRuntime(t, 4*time.Millisecond)
6287: +	r.captureSegment = 300 * time.Millisecond
6288: +	// a window shorter than a switch: the chains' holds keep the order across the switches
6289: +	r.captureReorderWindow = 15 * time.Millisecond
6290: +	clabwire.stampSkew["r2"] = 5 * time.Millisecond
6291: +	// r2 switches segments 120 ms after r1, so one chain streams live while the other holds
6292: +	clabwire.firstStartDelay["r2"] = 120 * time.Millisecond
6293: +
6294: +	var gaps []clablabruntime.CaptureGap
6295: +	var out bytes.Buffer
6296: +	err := r.Capture(context.Background(), clablabruntime.CaptureRequest{
6297: +		Name: "lab1",
6298: +		Targets: []clablabruntime.CaptureTarget{
6299: +			{Node: "r1", Interface: "e1-1"},
6300: +			{Node: "r2", Interface: "e1-1"},
6301: +		},
6302: +		Duration: 1300 * time.Millisecond,
6303: +		OnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },
6304: +	}, &out)
6305: +	if err != nil {
6306: +		t.Fatal(err)
6307: +	}
6308: +	if len(gaps) != 0 {
6309: +		t.Fatalf("gaps = %+v", gaps)
6310: +	}
6311: +
6312: +	parsed := parseCapture(t, out.Bytes())
6313: +	requireTimeOrdered(t, parsed.packets)
6314: +	for id := range uint32(2) {
6315: +		var sequence []uint64
6316: +		for _, packet := range parsed.packets {
6317: +			if packet.InterfaceID == id {
6318: +				sequence = append(sequence, packetSequence(packet))
6319: +			}
6320: +		}
6321: +		slices.Sort(sequence)
6322: +		if len(sequence) < 200 {
6323: +			t.Fatalf("interface %d has %d packets", id, len(sequence))
6324: +		}
6325: +		for idx := 1; idx < len(sequence); idx++ {
6326: +			if sequence[idx] != sequence[idx-1]+1 {
6327: +				t.Fatalf("interface %d: tick %d followed by %d", id, sequence[idx-1], sequence[idx])
6328: +			}
6329: +		}
6330: +	}
6331: +
6332: +	clabwire.mu.Lock()
6333: +	defer clabwire.mu.Unlock()
6334: +	for _, node := range []string{"r1", "r2"} {
6335: +		if clabwire.processes[node] < 4 || clabwire.stdinClosed[node] == 0 {
6336: +			t.Fatalf("%s: %d processes, %d stopped through stdin at a switch", node,
6337: +				clabwire.processes[node], clabwire.stdinClosed[node])
6338: +		}
6339: +	}
6340: +}
6341: +
6342: +func TestCaptureReorderWindowKnob(t *testing.T) {
6343: +	cases := map[string]time.Duration{
6344: +		"":      250 * time.Millisecond,
6345: +		"0":     0,
6346: +		"75ms":  75 * time.Millisecond,
6347: +		"bogus": 250 * time.Millisecond,
6348: +	}
6349: +	for value, want := range cases {
6350: +		t.Setenv(envCaptureReorderWindow, value)
6351: +		r := &Runtime{captureReorderWindow: captureReorderWindowFromEnv()}
6352: +		if got := r.captureReorderWindowLength(); got != want {
6353: +			t.Errorf("%s=%q: window %s, want %s", envCaptureReorderWindow, value, got, want)
6354: +		}
6355: +	}
6356: +}
6357: diff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go
6358: index 3c556e7..e869191 100644
6359: --- a/labruntime/clabernetes/clabernetes.go
6360: +++ b/labruntime/clabernetes/clabernetes.go
6361: @@ -84,10 +84,18 @@ type Runtime struct {
6362:  	// identity is the configured identity of calls without one; in a connected view it is the
6363:  	// identity the clients impersonate.
6364:  	identity clablabruntime.Identity
6365:  	// pollInterval overrides how often waits poll the cluster (tests).
6366:  	pollInterval time.Duration
6367: +	// podExec overrides how commands run in pod containers (tests).
6368: +	podExec podExecFunc
6369: +	// captureSegment is the length of one chained packet capture; zero uses the clabwire
6370: +	// maximum of one hour.
6371: +	captureSegment time.Duration
6372: +	// captureReorderWindow is how long the merged capture stream holds packets back to write
6373: +	// them in timestamp order: zero uses the default, a negative value disables reordering.
6374: +	captureReorderWindow time.Duration
6375:  	// support checks once per runtime instance, before the first cluster call, that the
6376:  	// cluster runs a clabernetes release with the contract this runtime needs. Every view
6377:  	// shares it. It is nil when the clients were injected (tests).
6378:  	support *supportCheck
6379:  }
6380: @@ -253,7 +261,9 @@ func New(cfg clablabruntime.Config) (clablabruntime.LabRuntime, error) {
6381:  		timeout:              cfg.Timeout,
6382:  		kindLinkApplyMode:    cfg.KindLinkApplyMode,
6383:  		identity:             cfg.Identity,
6384:  		clients:              newClientLoader(),
6385:  		support:              &supportCheck{},
6386: +		captureSegment:       captureSegmentFromEnv(),
6387: +		captureReorderWindow: captureReorderWindowFromEnv(),
6388:  	}, nil
6389:  }
6390: diff --git a/labruntime/runtime.go b/labruntime/runtime.go
6391: index 76e651c..367565d 100644
6392: --- a/labruntime/runtime.go
6393: +++ b/labruntime/runtime.go
6394: @@ -387,10 +387,80 @@ type NodeLogStreamer interface {
6395:  // exactly one node. Closing the connection closes the stream.
6396:  type NodePortForwarder interface {
6397:  	DialPort(ctx context.Context, req NodeRequest, port int) (net.Conn, error)
6398:  }
6399:  
6400: +// CaptureInterface is a lab link interface packet capture accepts, with the far end of its link.
6401: +type CaptureInterface struct {
6402: +	// Node is the node name as the topology spells it.
6403: +	Node string `json:"node"`
6404: +	// Interface is the interface name inside the node, which capture output carries.
6405: +	Interface string `json:"interface"`
6406: +	// Alias is the name the topology used for the interface when the node kind maps it (for
6407: +	// example ethernet-1/1 for SR Linux e1-1). Capture targets accept either name.
6408: +	Alias string `json:"alias,omitempty"`
6409: +	// PeerNode is the node at the other end of the link, "host" for a host endpoint, or empty
6410: +	// when the runtime cannot name it.
6411: +	PeerNode string `json:"peer_node"`
6412: +	// PeerInterface is the peer's interface as the topology wrote it.
6413: +	PeerInterface string `json:"peer_interface"`
6414: +}
6415: +
6416: +// CaptureTarget is one interface of one node to capture. Node takes the name the topology or
6417: +// the runtime uses, Interface the interface name or its alias.
6418: +type CaptureTarget struct {
6419: +	Node      string
6420: +	Interface string
6421: +}
6422: +
6423: +// CaptureRequest selects what Capture streams.
6424: +type CaptureRequest struct {
6425: +	// Name is the lab name.
6426: +	Name      string
6427: +	Namespace string
6428: +	Targets   []CaptureTarget
6429: +	// Duration ends the capture; zero captures until the context ends.
6430: +	Duration time.Duration
6431: +	// PacketLimit ends the capture after that many packets across all targets; zero means no
6432: +	// limit.
6433: +	PacketLimit int
6434: +	// SnapLength is the number of bytes kept of each packet; zero uses the runtime default.
6435: +	SnapLength int
6436: +	// OnGap is called when the capture missed traffic, for example because a chained capture
6437: +	// did not start in time. Without it, gaps are logged as warnings.
6438: +	OnGap    func(CaptureGap)
6439: +	Identity Identity
6440: +}
6441: +
6442: +// CaptureGap is a time span a capture has no packets for, although it was running.
6443: +type CaptureGap struct {
6444: +	Node       string
6445: +	Interfaces []string
6446: +	// From and To bound the gap on the node's clock; To is zero when it is unknown.
6447: +	From   time.Time
6448: +	To     time.Time
6449: +	Reason string
6450: +}
6451: +
6452: +// PacketCapturer streams pcapng from lab link interfaces. Capture writes one section with one
6453: +// Interface Description Block per target, named <node>:<interface>, before any packet. It
6454: +// returns when Duration passed, PacketLimit packets were written, or the context ended (which
6455: +// is not an error); the output is a valid capture whenever it stops.
6456: +type PacketCapturer interface {
6457: +	CaptureInterfaces(ctx context.Context, req NodeRequest) ([]CaptureInterface, error)
6458: +	Capture(ctx context.Context, req CaptureRequest, w io.Writer) error
6459: +}
6460: +
6461: +// InterfaceInspector lists the link interfaces of a lab's nodes with their current state, in the
6462: +// shape of `inspect interfaces`.
6463: +type InterfaceInspector interface {
6464: +	InspectInterfaces(
6465: +		ctx context.Context,
6466: +		req NodeRequest,
6467: +	) ([]*clabtypes.ContainerInterfaces, error)
6468: +}
6469: +
6470:  // NodeStatsSampler reports the resource usage of a lab's nodes. It returns an error wrapping
6471:  // ErrMetricsUnavailable when the cluster serves no resource metrics.
6472:  type NodeStatsSampler interface {
6473:  	SampleStats(ctx context.Context, req InspectRequest) ([]NodeStats, error)
6474:  }
6475: diff --git a/mkdocs.yml b/mkdocs.yml
6476: index 0285ad6..8dc17bd 100644
6477: --- a/mkdocs.yml
6478: +++ b/mkdocs.yml
6479: @@ -117,10 +117,11 @@ nav:
6480:        - inspect:
6481:            - cmd/inspect/index.md
6482:            - interfaces: cmd/inspect/interfaces.md
6483:        - events: cmd/events.md
6484:        - logs: cmd/logs.md
6485: +      - capture: cmd/capture.md
6486:        - save: cmd/save.md
6487:        - exec: cmd/exec.md
6488:        - generate: cmd/generate.md
6489:        - graph: cmd/graph.md
6490:        - validate: cmd/validate.md
6491: diff --git a/tests/01-smoke/33-capture-summary.py b/tests/01-smoke/33-capture-summary.py
6492: new file mode 100755
6493: index 0000000..d49014c
6494: --- /dev/null
6495: +++ b/tests/01-smoke/33-capture-summary.py
6496: @@ -0,0 +1,69 @@
6497: +#!/usr/bin/env python3
6498: +# Copyright 2020 Nokia
6499: +# Licensed under the BSD 3-Clause License.
6500: +# SPDX-License-Identifier: BSD-3-Clause
6501: +"""Summarize a little-endian pcapng file as containerlab capture writes it, as JSON.
6502: +
6503: +Prints the number of sections, the interface names in order, the packet count per interface,
6504: +whether packets are in timestamp order, the number of 802.1Q tagged frames and the number of
6505: +ICMP echo requests and replies (untagged or tagged).
6506: +"""
6507: +
6508: +import json
6509: +import struct
6510: +import sys
6511: +
6512: +SHB, IDB, EPB = 0x0A0D0D0A, 0x00000001, 0x00000006
6513: +
6514: +
6515: +def main(path):
6516: +    with open(path, "rb") as f:
6517: +        data = f.read()
6518: +
6519: +    sections, names, counts, stamps = 0, [], {}, []
6520: +    vlan, echo = 0, 0
6521: +    offset = 0
6522: +    while offset < len(data):
6523: +        block_type, length = struct.unpack_from("<II", data, offset)
6524: +        body = data[offset + 8 : offset + length - 4]
6525: +        if block_type == SHB:
6526: +            sections += 1
6527: +        elif block_type == IDB:
6528: +            options, name = body[8:], ""
6529: +            while len(options) >= 4:
6530: +                code, size = struct.unpack_from("<HH", options)
6531: +                if code == 0:
6532: +                    break
6533: +                if code == 2:
6534: +                    name = options[4 : 4 + size].decode()
6535: +                options = options[4 + size + (4 - size % 4) % 4 :]
6536: +            names.append(name)
6537: +        elif block_type == EPB:
6538: +            iface, high, low, captured = struct.unpack_from("<IIII", body)
6539: +            frame = body[20 : 20 + captured]
6540: +            counts[names[iface]] = counts.get(names[iface], 0) + 1
6541: +            stamps.append(high << 32 | low)
6542: +            ethertype, l3 = struct.unpack_from(">H", frame, 12)[0], 14
6543: +            if ethertype == 0x8100:
6544: +                vlan += 1
6545: +                ethertype, l3 = struct.unpack_from(">H", frame, 16)[0], 18
6546: +            if ethertype == 0x0800 and frame[l3 + 9] == 1 and frame[l3 + 20] in (0, 8):
6547: +                echo += 1
6548: +        offset += length
6549: +
6550: +    print(
6551: +        json.dumps(
6552: +            {
6553: +                "sections": sections,
6554: +                "interfaces": names,
6555: +                "packets": counts,
6556: +                "ordered": stamps == sorted(stamps),
6557: +                "vlan_frames": vlan,
6558: +                "icmp_echo": echo,
6559: +            }
6560: +        )
6561: +    )
6562: +
6563: +
6564: +if __name__ == "__main__":
6565: +    main(sys.argv[1])
6566: diff --git a/tests/01-smoke/33-capture.clab.yml b/tests/01-smoke/33-capture.clab.yml
6567: new file mode 100644
6568: index 0000000..3f70288
6569: --- /dev/null
6570: +++ b/tests/01-smoke/33-capture.clab.yml
6571: @@ -0,0 +1,29 @@
6572: +# yaml-language-server: $schema=../../schemas/clab.schema.json
6573: +name: capture
6574: +
6575: +topology:
6576: +  nodes:
6577: +    l1:
6578: +      kind: linux
6579: +      image: alpine:3
6580: +      exec:
6581: +        - ip addr add 10.0.0.1/24 dev eth1
6582: +        - ip link add link eth1 name eth1.10 type vlan id 10
6583: +        - ip addr add 10.10.0.1/24 dev eth1.10
6584: +        - ip link set eth1.10 up
6585: +    l2:
6586: +      kind: linux
6587: +      image: alpine:3
6588: +      exec:
6589: +        - ip addr add 10.0.0.2/24 dev eth1
6590: +        - ip link add link eth1 name eth1.10 type vlan id 10
6591: +        - ip addr add 10.10.0.2/24 dev eth1.10
6592: +        - ip link set eth1.10 up
6593: +
6594: +  links:
6595: +    - endpoints: ["l1:eth1", "l2:eth1"]
6596: +    - type: host
6597: +      host-interface: capl2eth2
6598: +      endpoint:
6599: +        node: l2
6600: +        interface: eth2
6601: diff --git a/tests/01-smoke/33-capture.robot b/tests/01-smoke/33-capture.robot
6602: new file mode 100644
6603: index 0000000..9502a8e
6604: --- /dev/null
6605: +++ b/tests/01-smoke/33-capture.robot
6606: @@ -0,0 +1,161 @@
6607: +*** Comments ***
6608: +This suite tests the capture command with the local container runtimes: containerlab reads the
6609: +lab link interfaces through packet sockets in the nodes' network namespaces.
6610: +
6611: +
6612: +*** Settings ***
6613: +Library             OperatingSystem
6614: +Library             Process
6615: +Library             String
6616: +Library             Collections
6617: +Resource            ../common.robot
6618: +
6619: +Suite Setup         Run    ${CLAB_BIN} --runtime ${runtime} destroy -t ${topo} --cleanup
6620: +Suite Teardown      Cleanup
6621: +
6622: +
6623: +*** Variables ***
6624: +${lab-name}         capture
6625: +${topo}             ${CURDIR}/33-capture.clab.yml
6626: +${runtime}          docker
6627: +${summary-script}   ${CURDIR}/33-capture-summary.py
6628: +${pcap}             /tmp/clab-capture.pcapng
6629: +${stdout-pcap}      /tmp/clab-capture-stdout.pcapng
6630: +${interrupt-pcap}   /tmp/clab-capture-interrupt.pcapng
6631: +${restart-pcap}     /tmp/clab-capture-restart.pcapng
6632: +
6633: +
6634: +*** Test Cases ***
6635: +Deploy ${lab-name} lab
6636: +    ${rc}    ${output} =    Run And Return Rc And Output
6637: +    ...    ${CLAB_BIN} --runtime ${runtime} deploy -t ${topo}
6638: +    Log    ${output}
6639: +    Should Be Equal As Integers    ${rc}    0
6640: +
6641: +List the capturable interfaces
6642: +    ${result} =    Run Capture    --name ${lab-name} --list -f json
6643: +    Should Be Equal As Integers    ${result.rc}    0
6644: +    ${interfaces} =    Evaluate    json.loads($result.stdout)    modules=json
6645: +    Length Should Be    ${interfaces}    3
6646: +    Should Be Equal    ${interfaces}[0][node]    l1
6647: +    Should Be Equal    ${interfaces}[0][interface]    eth1
6648: +    Should Be Equal    ${interfaces}[0][peer_node]    l2
6649: +    Should Be Equal    ${interfaces}[2][node]    l2
6650: +    Should Be Equal    ${interfaces}[2][interface]    eth2
6651: +    Should Be Equal    ${interfaces}[2][peer_node]    host
6652: +    Should Be Equal    ${interfaces}[2][peer_interface]    capl2eth2
6653: +
6654: +Capture both ends of a link with VLAN traffic
6655: +    Start Process
6656: +    ...    ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l1:eth1 --target l2:eth1 --duration 8s -w ${pcap}
6657: +    ...    shell=True
6658: +    ...    alias=both-ends
6659: +    Sleep    2s
6660: +    Ping From L1    10.0.0.2
6661: +    Ping From L1    10.10.0.2
6662: +    ${result} =    Wait For Process    both-ends    timeout=30s    on_timeout=kill
6663: +    Log    ${result.stderr}
6664: +    Should Be Equal As Integers    ${result.rc}    0
6665: +    ${summary} =    Capture Summary    ${pcap}
6666: +    Should Be Equal As Integers    ${summary}[sections]    1
6667: +    ${want} =    Create List    l1:eth1    l2:eth1
6668: +    Lists Should Be Equal    ${summary}[interfaces]    ${want}
6669: +    Should Be True    ${summary}[ordered]
6670: +    # 6 pings, each request and reply seen on both ends
6671: +    Should Be True    ${summary}[icmp_echo] >= 24
6672: +    # the VLAN 10 pings keep their 802.1Q tag
6673: +    Should Be True    ${summary}[vlan_frames] >= 12
6674: +
6675: +Capture to stdout stops at the packet limit
6676: +    Start Process
6677: +    ...    sleep 1 && sudo ${runtime} exec clab-${lab-name}-l1 ping -c 20 -i 0.2 10.0.0.2
6678: +    ...    shell=True
6679: +    ...    alias=background-ping
6680: +    ${result} =    Process.Run Process
6681: +    ...    ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l2:eth1 --packet-limit 6 -w - > ${stdout-pcap}
6682: +    ...    shell=True
6683: +    ...    timeout=30s
6684: +    ...    on_timeout=kill
6685: +    Log    ${result.stderr}
6686: +    Should Be Equal As Integers    ${result.rc}    0
6687: +    ${summary} =    Capture Summary    ${stdout-pcap}
6688: +    Should Be Equal As Integers    ${summary}[packets][l2:eth1]    6
6689: +    [Teardown]    Terminate Process    background-ping    kill=True
6690: +
6691: +An interrupt ends the capture with a valid file
6692: +    Start Process
6693: +    ...    exec ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l1:eth1 -w ${interrupt-pcap}
6694: +    ...    shell=True
6695: +    ...    alias=interrupted
6696: +    Sleep    2s
6697: +    Ping From L1    10.0.0.2
6698: +    Send Signal To Process    SIGINT    interrupted
6699: +    ${result} =    Wait For Process    interrupted    timeout=15s    on_timeout=kill
6700: +    Log    ${result.stderr}
6701: +    Should Be Equal As Integers    ${result.rc}    0
6702: +    ${summary} =    Capture Summary    ${interrupt-pcap}
6703: +    Should Be True    ${summary}[icmp_echo] >= 6
6704: +
6705: +The capture reattaches an interface after its node restarts
6706: +    Start Process
6707: +    ...    exec ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l2:eth1 -w ${restart-pcap}
6708: +    ...    shell=True
6709: +    ...    alias=restarted
6710: +    Sleep    2s
6711: +    Ping From L1    10.0.0.2
6712: +    ${rc}    ${output} =    Run And Return Rc And Output
6713: +    ...    ${CLAB_BIN} --runtime ${runtime} restart -t ${topo} --node l2
6714: +    Log    ${output}
6715: +    Should Be Equal As Integers    ${rc}    0
6716: +    ${rc}    ${output} =    Run And Return Rc And Output
6717: +    ...    sudo ${runtime} exec clab-${lab-name}-l2 ip addr replace 10.0.0.2/24 dev eth1
6718: +    Log    ${output}
6719: +    Wait Until Keyword Succeeds    20s    1s    Ping From L1    10.0.0.2
6720: +    # the capture reattaches within a fraction of a second after the link is back
6721: +    Sleep    1s
6722: +    Ping From L1    10.0.0.2
6723: +    Send Signal To Process    SIGINT    restarted
6724: +    ${result} =    Wait For Process    restarted    timeout=15s    on_timeout=kill
6725: +    Log    ${result.stderr}
6726: +    Should Be Equal As Integers    ${result.rc}    0
6727: +    Should Contain    ${result.stderr}    Capture has a gap
6728: +    ${summary} =    Capture Summary    ${restart-pcap}
6729: +    # 3 pings before and 3 after the reattach, request and reply each
6730: +    Should Be True    ${summary}[icmp_echo] >= 12
6731: +
6732: +The capture rejects the management interface
6733: +    ${result} =    Run Capture    --name ${lab-name} --target l1:eth0 -w /dev/null
6734: +    Should Not Be Equal As Integers    ${result.rc}    0
6735: +    Should Contain    ${result.stderr}    not a capturable link interface; capturable: eth1
6736: +
6737: +
6738: +*** Keywords ***
6739: +Run Capture
6740: +    [Arguments]    ${args}
6741: +    ${result} =    Process.Run Process
6742: +    ...    ${CLAB_BIN} --runtime ${runtime} capture ${args}
6743: +    ...    shell=True
6744: +    ...    timeout=60s
6745: +    ...    on_timeout=kill
6746: +    Log    stdout:${\n}${result.stdout}
6747: +    Log    stderr:${\n}${result.stderr}
6748: +    RETURN    ${result}
6749: +
6750: +Ping From L1
6751: +    [Arguments]    ${address}
6752: +    ${rc}    ${output} =    Run And Return Rc And Output
6753: +    ...    sudo ${runtime} exec clab-${lab-name}-l1 ping -c 3 -i 0.2 -W 1 ${address}
6754: +    Log    ${output}
6755: +    Should Be Equal As Integers    ${rc}    0
6756: +
6757: +Capture Summary
6758: +    [Arguments]    ${file}
6759: +    ${rc}    ${output} =    Run And Return Rc And Output    python3 ${summary-script} ${file}
6760: +    Log    ${output}
6761: +    Should Be Equal As Integers    ${rc}    0
6762: +    ${summary} =    Evaluate    json.loads($output)    modules=json
6763: +    RETURN    ${summary}
6764: +
6765: +Cleanup
6766: +    Run    ${CLAB_BIN} --runtime ${runtime} destroy -t ${topo} --cleanup
6767: +    Run    sudo rm -f ${pcap} ${stdout-pcap} ${interrupt-pcap} ${restart-pcap}
6768: diff --git a/tests/14-clabernetes/01-linux-lifecycle.robot b/tests/14-clabernetes/01-linux-lifecycle.robot
6769: index 1896ae4..f45a3ff 100644
6770: --- a/tests/14-clabernetes/01-linux-lifecycle.robot
6771: +++ b/tests/14-clabernetes/01-linux-lifecycle.robot
6772: @@ -23,10 +23,14 @@ ${events-err}           /tmp/clab-c9s-events.err
6773:  ${iface-events-log}     /tmp/clab-c9s-iface-events.log
6774:  ${iface-events-err}     /tmp/clab-c9s-iface-events.err
6775:  ${offline-env}          env CLAB_KUBECONFIG\=/nonexistent/kubeconfig KUBECONFIG\=/nonexistent/kubeconfig

(Showing lines 6076-6775 of 7018. Use offset=6776 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19653ff640016jN0Ef4b311v72",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653f6770018dflKPj7YadEFZ",
  "callID": "call_9e84e2434f034f5094adf10b",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 700,
      "offset": 6076
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n6076: +\tif err := r.Capture(ctx, clablabruntime.CaptureRequest{\n6077: +\t\tName: \"lab1\",\n6078: +\t\tTargets: []clablabruntime.CaptureTarget{\n6079: +\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n6080: +\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n6081: +\t\t},\n6082: +\t}, out); err != nil {\n6083: +\t\tt.Fatal(err)\n6084: +\t}\n6085: +\n6086: +\tparsed := parseCapture(t, out.bytes())\n6087: +\tgot := map[string]int{}\n6088: +\tfor _, packet := range parsed.packets {\n6089: +\t\tnode, _, _ := strings.Cut(packetOrigin(packet), \":\")\n6090: +\t\tgot[node]++\n6091: +\t}\n6092: +\tclabwire.mu.Lock()\n6093: +\tdefer clabwire.mu.Unlock()\n6094: +\tfor _, node := range []string{\"r1\", \"r2\"} {\n6095: +\t\tif clabwire.written[node] < 300 || got[node] != clabwire.written[node] {\n6096: +\t\t\tt.Fatalf(\"%s: clabwire wrote %d packets, the capture has %d\", node,\n6097: +\t\t\t\tclabwire.written[node], got[node])\n6098: +\t\t}\n6099: +\t}\n6100: +}\n6101: +\n6102: +// gatedWriter collects writes; once blocked, writes wait until open is closed.\n6103: +type gatedWriter struct {\n6104: +\topen chan struct{}\n6105: +\n6106: +\tmu      sync.Mutex\n6107: +\tblocked bool\n6108: +\tdata    bytes.Buffer\n6109: +}\n6110: +\n6111: +func (w *gatedWriter) block() {\n6112: +\tw.mu.Lock()\n6113: +\tw.blocked = true\n6114: +\tw.mu.Unlock()\n6115: +}\n6116: +\n6117: +func (w *gatedWriter) Write(data []byte) (int, error) {\n6118: +\tw.mu.Lock()\n6119: +\tblocked := w.blocked\n6120: +\tw.mu.Unlock()\n6121: +\tif blocked {\n6122: +\t\t<-w.open\n6123: +\t}\n6124: +\tw.mu.Lock()\n6125: +\tdefer w.mu.Unlock()\n6126: +\n6127: +\treturn w.data.Write(data)\n6128: +}\n6129: +\n6130: +func (w *gatedWriter) bytes() []byte {\n6131: +\tw.mu.Lock()\n6132: +\tdefer w.mu.Unlock()\n6133: +\n6134: +\treturn w.data.Bytes()\n6135: +}\n6136: +\n6137: +func TestCaptureClosesStdinWhenItEnds(t *testing.T) {\n6138: +\tt.Parallel()\n6139: +\n6140: +\ttargets := []clablabruntime.CaptureTarget{\n6141: +\t\t{Node: \"r1\", Interface: \"e1-1\"},\n6142: +\t\t{Node: \"r2\", Interface: \"e1-1\"},\n6143: +\t}\n6144: +\n6145: +\tt.Run(\"cancel\", func(t *testing.T) {\n6146: +\t\tt.Parallel()\n6147: +\n6148: +\t\tr, clabwire := captureTestRuntime(t, 2*time.Millisecond)\n6149: +\t\tctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)\n6150: +\t\tdefer cancel()\n6151: +\n6152: +\t\tif err := r.Capture(ctx, clablabruntime.CaptureRequest{Name: \"lab1\", Targets: targets},\n6153: +\t\t\tio.Discard); err != nil {\n6154: +\t\t\tt.Fatal(err)\n6155: +\t\t}\n6156: +\t\trequireStdinClosedEverywhere(t, clabwire)\n6157: +\t})\n6158: +\n6159: +\tt.Run(\"output fails\", func(t *testing.T) {\n6160: +\t\tt.Parallel()\n6161: +\n6162: +\t\tr, clabwire := captureTestRuntime(t, 2*time.Millisecond)\n6163: +\t\toutput := &failingWriter{accept: 3}\n6164: +\t\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n6165: +\t\t\tName: \"lab1\", Targets: targets, Duration: time.Hour,\n6166: +\t\t}, output)\n6167: +\t\tif err == nil || !strings.Contains(err.Error(), \"broken pipe\") {\n6168: +\t\t\tt.Fatalf(\"Capture() = %v, want the write error\", err)\n6169: +\t\t}\n6170: +\t\trequireStdinClosedEverywhere(t, clabwire)\n6171: +\t})\n6172: +}\n6173: +\n6174: +// failingWriter accepts some writes, then fails like a closed pipe.\n6175: +type failingWriter struct {\n6176: +\tmu     sync.Mutex\n6177: +\taccept int\n6178: +}\n6179: +\n6180: +func (w *failingWriter) Write(data []byte) (int, error) {\n6181: +\tw.mu.Lock()\n6182: +\tdefer w.mu.Unlock()\n6183: +\tif w.accept == 0 {\n6184: +\t\treturn 0, errors.New(\"write |1: broken pipe\")\n6185: +\t}\n6186: +\tw.accept--\n6187: +\n6188: +\treturn len(data), nil\n6189: +}\n6190: +\n6191: +func requireStdinClosedEverywhere(t *testing.T, clabwire *fakeClabwire) {\n6192: +\tt.Helper()\n6193: +\n6194: +\tclabwire.mu.Lock()\n6195: +\tdefer clabwire.mu.Unlock()\n6196: +\tfor _, node := range []string{\"r1\", \"r2\"} {\n6197: +\t\tif clabwire.processes[node] == 0 || clabwire.stdinClosed[node] != clabwire.processes[node] {\n6198: +\t\t\tt.Fatalf(\"%s: %d processes, %d ended through stdin\", node,\n6199: +\t\t\t\tclabwire.processes[node], clabwire.stdinClosed[node])\n6200: +\t\t}\n6201: +\t}\n6202: +}\n6203: +\n6204: +// TestCaptureRejectsAClabwireWithoutStopOnStdinClose turns the usage error of an older clabwire\n6205: +// into the release error.\n6206: +func TestCaptureRejectsAClabwireWithoutStopOnStdinClose(t *testing.T) {\n6207: +\tt.Parallel()\n6208: +\n6209: +\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n6210: +\tclabwire.stderrOnly = \"flag provided but not defined: -stop-on-stdin-close\"\n6211: +\n6212: +\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n6213: +\t\tName: \"lab1\", Targets: []clablabruntime.CaptureTarget{{Node: \"r2\", Interface: \"e1-1\"}},\n6214: +\t\tDuration: time.Second,\n6215: +\t}, io.Discard)\n6216: +\tif !errors.Is(err, clablabruntime.ErrUnsupportedRuntimeVersion) ||\n6217: +\t\t!strings.Contains(err.Error(), \"clabwire in pod lab-ns/lab1-r2-def does not accept \"+\n6218: +\t\t\t\"packet-capture --stop-on-stdin-close\") ||\n6219: +\t\t!strings.Contains(err.Error(), \"(0.11 or newer)\") {\n6220: +\t\tt.Fatalf(\"Capture() = %v, want the release error\", err)\n6221: +\t}\n6222: +}\n6223: +\n6224: +// requireTimeOrdered checks that the merged stream's timestamps never decrease.\n6225: +func requireTimeOrdered(t *testing.T, packets []clabcapture.Packet) {\n6226: +\tt.Helper()\n6227: +\n6228: +\tfor idx := 1; idx < len(packets); idx++ {\n6229: +\t\tif packets[idx].Timestamp < packets[idx-1].Timestamp {\n6230: +\t\t\tt.Fatalf(\"packet %d (%s) at %d precedes packet %d (%s) at %d\", idx,\n6231: +\t\t\t\tpacketOrigin(packets[idx]), packets[idx].Timestamp, idx-1,\n6232: +\t\t\t\tpacketOrigin(packets[idx-1]), packets[idx-1].Timestamp)\n6233: +\t\t}\n6234: +\t}\n6235: +}\n6236: +\n6237: +// TestCaptureMergesNodesInTimestampOrder merges two nodes whose streams arrive with different\n6238: +// delays: r2's packets are stamped 60 ms before they reach containerlab. The reorder window puts\n6239: +// them in order; without it they are not.\n6240: +func TestCaptureMergesNodesInTimestampOrder(t *testing.T) {\n6241: +\tt.Parallel()\n6242: +\n6243: +\tfor _, reorder := range []bool{true, false} {\n6244: +\t\tt.Run(fmt.Sprintf(\"reorder=%v\", reorder), func(t *testing.T) {\n6245: +\t\t\tt.Parallel()\n6246: +\n6247: +\t\t\tr, clabwire := captureTestRuntime(t, 5*time.Millisecond)\n6248: +\t\t\tclabwire.stampSkew[\"r2\"] = 60 * time.Millisecond\n6249: +\t\t\tif !reorder {\n6250: +\t\t\t\tr.captureReorderWindow = -1\n6251: +\t\t\t}\n6252: +\n6253: +\t\t\tvar out bytes.Buffer\n6254: +\t\t\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n6255: +\t\t\t\tName: \"lab1\",\n6256: +\t\t\t\tTargets: []clablabruntime.CaptureTarget{\n6257: +\t\t\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n6258: +\t\t\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n6259: +\t\t\t\t},\n6260: +\t\t\t\tDuration: 500 * time.Millisecond,\n6261: +\t\t\t}, &out)\n6262: +\t\t\tif err != nil {\n6263: +\t\t\t\tt.Fatal(err)\n6264: +\t\t\t}\n6265: +\n6266: +\t\t\tpackets := parseCapture(t, out.Bytes()).packets\n6267: +\t\t\tordered := slices.IsSortedFunc(packets, func(a, b clabcapture.Packet) int {\n6268: +\t\t\t\treturn int(a.Timestamp - b.Timestamp)\n6269: +\t\t\t})\n6270: +\t\t\tif reorder {\n6271: +\t\t\t\trequireTimeOrdered(t, packets)\n6272: +\t\t\t} else if ordered {\n6273: +\t\t\t\tt.Fatal(\"the skewed streams came out ordered without the reorder window\")\n6274: +\t\t\t}\n6275: +\t\t})\n6276: +\t}\n6277: +}\n6278: +\n6279: +// TestCaptureChainsSeveralNodesInOrderWithoutDuplicates chains two nodes with skewed streams and a\n6280: +// reorder window shorter than a segment switch:\n6281: +// every tick appears exactly once per interface and the merged stream stays in timestamp order\n6282: +// across every segment switch, while old segments are ended through stdin at the switch.\n6283: +func TestCaptureChainsSeveralNodesInOrderWithoutDuplicates(t *testing.T) {\n6284: +\tt.Parallel()\n6285: +\n6286: +\tr, clabwire := captureTestRuntime(t, 4*time.Millisecond)\n6287: +\tr.captureSegment = 300 * time.Millisecond\n6288: +\t// a window shorter than a switch: the chains' holds keep the order across the switches\n6289: +\tr.captureReorderWindow = 15 * time.Millisecond\n6290: +\tclabwire.stampSkew[\"r2\"] = 5 * time.Millisecond\n6291: +\t// r2 switches segments 120 ms after r1, so one chain streams live while the other holds\n6292: +\tclabwire.firstStartDelay[\"r2\"] = 120 * time.Millisecond\n6293: +\n6294: +\tvar gaps []clablabruntime.CaptureGap\n6295: +\tvar out bytes.Buffer\n6296: +\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n6297: +\t\tName: \"lab1\",\n6298: +\t\tTargets: []clablabruntime.CaptureTarget{\n6299: +\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n6300: +\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n6301: +\t\t},\n6302: +\t\tDuration: 1300 * time.Millisecond,\n6303: +\t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n6304: +\t}, &out)\n6305: +\tif err != nil {\n6306: +\t\tt.Fatal(err)\n6307: +\t}\n6308: +\tif len(gaps) != 0 {\n6309: +\t\tt.Fatalf(\"gaps = %+v\", gaps)\n6310: +\t}\n6311: +\n6312: +\tparsed := parseCapture(t, out.Bytes())\n6313: +\trequireTimeOrdered(t, parsed.packets)\n6314: +\tfor id := range uint32(2) {\n6315: +\t\tvar sequence []uint64\n6316: +\t\tfor _, packet := range parsed.packets {\n6317: +\t\t\tif packet.InterfaceID == id {\n6318: +\t\t\t\tsequence = append(sequence, packetSequence(packet))\n6319: +\t\t\t}\n6320: +\t\t}\n6321: +\t\tslices.Sort(sequence)\n6322: +\t\tif len(sequence) < 200 {\n6323: +\t\t\tt.Fatalf(\"interface %d has %d packets\", id, len(sequence))\n6324: +\t\t}\n6325: +\t\tfor idx := 1; idx < len(sequence); idx++ {\n6326: +\t\t\tif sequence[idx] != sequence[idx-1]+1 {\n6327: +\t\t\t\tt.Fatalf(\"interface %d: tick %d followed by %d\", id, sequence[idx-1], sequence[idx])\n6328: +\t\t\t}\n6329: +\t\t}\n6330: +\t}\n6331: +\n6332: +\tclabwire.mu.Lock()\n6333: +\tdefer clabwire.mu.Unlock()\n6334: +\tfor _, node := range []string{\"r1\", \"r2\"} {\n6335: +\t\tif clabwire.processes[node] < 4 || clabwire.stdinClosed[node] == 0 {\n6336: +\t\t\tt.Fatalf(\"%s: %d processes, %d stopped through stdin at a switch\", node,\n6337: +\t\t\t\tclabwire.processes[node], clabwire.stdinClosed[node])\n6338: +\t\t}\n6339: +\t}\n6340: +}\n6341: +\n6342: +func TestCaptureReorderWindowKnob(t *testing.T) {\n6343: +\tcases := map[string]time.Duration{\n6344: +\t\t\"\":      250 * time.Millisecond,\n6345: +\t\t\"0\":     0,\n6346: +\t\t\"75ms\":  75 * time.Millisecond,\n6347: +\t\t\"bogus\": 250 * time.Millisecond,\n6348: +\t}\n6349: +\tfor value, want := range cases {\n6350: +\t\tt.Setenv(envCaptureReorderWindow, value)\n6351: +\t\tr := &Runtime{captureReorderWindow: captureReorderWindowFromEnv()}\n6352: +\t\tif got := r.captureReorderWindowLength(); got != want {\n6353: +\t\t\tt.Errorf(\"%s=%q: window %s, want %s\", envCaptureReorderWindow, value, got, want)\n6354: +\t\t}\n6355: +\t}\n6356: +}\n6357: diff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go\n6358: index 3c556e7..e869191 100644\n6359: --- a/labruntime/clabernetes/clabernetes.go\n6360: +++ b/labruntime/clabernetes/clabernetes.go\n6361: @@ -84,10 +84,18 @@ type Runtime struct {\n6362:  \t// identity is the configured identity of calls without one; in a connected view it is the\n6363:  \t// identity the clients impersonate.\n6364:  \tidentity clablabruntime.Identity\n6365:  \t// pollInterval overrides how often waits poll the cluster (tests).\n6366:  \tpollInterval time.Duration\n6367: +\t// podExec overrides how commands run in pod containers (tests).\n6368: +\tpodExec podExecFunc\n6369: +\t// captureSegment is the length of one chained packet capture; zero uses the clabwire\n6370: +\t// maximum of one hour.\n6371: +\tcaptureSegment time.Duration\n6372: +\t// captureReorderWindow is how long the merged capture stream holds packets back to write\n6373: +\t// them in timestamp order: zero uses the default, a negative value disables reordering.\n6374: +\tcaptureReorderWindow time.Duration\n6375:  \t// support checks once per runtime instance, before the first cluster call, that the\n6376:  \t// cluster runs a clabernetes release with the contract this runtime needs. Every view\n6377:  \t// shares it. It is nil when the clients were injected (tests).\n6378:  \tsupport *supportCheck\n6379:  }\n6380: @@ -253,7 +261,9 @@ func New(cfg clablabruntime.Config) (clablabruntime.LabRuntime, error) {\n6381:  \t\ttimeout:              cfg.Timeout,\n6382:  \t\tkindLinkApplyMode:    cfg.KindLinkApplyMode,\n6383:  \t\tidentity:             cfg.Identity,\n6384:  \t\tclients:              newClientLoader(),\n6385:  \t\tsupport:              &supportCheck{},\n6386: +\t\tcaptureSegment:       captureSegmentFromEnv(),\n6387: +\t\tcaptureReorderWindow: captureReorderWindowFromEnv(),\n6388:  \t}, nil\n6389:  }\n6390: diff --git a/labruntime/runtime.go b/labruntime/runtime.go\n6391: index 76e651c..367565d 100644\n6392: --- a/labruntime/runtime.go\n6393: +++ b/labruntime/runtime.go\n6394: @@ -387,10 +387,80 @@ type NodeLogStreamer interface {\n6395:  // exactly one node. Closing the connection closes the stream.\n6396:  type NodePortForwarder interface {\n6397:  \tDialPort(ctx context.Context, req NodeRequest, port int) (net.Conn, error)\n6398:  }\n6399:  \n6400: +// CaptureInterface is a lab link interface packet capture accepts, with the far end of its link.\n6401: +type CaptureInterface struct {\n6402: +\t// Node is the node name as the topology spells it.\n6403: +\tNode string `json:\"node\"`\n6404: +\t// Interface is the interface name inside the node, which capture output carries.\n6405: +\tInterface string `json:\"interface\"`\n6406: +\t// Alias is the name the topology used for the interface when the node kind maps it (for\n6407: +\t// example ethernet-1/1 for SR Linux e1-1). Capture targets accept either name.\n6408: +\tAlias string `json:\"alias,omitempty\"`\n6409: +\t// PeerNode is the node at the other end of the link, \"host\" for a host endpoint, or empty\n6410: +\t// when the runtime cannot name it.\n6411: +\tPeerNode string `json:\"peer_node\"`\n6412: +\t// PeerInterface is the peer's interface as the topology wrote it.\n6413: +\tPeerInterface string `json:\"peer_interface\"`\n6414: +}\n6415: +\n6416: +// CaptureTarget is one interface of one node to capture. Node takes the name the topology or\n6417: +// the runtime uses, Interface the interface name or its alias.\n6418: +type CaptureTarget struct {\n6419: +\tNode      string\n6420: +\tInterface string\n6421: +}\n6422: +\n6423: +// CaptureRequest selects what Capture streams.\n6424: +type CaptureRequest struct {\n6425: +\t// Name is the lab name.\n6426: +\tName      string\n6427: +\tNamespace string\n6428: +\tTargets   []CaptureTarget\n6429: +\t// Duration ends the capture; zero captures until the context ends.\n6430: +\tDuration time.Duration\n6431: +\t// PacketLimit ends the capture after that many packets across all targets; zero means no\n6432: +\t// limit.\n6433: +\tPacketLimit int\n6434: +\t// SnapLength is the number of bytes kept of each packet; zero uses the runtime default.\n6435: +\tSnapLength int\n6436: +\t// OnGap is called when the capture missed traffic, for example because a chained capture\n6437: +\t// did not start in time. Without it, gaps are logged as warnings.\n6438: +\tOnGap    func(CaptureGap)\n6439: +\tIdentity Identity\n6440: +}\n6441: +\n6442: +// CaptureGap is a time span a capture has no packets for, although it was running.\n6443: +type CaptureGap struct {\n6444: +\tNode       string\n6445: +\tInterfaces []string\n6446: +\t// From and To bound the gap on the node's clock; To is zero when it is unknown.\n6447: +\tFrom   time.Time\n6448: +\tTo     time.Time\n6449: +\tReason string\n6450: +}\n6451: +\n6452: +// PacketCapturer streams pcapng from lab link interfaces. Capture writes one section with one\n6453: +// Interface Description Block per target, named <node>:<interface>, before any packet. It\n6454: +// returns when Duration passed, PacketLimit packets were written, or the context ended (which\n6455: +// is not an error); the output is a valid capture whenever it stops.\n6456: +type PacketCapturer interface {\n6457: +\tCaptureInterfaces(ctx context.Context, req NodeRequest) ([]CaptureInterface, error)\n6458: +\tCapture(ctx context.Context, req CaptureRequest, w io.Writer) error\n6459: +}\n6460: +\n6461: +// InterfaceInspector lists the link interfaces of a lab's nodes with their current state, in the\n6462: +// shape of `inspect interfaces`.\n6463: +type InterfaceInspector interface {\n6464: +\tInspectInterfaces(\n6465: +\t\tctx context.Context,\n6466: +\t\treq NodeRequest,\n6467: +\t) ([]*clabtypes.ContainerInterfaces, error)\n6468: +}\n6469: +\n6470:  // NodeStatsSampler reports the resource usage of a lab's nodes. It returns an error wrapping\n6471:  // ErrMetricsUnavailable when the cluster serves no resource metrics.\n6472:  type NodeStatsSampler interface {\n6473:  \tSampleStats(ctx context.Context, req InspectRequest) ([]NodeStats, error)\n6474:  }\n6475: diff --git a/mkdocs.yml b/mkdocs.yml\n6476: index 0285ad6..8dc17bd 100644\n6477: --- a/mkdocs.yml\n6478: +++ b/mkdocs.yml\n6479: @@ -117,10 +117,11 @@ nav:\n6480:        - inspect:\n6481:            - cmd/inspect/index.md\n6482:            - interfaces: cmd/inspect/interfaces.md\n6483:        - events: cmd/events.md\n6484:        - logs: cmd/logs.md\n6485: +      - capture: cmd/capture.md\n6486:        - save: cmd/save.md\n6487:        - exec: cmd/exec.md\n6488:        - generate: cmd/generate.md\n6489:        - graph: cmd/graph.md\n6490:        - validate: cmd/validate.md\n6491: diff --git a/tests/01-smoke/33-capture-summary.py b/tests/01-smoke/33-capture-summary.py\n6492: new file mode 100755\n6493: index 0000000..d49014c\n6494: --- /dev/null\n6495: +++ b/tests/01-smoke/33-capture-summary.py\n6496: @@ -0,0 +1,69 @@\n6497: +#!/usr/bin/env python3\n6498: +# Copyright 2020 Nokia\n6499: +# Licensed under the BSD 3-Clause License.\n6500: +# SPDX-License-Identifier: BSD-3-Clause\n6501: +\"\"\"Summarize a little-endian pcapng file as containerlab capture writes it, as JSON.\n6502: +\n6503: +Prints the number of sections, the interface names in order, the packet count per interface,\n6504: +whether packets are in timestamp order, the number of 802.1Q tagged frames and the number of\n6505: +ICMP echo requests and replies (untagged or tagged).\n6506: +\"\"\"\n6507: +\n6508: +import json\n6509: +import struct\n6510: +import sys\n6511: +\n6512: +SHB, IDB, EPB = 0x0A0D0D0A, 0x00000001, 0x00000006\n6513: +\n6514: +\n6515: +def main(path):\n6516: +    with open(path, \"rb\") as f:\n6517: +        data = f.read()\n6518: +\n6519: +    sections, names, counts, stamps = 0, [], {}, []\n6520: +    vlan, echo = 0, 0\n6521: +    offset = 0\n6522: +    while offset < len(data):\n6523: +        block_type, length = struct.unpack_from(\"<II\", data, offset)\n6524: +        body = data[offset + 8 : offset + length - 4]\n6525: +        if block_type == SHB:\n6526: +            sections += 1\n6527: +        elif block_type == IDB:\n6528: +            options, name = body[8:], \"\"\n6529: +            while len(options) >= 4:\n6530: +                code, size = struct.unpack_from(\"<HH\", options)\n6531: +                if code == 0:\n6532: +                    break\n6533: +                if code == 2:\n6534: +                    name = options[4 : 4 + size].decode()\n6535: +                options = options[4 + size + (4 - size % 4) % 4 :]\n6536: +            names.append(name)\n6537: +        elif block_type == EPB:\n6538: +            iface, high, low, captured = struct.unpack_from(\"<IIII\", body)\n6539: +            frame = body[20 : 20 + captured]\n6540: +            counts[names[iface]] = counts.get(names[iface], 0) + 1\n6541: +            stamps.append(high << 32 | low)\n6542: +            ethertype, l3 = struct.unpack_from(\">H\", frame, 12)[0], 14\n6543: +            if ethertype == 0x8100:\n6544: +                vlan += 1\n6545: +                ethertype, l3 = struct.unpack_from(\">H\", frame, 16)[0], 18\n6546: +            if ethertype == 0x0800 and frame[l3 + 9] == 1 and frame[l3 + 20] in (0, 8):\n6547: +                echo += 1\n6548: +        offset += length\n6549: +\n6550: +    print(\n6551: +        json.dumps(\n6552: +            {\n6553: +                \"sections\": sections,\n6554: +                \"interfaces\": names,\n6555: +                \"packets\": counts,\n6556: +                \"ordered\": stamps == sorted(stamps),\n6557: +                \"vlan_frames\": vlan,\n6558: +                \"icmp_echo\": echo,\n6559: +            }\n6560: +        )\n6561: +    )\n6562: +\n6563: +\n6564: +if __name__ == \"__main__\":\n6565: +    main(sys.argv[1])\n6566: diff --git a/tests/01-smoke/33-capture.clab.yml b/tests/01-smoke/33-capture.clab.yml\n6567: new file mode 100644\n6568: index 0000000..3f70288\n6569: --- /dev/null\n6570: +++ b/tests/01-smoke/33-capture.clab.yml\n6571: @@ -0,0 +1,29 @@\n6572: +# yaml-language-server: $schema=../../schemas/clab.schema.json\n6573: +name: capture\n6574: +\n6575: +topology:\n6576: +  nodes:\n6577: +    l1:\n6578: +      kind: linux\n6579: +      image: alpine:3\n6580: +      exec:\n6581: +        - ip addr add 10.0.0.1/24 dev eth1\n6582: +        - ip link add link eth1 name eth1.10 type vlan id 10\n6583: +        - ip addr add 10.10.0.1/24 dev eth1.10\n6584: +        - ip link set eth1.10 up\n6585: +    l2:\n6586: +      kind: linux\n6587: +      image: alpine:3\n6588: +      exec:\n6589: +        - ip addr add 10.0.0.2/24 dev eth1\n6590: +        - ip link add link eth1 name eth1.10 type vlan id 10\n6591: +        - ip addr add 10.10.0.2/24 dev eth1.10\n6592: +        - ip link set eth1.10 up\n6593: +\n6594: +  links:\n6595: +    - endpoints: [\"l1:eth1\", \"l2:eth1\"]\n6596: +    - type: host\n6597: +      host-interface: capl2eth2\n6598: +      endpoint:\n6599: +        node: l2\n6600: +        interface: eth2\n6601: diff --git a/tests/01-smoke/33-capture.robot b/tests/01-smoke/33-capture.robot\n6602: new file mode 100644\n6603: index 0000000..9502a8e\n6604: --- /dev/null\n6605: +++ b/tests/01-smoke/33-capture.robot\n6606: @@ -0,0 +1,161 @@\n6607: +*** Comments ***\n6608: +This suite tests the capture command with the local container runtimes: containerlab reads the\n6609: +lab link interfaces through packet sockets in the nodes' network namespaces.\n6610: +\n6611: +\n6612: +*** Settings ***\n6613: +Library             OperatingSystem\n6614: +Library             Process\n6615: +Library             String\n6616: +Library             Collections\n6617: +Resource            ../common.robot\n6618: +\n6619: +Suite Setup         Run    ${CLAB_BIN} --runtime ${runtime} destroy -t ${topo} --cleanup\n6620: +Suite Teardown      Cleanup\n6621: +\n6622: +\n6623: +*** Variables ***\n6624: +${lab-name}         capture\n6625: +${topo}             ${CURDIR}/33-capture.clab.yml\n6626: +${runtime}          docker\n6627: +${summary-script}   ${CURDIR}/33-capture-summary.py\n6628: +${pcap}             /tmp/clab-capture.pcapng\n6629: +${stdout-pcap}      /tmp/clab-capture-stdout.pcapng\n6630: +${interrupt-pcap}   /tmp/clab-capture-interrupt.pcapng\n6631: +${restart-pcap}     /tmp/clab-capture-restart.pcapng\n6632: +\n6633: +\n6634: +*** Test Cases ***\n6635: +Deploy ${lab-name} lab\n6636: +    ${rc}    ${output} =    Run And Return Rc And Output\n6637: +    ...    ${CLAB_BIN} --runtime ${runtime} deploy -t ${topo}\n6638: +    Log    ${output}\n6639: +    Should Be Equal As Integers    ${rc}    0\n6640: +\n6641: +List the capturable interfaces\n6642: +    ${result} =    Run Capture    --name ${lab-name} --list -f json\n6643: +    Should Be Equal As Integers    ${result.rc}    0\n6644: +    ${interfaces} =    Evaluate    json.loads($result.stdout)    modules=json\n6645: +    Length Should Be    ${interfaces}    3\n6646: +    Should Be Equal    ${interfaces}[0][node]    l1\n6647: +    Should Be Equal    ${interfaces}[0][interface]    eth1\n6648: +    Should Be Equal    ${interfaces}[0][peer_node]    l2\n6649: +    Should Be Equal    ${interfaces}[2][node]    l2\n6650: +    Should Be Equal    ${interfaces}[2][interface]    eth2\n6651: +    Should Be Equal    ${interfaces}[2][peer_node]    host\n6652: +    Should Be Equal    ${interfaces}[2][peer_interface]    capl2eth2\n6653: +\n6654: +Capture both ends of a link with VLAN traffic\n6655: +    Start Process\n6656: +    ...    ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l1:eth1 --target l2:eth1 --duration 8s -w ${pcap}\n6657: +    ...    shell=True\n6658: +    ...    alias=both-ends\n6659: +    Sleep    2s\n6660: +    Ping From L1    10.0.0.2\n6661: +    Ping From L1    10.10.0.2\n6662: +    ${result} =    Wait For Process    both-ends    timeout=30s    on_timeout=kill\n6663: +    Log    ${result.stderr}\n6664: +    Should Be Equal As Integers    ${result.rc}    0\n6665: +    ${summary} =    Capture Summary    ${pcap}\n6666: +    Should Be Equal As Integers    ${summary}[sections]    1\n6667: +    ${want} =    Create List    l1:eth1    l2:eth1\n6668: +    Lists Should Be Equal    ${summary}[interfaces]    ${want}\n6669: +    Should Be True    ${summary}[ordered]\n6670: +    # 6 pings, each request and reply seen on both ends\n6671: +    Should Be True    ${summary}[icmp_echo] >= 24\n6672: +    # the VLAN 10 pings keep their 802.1Q tag\n6673: +    Should Be True    ${summary}[vlan_frames] >= 12\n6674: +\n6675: +Capture to stdout stops at the packet limit\n6676: +    Start Process\n6677: +    ...    sleep 1 && sudo ${runtime} exec clab-${lab-name}-l1 ping -c 20 -i 0.2 10.0.0.2\n6678: +    ...    shell=True\n6679: +    ...    alias=background-ping\n6680: +    ${result} =    Process.Run Process\n6681: +    ...    ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l2:eth1 --packet-limit 6 -w - > ${stdout-pcap}\n6682: +    ...    shell=True\n6683: +    ...    timeout=30s\n6684: +    ...    on_timeout=kill\n6685: +    Log    ${result.stderr}\n6686: +    Should Be Equal As Integers    ${result.rc}    0\n6687: +    ${summary} =    Capture Summary    ${stdout-pcap}\n6688: +    Should Be Equal As Integers    ${summary}[packets][l2:eth1]    6\n6689: +    [Teardown]    Terminate Process    background-ping    kill=True\n6690: +\n6691: +An interrupt ends the capture with a valid file\n6692: +    Start Process\n6693: +    ...    exec ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l1:eth1 -w ${interrupt-pcap}\n6694: +    ...    shell=True\n6695: +    ...    alias=interrupted\n6696: +    Sleep    2s\n6697: +    Ping From L1    10.0.0.2\n6698: +    Send Signal To Process    SIGINT    interrupted\n6699: +    ${result} =    Wait For Process    interrupted    timeout=15s    on_timeout=kill\n6700: +    Log    ${result.stderr}\n6701: +    Should Be Equal As Integers    ${result.rc}    0\n6702: +    ${summary} =    Capture Summary    ${interrupt-pcap}\n6703: +    Should Be True    ${summary}[icmp_echo] >= 6\n6704: +\n6705: +The capture reattaches an interface after its node restarts\n6706: +    Start Process\n6707: +    ...    exec ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l2:eth1 -w ${restart-pcap}\n6708: +    ...    shell=True\n6709: +    ...    alias=restarted\n6710: +    Sleep    2s\n6711: +    Ping From L1    10.0.0.2\n6712: +    ${rc}    ${output} =    Run And Return Rc And Output\n6713: +    ...    ${CLAB_BIN} --runtime ${runtime} restart -t ${topo} --node l2\n6714: +    Log    ${output}\n6715: +    Should Be Equal As Integers    ${rc}    0\n6716: +    ${rc}    ${output} =    Run And Return Rc And Output\n6717: +    ...    sudo ${runtime} exec clab-${lab-name}-l2 ip addr replace 10.0.0.2/24 dev eth1\n6718: +    Log    ${output}\n6719: +    Wait Until Keyword Succeeds    20s    1s    Ping From L1    10.0.0.2\n6720: +    # the capture reattaches within a fraction of a second after the link is back\n6721: +    Sleep    1s\n6722: +    Ping From L1    10.0.0.2\n6723: +    Send Signal To Process    SIGINT    restarted\n6724: +    ${result} =    Wait For Process    restarted    timeout=15s    on_timeout=kill\n6725: +    Log    ${result.stderr}\n6726: +    Should Be Equal As Integers    ${result.rc}    0\n6727: +    Should Contain    ${result.stderr}    Capture has a gap\n6728: +    ${summary} =    Capture Summary    ${restart-pcap}\n6729: +    # 3 pings before and 3 after the reattach, request and reply each\n6730: +    Should Be True    ${summary}[icmp_echo] >= 12\n6731: +\n6732: +The capture rejects the management interface\n6733: +    ${result} =    Run Capture    --name ${lab-name} --target l1:eth0 -w /dev/null\n6734: +    Should Not Be Equal As Integers    ${result.rc}    0\n6735: +    Should Contain    ${result.stderr}    not a capturable link interface; capturable: eth1\n6736: +\n6737: +\n6738: +*** Keywords ***\n6739: +Run Capture\n6740: +    [Arguments]    ${args}\n6741: +    ${result} =    Process.Run Process\n6742: +    ...    ${CLAB_BIN} --runtime ${runtime} capture ${args}\n6743: +    ...    shell=True\n6744: +    ...    timeout=60s\n6745: +    ...    on_timeout=kill\n6746: +    Log    stdout:${\\n}${result.stdout}\n6747: +    Log    stderr:${\\n}${result.stderr}\n6748: +    RETURN    ${result}\n6749: +\n6750: +Ping From L1\n6751: +    [Arguments]    ${address}\n6752: +    ${rc}    ${output} =    Run And Return Rc And Output\n6753: +    ...    sudo ${runtime} exec clab-${lab-name}-l1 ping -c 3 -i 0.2 -W 1 ${address}\n6754: +    Log    ${output}\n6755: +    Should Be Equal As Integers    ${rc}    0\n6756: +\n6757: +Capture Summary\n6758: +    [Arguments]    ${file}\n6759: +    ${rc}    ${output} =    Run And Return Rc And Output    python3 ${summary-script} ${file}\n6760: +    Log    ${output}\n6761: +    Should Be Equal As Integers    ${rc}    0\n6762: +    ${summary} =    Evaluate    json.loads($output)    modules=json\n6763: +    RETURN    ${summary}\n6764: +\n6765: +Cleanup\n6766: +    Run    ${CLAB_BIN} --runtime ${runtime} destroy -t ${topo} --cleanup\n6767: +    Run    sudo rm -f ${pcap} ${stdout-pcap} ${interrupt-pcap} ${restart-pcap}\n6768: diff --git a/tests/14-clabernetes/01-linux-lifecycle.robot b/tests/14-clabernetes/01-linux-lifecycle.robot\n6769: index 1896ae4..f45a3ff 100644\n6770: --- a/tests/14-clabernetes/01-linux-lifecycle.robot\n6771: +++ b/tests/14-clabernetes/01-linux-lifecycle.robot\n6772: @@ -23,10 +23,14 @@ ${events-err}           /tmp/clab-c9s-events.err\n6773:  ${iface-events-log}     /tmp/clab-c9s-iface-events.log\n6774:  ${iface-events-err}     /tmp/clab-c9s-iface-events.err\n6775:  ${offline-env}          env CLAB_KUBECONFIG\\=/nonexistent/kubeconfig KUBECONFIG\\=/nonexistent/kubeconfig\n\n(Showing lines 6076-6775 of 7018. Use offset=6776 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+\tif err := r.Capture(ctx, clablabruntime.CaptureRequest{\n+\t\tName: \"lab1\",\n+\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n+\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n+\t\t},\n+\t}, out); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\n+\tparsed := parseCapture(t, out.bytes())\n+\tgot := map[string]int{}\n+\tfor _, packet := range parsed.packets {\n+\t\tnode, _, _ := strings.Cut(packetOrigin(packet), \":\")\n+\t\tgot[node]++\n+\t}\n+\tclabwire.mu.Lock()\n+\tdefer clabwire.mu.Unlock()\n+\tfor _, node := range []string{\"r1\", \"r2\"} {\n+\t\tif clabwire.written[node] < 300 || got[node] != clabwire.written[node] {",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+\tif err := r.Capture(ctx, clablabruntime.CaptureRequest{\n+\t\tName: \"lab1\",\n+\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n+\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n+\t\t},\n+\t}, out); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\n+\tparsed := parseCapture(t, out.bytes())\n+\tgot := map[string]int{}\n+\tfor _, packet := range parsed.packets {\n+\t\tnode, _, _ := strings.Cut(packetOrigin(packet), \":\")\n+\t\tgot[node]++\n+\t}\n+\tclabwire.mu.Lock()\n+\tdefer clabwire.mu.Unlock()\n+\tfor _, node := range []string{\"r1\", \"r2\"} {\n+\t\tif clabwire.written[node] < 300 || got[node] != clabwire.written[node] {\n+\t\t\tt.Fatalf(\"%s: clabwire wrote %d packets, the capture has %d\", node,\n+\t\t\t\tclabwire.written[node], got[node])\n+\t\t}\n+\t}\n+}\n+\n+// gatedWriter collects writes; once blocked, writes wait until open is closed.\n+type gatedWriter struct {\n+\topen chan struct{}\n+\n+\tmu      sync.Mutex\n+\tblocked bool\n+\tdata    bytes.Buffer\n+}\n+\n+func (w *gatedWriter) block() {\n+\tw.mu.Lock()\n+\tw.blocked = true\n+\tw.mu.Unlock()\n+}\n+\n+func (w *gatedWriter) Write(data []byte) (int, error) {\n+\tw.mu.Lock()\n+\tblocked := w.blocked\n+\tw.mu.Unlock()\n+\tif blocked {\n+\t\t<-w.open\n+\t}\n+\tw.mu.Lock()\n+\tdefer w.mu.Unlock()\n+\n+\treturn w.data.Write(data)\n+}\n+\n+func (w *gatedWriter) bytes() []byte {\n+\tw.mu.Lock()\n+\tdefer w.mu.Unlock()\n+\n+\treturn w.data.Bytes()\n+}\n+\n+func TestCaptureClosesStdinWhenItEnds(t *testing.T) {\n+\tt.Parallel()\n+\n+\ttargets := []clablabruntime.CaptureTarget{\n+\t\t{Node: \"r1\", Interface: \"e1-1\"},\n+\t\t{Node: \"r2\", Interface: \"e1-1\"},\n+\t}\n+\n+\tt.Run(\"cancel\", func(t *testing.T) {\n+\t\tt.Parallel()\n+\n+\t\tr, clabwire := captureTestRuntime(t, 2*time.Millisecond)\n+\t\tctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)\n+\t\tdefer cancel()\n+\n+\t\tif err := r.Capture(ctx, clablabruntime.CaptureRequest{Name: \"lab1\", Targets: targets},\n+\t\t\tio.Discard); err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\trequireStdinClosedEverywhere(t, clabwire)\n+\t})\n+\n+\tt.Run(\"output fails\", func(t *testing.T) {\n+\t\tt.Parallel()\n+\n+\t\tr, clabwire := captureTestRuntime(t, 2*time.Millisecond)\n+\t\toutput := &failingWriter{accept: 3}\n+\t\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\t\tName: \"lab1\", Targets: targets, Duration: time.Hour,\n+\t\t}, output)\n+\t\tif err == nil || !strings.Contains(err.Error(), \"broken pipe\") {\n+\t\t\tt.Fatalf(\"Capture() = %v, want the write error\", err)\n+\t\t}\n+\t\trequireStdinClosedEverywhere(t, clabwire)\n+\t})\n+}\n+\n+// failingWriter accepts some writes, then fails like a closed pipe.\n+type failingWriter struct {\n+\tmu     sync.Mutex\n+\taccept int\n+}\n+\n+func (w *failingWriter) Write(data []byte) (int, error) {\n+\tw.mu.Lock()\n+\tdefer w.mu.Unlock()\n+\tif w.accept == 0 {\n+\t\treturn 0, errors.New(\"write |1: broken pipe\")\n+\t}\n+\tw.accept--\n+\n+\treturn len(data), nil\n+}\n+\n+func requireStdinClosedEverywhere(t *testing.T, clabwire *fakeClabwire) {\n+\tt.Helper()\n+\n+\tclabwire.mu.Lock()\n+\tdefer clabwire.mu.Unlock()\n+\tfor _, node := range []string{\"r1\", \"r2\"} {\n+\t\tif clabwire.processes[node] == 0 || clabwire.stdinClosed[node] != clabwire.processes[node] {\n+\t\t\tt.Fatalf(\"%s: %d processes, %d ended through stdin\", node,\n+\t\t\t\tclabwire.processes[node], clabwire.stdinClosed[node])\n+\t\t}\n+\t}\n+}\n+\n+// TestCaptureRejectsAClabwireWithoutStopOnStdinClose turns the usage error of an older clabwire\n+// into the release error.\n+func TestCaptureRejectsAClabwireWithoutStopOnStdinClose(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, time.Millisecond)\n+\tclabwire.stderrOnly = \"flag provided but not defined: -stop-on-stdin-close\"\n+\n+\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tName: \"lab1\", Targets: []clablabruntime.CaptureTarget{{Node: \"r2\", Interface: \"e1-1\"}},\n+\t\tDuration: time.Second,\n+\t}, io.Discard)\n+\tif !errors.Is(err, clablabruntime.ErrUnsupportedRuntimeVersion) ||\n+\t\t!strings.Contains(err.Error(), \"clabwire in pod lab-ns/lab1-r2-def does not accept \"+\n+\t\t\t\"packet-capture --stop-on-stdin-close\") ||\n+\t\t!strings.Contains(err.Error(), \"(0.11 or newer)\") {\n+\t\tt.Fatalf(\"Capture() = %v, want the release error\", err)\n+\t}\n+}\n+\n+// requireTimeOrdered checks that the merged stream's timestamps never decrease.\n+func requireTimeOrdered(t *testing.T, packets []clabcapture.Packet) {\n+\tt.Helper()\n+\n+\tfor idx := 1; idx < len(packets); idx++ {\n+\t\tif packets[idx].Timestamp < packets[idx-1].Timestamp {\n+\t\t\tt.Fatalf(\"packet %d (%s) at %d precedes packet %d (%s) at %d\", idx,\n+\t\t\t\tpacketOrigin(packets[idx]), packets[idx].Timestamp, idx-1,\n+\t\t\t\tpacketOrigin(packets[idx-1]), packets[idx-1].Timestamp)\n+\t\t}\n+\t}\n+}\n+\n+// TestCaptureMergesNodesInTimestampOrder merges two nodes whose streams arrive with different\n+// delays: r2's packets are stamped 60 ms before they reach containerlab. The reorder window puts\n+// them in order; without it they are not.\n+func TestCaptureMergesNodesInTimestampOrder(t *testing.T) {\n+\tt.Parallel()\n+\n+\tfor _, reorder := range []bool{true, false} {\n+\t\tt.Run(fmt.Sprintf(\"reorder=%v\", reorder), func(t *testing.T) {\n+\t\t\tt.Parallel()\n+\n+\t\t\tr, clabwire := captureTestRuntime(t, 5*time.Millisecond)\n+\t\t\tclabwire.stampSkew[\"r2\"] = 60 * time.Millisecond\n+\t\t\tif !reorder {\n+\t\t\t\tr.captureReorderWindow = -1\n+\t\t\t}\n+\n+\t\t\tvar out bytes.Buffer\n+\t\t\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\t\t\tName: \"lab1\",\n+\t\t\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n+\t\t\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n+\t\t\t\t},\n+\t\t\t\tDuration: 500 * time.Millisecond,\n+\t\t\t}, &out)\n+\t\t\tif err != nil {\n+\t\t\t\tt.Fatal(err)\n+\t\t\t}\n+\n+\t\t\tpackets := parseCapture(t, out.Bytes()).packets\n+\t\t\tordered := slices.IsSortedFunc(packets, func(a, b clabcapture.Packet) int {\n+\t\t\t\treturn int(a.Timestamp - b.Timestamp)\n+\t\t\t})\n+\t\t\tif reorder {\n+\t\t\t\trequireTimeOrdered(t, packets)\n+\t\t\t} else if ordered {\n+\t\t\t\tt.Fatal(\"the skewed streams came out ordered without the reorder window\")\n+\t\t\t}\n+\t\t})\n+\t}\n+}\n+\n+// TestCaptureChainsSeveralNodesInOrderWithoutDuplicates chains two nodes with skewed streams and a\n+// reorder window shorter than a segment switch:\n+// every tick appears exactly once per interface and the merged stream stays in timestamp order\n+// across every segment switch, while old segments are ended through stdin at the switch.\n+func TestCaptureChainsSeveralNodesInOrderWithoutDuplicates(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr, clabwire := captureTestRuntime(t, 4*time.Millisecond)\n+\tr.captureSegment = 300 * time.Millisecond\n+\t// a window shorter than a switch: the chains' holds keep the order across the switches\n+\tr.captureReorderWindow = 15 * time.Millisecond\n+\tclabwire.stampSkew[\"r2\"] = 5 * time.Millisecond\n+\t// r2 switches segments 120 ms after r1, so one chain streams live while the other holds\n+\tclabwire.firstStartDelay[\"r2\"] = 120 * time.Millisecond\n+\n+\tvar gaps []clablabruntime.CaptureGap\n+\tvar out bytes.Buffer\n+\terr := r.Capture(context.Background(), clablabruntime.CaptureRequest{\n+\t\tName: \"lab1\",\n+\t\tTargets: []clablabruntime.CaptureTarget{\n+\t\t\t{Node: \"r1\", Interface: \"e1-1\"},\n+\t\t\t{Node: \"r2\", Interface: \"e1-1\"},\n+\t\t},\n+\t\tDuration: 1300 * time.Millisecond,\n+\t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n+\t}, &out)\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif len(gaps) != 0 {\n+\t\tt.Fatalf(\"gaps = %+v\", gaps)\n+\t}\n+\n+\tparsed := parseCapture(t, out.Bytes())\n+\trequireTimeOrdered(t, parsed.packets)\n+\tfor id := range uint32(2) {\n+\t\tvar sequence []uint64\n+\t\tfor _, packet := range parsed.packets {\n+\t\t\tif packet.InterfaceID == id {\n+\t\t\t\tsequence = append(sequence, packetSequence(packet))\n+\t\t\t}\n+\t\t}\n+\t\tslices.Sort(sequence)\n+\t\tif len(sequence) < 200 {\n+\t\t\tt.Fatalf(\"interface %d has %d packets\", id, len(sequence))\n+\t\t}\n+\t\tfor idx := 1; idx < len(sequence); idx++ {\n+\t\t\tif sequence[idx] != sequence[idx-1]+1 {\n+\t\t\t\tt.Fatalf(\"interface %d: tick %d followed by %d\", id, sequence[idx-1], sequence[idx])\n+\t\t\t}\n+\t\t}\n+\t}\n+\n+\tclabwire.mu.Lock()\n+\tdefer clabwire.mu.Unlock()\n+\tfor _, node := range []string{\"r1\", \"r2\"} {\n+\t\tif clabwire.processes[node] < 4 || clabwire.stdinClosed[node] == 0 {\n+\t\t\tt.Fatalf(\"%s: %d processes, %d stopped through stdin at a switch\", node,\n+\t\t\t\tclabwire.processes[node], clabwire.stdinClosed[node])\n+\t\t}\n+\t}\n+}\n+\n+func TestCaptureReorderWindowKnob(t *testing.T) {\n+\tcases := map[string]time.Duration{\n+\t\t\"\":      250 * time.Millisecond,\n+\t\t\"0\":     0,\n+\t\t\"75ms\":  75 * time.Millisecond,\n+\t\t\"bogus\": 250 * time.Millisecond,\n+\t}\n+\tfor value, want := range cases {\n+\t\tt.Setenv(envCaptureReorderWindow, value)\n+\t\tr := &Runtime{captureReorderWindow: captureReorderWindowFromEnv()}\n+\t\tif got := r.captureReorderWindowLength(); got != want {\n+\t\t\tt.Errorf(\"%s=%q: window %s, want %s\", envCaptureReorderWindow, value, got, want)\n+\t\t}\n+\t}\n+}\ndiff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go\nindex 3c556e7..e869191 100644\n--- a/labruntime/clabernetes/clabernetes.go\n+++ b/labruntime/clabernetes/clabernetes.go\n@@ -84,10 +84,18 @@ type Runtime struct {\n \t// identity is the configured identity of calls without one; in a connected view it is the\n \t// identity the clients impersonate.\n \tidentity clablabruntime.Identity\n \t// pollInterval overrides how often waits poll the cluster (tests).\n \tpollInterval time.Duration\n+\t// podExec overrides how commands run in pod containers (tests).\n+\tpodExec podExecFunc\n+\t// captureSegment is the length of one chained packet capture; zero uses the clabwire\n+\t// maximum of one hour.\n+\tcaptureSegment time.Duration\n+\t// captureReorderWindow is how long the merged capture stream holds packets back to write\n+\t// them in timestamp order: zero uses the default, a negative value disables reordering.\n+\tcaptureReorderWindow time.Duration\n \t// support checks once per runtime instance, before the first cluster call, that the\n \t// cluster runs a clabernetes release with the contract this runtime needs. Every view\n \t// shares it. It is nil when the clients were injected (tests).\n \tsupport *supportCheck\n }\n@@ -253,7 +261,9 @@ func New(cfg clablabruntime.Config) (clablabruntime.LabRuntime, error) {\n \t\ttimeout:              cfg.Timeout,\n \t\tkindLinkApplyMode:    cfg.KindLinkApplyMode,\n \t\tidentity:             cfg.Identity,\n \t\tclients:              newClientLoader(),\n \t\tsupport:              &supportCheck{},\n+\t\tcaptureSegment:       captureSegmentFromEnv(),\n+\t\tcaptureReorderWindow: captureReorderWindowFromEnv(),\n \t}, nil\n }\ndiff --git a/labruntime/runtime.go b/labruntime/runtime.go\nindex 76e651c..367565d 100644\n--- a/labruntime/runtime.go\n+++ b/labruntime/runtime.go\n@@ -387,10 +387,80 @@ type NodeLogStreamer interface {\n // exactly one node. Closing the connection closes the stream.\n type NodePortForwarder interface {\n \tDialPort(ctx context.Context, req NodeRequest, port int) (net.Conn, error)\n }\n \n+// CaptureInterface is a lab link interface packet capture accepts, with the far end of its link.\n+type CaptureInterface struct {\n+\t// Node is the node name as the topology spells it.\n+\tNode string `json:\"node\"`\n+\t// Interface is the interface name inside the node, which capture output carries.\n+\tInterface string `json:\"interface\"`\n+\t// Alias is the name the topology used for the interface when the node kind maps it (for\n+\t// example ethernet-1/1 for SR Linux e1-1). Capture targets accept either name.\n+\tAlias string `json:\"alias,omitempty\"`\n+\t// PeerNode is the node at the other end of the link, \"host\" for a host endpoint, or empty\n+\t// when the runtime cannot name it.\n+\tPeerNode string `json:\"peer_node\"`\n+\t// PeerInterface is the peer's interface as the topology wrote it.\n+\tPeerInterface string `json:\"peer_interface\"`\n+}\n+\n+// CaptureTarget is one interface of one node to capture. Node takes the name the topology or\n+// the runtime uses, Interface the interface name or its alias.\n+type CaptureTarget struct {\n+\tNode      string\n+\tInterface string\n+}\n+\n+// CaptureRequest selects what Capture streams.\n+type CaptureRequest struct {\n+\t// Name is the lab name.\n+\tName      string\n+\tNamespace string\n+\tTargets   []CaptureTarget\n+\t// Duration ends the capture; zero captures until the context ends.\n+\tDuration time.Duration\n+\t// PacketLimit ends the capture after that many packets across all targets; zero means no\n+\t// limit.\n+\tPacketLimit int\n+\t// SnapLength is the number of bytes kept of each packet; zero uses the runtime default.\n+\tSnapLength int\n+\t// OnGap is called when the capture missed traffic, for example because a chained capture\n+\t// did not start in time. Without it, gaps are logged as warnings.\n+\tOnGap    func(CaptureGap)\n+\tIdentity Identity\n+}\n+\n+// CaptureGap is a time span a capture has no packets for, although it was running.\n+type CaptureGap struct {\n+\tNode       string\n+\tInterfaces []string\n+\t// From and To bound the gap on the node's clock; To is zero when it is unknown.\n+\tFrom   time.Time\n+\tTo     time.Time\n+\tReason string\n+}\n+\n+// PacketCapturer streams pcapng from lab link interfaces. Capture writes one section with one\n+// Interface Description Block per target, named <node>:<interface>, before any packet. It\n+// returns when Duration passed, PacketLimit packets were written, or the context ended (which\n+// is not an error); the output is a valid capture whenever it stops.\n+type PacketCapturer interface {\n+\tCaptureInterfaces(ctx context.Context, req NodeRequest) ([]CaptureInterface, error)\n+\tCapture(ctx context.Context, req CaptureRequest, w io.Writer) error\n+}\n+\n+// InterfaceInspector lists the link interfaces of a lab's nodes with their current state, in the\n+// shape of `inspect interfaces`.\n+type InterfaceInspector interface {\n+\tInspectInterfaces(\n+\t\tctx context.Context,\n+\t\treq NodeRequest,\n+\t) ([]*clabtypes.ContainerInterfaces, error)\n+}\n+\n // NodeStatsSampler reports the resource usage of a lab's nodes. It returns an error wrapping\n // ErrMetricsUnavailable when the cluster serves no resource metrics.\n type NodeStatsSampler interface {\n \tSampleStats(ctx context.Context, req InspectRequest) ([]NodeStats, error)\n }\ndiff --git a/mkdocs.yml b/mkdocs.yml\nindex 0285ad6..8dc17bd 100644\n--- a/mkdocs.yml\n+++ b/mkdocs.yml\n@@ -117,10 +117,11 @@ nav:\n       - inspect:\n           - cmd/inspect/index.md\n           - interfaces: cmd/inspect/interfaces.md\n       - events: cmd/events.md\n       - logs: cmd/logs.md\n+      - capture: cmd/capture.md\n       - save: cmd/save.md\n       - exec: cmd/exec.md\n       - generate: cmd/generate.md\n       - graph: cmd/graph.md\n       - validate: cmd/validate.md\ndiff --git a/tests/01-smoke/33-capture-summary.py b/tests/01-smoke/33-capture-summary.py\nnew file mode 100755\nindex 0000000..d49014c\n--- /dev/null\n+++ b/tests/01-smoke/33-capture-summary.py\n@@ -0,0 +1,69 @@\n+#!/usr/bin/env python3\n+# Copyright 2020 Nokia\n+# Licensed under the BSD 3-Clause License.\n+# SPDX-License-Identifier: BSD-3-Clause\n+\"\"\"Summarize a little-endian pcapng file as containerlab capture writes it, as JSON.\n+\n+Prints the number of sections, the interface names in order, the packet count per interface,\n+whether packets are in timestamp order, the number of 802.1Q tagged frames and the number of\n+ICMP echo requests and replies (untagged or tagged).\n+\"\"\"\n+\n+import json\n+import struct\n+import sys\n+\n+SHB, IDB, EPB = 0x0A0D0D0A, 0x00000001, 0x00000006\n+\n+\n+def main(path):\n+    with open(path, \"rb\") as f:\n+        data = f.read()\n+\n+    sections, names, counts, stamps = 0, [], {}, []\n+    vlan, echo = 0, 0\n+    offset = 0\n+    while offset < len(data):\n+        block_type, length = struct.unpack_from(\"<II\", data, offset)\n+        body = data[offset + 8 : offset + length - 4]\n+        if block_type == SHB:\n+            sections += 1\n+        elif block_type == IDB:\n+            options, name = body[8:], \"\"\n+            while len(options) >= 4:\n+                code, size = struct.unpack_from(\"<HH\", options)\n+                if code == 0:\n+                    break\n+                if code == 2:\n+                    name = options[4 : 4 + size].decode()\n+                options = options[4 + size + (4 - size % 4) % 4 :]\n+            names.append(name)\n+        elif block_type == EPB:\n+            iface, high, low, captured = struct.unpack_from(\"<IIII\", body)\n+            frame = body[20 : 20 + captured]\n+            counts[names[iface]] = counts.get(names[iface], 0) + 1\n+            stamps.append(high << 32 | low)\n+            ethertype, l3 = struct.unpack_from(\">H\", frame, 12)[0], 14\n+            if ethertype == 0x8100:\n+                vlan += 1\n+                ethertype, l3 = struct.unpack_from(\">H\", frame, 16)[0], 18\n+            if ethertype == 0x0800 and frame[l3 + 9] == 1 and frame[l3 + 20] in (0, 8):\n+                echo += 1\n+        offset += length\n+\n+    print(\n+        json.dumps(\n+            {\n+                \"sections\": sections,\n+                \"interfaces\": names,\n+                \"packets\": counts,\n+                \"ordered\": stamps == sorted(stamps),\n+                \"vlan_frames\": vlan,\n+                \"icmp_echo\": echo,\n+            }\n+        )\n+    )\n+\n+\n+if __name__ == \"__main__\":\n+    main(sys.argv[1])\ndiff --git a/tests/01-smoke/33-capture.clab.yml b/tests/01-smoke/33-capture.clab.yml\nnew file mode 100644\nindex 0000000..3f70288\n--- /dev/null\n+++ b/tests/01-smoke/33-capture.clab.yml\n@@ -0,0 +1,29 @@\n+# yaml-language-server: $schema=../../schemas/clab.schema.json\n+name: capture\n+\n+topology:\n+  nodes:\n+    l1:\n+      kind: linux\n+      image: alpine:3\n+      exec:\n+        - ip addr add 10.0.0.1/24 dev eth1\n+        - ip link add link eth1 name eth1.10 type vlan id 10\n+        - ip addr add 10.10.0.1/24 dev eth1.10\n+        - ip link set eth1.10 up\n+    l2:\n+      kind: linux\n+      image: alpine:3\n+      exec:\n+        - ip addr add 10.0.0.2/24 dev eth1\n+        - ip link add link eth1 name eth1.10 type vlan id 10\n+        - ip addr add 10.10.0.2/24 dev eth1.10\n+        - ip link set eth1.10 up\n+\n+  links:\n+    - endpoints: [\"l1:eth1\", \"l2:eth1\"]\n+    - type: host\n+      host-interface: capl2eth2\n+      endpoint:\n+        node: l2\n+        interface: eth2\ndiff --git a/tests/01-smoke/33-capture.robot b/tests/01-smoke/33-capture.robot\nnew file mode 100644\nindex 0000000..9502a8e\n--- /dev/null\n+++ b/tests/01-smoke/33-capture.robot\n@@ -0,0 +1,161 @@\n+*** Comments ***\n+This suite tests the capture command with the local container runtimes: containerlab reads the\n+lab link interfaces through packet sockets in the nodes' network namespaces.\n+\n+\n+*** Settings ***\n+Library             OperatingSystem\n+Library             Process\n+Library             String\n+Library             Collections\n+Resource            ../common.robot\n+\n+Suite Setup         Run    ${CLAB_BIN} --runtime ${runtime} destroy -t ${topo} --cleanup\n+Suite Teardown      Cleanup\n+\n+\n+*** Variables ***\n+${lab-name}         capture\n+${topo}             ${CURDIR}/33-capture.clab.yml\n+${runtime}          docker\n+${summary-script}   ${CURDIR}/33-capture-summary.py\n+${pcap}             /tmp/clab-capture.pcapng\n+${stdout-pcap}      /tmp/clab-capture-stdout.pcapng\n+${interrupt-pcap}   /tmp/clab-capture-interrupt.pcapng\n+${restart-pcap}     /tmp/clab-capture-restart.pcapng\n+\n+\n+*** Test Cases ***\n+Deploy ${lab-name} lab\n+    ${rc}    ${output} =    Run And Return Rc And Output\n+    ...    ${CLAB_BIN} --runtime ${runtime} deploy -t ${topo}\n+    Log    ${output}\n+    Should Be Equal As Integers    ${rc}    0\n+\n+List the capturable interfaces\n+    ${result} =    Run Capture    --name ${lab-name} --list -f json\n+    Should Be Equal As Integers    ${result.rc}    0\n+    ${interfaces} =    Evaluate    json.loads($result.stdout)    modules=json\n+    Length Should Be    ${interfaces}    3\n+    Should Be Equal    ${interfaces}[0][node]    l1\n+    Should Be Equal    ${interfaces}[0][interface]    eth1\n+    Should Be Equal    ${interfaces}[0][peer_node]    l2\n+    Should Be Equal    ${interfaces}[2][node]    l2\n+    Should Be Equal    ${interfaces}[2][interface]    eth2\n+    Should Be Equal    ${interfaces}[2][peer_node]    host\n+    Should Be Equal    ${interfaces}[2][peer_interface]    capl2eth2\n+\n+Capture both ends of a link with VLAN traffic\n+    Start Process\n+    ...    ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l1:eth1 --target l2:eth1 --duration 8s -w ${pcap}\n+    ...    shell=True\n+    ...    alias=both-ends\n+    Sleep    2s\n+    Ping From L1    10.0.0.2\n+    Ping From L1    10.10.0.2\n+    ${result} =    Wait For Process    both-ends    timeout=30s    on_timeout=kill\n+    Log    ${result.stderr}\n+    Should Be Equal As Integers    ${result.rc}    0\n+    ${summary} =    Capture Summary    ${pcap}\n+    Should Be Equal As Integers    ${summary}[sections]    1\n+    ${want} =    Create List    l1:eth1    l2:eth1\n+    Lists Should Be Equal    ${summary}[interfaces]    ${want}\n+    Should Be True    ${summary}[ordered]\n+    # 6 pings, each request and reply seen on both ends\n+    Should Be True    ${summary}[icmp_echo] >= 24\n+    # the VLAN 10 pings keep their 802.1Q tag\n+    Should Be True    ${summary}[vlan_frames] >= 12\n+\n+Capture to stdout stops at the packet limit\n+    Start Process\n+    ...    sleep 1 && sudo ${runtime} exec clab-${lab-name}-l1 ping -c 20 -i 0.2 10.0.0.2\n+    ...    shell=True\n+    ...    alias=background-ping\n+    ${result} =    Process.Run Process\n+    ...    ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l2:eth1 --packet-limit 6 -w - > ${stdout-pcap}\n+    ...    shell=True\n+    ...    timeout=30s\n+    ...    on_timeout=kill\n+    Log    ${result.stderr}\n+    Should Be Equal As Integers    ${result.rc}    0\n+    ${summary} =    Capture Summary    ${stdout-pcap}\n+    Should Be Equal As Integers    ${summary}[packets][l2:eth1]    6\n+    [Teardown]    Terminate Process    background-ping    kill=True\n+\n+An interrupt ends the capture with a valid file\n+    Start Process\n+    ...    exec ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l1:eth1 -w ${interrupt-pcap}\n+    ...    shell=True\n+    ...    alias=interrupted\n+    Sleep    2s\n+    Ping From L1    10.0.0.2\n+    Send Signal To Process    SIGINT    interrupted\n+    ${result} =    Wait For Process    interrupted    timeout=15s    on_timeout=kill\n+    Log    ${result.stderr}\n+    Should Be Equal As Integers    ${result.rc}    0\n+    ${summary} =    Capture Summary    ${interrupt-pcap}\n+    Should Be True    ${summary}[icmp_echo] >= 6\n+\n+The capture reattaches an interface after its node restarts\n+    Start Process\n+    ...    exec ${CLAB_BIN} --runtime ${runtime} capture --name ${lab-name} --target l2:eth1 -w ${restart-pcap}\n+    ...    shell=True\n+    ...    alias=restarted\n+    Sleep    2s\n+    Ping From L1    10.0.0.2\n+    ${rc}    ${output} =    Run And Return Rc And Output\n+    ...    ${CLAB_BIN} --runtime ${runtime} restart -t ${topo} --node l2\n+    Log    ${output}\n+    Should Be Equal As Integers    ${rc}    0\n+    ${rc}    ${output} =    Run And Return Rc And Output\n+    ...    sudo ${runtime} exec clab-${lab-name}-l2 ip addr replace 10.0.0.2/24 dev eth1\n+    Log    ${output}\n+    Wait Until Keyword Succeeds    20s    1s    Ping From L1    10.0.0.2\n+    # the capture reattaches within a fraction of a second after the link is back\n+    Sleep    1s\n+    Ping From L1    10.0.0.2\n+    Send Signal To Process    SIGINT    restarted\n+    ${result} =    Wait For Process    restarted    timeout=15s    on_timeout=kill\n+    Log    ${result.stderr}\n+    Should Be Equal As Integers    ${result.rc}    0\n+    Should Contain    ${result.stderr}    Capture has a gap\n+    ${summary} =    Capture Summary    ${restart-pcap}\n+    # 3 pings before and 3 after the reattach, request and reply each\n+    Should Be True    ${summary}[icmp_echo] >= 12\n+\n+The capture rejects the management interface\n+    ${result} =    Run Capture    --name ${lab-name} --target l1:eth0 -w /dev/null\n+    Should Not Be Equal As Integers    ${result.rc}    0\n+    Should Contain    ${result.stderr}    not a capturable link interface; capturable: eth1\n+\n+\n+*** Keywords ***\n+Run Capture\n+    [Arguments]    ${args}\n+    ${result} =    Process.Run Process\n+    ...    ${CLAB_BIN} --runtime ${runtime} capture ${args}\n+    ...    shell=True\n+    ...    timeout=60s\n+    ...    on_timeout=kill\n+    Log    stdout:${\\n}${result.stdout}\n+    Log    stderr:${\\n}${result.stderr}\n+    RETURN    ${result}\n+\n+Ping From L1\n+    [Arguments]    ${address}\n+    ${rc}    ${output} =    Run And Return Rc And Output\n+    ...    sudo ${runtime} exec clab-${lab-name}-l1 ping -c 3 -i 0.2 -W 1 ${address}\n+    Log    ${output}\n+    Should Be Equal As Integers    ${rc}    0\n+\n+Capture Summary\n+    [Arguments]    ${file}\n+    ${rc}    ${output} =    Run And Return Rc And Output    python3 ${summary-script} ${file}\n+    Log    ${output}\n+    Should Be Equal As Integers    ${rc}    0\n+    ${summary} =    Evaluate    json.loads($output)    modules=json\n+    RETURN    ${summary}\n+\n+Cleanup\n+    Run    ${CLAB_BIN} --runtime ${runtime} destroy -t ${topo} --cleanup\n+    Run    sudo rm -f ${pcap} ${stdout-pcap} ${interrupt-pcap} ${restart-pcap}\ndiff --git a/tests/14-clabernetes/01-linux-lifecycle.robot b/tests/14-clabernetes/01-linux-lifecycle.robot\nindex 1896ae4..f45a3ff 100644\n--- a/tests/14-clabernetes/01-linux-lifecycle.robot\n+++ b/tests/14-clabernetes/01-linux-lifecycle.robot\n@@ -23,10 +23,14 @@ ${events-err}           /tmp/clab-c9s-events.err\n ${iface-events-log}     /tmp/clab-c9s-iface-events.log\n ${iface-events-err}     /tmp/clab-c9s-iface-events.err\n ${offline-env}          env CLAB_KUBECONFIG\\=/nonexistent/kubeconfig KUBECONFIG\\=/nonexistent/kubeconfig",
        "lineStart": 6076,
        "lineEnd": 6775,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523449704,
      "end": 1793523449719
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19653ff7a001yJ2fkZZkK8A05A",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653f6770018dflKPj7YadEFZ",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 86528,
    "input": 9956,
    "output": 27,
    "reasoning": 1,
    "cache": {
      "read": 76544,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19653f6770018dflKPj7YadEFZ",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523447415,
    "completed": 1793523449725
  },
  "parentID": "msg_19653b129001cj4QAfxRVtxTFM",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 86528,
    "input": 9956,
    "output": 27,
    "reasoning": 1,
    "cache": {
      "read": 76544,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
User · 52
compaction
{
  "type": "compaction",
  "id": "prt_19653ff7f001N1mHakc00nFvsN",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653ff7e001McEi21advBqMyE",
  "auto": true,
  "overflow": false,
  "tail_start_id": "msg_19653f6770018dflKPj7YadEFZ"
}
Message metadata
{
  "role": "user",
  "id": "msg_19653ff7e001McEi21advBqMyE",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523449726
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 53
step-start
{
  "type": "step-start",
  "id": "prt_1965405d7001tWmzs4f1059FK5",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653ff8f001spWXGnVQFRdXem"
}
Reasoning
Combine prior summary with new progress. New progress: read diff regions 1-400 (workflows + capture local.go start), 401-1100 (rest of local.go), 1101-1680 (output.go rest + pcapng.go start), 1676-2165 (reorder.go + reorder_test?), 2166-2765 (cmd/capture.go), 2766-3395 (core/capture.go, labruntime_cluster_test), 3396-3975 (test_data + docs + clabernetes capture.go start), 3976-4675, 4676-5375, 5376-~6075 (fakeClabwire test harness in capture_test.go). So basically full diff traversed except tail ~6076-7018 (clabernetes.go, runtime.go, workflows at end?) — prior summary said diff tail 6410-6474 seen (runtime.go interface additions), clabernetes.go 6357-6390 seen. So remaining: 6076-6357 and 6475-7018 (capture_test.go tail, workflows at end, etc.). Actually smoke-tests.yml appeared at line 21 in diff, clabernetes-tests at line 1. So tail 6475-7018 likely capture_test.go remainder and maybe mkdocs.yml.

Update Completed list with diff regions read, fakeClabwire harness details, captureAudit schema details, segement state machine details. Active: read 6076-6357 and 6475-7018 diff regions, capture package tests, cmd tests, docs, mkdocs.yml, then final result.

Keep all important details. Note corrections: prior summary said capture package tests "not yet read" — still not read (only reorder.go impl re-seen in diff). Conversation shows reading of diff lines but no head file test reads beyond what prior summary said.

Update Next Move accordingly.
## Objective
- Review the read-only PR snapshot at `/source` (srl-labs/containerlab): read `standards.json` + referenced rules, fully review `diff.txt` (7018 lines, 37 changed paths) and head/base files, complete per-path checks (callers, tests, docs, schema), verify candidate defects, then produce the trusted result schema (JSON + findings).

## Important Details
- Head commit: `657b1700664a99c5e12c60b4cfd179eb11889bae`; base/mergeBase: `00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4`.
- Permalink roots: head=`https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/`; base=`https://github.com/srl-labs/containerlab/blob/00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4/`.
- Snapshot incomplete: false; full inventory in `/source/manifest.json`. Source-only review; cannot execute tests — disclose limitation in final result.
- Standards: `.cursor/rules/karpathy-guidelines.mdc` (surgical changes, simplicity) and `.cursor/rules/ponytail.mdc` (YAGNI, reuse, shortest diff).
- **Head files live under `/source/head/...`** (not `/source/capture/...`). Direct read of `/source` dir itself denied; read individual files.
- PR adds packet-capture feature: new `capture` package (`local.go`, `reorder.go`, `pcapng.go`, `output.go` + tests), new `cmd/capture.go` (+test), new `core/capture.go`/`core/capture_local.go` (+test), c9s runtime capture (`labruntime/clabernetes/capture.go` ~1202 lines, `capture_interfaces.go`), chained segments (1h max, 10s overlap, 500ms cut window), `CaptureGap` reporting, docs/workflow/CMD changes.
- Diff grep anchors (`^diff --git` lines): workflows (1, 21), capture/* (37–1676), cmd/* (2161–2709), core/* (2744–3320), test_data (3490), docs (3511–3879), `labruntime/clabernetes/` starts at 3900; runtime.go interface additions at 6390–6474.
- cmd context facts: `log.SetOutput(os.Stderr)` in `cmd/root.go:163` → stdout stays pure for `-w -` pcapng (verified). `commandSkipsRoot` (`cmd/root.go:211`) returns `IsLabRuntimeName(name)` — capture/inspect PreRunE skip root for c9s. `LocateNode` (`labruntime/clabernetes/access.go:49`) preserves request order for named nodes → `resolveCaptureTargets`'s `byRequest` mapping is safe.
- `cmd/context.go` FinishOnCancel verified: first signal closes `cancellationSignaled`, cancels ctx, logs "Stopping, press Ctrl+C again to abort", waits for second signal then `os.Exit(1)`; goroutine leak on clean exit is benign.
- Key implementation facts (verified): `CaptureOptions` struct = {Targets, Duration, PacketLimit, SnapLength, Write, List, Format}; `--write` default "-" (stdout); `parseCaptureTargets` accepts `<node>:<if1>,<if2>`. `Output.Emit` limit logic correct (limit-th packet written then stop). `Reorder` uses min-heap, `maxReorderBytes=64MiB`, holds map, cursor, holds/released via `Hold`/`Release(key)`. c9s `podExecFunc` signature, `clabwireInterface` JSON fields {node, interface, alias, peerNode, peerInterface}, `captureAudit` schema `c9s.direct-packet-capture-audit/v1alpha1` with statuses started/succeeded/denied/failed; `captureSegmentLength()` = `r.captureSegment` if ≤ `maxCaptureSegment` else `maxCaptureSegment`; audit "denied"/"failed" → `captureAuditError` error string "capture of %s on node %s %s by clabwire: %s".
- Verified analysis conclusions:
  - `setCut` cut==0 duplicate-packet case is effectively unreachable in production: window = min(500ms, overlap/4) always satisfies 2*window < overlap; only a defensive branch.
  - Audit Failed/Denied errors propagate as chain errors even when `c.stopping` — if clabwire writes Failed on stdin-close during Ctrl+C stop, an error could surface despite the clean-exit promise (speculative, clabwire behavior unverifiable).
  - Potential P4: `held`/`emitted` in captureChain grow unbounded during the ≤10s overlap at very high packet rates.
  - `packetKey` truncates InterfaceID to 16 bits (fnv over `id[0]`/`id[1]`) — fine for small interface counts.
  - c9s `Capture` wraps `captureCtx` with `WithTimeout(req.Duration+overlap+captureEndGrace)`; `defer stop()` cancels original ctx which propagates — OK.
  - afpacket TPACKET_V3 setup in `capture/local.go`: blockSize = max(localMinBlockSize, snapLength+pageSize) page-rounded; `OptAddVLANHeader(true)` to re-insert 802.1Q tags; promiscuous socket-scoped.
- Integration test facts seen (`core/labruntime_cluster_test.go` ~3396+): capture test runs ping via `AttachLabRuntimeNode` (client→10.10.10.2), asserts `summarizePCAPNG` returns 2 interfaces `client:eth1`, `server:eth1` with ≥8 ICMP packets each; "restart as lab editor" subtest; "forbidden identity" subtest skips unless `CLAB_C9S_TEST_FORBIDDEN_USER` set, expects error containing "forbidden".
- c9s capture_test.go harness: `fakeClabwire` plays `packet-capture`/`--list-interfaces` in fake pod exec; one packet per tick per requested interface; knobs: `startDelay` (per process index), `firstStartDelay` (per node first process), `fail` (audit status + exit 1), `stderrOnly`, `stampSkew` (per-node timestamp skew), `stdinClosed`, `written`, `sysfs` (device container interface sample); fixture targets include `r2:e1-1` with `Alias: ethernet-1/1`, peer `r1:ethernet-1/1`.

## Work State
### Completed
- Read standards + both rule files; manifest.json read; diff.txt nearly fully traversed: offsets 1, 401, 1101, 1676, 2166, 2766, 3396, 3976, 4676, 5376, plus prior overlapping reads at 1702, 3478, 4780, 6410, 2161, 2761, 3521, 3900, 6357.
- Detailed review of head files: `capture/local.go` (constants: localReorderWindow=100ms, localBlockTimeout=10ms, localPollTimeout=100ms, localReopenInterval=200ms, localDrainQuiet=5×block, localDrainTimeout=250ms, ring 8×1MiB, vlanHeaderLength=4; openAll count assumption safe; drain deadline logic correct), `capture/reorder.go` (verified late-packet cursor non-update benign; Push/writeDue backpressure deadlock-free), `capture/pcapng.go` (codec verified: SHB min body 16, EPB timestamp high/low layout, padding, tsresol; Reader.Next ErrUnexpectedEOF only on truncated stream), `capture/output.go` (ValidateRequest: DefaultSnapLength=256KiB bounds 64..1MiB; Written() atomic races benign), `cmd/capture.go`, `core/capture.go` (CLab.Capture/CaptureInterfaces dispatch local vs runtime), `core/capture_local.go`, `labruntime/clabernetes/capture.go` (captureChain state machine lines 60–1210: stop/drain/segmentDuration/nextStartIn/startNext/handle/switchSegments; events chan buf 256), `labruntime/clabernetes/capture_interfaces.go`, `access.go` LocateNode ordering, `cmd/context.go`, `cmd/root.go`, `docs/cmd/capture.md`.
- Workflow changes verified in diff: clabernetes-tests.yml installs tshark (apt-get) before robot tests; smoke-tests.yml adds `"33*.robot"` glob.
- Remaining candidate defects identified (see Important Details) with reasoning.

### Active
- Remaining diff hunks to read: tail regions ~6076–6357 and 6475–7018 (rest of `labruntime/clabernetes/capture_test.go`, `labruntime/clabernetes/clabernetes.go` diff, `labruntime/runtime.go` interface additions detail, any trailing paths e.g. `mkdocs.yml`).
- Not yet read: capture package tests (`capture/local_test.go`, `pcapng_test.go`, `reorder_test.go`), `cmd/capture_test.go`, `cmd/options.go` diff (2618), `cmd/root_test.go` (2709), `cmd/inspect_interfaces.go` full, `core/capture_test.go`, docs (`docs/manual/clabernetes/runtime.md`, `docs/manual/wireshark.md`, `docs/cmd/inspect/interfaces.md`), `mkdocs.yml` nav, `core/test_data/capture.clab.yml` full.
- Final deliverable: trusted result with per-path verdicts, findings (incl. audit-error-while-stopping and held/emitted-memory notes), permalink references, test-execution limitation disclosed.

### Blocked
- Cannot execute tests (read-only snapshot) — must be disclosed in final result.
- manifest.json truncated in tool output; remaining changed paths must be enumerated from diff headers (lines 6475–7018 mapping incomplete).

## Next Move
1. Read diff tail regions: offset 6076 limit ~282 (6076–6357) and offset 6475 limit ~543 (6475–7018) to enumerate/review remaining labruntime paths and any trailing changed files (mkdocs.yml etc.).
2. Skim capture package tests (`local_test.go`, `pcapng_test.go`, `reorder_test.go`), `cmd/capture_test.go`, `cmd/options.go`/`cmd/root_test.go` diffs for coverage gaps; check `mkdocs.yml` nav and remaining docs files; then assemble final result schema with per-path verdicts, findings, and permalinks.

## Relevant Files
- `/source/standards.json`, `/source/standards/karpathy-guidelines.mdc`, `/source/standards/ponytail.mdc` — review standards (read).
- `/source/diff.txt` — full 7018-line PR diff (traversed except ~6076–6357 and 6475–7018).
- `/source/manifest.json` — inventory (head hash `657b1700664a99c5e12c60b4cfd179eb11889bae`).
- `/source/head/capture/{local.go, local_test.go, output.go, pcapng.go, pcapng_test.go, reorder.go, reorder_test.go}` — new capture package (non-test files read & verified; tests not yet read).
- `/source/head/cmd/{capture.go, capture_test.go, context.go, inspect.go, inspect_interfaces.go, options.go, root.go, root_test.go}` — command layer (capture.go, context.go, root.go verified; options.go/root_test.go/inspect_interfaces.go diff-only).
- `/source/head/core/{capture.go, capture_local.go, capture_test.go, labruntime_cluster_test.go}` — core integration (capture.go, capture_local.go verified; cluster test partially seen in diff).
- `/source/head/labruntime/clabernetes/{capture.go, capture_interfaces.go, access.go, clabernetes.go, capture_test.go}` — c9s capture (impl files verified; capture_test.go partially seen via diff fakeClabwire harness).
- `/source/head/labruntime/runtime.go` — PacketCapturer/CaptureRequest/NodeRequest interface additions (diff tail 6410–6474 seen).
- `/source/cmd/root.go:163` — `log.SetOutput(os.Stderr)` (stdout purity for `-w -`).
- `/source/core/test_data/capture.clab.yml` — new test topology (seen in diff 3490–3510).
- `/source/docs/cmd/capture.md`, `/source/docs/cmd/inspect/interfaces.md`, `/source/docs/manual/clabernetes/runtime.md`, `/source/docs/manual/wireshark.md` — docs (capture.md read; others pending).
- `/source/.github/workflows/{clabernetes-tests.yml, smoke-tests.yml}` — CI changes verified (tshark install; `"33*.robot"`).
- `/source/mkdocs.yml` — nav entry for capture docs (not yet checked).
step-finish
{
  "type": "step-finish",
  "id": "prt_1965436dd001vJGgC495jAT4ll",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19653ff8f001spWXGnVQFRdXem",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 14196,
    "input": 10742,
    "output": 2904,
    "reasoning": 422,
    "cache": {
      "read": 128,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19653ff8f001spWXGnVQFRdXem",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523449743,
    "completed": 1793523463907
  },
  "parentID": "msg_19653ff7e001McEi21advBqMyE",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "compaction",
  "agent": "compaction",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "summary": true,
  "cost": 0,
  "tokens": {
    "total": 14196,
    "input": 10742,
    "output": 2904,
    "reasoning": 422,
    "cache": {
      "read": 128,
      "write": 0
    }
  },
  "finish": "stop"
}
User · 54
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_1965436e6001620KypTRi1ley5",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523463910
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 55
step-start
{
  "type": "step-start",
  "id": "prt_196543e42001wFaTuHzWrf1zH8",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965436f30019ghHotYqzFR5jH"
}
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 243,
  "offset": 6776
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
6776:  ${recovery-timeout}     180s
6777:  ${retry-interval}       5s
6778: +${capture-file}         /tmp/clab-c9s-capture.pcapng
6779: +${chain-file}           /tmp/clab-c9s-capture-chain.pcapng
6780: +${stop-file}            /tmp/clab-c9s-capture-stop.pcapng
6781: +${stop-err}             /tmp/clab-c9s-capture-stop.err
6782:  
6783:  
6784:  *** Test Cases ***
6785:  Deploy c9s linux lab
6786:      ${output} =    Run Clab Command    deploy -t ${topo}
6787: @@ -130,10 +134,157 @@ Graph renders from the topology file without a cluster
6788:  
6789:  Exec into client and verify dataplane
6790:      Wait Until Keyword Succeeds    60s    ${retry-interval}    Client Eth1 Should Be Visible
6791:      Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Succeed
6792:  
6793: +Inspect interfaces lists the link interfaces with their state
6794: +    ${output} =    Run Clab Command    inspect interfaces -t ${topo} -f json
6795: +    Should Be Equal As Integers    ${output.rc}    0
6796: +    ${containers} =    Evaluate    json.loads($output.stdout)    modules=json
6797: +    Length Should Be    ${containers}    2
6798: +    FOR    ${container}    IN    @{containers}
6799: +        Should Match Regexp    ${container}[name]    ^${lab-name}-(client|server)$
6800: +        Length Should Be    ${container}[interfaces]    1
6801: +        ${iface} =    Set Variable    ${container}[interfaces][0]
6802: +        Should Be Equal    ${iface}[name]    eth1
6803: +        Should Be Equal    ${iface}[type]    veth
6804: +        Should Be Equal    ${iface}[state]    up
6805: +        Should Match Regexp    ${iface}[mac]    ^([0-9a-f]{2}:){5}[0-9a-f]{2}$
6806: +        Should Be True    ${iface}[ifindex] > 0 and ${iface}[mtu] > 0
6807: +    END
6808: +
6809: +    ${one} =    Run Clab Command    inspect interfaces --name ${lab-name} -n client -f json
6810: +    Should Be Equal As Integers    ${one.rc}    0
6811: +    ${only} =    Evaluate    [c["name"] for c in json.loads($one.stdout)]    modules=json
6812: +    Should Be Equal    ${only}    ${{["${lab-name}-client"]}}
6813: +
6814: +Capture lists the capturable interfaces with their peers
6815: +    ${output} =    Run Clab Command    capture -t ${topo} --list -f json
6816: +    Should Be Equal As Integers    ${output.rc}    0
6817: +    ${interfaces} =    Evaluate    json.loads($output.stdout)    modules=json
6818: +    ${want} =    Evaluate
6819: +    ...    [{"node": "client", "interface": "eth1", "peer_node": "server", "peer_interface": "eth1"}, {"node": "server", "interface": "eth1", "peer_node": "client", "peer_interface": "eth1"}]
6820: +    Should Be Equal    ${interfaces}    ${want}
6821: +
6822: +Capture both ends of a link into one pcapng stream
6823: +    Skip If    not shutil.which("tshark")    tshark is not installed
6824: +    Remove File If Exists    ${capture-file}
6825: +    Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 10 -i 0.3 10.10.10.2'
6826: +    ...    shell=True    alias=c9s_ping
6827: +    ${output} =    Run Clab Command
6828: +    ...    capture -t ${topo} --target client:eth1 --target server:eth1 --duration 5s -w ${capture-file}
6829: +    Wait For Process    c9s_ping    timeout=30s
6830: +    Should Be Equal As Integers    ${output.rc}    0
6831: +
6832: +    ${idbs} =    Process.Run Process    capinfos -T -m -I ${capture-file}    shell=True
6833: +    Log    ${idbs.stdout}
6834: +    ${names} =    Process.Run Process
6835: +    ...    tshark -r ${capture-file} -T fields -e frame.interface_name -Y icmp | sort | uniq -c
6836: +    ...    shell=True
6837: +    Log    ${names.stdout}
6838: +    Should Be Equal As Integers    ${names.rc}    0
6839: +    ${counts} =    Evaluate
6840: +    ...    {l.split()[1]: int(l.split()[0]) for l in $names.stdout.splitlines() if l.strip()}
6841: +    Should Be Equal    ${{sorted($counts)}}    ${{["client:eth1", "server:eth1"]}}
6842: +    Should Be True    ${counts}[client:eth1] >= 10 and ${counts}[server:eth1] >= 10
6843: +
6844: +    ${info} =    Process.Run Process    capinfos ${capture-file}    shell=True
6845: +    Log    ${info.stdout}
6846: +    Should Contain    ${info.stdout}    Number of interfaces in file: 2
6847: +    Should Contain    ${info.stdout}    Capture application: containerlab
6848: +    Should Contain    ${info.stdout}    nanoseconds
6849: +
6850: +    # the packets of both nodes are merged in timestamp order
6851: +    ${times} =    Process.Run Process
6852: +    ...    tshark -r ${capture-file} -T fields -e frame.time_epoch
6853: +    ...    shell=True
6854: +    Should Be Equal As Integers    ${times.rc}    0
6855: +    ${epochs} =    Evaluate    [decimal.Decimal(x) for x in $times.stdout.split()]    modules=decimal
6856: +    ${count} =    Get Length    ${epochs}
6857: +    Should Be True    ${count} >= 20    only ${count} packets
6858: +    ${inversions} =    Evaluate
6859: +    ...    [(i, str($epochs[i - 1]), str($epochs[i])) for i in range(1, len($epochs)) if $epochs[i] < $epochs[i - 1]]
6860: +    Should Be Empty    ${inversions}    frame.time_epoch decreases
6861: +    [Teardown]    Remove File If Exists    ${capture-file}
6862: +
6863: +Stopping a capture leaves no capture process in clabwire
6864: +    Skip If    not shutil.which("docker")    docker is needed to list the processes of a KinD worker
6865: +    Skip If    not shutil.which("capinfos")    capinfos is not installed
6866: +    Remove File If Exists    ${stop-file}
6867: +    Start Process    ${CLAB_BIN}    --runtime    ${runtime}    capture    -t    ${topo}
6868: +    ...    --target    client:eth1    --target    server:eth1    -w    ${stop-file}
6869: +    ...    alias=c9s_capture    stderr=${stop-err}
6870: +    Wait Until Keyword Succeeds    60s    1s    Capture Process Should Run In Clabwire    client
6871: +    Wait Until Keyword Succeeds    10s    1s    Capture Process Should Run In Clabwire    server
6872: +
6873: +    Send Signal To Process    SIGINT    c9s_capture
6874: +    ${result} =    Wait For Process    c9s_capture    timeout=30s    on_timeout=kill
6875: +    Log    ${result.stderr}
6876: +    Should Be Equal As Integers    ${result.rc}    0
6877: +    # Kubernetes does not stop an exec'd process when its stream closes; clabwire ends the
6878: +    # capture when containerlab closes its stdin
6879: +    Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    client
6880: +    Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    server
6881: +
6882: +    ${info} =    Process.Run Process    capinfos ${stop-file}    shell=True
6883: +    Should Be Equal As Integers    ${info.rc}    0
6884: +    Should Contain    ${info.stdout}    Number of interfaces in file: 2
6885: +    [Teardown]    Run Keywords    Remove File If Exists    ${stop-file}
6886: +    ...    AND    Remove File If Exists    ${stop-err}
6887: +
6888: +Capture chains segments without duplicates or gaps
6889: +    Skip If    not shutil.which("tshark")    tshark is not installed
6890: +    Remove File If Exists    ${chain-file}
6891: +    Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 130 -i 0.2 10.10.10.2'
6892: +    ...    shell=True    alias=c9s_ping
6893: +    Sleep    1s
6894: +    # a 6 s segment length forces four switches in 20 s
6895: +    ${output} =    Process.Run Process
6896: +    ...    ${CLAB_BIN} --runtime ${runtime} --log-level debug capture -t ${topo} --target client:eth1 --duration 20s -w ${chain-file}
6897: +    ...    shell=True
6898: +    ...    env:CLAB_C9S_CAPTURE_SEGMENT=6s
6899: +    Log    ${output.stderr}
6900: +    Wait For Process    c9s_ping    timeout=60s
6901: +    Should Be Equal As Integers    ${output.rc}    0
6902: +    Should Contain    ${output.stderr}    segment=4
6903: +    Should Not Contain    ${output.stderr}    gap
6904: +
6905: +    ${seqs} =    Process.Run Process
6906: +    ...    tshark -r ${chain-file} -Y 'icmp.type \=\= 8' -T fields -e icmp.seq
6907: +    ...    shell=True
6908: +    Should Be Equal As Integers    ${seqs.rc}    0
6909: +    ${numbers} =    Evaluate    [int(x) for x in $seqs.stdout.split()]
6910: +    ${count} =    Get Length    ${numbers}
6911: +    Should Be True    ${count} >= 90    only ${count} echo requests
6912: +    ${unique} =    Evaluate    len(set($numbers))
6913: +    Should Be Equal As Integers    ${unique}    ${count}    duplicate echo requests
6914: +    ${span} =    Evaluate    max($numbers) - min($numbers) + 1
6915: +    Should Be Equal As Integers    ${span}    ${count}    missing echo requests
6916: +    [Teardown]    Remove File If Exists    ${chain-file}
6917: +
6918: +Capture works for a lab editor and is forbidden without a binding
6919: +    ${rbac} =    Process.Run Process
6920: +    ...    kubectl -n ${lab-namespace} create serviceaccount capture-editor && kubectl -n ${lab-namespace} create rolebinding capture-editor --clusterrole\=clabernetes-lab-editor --serviceaccount\=${lab-namespace}:capture-editor
6921: +    ...    shell=True
6922: +    Log    ${rbac.stdout}${\n}${rbac.stderr}
6923: +    Should Be Equal As Integers    ${rbac.rc}    0
6924: +
6925: +    ${result} =    Process.Run Process
6926: +    ...    go test ./core/ -run TestC9sClusterCapture -count\=1 -v
6927: +    ...    shell=True
6928: +    ...    cwd=${CURDIR}/../..
6929: +    ...    env:CLAB_C9S_TEST_LAB=${lab-name}
6930: +    ...    env:CLAB_C9S_TEST_CAPTURE_USER=system:serviceaccount:${lab-namespace}:capture-editor
6931: +    ...    env:CLAB_C9S_TEST_FORBIDDEN_USER=system:serviceaccount:${lab-namespace}:nobody
6932: +    Log    ${result.stdout}${\n}${result.stderr}    console=${True}
6933: +    Should Be Equal As Integers    ${result.rc}    0
6934: +    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/capture_both_ends_of_a_link
6935: +    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/restart_as_lab_editor
6936: +    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/forbidden_identity
6937: +    Should Not Contain    ${result.stdout}    SKIP
6938: +    Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed
6939: +
6940:  Logs shows the device container log
6941:      ${result} =    Run Clab Command    logs -t ${topo} -n client --tail 2 --timestamps
6942:      Should Be Equal As Integers    ${result.rc}    0
6943:      ${lines} =    Split To Lines    ${result.stdout}
6944:      ${count} =    Get Length    ${lines}
6945: @@ -411,10 +562,32 @@ Run Clab Command
6946:      ...    shell=True
6947:      Log    stdout:${\n}${output.stdout}    console=${True}
6948:      Log    stderr:${\n}${output.stderr}    console=${True}
6949:      RETURN    ${output}
6950:  
6951: +Clabwire Capture Processes
6952: +    [Arguments]    ${node}
6953: +    ${result} =    Process.Run Process
6954: +    ...    ${CURDIR}/clabwire-captures.sh ${lab-namespace} ${node}
6955: +    ...    shell=True
6956: +    Log    ${result.stdout}${\n}${result.stderr}
6957: +    Should Be Equal As Integers    ${result.rc}    0
6958: +    ${lines} =    Get Lines Containing String    ${result.stdout}    packet-capture
6959: +    ${count} =    Get Line Count    ${lines}
6960: +    RETURN    ${count}
6961: +
6962: +Capture Process Should Run In Clabwire
6963: +    [Arguments]    ${node}
6964: +    ${count} =    Clabwire Capture Processes    ${node}
6965: +    Should Be True    ${count} > 0    no packet-capture process in the clabwire container of ${node}
6966: +
6967: +No Capture Process Should Run In Clabwire
6968: +    [Arguments]    ${node}
6969: +    ${count} =    Clabwire Capture Processes    ${node}
6970: +    Should Be Equal As Integers    ${count}    0
6971: +    ...    ${count} packet-capture processes still run in the clabwire container of ${node}
6972: +
6973:  Ping From Client Should Succeed
6974:      ${output} =    Run Clab Command
6975:      ...    exec -t ${topo} --label ${client-label} --cmd 'ping -c 1 -W 2 10.10.10.2'
6976:      ${combined} =    Catenate    SEPARATOR=\n    ${output.stdout}    ${output.stderr}
6977:      Should Be Equal As Integers    ${output.rc}    0
6978: diff --git a/tests/14-clabernetes/clabwire-captures.sh b/tests/14-clabernetes/clabwire-captures.sh
6979: new file mode 100755
6980: index 0000000..14833b3
6981: --- /dev/null
6982: +++ b/tests/14-clabernetes/clabwire-captures.sh
6983: @@ -0,0 +1,35 @@
6984: +#!/bin/sh
6985: +# Prints the packet-capture processes running in the clabwire container of a c9s node's pod.
6986: +# usage: clabwire-captures.sh <namespace> <node>
6987: +#
6988: +# A process of a Kubernetes exec is not visible through the API, so this looks at the worker
6989: +# that runs the pod: a KinD node, which is a Docker container. It lists the processes whose
6990: +# cgroup belongs to the clabwire container. Exits 2 when the worker is not a Docker container.
6991: +set -eu
6992: +
6993: +namespace=$1
6994: +node=$2
6995: +
6996: +pod=$(kubectl -n "$namespace" get pod -l "c9s.run/topologyNode=$node" \
6997: +  -o jsonpath='{.items[0].metadata.name}')
6998: +worker=$(kubectl -n "$namespace" get pod "$pod" -o jsonpath='{.spec.nodeName}')
6999: +# clabwire is a sidecar (an init container that keeps running)
7000: +container=$(kubectl -n "$namespace" get pod "$pod" -o jsonpath=\
7001: +'{.status.initContainerStatuses[?(@.name=="clabwire")].containerID}{.status.containerStatuses[?(@.name=="clabwire")].containerID}')
7002: +container=${container#*://}
7003: +
7004: +if ! docker inspect --type container "$worker" >/dev/null 2>&1; then
7005: +  echo "worker $worker of pod $namespace/$pod is not a Docker container (KinD)" >&2
7006: +  exit 2
7007: +fi
7008: +if [ -z "$container" ]; then
7009: +  echo "pod $namespace/$pod has no running clabwire container" >&2
7010: +  exit 1
7011: +fi
7012: +
7013: +docker exec "$worker" sh -c "
7014: +  for proc in /proc/[0-9]*; do
7015: +    if grep -qs '$container' \"\$proc/cgroup\"; then
7016: +      tr '\\0' ' ' < \"\$proc/cmdline\" 2>/dev/null && echo
7017: +    fi
7018: +  done" | grep 'packet-capture' || true

(End of file - total 7018 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196543e90001C3P3Xj1J33GpIA",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965436f30019ghHotYqzFR5jH",
  "callID": "call_40e2b2ac3af2410a8c7a24db",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 243,
      "offset": 6776
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n6776:  ${recovery-timeout}     180s\n6777:  ${retry-interval}       5s\n6778: +${capture-file}         /tmp/clab-c9s-capture.pcapng\n6779: +${chain-file}           /tmp/clab-c9s-capture-chain.pcapng\n6780: +${stop-file}            /tmp/clab-c9s-capture-stop.pcapng\n6781: +${stop-err}             /tmp/clab-c9s-capture-stop.err\n6782:  \n6783:  \n6784:  *** Test Cases ***\n6785:  Deploy c9s linux lab\n6786:      ${output} =    Run Clab Command    deploy -t ${topo}\n6787: @@ -130,10 +134,157 @@ Graph renders from the topology file without a cluster\n6788:  \n6789:  Exec into client and verify dataplane\n6790:      Wait Until Keyword Succeeds    60s    ${retry-interval}    Client Eth1 Should Be Visible\n6791:      Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Succeed\n6792:  \n6793: +Inspect interfaces lists the link interfaces with their state\n6794: +    ${output} =    Run Clab Command    inspect interfaces -t ${topo} -f json\n6795: +    Should Be Equal As Integers    ${output.rc}    0\n6796: +    ${containers} =    Evaluate    json.loads($output.stdout)    modules=json\n6797: +    Length Should Be    ${containers}    2\n6798: +    FOR    ${container}    IN    @{containers}\n6799: +        Should Match Regexp    ${container}[name]    ^${lab-name}-(client|server)$\n6800: +        Length Should Be    ${container}[interfaces]    1\n6801: +        ${iface} =    Set Variable    ${container}[interfaces][0]\n6802: +        Should Be Equal    ${iface}[name]    eth1\n6803: +        Should Be Equal    ${iface}[type]    veth\n6804: +        Should Be Equal    ${iface}[state]    up\n6805: +        Should Match Regexp    ${iface}[mac]    ^([0-9a-f]{2}:){5}[0-9a-f]{2}$\n6806: +        Should Be True    ${iface}[ifindex] > 0 and ${iface}[mtu] > 0\n6807: +    END\n6808: +\n6809: +    ${one} =    Run Clab Command    inspect interfaces --name ${lab-name} -n client -f json\n6810: +    Should Be Equal As Integers    ${one.rc}    0\n6811: +    ${only} =    Evaluate    [c[\"name\"] for c in json.loads($one.stdout)]    modules=json\n6812: +    Should Be Equal    ${only}    ${{[\"${lab-name}-client\"]}}\n6813: +\n6814: +Capture lists the capturable interfaces with their peers\n6815: +    ${output} =    Run Clab Command    capture -t ${topo} --list -f json\n6816: +    Should Be Equal As Integers    ${output.rc}    0\n6817: +    ${interfaces} =    Evaluate    json.loads($output.stdout)    modules=json\n6818: +    ${want} =    Evaluate\n6819: +    ...    [{\"node\": \"client\", \"interface\": \"eth1\", \"peer_node\": \"server\", \"peer_interface\": \"eth1\"}, {\"node\": \"server\", \"interface\": \"eth1\", \"peer_node\": \"client\", \"peer_interface\": \"eth1\"}]\n6820: +    Should Be Equal    ${interfaces}    ${want}\n6821: +\n6822: +Capture both ends of a link into one pcapng stream\n6823: +    Skip If    not shutil.which(\"tshark\")    tshark is not installed\n6824: +    Remove File If Exists    ${capture-file}\n6825: +    Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 10 -i 0.3 10.10.10.2'\n6826: +    ...    shell=True    alias=c9s_ping\n6827: +    ${output} =    Run Clab Command\n6828: +    ...    capture -t ${topo} --target client:eth1 --target server:eth1 --duration 5s -w ${capture-file}\n6829: +    Wait For Process    c9s_ping    timeout=30s\n6830: +    Should Be Equal As Integers    ${output.rc}    0\n6831: +\n6832: +    ${idbs} =    Process.Run Process    capinfos -T -m -I ${capture-file}    shell=True\n6833: +    Log    ${idbs.stdout}\n6834: +    ${names} =    Process.Run Process\n6835: +    ...    tshark -r ${capture-file} -T fields -e frame.interface_name -Y icmp | sort | uniq -c\n6836: +    ...    shell=True\n6837: +    Log    ${names.stdout}\n6838: +    Should Be Equal As Integers    ${names.rc}    0\n6839: +    ${counts} =    Evaluate\n6840: +    ...    {l.split()[1]: int(l.split()[0]) for l in $names.stdout.splitlines() if l.strip()}\n6841: +    Should Be Equal    ${{sorted($counts)}}    ${{[\"client:eth1\", \"server:eth1\"]}}\n6842: +    Should Be True    ${counts}[client:eth1] >= 10 and ${counts}[server:eth1] >= 10\n6843: +\n6844: +    ${info} =    Process.Run Process    capinfos ${capture-file}    shell=True\n6845: +    Log    ${info.stdout}\n6846: +    Should Contain    ${info.stdout}    Number of interfaces in file: 2\n6847: +    Should Contain    ${info.stdout}    Capture application: containerlab\n6848: +    Should Contain    ${info.stdout}    nanoseconds\n6849: +\n6850: +    # the packets of both nodes are merged in timestamp order\n6851: +    ${times} =    Process.Run Process\n6852: +    ...    tshark -r ${capture-file} -T fields -e frame.time_epoch\n6853: +    ...    shell=True\n6854: +    Should Be Equal As Integers    ${times.rc}    0\n6855: +    ${epochs} =    Evaluate    [decimal.Decimal(x) for x in $times.stdout.split()]    modules=decimal\n6856: +    ${count} =    Get Length    ${epochs}\n6857: +    Should Be True    ${count} >= 20    only ${count} packets\n6858: +    ${inversions} =    Evaluate\n6859: +    ...    [(i, str($epochs[i - 1]), str($epochs[i])) for i in range(1, len($epochs)) if $epochs[i] < $epochs[i - 1]]\n6860: +    Should Be Empty    ${inversions}    frame.time_epoch decreases\n6861: +    [Teardown]    Remove File If Exists    ${capture-file}\n6862: +\n6863: +Stopping a capture leaves no capture process in clabwire\n6864: +    Skip If    not shutil.which(\"docker\")    docker is needed to list the processes of a KinD worker\n6865: +    Skip If    not shutil.which(\"capinfos\")    capinfos is not installed\n6866: +    Remove File If Exists    ${stop-file}\n6867: +    Start Process    ${CLAB_BIN}    --runtime    ${runtime}    capture    -t    ${topo}\n6868: +    ...    --target    client:eth1    --target    server:eth1    -w    ${stop-file}\n6869: +    ...    alias=c9s_capture    stderr=${stop-err}\n6870: +    Wait Until Keyword Succeeds    60s    1s    Capture Process Should Run In Clabwire    client\n6871: +    Wait Until Keyword Succeeds    10s    1s    Capture Process Should Run In Clabwire    server\n6872: +\n6873: +    Send Signal To Process    SIGINT    c9s_capture\n6874: +    ${result} =    Wait For Process    c9s_capture    timeout=30s    on_timeout=kill\n6875: +    Log    ${result.stderr}\n6876: +    Should Be Equal As Integers    ${result.rc}    0\n6877: +    # Kubernetes does not stop an exec'd process when its stream closes; clabwire ends the\n6878: +    # capture when containerlab closes its stdin\n6879: +    Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    client\n6880: +    Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    server\n6881: +\n6882: +    ${info} =    Process.Run Process    capinfos ${stop-file}    shell=True\n6883: +    Should Be Equal As Integers    ${info.rc}    0\n6884: +    Should Contain    ${info.stdout}    Number of interfaces in file: 2\n6885: +    [Teardown]    Run Keywords    Remove File If Exists    ${stop-file}\n6886: +    ...    AND    Remove File If Exists    ${stop-err}\n6887: +\n6888: +Capture chains segments without duplicates or gaps\n6889: +    Skip If    not shutil.which(\"tshark\")    tshark is not installed\n6890: +    Remove File If Exists    ${chain-file}\n6891: +    Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 130 -i 0.2 10.10.10.2'\n6892: +    ...    shell=True    alias=c9s_ping\n6893: +    Sleep    1s\n6894: +    # a 6 s segment length forces four switches in 20 s\n6895: +    ${output} =    Process.Run Process\n6896: +    ...    ${CLAB_BIN} --runtime ${runtime} --log-level debug capture -t ${topo} --target client:eth1 --duration 20s -w ${chain-file}\n6897: +    ...    shell=True\n6898: +    ...    env:CLAB_C9S_CAPTURE_SEGMENT=6s\n6899: +    Log    ${output.stderr}\n6900: +    Wait For Process    c9s_ping    timeout=60s\n6901: +    Should Be Equal As Integers    ${output.rc}    0\n6902: +    Should Contain    ${output.stderr}    segment=4\n6903: +    Should Not Contain    ${output.stderr}    gap\n6904: +\n6905: +    ${seqs} =    Process.Run Process\n6906: +    ...    tshark -r ${chain-file} -Y 'icmp.type \\=\\= 8' -T fields -e icmp.seq\n6907: +    ...    shell=True\n6908: +    Should Be Equal As Integers    ${seqs.rc}    0\n6909: +    ${numbers} =    Evaluate    [int(x) for x in $seqs.stdout.split()]\n6910: +    ${count} =    Get Length    ${numbers}\n6911: +    Should Be True    ${count} >= 90    only ${count} echo requests\n6912: +    ${unique} =    Evaluate    len(set($numbers))\n6913: +    Should Be Equal As Integers    ${unique}    ${count}    duplicate echo requests\n6914: +    ${span} =    Evaluate    max($numbers) - min($numbers) + 1\n6915: +    Should Be Equal As Integers    ${span}    ${count}    missing echo requests\n6916: +    [Teardown]    Remove File If Exists    ${chain-file}\n6917: +\n6918: +Capture works for a lab editor and is forbidden without a binding\n6919: +    ${rbac} =    Process.Run Process\n6920: +    ...    kubectl -n ${lab-namespace} create serviceaccount capture-editor && kubectl -n ${lab-namespace} create rolebinding capture-editor --clusterrole\\=clabernetes-lab-editor --serviceaccount\\=${lab-namespace}:capture-editor\n6921: +    ...    shell=True\n6922: +    Log    ${rbac.stdout}${\\n}${rbac.stderr}\n6923: +    Should Be Equal As Integers    ${rbac.rc}    0\n6924: +\n6925: +    ${result} =    Process.Run Process\n6926: +    ...    go test ./core/ -run TestC9sClusterCapture -count\\=1 -v\n6927: +    ...    shell=True\n6928: +    ...    cwd=${CURDIR}/../..\n6929: +    ...    env:CLAB_C9S_TEST_LAB=${lab-name}\n6930: +    ...    env:CLAB_C9S_TEST_CAPTURE_USER=system:serviceaccount:${lab-namespace}:capture-editor\n6931: +    ...    env:CLAB_C9S_TEST_FORBIDDEN_USER=system:serviceaccount:${lab-namespace}:nobody\n6932: +    Log    ${result.stdout}${\\n}${result.stderr}    console=${True}\n6933: +    Should Be Equal As Integers    ${result.rc}    0\n6934: +    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/capture_both_ends_of_a_link\n6935: +    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/restart_as_lab_editor\n6936: +    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/forbidden_identity\n6937: +    Should Not Contain    ${result.stdout}    SKIP\n6938: +    Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n6939: +\n6940:  Logs shows the device container log\n6941:      ${result} =    Run Clab Command    logs -t ${topo} -n client --tail 2 --timestamps\n6942:      Should Be Equal As Integers    ${result.rc}    0\n6943:      ${lines} =    Split To Lines    ${result.stdout}\n6944:      ${count} =    Get Length    ${lines}\n6945: @@ -411,10 +562,32 @@ Run Clab Command\n6946:      ...    shell=True\n6947:      Log    stdout:${\\n}${output.stdout}    console=${True}\n6948:      Log    stderr:${\\n}${output.stderr}    console=${True}\n6949:      RETURN    ${output}\n6950:  \n6951: +Clabwire Capture Processes\n6952: +    [Arguments]    ${node}\n6953: +    ${result} =    Process.Run Process\n6954: +    ...    ${CURDIR}/clabwire-captures.sh ${lab-namespace} ${node}\n6955: +    ...    shell=True\n6956: +    Log    ${result.stdout}${\\n}${result.stderr}\n6957: +    Should Be Equal As Integers    ${result.rc}    0\n6958: +    ${lines} =    Get Lines Containing String    ${result.stdout}    packet-capture\n6959: +    ${count} =    Get Line Count    ${lines}\n6960: +    RETURN    ${count}\n6961: +\n6962: +Capture Process Should Run In Clabwire\n6963: +    [Arguments]    ${node}\n6964: +    ${count} =    Clabwire Capture Processes    ${node}\n6965: +    Should Be True    ${count} > 0    no packet-capture process in the clabwire container of ${node}\n6966: +\n6967: +No Capture Process Should Run In Clabwire\n6968: +    [Arguments]    ${node}\n6969: +    ${count} =    Clabwire Capture Processes    ${node}\n6970: +    Should Be Equal As Integers    ${count}    0\n6971: +    ...    ${count} packet-capture processes still run in the clabwire container of ${node}\n6972: +\n6973:  Ping From Client Should Succeed\n6974:      ${output} =    Run Clab Command\n6975:      ...    exec -t ${topo} --label ${client-label} --cmd 'ping -c 1 -W 2 10.10.10.2'\n6976:      ${combined} =    Catenate    SEPARATOR=\\n    ${output.stdout}    ${output.stderr}\n6977:      Should Be Equal As Integers    ${output.rc}    0\n6978: diff --git a/tests/14-clabernetes/clabwire-captures.sh b/tests/14-clabernetes/clabwire-captures.sh\n6979: new file mode 100755\n6980: index 0000000..14833b3\n6981: --- /dev/null\n6982: +++ b/tests/14-clabernetes/clabwire-captures.sh\n6983: @@ -0,0 +1,35 @@\n6984: +#!/bin/sh\n6985: +# Prints the packet-capture processes running in the clabwire container of a c9s node's pod.\n6986: +# usage: clabwire-captures.sh <namespace> <node>\n6987: +#\n6988: +# A process of a Kubernetes exec is not visible through the API, so this looks at the worker\n6989: +# that runs the pod: a KinD node, which is a Docker container. It lists the processes whose\n6990: +# cgroup belongs to the clabwire container. Exits 2 when the worker is not a Docker container.\n6991: +set -eu\n6992: +\n6993: +namespace=$1\n6994: +node=$2\n6995: +\n6996: +pod=$(kubectl -n \"$namespace\" get pod -l \"c9s.run/topologyNode=$node\" \\\n6997: +  -o jsonpath='{.items[0].metadata.name}')\n6998: +worker=$(kubectl -n \"$namespace\" get pod \"$pod\" -o jsonpath='{.spec.nodeName}')\n6999: +# clabwire is a sidecar (an init container that keeps running)\n7000: +container=$(kubectl -n \"$namespace\" get pod \"$pod\" -o jsonpath=\\\n7001: +'{.status.initContainerStatuses[?(@.name==\"clabwire\")].containerID}{.status.containerStatuses[?(@.name==\"clabwire\")].containerID}')\n7002: +container=${container#*://}\n7003: +\n7004: +if ! docker inspect --type container \"$worker\" >/dev/null 2>&1; then\n7005: +  echo \"worker $worker of pod $namespace/$pod is not a Docker container (KinD)\" >&2\n7006: +  exit 2\n7007: +fi\n7008: +if [ -z \"$container\" ]; then\n7009: +  echo \"pod $namespace/$pod has no running clabwire container\" >&2\n7010: +  exit 1\n7011: +fi\n7012: +\n7013: +docker exec \"$worker\" sh -c \"\n7014: +  for proc in /proc/[0-9]*; do\n7015: +    if grep -qs '$container' \\\"\\$proc/cgroup\\\"; then\n7016: +      tr '\\\\0' ' ' < \\\"\\$proc/cmdline\\\" 2>/dev/null && echo\n7017: +    fi\n7018: +  done\" | grep 'packet-capture' || true\n\n(End of file - total 7018 lines)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": " ${recovery-timeout}     180s\n ${retry-interval}       5s\n+${capture-file}         /tmp/clab-c9s-capture.pcapng\n+${chain-file}           /tmp/clab-c9s-capture-chain.pcapng\n+${stop-file}            /tmp/clab-c9s-capture-stop.pcapng\n+${stop-err}             /tmp/clab-c9s-capture-stop.err\n \n \n *** Test Cases ***\n Deploy c9s linux lab\n     ${output} =    Run Clab Command    deploy -t ${topo}\n@@ -130,10 +134,157 @@ Graph renders from the topology file without a cluster\n \n Exec into client and verify dataplane\n     Wait Until Keyword Succeeds    60s    ${retry-interval}    Client Eth1 Should Be Visible\n     Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Succeed\n \n+Inspect interfaces lists the link interfaces with their state\n+    ${output} =    Run Clab Command    inspect interfaces -t ${topo} -f json\n+    Should Be Equal As Integers    ${output.rc}    0",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": " ${recovery-timeout}     180s\n ${retry-interval}       5s\n+${capture-file}         /tmp/clab-c9s-capture.pcapng\n+${chain-file}           /tmp/clab-c9s-capture-chain.pcapng\n+${stop-file}            /tmp/clab-c9s-capture-stop.pcapng\n+${stop-err}             /tmp/clab-c9s-capture-stop.err\n \n \n *** Test Cases ***\n Deploy c9s linux lab\n     ${output} =    Run Clab Command    deploy -t ${topo}\n@@ -130,10 +134,157 @@ Graph renders from the topology file without a cluster\n \n Exec into client and verify dataplane\n     Wait Until Keyword Succeeds    60s    ${retry-interval}    Client Eth1 Should Be Visible\n     Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Succeed\n \n+Inspect interfaces lists the link interfaces with their state\n+    ${output} =    Run Clab Command    inspect interfaces -t ${topo} -f json\n+    Should Be Equal As Integers    ${output.rc}    0\n+    ${containers} =    Evaluate    json.loads($output.stdout)    modules=json\n+    Length Should Be    ${containers}    2\n+    FOR    ${container}    IN    @{containers}\n+        Should Match Regexp    ${container}[name]    ^${lab-name}-(client|server)$\n+        Length Should Be    ${container}[interfaces]    1\n+        ${iface} =    Set Variable    ${container}[interfaces][0]\n+        Should Be Equal    ${iface}[name]    eth1\n+        Should Be Equal    ${iface}[type]    veth\n+        Should Be Equal    ${iface}[state]    up\n+        Should Match Regexp    ${iface}[mac]    ^([0-9a-f]{2}:){5}[0-9a-f]{2}$\n+        Should Be True    ${iface}[ifindex] > 0 and ${iface}[mtu] > 0\n+    END\n+\n+    ${one} =    Run Clab Command    inspect interfaces --name ${lab-name} -n client -f json\n+    Should Be Equal As Integers    ${one.rc}    0\n+    ${only} =    Evaluate    [c[\"name\"] for c in json.loads($one.stdout)]    modules=json\n+    Should Be Equal    ${only}    ${{[\"${lab-name}-client\"]}}\n+\n+Capture lists the capturable interfaces with their peers\n+    ${output} =    Run Clab Command    capture -t ${topo} --list -f json\n+    Should Be Equal As Integers    ${output.rc}    0\n+    ${interfaces} =    Evaluate    json.loads($output.stdout)    modules=json\n+    ${want} =    Evaluate\n+    ...    [{\"node\": \"client\", \"interface\": \"eth1\", \"peer_node\": \"server\", \"peer_interface\": \"eth1\"}, {\"node\": \"server\", \"interface\": \"eth1\", \"peer_node\": \"client\", \"peer_interface\": \"eth1\"}]\n+    Should Be Equal    ${interfaces}    ${want}\n+\n+Capture both ends of a link into one pcapng stream\n+    Skip If    not shutil.which(\"tshark\")    tshark is not installed\n+    Remove File If Exists    ${capture-file}\n+    Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 10 -i 0.3 10.10.10.2'\n+    ...    shell=True    alias=c9s_ping\n+    ${output} =    Run Clab Command\n+    ...    capture -t ${topo} --target client:eth1 --target server:eth1 --duration 5s -w ${capture-file}\n+    Wait For Process    c9s_ping    timeout=30s\n+    Should Be Equal As Integers    ${output.rc}    0\n+\n+    ${idbs} =    Process.Run Process    capinfos -T -m -I ${capture-file}    shell=True\n+    Log    ${idbs.stdout}\n+    ${names} =    Process.Run Process\n+    ...    tshark -r ${capture-file} -T fields -e frame.interface_name -Y icmp | sort | uniq -c\n+    ...    shell=True\n+    Log    ${names.stdout}\n+    Should Be Equal As Integers    ${names.rc}    0\n+    ${counts} =    Evaluate\n+    ...    {l.split()[1]: int(l.split()[0]) for l in $names.stdout.splitlines() if l.strip()}\n+    Should Be Equal    ${{sorted($counts)}}    ${{[\"client:eth1\", \"server:eth1\"]}}\n+    Should Be True    ${counts}[client:eth1] >= 10 and ${counts}[server:eth1] >= 10\n+\n+    ${info} =    Process.Run Process    capinfos ${capture-file}    shell=True\n+    Log    ${info.stdout}\n+    Should Contain    ${info.stdout}    Number of interfaces in file: 2\n+    Should Contain    ${info.stdout}    Capture application: containerlab\n+    Should Contain    ${info.stdout}    nanoseconds\n+\n+    # the packets of both nodes are merged in timestamp order\n+    ${times} =    Process.Run Process\n+    ...    tshark -r ${capture-file} -T fields -e frame.time_epoch\n+    ...    shell=True\n+    Should Be Equal As Integers    ${times.rc}    0\n+    ${epochs} =    Evaluate    [decimal.Decimal(x) for x in $times.stdout.split()]    modules=decimal\n+    ${count} =    Get Length    ${epochs}\n+    Should Be True    ${count} >= 20    only ${count} packets\n+    ${inversions} =    Evaluate\n+    ...    [(i, str($epochs[i - 1]), str($epochs[i])) for i in range(1, len($epochs)) if $epochs[i] < $epochs[i - 1]]\n+    Should Be Empty    ${inversions}    frame.time_epoch decreases\n+    [Teardown]    Remove File If Exists    ${capture-file}\n+\n+Stopping a capture leaves no capture process in clabwire\n+    Skip If    not shutil.which(\"docker\")    docker is needed to list the processes of a KinD worker\n+    Skip If    not shutil.which(\"capinfos\")    capinfos is not installed\n+    Remove File If Exists    ${stop-file}\n+    Start Process    ${CLAB_BIN}    --runtime    ${runtime}    capture    -t    ${topo}\n+    ...    --target    client:eth1    --target    server:eth1    -w    ${stop-file}\n+    ...    alias=c9s_capture    stderr=${stop-err}\n+    Wait Until Keyword Succeeds    60s    1s    Capture Process Should Run In Clabwire    client\n+    Wait Until Keyword Succeeds    10s    1s    Capture Process Should Run In Clabwire    server\n+\n+    Send Signal To Process    SIGINT    c9s_capture\n+    ${result} =    Wait For Process    c9s_capture    timeout=30s    on_timeout=kill\n+    Log    ${result.stderr}\n+    Should Be Equal As Integers    ${result.rc}    0\n+    # Kubernetes does not stop an exec'd process when its stream closes; clabwire ends the\n+    # capture when containerlab closes its stdin\n+    Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    client\n+    Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    server\n+\n+    ${info} =    Process.Run Process    capinfos ${stop-file}    shell=True\n+    Should Be Equal As Integers    ${info.rc}    0\n+    Should Contain    ${info.stdout}    Number of interfaces in file: 2\n+    [Teardown]    Run Keywords    Remove File If Exists    ${stop-file}\n+    ...    AND    Remove File If Exists    ${stop-err}\n+\n+Capture chains segments without duplicates or gaps\n+    Skip If    not shutil.which(\"tshark\")    tshark is not installed\n+    Remove File If Exists    ${chain-file}\n+    Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 130 -i 0.2 10.10.10.2'\n+    ...    shell=True    alias=c9s_ping\n+    Sleep    1s\n+    # a 6 s segment length forces four switches in 20 s\n+    ${output} =    Process.Run Process\n+    ...    ${CLAB_BIN} --runtime ${runtime} --log-level debug capture -t ${topo} --target client:eth1 --duration 20s -w ${chain-file}\n+    ...    shell=True\n+    ...    env:CLAB_C9S_CAPTURE_SEGMENT=6s\n+    Log    ${output.stderr}\n+    Wait For Process    c9s_ping    timeout=60s\n+    Should Be Equal As Integers    ${output.rc}    0\n+    Should Contain    ${output.stderr}    segment=4\n+    Should Not Contain    ${output.stderr}    gap\n+\n+    ${seqs} =    Process.Run Process\n+    ...    tshark -r ${chain-file} -Y 'icmp.type \\=\\= 8' -T fields -e icmp.seq\n+    ...    shell=True\n+    Should Be Equal As Integers    ${seqs.rc}    0\n+    ${numbers} =    Evaluate    [int(x) for x in $seqs.stdout.split()]\n+    ${count} =    Get Length    ${numbers}\n+    Should Be True    ${count} >= 90    only ${count} echo requests\n+    ${unique} =    Evaluate    len(set($numbers))\n+    Should Be Equal As Integers    ${unique}    ${count}    duplicate echo requests\n+    ${span} =    Evaluate    max($numbers) - min($numbers) + 1\n+    Should Be Equal As Integers    ${span}    ${count}    missing echo requests\n+    [Teardown]    Remove File If Exists    ${chain-file}\n+\n+Capture works for a lab editor and is forbidden without a binding\n+    ${rbac} =    Process.Run Process\n+    ...    kubectl -n ${lab-namespace} create serviceaccount capture-editor && kubectl -n ${lab-namespace} create rolebinding capture-editor --clusterrole\\=clabernetes-lab-editor --serviceaccount\\=${lab-namespace}:capture-editor\n+    ...    shell=True\n+    Log    ${rbac.stdout}${\\n}${rbac.stderr}\n+    Should Be Equal As Integers    ${rbac.rc}    0\n+\n+    ${result} =    Process.Run Process\n+    ...    go test ./core/ -run TestC9sClusterCapture -count\\=1 -v\n+    ...    shell=True\n+    ...    cwd=${CURDIR}/../..\n+    ...    env:CLAB_C9S_TEST_LAB=${lab-name}\n+    ...    env:CLAB_C9S_TEST_CAPTURE_USER=system:serviceaccount:${lab-namespace}:capture-editor\n+    ...    env:CLAB_C9S_TEST_FORBIDDEN_USER=system:serviceaccount:${lab-namespace}:nobody\n+    Log    ${result.stdout}${\\n}${result.stderr}    console=${True}\n+    Should Be Equal As Integers    ${result.rc}    0\n+    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/capture_both_ends_of_a_link\n+    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/restart_as_lab_editor\n+    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/forbidden_identity\n+    Should Not Contain    ${result.stdout}    SKIP\n+    Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n+\n Logs shows the device container log\n     ${result} =    Run Clab Command    logs -t ${topo} -n client --tail 2 --timestamps\n     Should Be Equal As Integers    ${result.rc}    0\n     ${lines} =    Split To Lines    ${result.stdout}\n     ${count} =    Get Length    ${lines}\n@@ -411,10 +562,32 @@ Run Clab Command\n     ...    shell=True\n     Log    stdout:${\\n}${output.stdout}    console=${True}\n     Log    stderr:${\\n}${output.stderr}    console=${True}\n     RETURN    ${output}\n \n+Clabwire Capture Processes\n+    [Arguments]    ${node}\n+    ${result} =    Process.Run Process\n+    ...    ${CURDIR}/clabwire-captures.sh ${lab-namespace} ${node}\n+    ...    shell=True\n+    Log    ${result.stdout}${\\n}${result.stderr}\n+    Should Be Equal As Integers    ${result.rc}    0\n+    ${lines} =    Get Lines Containing String    ${result.stdout}    packet-capture\n+    ${count} =    Get Line Count    ${lines}\n+    RETURN    ${count}\n+\n+Capture Process Should Run In Clabwire\n+    [Arguments]    ${node}\n+    ${count} =    Clabwire Capture Processes    ${node}\n+    Should Be True    ${count} > 0    no packet-capture process in the clabwire container of ${node}\n+\n+No Capture Process Should Run In Clabwire\n+    [Arguments]    ${node}\n+    ${count} =    Clabwire Capture Processes    ${node}\n+    Should Be Equal As Integers    ${count}    0\n+    ...    ${count} packet-capture processes still run in the clabwire container of ${node}\n+\n Ping From Client Should Succeed\n     ${output} =    Run Clab Command\n     ...    exec -t ${topo} --label ${client-label} --cmd 'ping -c 1 -W 2 10.10.10.2'\n     ${combined} =    Catenate    SEPARATOR=\\n    ${output.stdout}    ${output.stderr}\n     Should Be Equal As Integers    ${output.rc}    0\ndiff --git a/tests/14-clabernetes/clabwire-captures.sh b/tests/14-clabernetes/clabwire-captures.sh\nnew file mode 100755\nindex 0000000..14833b3\n--- /dev/null\n+++ b/tests/14-clabernetes/clabwire-captures.sh\n@@ -0,0 +1,35 @@\n+#!/bin/sh\n+# Prints the packet-capture processes running in the clabwire container of a c9s node's pod.\n+# usage: clabwire-captures.sh <namespace> <node>\n+#\n+# A process of a Kubernetes exec is not visible through the API, so this looks at the worker\n+# that runs the pod: a KinD node, which is a Docker container. It lists the processes whose\n+# cgroup belongs to the clabwire container. Exits 2 when the worker is not a Docker container.\n+set -eu\n+\n+namespace=$1\n+node=$2\n+\n+pod=$(kubectl -n \"$namespace\" get pod -l \"c9s.run/topologyNode=$node\" \\\n+  -o jsonpath='{.items[0].metadata.name}')\n+worker=$(kubectl -n \"$namespace\" get pod \"$pod\" -o jsonpath='{.spec.nodeName}')\n+# clabwire is a sidecar (an init container that keeps running)\n+container=$(kubectl -n \"$namespace\" get pod \"$pod\" -o jsonpath=\\\n+'{.status.initContainerStatuses[?(@.name==\"clabwire\")].containerID}{.status.containerStatuses[?(@.name==\"clabwire\")].containerID}')\n+container=${container#*://}\n+\n+if ! docker inspect --type container \"$worker\" >/dev/null 2>&1; then\n+  echo \"worker $worker of pod $namespace/$pod is not a Docker container (KinD)\" >&2\n+  exit 2\n+fi\n+if [ -z \"$container\" ]; then\n+  echo \"pod $namespace/$pod has no running clabwire container\" >&2\n+  exit 1\n+fi\n+\n+docker exec \"$worker\" sh -c \"\n+  for proc in /proc/[0-9]*; do\n+    if grep -qs '$container' \\\"\\$proc/cgroup\\\"; then\n+      tr '\\\\0' ' ' < \\\"\\$proc/cmdline\\\" 2>/dev/null && echo\n+    fi\n+  done\" | grep 'packet-capture' || true",
        "lineStart": 6776,
        "lineEnd": 7018,
        "totalLines": 7018,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523465879,
      "end": 1793523465910
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196543eb9001gvSjTeWh9SROP8",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965436f30019ghHotYqzFR5jH",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 16849,
    "input": 13876,
    "output": 28,
    "reasoning": 1,
    "cache": {
      "read": 2944,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1965436f30019ghHotYqzFR5jH",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523463923,
    "completed": 1793523465918
  },
  "parentID": "msg_1965436e6001620KypTRi1ley5",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 16849,
    "input": 13876,
    "output": 28,
    "reasoning": 1,
    "cache": {
      "read": 2944,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 56
step-start
{
  "type": "step-start",
  "id": "prt_1965445880013QdweB6rSoaD5f",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196543ecb001f61Y3euhR027F8"
}
Reasoning
The diff is fully traversed now (1–7018). Remaining head files not yet read directly: capture package tests, cmd/capture_test.go, cmd/options.go, cmd/root_test.go, cmd/inspect_interfaces.go, core/capture_test.go, docs files (wireshark.md, clabernetes/runtime.md, inspect/interfaces.md), mkdocs.yml (seen in diff — nav entry added). Let me now skim the capture package tests to check coverage, and quickly check remaining docs. Then finalize.

Let me read capture tests in parallel.
The diff is now fully traversed (all 7018 lines). Remaining checks: skim the new unit tests, remaining docs, and a couple of head files I haven't read directly, then finalize the review.
read · completed

Input

{
  "filePath": "/source/head/capture/local_test.go",
  "limit": 2000
}

Output

<path>/source/head/capture/local_test.go</path>
<type>file</type>
<content>
1: package capture
2: 
3: import (
4: 	"bytes"
5: 	"context"
6: 	"errors"
7: 	"fmt"
8: 	"io"
9: 	"slices"
10: 	"strings"
11: 	"sync"
12: 	"testing"
13: 	"time"
14: 
15: 	"github.com/containernetworking/plugins/pkg/ns"
16: 	"github.com/gopacket/gopacket"
17: 	"github.com/gopacket/gopacket/afpacket"
18: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
19: )
20: 
21: // fakeFrame is one packet a fake source returns.
22: type fakeFrame struct {
23: 	data   []byte
24: 	stamp  time.Time
25: 	length int
26: 	vlan   bool
27: 	// visible delays the frame like a ring block the kernel has not handed over yet.
28: 	visible time.Time
29: 	// err ends the source with this error instead of a packet.
30: 	err error
31: }
32: 
33: // fakeSource returns frames from a channel, errReadTimeout while none is queued.
34: type fakeSource struct {
35: 	frames  chan fakeFrame
36: 	closed  chan struct{}
37: 	once    sync.Once
38: 	pending *fakeFrame
39: }
40: 
41: func newFakeSource() *fakeSource {
42: 	return &fakeSource{frames: make(chan fakeFrame, 64), closed: make(chan struct{})}
43: }
44: 
45: func (s *fakeSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {
46: 	if s.pending == nil {
47: 		select {
48: 		case frame := <-s.frames:
49: 			s.pending = &frame
50: 		case <-time.After(5 * time.Millisecond):
51: 			return nil, gopacket.CaptureInfo{}, errReadTimeout
52: 		}
53: 	}
54: 	if wait := time.Until(s.pending.visible); wait > 0 {
55: 		time.Sleep(min(wait, 5*time.Millisecond))
56: 		if time.Now().Before(s.pending.visible) {
57: 			return nil, gopacket.CaptureInfo{}, errReadTimeout
58: 		}
59: 	}
60: 
61: 	{
62: 		frame := *s.pending
63: 		s.pending = nil
64: 		if frame.err != nil {
65: 			return nil, gopacket.CaptureInfo{}, frame.err
66: 		}
67: 		info := gopacket.CaptureInfo{
68: 			Timestamp: frame.stamp, CaptureLength: len(frame.data), Length: frame.length,
69: 		}
70: 		if frame.vlan {
71: 			info.AncillaryData = []any{afpacket.AncillaryVLAN{VLAN: 10}}
72: 		}
73: 
74: 		return frame.data, info, nil
75: 	}
76: }
77: 
78: func (s *fakeSource) Close() {
79: 	s.once.Do(func() { close(s.closed) })
80: }
81: 
82: // fakeHost hands out fake sources per node and interface. Opening an interface listed in
83: // missing fails, like an interface whose node does not run.
84: type fakeHost struct {
85: 	mu      sync.Mutex
86: 	opened  map[string][]*fakeSource
87: 	missing map[string]bool
88: 	ready   chan string
89: }
90: 
91: func newFakeHost() *fakeHost {
92: 	return &fakeHost{
93: 		opened: map[string][]*fakeSource{}, missing: map[string]bool{},
94: 		ready: make(chan string, 64),
95: 	}
96: }
97: 
98: func (h *fakeHost) exec(node string) ExecFunc {
99: 	return func(_ context.Context, f func(ns.NetNS) error) error {
100: 		h.mu.Lock()
101: 		missing := h.missing[node]
102: 		h.mu.Unlock()
103: 		if missing {
104: 			return fmt.Errorf("node %q: container network namespace is not available", node)
105: 		}
106: 
107: 		return f(nil)
108: 	}
109: }
110: 
111: func (h *fakeHost) open(
112: 	ctx context.Context,
113: 	exec ExecFunc,
114: 	interfaces []string,
115: 	_ int,
116: ) ([]packetSource, error) {
117: 	var node string
118: 	err := exec(ctx, func(ns.NetNS) error { return nil })
119: 	if err != nil {
120: 		return nil, err
121: 	}
122: 
123: 	h.mu.Lock()
124: 	defer h.mu.Unlock()
125: 	sources := make([]packetSource, 0, len(interfaces))
126: 	for _, name := range interfaces {
127: 		if h.missing[name] {
128: 			return nil, fmt.Errorf("interface %q: no such network interface", name)
129: 		}
130: 		node = name
131: 		source := newFakeSource()
132: 		h.opened[name] = append(h.opened[name], source)
133: 		sources = append(sources, source)
134: 		h.ready <- node
135: 	}
136: 
137: 	return sources, nil
138: }
139: 
140: func (h *fakeHost) source(name string, generation int) *fakeSource {
141: 	h.mu.Lock()
142: 	defer h.mu.Unlock()
143: 
144: 	return h.opened[name][generation]
145: }
146: 
147: func (h *fakeHost) setMissing(name string, missing bool) {
148: 	h.mu.Lock()
149: 	defer h.mu.Unlock()
150: 	h.missing[name] = missing
151: }
152: 
153: func (h *fakeHost) capture() localCapture {
154: 	return localCapture{
155: 		open:           h.open,
156: 		window:         20 * time.Millisecond,
157: 		reopenInterval: time.Millisecond,
158: 	}
159: }
160: 
161: // waitOpened waits until n sources were opened.
162: func (h *fakeHost) waitOpened(t *testing.T, n int) {
163: 	t.Helper()
164: 	for range n {
165: 		select {
166: 		case <-h.ready:
167: 		case <-time.After(2 * time.Second):
168: 			t.Fatal("source was not opened")
169: 		}
170: 	}
171: }
172: 
173: type parsedLocalCapture struct {
174: 	interfaces []string
175: 	packets    []Packet
176: }
177: 
178: func parseLocalCapture(t *testing.T, data []byte) parsedLocalCapture {
179: 	t.Helper()
180: 
181: 	var parsed parsedLocalCapture
182: 	reader := NewReader(bytes.NewReader(data))
183: 	for {
184: 		event, err := reader.Next()
185: 		if errors.Is(err, io.EOF) {
186: 			break
187: 		}
188: 		if err != nil {
189: 			t.Fatalf("invalid capture: %v", err)
190: 		}
191: 		if event.Interface != nil {
192: 			parsed.interfaces = append(parsed.interfaces, event.Interface.Name)
193: 		}
194: 		if event.Packet != nil {
195: 			parsed.packets = append(parsed.packets, *event.Packet)
196: 		}
197: 	}
198: 	if reader.Sections() != 1 {
199: 		t.Fatalf("capture has %d sections", reader.Sections())
200: 	}
201: 
202: 	return parsed
203: }
204: 
205: func localRequest(packetLimit int, duration time.Duration) clablabruntime.CaptureRequest {
206: 	return clablabruntime.CaptureRequest{
207: 		Name: "lab",
208: 		Targets: []clablabruntime.CaptureTarget{
209: 			{Node: "r1", Interface: "eth1"}, {Node: "r2", Interface: "eth1"},
210: 		},
211: 		PacketLimit: packetLimit,
212: 		Duration:    duration,
213: 		SnapLength:  64,
214: 	}
215: }
216: 
217: func TestCaptureLocalMergesInterfacesInTimestampOrder(t *testing.T) {
218: 	t.Parallel()
219: 
220: 	host := newFakeHost()
221: 	// the sources are keyed by interface name in the fake host, so the two nodes use distinct
222: 	// names behind the requested ones
223: 	targets := []LocalTarget{
224: 		{Node: "r1", Interface: "e1", Exec: host.exec("r1")},
225: 		{Node: "r2", Interface: "e2", Exec: host.exec("r2")},
226: 	}
227: 
228: 	var out bytes.Buffer
229: 	done := make(chan error, 1)
230: 	go func() {
231: 		done <- host.capture().run(context.Background(), localRequest(4, 0), targets, &out)
232: 	}()
233: 	host.waitOpened(t, 2)
234: 
235: 	base := time.Unix(1_761_559_200, 0)
236: 	// r2's packets reach containerlab first although r1 stamped one of them earlier
237: 	host.source("e2", 0).frames <- fakeFrame{
238: 		data: []byte("r2-a"), stamp: base.Add(2 * time.Millisecond), length: 4,
239: 	}
240: 	host.source("e2", 0).frames <- fakeFrame{
241: 		data: bytes.Repeat([]byte{7}, 100), stamp: base.Add(4 * time.Millisecond), length: 100,
242: 	}
243: 	host.source("e1", 0).frames <- fakeFrame{
244: 		data: []byte("r1-a"), stamp: base.Add(1 * time.Millisecond), length: 4,
245: 	}
246: 	host.source("e1", 0).frames <- fakeFrame{
247: 		data: []byte("r1-v"), stamp: base.Add(3 * time.Millisecond), length: 60, vlan: true,
248: 	}
249: 
250: 	select {
251: 	case err := <-done:
252: 		if err != nil {
253: 			t.Fatal(err)
254: 		}
255: 	case <-time.After(5 * time.Second):
256: 		t.Fatal("capture did not stop at the packet limit")
257: 	}
258: 
259: 	parsed := parseLocalCapture(t, out.Bytes())
260: 	if want := []string{"r1:e1", "r2:e2"}; !slices.Equal(parsed.interfaces, want) {
261: 		t.Fatalf("interfaces = %v, want %v", parsed.interfaces, want)
262: 	}
263: 	if len(parsed.packets) != 4 {
264: 		t.Fatalf("captured %d packets, want 4", len(parsed.packets))
265: 	}
266: 	var ids []uint32
267: 	for idx, packet := range parsed.packets {
268: 		ids = append(ids, packet.InterfaceID)
269: 		if want := base.Add(time.Duration(idx+1) * time.Millisecond).
270: 			UnixNano(); packet.Timestamp != want {
271: 			t.Fatalf("packet %d stamped %d, want %d", idx, packet.Timestamp, want)
272: 		}
273: 	}
274: 	if !slices.Equal(ids, []uint32{0, 1, 0, 1}) {
275: 		t.Fatalf("interface IDs = %v", ids)
276: 	}
277: 	// a re-inserted VLAN tag counts toward the frame length
278: 	if parsed.packets[2].OriginalLength != 64 {
279: 		t.Fatalf("VLAN frame length = %d, want 64", parsed.packets[2].OriginalLength)
280: 	}
281: 	// frames are cut to the snap length
282: 	if last := parsed.packets[3]; len(last.Data) != 64 || last.OriginalLength != 100 {
283: 		t.Fatalf("long frame kept %d of %d bytes", len(last.Data), last.OriginalLength)
284: 	}
285: 	for _, name := range []string{"e1", "e2"} {
286: 		select {
287: 		case <-host.source(name, 0).closed:
288: 		default:
289: 			t.Fatalf("source %s was not closed", name)
290: 		}
291: 	}
292: }
293: 
294: func TestCaptureLocalEndsAfterTheDurationOrWhenCanceled(t *testing.T) {
295: 	t.Parallel()
296: 
297: 	host := newFakeHost()
298: 	targets := []LocalTarget{
299: 		{Node: "r1", Interface: "e1", Exec: host.exec("r1")},
300: 		{Node: "r1", Interface: "e2", Exec: host.exec("r1")},
301: 	}
302: 
303: 	var out bytes.Buffer
304: 	start := time.Now()
305: 	if err := host.capture().run(context.Background(), localRequest(0, 50*time.Millisecond),
306: 		targets, &out); err != nil {
307: 		t.Fatal(err)
308: 	}
309: 	if elapsed := time.Since(start); elapsed < 50*time.Millisecond || elapsed > 2*time.Second {
310: 		t.Fatalf("capture ran %s for a 50ms duration", elapsed)
311: 	}
312: 	if parsed := parseLocalCapture(t, out.Bytes()); len(parsed.interfaces) != 2 {
313: 		t.Fatalf("interfaces = %v", parsed.interfaces)
314: 	}
315: 
316: 	ctx, cancel := context.WithCancel(context.Background())
317: 	done := make(chan error, 1)
318: 	go func() {
319: 		done <- host.capture().run(ctx, localRequest(0, 0), targets, io.Discard)
320: 	}()
321: 	host.waitOpened(t, 4)
322: 	cancel()
323: 	select {
324: 	case err := <-done:
325: 		if err != nil {
326: 			t.Fatalf("canceled capture returned %v", err)
327: 		}
328: 	case <-time.After(2 * time.Second):
329: 		t.Fatal("canceled capture did not end")
330: 	}
331: }
332: 
333: func TestCaptureLocalWritesPacketsStillInTheRingWhenItEnds(t *testing.T) {
334: 	t.Parallel()
335: 
336: 	host := newFakeHost()
337: 	targets := []LocalTarget{{Node: "r1", Interface: "e1", Exec: host.exec("r1")}}
338: 	req := localRequest(0, 0)
339: 	req.Targets = req.Targets[:1]
340: 
341: 	ctx, cancel := context.WithCancel(context.Background())
342: 	var out bytes.Buffer
343: 	done := make(chan error, 1)
344: 	go func() {
345: 		done <- host.capture().run(ctx, req, targets, &out)
346: 	}()
347: 	host.waitOpened(t, 1)
348: 
349: 	now := time.Now()
350: 	// stamped before the end, handed over by the kernel only after it
351: 	host.source("e1", 0).frames <- fakeFrame{
352: 		data: []byte("before"), stamp: now, length: 6, visible: now.Add(30 * time.Millisecond),
353: 	}
354: 	// stamped after the end: not part of the capture
355: 	host.source("e1", 0).frames <- fakeFrame{
356: 		data: []byte("after"), stamp: now.Add(time.Hour), length: 5,
357: 		visible: now.Add(40 * time.Millisecond),
358: 	}
359: 	cancel()
360: 
361: 	if err := <-done; err != nil {
362: 		t.Fatal(err)
363: 	}
364: 	parsed := parseLocalCapture(t, out.Bytes())
365: 	if len(parsed.packets) != 1 || string(parsed.packets[0].Data) != "before" {
366: 		t.Fatalf("packets = %+v, want only the one stamped before the end", parsed.packets)
367: 	}
368: }
369: 
370: func TestCaptureLocalFailsWithoutOutputWhenAnInterfaceCannotBeOpened(t *testing.T) {
371: 	t.Parallel()
372: 
373: 	host := newFakeHost()
374: 	host.setMissing("r2", true)
375: 	targets := []LocalTarget{
376: 		{Node: "r1", Interface: "e1", Exec: host.exec("r1")},
377: 		{Node: "r2", Interface: "e2", Exec: host.exec("r2")},
378: 	}
379: 
380: 	var out bytes.Buffer
381: 	err := host.capture().run(context.Background(), localRequest(0, 0), targets, &out)
382: 	if err == nil || !strings.Contains(err.Error(), `failed to start the capture on node "r2"`) {
383: 		t.Fatalf("error = %v", err)
384: 	}
385: 	if out.Len() != 0 {
386: 		t.Fatalf("wrote %d bytes before failing", out.Len())
387: 	}
388: 	select {
389: 	case <-host.source("e1", 0).closed:
390: 	default:
391: 		t.Fatal("the source opened before the failure was not closed")
392: 	}
393: }
394: 
395: func TestCaptureLocalReopensInterfacesAndReportsWhileTheyWereGone(t *testing.T) {
396: 	t.Parallel()
397: 
398: 	host := newFakeHost()
399: 	targets := []LocalTarget{{Node: "r1", Interface: "e1", Exec: host.exec("r1")}}
400: 	req := localRequest(2, 0)
401: 	req.Targets = req.Targets[:1]
402: 
403: 	var mu sync.Mutex
404: 	var gaps []clablabruntime.CaptureGap
405: 	req.OnGap = func(gap clablabruntime.CaptureGap) {
406: 		mu.Lock()
407: 		defer mu.Unlock()
408: 		gaps = append(gaps, gap)
409: 	}
410: 
411: 	var out bytes.Buffer
412: 	done := make(chan error, 1)
413: 	go func() {
414: 		done <- host.capture().run(context.Background(), req, targets, &out)
415: 	}()
416: 	host.waitOpened(t, 1)
417: 
418: 	base := time.Unix(1_761_559_200, 0)
419: 	host.source("e1", 0).frames <- fakeFrame{data: []byte("a"), stamp: base, length: 1}
420: 
421: 	// the interface goes down: the socket fails and is reopened at once, without a gap
422: 	host.source("e1", 0).frames <- fakeFrame{err: afpacket.ErrPoll}
423: 	host.waitOpened(t, 1)
424: 
425: 	// the node restarts: the interface is gone for a while, then back
426: 	host.setMissing("r1", true)
427: 	host.source("e1", 1).frames <- fakeFrame{err: afpacket.ErrPoll}
428: 	time.Sleep(20 * time.Millisecond)
429: 	host.setMissing("r1", false)
430: 	host.waitOpened(t, 1)
431: 	host.source("e1", 2).frames <- fakeFrame{
432: 		data: []byte("b"), stamp: base.Add(time.Second), length: 1,
433: 	}
434: 
435: 	select {
436: 	case err := <-done:
437: 		if err != nil {
438: 			t.Fatal(err)
439: 		}
440: 	case <-time.After(5 * time.Second):
441: 		t.Fatal("capture did not stop at the packet limit")
442: 	}
443: 
444: 	if parsed := parseLocalCapture(t, out.Bytes()); len(parsed.packets) != 2 {
445: 		t.Fatalf("captured %d packets across the reopen, want 2", len(parsed.packets))
446: 	}
447: 	mu.Lock()
448: 	defer mu.Unlock()
449: 	if len(gaps) != 1 {
450: 		t.Fatalf("gaps = %+v, want one for the restart", gaps)
451: 	}
452: 	gap := gaps[0]
453: 	if gap.Node != "r1" || !slices.Equal(gap.Interfaces, []string{"e1"}) || gap.To.IsZero() ||
454: 		!gap.To.After(gap.From) || !strings.Contains(gap.Reason, "not available") {
455: 		t.Fatalf("gap = %+v", gap)
456: 	}
457: }
458: 
459: func TestCaptureLocalChecksTheRequest(t *testing.T) {
460: 	t.Parallel()
461: 
462: 	host := newFakeHost()
463: 	targets := []LocalTarget{{Node: "r1", Interface: "e1", Exec: host.exec("r1")}}
464: 
465: 	req := localRequest(0, 0)
466: 	req.SnapLength = 10
467: 	if err := host.capture().run(context.Background(), req, targets[:1], io.Discard); err == nil ||
468: 		!strings.Contains(err.Error(), "snap length 10") {
469: 		t.Fatalf("small snap length: error = %v", err)
470: 	}
471: 
472: 	if err := host.capture().run(context.Background(), localRequest(0, 0), targets,
473: 		io.Discard); err == nil || !strings.Contains(err.Error(), "1 resolved targets for 2") {
474: 		t.Fatalf("target mismatch: error = %v", err)
475: 	}
476: }

(End of file - total 476 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196544904001AXOkoIawbaaQbn",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196543ecb001f61Y3euhR027F8",
  "callID": "call_276ff79811d84268a4a49efc",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/capture/local_test.go",
      "limit": 2000
    },
    "output": "<path>/source/head/capture/local_test.go</path>\n<type>file</type>\n<content>\n1: package capture\n2: \n3: import (\n4: \t\"bytes\"\n5: \t\"context\"\n6: \t\"errors\"\n7: \t\"fmt\"\n8: \t\"io\"\n9: \t\"slices\"\n10: \t\"strings\"\n11: \t\"sync\"\n12: \t\"testing\"\n13: \t\"time\"\n14: \n15: \t\"github.com/containernetworking/plugins/pkg/ns\"\n16: \t\"github.com/gopacket/gopacket\"\n17: \t\"github.com/gopacket/gopacket/afpacket\"\n18: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n19: )\n20: \n21: // fakeFrame is one packet a fake source returns.\n22: type fakeFrame struct {\n23: \tdata   []byte\n24: \tstamp  time.Time\n25: \tlength int\n26: \tvlan   bool\n27: \t// visible delays the frame like a ring block the kernel has not handed over yet.\n28: \tvisible time.Time\n29: \t// err ends the source with this error instead of a packet.\n30: \terr error\n31: }\n32: \n33: // fakeSource returns frames from a channel, errReadTimeout while none is queued.\n34: type fakeSource struct {\n35: \tframes  chan fakeFrame\n36: \tclosed  chan struct{}\n37: \tonce    sync.Once\n38: \tpending *fakeFrame\n39: }\n40: \n41: func newFakeSource() *fakeSource {\n42: \treturn &fakeSource{frames: make(chan fakeFrame, 64), closed: make(chan struct{})}\n43: }\n44: \n45: func (s *fakeSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {\n46: \tif s.pending == nil {\n47: \t\tselect {\n48: \t\tcase frame := <-s.frames:\n49: \t\t\ts.pending = &frame\n50: \t\tcase <-time.After(5 * time.Millisecond):\n51: \t\t\treturn nil, gopacket.CaptureInfo{}, errReadTimeout\n52: \t\t}\n53: \t}\n54: \tif wait := time.Until(s.pending.visible); wait > 0 {\n55: \t\ttime.Sleep(min(wait, 5*time.Millisecond))\n56: \t\tif time.Now().Before(s.pending.visible) {\n57: \t\t\treturn nil, gopacket.CaptureInfo{}, errReadTimeout\n58: \t\t}\n59: \t}\n60: \n61: \t{\n62: \t\tframe := *s.pending\n63: \t\ts.pending = nil\n64: \t\tif frame.err != nil {\n65: \t\t\treturn nil, gopacket.CaptureInfo{}, frame.err\n66: \t\t}\n67: \t\tinfo := gopacket.CaptureInfo{\n68: \t\t\tTimestamp: frame.stamp, CaptureLength: len(frame.data), Length: frame.length,\n69: \t\t}\n70: \t\tif frame.vlan {\n71: \t\t\tinfo.AncillaryData = []any{afpacket.AncillaryVLAN{VLAN: 10}}\n72: \t\t}\n73: \n74: \t\treturn frame.data, info, nil\n75: \t}\n76: }\n77: \n78: func (s *fakeSource) Close() {\n79: \ts.once.Do(func() { close(s.closed) })\n80: }\n81: \n82: // fakeHost hands out fake sources per node and interface. Opening an interface listed in\n83: // missing fails, like an interface whose node does not run.\n84: type fakeHost struct {\n85: \tmu      sync.Mutex\n86: \topened  map[string][]*fakeSource\n87: \tmissing map[string]bool\n88: \tready   chan string\n89: }\n90: \n91: func newFakeHost() *fakeHost {\n92: \treturn &fakeHost{\n93: \t\topened: map[string][]*fakeSource{}, missing: map[string]bool{},\n94: \t\tready: make(chan string, 64),\n95: \t}\n96: }\n97: \n98: func (h *fakeHost) exec(node string) ExecFunc {\n99: \treturn func(_ context.Context, f func(ns.NetNS) error) error {\n100: \t\th.mu.Lock()\n101: \t\tmissing := h.missing[node]\n102: \t\th.mu.Unlock()\n103: \t\tif missing {\n104: \t\t\treturn fmt.Errorf(\"node %q: container network namespace is not available\", node)\n105: \t\t}\n106: \n107: \t\treturn f(nil)\n108: \t}\n109: }\n110: \n111: func (h *fakeHost) open(\n112: \tctx context.Context,\n113: \texec ExecFunc,\n114: \tinterfaces []string,\n115: \t_ int,\n116: ) ([]packetSource, error) {\n117: \tvar node string\n118: \terr := exec(ctx, func(ns.NetNS) error { return nil })\n119: \tif err != nil {\n120: \t\treturn nil, err\n121: \t}\n122: \n123: \th.mu.Lock()\n124: \tdefer h.mu.Unlock()\n125: \tsources := make([]packetSource, 0, len(interfaces))\n126: \tfor _, name := range interfaces {\n127: \t\tif h.missing[name] {\n128: \t\t\treturn nil, fmt.Errorf(\"interface %q: no such network interface\", name)\n129: \t\t}\n130: \t\tnode = name\n131: \t\tsource := newFakeSource()\n132: \t\th.opened[name] = append(h.opened[name], source)\n133: \t\tsources = append(sources, source)\n134: \t\th.ready <- node\n135: \t}\n136: \n137: \treturn sources, nil\n138: }\n139: \n140: func (h *fakeHost) source(name string, generation int) *fakeSource {\n141: \th.mu.Lock()\n142: \tdefer h.mu.Unlock()\n143: \n144: \treturn h.opened[name][generation]\n145: }\n146: \n147: func (h *fakeHost) setMissing(name string, missing bool) {\n148: \th.mu.Lock()\n149: \tdefer h.mu.Unlock()\n150: \th.missing[name] = missing\n151: }\n152: \n153: func (h *fakeHost) capture() localCapture {\n154: \treturn localCapture{\n155: \t\topen:           h.open,\n156: \t\twindow:         20 * time.Millisecond,\n157: \t\treopenInterval: time.Millisecond,\n158: \t}\n159: }\n160: \n161: // waitOpened waits until n sources were opened.\n162: func (h *fakeHost) waitOpened(t *testing.T, n int) {\n163: \tt.Helper()\n164: \tfor range n {\n165: \t\tselect {\n166: \t\tcase <-h.ready:\n167: \t\tcase <-time.After(2 * time.Second):\n168: \t\t\tt.Fatal(\"source was not opened\")\n169: \t\t}\n170: \t}\n171: }\n172: \n173: type parsedLocalCapture struct {\n174: \tinterfaces []string\n175: \tpackets    []Packet\n176: }\n177: \n178: func parseLocalCapture(t *testing.T, data []byte) parsedLocalCapture {\n179: \tt.Helper()\n180: \n181: \tvar parsed parsedLocalCapture\n182: \treader := NewReader(bytes.NewReader(data))\n183: \tfor {\n184: \t\tevent, err := reader.Next()\n185: \t\tif errors.Is(err, io.EOF) {\n186: \t\t\tbreak\n187: \t\t}\n188: \t\tif err != nil {\n189: \t\t\tt.Fatalf(\"invalid capture: %v\", err)\n190: \t\t}\n191: \t\tif event.Interface != nil {\n192: \t\t\tparsed.interfaces = append(parsed.interfaces, event.Interface.Name)\n193: \t\t}\n194: \t\tif event.Packet != nil {\n195: \t\t\tparsed.packets = append(parsed.packets, *event.Packet)\n196: \t\t}\n197: \t}\n198: \tif reader.Sections() != 1 {\n199: \t\tt.Fatalf(\"capture has %d sections\", reader.Sections())\n200: \t}\n201: \n202: \treturn parsed\n203: }\n204: \n205: func localRequest(packetLimit int, duration time.Duration) clablabruntime.CaptureRequest {\n206: \treturn clablabruntime.CaptureRequest{\n207: \t\tName: \"lab\",\n208: \t\tTargets: []clablabruntime.CaptureTarget{\n209: \t\t\t{Node: \"r1\", Interface: \"eth1\"}, {Node: \"r2\", Interface: \"eth1\"},\n210: \t\t},\n211: \t\tPacketLimit: packetLimit,\n212: \t\tDuration:    duration,\n213: \t\tSnapLength:  64,\n214: \t}\n215: }\n216: \n217: func TestCaptureLocalMergesInterfacesInTimestampOrder(t *testing.T) {\n218: \tt.Parallel()\n219: \n220: \thost := newFakeHost()\n221: \t// the sources are keyed by interface name in the fake host, so the two nodes use distinct\n222: \t// names behind the requested ones\n223: \ttargets := []LocalTarget{\n224: \t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n225: \t\t{Node: \"r2\", Interface: \"e2\", Exec: host.exec(\"r2\")},\n226: \t}\n227: \n228: \tvar out bytes.Buffer\n229: \tdone := make(chan error, 1)\n230: \tgo func() {\n231: \t\tdone <- host.capture().run(context.Background(), localRequest(4, 0), targets, &out)\n232: \t}()\n233: \thost.waitOpened(t, 2)\n234: \n235: \tbase := time.Unix(1_761_559_200, 0)\n236: \t// r2's packets reach containerlab first although r1 stamped one of them earlier\n237: \thost.source(\"e2\", 0).frames <- fakeFrame{\n238: \t\tdata: []byte(\"r2-a\"), stamp: base.Add(2 * time.Millisecond), length: 4,\n239: \t}\n240: \thost.source(\"e2\", 0).frames <- fakeFrame{\n241: \t\tdata: bytes.Repeat([]byte{7}, 100), stamp: base.Add(4 * time.Millisecond), length: 100,\n242: \t}\n243: \thost.source(\"e1\", 0).frames <- fakeFrame{\n244: \t\tdata: []byte(\"r1-a\"), stamp: base.Add(1 * time.Millisecond), length: 4,\n245: \t}\n246: \thost.source(\"e1\", 0).frames <- fakeFrame{\n247: \t\tdata: []byte(\"r1-v\"), stamp: base.Add(3 * time.Millisecond), length: 60, vlan: true,\n248: \t}\n249: \n250: \tselect {\n251: \tcase err := <-done:\n252: \t\tif err != nil {\n253: \t\t\tt.Fatal(err)\n254: \t\t}\n255: \tcase <-time.After(5 * time.Second):\n256: \t\tt.Fatal(\"capture did not stop at the packet limit\")\n257: \t}\n258: \n259: \tparsed := parseLocalCapture(t, out.Bytes())\n260: \tif want := []string{\"r1:e1\", \"r2:e2\"}; !slices.Equal(parsed.interfaces, want) {\n261: \t\tt.Fatalf(\"interfaces = %v, want %v\", parsed.interfaces, want)\n262: \t}\n263: \tif len(parsed.packets) != 4 {\n264: \t\tt.Fatalf(\"captured %d packets, want 4\", len(parsed.packets))\n265: \t}\n266: \tvar ids []uint32\n267: \tfor idx, packet := range parsed.packets {\n268: \t\tids = append(ids, packet.InterfaceID)\n269: \t\tif want := base.Add(time.Duration(idx+1) * time.Millisecond).\n270: \t\t\tUnixNano(); packet.Timestamp != want {\n271: \t\t\tt.Fatalf(\"packet %d stamped %d, want %d\", idx, packet.Timestamp, want)\n272: \t\t}\n273: \t}\n274: \tif !slices.Equal(ids, []uint32{0, 1, 0, 1}) {\n275: \t\tt.Fatalf(\"interface IDs = %v\", ids)\n276: \t}\n277: \t// a re-inserted VLAN tag counts toward the frame length\n278: \tif parsed.packets[2].OriginalLength != 64 {\n279: \t\tt.Fatalf(\"VLAN frame length = %d, want 64\", parsed.packets[2].OriginalLength)\n280: \t}\n281: \t// frames are cut to the snap length\n282: \tif last := parsed.packets[3]; len(last.Data) != 64 || last.OriginalLength != 100 {\n283: \t\tt.Fatalf(\"long frame kept %d of %d bytes\", len(last.Data), last.OriginalLength)\n284: \t}\n285: \tfor _, name := range []string{\"e1\", \"e2\"} {\n286: \t\tselect {\n287: \t\tcase <-host.source(name, 0).closed:\n288: \t\tdefault:\n289: \t\t\tt.Fatalf(\"source %s was not closed\", name)\n290: \t\t}\n291: \t}\n292: }\n293: \n294: func TestCaptureLocalEndsAfterTheDurationOrWhenCanceled(t *testing.T) {\n295: \tt.Parallel()\n296: \n297: \thost := newFakeHost()\n298: \ttargets := []LocalTarget{\n299: \t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n300: \t\t{Node: \"r1\", Interface: \"e2\", Exec: host.exec(\"r1\")},\n301: \t}\n302: \n303: \tvar out bytes.Buffer\n304: \tstart := time.Now()\n305: \tif err := host.capture().run(context.Background(), localRequest(0, 50*time.Millisecond),\n306: \t\ttargets, &out); err != nil {\n307: \t\tt.Fatal(err)\n308: \t}\n309: \tif elapsed := time.Since(start); elapsed < 50*time.Millisecond || elapsed > 2*time.Second {\n310: \t\tt.Fatalf(\"capture ran %s for a 50ms duration\", elapsed)\n311: \t}\n312: \tif parsed := parseLocalCapture(t, out.Bytes()); len(parsed.interfaces) != 2 {\n313: \t\tt.Fatalf(\"interfaces = %v\", parsed.interfaces)\n314: \t}\n315: \n316: \tctx, cancel := context.WithCancel(context.Background())\n317: \tdone := make(chan error, 1)\n318: \tgo func() {\n319: \t\tdone <- host.capture().run(ctx, localRequest(0, 0), targets, io.Discard)\n320: \t}()\n321: \thost.waitOpened(t, 4)\n322: \tcancel()\n323: \tselect {\n324: \tcase err := <-done:\n325: \t\tif err != nil {\n326: \t\t\tt.Fatalf(\"canceled capture returned %v\", err)\n327: \t\t}\n328: \tcase <-time.After(2 * time.Second):\n329: \t\tt.Fatal(\"canceled capture did not end\")\n330: \t}\n331: }\n332: \n333: func TestCaptureLocalWritesPacketsStillInTheRingWhenItEnds(t *testing.T) {\n334: \tt.Parallel()\n335: \n336: \thost := newFakeHost()\n337: \ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n338: \treq := localRequest(0, 0)\n339: \treq.Targets = req.Targets[:1]\n340: \n341: \tctx, cancel := context.WithCancel(context.Background())\n342: \tvar out bytes.Buffer\n343: \tdone := make(chan error, 1)\n344: \tgo func() {\n345: \t\tdone <- host.capture().run(ctx, req, targets, &out)\n346: \t}()\n347: \thost.waitOpened(t, 1)\n348: \n349: \tnow := time.Now()\n350: \t// stamped before the end, handed over by the kernel only after it\n351: \thost.source(\"e1\", 0).frames <- fakeFrame{\n352: \t\tdata: []byte(\"before\"), stamp: now, length: 6, visible: now.Add(30 * time.Millisecond),\n353: \t}\n354: \t// stamped after the end: not part of the capture\n355: \thost.source(\"e1\", 0).frames <- fakeFrame{\n356: \t\tdata: []byte(\"after\"), stamp: now.Add(time.Hour), length: 5,\n357: \t\tvisible: now.Add(40 * time.Millisecond),\n358: \t}\n359: \tcancel()\n360: \n361: \tif err := <-done; err != nil {\n362: \t\tt.Fatal(err)\n363: \t}\n364: \tparsed := parseLocalCapture(t, out.Bytes())\n365: \tif len(parsed.packets) != 1 || string(parsed.packets[0].Data) != \"before\" {\n366: \t\tt.Fatalf(\"packets = %+v, want only the one stamped before the end\", parsed.packets)\n367: \t}\n368: }\n369: \n370: func TestCaptureLocalFailsWithoutOutputWhenAnInterfaceCannotBeOpened(t *testing.T) {\n371: \tt.Parallel()\n372: \n373: \thost := newFakeHost()\n374: \thost.setMissing(\"r2\", true)\n375: \ttargets := []LocalTarget{\n376: \t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n377: \t\t{Node: \"r2\", Interface: \"e2\", Exec: host.exec(\"r2\")},\n378: \t}\n379: \n380: \tvar out bytes.Buffer\n381: \terr := host.capture().run(context.Background(), localRequest(0, 0), targets, &out)\n382: \tif err == nil || !strings.Contains(err.Error(), `failed to start the capture on node \"r2\"`) {\n383: \t\tt.Fatalf(\"error = %v\", err)\n384: \t}\n385: \tif out.Len() != 0 {\n386: \t\tt.Fatalf(\"wrote %d bytes before failing\", out.Len())\n387: \t}\n388: \tselect {\n389: \tcase <-host.source(\"e1\", 0).closed:\n390: \tdefault:\n391: \t\tt.Fatal(\"the source opened before the failure was not closed\")\n392: \t}\n393: }\n394: \n395: func TestCaptureLocalReopensInterfacesAndReportsWhileTheyWereGone(t *testing.T) {\n396: \tt.Parallel()\n397: \n398: \thost := newFakeHost()\n399: \ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n400: \treq := localRequest(2, 0)\n401: \treq.Targets = req.Targets[:1]\n402: \n403: \tvar mu sync.Mutex\n404: \tvar gaps []clablabruntime.CaptureGap\n405: \treq.OnGap = func(gap clablabruntime.CaptureGap) {\n406: \t\tmu.Lock()\n407: \t\tdefer mu.Unlock()\n408: \t\tgaps = append(gaps, gap)\n409: \t}\n410: \n411: \tvar out bytes.Buffer\n412: \tdone := make(chan error, 1)\n413: \tgo func() {\n414: \t\tdone <- host.capture().run(context.Background(), req, targets, &out)\n415: \t}()\n416: \thost.waitOpened(t, 1)\n417: \n418: \tbase := time.Unix(1_761_559_200, 0)\n419: \thost.source(\"e1\", 0).frames <- fakeFrame{data: []byte(\"a\"), stamp: base, length: 1}\n420: \n421: \t// the interface goes down: the socket fails and is reopened at once, without a gap\n422: \thost.source(\"e1\", 0).frames <- fakeFrame{err: afpacket.ErrPoll}\n423: \thost.waitOpened(t, 1)\n424: \n425: \t// the node restarts: the interface is gone for a while, then back\n426: \thost.setMissing(\"r1\", true)\n427: \thost.source(\"e1\", 1).frames <- fakeFrame{err: afpacket.ErrPoll}\n428: \ttime.Sleep(20 * time.Millisecond)\n429: \thost.setMissing(\"r1\", false)\n430: \thost.waitOpened(t, 1)\n431: \thost.source(\"e1\", 2).frames <- fakeFrame{\n432: \t\tdata: []byte(\"b\"), stamp: base.Add(time.Second), length: 1,\n433: \t}\n434: \n435: \tselect {\n436: \tcase err := <-done:\n437: \t\tif err != nil {\n438: \t\t\tt.Fatal(err)\n439: \t\t}\n440: \tcase <-time.After(5 * time.Second):\n441: \t\tt.Fatal(\"capture did not stop at the packet limit\")\n442: \t}\n443: \n444: \tif parsed := parseLocalCapture(t, out.Bytes()); len(parsed.packets) != 2 {\n445: \t\tt.Fatalf(\"captured %d packets across the reopen, want 2\", len(parsed.packets))\n446: \t}\n447: \tmu.Lock()\n448: \tdefer mu.Unlock()\n449: \tif len(gaps) != 1 {\n450: \t\tt.Fatalf(\"gaps = %+v, want one for the restart\", gaps)\n451: \t}\n452: \tgap := gaps[0]\n453: \tif gap.Node != \"r1\" || !slices.Equal(gap.Interfaces, []string{\"e1\"}) || gap.To.IsZero() ||\n454: \t\t!gap.To.After(gap.From) || !strings.Contains(gap.Reason, \"not available\") {\n455: \t\tt.Fatalf(\"gap = %+v\", gap)\n456: \t}\n457: }\n458: \n459: func TestCaptureLocalChecksTheRequest(t *testing.T) {\n460: \tt.Parallel()\n461: \n462: \thost := newFakeHost()\n463: \ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n464: \n465: \treq := localRequest(0, 0)\n466: \treq.SnapLength = 10\n467: \tif err := host.capture().run(context.Background(), req, targets[:1], io.Discard); err == nil ||\n468: \t\t!strings.Contains(err.Error(), \"snap length 10\") {\n469: \t\tt.Fatalf(\"small snap length: error = %v\", err)\n470: \t}\n471: \n472: \tif err := host.capture().run(context.Background(), localRequest(0, 0), targets,\n473: \t\tio.Discard); err == nil || !strings.Contains(err.Error(), \"1 resolved targets for 2\") {\n474: \t\tt.Fatalf(\"target mismatch: error = %v\", err)\n475: \t}\n476: }\n\n(End of file - total 476 lines)\n</content>",
    "title": "source/head/capture/local_test.go",
    "metadata": {
      "preview": "package capture\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"slices\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/containernetworking/plugins/pkg/ns\"\n\t\"github.com/gopacket/gopacket\"\n\t\"github.com/gopacket/gopacket/afpacket\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/capture/local_test.go",
        "text": "package capture\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"slices\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/containernetworking/plugins/pkg/ns\"\n\t\"github.com/gopacket/gopacket\"\n\t\"github.com/gopacket/gopacket/afpacket\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\n// fakeFrame is one packet a fake source returns.\ntype fakeFrame struct {\n\tdata   []byte\n\tstamp  time.Time\n\tlength int\n\tvlan   bool\n\t// visible delays the frame like a ring block the kernel has not handed over yet.\n\tvisible time.Time\n\t// err ends the source with this error instead of a packet.\n\terr error\n}\n\n// fakeSource returns frames from a channel, errReadTimeout while none is queued.\ntype fakeSource struct {\n\tframes  chan fakeFrame\n\tclosed  chan struct{}\n\tonce    sync.Once\n\tpending *fakeFrame\n}\n\nfunc newFakeSource() *fakeSource {\n\treturn &fakeSource{frames: make(chan fakeFrame, 64), closed: make(chan struct{})}\n}\n\nfunc (s *fakeSource) ReadPacket() ([]byte, gopacket.CaptureInfo, error) {\n\tif s.pending == nil {\n\t\tselect {\n\t\tcase frame := <-s.frames:\n\t\t\ts.pending = &frame\n\t\tcase <-time.After(5 * time.Millisecond):\n\t\t\treturn nil, gopacket.CaptureInfo{}, errReadTimeout\n\t\t}\n\t}\n\tif wait := time.Until(s.pending.visible); wait > 0 {\n\t\ttime.Sleep(min(wait, 5*time.Millisecond))\n\t\tif time.Now().Before(s.pending.visible) {\n\t\t\treturn nil, gopacket.CaptureInfo{}, errReadTimeout\n\t\t}\n\t}\n\n\t{\n\t\tframe := *s.pending\n\t\ts.pending = nil\n\t\tif frame.err != nil {\n\t\t\treturn nil, gopacket.CaptureInfo{}, frame.err\n\t\t}\n\t\tinfo := gopacket.CaptureInfo{\n\t\t\tTimestamp: frame.stamp, CaptureLength: len(frame.data), Length: frame.length,\n\t\t}\n\t\tif frame.vlan {\n\t\t\tinfo.AncillaryData = []any{afpacket.AncillaryVLAN{VLAN: 10}}\n\t\t}\n\n\t\treturn frame.data, info, nil\n\t}\n}\n\nfunc (s *fakeSource) Close() {\n\ts.once.Do(func() { close(s.closed) })\n}\n\n// fakeHost hands out fake sources per node and interface. Opening an interface listed in\n// missing fails, like an interface whose node does not run.\ntype fakeHost struct {\n\tmu      sync.Mutex\n\topened  map[string][]*fakeSource\n\tmissing map[string]bool\n\tready   chan string\n}\n\nfunc newFakeHost() *fakeHost {\n\treturn &fakeHost{\n\t\topened: map[string][]*fakeSource{}, missing: map[string]bool{},\n\t\tready: make(chan string, 64),\n\t}\n}\n\nfunc (h *fakeHost) exec(node string) ExecFunc {\n\treturn func(_ context.Context, f func(ns.NetNS) error) error {\n\t\th.mu.Lock()\n\t\tmissing := h.missing[node]\n\t\th.mu.Unlock()\n\t\tif missing {\n\t\t\treturn fmt.Errorf(\"node %q: container network namespace is not available\", node)\n\t\t}\n\n\t\treturn f(nil)\n\t}\n}\n\nfunc (h *fakeHost) open(\n\tctx context.Context,\n\texec ExecFunc,\n\tinterfaces []string,\n\t_ int,\n) ([]packetSource, error) {\n\tvar node string\n\terr := exec(ctx, func(ns.NetNS) error { return nil })\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\tsources := make([]packetSource, 0, len(interfaces))\n\tfor _, name := range interfaces {\n\t\tif h.missing[name] {\n\t\t\treturn nil, fmt.Errorf(\"interface %q: no such network interface\", name)\n\t\t}\n\t\tnode = name\n\t\tsource := newFakeSource()\n\t\th.opened[name] = append(h.opened[name], source)\n\t\tsources = append(sources, source)\n\t\th.ready <- node\n\t}\n\n\treturn sources, nil\n}\n\nfunc (h *fakeHost) source(name string, generation int) *fakeSource {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\treturn h.opened[name][generation]\n}\n\nfunc (h *fakeHost) setMissing(name string, missing bool) {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.missing[name] = missing\n}\n\nfunc (h *fakeHost) capture() localCapture {\n\treturn localCapture{\n\t\topen:           h.open,\n\t\twindow:         20 * time.Millisecond,\n\t\treopenInterval: time.Millisecond,\n\t}\n}\n\n// waitOpened waits until n sources were opened.\nfunc (h *fakeHost) waitOpened(t *testing.T, n int) {\n\tt.Helper()\n\tfor range n {\n\t\tselect {\n\t\tcase <-h.ready:\n\t\tcase <-time.After(2 * time.Second):\n\t\t\tt.Fatal(\"source was not opened\")\n\t\t}\n\t}\n}\n\ntype parsedLocalCapture struct {\n\tinterfaces []string\n\tpackets    []Packet\n}\n\nfunc parseLocalCapture(t *testing.T, data []byte) parsedLocalCapture {\n\tt.Helper()\n\n\tvar parsed parsedLocalCapture\n\treader := NewReader(bytes.NewReader(data))\n\tfor {\n\t\tevent, err := reader.Next()\n\t\tif errors.Is(err, io.EOF) {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"invalid capture: %v\", err)\n\t\t}\n\t\tif event.Interface != nil {\n\t\t\tparsed.interfaces = append(parsed.interfaces, event.Interface.Name)\n\t\t}\n\t\tif event.Packet != nil {\n\t\t\tparsed.packets = append(parsed.packets, *event.Packet)\n\t\t}\n\t}\n\tif reader.Sections() != 1 {\n\t\tt.Fatalf(\"capture has %d sections\", reader.Sections())\n\t}\n\n\treturn parsed\n}\n\nfunc localRequest(packetLimit int, duration time.Duration) clablabruntime.CaptureRequest {\n\treturn clablabruntime.CaptureRequest{\n\t\tName: \"lab\",\n\t\tTargets: []clablabruntime.CaptureTarget{\n\t\t\t{Node: \"r1\", Interface: \"eth1\"}, {Node: \"r2\", Interface: \"eth1\"},\n\t\t},\n\t\tPacketLimit: packetLimit,\n\t\tDuration:    duration,\n\t\tSnapLength:  64,\n\t}\n}\n\nfunc TestCaptureLocalMergesInterfacesInTimestampOrder(t *testing.T) {\n\tt.Parallel()\n\n\thost := newFakeHost()\n\t// the sources are keyed by interface name in the fake host, so the two nodes use distinct\n\t// names behind the requested ones\n\ttargets := []LocalTarget{\n\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n\t\t{Node: \"r2\", Interface: \"e2\", Exec: host.exec(\"r2\")},\n\t}\n\n\tvar out bytes.Buffer\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdone <- host.capture().run(context.Background(), localRequest(4, 0), targets, &out)\n\t}()\n\thost.waitOpened(t, 2)\n\n\tbase := time.Unix(1_761_559_200, 0)\n\t// r2's packets reach containerlab first although r1 stamped one of them earlier\n\thost.source(\"e2\", 0).frames <- fakeFrame{\n\t\tdata: []byte(\"r2-a\"), stamp: base.Add(2 * time.Millisecond), length: 4,\n\t}\n\thost.source(\"e2\", 0).frames <- fakeFrame{\n\t\tdata: bytes.Repeat([]byte{7}, 100), stamp: base.Add(4 * time.Millisecond), length: 100,\n\t}\n\thost.source(\"e1\", 0).frames <- fakeFrame{\n\t\tdata: []byte(\"r1-a\"), stamp: base.Add(1 * time.Millisecond), length: 4,\n\t}\n\thost.source(\"e1\", 0).frames <- fakeFrame{\n\t\tdata: []byte(\"r1-v\"), stamp: base.Add(3 * time.Millisecond), length: 60, vlan: true,\n\t}\n\n\tselect {\n\tcase err := <-done:\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\tcase <-time.After(5 * time.Second):\n\t\tt.Fatal(\"capture did not stop at the packet limit\")\n\t}\n\n\tparsed := parseLocalCapture(t, out.Bytes())\n\tif want := []string{\"r1:e1\", \"r2:e2\"}; !slices.Equal(parsed.interfaces, want) {\n\t\tt.Fatalf(\"interfaces = %v, want %v\", parsed.interfaces, want)\n\t}\n\tif len(parsed.packets) != 4 {\n\t\tt.Fatalf(\"captured %d packets, want 4\", len(parsed.packets))\n\t}\n\tvar ids []uint32\n\tfor idx, packet := range parsed.packets {\n\t\tids = append(ids, packet.InterfaceID)\n\t\tif want := base.Add(time.Duration(idx+1) * time.Millisecond).\n\t\t\tUnixNano(); packet.Timestamp != want {\n\t\t\tt.Fatalf(\"packet %d stamped %d, want %d\", idx, packet.Timestamp, want)\n\t\t}\n\t}\n\tif !slices.Equal(ids, []uint32{0, 1, 0, 1}) {\n\t\tt.Fatalf(\"interface IDs = %v\", ids)\n\t}\n\t// a re-inserted VLAN tag counts toward the frame length\n\tif parsed.packets[2].OriginalLength != 64 {\n\t\tt.Fatalf(\"VLAN frame length = %d, want 64\", parsed.packets[2].OriginalLength)\n\t}\n\t// frames are cut to the snap length\n\tif last := parsed.packets[3]; len(last.Data) != 64 || last.OriginalLength != 100 {\n\t\tt.Fatalf(\"long frame kept %d of %d bytes\", len(last.Data), last.OriginalLength)\n\t}\n\tfor _, name := range []string{\"e1\", \"e2\"} {\n\t\tselect {\n\t\tcase <-host.source(name, 0).closed:\n\t\tdefault:\n\t\t\tt.Fatalf(\"source %s was not closed\", name)\n\t\t}\n\t}\n}\n\nfunc TestCaptureLocalEndsAfterTheDurationOrWhenCanceled(t *testing.T) {\n\tt.Parallel()\n\n\thost := newFakeHost()\n\ttargets := []LocalTarget{\n\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n\t\t{Node: \"r1\", Interface: \"e2\", Exec: host.exec(\"r1\")},\n\t}\n\n\tvar out bytes.Buffer\n\tstart := time.Now()\n\tif err := host.capture().run(context.Background(), localRequest(0, 50*time.Millisecond),\n\t\ttargets, &out); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif elapsed := time.Since(start); elapsed < 50*time.Millisecond || elapsed > 2*time.Second {\n\t\tt.Fatalf(\"capture ran %s for a 50ms duration\", elapsed)\n\t}\n\tif parsed := parseLocalCapture(t, out.Bytes()); len(parsed.interfaces) != 2 {\n\t\tt.Fatalf(\"interfaces = %v\", parsed.interfaces)\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdone <- host.capture().run(ctx, localRequest(0, 0), targets, io.Discard)\n\t}()\n\thost.waitOpened(t, 4)\n\tcancel()\n\tselect {\n\tcase err := <-done:\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"canceled capture returned %v\", err)\n\t\t}\n\tcase <-time.After(2 * time.Second):\n\t\tt.Fatal(\"canceled capture did not end\")\n\t}\n}\n\nfunc TestCaptureLocalWritesPacketsStillInTheRingWhenItEnds(t *testing.T) {\n\tt.Parallel()\n\n\thost := newFakeHost()\n\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n\treq := localRequest(0, 0)\n\treq.Targets = req.Targets[:1]\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tvar out bytes.Buffer\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdone <- host.capture().run(ctx, req, targets, &out)\n\t}()\n\thost.waitOpened(t, 1)\n\n\tnow := time.Now()\n\t// stamped before the end, handed over by the kernel only after it\n\thost.source(\"e1\", 0).frames <- fakeFrame{\n\t\tdata: []byte(\"before\"), stamp: now, length: 6, visible: now.Add(30 * time.Millisecond),\n\t}\n\t// stamped after the end: not part of the capture\n\thost.source(\"e1\", 0).frames <- fakeFrame{\n\t\tdata: []byte(\"after\"), stamp: now.Add(time.Hour), length: 5,\n\t\tvisible: now.Add(40 * time.Millisecond),\n\t}\n\tcancel()\n\n\tif err := <-done; err != nil {\n\t\tt.Fatal(err)\n\t}\n\tparsed := parseLocalCapture(t, out.Bytes())\n\tif len(parsed.packets) != 1 || string(parsed.packets[0].Data) != \"before\" {\n\t\tt.Fatalf(\"packets = %+v, want only the one stamped before the end\", parsed.packets)\n\t}\n}\n\nfunc TestCaptureLocalFailsWithoutOutputWhenAnInterfaceCannotBeOpened(t *testing.T) {\n\tt.Parallel()\n\n\thost := newFakeHost()\n\thost.setMissing(\"r2\", true)\n\ttargets := []LocalTarget{\n\t\t{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")},\n\t\t{Node: \"r2\", Interface: \"e2\", Exec: host.exec(\"r2\")},\n\t}\n\n\tvar out bytes.Buffer\n\terr := host.capture().run(context.Background(), localRequest(0, 0), targets, &out)\n\tif err == nil || !strings.Contains(err.Error(), `failed to start the capture on node \"r2\"`) {\n\t\tt.Fatalf(\"error = %v\", err)\n\t}\n\tif out.Len() != 0 {\n\t\tt.Fatalf(\"wrote %d bytes before failing\", out.Len())\n\t}\n\tselect {\n\tcase <-host.source(\"e1\", 0).closed:\n\tdefault:\n\t\tt.Fatal(\"the source opened before the failure was not closed\")\n\t}\n}\n\nfunc TestCaptureLocalReopensInterfacesAndReportsWhileTheyWereGone(t *testing.T) {\n\tt.Parallel()\n\n\thost := newFakeHost()\n\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n\treq := localRequest(2, 0)\n\treq.Targets = req.Targets[:1]\n\n\tvar mu sync.Mutex\n\tvar gaps []clablabruntime.CaptureGap\n\treq.OnGap = func(gap clablabruntime.CaptureGap) {\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\t\tgaps = append(gaps, gap)\n\t}\n\n\tvar out bytes.Buffer\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdone <- host.capture().run(context.Background(), req, targets, &out)\n\t}()\n\thost.waitOpened(t, 1)\n\n\tbase := time.Unix(1_761_559_200, 0)\n\thost.source(\"e1\", 0).frames <- fakeFrame{data: []byte(\"a\"), stamp: base, length: 1}\n\n\t// the interface goes down: the socket fails and is reopened at once, without a gap\n\thost.source(\"e1\", 0).frames <- fakeFrame{err: afpacket.ErrPoll}\n\thost.waitOpened(t, 1)\n\n\t// the node restarts: the interface is gone for a while, then back\n\thost.setMissing(\"r1\", true)\n\thost.source(\"e1\", 1).frames <- fakeFrame{err: afpacket.ErrPoll}\n\ttime.Sleep(20 * time.Millisecond)\n\thost.setMissing(\"r1\", false)\n\thost.waitOpened(t, 1)\n\thost.source(\"e1\", 2).frames <- fakeFrame{\n\t\tdata: []byte(\"b\"), stamp: base.Add(time.Second), length: 1,\n\t}\n\n\tselect {\n\tcase err := <-done:\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\tcase <-time.After(5 * time.Second):\n\t\tt.Fatal(\"capture did not stop at the packet limit\")\n\t}\n\n\tif parsed := parseLocalCapture(t, out.Bytes()); len(parsed.packets) != 2 {\n\t\tt.Fatalf(\"captured %d packets across the reopen, want 2\", len(parsed.packets))\n\t}\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tif len(gaps) != 1 {\n\t\tt.Fatalf(\"gaps = %+v, want one for the restart\", gaps)\n\t}\n\tgap := gaps[0]\n\tif gap.Node != \"r1\" || !slices.Equal(gap.Interfaces, []string{\"e1\"}) || gap.To.IsZero() ||\n\t\t!gap.To.After(gap.From) || !strings.Contains(gap.Reason, \"not available\") {\n\t\tt.Fatalf(\"gap = %+v\", gap)\n\t}\n}\n\nfunc TestCaptureLocalChecksTheRequest(t *testing.T) {\n\tt.Parallel()\n\n\thost := newFakeHost()\n\ttargets := []LocalTarget{{Node: \"r1\", Interface: \"e1\", Exec: host.exec(\"r1\")}}\n\n\treq := localRequest(0, 0)\n\treq.SnapLength = 10\n\tif err := host.capture().run(context.Background(), req, targets[:1], io.Discard); err == nil ||\n\t\t!strings.Contains(err.Error(), \"snap length 10\") {\n\t\tt.Fatalf(\"small snap length: error = %v\", err)\n\t}\n\n\tif err := host.capture().run(context.Background(), localRequest(0, 0), targets,\n\t\tio.Discard); err == nil || !strings.Contains(err.Error(), \"1 resolved targets for 2\") {\n\t\tt.Fatalf(\"target mismatch: error = %v\", err)\n\t}\n}",
        "lineStart": 1,
        "lineEnd": 476,
        "totalLines": 476,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523468553,
      "end": 1793523468559
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/cmd/capture_test.go",
  "limit": 800
}

Output

<path>/source/head/cmd/capture_test.go</path>
<type>file</type>
<content>
1: package cmd
2: 
3: import (
4: 	"bytes"
5: 	"encoding/json"
6: 	"slices"
7: 	"strings"
8: 	"testing"
9: 
10: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
11: )
12: 
13: func TestParseCaptureTargets(t *testing.T) {
14: 	t.Parallel()
15: 
16: 	targets, err := parseCaptureTargets([]string{
17: 		"srl1:e1-1,ethernet-1/2", " sros : 1/1/3 ", "r1:eth1",
18: 	})
19: 	if err != nil {
20: 		t.Fatal(err)
21: 	}
22: 	want := []clablabruntime.CaptureTarget{
23: 		{Node: "srl1", Interface: "e1-1"},
24: 		{Node: "srl1", Interface: "ethernet-1/2"},
25: 		{Node: "sros", Interface: "1/1/3"},
26: 		{Node: "r1", Interface: "eth1"},
27: 	}
28: 	if !slices.Equal(targets, want) {
29: 		t.Fatalf("targets = %+v, want %+v", targets, want)
30: 	}
31: 
32: 	for _, bad := range [][]string{nil, {"srl1"}, {":e1-1"}, {"srl1:"}, {"srl1:e1-1,,e1-2"}} {
33: 		if _, err := parseCaptureTargets(bad); err == nil {
34: 			t.Errorf("parseCaptureTargets(%q) succeeded", bad)
35: 		}
36: 	}
37: }
38: 
39: func TestCaptureCommandFlags(t *testing.T) {
40: 	o := GetOptions()
41: 	cmd, err := captureCmd(o)
42: 	if err != nil {
43: 		t.Fatal(err)
44: 	}
45: 	if err := cmd.ParseFlags([]string{
46: 		"--target", "srl1:e1-1", "--target", "srl2:e1-1,e1-2", "--duration", "90m",
47: 		"--packet-limit", "100", "--snap-length", "128", "-w", "out.pcapng",
48: 	}); err != nil {
49: 		t.Fatal(err)
50: 	}
51: 	if !slices.Equal(o.Capture.Targets, []string{"srl1:e1-1", "srl2:e1-1,e1-2"}) ||
52: 		o.Capture.Duration.Minutes() != 90 || o.Capture.PacketLimit != 100 ||
53: 		o.Capture.SnapLength != 128 || o.Capture.Write != "out.pcapng" {
54: 		t.Fatalf("capture options = %+v", o.Capture)
55: 	}
56: 	if def := cmd.Flag("write").DefValue; def != "-" {
57: 		t.Fatalf("--write default = %q, want stdout", def)
58: 	}
59: }
60: 
61: func TestPrintCaptureInterfaces(t *testing.T) {
62: 	t.Parallel()
63: 
64: 	interfaces := []clablabruntime.CaptureInterface{
65: 		{
66: 			Node:          "srl1",
67: 			Interface:     "e1-1",
68: 			Alias:         "ethernet-1/1",
69: 			PeerNode:      "srl2",
70: 			PeerInterface: "ethernet-1/1",
71: 		},
72: 		{Node: "srl1", Interface: "e1-2", PeerNode: "host", PeerInterface: "srl1-e1-2"},
73: 	}
74: 
75: 	var out bytes.Buffer
76: 	if err := printCaptureInterfaces(&out, interfaces, "json"); err != nil {
77: 		t.Fatal(err)
78: 	}
79: 	var decoded []map[string]any
80: 	if err := json.Unmarshal(out.Bytes(), &decoded); err != nil {
81: 		t.Fatal(err)
82: 	}
83: 	if decoded[0]["peer_node"] != "srl2" || decoded[0]["alias"] != "ethernet-1/1" {
84: 		t.Fatalf("json = %s", out.String())
85: 	}
86: 	if _, hasAlias := decoded[1]["alias"]; hasAlias {
87: 		t.Fatalf("an empty alias is printed: %s", out.String())
88: 	}
89: 
90: 	out.Reset()
91: 	if err := printCaptureInterfaces(
92: 		&out,
93: 		nil,
94: 		"json",
95: 	); err != nil ||
96: 		strings.TrimSpace(out.String()) != "[]" {
97: 		t.Fatalf("empty json = %q, %v", out.String(), err)
98: 	}
99: 
100: 	out.Reset()
101: 	if err := printCaptureInterfaces(&out, interfaces, "table"); err != nil {
102: 		t.Fatal(err)
103: 	}
104: 	for _, want := range []string{"Peer Interface", "ethernet-1/1", "srl1-e1-2", "N/A"} {
105: 		if !strings.Contains(out.String(), want) {
106: 			t.Fatalf("table does not contain %q:\n%s", want, out.String())
107: 		}
108: 	}
109: }

(End of file - total 109 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1965449480016TLozXxbMfNpQw",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196543ecb001f61Y3euhR027F8",
  "callID": "call_46d03ba43c0545c899cc7263",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/cmd/capture_test.go",
      "limit": 800
    },
    "output": "<path>/source/head/cmd/capture_test.go</path>\n<type>file</type>\n<content>\n1: package cmd\n2: \n3: import (\n4: \t\"bytes\"\n5: \t\"encoding/json\"\n6: \t\"slices\"\n7: \t\"strings\"\n8: \t\"testing\"\n9: \n10: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n11: )\n12: \n13: func TestParseCaptureTargets(t *testing.T) {\n14: \tt.Parallel()\n15: \n16: \ttargets, err := parseCaptureTargets([]string{\n17: \t\t\"srl1:e1-1,ethernet-1/2\", \" sros : 1/1/3 \", \"r1:eth1\",\n18: \t})\n19: \tif err != nil {\n20: \t\tt.Fatal(err)\n21: \t}\n22: \twant := []clablabruntime.CaptureTarget{\n23: \t\t{Node: \"srl1\", Interface: \"e1-1\"},\n24: \t\t{Node: \"srl1\", Interface: \"ethernet-1/2\"},\n25: \t\t{Node: \"sros\", Interface: \"1/1/3\"},\n26: \t\t{Node: \"r1\", Interface: \"eth1\"},\n27: \t}\n28: \tif !slices.Equal(targets, want) {\n29: \t\tt.Fatalf(\"targets = %+v, want %+v\", targets, want)\n30: \t}\n31: \n32: \tfor _, bad := range [][]string{nil, {\"srl1\"}, {\":e1-1\"}, {\"srl1:\"}, {\"srl1:e1-1,,e1-2\"}} {\n33: \t\tif _, err := parseCaptureTargets(bad); err == nil {\n34: \t\t\tt.Errorf(\"parseCaptureTargets(%q) succeeded\", bad)\n35: \t\t}\n36: \t}\n37: }\n38: \n39: func TestCaptureCommandFlags(t *testing.T) {\n40: \to := GetOptions()\n41: \tcmd, err := captureCmd(o)\n42: \tif err != nil {\n43: \t\tt.Fatal(err)\n44: \t}\n45: \tif err := cmd.ParseFlags([]string{\n46: \t\t\"--target\", \"srl1:e1-1\", \"--target\", \"srl2:e1-1,e1-2\", \"--duration\", \"90m\",\n47: \t\t\"--packet-limit\", \"100\", \"--snap-length\", \"128\", \"-w\", \"out.pcapng\",\n48: \t}); err != nil {\n49: \t\tt.Fatal(err)\n50: \t}\n51: \tif !slices.Equal(o.Capture.Targets, []string{\"srl1:e1-1\", \"srl2:e1-1,e1-2\"}) ||\n52: \t\to.Capture.Duration.Minutes() != 90 || o.Capture.PacketLimit != 100 ||\n53: \t\to.Capture.SnapLength != 128 || o.Capture.Write != \"out.pcapng\" {\n54: \t\tt.Fatalf(\"capture options = %+v\", o.Capture)\n55: \t}\n56: \tif def := cmd.Flag(\"write\").DefValue; def != \"-\" {\n57: \t\tt.Fatalf(\"--write default = %q, want stdout\", def)\n58: \t}\n59: }\n60: \n61: func TestPrintCaptureInterfaces(t *testing.T) {\n62: \tt.Parallel()\n63: \n64: \tinterfaces := []clablabruntime.CaptureInterface{\n65: \t\t{\n66: \t\t\tNode:          \"srl1\",\n67: \t\t\tInterface:     \"e1-1\",\n68: \t\t\tAlias:         \"ethernet-1/1\",\n69: \t\t\tPeerNode:      \"srl2\",\n70: \t\t\tPeerInterface: \"ethernet-1/1\",\n71: \t\t},\n72: \t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"srl1-e1-2\"},\n73: \t}\n74: \n75: \tvar out bytes.Buffer\n76: \tif err := printCaptureInterfaces(&out, interfaces, \"json\"); err != nil {\n77: \t\tt.Fatal(err)\n78: \t}\n79: \tvar decoded []map[string]any\n80: \tif err := json.Unmarshal(out.Bytes(), &decoded); err != nil {\n81: \t\tt.Fatal(err)\n82: \t}\n83: \tif decoded[0][\"peer_node\"] != \"srl2\" || decoded[0][\"alias\"] != \"ethernet-1/1\" {\n84: \t\tt.Fatalf(\"json = %s\", out.String())\n85: \t}\n86: \tif _, hasAlias := decoded[1][\"alias\"]; hasAlias {\n87: \t\tt.Fatalf(\"an empty alias is printed: %s\", out.String())\n88: \t}\n89: \n90: \tout.Reset()\n91: \tif err := printCaptureInterfaces(\n92: \t\t&out,\n93: \t\tnil,\n94: \t\t\"json\",\n95: \t); err != nil ||\n96: \t\tstrings.TrimSpace(out.String()) != \"[]\" {\n97: \t\tt.Fatalf(\"empty json = %q, %v\", out.String(), err)\n98: \t}\n99: \n100: \tout.Reset()\n101: \tif err := printCaptureInterfaces(&out, interfaces, \"table\"); err != nil {\n102: \t\tt.Fatal(err)\n103: \t}\n104: \tfor _, want := range []string{\"Peer Interface\", \"ethernet-1/1\", \"srl1-e1-2\", \"N/A\"} {\n105: \t\tif !strings.Contains(out.String(), want) {\n106: \t\t\tt.Fatalf(\"table does not contain %q:\\n%s\", want, out.String())\n107: \t\t}\n108: \t}\n109: }\n\n(End of file - total 109 lines)\n</content>",
    "title": "source/head/cmd/capture_test.go",
    "metadata": {
      "preview": "package cmd\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"slices\"\n\t\"strings\"\n\t\"testing\"\n\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\nfunc TestParseCaptureTargets(t *testing.T) {\n\tt.Parallel()\n\n\ttargets, err := parseCaptureTargets([]string{\n\t\t\"srl1:e1-1,ethernet-1/2\", \" sros : 1/1/3 \", \"r1:eth1\",\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/cmd/capture_test.go",
        "text": "package cmd\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"slices\"\n\t\"strings\"\n\t\"testing\"\n\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\nfunc TestParseCaptureTargets(t *testing.T) {\n\tt.Parallel()\n\n\ttargets, err := parseCaptureTargets([]string{\n\t\t\"srl1:e1-1,ethernet-1/2\", \" sros : 1/1/3 \", \"r1:eth1\",\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\twant := []clablabruntime.CaptureTarget{\n\t\t{Node: \"srl1\", Interface: \"e1-1\"},\n\t\t{Node: \"srl1\", Interface: \"ethernet-1/2\"},\n\t\t{Node: \"sros\", Interface: \"1/1/3\"},\n\t\t{Node: \"r1\", Interface: \"eth1\"},\n\t}\n\tif !slices.Equal(targets, want) {\n\t\tt.Fatalf(\"targets = %+v, want %+v\", targets, want)\n\t}\n\n\tfor _, bad := range [][]string{nil, {\"srl1\"}, {\":e1-1\"}, {\"srl1:\"}, {\"srl1:e1-1,,e1-2\"}} {\n\t\tif _, err := parseCaptureTargets(bad); err == nil {\n\t\t\tt.Errorf(\"parseCaptureTargets(%q) succeeded\", bad)\n\t\t}\n\t}\n}\n\nfunc TestCaptureCommandFlags(t *testing.T) {\n\to := GetOptions()\n\tcmd, err := captureCmd(o)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := cmd.ParseFlags([]string{\n\t\t\"--target\", \"srl1:e1-1\", \"--target\", \"srl2:e1-1,e1-2\", \"--duration\", \"90m\",\n\t\t\"--packet-limit\", \"100\", \"--snap-length\", \"128\", \"-w\", \"out.pcapng\",\n\t}); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !slices.Equal(o.Capture.Targets, []string{\"srl1:e1-1\", \"srl2:e1-1,e1-2\"}) ||\n\t\to.Capture.Duration.Minutes() != 90 || o.Capture.PacketLimit != 100 ||\n\t\to.Capture.SnapLength != 128 || o.Capture.Write != \"out.pcapng\" {\n\t\tt.Fatalf(\"capture options = %+v\", o.Capture)\n\t}\n\tif def := cmd.Flag(\"write\").DefValue; def != \"-\" {\n\t\tt.Fatalf(\"--write default = %q, want stdout\", def)\n\t}\n}\n\nfunc TestPrintCaptureInterfaces(t *testing.T) {\n\tt.Parallel()\n\n\tinterfaces := []clablabruntime.CaptureInterface{\n\t\t{\n\t\t\tNode:          \"srl1\",\n\t\t\tInterface:     \"e1-1\",\n\t\t\tAlias:         \"ethernet-1/1\",\n\t\t\tPeerNode:      \"srl2\",\n\t\t\tPeerInterface: \"ethernet-1/1\",\n\t\t},\n\t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"host\", PeerInterface: \"srl1-e1-2\"},\n\t}\n\n\tvar out bytes.Buffer\n\tif err := printCaptureInterfaces(&out, interfaces, \"json\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar decoded []map[string]any\n\tif err := json.Unmarshal(out.Bytes(), &decoded); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif decoded[0][\"peer_node\"] != \"srl2\" || decoded[0][\"alias\"] != \"ethernet-1/1\" {\n\t\tt.Fatalf(\"json = %s\", out.String())\n\t}\n\tif _, hasAlias := decoded[1][\"alias\"]; hasAlias {\n\t\tt.Fatalf(\"an empty alias is printed: %s\", out.String())\n\t}\n\n\tout.Reset()\n\tif err := printCaptureInterfaces(\n\t\t&out,\n\t\tnil,\n\t\t\"json\",\n\t); err != nil ||\n\t\tstrings.TrimSpace(out.String()) != \"[]\" {\n\t\tt.Fatalf(\"empty json = %q, %v\", out.String(), err)\n\t}\n\n\tout.Reset()\n\tif err := printCaptureInterfaces(&out, interfaces, \"table\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor _, want := range []string{\"Peer Interface\", \"ethernet-1/1\", \"srl1-e1-2\", \"N/A\"} {\n\t\tif !strings.Contains(out.String(), want) {\n\t\t\tt.Fatalf(\"table does not contain %q:\\n%s\", want, out.String())\n\t\t}\n\t}\n}",
        "lineStart": 1,
        "lineEnd": 109,
        "totalLines": 109,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523468619,
      "end": 1793523468625
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19654495300114WuMFrGE4VTD2",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196543ecb001f61Y3euhR027F8",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 21876,
    "input": 4907,
    "output": 88,
    "reasoning": 113,
    "cache": {
      "read": 16768,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196543ecb001f61Y3euhR027F8",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523465931,
    "completed": 1793523468630
  },
  "parentID": "msg_1965436e6001620KypTRi1ley5",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 21876,
    "input": 4907,
    "output": 88,
    "reasoning": 113,
    "cache": {
      "read": 16768,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 57
step-start
{
  "type": "step-start",
  "id": "prt_196545037001HGGvwhfItTn1Ee",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196544960001jOFhFncIdgj9Pi"
}
Reasoning
Good coverage in tests. Now quickly check remaining docs files and core/capture_test.go briefly, plus cmd/options.go diff region and cmd/root_test.go diff region (2618-2744). Also docs/manual/wireshark.md and clabernetes/runtime.md. Let me read those diff regions and a couple of files.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 286,
  "offset": 3490
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
3490: diff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml
3491: new file mode 100644
3492: index 0000000..0422c22
3493: --- /dev/null
3494: +++ b/core/test_data/capture.clab.yml
3495: @@ -0,0 +1,15 @@
3496: +name: capture
3497: +topology:
3498: +  nodes:
3499: +    srl1:
3500: +      kind: nokia_srlinux
3501: +    srl2:
3502: +      kind: nokia_srlinux
3503: +    client:
3504: +      kind: linux
3505: +      image: alpine:3
3506: +  links:
3507: +    - endpoints: ["srl1:ethernet-1/1", "srl2:e1-1"]
3508: +    - endpoints: ["srl1:e1-2", "client:eth1"]
3509: +    - endpoints: ["client:eth2", "host:client-eth2"]
3510: +    - endpoints: ["client:eth3", "mgmt-net:client-eth3"]
3511: diff --git a/docs/cmd/capture.md b/docs/cmd/capture.md
3512: new file mode 100644
3513: index 0000000..15006ff
3514: --- /dev/null
3515: +++ b/docs/cmd/capture.md
3516: @@ -0,0 +1,134 @@
3517: +# capture command
3518: +
3519: +### Description
3520: +
3521: +The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.
3522: +
3523: +It works with every runtime:
3524: +
3525: +- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).
3526: +- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).
3527: +
3528: +The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.
3529: +
3530: +--8<-- "docs/cmd/deploy.md:env-vars-flags"
3531: +
3532: +### Usage
3533: +
3534: +`containerlab [global-flags] capture [local-flags]`
3535: +
3536: +### Flags
3537: +
3538: +#### topology | name
3539: +
3540: +Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.
3541: +
3542: +With Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.
3543: +
3544: +#### target
3545: +
3546: +The local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:
3547: +
3548: +```text
3549: +--target srl1:e1-1,e1-2 --target srl2:e1-1
3550: +```
3551: +
3552: +The node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.
3553: +
3554: +Only lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.
3555: +
3556: +#### duration
3557: +
3558: +The local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).
3559: +
3560: +#### packet-limit
3561: +
3562: +The local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.
3563: +
3564: +#### snap-length
3565: +
3566: +The local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.
3567: +
3568: +#### write
3569: +
3570: +The local `--write | -w` flag names the output file. The default `-` writes to stdout.
3571: +
3572: +#### list
3573: +
3574: +The local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.
3575: +
3576: +### Output
3577: +
3578: +The output is one pcapng section:
3579: +
3580: +- a Section Header Block with `shb_userappl` set to `containerlab`
3581: +- one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it
3582: +- Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes
3583: +
3584: +The interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.
3585: +
3586: +When the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.
3587: +
3588: +`--list -f json` prints an array:
3589: +
3590: +```json
3591: +[
3592: +  {
3593: +    "node": "srl1",
3594: +    "interface": "e1-1",
3595: +    "alias": "ethernet-1/1",
3596: +    "peer_node": "srl2",
3597: +    "peer_interface": "ethernet-1/1"
3598: +  }
3599: +]
3600: +```
3601: +
3602: +`alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.
3603: +
3604: +### How Docker and Podman captures work
3605: +
3606: +For each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.
3607: +
3608: +- Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.
3609: +- 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.
3610: +- Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.
3611: +- An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.
3612: +
3613: +The command needs root (to open packet sockets and enter network namespaces), as other lab commands do.
3614: +
3615: +### Long captures
3616: +
3617: +Docker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.
3618: +
3619: +### Examples
3620: +
3621: +#### Capture two nodes for 30 seconds into one file
3622: +
3623: +```bash
3624: +containerlab capture -t srl.clab.yml \
3625: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng
3626: +```
3627: +
3628: +#### Watch a capture live in Wireshark
3629: +
3630: +```bash
3631: +containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -
3632: +```
3633: +
3634: +#### Capture the first 100 packets with tshark
3635: +
3636: +```bash
3637: +containerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -
3638: +```
3639: +
3640: +#### List the capturable interfaces
3641: +
3642: +```bash
3643: +containerlab capture --name srl --list
3644: +```
3645: +
3646: +#### Capture a c9s lab
3647: +
3648: +```bash
3649: +containerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng
3650: +```
3651: diff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md
3652: index 3dc8e27..2354dc1 100644
3653: --- a/docs/cmd/inspect/interfaces.md
3654: +++ b/docs/cmd/inspect/interfaces.md
3655: @@ -3,10 +3,12 @@
3656:  ### Description
3657:  
3658:  The `inspect interfaces` subcommand provides information about the network interfaces of deployed nodes of a deployed lab.
3659:  The subcommand gathers information directly from deployed containers, and displays information about their operational state, network interface type, and if applicable, the applied network interface alias.
3660:  
3661: +With the [c9s runtime](../../manual/clabernetes/runtime.md#packet-capture), the listing covers the lab link interfaces of each running node, the ones [`capture`](../capture.md) accepts, with the alias the topology used, and the MAC address, index, MTU and operational state read in the node's device container. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields are the same as with Docker.
3662: +
3663:  ### Usage
3664:  
3665:  `containerlab [global-flags] inspect interfaces [local-flags]`
3666:  
3667:  A shorthand can be used for this subcommand: `int` or `intf`.
3668: diff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md
3669: index 0ce708d..8174c98 100644
3670: --- a/docs/manual/clabernetes/runtime.md
3671: +++ b/docs/manual/clabernetes/runtime.md
3672: @@ -110,10 +110,13 @@ The c9s runtime currently supports the main lab lifecycle and node operations:
3673:  | `start` | sets the node's `spec.runState` to `Running` |
3674:  | `stop` | sets the node's `spec.runState` to `Stopped` |
3675:  | `restart` | requests a Pod replacement with a `c9s.run/restart-requested` token |
3676:  | `save` | runs the node's save lifecycle inside its device container |
3677:  | `events` | watches Clabernetes resources and pods |
3678: +| `logs` | streams the device container log |
3679: +| `capture` | captures lab link interfaces through the `clabwire` sidecar into one pcapng stream |
3680: +| `inspect interfaces` | lists the capturable link interfaces with their sysfs state |
3681:  | `validate` | checks c9s compatibility without creating Kubernetes resources |
3682:  | `deploy --dry-run` | compiles and diffs Namespace, ConfigMap, NodeProfile, Link, and Node resources without changing them |
3683:  | `deploy --emit-crs` | prints the Namespace, ConfigMap, and Topology (or NodeProfile, Link, and Node) manifests deploy would create, without contacting the cluster |
3684:  
3685:  ## Requirements
3686: @@ -141,11 +144,11 @@ Containerlab needs a clabernetes release that has:
3687:  
3688:  - Node run state: `nodes.c9s.run` `spec.runState` (`Running` | `Stopped`), the
3689:    `Stopped` condition, and restart requests through the
3690:    `c9s.run/restart-requested` annotation
3691:  - the clabwire packet capture contract: `--nodeName`, repeated `--interface`,
3692: -  `--format pcapng` and `--list-interfaces`
3693: +  `--format pcapng`, `--list-interfaces` and `--stop-on-stdin-close`
3694:  - the namespace-bindable `clabernetes-lab-viewer` and `clabernetes-lab-editor`
3695:    roles
3696:  
3697:  Both features ship in the same release, so containerlab checks one field: the
3698:  published OpenAPI schema of `nodes.c9s.run` (`/openapi/v3/apis/c9s.run/v1alpha1`)
3699: @@ -159,10 +162,21 @@ an older release every other command fails like this:
3700:  the clabernetes release on this cluster is not supported: nodes.c9s.run has no
3701:  spec.runState (Node run state); the c9s runtime needs clabernetes with Node run
3702:  state and the clabwire capture contract (0.11 or newer)
3703:  ```
3704:  
3705: +A cluster that passes this check but runs a `clabwire` without
3706: +`--stop-on-stdin-close` (a development build between the two features) fails
3707: +the first capture with the same kind of error, naming the pod:
3708: +
3709: +```text
3710: +the clabernetes release on this cluster is not supported: clabwire in pod
3711: +<namespace>/<pod> does not accept packet-capture --stop-on-stdin-close; the c9s
3712: +runtime needs clabernetes with Node run state and the clabwire capture contract
3713: +(0.11 or newer)
3714: +```
3715: +
3716:  Library users can run the check up front with
3717:  `(*core.CLab).CheckLabRuntimeSupport(ctx)` or the optional
3718:  `labruntime.SupportChecker` interface; the error wraps
3719:  `labruntime.ErrUnsupportedRuntimeVersion`.
3720:  
3721: @@ -579,10 +593,82 @@ containerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timest
3722:  
3723:  It reads the `pods/log` subresource of the node's pod, so RBAC must allow
3724:  `get` on `pods/log`. Kubernetes returns stdout and stderr as one stream. See
3725:  the [`logs` command](../../cmd/logs.md) for the flags.
3726:  
3727: +## Packet capture
3728: +
3729: +[`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of
3730: +one or more nodes into one pcapng stream. Each node's pod runs the `clabwire`
3731: +sidecar, which realized the node's links; containerlab execs its capture
3732: +command (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.
3733: +No capture service runs in the cluster, and nothing is captured outside the
3734: +lab's planned link interfaces.
3735: +
3736: +```bash
3737: +# both ends of a link, for 30 seconds
3738: +containerlab -r c9s capture -t clos.clab.yml \
3739: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng
3740: +
3741: +# live in Wireshark until Wireshark or Ctrl+C ends it
3742: +containerlab -r c9s capture --name clos --target srl1:e1-1,e1-2 -w - | wireshark -k -i -
3743: +
3744: +# what can be captured, with the peer of each link
3745: +containerlab -r c9s capture --name clos --list
3746: +```
3747: +
3748: +How it works:
3749: +
3750: +- containerlab locates each target node's pod and runs one `clabwire` capture
3751: +  per node, with `--nodeName`, every requested interface of that node,
3752: +  `--format pcapng` and `--stop-on-stdin-close`, with stdin attached.
3753: +- The streams are merged into one section: one Interface Description Block per
3754: +  target named `<node>:<interface>` (the node as the topology spells it),
3755: +  written before the first packet, and the packets of every target with their
3756: +  interface IDs remapped.
3757: +- Packets are written in timestamp order. Each node's stream arrives over its
3758: +  own exec stream, so the merged stream holds every packet for 250 ms and
3759: +  writes the held packets ordered by timestamp. A packet that arrives later
3760: +  than that, stamped before a packet already written, is written as it comes;
3761: +  the number of such packets goes to the debug log.
3762: +- `clabwire` limits one capture to one hour. Longer captures, and captures
3763: +  without `--duration`, chain captures with a few seconds of overlap and switch
3764: +  in the middle of it; packets near the switch are matched by content so each
3765: +  is written once. A follow-up that does not start in time is reported as a
3766: +  gap, with its time span.
3767: +- `clabwire` audit records (JSON on its stderr, schema
3768: +  `c9s.direct-packet-capture-audit/v1alpha1`) with status `Denied` or `Failed`
3769: +  end the command with their reason. `Started` and `Succeeded` go to the debug
3770: +  log.
3771: +
3772: +Interface names are the names inside the node; targets may also use the alias
3773: +the topology used for an interface:
3774: +
3775: +| Kind | Interface | Alias |

(Showing lines 3490-3775 of 7018. Use offset=3776 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196545211001Cnj3bz7rtQWP35",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196544960001jOFhFncIdgj9Pi",
  "callID": "call_31d59cf186e74cb0b910db1a",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 286,
      "offset": 3490
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n3490: diff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml\n3491: new file mode 100644\n3492: index 0000000..0422c22\n3493: --- /dev/null\n3494: +++ b/core/test_data/capture.clab.yml\n3495: @@ -0,0 +1,15 @@\n3496: +name: capture\n3497: +topology:\n3498: +  nodes:\n3499: +    srl1:\n3500: +      kind: nokia_srlinux\n3501: +    srl2:\n3502: +      kind: nokia_srlinux\n3503: +    client:\n3504: +      kind: linux\n3505: +      image: alpine:3\n3506: +  links:\n3507: +    - endpoints: [\"srl1:ethernet-1/1\", \"srl2:e1-1\"]\n3508: +    - endpoints: [\"srl1:e1-2\", \"client:eth1\"]\n3509: +    - endpoints: [\"client:eth2\", \"host:client-eth2\"]\n3510: +    - endpoints: [\"client:eth3\", \"mgmt-net:client-eth3\"]\n3511: diff --git a/docs/cmd/capture.md b/docs/cmd/capture.md\n3512: new file mode 100644\n3513: index 0000000..15006ff\n3514: --- /dev/null\n3515: +++ b/docs/cmd/capture.md\n3516: @@ -0,0 +1,134 @@\n3517: +# capture command\n3518: +\n3519: +### Description\n3520: +\n3521: +The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.\n3522: +\n3523: +It works with every runtime:\n3524: +\n3525: +- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).\n3526: +- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).\n3527: +\n3528: +The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.\n3529: +\n3530: +--8<-- \"docs/cmd/deploy.md:env-vars-flags\"\n3531: +\n3532: +### Usage\n3533: +\n3534: +`containerlab [global-flags] capture [local-flags]`\n3535: +\n3536: +### Flags\n3537: +\n3538: +#### topology | name\n3539: +\n3540: +Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.\n3541: +\n3542: +With Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.\n3543: +\n3544: +#### target\n3545: +\n3546: +The local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:\n3547: +\n3548: +```text\n3549: +--target srl1:e1-1,e1-2 --target srl2:e1-1\n3550: +```\n3551: +\n3552: +The node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.\n3553: +\n3554: +Only lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.\n3555: +\n3556: +#### duration\n3557: +\n3558: +The local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).\n3559: +\n3560: +#### packet-limit\n3561: +\n3562: +The local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.\n3563: +\n3564: +#### snap-length\n3565: +\n3566: +The local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.\n3567: +\n3568: +#### write\n3569: +\n3570: +The local `--write | -w` flag names the output file. The default `-` writes to stdout.\n3571: +\n3572: +#### list\n3573: +\n3574: +The local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.\n3575: +\n3576: +### Output\n3577: +\n3578: +The output is one pcapng section:\n3579: +\n3580: +- a Section Header Block with `shb_userappl` set to `containerlab`\n3581: +- one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it\n3582: +- Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes\n3583: +\n3584: +The interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.\n3585: +\n3586: +When the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.\n3587: +\n3588: +`--list -f json` prints an array:\n3589: +\n3590: +```json\n3591: +[\n3592: +  {\n3593: +    \"node\": \"srl1\",\n3594: +    \"interface\": \"e1-1\",\n3595: +    \"alias\": \"ethernet-1/1\",\n3596: +    \"peer_node\": \"srl2\",\n3597: +    \"peer_interface\": \"ethernet-1/1\"\n3598: +  }\n3599: +]\n3600: +```\n3601: +\n3602: +`alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.\n3603: +\n3604: +### How Docker and Podman captures work\n3605: +\n3606: +For each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.\n3607: +\n3608: +- Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.\n3609: +- 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.\n3610: +- Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.\n3611: +- An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.\n3612: +\n3613: +The command needs root (to open packet sockets and enter network namespaces), as other lab commands do.\n3614: +\n3615: +### Long captures\n3616: +\n3617: +Docker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.\n3618: +\n3619: +### Examples\n3620: +\n3621: +#### Capture two nodes for 30 seconds into one file\n3622: +\n3623: +```bash\n3624: +containerlab capture -t srl.clab.yml \\\n3625: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n3626: +```\n3627: +\n3628: +#### Watch a capture live in Wireshark\n3629: +\n3630: +```bash\n3631: +containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n3632: +```\n3633: +\n3634: +#### Capture the first 100 packets with tshark\n3635: +\n3636: +```bash\n3637: +containerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -\n3638: +```\n3639: +\n3640: +#### List the capturable interfaces\n3641: +\n3642: +```bash\n3643: +containerlab capture --name srl --list\n3644: +```\n3645: +\n3646: +#### Capture a c9s lab\n3647: +\n3648: +```bash\n3649: +containerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng\n3650: +```\n3651: diff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md\n3652: index 3dc8e27..2354dc1 100644\n3653: --- a/docs/cmd/inspect/interfaces.md\n3654: +++ b/docs/cmd/inspect/interfaces.md\n3655: @@ -3,10 +3,12 @@\n3656:  ### Description\n3657:  \n3658:  The `inspect interfaces` subcommand provides information about the network interfaces of deployed nodes of a deployed lab.\n3659:  The subcommand gathers information directly from deployed containers, and displays information about their operational state, network interface type, and if applicable, the applied network interface alias.\n3660:  \n3661: +With the [c9s runtime](../../manual/clabernetes/runtime.md#packet-capture), the listing covers the lab link interfaces of each running node, the ones [`capture`](../capture.md) accepts, with the alias the topology used, and the MAC address, index, MTU and operational state read in the node's device container. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields are the same as with Docker.\n3662: +\n3663:  ### Usage\n3664:  \n3665:  `containerlab [global-flags] inspect interfaces [local-flags]`\n3666:  \n3667:  A shorthand can be used for this subcommand: `int` or `intf`.\n3668: diff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md\n3669: index 0ce708d..8174c98 100644\n3670: --- a/docs/manual/clabernetes/runtime.md\n3671: +++ b/docs/manual/clabernetes/runtime.md\n3672: @@ -110,10 +110,13 @@ The c9s runtime currently supports the main lab lifecycle and node operations:\n3673:  | `start` | sets the node's `spec.runState` to `Running` |\n3674:  | `stop` | sets the node's `spec.runState` to `Stopped` |\n3675:  | `restart` | requests a Pod replacement with a `c9s.run/restart-requested` token |\n3676:  | `save` | runs the node's save lifecycle inside its device container |\n3677:  | `events` | watches Clabernetes resources and pods |\n3678: +| `logs` | streams the device container log |\n3679: +| `capture` | captures lab link interfaces through the `clabwire` sidecar into one pcapng stream |\n3680: +| `inspect interfaces` | lists the capturable link interfaces with their sysfs state |\n3681:  | `validate` | checks c9s compatibility without creating Kubernetes resources |\n3682:  | `deploy --dry-run` | compiles and diffs Namespace, ConfigMap, NodeProfile, Link, and Node resources without changing them |\n3683:  | `deploy --emit-crs` | prints the Namespace, ConfigMap, and Topology (or NodeProfile, Link, and Node) manifests deploy would create, without contacting the cluster |\n3684:  \n3685:  ## Requirements\n3686: @@ -141,11 +144,11 @@ Containerlab needs a clabernetes release that has:\n3687:  \n3688:  - Node run state: `nodes.c9s.run` `spec.runState` (`Running` | `Stopped`), the\n3689:    `Stopped` condition, and restart requests through the\n3690:    `c9s.run/restart-requested` annotation\n3691:  - the clabwire packet capture contract: `--nodeName`, repeated `--interface`,\n3692: -  `--format pcapng` and `--list-interfaces`\n3693: +  `--format pcapng`, `--list-interfaces` and `--stop-on-stdin-close`\n3694:  - the namespace-bindable `clabernetes-lab-viewer` and `clabernetes-lab-editor`\n3695:    roles\n3696:  \n3697:  Both features ship in the same release, so containerlab checks one field: the\n3698:  published OpenAPI schema of `nodes.c9s.run` (`/openapi/v3/apis/c9s.run/v1alpha1`)\n3699: @@ -159,10 +162,21 @@ an older release every other command fails like this:\n3700:  the clabernetes release on this cluster is not supported: nodes.c9s.run has no\n3701:  spec.runState (Node run state); the c9s runtime needs clabernetes with Node run\n3702:  state and the clabwire capture contract (0.11 or newer)\n3703:  ```\n3704:  \n3705: +A cluster that passes this check but runs a `clabwire` without\n3706: +`--stop-on-stdin-close` (a development build between the two features) fails\n3707: +the first capture with the same kind of error, naming the pod:\n3708: +\n3709: +```text\n3710: +the clabernetes release on this cluster is not supported: clabwire in pod\n3711: +<namespace>/<pod> does not accept packet-capture --stop-on-stdin-close; the c9s\n3712: +runtime needs clabernetes with Node run state and the clabwire capture contract\n3713: +(0.11 or newer)\n3714: +```\n3715: +\n3716:  Library users can run the check up front with\n3717:  `(*core.CLab).CheckLabRuntimeSupport(ctx)` or the optional\n3718:  `labruntime.SupportChecker` interface; the error wraps\n3719:  `labruntime.ErrUnsupportedRuntimeVersion`.\n3720:  \n3721: @@ -579,10 +593,82 @@ containerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timest\n3722:  \n3723:  It reads the `pods/log` subresource of the node's pod, so RBAC must allow\n3724:  `get` on `pods/log`. Kubernetes returns stdout and stderr as one stream. See\n3725:  the [`logs` command](../../cmd/logs.md) for the flags.\n3726:  \n3727: +## Packet capture\n3728: +\n3729: +[`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of\n3730: +one or more nodes into one pcapng stream. Each node's pod runs the `clabwire`\n3731: +sidecar, which realized the node's links; containerlab execs its capture\n3732: +command (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.\n3733: +No capture service runs in the cluster, and nothing is captured outside the\n3734: +lab's planned link interfaces.\n3735: +\n3736: +```bash\n3737: +# both ends of a link, for 30 seconds\n3738: +containerlab -r c9s capture -t clos.clab.yml \\\n3739: +  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n3740: +\n3741: +# live in Wireshark until Wireshark or Ctrl+C ends it\n3742: +containerlab -r c9s capture --name clos --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n3743: +\n3744: +# what can be captured, with the peer of each link\n3745: +containerlab -r c9s capture --name clos --list\n3746: +```\n3747: +\n3748: +How it works:\n3749: +\n3750: +- containerlab locates each target node's pod and runs one `clabwire` capture\n3751: +  per node, with `--nodeName`, every requested interface of that node,\n3752: +  `--format pcapng` and `--stop-on-stdin-close`, with stdin attached.\n3753: +- The streams are merged into one section: one Interface Description Block per\n3754: +  target named `<node>:<interface>` (the node as the topology spells it),\n3755: +  written before the first packet, and the packets of every target with their\n3756: +  interface IDs remapped.\n3757: +- Packets are written in timestamp order. Each node's stream arrives over its\n3758: +  own exec stream, so the merged stream holds every packet for 250 ms and\n3759: +  writes the held packets ordered by timestamp. A packet that arrives later\n3760: +  than that, stamped before a packet already written, is written as it comes;\n3761: +  the number of such packets goes to the debug log.\n3762: +- `clabwire` limits one capture to one hour. Longer captures, and captures\n3763: +  without `--duration`, chain captures with a few seconds of overlap and switch\n3764: +  in the middle of it; packets near the switch are matched by content so each\n3765: +  is written once. A follow-up that does not start in time is reported as a\n3766: +  gap, with its time span.\n3767: +- `clabwire` audit records (JSON on its stderr, schema\n3768: +  `c9s.direct-packet-capture-audit/v1alpha1`) with status `Denied` or `Failed`\n3769: +  end the command with their reason. `Started` and `Succeeded` go to the debug\n3770: +  log.\n3771: +\n3772: +Interface names are the names inside the node; targets may also use the alias\n3773: +the topology used for an interface:\n3774: +\n3775: +| Kind | Interface | Alias |\n\n(Showing lines 3490-3775 of 7018. Use offset=3776 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "diff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml\nnew file mode 100644\nindex 0000000..0422c22\n--- /dev/null\n+++ b/core/test_data/capture.clab.yml\n@@ -0,0 +1,15 @@\n+name: capture\n+topology:\n+  nodes:\n+    srl1:\n+      kind: nokia_srlinux\n+    srl2:\n+      kind: nokia_srlinux\n+    client:\n+      kind: linux\n+      image: alpine:3\n+  links:\n+    - endpoints: [\"srl1:ethernet-1/1\", \"srl2:e1-1\"]\n+    - endpoints: [\"srl1:e1-2\", \"client:eth1\"]\n+    - endpoints: [\"client:eth2\", \"host:client-eth2\"]",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "diff --git a/core/test_data/capture.clab.yml b/core/test_data/capture.clab.yml\nnew file mode 100644\nindex 0000000..0422c22\n--- /dev/null\n+++ b/core/test_data/capture.clab.yml\n@@ -0,0 +1,15 @@\n+name: capture\n+topology:\n+  nodes:\n+    srl1:\n+      kind: nokia_srlinux\n+    srl2:\n+      kind: nokia_srlinux\n+    client:\n+      kind: linux\n+      image: alpine:3\n+  links:\n+    - endpoints: [\"srl1:ethernet-1/1\", \"srl2:e1-1\"]\n+    - endpoints: [\"srl1:e1-2\", \"client:eth1\"]\n+    - endpoints: [\"client:eth2\", \"host:client-eth2\"]\n+    - endpoints: [\"client:eth3\", \"mgmt-net:client-eth3\"]\ndiff --git a/docs/cmd/capture.md b/docs/cmd/capture.md\nnew file mode 100644\nindex 0000000..15006ff\n--- /dev/null\n+++ b/docs/cmd/capture.md\n@@ -0,0 +1,134 @@\n+# capture command\n+\n+### Description\n+\n+The `capture` command captures packets on lab link interfaces of one or more nodes and writes them as one [pcapng](https://www.ietf.org/archive/id/draft-ietf-opsawg-pcapng-03.html) stream, to a file or to stdout for Wireshark.\n+\n+It works with every runtime:\n+\n+- **Docker and Podman**: containerlab opens a packet socket on each interface inside the node's network namespace. Nothing runs in the node, the node image needs no capture tools, and no extra software is needed on the host: the command needs root, like `deploy`. See [How Docker and Podman captures work](#how-docker-and-podman-captures-work).\n+- **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).\n+\n+The output is the same with both. [Edgeshark](../manual/wireshark.md) remains an alternative for Docker labs when you prefer to pick interfaces in a GUI.\n+\n+--8<-- \"docs/cmd/deploy.md:env-vars-flags\"\n+\n+### Usage\n+\n+`containerlab [global-flags] capture [local-flags]`\n+\n+### Flags\n+\n+#### topology | name\n+\n+Use the global `--topo | -t` flag to reference the lab topology file, or use the global `--name` flag to reference an already deployed lab by name. Without either, containerlab looks for a `*.clab.yml` file in the current directory, like the other lab commands.\n+\n+With Docker and Podman, the capturable interfaces are the links of the topology file, so `--name` needs the topology file the lab was deployed from to still be in place.\n+\n+#### target\n+\n+The local `--target` flag selects what to capture, as `<node>:<interface>[,<interface>...]`. Repeat it for more nodes:\n+\n+```text\n+--target srl1:e1-1,e1-2 --target srl2:e1-1\n+```\n+\n+The node name ends at the first colon, so interface names such as `1/1/3` or `ethernet-1/1` need no quoting. Node names are accepted as the topology file spells them; with Docker and Podman also as the container name (`clab-srl-srl1`), with c9s also as they were sanitized for Kubernetes (`R1` or `r1`). Interfaces are accepted by their name in the node or by the alias the topology used for them (`e1-1` or `ethernet-1/1` for SR Linux). `--list` shows both.\n+\n+Only lab link interfaces can be captured; the management interface cannot. An interface that is not a link interface of the node fails the command before anything is captured, and the error lists the node's capturable interfaces.\n+\n+#### duration\n+\n+The local `--duration` flag stops the capture after the given time (`30s`, `5m`, `2h`). The default `0` captures until the command is interrupted with Ctrl+C or SIGTERM. Captures may run longer than an hour; see [Long captures](#long-captures).\n+\n+#### packet-limit\n+\n+The local `--packet-limit` flag stops the capture after that many packets, counted across all targets. `0`, the default, means no limit.\n+\n+#### snap-length\n+\n+The local `--snap-length` flag sets how many bytes of each packet are kept, from 64 to 1048576. The default `0` keeps 256 KiB.\n+\n+#### write\n+\n+The local `--write | -w` flag names the output file. The default `-` writes to stdout.\n+\n+#### list\n+\n+The local `--list` flag lists the interfaces `capture` accepts, for every running node, with the node and interface at the other end of each link, instead of capturing. `--format | -f` selects `table` (default) or `json`.\n+\n+### Output\n+\n+The output is one pcapng section:\n+\n+- a Section Header Block with `shb_userappl` set to `containerlab`\n+- one Interface Description Block per target, in the order of the `--target` flags, written before any packet: link type Ethernet, the snap length, nanosecond timestamps, and the name `<node>:<interface>` (for example `srl1:e1-1`), with the node named as the topology spells it\n+- Enhanced Packet Blocks of all targets, in timestamp order: packets are held briefly (100 ms with Docker and Podman, 250 ms with c9s) and written ordered by timestamp, so packets of different interfaces come out in order even though each one is read on its own; a packet that arrives later than that is written as it comes\n+\n+The interface name shows in Wireshark's interface column (`frame.interface_name`), so a capture of several nodes can be filtered by node and interface.\n+\n+When the capture ends (duration, packet limit, Ctrl+C or SIGTERM), the command finishes the stream and exits with code 0; the file is a valid capture. Status messages go to stderr. With c9s, every `clabwire` capture in the pods ends with the command: containerlab closes its stdin, and `clabwire` (`--stop-on-stdin-close`) stops.\n+\n+`--list -f json` prints an array:\n+\n+```json\n+[\n+  {\n+    \"node\": \"srl1\",\n+    \"interface\": \"e1-1\",\n+    \"alias\": \"ethernet-1/1\",\n+    \"peer_node\": \"srl2\",\n+    \"peer_interface\": \"ethernet-1/1\"\n+  }\n+]\n+```\n+\n+`alias` is present only when the topology used an alias for the interface. `peer_node` is `host` for a host endpoint and `mgmt-net` for a management network endpoint.\n+\n+### How Docker and Podman captures work\n+\n+For each target, containerlab enters the node's network namespace, opens a Linux packet socket (`AF_PACKET`) bound to the interface, and leaves the namespace again; the socket keeps capturing on that interface. This is what `tcpdump` does inside the node, without needing `tcpdump` in the node or on the host. All sockets are opened before the first byte is written, so a capture that cannot start (a node that does not run, a missing interface) fails without output.\n+\n+- Packets carry the kernel's receive timestamps, so packets of different nodes compare on one clock.\n+- 802.1Q tags, which the kernel keeps outside the frame, are put back in place, so VLAN traffic shows its tags as on the wire.\n+- Each socket is in promiscuous mode for as long as it is open; the interface returns to its previous state when the capture ends.\n+- An interface that goes down and up again keeps being captured. When an interface disappears, for example while its node restarts, containerlab waits for it and reattaches once the node is back (`containerlab restart --node`). The time it was gone is reported as a warning with its start and end time.\n+\n+The command needs root (to open packet sockets and enter network namespaces), as other lab commands do.\n+\n+### Long captures\n+\n+Docker and Podman captures have no length limit. With c9s, one `clabwire` capture lasts at most one hour. `capture` chains captures: it starts the next one shortly before the current one ends, lets both run for a few seconds, and switches between them in the middle of that overlap. The repeated section and interface headers of the follow-up are dropped, and packets seen by both captures near the switch are written once (they are matched by content, because each capture stamps packets when it reads them). Once the switch time has passed, the previous capture is stopped through its stdin instead of running to its end. If a follow-up capture does not start in time, the missing interval is reported as a warning with its start and end time; it is never skipped silently. The timestamp order holds across switches: while one node's capture switches, packets of other nodes stamped after the switch wait for it.\n+\n+### Examples\n+\n+#### Capture two nodes for 30 seconds into one file\n+\n+```bash\n+containerlab capture -t srl.clab.yml \\\n+  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n+```\n+\n+#### Watch a capture live in Wireshark\n+\n+```bash\n+containerlab capture --name srl --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n+```\n+\n+#### Capture the first 100 packets with tshark\n+\n+```bash\n+containerlab capture --name srl --target srl1:ethernet-1/1 --packet-limit 100 -w - | tshark -r -\n+```\n+\n+#### List the capturable interfaces\n+\n+```bash\n+containerlab capture --name srl --list\n+```\n+\n+#### Capture a c9s lab\n+\n+```bash\n+containerlab -r c9s capture --name srl --target srl1:e1-1 --target srl2:e1-1 -w srl.pcapng\n+```\ndiff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md\nindex 3dc8e27..2354dc1 100644\n--- a/docs/cmd/inspect/interfaces.md\n+++ b/docs/cmd/inspect/interfaces.md\n@@ -3,10 +3,12 @@\n ### Description\n \n The `inspect interfaces` subcommand provides information about the network interfaces of deployed nodes of a deployed lab.\n The subcommand gathers information directly from deployed containers, and displays information about their operational state, network interface type, and if applicable, the applied network interface alias.\n \n+With the [c9s runtime](../../manual/clabernetes/runtime.md#packet-capture), the listing covers the lab link interfaces of each running node, the ones [`capture`](../capture.md) accepts, with the alias the topology used, and the MAC address, index, MTU and operational state read in the node's device container. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields are the same as with Docker.\n+\n ### Usage\n \n `containerlab [global-flags] inspect interfaces [local-flags]`\n \n A shorthand can be used for this subcommand: `int` or `intf`.\ndiff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md\nindex 0ce708d..8174c98 100644\n--- a/docs/manual/clabernetes/runtime.md\n+++ b/docs/manual/clabernetes/runtime.md\n@@ -110,10 +110,13 @@ The c9s runtime currently supports the main lab lifecycle and node operations:\n | `start` | sets the node's `spec.runState` to `Running` |\n | `stop` | sets the node's `spec.runState` to `Stopped` |\n | `restart` | requests a Pod replacement with a `c9s.run/restart-requested` token |\n | `save` | runs the node's save lifecycle inside its device container |\n | `events` | watches Clabernetes resources and pods |\n+| `logs` | streams the device container log |\n+| `capture` | captures lab link interfaces through the `clabwire` sidecar into one pcapng stream |\n+| `inspect interfaces` | lists the capturable link interfaces with their sysfs state |\n | `validate` | checks c9s compatibility without creating Kubernetes resources |\n | `deploy --dry-run` | compiles and diffs Namespace, ConfigMap, NodeProfile, Link, and Node resources without changing them |\n | `deploy --emit-crs` | prints the Namespace, ConfigMap, and Topology (or NodeProfile, Link, and Node) manifests deploy would create, without contacting the cluster |\n \n ## Requirements\n@@ -141,11 +144,11 @@ Containerlab needs a clabernetes release that has:\n \n - Node run state: `nodes.c9s.run` `spec.runState` (`Running` | `Stopped`), the\n   `Stopped` condition, and restart requests through the\n   `c9s.run/restart-requested` annotation\n - the clabwire packet capture contract: `--nodeName`, repeated `--interface`,\n-  `--format pcapng` and `--list-interfaces`\n+  `--format pcapng`, `--list-interfaces` and `--stop-on-stdin-close`\n - the namespace-bindable `clabernetes-lab-viewer` and `clabernetes-lab-editor`\n   roles\n \n Both features ship in the same release, so containerlab checks one field: the\n published OpenAPI schema of `nodes.c9s.run` (`/openapi/v3/apis/c9s.run/v1alpha1`)\n@@ -159,10 +162,21 @@ an older release every other command fails like this:\n the clabernetes release on this cluster is not supported: nodes.c9s.run has no\n spec.runState (Node run state); the c9s runtime needs clabernetes with Node run\n state and the clabwire capture contract (0.11 or newer)\n ```\n \n+A cluster that passes this check but runs a `clabwire` without\n+`--stop-on-stdin-close` (a development build between the two features) fails\n+the first capture with the same kind of error, naming the pod:\n+\n+```text\n+the clabernetes release on this cluster is not supported: clabwire in pod\n+<namespace>/<pod> does not accept packet-capture --stop-on-stdin-close; the c9s\n+runtime needs clabernetes with Node run state and the clabwire capture contract\n+(0.11 or newer)\n+```\n+\n Library users can run the check up front with\n `(*core.CLab).CheckLabRuntimeSupport(ctx)` or the optional\n `labruntime.SupportChecker` interface; the error wraps\n `labruntime.ErrUnsupportedRuntimeVersion`.\n \n@@ -579,10 +593,82 @@ containerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timest\n \n It reads the `pods/log` subresource of the node's pod, so RBAC must allow\n `get` on `pods/log`. Kubernetes returns stdout and stderr as one stream. See\n the [`logs` command](../../cmd/logs.md) for the flags.\n \n+## Packet capture\n+\n+[`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of\n+one or more nodes into one pcapng stream. Each node's pod runs the `clabwire`\n+sidecar, which realized the node's links; containerlab execs its capture\n+command (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.\n+No capture service runs in the cluster, and nothing is captured outside the\n+lab's planned link interfaces.\n+\n+```bash\n+# both ends of a link, for 30 seconds\n+containerlab -r c9s capture -t clos.clab.yml \\\n+  --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n+\n+# live in Wireshark until Wireshark or Ctrl+C ends it\n+containerlab -r c9s capture --name clos --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n+\n+# what can be captured, with the peer of each link\n+containerlab -r c9s capture --name clos --list\n+```\n+\n+How it works:\n+\n+- containerlab locates each target node's pod and runs one `clabwire` capture\n+  per node, with `--nodeName`, every requested interface of that node,\n+  `--format pcapng` and `--stop-on-stdin-close`, with stdin attached.\n+- The streams are merged into one section: one Interface Description Block per\n+  target named `<node>:<interface>` (the node as the topology spells it),\n+  written before the first packet, and the packets of every target with their\n+  interface IDs remapped.\n+- Packets are written in timestamp order. Each node's stream arrives over its\n+  own exec stream, so the merged stream holds every packet for 250 ms and\n+  writes the held packets ordered by timestamp. A packet that arrives later\n+  than that, stamped before a packet already written, is written as it comes;\n+  the number of such packets goes to the debug log.\n+- `clabwire` limits one capture to one hour. Longer captures, and captures\n+  without `--duration`, chain captures with a few seconds of overlap and switch\n+  in the middle of it; packets near the switch are matched by content so each\n+  is written once. A follow-up that does not start in time is reported as a\n+  gap, with its time span.\n+- `clabwire` audit records (JSON on its stderr, schema\n+  `c9s.direct-packet-capture-audit/v1alpha1`) with status `Denied` or `Failed`\n+  end the command with their reason. `Started` and `Succeeded` go to the debug\n+  log.\n+\n+Interface names are the names inside the node; targets may also use the alias\n+the topology used for an interface:\n+\n+| Kind | Interface | Alias |",
        "lineStart": 3490,
        "lineEnd": 3775,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523470868,
      "end": 1793523470883
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/core/capture_test.go",
  "limit": 400
}

Output

<path>/source/head/core/capture_test.go</path>
<type>file</type>
<content>
1: package core
2: 
3: import (
4: 	"bytes"
5: 	"context"
6: 	"io"
7: 	"slices"
8: 	"strings"
9: 	"testing"
10: 
11: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
12: 	clabtypes "github.com/srl-labs/containerlab/types"
13: )
14: 
15: // captureLabRuntime records the capture requests core sends.
16: type captureLabRuntime struct {
17: 	clablabruntime.LabRuntime
18: 
19: 	nodeRequest    clablabruntime.NodeRequest
20: 	captureRequest clablabruntime.CaptureRequest
21: }
22: 
23: func (r *captureLabRuntime) CaptureInterfaces(
24: 	_ context.Context,
25: 	req clablabruntime.NodeRequest,
26: ) ([]clablabruntime.CaptureInterface, error) {
27: 	r.nodeRequest = req
28: 
29: 	return []clablabruntime.CaptureInterface{{Node: "r1", Interface: "eth1"}}, nil
30: }
31: 
32: func (r *captureLabRuntime) Capture(
33: 	_ context.Context,
34: 	req clablabruntime.CaptureRequest,
35: 	w io.Writer,
36: ) error {
37: 	r.captureRequest = req
38: 	_, err := io.WriteString(w, "pcapng")
39: 
40: 	return err
41: }
42: 
43: func (r *captureLabRuntime) InspectInterfaces(
44: 	_ context.Context,
45: 	req clablabruntime.NodeRequest,
46: ) ([]*clabtypes.ContainerInterfaces, error) {
47: 	r.nodeRequest = req
48: 
49: 	return []*clabtypes.ContainerInterfaces{{ContainerName: "lab1-r1"}}, nil
50: }
51: 
52: func TestCaptureHelpersFillLabAndIdentity(t *testing.T) {
53: 	t.Parallel()
54: 
55: 	lr := &captureLabRuntime{}
56: 	c := newAccessTestCLab(lr)
57: 	ctx := context.Background()
58: 
59: 	interfaces, err := c.CaptureInterfaces(ctx, "R1")
60: 	if err != nil || len(interfaces) != 1 {
61: 		t.Fatalf("CaptureInterfaces() = %+v, %v", interfaces, err)
62: 	}
63: 	if lr.nodeRequest.Name != "lab1" || lr.nodeRequest.Nodes[0] != "R1" ||
64: 		!lr.nodeRequest.Identity.Equal(testIdentity) {
65: 		t.Fatalf("interfaces request = %+v", lr.nodeRequest)
66: 	}
67: 
68: 	var out bytes.Buffer
69: 	if err := c.Capture(ctx, clablabruntime.CaptureRequest{
70: 		Targets: []clablabruntime.CaptureTarget{{Node: "r1", Interface: "eth1"}},
71: 	}, &out); err != nil {
72: 		t.Fatal(err)
73: 	}
74: 	if out.String() != "pcapng" || lr.captureRequest.Name != "lab1" ||
75: 		!lr.captureRequest.Identity.Equal(testIdentity) {
76: 		t.Fatalf("capture request = %+v, output %q", lr.captureRequest, out.String())
77: 	}
78: 
79: 	ifaces, err := c.LabRuntimeInterfaces(ctx, "r1")
80: 	if err != nil || len(ifaces) != 1 || lr.nodeRequest.Nodes[0] != "r1" {
81: 		t.Fatalf("LabRuntimeInterfaces() = %+v, %v, request %+v", ifaces, err, lr.nodeRequest)
82: 	}
83: 	if _, err := c.LabRuntimeInterfaces(ctx, ""); err != nil || lr.nodeRequest.Nodes != nil {
84: 		t.Fatalf("all nodes request = %+v, %v", lr.nodeRequest, err)
85: 	}
86: }
87: 
88: // newLocalCaptureCLab loads the capture test topology. Its host and mgmt-net links register
89: // endpoints on link nodes the whole process shares, so the tests using it do not run in
90: // parallel and release the endpoints when they end.
91: func newLocalCaptureCLab(t *testing.T) *CLab {
92: 	t.Helper()
93: 
94: 	c, err := NewContainerLab(WithTopoPath("test_data/capture.clab.yml", nil))
95: 	if err != nil {
96: 		t.Fatal(err)
97: 	}
98: 	t.Cleanup(c.resetResolvedLinks)
99: 
100: 	return c
101: }
102: 
103: func TestLocalCaptureInterfacesComeFromTheTopologyLinks(t *testing.T) {
104: 	c := newLocalCaptureCLab(t)
105: 
106: 	got, err := c.CaptureInterfaces(context.Background(), "srl1", "client")
107: 	if err != nil {
108: 		t.Fatal(err)
109: 	}
110: 	want := []clablabruntime.CaptureInterface{
111: 		{Node: "client", Interface: "eth1", PeerNode: "srl1", PeerInterface: "e1-2"},
112: 		{Node: "client", Interface: "eth2", PeerNode: "host", PeerInterface: "client-eth2"},
113: 		{Node: "client", Interface: "eth3", PeerNode: "mgmt-net", PeerInterface: "client-eth3"},
114: 		{
115: 			Node: "srl1", Interface: "e1-1", Alias: "ethernet-1/1",
116: 			PeerNode: "srl2", PeerInterface: "e1-1",
117: 		},
118: 		{Node: "srl1", Interface: "e1-2", PeerNode: "client", PeerInterface: "eth1"},
119: 	}
120: 	if !slices.Equal(got, want) {
121: 		t.Fatalf("CaptureInterfaces() =\n%+v\nwant\n%+v", got, want)
122: 	}
123: 
124: 	if _, err := c.CaptureInterfaces(context.Background(), "r9"); err == nil ||
125: 		!strings.Contains(err.Error(), `node "r9" is not part of lab "capture"`) {
126: 		t.Fatalf("unknown node: error = %v", err)
127: 	}
128: }
129: 
130: func TestLocalCaptureTargetsResolveByNameOrAlias(t *testing.T) {
131: 	c := newLocalCaptureCLab(t)
132: 
133: 	targets, err := c.resolveLocalCaptureTargets([]clablabruntime.CaptureTarget{
134: 		{Node: "srl2", Interface: "e1-1"},
135: 		{Node: "srl1", Interface: "ethernet-1/1"},
136: 		{Node: "clab-capture-client", Interface: "eth2"},
137: 	})
138: 	if err != nil {
139: 		t.Fatal(err)
140: 	}
141: 	var got []string
142: 	for _, target := range targets {
143: 		if target.Exec == nil {
144: 			t.Fatalf("target %s:%s has no namespace exec", target.Node, target.Interface)
145: 		}
146: 		got = append(got, target.Node+":"+target.Interface)
147: 	}
148: 	if want := []string{"srl2:e1-1", "srl1:e1-1", "client:eth2"}; !slices.Equal(got, want) {
149: 		t.Fatalf("targets = %v, want %v", got, want)
150: 	}
151: 
152: 	for _, tc := range []struct {
153: 		name    string
154: 		targets []clablabruntime.CaptureTarget
155: 		want    string
156: 	}{
157: 		{
158: 			name:    "management interface",
159: 			targets: []clablabruntime.CaptureTarget{{Node: "client", Interface: "eth0"}},
160: 			want: `interface "eth0" of node "client" is not a capturable link interface; ` +
161: 				"capturable: eth1, eth2, eth3",
162: 		},
163: 		{
164: 			name: "same interface twice",
165: 			targets: []clablabruntime.CaptureTarget{
166: 				{Node: "srl1", Interface: "e1-1"}, {Node: "srl1", Interface: "ethernet-1/1"},
167: 			},
168: 			want: `interface "e1-1" of node "srl1" is requested more than once`,
169: 		},
170: 		{
171: 			name:    "unknown node",
172: 			targets: []clablabruntime.CaptureTarget{{Node: "r9", Interface: "eth1"}},
173: 			want:    `node "r9" is not part of lab "capture"`,
174: 		},
175: 	} {
176: 		if _, err := c.resolveLocalCaptureTargets(tc.targets); err == nil ||
177: 			!strings.Contains(err.Error(), tc.want) {
178: 			t.Errorf("%s: error = %v, want %q", tc.name, err, tc.want)
179: 		}
180: 	}
181: }
182: 
183: func TestLocalCaptureNeedsTheTopology(t *testing.T) {
184: 	t.Parallel()
185: 
186: 	c := &CLab{Config: &Config{Name: "lab1"}, globalRuntimeName: "docker"}
187: 	err := c.Capture(context.Background(), clablabruntime.CaptureRequest{
188: 		Targets: []clablabruntime.CaptureTarget{{Node: "r1", Interface: "eth1"}},
189: 	}, io.Discard)
190: 	if err == nil || !strings.Contains(err.Error(), `the topology of lab "lab1" is not available`) {
191: 		t.Fatalf("error = %v", err)
192: 	}
193: 	if err := c.Capture(context.Background(), clablabruntime.CaptureRequest{},
194: 		io.Discard); err == nil || !strings.Contains(err.Error(), "at least one capture target") {
195: 		t.Fatalf("no targets: error = %v", err)
196: 	}
197: }
198: 
199: func TestLabRuntimeWithoutCaptureFails(t *testing.T) {
200: 	t.Parallel()
201: 
202: 	unsupported := newAccessTestCLab(&recordingDestroyLabRuntime{})
203: 	if err := unsupported.Capture(
204: 		context.Background(),
205: 		clablabruntime.CaptureRequest{},
206: 		io.Discard,
207: 	); err == nil || !strings.Contains(err.Error(), "does not support packet capture") {
208: 		t.Fatalf("lab runtime without capture: error = %v", err)
209: 	}
210: }

(End of file - total 210 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19654524f001W77ZbErD7lJ4QI",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196544960001jOFhFncIdgj9Pi",
  "callID": "call_3b5042574f2e40c0b00022f5",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/capture_test.go",
      "limit": 400
    },
    "output": "<path>/source/head/core/capture_test.go</path>\n<type>file</type>\n<content>\n1: package core\n2: \n3: import (\n4: \t\"bytes\"\n5: \t\"context\"\n6: \t\"io\"\n7: \t\"slices\"\n8: \t\"strings\"\n9: \t\"testing\"\n10: \n11: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n12: \tclabtypes \"github.com/srl-labs/containerlab/types\"\n13: )\n14: \n15: // captureLabRuntime records the capture requests core sends.\n16: type captureLabRuntime struct {\n17: \tclablabruntime.LabRuntime\n18: \n19: \tnodeRequest    clablabruntime.NodeRequest\n20: \tcaptureRequest clablabruntime.CaptureRequest\n21: }\n22: \n23: func (r *captureLabRuntime) CaptureInterfaces(\n24: \t_ context.Context,\n25: \treq clablabruntime.NodeRequest,\n26: ) ([]clablabruntime.CaptureInterface, error) {\n27: \tr.nodeRequest = req\n28: \n29: \treturn []clablabruntime.CaptureInterface{{Node: \"r1\", Interface: \"eth1\"}}, nil\n30: }\n31: \n32: func (r *captureLabRuntime) Capture(\n33: \t_ context.Context,\n34: \treq clablabruntime.CaptureRequest,\n35: \tw io.Writer,\n36: ) error {\n37: \tr.captureRequest = req\n38: \t_, err := io.WriteString(w, \"pcapng\")\n39: \n40: \treturn err\n41: }\n42: \n43: func (r *captureLabRuntime) InspectInterfaces(\n44: \t_ context.Context,\n45: \treq clablabruntime.NodeRequest,\n46: ) ([]*clabtypes.ContainerInterfaces, error) {\n47: \tr.nodeRequest = req\n48: \n49: \treturn []*clabtypes.ContainerInterfaces{{ContainerName: \"lab1-r1\"}}, nil\n50: }\n51: \n52: func TestCaptureHelpersFillLabAndIdentity(t *testing.T) {\n53: \tt.Parallel()\n54: \n55: \tlr := &captureLabRuntime{}\n56: \tc := newAccessTestCLab(lr)\n57: \tctx := context.Background()\n58: \n59: \tinterfaces, err := c.CaptureInterfaces(ctx, \"R1\")\n60: \tif err != nil || len(interfaces) != 1 {\n61: \t\tt.Fatalf(\"CaptureInterfaces() = %+v, %v\", interfaces, err)\n62: \t}\n63: \tif lr.nodeRequest.Name != \"lab1\" || lr.nodeRequest.Nodes[0] != \"R1\" ||\n64: \t\t!lr.nodeRequest.Identity.Equal(testIdentity) {\n65: \t\tt.Fatalf(\"interfaces request = %+v\", lr.nodeRequest)\n66: \t}\n67: \n68: \tvar out bytes.Buffer\n69: \tif err := c.Capture(ctx, clablabruntime.CaptureRequest{\n70: \t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n71: \t}, &out); err != nil {\n72: \t\tt.Fatal(err)\n73: \t}\n74: \tif out.String() != \"pcapng\" || lr.captureRequest.Name != \"lab1\" ||\n75: \t\t!lr.captureRequest.Identity.Equal(testIdentity) {\n76: \t\tt.Fatalf(\"capture request = %+v, output %q\", lr.captureRequest, out.String())\n77: \t}\n78: \n79: \tifaces, err := c.LabRuntimeInterfaces(ctx, \"r1\")\n80: \tif err != nil || len(ifaces) != 1 || lr.nodeRequest.Nodes[0] != \"r1\" {\n81: \t\tt.Fatalf(\"LabRuntimeInterfaces() = %+v, %v, request %+v\", ifaces, err, lr.nodeRequest)\n82: \t}\n83: \tif _, err := c.LabRuntimeInterfaces(ctx, \"\"); err != nil || lr.nodeRequest.Nodes != nil {\n84: \t\tt.Fatalf(\"all nodes request = %+v, %v\", lr.nodeRequest, err)\n85: \t}\n86: }\n87: \n88: // newLocalCaptureCLab loads the capture test topology. Its host and mgmt-net links register\n89: // endpoints on link nodes the whole process shares, so the tests using it do not run in\n90: // parallel and release the endpoints when they end.\n91: func newLocalCaptureCLab(t *testing.T) *CLab {\n92: \tt.Helper()\n93: \n94: \tc, err := NewContainerLab(WithTopoPath(\"test_data/capture.clab.yml\", nil))\n95: \tif err != nil {\n96: \t\tt.Fatal(err)\n97: \t}\n98: \tt.Cleanup(c.resetResolvedLinks)\n99: \n100: \treturn c\n101: }\n102: \n103: func TestLocalCaptureInterfacesComeFromTheTopologyLinks(t *testing.T) {\n104: \tc := newLocalCaptureCLab(t)\n105: \n106: \tgot, err := c.CaptureInterfaces(context.Background(), \"srl1\", \"client\")\n107: \tif err != nil {\n108: \t\tt.Fatal(err)\n109: \t}\n110: \twant := []clablabruntime.CaptureInterface{\n111: \t\t{Node: \"client\", Interface: \"eth1\", PeerNode: \"srl1\", PeerInterface: \"e1-2\"},\n112: \t\t{Node: \"client\", Interface: \"eth2\", PeerNode: \"host\", PeerInterface: \"client-eth2\"},\n113: \t\t{Node: \"client\", Interface: \"eth3\", PeerNode: \"mgmt-net\", PeerInterface: \"client-eth3\"},\n114: \t\t{\n115: \t\t\tNode: \"srl1\", Interface: \"e1-1\", Alias: \"ethernet-1/1\",\n116: \t\t\tPeerNode: \"srl2\", PeerInterface: \"e1-1\",\n117: \t\t},\n118: \t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"client\", PeerInterface: \"eth1\"},\n119: \t}\n120: \tif !slices.Equal(got, want) {\n121: \t\tt.Fatalf(\"CaptureInterfaces() =\\n%+v\\nwant\\n%+v\", got, want)\n122: \t}\n123: \n124: \tif _, err := c.CaptureInterfaces(context.Background(), \"r9\"); err == nil ||\n125: \t\t!strings.Contains(err.Error(), `node \"r9\" is not part of lab \"capture\"`) {\n126: \t\tt.Fatalf(\"unknown node: error = %v\", err)\n127: \t}\n128: }\n129: \n130: func TestLocalCaptureTargetsResolveByNameOrAlias(t *testing.T) {\n131: \tc := newLocalCaptureCLab(t)\n132: \n133: \ttargets, err := c.resolveLocalCaptureTargets([]clablabruntime.CaptureTarget{\n134: \t\t{Node: \"srl2\", Interface: \"e1-1\"},\n135: \t\t{Node: \"srl1\", Interface: \"ethernet-1/1\"},\n136: \t\t{Node: \"clab-capture-client\", Interface: \"eth2\"},\n137: \t})\n138: \tif err != nil {\n139: \t\tt.Fatal(err)\n140: \t}\n141: \tvar got []string\n142: \tfor _, target := range targets {\n143: \t\tif target.Exec == nil {\n144: \t\t\tt.Fatalf(\"target %s:%s has no namespace exec\", target.Node, target.Interface)\n145: \t\t}\n146: \t\tgot = append(got, target.Node+\":\"+target.Interface)\n147: \t}\n148: \tif want := []string{\"srl2:e1-1\", \"srl1:e1-1\", \"client:eth2\"}; !slices.Equal(got, want) {\n149: \t\tt.Fatalf(\"targets = %v, want %v\", got, want)\n150: \t}\n151: \n152: \tfor _, tc := range []struct {\n153: \t\tname    string\n154: \t\ttargets []clablabruntime.CaptureTarget\n155: \t\twant    string\n156: \t}{\n157: \t\t{\n158: \t\t\tname:    \"management interface\",\n159: \t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"client\", Interface: \"eth0\"}},\n160: \t\t\twant: `interface \"eth0\" of node \"client\" is not a capturable link interface; ` +\n161: \t\t\t\t\"capturable: eth1, eth2, eth3\",\n162: \t\t},\n163: \t\t{\n164: \t\t\tname: \"same interface twice\",\n165: \t\t\ttargets: []clablabruntime.CaptureTarget{\n166: \t\t\t\t{Node: \"srl1\", Interface: \"e1-1\"}, {Node: \"srl1\", Interface: \"ethernet-1/1\"},\n167: \t\t\t},\n168: \t\t\twant: `interface \"e1-1\" of node \"srl1\" is requested more than once`,\n169: \t\t},\n170: \t\t{\n171: \t\t\tname:    \"unknown node\",\n172: \t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"r9\", Interface: \"eth1\"}},\n173: \t\t\twant:    `node \"r9\" is not part of lab \"capture\"`,\n174: \t\t},\n175: \t} {\n176: \t\tif _, err := c.resolveLocalCaptureTargets(tc.targets); err == nil ||\n177: \t\t\t!strings.Contains(err.Error(), tc.want) {\n178: \t\t\tt.Errorf(\"%s: error = %v, want %q\", tc.name, err, tc.want)\n179: \t\t}\n180: \t}\n181: }\n182: \n183: func TestLocalCaptureNeedsTheTopology(t *testing.T) {\n184: \tt.Parallel()\n185: \n186: \tc := &CLab{Config: &Config{Name: \"lab1\"}, globalRuntimeName: \"docker\"}\n187: \terr := c.Capture(context.Background(), clablabruntime.CaptureRequest{\n188: \t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n189: \t}, io.Discard)\n190: \tif err == nil || !strings.Contains(err.Error(), `the topology of lab \"lab1\" is not available`) {\n191: \t\tt.Fatalf(\"error = %v\", err)\n192: \t}\n193: \tif err := c.Capture(context.Background(), clablabruntime.CaptureRequest{},\n194: \t\tio.Discard); err == nil || !strings.Contains(err.Error(), \"at least one capture target\") {\n195: \t\tt.Fatalf(\"no targets: error = %v\", err)\n196: \t}\n197: }\n198: \n199: func TestLabRuntimeWithoutCaptureFails(t *testing.T) {\n200: \tt.Parallel()\n201: \n202: \tunsupported := newAccessTestCLab(&recordingDestroyLabRuntime{})\n203: \tif err := unsupported.Capture(\n204: \t\tcontext.Background(),\n205: \t\tclablabruntime.CaptureRequest{},\n206: \t\tio.Discard,\n207: \t); err == nil || !strings.Contains(err.Error(), \"does not support packet capture\") {\n208: \t\tt.Fatalf(\"lab runtime without capture: error = %v\", err)\n209: \t}\n210: }\n\n(End of file - total 210 lines)\n</content>",
    "title": "source/head/core/capture_test.go",
    "metadata": {
      "preview": "package core\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"io\"\n\t\"slices\"\n\t\"strings\"\n\t\"testing\"\n\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\tclabtypes \"github.com/srl-labs/containerlab/types\"\n)\n\n// captureLabRuntime records the capture requests core sends.\ntype captureLabRuntime struct {\n\tclablabruntime.LabRuntime\n\n\tnodeRequest    clablabruntime.NodeRequest\n\tcaptureRequest clablabruntime.CaptureRequest",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/capture_test.go",
        "text": "package core\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"io\"\n\t\"slices\"\n\t\"strings\"\n\t\"testing\"\n\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\tclabtypes \"github.com/srl-labs/containerlab/types\"\n)\n\n// captureLabRuntime records the capture requests core sends.\ntype captureLabRuntime struct {\n\tclablabruntime.LabRuntime\n\n\tnodeRequest    clablabruntime.NodeRequest\n\tcaptureRequest clablabruntime.CaptureRequest\n}\n\nfunc (r *captureLabRuntime) CaptureInterfaces(\n\t_ context.Context,\n\treq clablabruntime.NodeRequest,\n) ([]clablabruntime.CaptureInterface, error) {\n\tr.nodeRequest = req\n\n\treturn []clablabruntime.CaptureInterface{{Node: \"r1\", Interface: \"eth1\"}}, nil\n}\n\nfunc (r *captureLabRuntime) Capture(\n\t_ context.Context,\n\treq clablabruntime.CaptureRequest,\n\tw io.Writer,\n) error {\n\tr.captureRequest = req\n\t_, err := io.WriteString(w, \"pcapng\")\n\n\treturn err\n}\n\nfunc (r *captureLabRuntime) InspectInterfaces(\n\t_ context.Context,\n\treq clablabruntime.NodeRequest,\n) ([]*clabtypes.ContainerInterfaces, error) {\n\tr.nodeRequest = req\n\n\treturn []*clabtypes.ContainerInterfaces{{ContainerName: \"lab1-r1\"}}, nil\n}\n\nfunc TestCaptureHelpersFillLabAndIdentity(t *testing.T) {\n\tt.Parallel()\n\n\tlr := &captureLabRuntime{}\n\tc := newAccessTestCLab(lr)\n\tctx := context.Background()\n\n\tinterfaces, err := c.CaptureInterfaces(ctx, \"R1\")\n\tif err != nil || len(interfaces) != 1 {\n\t\tt.Fatalf(\"CaptureInterfaces() = %+v, %v\", interfaces, err)\n\t}\n\tif lr.nodeRequest.Name != \"lab1\" || lr.nodeRequest.Nodes[0] != \"R1\" ||\n\t\t!lr.nodeRequest.Identity.Equal(testIdentity) {\n\t\tt.Fatalf(\"interfaces request = %+v\", lr.nodeRequest)\n\t}\n\n\tvar out bytes.Buffer\n\tif err := c.Capture(ctx, clablabruntime.CaptureRequest{\n\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n\t}, &out); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif out.String() != \"pcapng\" || lr.captureRequest.Name != \"lab1\" ||\n\t\t!lr.captureRequest.Identity.Equal(testIdentity) {\n\t\tt.Fatalf(\"capture request = %+v, output %q\", lr.captureRequest, out.String())\n\t}\n\n\tifaces, err := c.LabRuntimeInterfaces(ctx, \"r1\")\n\tif err != nil || len(ifaces) != 1 || lr.nodeRequest.Nodes[0] != \"r1\" {\n\t\tt.Fatalf(\"LabRuntimeInterfaces() = %+v, %v, request %+v\", ifaces, err, lr.nodeRequest)\n\t}\n\tif _, err := c.LabRuntimeInterfaces(ctx, \"\"); err != nil || lr.nodeRequest.Nodes != nil {\n\t\tt.Fatalf(\"all nodes request = %+v, %v\", lr.nodeRequest, err)\n\t}\n}\n\n// newLocalCaptureCLab loads the capture test topology. Its host and mgmt-net links register\n// endpoints on link nodes the whole process shares, so the tests using it do not run in\n// parallel and release the endpoints when they end.\nfunc newLocalCaptureCLab(t *testing.T) *CLab {\n\tt.Helper()\n\n\tc, err := NewContainerLab(WithTopoPath(\"test_data/capture.clab.yml\", nil))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Cleanup(c.resetResolvedLinks)\n\n\treturn c\n}\n\nfunc TestLocalCaptureInterfacesComeFromTheTopologyLinks(t *testing.T) {\n\tc := newLocalCaptureCLab(t)\n\n\tgot, err := c.CaptureInterfaces(context.Background(), \"srl1\", \"client\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\twant := []clablabruntime.CaptureInterface{\n\t\t{Node: \"client\", Interface: \"eth1\", PeerNode: \"srl1\", PeerInterface: \"e1-2\"},\n\t\t{Node: \"client\", Interface: \"eth2\", PeerNode: \"host\", PeerInterface: \"client-eth2\"},\n\t\t{Node: \"client\", Interface: \"eth3\", PeerNode: \"mgmt-net\", PeerInterface: \"client-eth3\"},\n\t\t{\n\t\t\tNode: \"srl1\", Interface: \"e1-1\", Alias: \"ethernet-1/1\",\n\t\t\tPeerNode: \"srl2\", PeerInterface: \"e1-1\",\n\t\t},\n\t\t{Node: \"srl1\", Interface: \"e1-2\", PeerNode: \"client\", PeerInterface: \"eth1\"},\n\t}\n\tif !slices.Equal(got, want) {\n\t\tt.Fatalf(\"CaptureInterfaces() =\\n%+v\\nwant\\n%+v\", got, want)\n\t}\n\n\tif _, err := c.CaptureInterfaces(context.Background(), \"r9\"); err == nil ||\n\t\t!strings.Contains(err.Error(), `node \"r9\" is not part of lab \"capture\"`) {\n\t\tt.Fatalf(\"unknown node: error = %v\", err)\n\t}\n}\n\nfunc TestLocalCaptureTargetsResolveByNameOrAlias(t *testing.T) {\n\tc := newLocalCaptureCLab(t)\n\n\ttargets, err := c.resolveLocalCaptureTargets([]clablabruntime.CaptureTarget{\n\t\t{Node: \"srl2\", Interface: \"e1-1\"},\n\t\t{Node: \"srl1\", Interface: \"ethernet-1/1\"},\n\t\t{Node: \"clab-capture-client\", Interface: \"eth2\"},\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar got []string\n\tfor _, target := range targets {\n\t\tif target.Exec == nil {\n\t\t\tt.Fatalf(\"target %s:%s has no namespace exec\", target.Node, target.Interface)\n\t\t}\n\t\tgot = append(got, target.Node+\":\"+target.Interface)\n\t}\n\tif want := []string{\"srl2:e1-1\", \"srl1:e1-1\", \"client:eth2\"}; !slices.Equal(got, want) {\n\t\tt.Fatalf(\"targets = %v, want %v\", got, want)\n\t}\n\n\tfor _, tc := range []struct {\n\t\tname    string\n\t\ttargets []clablabruntime.CaptureTarget\n\t\twant    string\n\t}{\n\t\t{\n\t\t\tname:    \"management interface\",\n\t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"client\", Interface: \"eth0\"}},\n\t\t\twant: `interface \"eth0\" of node \"client\" is not a capturable link interface; ` +\n\t\t\t\t\"capturable: eth1, eth2, eth3\",\n\t\t},\n\t\t{\n\t\t\tname: \"same interface twice\",\n\t\t\ttargets: []clablabruntime.CaptureTarget{\n\t\t\t\t{Node: \"srl1\", Interface: \"e1-1\"}, {Node: \"srl1\", Interface: \"ethernet-1/1\"},\n\t\t\t},\n\t\t\twant: `interface \"e1-1\" of node \"srl1\" is requested more than once`,\n\t\t},\n\t\t{\n\t\t\tname:    \"unknown node\",\n\t\t\ttargets: []clablabruntime.CaptureTarget{{Node: \"r9\", Interface: \"eth1\"}},\n\t\t\twant:    `node \"r9\" is not part of lab \"capture\"`,\n\t\t},\n\t} {\n\t\tif _, err := c.resolveLocalCaptureTargets(tc.targets); err == nil ||\n\t\t\t!strings.Contains(err.Error(), tc.want) {\n\t\t\tt.Errorf(\"%s: error = %v, want %q\", tc.name, err, tc.want)\n\t\t}\n\t}\n}\n\nfunc TestLocalCaptureNeedsTheTopology(t *testing.T) {\n\tt.Parallel()\n\n\tc := &CLab{Config: &Config{Name: \"lab1\"}, globalRuntimeName: \"docker\"}\n\terr := c.Capture(context.Background(), clablabruntime.CaptureRequest{\n\t\tTargets: []clablabruntime.CaptureTarget{{Node: \"r1\", Interface: \"eth1\"}},\n\t}, io.Discard)\n\tif err == nil || !strings.Contains(err.Error(), `the topology of lab \"lab1\" is not available`) {\n\t\tt.Fatalf(\"error = %v\", err)\n\t}\n\tif err := c.Capture(context.Background(), clablabruntime.CaptureRequest{},\n\t\tio.Discard); err == nil || !strings.Contains(err.Error(), \"at least one capture target\") {\n\t\tt.Fatalf(\"no targets: error = %v\", err)\n\t}\n}\n\nfunc TestLabRuntimeWithoutCaptureFails(t *testing.T) {\n\tt.Parallel()\n\n\tunsupported := newAccessTestCLab(&recordingDestroyLabRuntime{})\n\tif err := unsupported.Capture(\n\t\tcontext.Background(),\n\t\tclablabruntime.CaptureRequest{},\n\t\tio.Discard,\n\t); err == nil || !strings.Contains(err.Error(), \"does not support packet capture\") {\n\t\tt.Fatalf(\"lab runtime without capture: error = %v\", err)\n\t}\n}",
        "lineStart": 1,
        "lineEnd": 210,
        "totalLines": 210,
        "truncated": false
      }
    },
    "time": {
      "start": 1793523470931,
      "end": 1793523470936
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19654525a001HJpik3IThNdq0C",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196544960001jOFhFncIdgj9Pi",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 28581,
    "input": 6703,
    "output": 49,
    "reasoning": 69,
    "cache": {
      "read": 21760,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196544960001jOFhFncIdgj9Pi",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523468640,
    "completed": 1793523470942
  },
  "parentID": "msg_1965436e6001620KypTRi1ley5",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 28581,
    "input": 6703,
    "output": 49,
    "reasoning": 69,
    "cache": {
      "read": 21760,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 58
step-start
{
  "type": "step-start",
  "id": "prt_196545d77001f6IyJMCVemWuoO",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196545269001hgrDfxsl6X7Rxi"
}
Reasoning
Test coverage is thorough. Let me do the final remaining checks:

1. Read the remaining diff region 3776–4676 (docs + c9s capture.go start) — I saw 3478-3975, 3976-4675 already read. And 4676–5375, 5376–6075 read. So diff fully covered now (1-7018).

2. Remaining files to check: docs/manual/wireshark.md diff (3879-3900), pcapng_test.go, reorder_test.go (skim for coverage), core/capture_local.go (already read per summary), cmd/options.go diff, cmd/root_test.go diff (2618-2744 region — I read 2761+ and 2161-2761... summary says 2166 and 2766 read; the 2618 root_test region was within 2166-2765 read).

Let me quickly verify a couple of things I flagged:

Candidate findings so far:
1. Audit Failed/Denied error propagated even when stopping (speculative; check code). Let me check the actual code in head/labruntime/clabernetes/capture.go around audit handling to confirm.
2. held/emitted unbounded growth — verified earlier as acceptable (window bounds by timestamp, but under overload with skewed timestamps... actually held is bounded by reorder window timestamps; packets stamped within window; emitted map holds per-interface last emitted timestamp — bounded by number of interfaces. held is bounded by packets within the window window at high rates could be large but bounded by window duration × packet rate. Fine, P4 at most.)
3. Maybe check cmd/options.go diff for anything.
4. Check pcapng_test.go / reorder_test.go briefly for coverage notes.

Also I should verify the captureAudit error-when-stopping claim by reading the relevant code. Let me grep for captureAuditError and the stopping check.
Diff is fully covered now. Let me verify the remaining candidate findings against the head code and skim the remaining test files for coverage notes.
grep · completed

Input

{
  "pattern": "captureAuditError|stopping|audit.*error|OnGap",
  "path": "/source/head/labruntime/clabernetes/capture.go"
}

Output

Found 27 matches
/source/head/labruntime/clabernetes/capture.go:
  Line 464: // whenever it stops. A clabwire Denied or Failed audit record is returned as an error.

  Line 553: 	clabcapture.ReportGap(run.req.OnGap, gap)

  Line 610: // a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.

  Line 630: 	// stopping is set once ctx ended: the segments are asked to end and what they still

  Line 632: 	stopping bool

  Line 681: 	c.stopping = true

  Line 719: 	if c.stopping {

  Line 758: 		if event.err != nil && !c.stopping {

  Line 783: func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {

  Line 800: 		return captureAuditError(c.group.display, audit)

  Line 806: // captureAuditError turns a Denied or Failed clabwire audit record into an error.

  Line 807: func captureAuditError(node string, audit *captureAudit) error {

  Line 887: 	if c.stopping && c.next != nil && c.next.started.IsZero() {

  Line 888: 		// the chain is stopping: a follow-up that has not started takes nothing over

  Line 910: 	if c.next != nil && c.next.done && !c.stopping {

  Line 954: 		// the chain is stopping and the follow-up ended before the active one

  Line 1143: func (w *auditLineWriter) Write(data []byte) (int, error) {


/source/head/labruntime/clabernetes/lifecycle.go:
  Line 721: 		if node.State == "stopped" || node.State == "stopping" {


/source/head/labruntime/clabernetes/state.go:
  Line 212: 			node.State = "stopping"


/source/head/labruntime/clabernetes/nodes.go:
  Line 485: // stopped reports whether a node's pod is stopped or stopping: the run state of the node's


/source/head/labruntime/clabernetes/nodes_test.go:
  Line 219: 	// r2b shares the pod of r2, so stopping it stops r2, once

  Line 267: 		t.Fatalf("stopping the lab patched %v, want the primaries r1 and r2", bodies)


/source/head/labruntime/clabernetes/capture_test.go:
  Line 495: 		OnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },

  Line 553: 		OnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },

  Line 619: 	err := captureAuditError("r1", &captureAudit{

  Line 628: 		t.Fatalf("audit error = %q", err)

  Line 997: 		OnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },
Tool metadata
{
  "type": "tool",
  "id": "prt_196546982001Qj4KRJqYViTfmy",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196545269001hgrDfxsl6X7Rxi",
  "callID": "call_e58b6555beb849f4b5c9a19a",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "pattern": "captureAuditError|stopping|audit.*error|OnGap",
      "path": "/source/head/labruntime/clabernetes/capture.go"
    },
    "output": "Found 27 matches\n/source/head/labruntime/clabernetes/capture.go:\n  Line 464: // whenever it stops. A clabwire Denied or Failed audit record is returned as an error.\n\n  Line 553: \tclabcapture.ReportGap(run.req.OnGap, gap)\n\n  Line 610: // a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.\n\n  Line 630: \t// stopping is set once ctx ended: the segments are asked to end and what they still\n\n  Line 632: \tstopping bool\n\n  Line 681: \tc.stopping = true\n\n  Line 719: \tif c.stopping {\n\n  Line 758: \t\tif event.err != nil && !c.stopping {\n\n  Line 783: func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {\n\n  Line 800: \t\treturn captureAuditError(c.group.display, audit)\n\n  Line 806: // captureAuditError turns a Denied or Failed clabwire audit record into an error.\n\n  Line 807: func captureAuditError(node string, audit *captureAudit) error {\n\n  Line 887: \tif c.stopping && c.next != nil && c.next.started.IsZero() {\n\n  Line 888: \t\t// the chain is stopping: a follow-up that has not started takes nothing over\n\n  Line 910: \tif c.next != nil && c.next.done && !c.stopping {\n\n  Line 954: \t\t// the chain is stopping and the follow-up ended before the active one\n\n  Line 1143: func (w *auditLineWriter) Write(data []byte) (int, error) {\n\n\n/source/head/labruntime/clabernetes/lifecycle.go:\n  Line 721: \t\tif node.State == \"stopped\" || node.State == \"stopping\" {\n\n\n/source/head/labruntime/clabernetes/state.go:\n  Line 212: \t\t\tnode.State = \"stopping\"\n\n\n/source/head/labruntime/clabernetes/nodes.go:\n  Line 485: // stopped reports whether a node's pod is stopped or stopping: the run state of the node's\n\n\n/source/head/labruntime/clabernetes/nodes_test.go:\n  Line 219: \t// r2b shares the pod of r2, so stopping it stops r2, once\n\n  Line 267: \t\tt.Fatalf(\"stopping the lab patched %v, want the primaries r1 and r2\", bodies)\n\n\n/source/head/labruntime/clabernetes/capture_test.go:\n  Line 495: \t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n\n  Line 553: \t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n\n  Line 619: \terr := captureAuditError(\"r1\", &captureAudit{\n\n  Line 628: \t\tt.Fatalf(\"audit error = %q\", err)\n\n  Line 997: \t\tOnGap:    func(gap clablabruntime.CaptureGap) { gaps = append(gaps, gap) },\n",
    "title": "captureAuditError|stopping|audit.*error|OnGap",
    "metadata": {
      "matches": 27,
      "truncated": false
    },
    "time": {
      "start": 1793523476870,
      "end": 1793523476880
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/capture/reorder_test.go",
  "limit": 120
}

Output

<path>/source/head/capture/reorder_test.go</path>
<type>file</type>
<content>
1: package capture
2: 
3: import (
4: 	"context"
5: 	"errors"
6: 	"slices"
7: 	"sync"
8: 	"testing"
9: 	"time"
10: )
11: 
12: // reorderSink records what a reorder buffer writes.
13: type reorderSink struct {
14: 	mu      sync.Mutex
15: 	written []int64
16: 	ids     []uint32
17: 	failAt  int
18: }
19: 
20: func (s *reorderSink) write(id uint32, packet *Packet) error {
21: 	s.mu.Lock()
22: 	defer s.mu.Unlock()
23: 	if s.failAt > 0 && len(s.written) == s.failAt {
24: 		return errors.New("write |1: broken pipe")
25: 	}
26: 	s.written = append(s.written, packet.Timestamp)
27: 	s.ids = append(s.ids, id)
28: 
29: 	return nil
30: }
31: 
32: func (s *reorderSink) timestamps() []int64 {
33: 	s.mu.Lock()
34: 	defer s.mu.Unlock()
35: 
36: 	return slices.Clone(s.written)
37: }
38: 
39: // interleavedStreams pushes two synthetic streams of ticks, interleaved in time: stream 0 is
40: // delivered at once, stream 1 `delay` after its packets were stamped. Both stamp a packet every
41: // 2 ms, offset by 1 ms.
42: func interleavedStreams(t *testing.T, q *Reorder, ticks int, delay time.Duration) {
43: 	t.Helper()
44: 
45: 	start := time.Now()
46: 	type delivery struct {
47: 		at time.Time
48: 		id uint32
49: 		ts int64
50: 	}
51: 	var deliveries []delivery
52: 	for tick := range ticks {
53: 		stamp := start.Add(time.Duration(tick) * 2 * time.Millisecond)
54: 		deliveries = append(deliveries,
55: 			delivery{at: stamp, id: 0, ts: stamp.UnixNano()},
56: 			delivery{
57: 				at: stamp.Add(time.Millisecond + delay), id: 1,
58: 				ts: stamp.Add(time.Millisecond).UnixNano(),
59: 			})
60: 	}
61: 	slices.SortStableFunc(deliveries, func(a, b delivery) int { return a.at.Compare(b.at) })
62: 
63: 	for _, next := range deliveries {
64: 		time.Sleep(time.Until(next.at))
65: 		if err := q.Push(
66: 			next.id,
67: 			&Packet{InterfaceID: next.id, Timestamp: next.ts},
68: 		); err != nil {
69: 			t.Fatal(err)
70: 		}
71: 	}
72: }
73: 
74: func runReorder(q *Reorder) func() {
75: 	ctx, cancel := context.WithCancel(context.Background())
76: 	done := make(chan struct{})
77: 	go func() {
78: 		defer close(done)
79: 		q.Run(ctx)
80: 	}()
81: 
82: 	return func() {
83: 		cancel()
84: 		<-done
85: 		q.Flush()
86: 	}
87: }
88: 
89: func TestReorderOrdersStreamsWithinTheWindow(t *testing.T) {
90: 	t.Parallel()
91: 
92: 	sink := &reorderSink{}
93: 	q := NewReorder(100*time.Millisecond, sink.write, nil)
94: 	stop := runReorder(q)
95: 	interleavedStreams(t, q, 60, 40*time.Millisecond)
96: 
97: 	// packets go out while the capture runs, not only at the end
98: 	time.Sleep(150 * time.Millisecond)
99: 	if len(sink.timestamps()) == 0 {
100: 		t.Fatal("nothing written while the streams ran")
101: 	}
102: 	stop()
103: 
104: 	written := sink.timestamps()
105: 	if len(written) != 120 || !slices.IsSorted(written) {
106: 		t.Fatalf("written %d packets, sorted %v", len(written), slices.IsSorted(written))
107: 	}
108: 	if q.stats.late != 0 {
109: 		t.Fatalf("late packets = %d", q.stats.late)
110: 	}
111: }
112: 
113: func TestReorderWritesLatePacketsAsTheyCome(t *testing.T) {
114: 	t.Parallel()
115: 
116: 	sink := &reorderSink{}
117: 	q := NewReorder(20*time.Millisecond, sink.write, nil)
118: 	stop := runReorder(q)
119: 	// stream 1 arrives 80 ms after its stamps, far beyond the 20 ms window
120: 	interleavedStreams(t, q, 60, 80*time.Millisecond)

(Showing lines 1-120 of 202. Use offset=121 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1965469c5001q5849e4gVzL4Cg",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196545269001hgrDfxsl6X7Rxi",
  "callID": "call_cf44f8912efb4c2a890de0ea",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/capture/reorder_test.go",
      "limit": 120
    },
    "output": "<path>/source/head/capture/reorder_test.go</path>\n<type>file</type>\n<content>\n1: package capture\n2: \n3: import (\n4: \t\"context\"\n5: \t\"errors\"\n6: \t\"slices\"\n7: \t\"sync\"\n8: \t\"testing\"\n9: \t\"time\"\n10: )\n11: \n12: // reorderSink records what a reorder buffer writes.\n13: type reorderSink struct {\n14: \tmu      sync.Mutex\n15: \twritten []int64\n16: \tids     []uint32\n17: \tfailAt  int\n18: }\n19: \n20: func (s *reorderSink) write(id uint32, packet *Packet) error {\n21: \ts.mu.Lock()\n22: \tdefer s.mu.Unlock()\n23: \tif s.failAt > 0 && len(s.written) == s.failAt {\n24: \t\treturn errors.New(\"write |1: broken pipe\")\n25: \t}\n26: \ts.written = append(s.written, packet.Timestamp)\n27: \ts.ids = append(s.ids, id)\n28: \n29: \treturn nil\n30: }\n31: \n32: func (s *reorderSink) timestamps() []int64 {\n33: \ts.mu.Lock()\n34: \tdefer s.mu.Unlock()\n35: \n36: \treturn slices.Clone(s.written)\n37: }\n38: \n39: // interleavedStreams pushes two synthetic streams of ticks, interleaved in time: stream 0 is\n40: // delivered at once, stream 1 `delay` after its packets were stamped. Both stamp a packet every\n41: // 2 ms, offset by 1 ms.\n42: func interleavedStreams(t *testing.T, q *Reorder, ticks int, delay time.Duration) {\n43: \tt.Helper()\n44: \n45: \tstart := time.Now()\n46: \ttype delivery struct {\n47: \t\tat time.Time\n48: \t\tid uint32\n49: \t\tts int64\n50: \t}\n51: \tvar deliveries []delivery\n52: \tfor tick := range ticks {\n53: \t\tstamp := start.Add(time.Duration(tick) * 2 * time.Millisecond)\n54: \t\tdeliveries = append(deliveries,\n55: \t\t\tdelivery{at: stamp, id: 0, ts: stamp.UnixNano()},\n56: \t\t\tdelivery{\n57: \t\t\t\tat: stamp.Add(time.Millisecond + delay), id: 1,\n58: \t\t\t\tts: stamp.Add(time.Millisecond).UnixNano(),\n59: \t\t\t})\n60: \t}\n61: \tslices.SortStableFunc(deliveries, func(a, b delivery) int { return a.at.Compare(b.at) })\n62: \n63: \tfor _, next := range deliveries {\n64: \t\ttime.Sleep(time.Until(next.at))\n65: \t\tif err := q.Push(\n66: \t\t\tnext.id,\n67: \t\t\t&Packet{InterfaceID: next.id, Timestamp: next.ts},\n68: \t\t); err != nil {\n69: \t\t\tt.Fatal(err)\n70: \t\t}\n71: \t}\n72: }\n73: \n74: func runReorder(q *Reorder) func() {\n75: \tctx, cancel := context.WithCancel(context.Background())\n76: \tdone := make(chan struct{})\n77: \tgo func() {\n78: \t\tdefer close(done)\n79: \t\tq.Run(ctx)\n80: \t}()\n81: \n82: \treturn func() {\n83: \t\tcancel()\n84: \t\t<-done\n85: \t\tq.Flush()\n86: \t}\n87: }\n88: \n89: func TestReorderOrdersStreamsWithinTheWindow(t *testing.T) {\n90: \tt.Parallel()\n91: \n92: \tsink := &reorderSink{}\n93: \tq := NewReorder(100*time.Millisecond, sink.write, nil)\n94: \tstop := runReorder(q)\n95: \tinterleavedStreams(t, q, 60, 40*time.Millisecond)\n96: \n97: \t// packets go out while the capture runs, not only at the end\n98: \ttime.Sleep(150 * time.Millisecond)\n99: \tif len(sink.timestamps()) == 0 {\n100: \t\tt.Fatal(\"nothing written while the streams ran\")\n101: \t}\n102: \tstop()\n103: \n104: \twritten := sink.timestamps()\n105: \tif len(written) != 120 || !slices.IsSorted(written) {\n106: \t\tt.Fatalf(\"written %d packets, sorted %v\", len(written), slices.IsSorted(written))\n107: \t}\n108: \tif q.stats.late != 0 {\n109: \t\tt.Fatalf(\"late packets = %d\", q.stats.late)\n110: \t}\n111: }\n112: \n113: func TestReorderWritesLatePacketsAsTheyCome(t *testing.T) {\n114: \tt.Parallel()\n115: \n116: \tsink := &reorderSink{}\n117: \tq := NewReorder(20*time.Millisecond, sink.write, nil)\n118: \tstop := runReorder(q)\n119: \t// stream 1 arrives 80 ms after its stamps, far beyond the 20 ms window\n120: \tinterleavedStreams(t, q, 60, 80*time.Millisecond)\n\n(Showing lines 1-120 of 202. Use offset=121 to continue.)\n</content>",
    "title": "source/head/capture/reorder_test.go",
    "metadata": {
      "preview": "package capture\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"slices\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n)\n\n// reorderSink records what a reorder buffer writes.\ntype reorderSink struct {\n\tmu      sync.Mutex\n\twritten []int64\n\tids     []uint32\n\tfailAt  int\n}\n\nfunc (s *reorderSink) write(id uint32, packet *Packet) error {",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/capture/reorder_test.go",
        "text": "package capture\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"slices\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n)\n\n// reorderSink records what a reorder buffer writes.\ntype reorderSink struct {\n\tmu      sync.Mutex\n\twritten []int64\n\tids     []uint32\n\tfailAt  int\n}\n\nfunc (s *reorderSink) write(id uint32, packet *Packet) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif s.failAt > 0 && len(s.written) == s.failAt {\n\t\treturn errors.New(\"write |1: broken pipe\")\n\t}\n\ts.written = append(s.written, packet.Timestamp)\n\ts.ids = append(s.ids, id)\n\n\treturn nil\n}\n\nfunc (s *reorderSink) timestamps() []int64 {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\treturn slices.Clone(s.written)\n}\n\n// interleavedStreams pushes two synthetic streams of ticks, interleaved in time: stream 0 is\n// delivered at once, stream 1 `delay` after its packets were stamped. Both stamp a packet every\n// 2 ms, offset by 1 ms.\nfunc interleavedStreams(t *testing.T, q *Reorder, ticks int, delay time.Duration) {\n\tt.Helper()\n\n\tstart := time.Now()\n\ttype delivery struct {\n\t\tat time.Time\n\t\tid uint32\n\t\tts int64\n\t}\n\tvar deliveries []delivery\n\tfor tick := range ticks {\n\t\tstamp := start.Add(time.Duration(tick) * 2 * time.Millisecond)\n\t\tdeliveries = append(deliveries,\n\t\t\tdelivery{at: stamp, id: 0, ts: stamp.UnixNano()},\n\t\t\tdelivery{\n\t\t\t\tat: stamp.Add(time.Millisecond + delay), id: 1,\n\t\t\t\tts: stamp.Add(time.Millisecond).UnixNano(),\n\t\t\t})\n\t}\n\tslices.SortStableFunc(deliveries, func(a, b delivery) int { return a.at.Compare(b.at) })\n\n\tfor _, next := range deliveries {\n\t\ttime.Sleep(time.Until(next.at))\n\t\tif err := q.Push(\n\t\t\tnext.id,\n\t\t\t&Packet{InterfaceID: next.id, Timestamp: next.ts},\n\t\t); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}\n\nfunc runReorder(q *Reorder) func() {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tdefer close(done)\n\t\tq.Run(ctx)\n\t}()\n\n\treturn func() {\n\t\tcancel()\n\t\t<-done\n\t\tq.Flush()\n\t}\n}\n\nfunc TestReorderOrdersStreamsWithinTheWindow(t *testing.T) {\n\tt.Parallel()\n\n\tsink := &reorderSink{}\n\tq := NewReorder(100*time.Millisecond, sink.write, nil)\n\tstop := runReorder(q)\n\tinterleavedStreams(t, q, 60, 40*time.Millisecond)\n\n\t// packets go out while the capture runs, not only at the end\n\ttime.Sleep(150 * time.Millisecond)\n\tif len(sink.timestamps()) == 0 {\n\t\tt.Fatal(\"nothing written while the streams ran\")\n\t}\n\tstop()\n\n\twritten := sink.timestamps()\n\tif len(written) != 120 || !slices.IsSorted(written) {\n\t\tt.Fatalf(\"written %d packets, sorted %v\", len(written), slices.IsSorted(written))\n\t}\n\tif q.stats.late != 0 {\n\t\tt.Fatalf(\"late packets = %d\", q.stats.late)\n\t}\n}\n\nfunc TestReorderWritesLatePacketsAsTheyCome(t *testing.T) {\n\tt.Parallel()\n\n\tsink := &reorderSink{}\n\tq := NewReorder(20*time.Millisecond, sink.write, nil)\n\tstop := runReorder(q)\n\t// stream 1 arrives 80 ms after its stamps, far beyond the 20 ms window\n\tinterleavedStreams(t, q, 60, 80*time.Millisecond)",
        "lineStart": 1,
        "lineEnd": 120,
        "totalLines": 202,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523476937,
      "end": 1793523476942
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1965469d0001bDiQwGkZ3v1MPo",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196545269001hgrDfxsl6X7Rxi",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 36915,
    "input": 36419,
    "output": 86,
    "reasoning": 410,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196545269001hgrDfxsl6X7Rxi",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523470953,
    "completed": 1793523476947
  },
  "parentID": "msg_1965436e6001620KypTRi1ley5",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 36915,
    "input": 36419,
    "output": 86,
    "reasoning": 410,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 59
step-start
{
  "type": "step-start",
  "id": "prt_196546fe4001NnpoJbZmSpCY1S",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965469dd001abKSHVc0hGYfzy"
}
Reasoning
Let me look at the audit handling code around lines 758-810 in capture.go to confirm the stopping/audit-error behavior.
read · completed

Input

{
  "filePath": "/source/head/labruntime/clabernetes/capture.go",
  "limit": 120,
  "offset": 700
}

Output

<path>/source/head/labruntime/clabernetes/capture.go</path>
<type>file</type>
<content>
700: 			return
701: 		case <-c.events:
702: 		}
703: 	}
704: }
705: 
706: // segmentDuration is the requested duration of a segment starting now.
707: func (c *captureChain) segmentDuration(now time.Time) time.Duration {
708: 	duration := c.capture.segment
709: 	if !c.capture.deadline.IsZero() {
710: 		duration = min(duration, c.capture.deadline.Sub(now))
711: 	}
712: 
713: 	return max(duration, minCaptureSegment)
714: }
715: 
716: // nextStartIn is the time until the follow-up of the active segment is due. It marks the chain
717: // final when none is due.
718: func (c *captureChain) nextStartIn() time.Duration {
719: 	if c.stopping {
720: 		c.final = true
721: 		return maxCaptureSegment
722: 	}
723: 	activeEnd := c.active.localStart.Add(c.active.duration)
724: 	if !c.capture.deadline.IsZero() &&
725: 		!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {
726: 		c.final = true
727: 		return maxCaptureSegment
728: 	}
729: 	c.final = false
730: 
731: 	return max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)
732: }
733: 
734: func (c *captureChain) startNext(ctx context.Context) {
735: 	c.next = c.start(ctx, c.segmentDuration(time.Now()))
736: 	c.emitted = map[uint64]int{}
737: 	c.held = nil
738: 	c.cut = 0
739: }
740: 
741: func (c *captureChain) handle(
742: 	ctx context.Context,
743: 	event segmentEvent,
744: 	timer *time.Timer,
745: ) (bool, error) {
746: 	segment := event.segment
747: 
748: 	switch {
749: 	case event.audit != nil:
750: 		return false, c.handleAudit(segment, event.audit)
751: 	case event.packet != nil:
752: 		return c.handlePacket(segment, event.packet)
753: 	case event.done:
754: 		segment.done = true
755: 		if segment.stopTimer != nil {
756: 			segment.stopTimer.Stop()
757: 		}
758: 		if event.err != nil && !c.stopping {
759: 			if segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {
760: 				// the follow-up did not start; try again while the active one still runs
761: 				c.retries++
762: 				log.Warn("Capture follow-up segment failed to start, retrying",
763: 					"node", c.group.display, "error", event.err)
764: 				c.next = nil
765: 				resetTimer(timer, time.Second)
766: 
767: 				return false, nil
768: 			}
769: 
770: 			return true, fmt.Errorf("capture on c9s node %s/%s/%s failed: %w",
771: 				c.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)
772: 		}
773: 		if segment != c.active {
774: 			return false, nil
775: 		}
776: 
777: 		return c.switchSegments(ctx, timer)
778: 	}
779: 
780: 	return false, nil
781: }
782: 
783: func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {
784: 	switch audit.Status {
785: 	case captureAuditStarted:
786: 		segment.started = audit.Time
787: 		log.Debug("Capture segment started", "node", c.group.display, "segment", segment.index,
788: 			"interfaces", strings.Join(c.group.interfaces, ","), "duration", segment.duration)
789: 		if segment == c.next && !c.active.started.IsZero() {
790: 			c.setCut()
791: 		}
792: 		if segment == c.next {
793: 			c.retries = 0
794: 		}
795: 	case captureAuditSucceeded:
796: 		segment.ended = audit.Time
797: 		log.Debug("Capture segment succeeded", "node", c.group.display,
798: 			"segment", segment.index, "packets", audit.Packets)
799: 	case captureAuditDenied, captureAuditFailed:
800: 		return captureAuditError(c.group.display, audit)
801: 	}
802: 
803: 	return nil
804: }
805: 
806: // captureAuditError turns a Denied or Failed clabwire audit record into an error.
807: func captureAuditError(node string, audit *captureAudit) error {
808: 	verb := "failed"
809: 	if audit.Status == captureAuditDenied {
810: 		verb = "was denied"
811: 	}
812: 	interfaces := make([]string, 0, len(audit.Interfaces))
813: 	for _, intf := range audit.Interfaces {
814: 		interfaces = append(interfaces, intf.Name)
815: 	}
816: 
817: 	return fmt.Errorf("capture of %s on node %s %s by clabwire: %s",
818: 		strings.Join(interfaces, ","), node, verb, audit.Reason)
819: }

(Showing lines 700-819 of 1202. Use offset=820 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1965470f0001fjGIGBC3vg8zsz",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965469dd001abKSHVc0hGYfzy",
  "callID": "call_054731461af84e7b906aa137",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/capture.go",
      "limit": 120,
      "offset": 700
    },
    "output": "<path>/source/head/labruntime/clabernetes/capture.go</path>\n<type>file</type>\n<content>\n700: \t\t\treturn\n701: \t\tcase <-c.events:\n702: \t\t}\n703: \t}\n704: }\n705: \n706: // segmentDuration is the requested duration of a segment starting now.\n707: func (c *captureChain) segmentDuration(now time.Time) time.Duration {\n708: \tduration := c.capture.segment\n709: \tif !c.capture.deadline.IsZero() {\n710: \t\tduration = min(duration, c.capture.deadline.Sub(now))\n711: \t}\n712: \n713: \treturn max(duration, minCaptureSegment)\n714: }\n715: \n716: // nextStartIn is the time until the follow-up of the active segment is due. It marks the chain\n717: // final when none is due.\n718: func (c *captureChain) nextStartIn() time.Duration {\n719: \tif c.stopping {\n720: \t\tc.final = true\n721: \t\treturn maxCaptureSegment\n722: \t}\n723: \tactiveEnd := c.active.localStart.Add(c.active.duration)\n724: \tif !c.capture.deadline.IsZero() &&\n725: \t\t!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {\n726: \t\tc.final = true\n727: \t\treturn maxCaptureSegment\n728: \t}\n729: \tc.final = false\n730: \n731: \treturn max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)\n732: }\n733: \n734: func (c *captureChain) startNext(ctx context.Context) {\n735: \tc.next = c.start(ctx, c.segmentDuration(time.Now()))\n736: \tc.emitted = map[uint64]int{}\n737: \tc.held = nil\n738: \tc.cut = 0\n739: }\n740: \n741: func (c *captureChain) handle(\n742: \tctx context.Context,\n743: \tevent segmentEvent,\n744: \ttimer *time.Timer,\n745: ) (bool, error) {\n746: \tsegment := event.segment\n747: \n748: \tswitch {\n749: \tcase event.audit != nil:\n750: \t\treturn false, c.handleAudit(segment, event.audit)\n751: \tcase event.packet != nil:\n752: \t\treturn c.handlePacket(segment, event.packet)\n753: \tcase event.done:\n754: \t\tsegment.done = true\n755: \t\tif segment.stopTimer != nil {\n756: \t\t\tsegment.stopTimer.Stop()\n757: \t\t}\n758: \t\tif event.err != nil && !c.stopping {\n759: \t\t\tif segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {\n760: \t\t\t\t// the follow-up did not start; try again while the active one still runs\n761: \t\t\t\tc.retries++\n762: \t\t\t\tlog.Warn(\"Capture follow-up segment failed to start, retrying\",\n763: \t\t\t\t\t\"node\", c.group.display, \"error\", event.err)\n764: \t\t\t\tc.next = nil\n765: \t\t\t\tresetTimer(timer, time.Second)\n766: \n767: \t\t\t\treturn false, nil\n768: \t\t\t}\n769: \n770: \t\t\treturn true, fmt.Errorf(\"capture on c9s node %s/%s/%s failed: %w\",\n771: \t\t\t\tc.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)\n772: \t\t}\n773: \t\tif segment != c.active {\n774: \t\t\treturn false, nil\n775: \t\t}\n776: \n777: \t\treturn c.switchSegments(ctx, timer)\n778: \t}\n779: \n780: \treturn false, nil\n781: }\n782: \n783: func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {\n784: \tswitch audit.Status {\n785: \tcase captureAuditStarted:\n786: \t\tsegment.started = audit.Time\n787: \t\tlog.Debug(\"Capture segment started\", \"node\", c.group.display, \"segment\", segment.index,\n788: \t\t\t\"interfaces\", strings.Join(c.group.interfaces, \",\"), \"duration\", segment.duration)\n789: \t\tif segment == c.next && !c.active.started.IsZero() {\n790: \t\t\tc.setCut()\n791: \t\t}\n792: \t\tif segment == c.next {\n793: \t\t\tc.retries = 0\n794: \t\t}\n795: \tcase captureAuditSucceeded:\n796: \t\tsegment.ended = audit.Time\n797: \t\tlog.Debug(\"Capture segment succeeded\", \"node\", c.group.display,\n798: \t\t\t\"segment\", segment.index, \"packets\", audit.Packets)\n799: \tcase captureAuditDenied, captureAuditFailed:\n800: \t\treturn captureAuditError(c.group.display, audit)\n801: \t}\n802: \n803: \treturn nil\n804: }\n805: \n806: // captureAuditError turns a Denied or Failed clabwire audit record into an error.\n807: func captureAuditError(node string, audit *captureAudit) error {\n808: \tverb := \"failed\"\n809: \tif audit.Status == captureAuditDenied {\n810: \t\tverb = \"was denied\"\n811: \t}\n812: \tinterfaces := make([]string, 0, len(audit.Interfaces))\n813: \tfor _, intf := range audit.Interfaces {\n814: \t\tinterfaces = append(interfaces, intf.Name)\n815: \t}\n816: \n817: \treturn fmt.Errorf(\"capture of %s on node %s %s by clabwire: %s\",\n818: \t\tstrings.Join(interfaces, \",\"), node, verb, audit.Reason)\n819: }\n\n(Showing lines 700-819 of 1202. Use offset=820 to continue.)\n</content>",
    "title": "source/head/labruntime/clabernetes/capture.go",
    "metadata": {
      "preview": "\t\t\treturn\n\t\tcase <-c.events:\n\t\t}\n\t}\n}\n\n// segmentDuration is the requested duration of a segment starting now.\nfunc (c *captureChain) segmentDuration(now time.Time) time.Duration {\n\tduration := c.capture.segment\n\tif !c.capture.deadline.IsZero() {\n\t\tduration = min(duration, c.capture.deadline.Sub(now))\n\t}\n\n\treturn max(duration, minCaptureSegment)\n}\n\n// nextStartIn is the time until the follow-up of the active segment is due. It marks the chain\n// final when none is due.\nfunc (c *captureChain) nextStartIn() time.Duration {\n\tif c.stopping {",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/capture.go",
        "text": "\t\t\treturn\n\t\tcase <-c.events:\n\t\t}\n\t}\n}\n\n// segmentDuration is the requested duration of a segment starting now.\nfunc (c *captureChain) segmentDuration(now time.Time) time.Duration {\n\tduration := c.capture.segment\n\tif !c.capture.deadline.IsZero() {\n\t\tduration = min(duration, c.capture.deadline.Sub(now))\n\t}\n\n\treturn max(duration, minCaptureSegment)\n}\n\n// nextStartIn is the time until the follow-up of the active segment is due. It marks the chain\n// final when none is due.\nfunc (c *captureChain) nextStartIn() time.Duration {\n\tif c.stopping {\n\t\tc.final = true\n\t\treturn maxCaptureSegment\n\t}\n\tactiveEnd := c.active.localStart.Add(c.active.duration)\n\tif !c.capture.deadline.IsZero() &&\n\t\t!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {\n\t\tc.final = true\n\t\treturn maxCaptureSegment\n\t}\n\tc.final = false\n\n\treturn max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)\n}\n\nfunc (c *captureChain) startNext(ctx context.Context) {\n\tc.next = c.start(ctx, c.segmentDuration(time.Now()))\n\tc.emitted = map[uint64]int{}\n\tc.held = nil\n\tc.cut = 0\n}\n\nfunc (c *captureChain) handle(\n\tctx context.Context,\n\tevent segmentEvent,\n\ttimer *time.Timer,\n) (bool, error) {\n\tsegment := event.segment\n\n\tswitch {\n\tcase event.audit != nil:\n\t\treturn false, c.handleAudit(segment, event.audit)\n\tcase event.packet != nil:\n\t\treturn c.handlePacket(segment, event.packet)\n\tcase event.done:\n\t\tsegment.done = true\n\t\tif segment.stopTimer != nil {\n\t\t\tsegment.stopTimer.Stop()\n\t\t}\n\t\tif event.err != nil && !c.stopping {\n\t\t\tif segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {\n\t\t\t\t// the follow-up did not start; try again while the active one still runs\n\t\t\t\tc.retries++\n\t\t\t\tlog.Warn(\"Capture follow-up segment failed to start, retrying\",\n\t\t\t\t\t\"node\", c.group.display, \"error\", event.err)\n\t\t\t\tc.next = nil\n\t\t\t\tresetTimer(timer, time.Second)\n\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\treturn true, fmt.Errorf(\"capture on c9s node %s/%s/%s failed: %w\",\n\t\t\t\tc.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)\n\t\t}\n\t\tif segment != c.active {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn c.switchSegments(ctx, timer)\n\t}\n\n\treturn false, nil\n}\n\nfunc (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {\n\tswitch audit.Status {\n\tcase captureAuditStarted:\n\t\tsegment.started = audit.Time\n\t\tlog.Debug(\"Capture segment started\", \"node\", c.group.display, \"segment\", segment.index,\n\t\t\t\"interfaces\", strings.Join(c.group.interfaces, \",\"), \"duration\", segment.duration)\n\t\tif segment == c.next && !c.active.started.IsZero() {\n\t\t\tc.setCut()\n\t\t}\n\t\tif segment == c.next {\n\t\t\tc.retries = 0\n\t\t}\n\tcase captureAuditSucceeded:\n\t\tsegment.ended = audit.Time\n\t\tlog.Debug(\"Capture segment succeeded\", \"node\", c.group.display,\n\t\t\t\"segment\", segment.index, \"packets\", audit.Packets)\n\tcase captureAuditDenied, captureAuditFailed:\n\t\treturn captureAuditError(c.group.display, audit)\n\t}\n\n\treturn nil\n}\n\n// captureAuditError turns a Denied or Failed clabwire audit record into an error.\nfunc captureAuditError(node string, audit *captureAudit) error {\n\tverb := \"failed\"\n\tif audit.Status == captureAuditDenied {\n\t\tverb = \"was denied\"\n\t}\n\tinterfaces := make([]string, 0, len(audit.Interfaces))\n\tfor _, intf := range audit.Interfaces {\n\t\tinterfaces = append(interfaces, intf.Name)\n\t}\n\n\treturn fmt.Errorf(\"capture of %s on node %s %s by clabwire: %s\",\n\t\tstrings.Join(interfaces, \",\"), node, verb, audit.Reason)\n}",
        "lineStart": 700,
        "lineEnd": 819,
        "totalLines": 1202,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523478772,
      "end": 1793523478778
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1965470fc0019mtZWgxmgWbWTr",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965469dd001abKSHVc0hGYfzy",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 38833,
    "input": 1909,
    "output": 31,
    "reasoning": 29,
    "cache": {
      "read": 36864,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1965469dd001abKSHVc0hGYfzy",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523476957,
    "completed": 1793523478783
  },
  "parentID": "msg_1965436e6001620KypTRi1ley5",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 38833,
    "input": 1909,
    "output": 31,
    "reasoning": 29,
    "cache": {
      "read": 36864,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 60
step-start
{
  "type": "step-start",
  "id": "prt_19654785c001lf2gmbS0DLTLp9",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965471090010I0XCBAsYtLHBt"
}
Reasoning
Confirmed: `handleAudit` returns an error for Denied/Failed regardless of `c.stopping`. When stopping (Ctrl+C), if clabwire emits a Failed audit record on stdin close, the chain returns that error even though the run's clean-exit contract promises "context ended is not an error". Is this actually a bug? Let me check how the chain error is consumed at stop. Look at the chain run loop and where stop() is invoked — the run function around line 464 and where c.stopping is set (line 681).

Let me read lines 600-700 and 940-1000 to see error flow at stop.
read · completed

Input

{
  "filePath": "/source/head/labruntime/clabernetes/capture.go",
  "limit": 130,
  "offset": 590
}

Output

<path>/source/head/labruntime/clabernetes/capture.go</path>
<type>file</type>
<content>
590: // processes give the same packet timestamps a few microseconds apart, and timestamps alone
591: // cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by
592: // content close to the cut:
593: //
594: //  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is
595: //     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.
596: //  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the
597: //     content of what it wrote since segment k+1 started.
598: //  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped
599: //     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped
600: //     when segment k wrote the same bytes on the same interface, and every other one is written.
601: //     From then on segment k+1 streams live.
602: //
603: // Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its
604: // planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other
605: // nodes' later packets do not overtake them in the merged stream.
606: //
607: // W (500 ms, less for short test segments) covers the stamping difference. Identical frames on
608: // the same interface within W of the cut can be paired with each other, which can drop a true
609: // repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves
610: // a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.
611: type captureChain struct {
612: 	capture *captureRun
613: 	group   *captureGroup
614: 
615: 	events chan segmentEvent
616: 	wg     sync.WaitGroup
617: 
618: 	active *captureSegment
619: 	next   *captureSegment
620: 	// cut is the switch time between active and next, in nanoseconds; zero until known.
621: 	cut int64
622: 	// emitted remembers the content of the packets active wrote while next runs.
623: 	emitted map[uint64]int
624: 	// held are the packets of next until active ends.
625: 	held     []*clabcapture.Packet
626: 	segments int
627: 	retries  int
628: 	// final is set once no further segment is due.
629: 	final bool
630: 	// stopping is set once ctx ended: the segments are asked to end and what they still
631: 	// deliver is written.
632: 	stopping bool
633: }
634: 
635: // run runs the chain until its last segment ended. When ctx ends, it stops the segments and
636: // keeps writing the packets they read until then; a segment that does not end within
637: // captureStdinCloseGrace is cut.
638: func (c *captureChain) run(ctx context.Context) error {
639: 	c.events = make(chan segmentEvent, 256)
640: 	// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them
641: 	segmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
642: 	var abort *time.Timer
643: 	defer func() {
644: 		if abort != nil {
645: 			abort.Stop()
646: 		}
647: 		cancel()
648: 		c.drain()
649: 		c.capture.out.Release(c)
650: 	}()
651: 
652: 	c.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))
653: 	timer := time.NewTimer(c.nextStartIn())
654: 	defer timer.Stop()
655: 
656: 	done := ctx.Done()
657: 	for {
658: 		select {
659: 		case <-done:
660: 			done = nil
661: 			c.stop(timer)
662: 			abort = time.AfterFunc(captureStdinCloseGrace, cancel)
663: 		case <-segmentsCtx.Done():
664: 			return nil
665: 		case <-timer.C:
666: 			if c.next == nil && !c.final {
667: 				c.startNext(segmentsCtx)
668: 			}
669: 		case event := <-c.events:
670: 			stop, err := c.handle(segmentsCtx, event, timer)
671: 			if err != nil || stop {
672: 				return err
673: 			}
674: 		}
675: 	}
676: }
677: 
678: // stop ends the chain early, like a deadline would: no further segment starts and the running
679: // ones are asked to end. The chain then writes what they deliver until they ended.
680: func (c *captureChain) stop(timer *time.Timer) {
681: 	c.stopping = true
682: 	c.final = true
683: 	timer.Stop()
684: 	c.active.closeStdin()
685: 	if c.next != nil {
686: 		c.next.closeStdin()
687: 	}
688: }
689: 
690: // drain waits for the segment goroutines after the chain ended.
691: func (c *captureChain) drain() {
692: 	done := make(chan struct{})
693: 	go func() {
694: 		c.wg.Wait()
695: 		close(done)
696: 	}()
697: 	for {
698: 		select {
699: 		case <-done:
700: 			return
701: 		case <-c.events:
702: 		}
703: 	}
704: }
705: 
706: // segmentDuration is the requested duration of a segment starting now.
707: func (c *captureChain) segmentDuration(now time.Time) time.Duration {
708: 	duration := c.capture.segment
709: 	if !c.capture.deadline.IsZero() {
710: 		duration = min(duration, c.capture.deadline.Sub(now))
711: 	}
712: 
713: 	return max(duration, minCaptureSegment)
714: }
715: 
716: // nextStartIn is the time until the follow-up of the active segment is due. It marks the chain
717: // final when none is due.
718: func (c *captureChain) nextStartIn() time.Duration {
719: 	if c.stopping {

(Showing lines 590-719 of 1202. Use offset=720 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196547c75001Ve0DKx6Fyx6P5t",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965471090010I0XCBAsYtLHBt",
  "callID": "call_0a54e24d901b46bd868587c7",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/capture.go",
      "limit": 130,
      "offset": 590
    },
    "output": "<path>/source/head/labruntime/clabernetes/capture.go</path>\n<type>file</type>\n<content>\n590: // processes give the same packet timestamps a few microseconds apart, and timestamps alone\n591: // cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by\n592: // content close to the cut:\n593: //\n594: //  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is\n595: //     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.\n596: //  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the\n597: //     content of what it wrote since segment k+1 started.\n598: //  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped\n599: //     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped\n600: //     when segment k wrote the same bytes on the same interface, and every other one is written.\n601: //     From then on segment k+1 streams live.\n602: //\n603: // Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its\n604: // planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other\n605: // nodes' later packets do not overtake them in the merged stream.\n606: //\n607: // W (500 ms, less for short test segments) covers the stamping difference. Identical frames on\n608: // the same interface within W of the cut can be paired with each other, which can drop a true\n609: // repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves\n610: // a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.\n611: type captureChain struct {\n612: \tcapture *captureRun\n613: \tgroup   *captureGroup\n614: \n615: \tevents chan segmentEvent\n616: \twg     sync.WaitGroup\n617: \n618: \tactive *captureSegment\n619: \tnext   *captureSegment\n620: \t// cut is the switch time between active and next, in nanoseconds; zero until known.\n621: \tcut int64\n622: \t// emitted remembers the content of the packets active wrote while next runs.\n623: \temitted map[uint64]int\n624: \t// held are the packets of next until active ends.\n625: \theld     []*clabcapture.Packet\n626: \tsegments int\n627: \tretries  int\n628: \t// final is set once no further segment is due.\n629: \tfinal bool\n630: \t// stopping is set once ctx ended: the segments are asked to end and what they still\n631: \t// deliver is written.\n632: \tstopping bool\n633: }\n634: \n635: // run runs the chain until its last segment ended. When ctx ends, it stops the segments and\n636: // keeps writing the packets they read until then; a segment that does not end within\n637: // captureStdinCloseGrace is cut.\n638: func (c *captureChain) run(ctx context.Context) error {\n639: \tc.events = make(chan segmentEvent, 256)\n640: \t// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them\n641: \tsegmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))\n642: \tvar abort *time.Timer\n643: \tdefer func() {\n644: \t\tif abort != nil {\n645: \t\t\tabort.Stop()\n646: \t\t}\n647: \t\tcancel()\n648: \t\tc.drain()\n649: \t\tc.capture.out.Release(c)\n650: \t}()\n651: \n652: \tc.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))\n653: \ttimer := time.NewTimer(c.nextStartIn())\n654: \tdefer timer.Stop()\n655: \n656: \tdone := ctx.Done()\n657: \tfor {\n658: \t\tselect {\n659: \t\tcase <-done:\n660: \t\t\tdone = nil\n661: \t\t\tc.stop(timer)\n662: \t\t\tabort = time.AfterFunc(captureStdinCloseGrace, cancel)\n663: \t\tcase <-segmentsCtx.Done():\n664: \t\t\treturn nil\n665: \t\tcase <-timer.C:\n666: \t\t\tif c.next == nil && !c.final {\n667: \t\t\t\tc.startNext(segmentsCtx)\n668: \t\t\t}\n669: \t\tcase event := <-c.events:\n670: \t\t\tstop, err := c.handle(segmentsCtx, event, timer)\n671: \t\t\tif err != nil || stop {\n672: \t\t\t\treturn err\n673: \t\t\t}\n674: \t\t}\n675: \t}\n676: }\n677: \n678: // stop ends the chain early, like a deadline would: no further segment starts and the running\n679: // ones are asked to end. The chain then writes what they deliver until they ended.\n680: func (c *captureChain) stop(timer *time.Timer) {\n681: \tc.stopping = true\n682: \tc.final = true\n683: \ttimer.Stop()\n684: \tc.active.closeStdin()\n685: \tif c.next != nil {\n686: \t\tc.next.closeStdin()\n687: \t}\n688: }\n689: \n690: // drain waits for the segment goroutines after the chain ended.\n691: func (c *captureChain) drain() {\n692: \tdone := make(chan struct{})\n693: \tgo func() {\n694: \t\tc.wg.Wait()\n695: \t\tclose(done)\n696: \t}()\n697: \tfor {\n698: \t\tselect {\n699: \t\tcase <-done:\n700: \t\t\treturn\n701: \t\tcase <-c.events:\n702: \t\t}\n703: \t}\n704: }\n705: \n706: // segmentDuration is the requested duration of a segment starting now.\n707: func (c *captureChain) segmentDuration(now time.Time) time.Duration {\n708: \tduration := c.capture.segment\n709: \tif !c.capture.deadline.IsZero() {\n710: \t\tduration = min(duration, c.capture.deadline.Sub(now))\n711: \t}\n712: \n713: \treturn max(duration, minCaptureSegment)\n714: }\n715: \n716: // nextStartIn is the time until the follow-up of the active segment is due. It marks the chain\n717: // final when none is due.\n718: func (c *captureChain) nextStartIn() time.Duration {\n719: \tif c.stopping {\n\n(Showing lines 590-719 of 1202. Use offset=720 to continue.)\n</content>",
    "title": "source/head/labruntime/clabernetes/capture.go",
    "metadata": {
      "preview": "// processes give the same packet timestamps a few microseconds apart, and timestamps alone\n// cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by\n// content close to the cut:\n//\n//  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is\n//     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.\n//  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the\n//     content of what it wrote since segment k+1 started.\n//  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped\n//     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped\n//     when segment k wrote the same bytes on the same interface, and every other one is written.\n//     From then on segment k+1 streams live.\n//\n// Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its\n// planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other\n// nodes' later packets do not overtake them in the merged stream.\n//\n// W (500 ms, less for short test segments) covers the stamping difference. Identical frames on\n// the same interface within W of the cut can be paired with each other, which can drop a true\n// repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/capture.go",
        "text": "// processes give the same packet timestamps a few microseconds apart, and timestamps alone\n// cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by\n// content close to the cut:\n//\n//  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is\n//     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.\n//  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the\n//     content of what it wrote since segment k+1 started.\n//  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped\n//     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped\n//     when segment k wrote the same bytes on the same interface, and every other one is written.\n//     From then on segment k+1 streams live.\n//\n// Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its\n// planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other\n// nodes' later packets do not overtake them in the merged stream.\n//\n// W (500 ms, less for short test segments) covers the stamping difference. Identical frames on\n// the same interface within W of the cut can be paired with each other, which can drop a true\n// repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves\n// a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.\ntype captureChain struct {\n\tcapture *captureRun\n\tgroup   *captureGroup\n\n\tevents chan segmentEvent\n\twg     sync.WaitGroup\n\n\tactive *captureSegment\n\tnext   *captureSegment\n\t// cut is the switch time between active and next, in nanoseconds; zero until known.\n\tcut int64\n\t// emitted remembers the content of the packets active wrote while next runs.\n\temitted map[uint64]int\n\t// held are the packets of next until active ends.\n\theld     []*clabcapture.Packet\n\tsegments int\n\tretries  int\n\t// final is set once no further segment is due.\n\tfinal bool\n\t// stopping is set once ctx ended: the segments are asked to end and what they still\n\t// deliver is written.\n\tstopping bool\n}\n\n// run runs the chain until its last segment ended. When ctx ends, it stops the segments and\n// keeps writing the packets they read until then; a segment that does not end within\n// captureStdinCloseGrace is cut.\nfunc (c *captureChain) run(ctx context.Context) error {\n\tc.events = make(chan segmentEvent, 256)\n\t// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them\n\tsegmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))\n\tvar abort *time.Timer\n\tdefer func() {\n\t\tif abort != nil {\n\t\t\tabort.Stop()\n\t\t}\n\t\tcancel()\n\t\tc.drain()\n\t\tc.capture.out.Release(c)\n\t}()\n\n\tc.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))\n\ttimer := time.NewTimer(c.nextStartIn())\n\tdefer timer.Stop()\n\n\tdone := ctx.Done()\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\tdone = nil\n\t\t\tc.stop(timer)\n\t\t\tabort = time.AfterFunc(captureStdinCloseGrace, cancel)\n\t\tcase <-segmentsCtx.Done():\n\t\t\treturn nil\n\t\tcase <-timer.C:\n\t\t\tif c.next == nil && !c.final {\n\t\t\t\tc.startNext(segmentsCtx)\n\t\t\t}\n\t\tcase event := <-c.events:\n\t\t\tstop, err := c.handle(segmentsCtx, event, timer)\n\t\t\tif err != nil || stop {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n}\n\n// stop ends the chain early, like a deadline would: no further segment starts and the running\n// ones are asked to end. The chain then writes what they deliver until they ended.\nfunc (c *captureChain) stop(timer *time.Timer) {\n\tc.stopping = true\n\tc.final = true\n\ttimer.Stop()\n\tc.active.closeStdin()\n\tif c.next != nil {\n\t\tc.next.closeStdin()\n\t}\n}\n\n// drain waits for the segment goroutines after the chain ended.\nfunc (c *captureChain) drain() {\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tc.wg.Wait()\n\t\tclose(done)\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\treturn\n\t\tcase <-c.events:\n\t\t}\n\t}\n}\n\n// segmentDuration is the requested duration of a segment starting now.\nfunc (c *captureChain) segmentDuration(now time.Time) time.Duration {\n\tduration := c.capture.segment\n\tif !c.capture.deadline.IsZero() {\n\t\tduration = min(duration, c.capture.deadline.Sub(now))\n\t}\n\n\treturn max(duration, minCaptureSegment)\n}\n\n// nextStartIn is the time until the follow-up of the active segment is due. It marks the chain\n// final when none is due.\nfunc (c *captureChain) nextStartIn() time.Duration {\n\tif c.stopping {",
        "lineStart": 590,
        "lineEnd": 719,
        "totalLines": 1202,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523481721,
      "end": 1793523481727
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/labruntime/clabernetes/capture.go",
  "limit": 80,
  "offset": 930
}

Output

<path>/source/head/labruntime/clabernetes/capture.go</path>
<type>file</type>
<content>
930: 	}
931: 
932: 	window := c.capture.window.Nanoseconds()
933: 	for _, packet := range c.held {
934: 		if c.cut != 0 {
935: 			if packet.Timestamp < c.cut-window {
936: 				continue
937: 			}
938: 			if packet.Timestamp < c.cut+window {
939: 				key := packetKey(packet)
940: 				if c.emitted[key] > 0 {
941: 					c.emitted[key]--
942: 					continue
943: 				}
944: 			}
945: 		}
946: 		if stop, err := c.emit(packet); stop || err != nil {
947: 			return true, err
948: 		}
949: 	}
950: 
951: 	c.active, c.next = c.next, nil
952: 	c.held, c.emitted, c.cut = nil, nil, 0
953: 	if c.active.done {
954: 		// the chain is stopping and the follow-up ended before the active one
955: 		return true, nil
956: 	}
957: 	resetTimer(timer, c.nextStartIn())
958: 
959: 	return false, nil
960: }
961: 
962: func resetTimer(timer *time.Timer, d time.Duration) {
963: 	if !timer.Stop() {
964: 		select {
965: 		case <-timer.C:
966: 		default:
967: 		}
968: 	}
969: 	timer.Reset(d)
970: }
971: 
972: // packetKey identifies a packet by its interface and content.
973: func packetKey(packet *clabcapture.Packet) uint64 {
974: 	hash := fnv.New64a()
975: 	var id [4]byte
976: 	id[0] = byte(packet.InterfaceID)
977: 	id[1] = byte(packet.InterfaceID >> 8)
978: 	_, _ = hash.Write(id[:])
979: 	_, _ = hash.Write(packet.Data)
980: 
981: 	return hash.Sum64()
982: }
983: 
984: // start runs one clabwire capture and reports its packets, audit records and end as events.
985: func (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {
986: 	segmentCtx, cancel := context.WithCancel(ctx)
987: 	stdinReader, stdinWriter := io.Pipe()
988: 	segment := &captureSegment{
989: 		index: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,
990: 		closeStdin: func() { _ = stdinWriter.Close() },
991: 	}
992: 	c.segments++
993: 
994: 	command := []string{
995: 		clabwireManager, "node-runtime", "packet-capture",
996: 		"--nodeName", c.group.location.NodeName,
997: 		"--format", "pcapng",
998: 		"--snapLength", strconv.Itoa(c.capture.req.SnapLength),
999: 		"--duration", duration.String(),
1000: 		clabwireStopOnStdinClose,
1001: 	}
1002: 	for _, name := range c.group.interfaces {
1003: 		command = append(command, "--interface", name)
1004: 	}
1005: 	if c.capture.req.PacketLimit > 0 {
1006: 		remaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()
1007: 		command = append(command, "--packetLimit",
1008: 			strconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))
1009: 	}

(Showing lines 930-1009 of 1202. Use offset=1010 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196547cda001a5cAobG8stEOMf",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965471090010I0XCBAsYtLHBt",
  "callID": "call_6bd0fa86155a4806a1763cbc",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/capture.go",
      "limit": 80,
      "offset": 930
    },
    "output": "<path>/source/head/labruntime/clabernetes/capture.go</path>\n<type>file</type>\n<content>\n930: \t}\n931: \n932: \twindow := c.capture.window.Nanoseconds()\n933: \tfor _, packet := range c.held {\n934: \t\tif c.cut != 0 {\n935: \t\t\tif packet.Timestamp < c.cut-window {\n936: \t\t\t\tcontinue\n937: \t\t\t}\n938: \t\t\tif packet.Timestamp < c.cut+window {\n939: \t\t\t\tkey := packetKey(packet)\n940: \t\t\t\tif c.emitted[key] > 0 {\n941: \t\t\t\t\tc.emitted[key]--\n942: \t\t\t\t\tcontinue\n943: \t\t\t\t}\n944: \t\t\t}\n945: \t\t}\n946: \t\tif stop, err := c.emit(packet); stop || err != nil {\n947: \t\t\treturn true, err\n948: \t\t}\n949: \t}\n950: \n951: \tc.active, c.next = c.next, nil\n952: \tc.held, c.emitted, c.cut = nil, nil, 0\n953: \tif c.active.done {\n954: \t\t// the chain is stopping and the follow-up ended before the active one\n955: \t\treturn true, nil\n956: \t}\n957: \tresetTimer(timer, c.nextStartIn())\n958: \n959: \treturn false, nil\n960: }\n961: \n962: func resetTimer(timer *time.Timer, d time.Duration) {\n963: \tif !timer.Stop() {\n964: \t\tselect {\n965: \t\tcase <-timer.C:\n966: \t\tdefault:\n967: \t\t}\n968: \t}\n969: \ttimer.Reset(d)\n970: }\n971: \n972: // packetKey identifies a packet by its interface and content.\n973: func packetKey(packet *clabcapture.Packet) uint64 {\n974: \thash := fnv.New64a()\n975: \tvar id [4]byte\n976: \tid[0] = byte(packet.InterfaceID)\n977: \tid[1] = byte(packet.InterfaceID >> 8)\n978: \t_, _ = hash.Write(id[:])\n979: \t_, _ = hash.Write(packet.Data)\n980: \n981: \treturn hash.Sum64()\n982: }\n983: \n984: // start runs one clabwire capture and reports its packets, audit records and end as events.\n985: func (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {\n986: \tsegmentCtx, cancel := context.WithCancel(ctx)\n987: \tstdinReader, stdinWriter := io.Pipe()\n988: \tsegment := &captureSegment{\n989: \t\tindex: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,\n990: \t\tcloseStdin: func() { _ = stdinWriter.Close() },\n991: \t}\n992: \tc.segments++\n993: \n994: \tcommand := []string{\n995: \t\tclabwireManager, \"node-runtime\", \"packet-capture\",\n996: \t\t\"--nodeName\", c.group.location.NodeName,\n997: \t\t\"--format\", \"pcapng\",\n998: \t\t\"--snapLength\", strconv.Itoa(c.capture.req.SnapLength),\n999: \t\t\"--duration\", duration.String(),\n1000: \t\tclabwireStopOnStdinClose,\n1001: \t}\n1002: \tfor _, name := range c.group.interfaces {\n1003: \t\tcommand = append(command, \"--interface\", name)\n1004: \t}\n1005: \tif c.capture.req.PacketLimit > 0 {\n1006: \t\tremaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()\n1007: \t\tcommand = append(command, \"--packetLimit\",\n1008: \t\t\tstrconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))\n1009: \t}\n\n(Showing lines 930-1009 of 1202. Use offset=1010 to continue.)\n</content>",
    "title": "source/head/labruntime/clabernetes/capture.go",
    "metadata": {
      "preview": "\t}\n\n\twindow := c.capture.window.Nanoseconds()\n\tfor _, packet := range c.held {\n\t\tif c.cut != 0 {\n\t\t\tif packet.Timestamp < c.cut-window {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif packet.Timestamp < c.cut+window {\n\t\t\t\tkey := packetKey(packet)\n\t\t\t\tif c.emitted[key] > 0 {\n\t\t\t\t\tc.emitted[key]--\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif stop, err := c.emit(packet); stop || err != nil {\n\t\t\treturn true, err\n\t\t}\n\t}",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/capture.go",
        "text": "\t}\n\n\twindow := c.capture.window.Nanoseconds()\n\tfor _, packet := range c.held {\n\t\tif c.cut != 0 {\n\t\t\tif packet.Timestamp < c.cut-window {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif packet.Timestamp < c.cut+window {\n\t\t\t\tkey := packetKey(packet)\n\t\t\t\tif c.emitted[key] > 0 {\n\t\t\t\t\tc.emitted[key]--\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif stop, err := c.emit(packet); stop || err != nil {\n\t\t\treturn true, err\n\t\t}\n\t}\n\n\tc.active, c.next = c.next, nil\n\tc.held, c.emitted, c.cut = nil, nil, 0\n\tif c.active.done {\n\t\t// the chain is stopping and the follow-up ended before the active one\n\t\treturn true, nil\n\t}\n\tresetTimer(timer, c.nextStartIn())\n\n\treturn false, nil\n}\n\nfunc resetTimer(timer *time.Timer, d time.Duration) {\n\tif !timer.Stop() {\n\t\tselect {\n\t\tcase <-timer.C:\n\t\tdefault:\n\t\t}\n\t}\n\ttimer.Reset(d)\n}\n\n// packetKey identifies a packet by its interface and content.\nfunc packetKey(packet *clabcapture.Packet) uint64 {\n\thash := fnv.New64a()\n\tvar id [4]byte\n\tid[0] = byte(packet.InterfaceID)\n\tid[1] = byte(packet.InterfaceID >> 8)\n\t_, _ = hash.Write(id[:])\n\t_, _ = hash.Write(packet.Data)\n\n\treturn hash.Sum64()\n}\n\n// start runs one clabwire capture and reports its packets, audit records and end as events.\nfunc (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {\n\tsegmentCtx, cancel := context.WithCancel(ctx)\n\tstdinReader, stdinWriter := io.Pipe()\n\tsegment := &captureSegment{\n\t\tindex: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,\n\t\tcloseStdin: func() { _ = stdinWriter.Close() },\n\t}\n\tc.segments++\n\n\tcommand := []string{\n\t\tclabwireManager, \"node-runtime\", \"packet-capture\",\n\t\t\"--nodeName\", c.group.location.NodeName,\n\t\t\"--format\", \"pcapng\",\n\t\t\"--snapLength\", strconv.Itoa(c.capture.req.SnapLength),\n\t\t\"--duration\", duration.String(),\n\t\tclabwireStopOnStdinClose,\n\t}\n\tfor _, name := range c.group.interfaces {\n\t\tcommand = append(command, \"--interface\", name)\n\t}\n\tif c.capture.req.PacketLimit > 0 {\n\t\tremaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()\n\t\tcommand = append(command, \"--packetLimit\",\n\t\t\tstrconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))\n\t}",
        "lineStart": 930,
        "lineEnd": 1009,
        "totalLines": 1202,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523481822,
      "end": 1793523481828
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196547ce6001YCjy59ZJahq54o",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_1965471090010I0XCBAsYtLHBt",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 40384,
    "input": 1464,
    "output": 63,
    "reasoning": 137,
    "cache": {
      "read": 38720,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1965471090010I0XCBAsYtLHBt",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523478793,
    "completed": 1793523481833
  },
  "parentID": "msg_1965436e6001620KypTRi1ley5",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 40384,
    "input": 1464,
    "output": 63,
    "reasoning": 137,
    "cache": {
      "read": 38720,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 61
step-start
{
  "type": "step-start",
  "id": "prt_19654838e001c7VCDo5GvER70H",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196547cf3001gxJqoFK10D4pNC"
}
Reasoning
Confirmed: `handleAudit` returns `captureAuditError` regardless of `c.stopping`. When the run loop is in the `done` branch (ctx ended), and then a segment delivers a Failed audit record, `c.handle(...)` returns the error and `run` returns it. The doc contract says: "Capture writes one section ... It returns when Duration passed, PacketLimit packets were written, or the context ended (which is not an error)".

But is this a real issue? When stopping, the segments are asked to end via stdin close. Does clabwire emit a Failed audit record on stdin close? The `Succeeded` record goes to debug log. If the stdin-close end is modeled as Succeeded, no error. But if clabwire reports Failed because the client closed stdin (or writes Failed when killed), a clean Ctrl+C would surface "capture ... failed by clabwire" to the user. This is speculative — depends on clabwire's behavior, which is external. The contract test `TestCaptureClosesStdinWhenItEnds` "cancel" subtest runs with the fake clabwire which presumably doesn't emit Failed on stdin close. So it's a potential P3/P4 note, not confirmed. Actually wait — also consider: if clabwire legitimately fails mid-capture while the user is pressing Ctrl+C, reporting the failure is arguably correct. The questionable case is only whether clabwire reports Failed *because of* the stop. Unverifiable. I'll put it in coverage notes rather than a finding, or as a P4 with clear caveat. Hmm. The instructions: "Return only supported, useful findings... Put unresolved uncertainty in coverage notes." This is speculative — coverage notes.

Now let me finish remaining checks:
1. `capture/output.go` written/Written atomic — fine.
2. Check `cmd/options.go` diff (region ~2618) and `cmd/root_test.go` — already in read region 2166-2765? Summary says diff regions 2166 and 2766 were read, so 2618-2744 covered.
3. Remaining unread diff regions: none — 1 to 7018 fully covered now.

Remaining unread head files worth a skim: `capture/pcapng_test.go` (coverage), `capture/output.go` (read), `core/capture_local.go` (read per summary), `cmd/inspect_interfaces.go` (diff-only), docs/manual/wireshark.md diff (3900 region: lines 3879-3900).

Let me check the wireshark.md diff region and skim pcapng_test.go quickly. Also confirm `capture/output.go` ValidateRequest and the `-w -` doc. Actually those were verified.

One more candidate: in the smoke test 33-capture.robot "The capture reattaches..." test uses `containerlab restart -t ${topo} --node l2` — fine.

Let me quickly check pcapng_test.go coverage and the docs/manual/wireshark.md diff hunk (between 3879 and 3900).
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 100,
  "offset": 3876
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
3876:    rejected, and so is `--node-filter`. `--drawio` runs the clab-io-draw
3877:    container, so it needs Docker or Podman on the outer host.
3878:  - `tools` commands operate on local containers and host networking and are
3879: diff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md
3880: index b194b29..4654128 100644
3881: --- a/docs/manual/wireshark.md
3882: +++ b/docs/manual/wireshark.md
3883: @@ -15,10 +15,16 @@ Every lab emulation software must provide its users with the packet capturing ab
3884:  
3885:  Containerlab offers a simple way to capture the packets from any interface of any node in the lab. This article will explain how to do that.
3886:  
3887:  ///tip
3888:  
3889: +The [`containerlab capture`](../cmd/capture.md) command captures one or more lab link interfaces, of one or more nodes, into one pcapng file or stream, with nothing to install in the nodes or on the host:
3890: +
3891: +```bash
3892: +containerlab capture --name quickstart --target srl:e1-1 -w - | wireshark -k -i -
3893: +```
3894: +
3895:  If you are looking for a free Web UI for packet capture with Wireshark, check out our [Edgeshark integration](#edgeshark-integration).
3896:  ///
3897:  
3898:  Consider the following lab topology which highlights the typical points of packet capture.
3899:  
3900: diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go
3901: new file mode 100644
3902: index 0000000..69d4072
3903: --- /dev/null
3904: +++ b/labruntime/clabernetes/capture.go
3905: @@ -0,0 +1,1202 @@
3906: +package clabernetes
3907: +
3908: +import (
3909: +	"bytes"
3910: +	"context"
3911: +	"encoding/json"
3912: +	"errors"
3913: +	"fmt"
3914: +	"hash/fnv"
3915: +	"io"
3916: +	"os"
3917: +	"sort"
3918: +	"strconv"
3919: +	"strings"
3920: +	"sync"
3921: +	"time"
3922: +
3923: +	"github.com/charmbracelet/log"
3924: +	clabcapture "github.com/srl-labs/containerlab/capture"
3925: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
3926: +	"golang.org/x/sync/errgroup"
3927: +)
3928: +
3929: +// The clabwire packet capture contract (clabernetes 0.11 or newer).
3930: +const (
3931: +	clabwireContainer = "clabwire"
3932: +	clabwireManager   = "/clabernetes/manager"
3933: +	// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.
3934: +	captureAuditSchema = "c9s.direct-packet-capture-audit/v1alpha1"
3935: +
3936: +	captureAuditStarted   = "Started"
3937: +	captureAuditSucceeded = "Succeeded"
3938: +	captureAuditFailed    = "Failed"
3939: +	captureAuditDenied    = "Denied"
3940: +
3941: +	// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.
3942: +	maxCaptureSegment = time.Hour
3943: +	// maxClabwirePackets is the packet limit of a single clabwire capture.
3944: +	maxClabwirePackets = 1_000_000
3945: +	// maxCaptureOverlap is how long two chained segments run side by side.
3946: +	maxCaptureOverlap = 10 * time.Second
3947: +	// maxCaptureCutWindow is the half-width of the window around the cut in which packets of
3948: +	// two segments are matched by content; it covers the difference between the timestamps
3949: +	// two clabwire processes give the same packet.
3950: +	maxCaptureCutWindow = 500 * time.Millisecond
3951: +	// minCaptureSegment is the shortest segment the chain requests.
3952: +	minCaptureSegment = 100 * time.Millisecond
3953: +	// captureEndGrace is how long a capture with a duration waits for its last clabwire
3954: +	// process to end after the duration passed.
3955: +	captureEndGrace = 30 * time.Second
3956: +	// captureStartRetries bounds the attempts to start a follow-up segment.
3957: +	captureStartRetries = 3
3958: +	// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was
3959: +	// closed before the stream is cut.
3960: +	captureStdinCloseGrace = 3 * time.Second
3961: +	// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A
3962: +	// Kubernetes exec does not stop its process when the stream ends, but it closes the
3963: +	// process's stdin, so every capture runs with stdin attached and this flag.
3964: +	clabwireStopOnStdinClose = "--stop-on-stdin-close"
3965: +
3966: +	// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests
3967: +	// without hour-long captures.
3968: +	envCaptureSegment = "CLAB_C9S_CAPTURE_SEGMENT"
3969: +	// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets
3970: +	// of other nodes stamped earlier but delivered later still go out before it.
3971: +	defaultCaptureReorderWindow = 250 * time.Millisecond
3972: +	// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.
3973: +	// It is an internal knob, not a supported setting.
3974: +	envCaptureReorderWindow = "CLAB_C9S_CAPTURE_REORDER_WINDOW"
3975: +)

(Showing lines 3876-3975 of 7018. Use offset=3976 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1965493e6001oMUC0jPAAwlyFR",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196547cf3001gxJqoFK10D4pNC",
  "callID": "call_daaffa693bdc4610b52a14ff",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 100,
      "offset": 3876
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n3876:    rejected, and so is `--node-filter`. `--drawio` runs the clab-io-draw\n3877:    container, so it needs Docker or Podman on the outer host.\n3878:  - `tools` commands operate on local containers and host networking and are\n3879: diff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md\n3880: index b194b29..4654128 100644\n3881: --- a/docs/manual/wireshark.md\n3882: +++ b/docs/manual/wireshark.md\n3883: @@ -15,10 +15,16 @@ Every lab emulation software must provide its users with the packet capturing ab\n3884:  \n3885:  Containerlab offers a simple way to capture the packets from any interface of any node in the lab. This article will explain how to do that.\n3886:  \n3887:  ///tip\n3888:  \n3889: +The [`containerlab capture`](../cmd/capture.md) command captures one or more lab link interfaces, of one or more nodes, into one pcapng file or stream, with nothing to install in the nodes or on the host:\n3890: +\n3891: +```bash\n3892: +containerlab capture --name quickstart --target srl:e1-1 -w - | wireshark -k -i -\n3893: +```\n3894: +\n3895:  If you are looking for a free Web UI for packet capture with Wireshark, check out our [Edgeshark integration](#edgeshark-integration).\n3896:  ///\n3897:  \n3898:  Consider the following lab topology which highlights the typical points of packet capture.\n3899:  \n3900: diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go\n3901: new file mode 100644\n3902: index 0000000..69d4072\n3903: --- /dev/null\n3904: +++ b/labruntime/clabernetes/capture.go\n3905: @@ -0,0 +1,1202 @@\n3906: +package clabernetes\n3907: +\n3908: +import (\n3909: +\t\"bytes\"\n3910: +\t\"context\"\n3911: +\t\"encoding/json\"\n3912: +\t\"errors\"\n3913: +\t\"fmt\"\n3914: +\t\"hash/fnv\"\n3915: +\t\"io\"\n3916: +\t\"os\"\n3917: +\t\"sort\"\n3918: +\t\"strconv\"\n3919: +\t\"strings\"\n3920: +\t\"sync\"\n3921: +\t\"time\"\n3922: +\n3923: +\t\"github.com/charmbracelet/log\"\n3924: +\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n3925: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n3926: +\t\"golang.org/x/sync/errgroup\"\n3927: +)\n3928: +\n3929: +// The clabwire packet capture contract (clabernetes 0.11 or newer).\n3930: +const (\n3931: +\tclabwireContainer = \"clabwire\"\n3932: +\tclabwireManager   = \"/clabernetes/manager\"\n3933: +\t// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.\n3934: +\tcaptureAuditSchema = \"c9s.direct-packet-capture-audit/v1alpha1\"\n3935: +\n3936: +\tcaptureAuditStarted   = \"Started\"\n3937: +\tcaptureAuditSucceeded = \"Succeeded\"\n3938: +\tcaptureAuditFailed    = \"Failed\"\n3939: +\tcaptureAuditDenied    = \"Denied\"\n3940: +\n3941: +\t// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.\n3942: +\tmaxCaptureSegment = time.Hour\n3943: +\t// maxClabwirePackets is the packet limit of a single clabwire capture.\n3944: +\tmaxClabwirePackets = 1_000_000\n3945: +\t// maxCaptureOverlap is how long two chained segments run side by side.\n3946: +\tmaxCaptureOverlap = 10 * time.Second\n3947: +\t// maxCaptureCutWindow is the half-width of the window around the cut in which packets of\n3948: +\t// two segments are matched by content; it covers the difference between the timestamps\n3949: +\t// two clabwire processes give the same packet.\n3950: +\tmaxCaptureCutWindow = 500 * time.Millisecond\n3951: +\t// minCaptureSegment is the shortest segment the chain requests.\n3952: +\tminCaptureSegment = 100 * time.Millisecond\n3953: +\t// captureEndGrace is how long a capture with a duration waits for its last clabwire\n3954: +\t// process to end after the duration passed.\n3955: +\tcaptureEndGrace = 30 * time.Second\n3956: +\t// captureStartRetries bounds the attempts to start a follow-up segment.\n3957: +\tcaptureStartRetries = 3\n3958: +\t// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was\n3959: +\t// closed before the stream is cut.\n3960: +\tcaptureStdinCloseGrace = 3 * time.Second\n3961: +\t// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A\n3962: +\t// Kubernetes exec does not stop its process when the stream ends, but it closes the\n3963: +\t// process's stdin, so every capture runs with stdin attached and this flag.\n3964: +\tclabwireStopOnStdinClose = \"--stop-on-stdin-close\"\n3965: +\n3966: +\t// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests\n3967: +\t// without hour-long captures.\n3968: +\tenvCaptureSegment = \"CLAB_C9S_CAPTURE_SEGMENT\"\n3969: +\t// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets\n3970: +\t// of other nodes stamped earlier but delivered later still go out before it.\n3971: +\tdefaultCaptureReorderWindow = 250 * time.Millisecond\n3972: +\t// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.\n3973: +\t// It is an internal knob, not a supported setting.\n3974: +\tenvCaptureReorderWindow = \"CLAB_C9S_CAPTURE_REORDER_WINDOW\"\n3975: +)\n\n(Showing lines 3876-3975 of 7018. Use offset=3976 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "   rejected, and so is `--node-filter`. `--drawio` runs the clab-io-draw\n   container, so it needs Docker or Podman on the outer host.\n - `tools` commands operate on local containers and host networking and are\ndiff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md\nindex b194b29..4654128 100644\n--- a/docs/manual/wireshark.md\n+++ b/docs/manual/wireshark.md\n@@ -15,10 +15,16 @@ Every lab emulation software must provide its users with the packet capturing ab\n \n Containerlab offers a simple way to capture the packets from any interface of any node in the lab. This article will explain how to do that.\n \n ///tip\n \n+The [`containerlab capture`](../cmd/capture.md) command captures one or more lab link interfaces, of one or more nodes, into one pcapng file or stream, with nothing to install in the nodes or on the host:\n+\n+```bash\n+containerlab capture --name quickstart --target srl:e1-1 -w - | wireshark -k -i -\n+```\n+\n If you are looking for a free Web UI for packet capture with Wireshark, check out our [Edgeshark integration](#edgeshark-integration).",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "   rejected, and so is `--node-filter`. `--drawio` runs the clab-io-draw\n   container, so it needs Docker or Podman on the outer host.\n - `tools` commands operate on local containers and host networking and are\ndiff --git a/docs/manual/wireshark.md b/docs/manual/wireshark.md\nindex b194b29..4654128 100644\n--- a/docs/manual/wireshark.md\n+++ b/docs/manual/wireshark.md\n@@ -15,10 +15,16 @@ Every lab emulation software must provide its users with the packet capturing ab\n \n Containerlab offers a simple way to capture the packets from any interface of any node in the lab. This article will explain how to do that.\n \n ///tip\n \n+The [`containerlab capture`](../cmd/capture.md) command captures one or more lab link interfaces, of one or more nodes, into one pcapng file or stream, with nothing to install in the nodes or on the host:\n+\n+```bash\n+containerlab capture --name quickstart --target srl:e1-1 -w - | wireshark -k -i -\n+```\n+\n If you are looking for a free Web UI for packet capture with Wireshark, check out our [Edgeshark integration](#edgeshark-integration).\n ///\n \n Consider the following lab topology which highlights the typical points of packet capture.\n \ndiff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go\nnew file mode 100644\nindex 0000000..69d4072\n--- /dev/null\n+++ b/labruntime/clabernetes/capture.go\n@@ -0,0 +1,1202 @@\n+package clabernetes\n+\n+import (\n+\t\"bytes\"\n+\t\"context\"\n+\t\"encoding/json\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"hash/fnv\"\n+\t\"io\"\n+\t\"os\"\n+\t\"sort\"\n+\t\"strconv\"\n+\t\"strings\"\n+\t\"sync\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\tclabcapture \"github.com/srl-labs/containerlab/capture\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\t\"golang.org/x/sync/errgroup\"\n+)\n+\n+// The clabwire packet capture contract (clabernetes 0.11 or newer).\n+const (\n+\tclabwireContainer = \"clabwire\"\n+\tclabwireManager   = \"/clabernetes/manager\"\n+\t// captureAuditSchema is the schema of the JSON audit lines clabwire writes to stderr.\n+\tcaptureAuditSchema = \"c9s.direct-packet-capture-audit/v1alpha1\"\n+\n+\tcaptureAuditStarted   = \"Started\"\n+\tcaptureAuditSucceeded = \"Succeeded\"\n+\tcaptureAuditFailed    = \"Failed\"\n+\tcaptureAuditDenied    = \"Denied\"\n+\n+\t// maxCaptureSegment is the longest single clabwire capture; longer captures are chained.\n+\tmaxCaptureSegment = time.Hour\n+\t// maxClabwirePackets is the packet limit of a single clabwire capture.\n+\tmaxClabwirePackets = 1_000_000\n+\t// maxCaptureOverlap is how long two chained segments run side by side.\n+\tmaxCaptureOverlap = 10 * time.Second\n+\t// maxCaptureCutWindow is the half-width of the window around the cut in which packets of\n+\t// two segments are matched by content; it covers the difference between the timestamps\n+\t// two clabwire processes give the same packet.\n+\tmaxCaptureCutWindow = 500 * time.Millisecond\n+\t// minCaptureSegment is the shortest segment the chain requests.\n+\tminCaptureSegment = 100 * time.Millisecond\n+\t// captureEndGrace is how long a capture with a duration waits for its last clabwire\n+\t// process to end after the duration passed.\n+\tcaptureEndGrace = 30 * time.Second\n+\t// captureStartRetries bounds the attempts to start a follow-up segment.\n+\tcaptureStartRetries = 3\n+\t// captureStdinCloseGrace is how long a segment's exec may take to end after its stdin was\n+\t// closed before the stream is cut.\n+\tcaptureStdinCloseGrace = 3 * time.Second\n+\t// clabwireStopOnStdinClose makes clabwire end a capture when its stdin closes. A\n+\t// Kubernetes exec does not stop its process when the stream ends, but it closes the\n+\t// process's stdin, so every capture runs with stdin attached and this flag.\n+\tclabwireStopOnStdinClose = \"--stop-on-stdin-close\"\n+\n+\t// envCaptureSegment overrides the segment length. It exists to exercise chaining in tests\n+\t// without hour-long captures.\n+\tenvCaptureSegment = \"CLAB_C9S_CAPTURE_SEGMENT\"\n+\t// defaultCaptureReorderWindow is how long the merged stream holds a packet back so packets\n+\t// of other nodes stamped earlier but delivered later still go out before it.\n+\tdefaultCaptureReorderWindow = 250 * time.Millisecond\n+\t// envCaptureReorderWindow overrides the reorder window; 0 writes packets as they arrive.\n+\t// It is an internal knob, not a supported setting.\n+\tenvCaptureReorderWindow = \"CLAB_C9S_CAPTURE_REORDER_WINDOW\"\n+)",
        "lineStart": 3876,
        "lineEnd": 3975,
        "totalLines": 7018,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523487722,
      "end": 1793523487741
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/capture/pcapng_test.go",
  "limit": 150
}

Output

<path>/source/head/capture/pcapng_test.go</path>
<type>file</type>
<content>
1: package capture
2: 
3: import (
4: 	"bytes"
5: 	"encoding/binary"
6: 	"errors"
7: 	"io"
8: 	"strings"
9: 	"testing"
10: )
11: 
12: func TestPCAPNGWriterAndReaderRoundTrip(t *testing.T) {
13: 	t.Parallel()
14: 
15: 	var out bytes.Buffer
16: 	writer := NewWriter(&out)
17: 	if err := writer.WriteHeader([]string{"r1:e1-1", "r2:eth1"}, 1500); err != nil {
18: 		t.Fatal(err)
19: 	}
20: 	packets := []Packet{
21: 		{
22: 			InterfaceID:    1,
23: 			Timestamp:      1_761_559_200_123_456_789,
24: 			OriginalLength: 98,
25: 			Data:           []byte("abcde"),
26: 		},
27: 		{
28: 			InterfaceID:    0,
29: 			Timestamp:      1_761_559_200_123_456_790,
30: 			OriginalLength: 4,
31: 			Data:           []byte("wxyz"),
32: 		},
33: 	}
34: 	for idx := range packets {
35: 		if err := writer.WritePacket(packets[idx].InterfaceID, &packets[idx]); err != nil {
36: 			t.Fatal(err)
37: 		}
38: 	}
39: 
40: 	data := out.Bytes()
41: 	// the section header names the writer
42: 	if !bytes.Contains(data[:64], []byte(captureUserApplication)) {
43: 		t.Fatal("section header has no shb_userappl")
44: 	}
45: 	if len(data)%4 != 0 {
46: 		t.Fatalf("stream length %d is not 32-bit aligned", len(data))
47: 	}
48: 
49: 	reader := NewReader(bytes.NewReader(data))
50: 	var names []string
51: 	var read []Packet
52: 	for {
53: 		event, err := reader.Next()
54: 		if errors.Is(err, io.EOF) {
55: 			break
56: 		}
57: 		if err != nil {
58: 			t.Fatal(err)
59: 		}
60: 		if event.Interface != nil {
61: 			names = append(names, event.Interface.Name)
62: 			if event.Interface.SnapLength != 1500 || event.Interface.LinkType != 1 {
63: 				t.Fatalf("interface = %+v", event.Interface)
64: 			}
65: 		}
66: 		if event.Packet != nil {
67: 			read = append(read, *event.Packet)
68: 		}
69: 	}
70: 	if len(names) != 2 || names[0] != "r1:e1-1" || names[1] != "r2:eth1" {
71: 		t.Fatalf("names = %v", names)
72: 	}
73: 	for idx := range packets {
74: 		if read[idx].InterfaceID != packets[idx].InterfaceID ||
75: 			read[idx].Timestamp != packets[idx].Timestamp ||
76: 			read[idx].OriginalLength != packets[idx].OriginalLength ||
77: 			!bytes.Equal(read[idx].Data, packets[idx].Data) {
78: 			t.Fatalf("packet %d = %+v, want %+v", idx, read[idx], packets[idx])
79: 		}
80: 	}
81: }
82: 
83: func TestPCAPNGReaderHandlesRepeatedSectionsAndResolutions(t *testing.T) {
84: 	t.Parallel()
85: 
86: 	var out bytes.Buffer
87: 	first := NewWriter(&out)
88: 	_ = first.WriteHeader([]string{"eth1"}, 64)
89: 	_ = first.WritePacket(0, &Packet{Timestamp: 5, Data: []byte{1}})
90: 
91: 	// a second section whose interface has microsecond timestamps (no if_tsresol)
92: 	section := make([]byte, 16)
93: 	binary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)
94: 	binary.LittleEndian.PutUint16(section[4:], 1)
95: 	out.Write(pcapngBlock(pcapngSectionHeaderType, section))
96: 	description := make([]byte, 8)
97: 	binary.LittleEndian.PutUint16(description[0:], 1)
98: 	description = appendPCAPNGOption(description, pcapngOptionIfName, []byte("eth2"))
99: 	out.Write(pcapngBlock(pcapngInterfaceType, description))
100: 	body := make([]byte, 20)
101: 	binary.LittleEndian.PutUint32(body[8:], 7) // 7 microseconds
102: 	out.Write(pcapngBlock(pcapngEnhancedPacketType, body))
103: 
104: 	reader := NewReader(&out)
105: 	var timestamps []int64
106: 	for {
107: 		event, err := reader.Next()
108: 		if errors.Is(err, io.EOF) {
109: 			break
110: 		}
111: 		if err != nil {
112: 			t.Fatal(err)
113: 		}
114: 		if event.Packet != nil {
115: 			timestamps = append(timestamps, event.Packet.Timestamp)
116: 		}
117: 	}
118: 	if reader.sections != 2 || len(timestamps) != 2 || timestamps[0] != 5 || timestamps[1] != 7000 {
119: 		t.Fatalf("sections %d, timestamps %v", reader.sections, timestamps)
120: 	}
121: }
122: 
123: func TestPCAPNGReaderRejectsInvalidStreams(t *testing.T) {
124: 	t.Parallel()
125: 
126: 	var valid bytes.Buffer
127: 	writer := NewWriter(&valid)
128: 	_ = writer.WriteHeader([]string{"eth1"}, 64)
129: 	_ = writer.WritePacket(0, &Packet{Timestamp: 1, Data: []byte("data")})
130: 
131: 	readAll := func(data []byte) error {
132: 		reader := NewReader(bytes.NewReader(data))
133: 		for {
134: 			_, err := reader.Next()
135: 			if errors.Is(err, io.EOF) {
136: 				return nil
137: 			}
138: 			if err != nil {
139: 				return err
140: 			}
141: 		}
142: 	}
143: 
144: 	if err := readAll(valid.Bytes()[:valid.Len()-6]); !errors.Is(err, io.ErrUnexpectedEOF) {
145: 		t.Fatalf("truncated stream: %v", err)
146: 	}
147: 
148: 	bigEndian := append([]byte(nil), valid.Bytes()...)
149: 	binary.BigEndian.PutUint32(bigEndian[4:], binary.LittleEndian.Uint32(bigEndian[4:]))
150: 	binary.BigEndian.PutUint32(bigEndian[8:], pcapngByteOrderMagic)

(Showing lines 1-150 of 167. Use offset=151 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196549428001P2bpyegQoYNxV9",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196547cf3001gxJqoFK10D4pNC",
  "callID": "call_56a35f951c1c4a7e85d334ef",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/capture/pcapng_test.go",
      "limit": 150
    },
    "output": "<path>/source/head/capture/pcapng_test.go</path>\n<type>file</type>\n<content>\n1: package capture\n2: \n3: import (\n4: \t\"bytes\"\n5: \t\"encoding/binary\"\n6: \t\"errors\"\n7: \t\"io\"\n8: \t\"strings\"\n9: \t\"testing\"\n10: )\n11: \n12: func TestPCAPNGWriterAndReaderRoundTrip(t *testing.T) {\n13: \tt.Parallel()\n14: \n15: \tvar out bytes.Buffer\n16: \twriter := NewWriter(&out)\n17: \tif err := writer.WriteHeader([]string{\"r1:e1-1\", \"r2:eth1\"}, 1500); err != nil {\n18: \t\tt.Fatal(err)\n19: \t}\n20: \tpackets := []Packet{\n21: \t\t{\n22: \t\t\tInterfaceID:    1,\n23: \t\t\tTimestamp:      1_761_559_200_123_456_789,\n24: \t\t\tOriginalLength: 98,\n25: \t\t\tData:           []byte(\"abcde\"),\n26: \t\t},\n27: \t\t{\n28: \t\t\tInterfaceID:    0,\n29: \t\t\tTimestamp:      1_761_559_200_123_456_790,\n30: \t\t\tOriginalLength: 4,\n31: \t\t\tData:           []byte(\"wxyz\"),\n32: \t\t},\n33: \t}\n34: \tfor idx := range packets {\n35: \t\tif err := writer.WritePacket(packets[idx].InterfaceID, &packets[idx]); err != nil {\n36: \t\t\tt.Fatal(err)\n37: \t\t}\n38: \t}\n39: \n40: \tdata := out.Bytes()\n41: \t// the section header names the writer\n42: \tif !bytes.Contains(data[:64], []byte(captureUserApplication)) {\n43: \t\tt.Fatal(\"section header has no shb_userappl\")\n44: \t}\n45: \tif len(data)%4 != 0 {\n46: \t\tt.Fatalf(\"stream length %d is not 32-bit aligned\", len(data))\n47: \t}\n48: \n49: \treader := NewReader(bytes.NewReader(data))\n50: \tvar names []string\n51: \tvar read []Packet\n52: \tfor {\n53: \t\tevent, err := reader.Next()\n54: \t\tif errors.Is(err, io.EOF) {\n55: \t\t\tbreak\n56: \t\t}\n57: \t\tif err != nil {\n58: \t\t\tt.Fatal(err)\n59: \t\t}\n60: \t\tif event.Interface != nil {\n61: \t\t\tnames = append(names, event.Interface.Name)\n62: \t\t\tif event.Interface.SnapLength != 1500 || event.Interface.LinkType != 1 {\n63: \t\t\t\tt.Fatalf(\"interface = %+v\", event.Interface)\n64: \t\t\t}\n65: \t\t}\n66: \t\tif event.Packet != nil {\n67: \t\t\tread = append(read, *event.Packet)\n68: \t\t}\n69: \t}\n70: \tif len(names) != 2 || names[0] != \"r1:e1-1\" || names[1] != \"r2:eth1\" {\n71: \t\tt.Fatalf(\"names = %v\", names)\n72: \t}\n73: \tfor idx := range packets {\n74: \t\tif read[idx].InterfaceID != packets[idx].InterfaceID ||\n75: \t\t\tread[idx].Timestamp != packets[idx].Timestamp ||\n76: \t\t\tread[idx].OriginalLength != packets[idx].OriginalLength ||\n77: \t\t\t!bytes.Equal(read[idx].Data, packets[idx].Data) {\n78: \t\t\tt.Fatalf(\"packet %d = %+v, want %+v\", idx, read[idx], packets[idx])\n79: \t\t}\n80: \t}\n81: }\n82: \n83: func TestPCAPNGReaderHandlesRepeatedSectionsAndResolutions(t *testing.T) {\n84: \tt.Parallel()\n85: \n86: \tvar out bytes.Buffer\n87: \tfirst := NewWriter(&out)\n88: \t_ = first.WriteHeader([]string{\"eth1\"}, 64)\n89: \t_ = first.WritePacket(0, &Packet{Timestamp: 5, Data: []byte{1}})\n90: \n91: \t// a second section whose interface has microsecond timestamps (no if_tsresol)\n92: \tsection := make([]byte, 16)\n93: \tbinary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)\n94: \tbinary.LittleEndian.PutUint16(section[4:], 1)\n95: \tout.Write(pcapngBlock(pcapngSectionHeaderType, section))\n96: \tdescription := make([]byte, 8)\n97: \tbinary.LittleEndian.PutUint16(description[0:], 1)\n98: \tdescription = appendPCAPNGOption(description, pcapngOptionIfName, []byte(\"eth2\"))\n99: \tout.Write(pcapngBlock(pcapngInterfaceType, description))\n100: \tbody := make([]byte, 20)\n101: \tbinary.LittleEndian.PutUint32(body[8:], 7) // 7 microseconds\n102: \tout.Write(pcapngBlock(pcapngEnhancedPacketType, body))\n103: \n104: \treader := NewReader(&out)\n105: \tvar timestamps []int64\n106: \tfor {\n107: \t\tevent, err := reader.Next()\n108: \t\tif errors.Is(err, io.EOF) {\n109: \t\t\tbreak\n110: \t\t}\n111: \t\tif err != nil {\n112: \t\t\tt.Fatal(err)\n113: \t\t}\n114: \t\tif event.Packet != nil {\n115: \t\t\ttimestamps = append(timestamps, event.Packet.Timestamp)\n116: \t\t}\n117: \t}\n118: \tif reader.sections != 2 || len(timestamps) != 2 || timestamps[0] != 5 || timestamps[1] != 7000 {\n119: \t\tt.Fatalf(\"sections %d, timestamps %v\", reader.sections, timestamps)\n120: \t}\n121: }\n122: \n123: func TestPCAPNGReaderRejectsInvalidStreams(t *testing.T) {\n124: \tt.Parallel()\n125: \n126: \tvar valid bytes.Buffer\n127: \twriter := NewWriter(&valid)\n128: \t_ = writer.WriteHeader([]string{\"eth1\"}, 64)\n129: \t_ = writer.WritePacket(0, &Packet{Timestamp: 1, Data: []byte(\"data\")})\n130: \n131: \treadAll := func(data []byte) error {\n132: \t\treader := NewReader(bytes.NewReader(data))\n133: \t\tfor {\n134: \t\t\t_, err := reader.Next()\n135: \t\t\tif errors.Is(err, io.EOF) {\n136: \t\t\t\treturn nil\n137: \t\t\t}\n138: \t\t\tif err != nil {\n139: \t\t\t\treturn err\n140: \t\t\t}\n141: \t\t}\n142: \t}\n143: \n144: \tif err := readAll(valid.Bytes()[:valid.Len()-6]); !errors.Is(err, io.ErrUnexpectedEOF) {\n145: \t\tt.Fatalf(\"truncated stream: %v\", err)\n146: \t}\n147: \n148: \tbigEndian := append([]byte(nil), valid.Bytes()...)\n149: \tbinary.BigEndian.PutUint32(bigEndian[4:], binary.LittleEndian.Uint32(bigEndian[4:]))\n150: \tbinary.BigEndian.PutUint32(bigEndian[8:], pcapngByteOrderMagic)\n\n(Showing lines 1-150 of 167. Use offset=151 to continue.)\n</content>",
    "title": "source/head/capture/pcapng_test.go",
    "metadata": {
      "preview": "package capture\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"io\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestPCAPNGWriterAndReaderRoundTrip(t *testing.T) {\n\tt.Parallel()\n\n\tvar out bytes.Buffer\n\twriter := NewWriter(&out)\n\tif err := writer.WriteHeader([]string{\"r1:e1-1\", \"r2:eth1\"}, 1500); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tpackets := []Packet{",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/capture/pcapng_test.go",
        "text": "package capture\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"io\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestPCAPNGWriterAndReaderRoundTrip(t *testing.T) {\n\tt.Parallel()\n\n\tvar out bytes.Buffer\n\twriter := NewWriter(&out)\n\tif err := writer.WriteHeader([]string{\"r1:e1-1\", \"r2:eth1\"}, 1500); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tpackets := []Packet{\n\t\t{\n\t\t\tInterfaceID:    1,\n\t\t\tTimestamp:      1_761_559_200_123_456_789,\n\t\t\tOriginalLength: 98,\n\t\t\tData:           []byte(\"abcde\"),\n\t\t},\n\t\t{\n\t\t\tInterfaceID:    0,\n\t\t\tTimestamp:      1_761_559_200_123_456_790,\n\t\t\tOriginalLength: 4,\n\t\t\tData:           []byte(\"wxyz\"),\n\t\t},\n\t}\n\tfor idx := range packets {\n\t\tif err := writer.WritePacket(packets[idx].InterfaceID, &packets[idx]); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\tdata := out.Bytes()\n\t// the section header names the writer\n\tif !bytes.Contains(data[:64], []byte(captureUserApplication)) {\n\t\tt.Fatal(\"section header has no shb_userappl\")\n\t}\n\tif len(data)%4 != 0 {\n\t\tt.Fatalf(\"stream length %d is not 32-bit aligned\", len(data))\n\t}\n\n\treader := NewReader(bytes.NewReader(data))\n\tvar names []string\n\tvar read []Packet\n\tfor {\n\t\tevent, err := reader.Next()\n\t\tif errors.Is(err, io.EOF) {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif event.Interface != nil {\n\t\t\tnames = append(names, event.Interface.Name)\n\t\t\tif event.Interface.SnapLength != 1500 || event.Interface.LinkType != 1 {\n\t\t\t\tt.Fatalf(\"interface = %+v\", event.Interface)\n\t\t\t}\n\t\t}\n\t\tif event.Packet != nil {\n\t\t\tread = append(read, *event.Packet)\n\t\t}\n\t}\n\tif len(names) != 2 || names[0] != \"r1:e1-1\" || names[1] != \"r2:eth1\" {\n\t\tt.Fatalf(\"names = %v\", names)\n\t}\n\tfor idx := range packets {\n\t\tif read[idx].InterfaceID != packets[idx].InterfaceID ||\n\t\t\tread[idx].Timestamp != packets[idx].Timestamp ||\n\t\t\tread[idx].OriginalLength != packets[idx].OriginalLength ||\n\t\t\t!bytes.Equal(read[idx].Data, packets[idx].Data) {\n\t\t\tt.Fatalf(\"packet %d = %+v, want %+v\", idx, read[idx], packets[idx])\n\t\t}\n\t}\n}\n\nfunc TestPCAPNGReaderHandlesRepeatedSectionsAndResolutions(t *testing.T) {\n\tt.Parallel()\n\n\tvar out bytes.Buffer\n\tfirst := NewWriter(&out)\n\t_ = first.WriteHeader([]string{\"eth1\"}, 64)\n\t_ = first.WritePacket(0, &Packet{Timestamp: 5, Data: []byte{1}})\n\n\t// a second section whose interface has microsecond timestamps (no if_tsresol)\n\tsection := make([]byte, 16)\n\tbinary.LittleEndian.PutUint32(section[0:], pcapngByteOrderMagic)\n\tbinary.LittleEndian.PutUint16(section[4:], 1)\n\tout.Write(pcapngBlock(pcapngSectionHeaderType, section))\n\tdescription := make([]byte, 8)\n\tbinary.LittleEndian.PutUint16(description[0:], 1)\n\tdescription = appendPCAPNGOption(description, pcapngOptionIfName, []byte(\"eth2\"))\n\tout.Write(pcapngBlock(pcapngInterfaceType, description))\n\tbody := make([]byte, 20)\n\tbinary.LittleEndian.PutUint32(body[8:], 7) // 7 microseconds\n\tout.Write(pcapngBlock(pcapngEnhancedPacketType, body))\n\n\treader := NewReader(&out)\n\tvar timestamps []int64\n\tfor {\n\t\tevent, err := reader.Next()\n\t\tif errors.Is(err, io.EOF) {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif event.Packet != nil {\n\t\t\ttimestamps = append(timestamps, event.Packet.Timestamp)\n\t\t}\n\t}\n\tif reader.sections != 2 || len(timestamps) != 2 || timestamps[0] != 5 || timestamps[1] != 7000 {\n\t\tt.Fatalf(\"sections %d, timestamps %v\", reader.sections, timestamps)\n\t}\n}\n\nfunc TestPCAPNGReaderRejectsInvalidStreams(t *testing.T) {\n\tt.Parallel()\n\n\tvar valid bytes.Buffer\n\twriter := NewWriter(&valid)\n\t_ = writer.WriteHeader([]string{\"eth1\"}, 64)\n\t_ = writer.WritePacket(0, &Packet{Timestamp: 1, Data: []byte(\"data\")})\n\n\treadAll := func(data []byte) error {\n\t\treader := NewReader(bytes.NewReader(data))\n\t\tfor {\n\t\t\t_, err := reader.Next()\n\t\t\tif errors.Is(err, io.EOF) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := readAll(valid.Bytes()[:valid.Len()-6]); !errors.Is(err, io.ErrUnexpectedEOF) {\n\t\tt.Fatalf(\"truncated stream: %v\", err)\n\t}\n\n\tbigEndian := append([]byte(nil), valid.Bytes()...)\n\tbinary.BigEndian.PutUint32(bigEndian[4:], binary.LittleEndian.Uint32(bigEndian[4:]))\n\tbinary.BigEndian.PutUint32(bigEndian[8:], pcapngByteOrderMagic)",
        "lineStart": 1,
        "lineEnd": 150,
        "totalLines": 167,
        "truncated": true
      }
    },
    "time": {
      "start": 1793523487789,
      "end": 1793523487795
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196549436001IfKSTpUsqTxf6X",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196547cf3001gxJqoFK10D4pNC",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 43599,
    "input": 2707,
    "output": 51,
    "reasoning": 649,
    "cache": {
      "read": 40192,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196547cf3001gxJqoFK10D4pNC",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523481843,
    "completed": 1793523487803
  },
  "parentID": "msg_1965436e6001620KypTRi1ley5",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 43599,
    "input": 2707,
    "output": 51,
    "reasoning": 649,
    "cache": {
      "read": 40192,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 62
step-start
{
  "type": "step-start",
  "id": "prt_196549a9f00153PK2myeTtgYcS",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196549448001WpxHDY5Re1V0HR"
}
Reasoning
Everything checks out. All diff regions (1–7018) and key head files are covered. Test coverage is strong across capture, cmd, core, c9s, and smoke/robot suites.

Now finalize. Findings assessment:

Candidate findings considered across the review:
1. Audit Failed/Denied error returned even when `c.stopping` — speculative (depends on external clabwire behavior); put in coverage notes, not a finding. Actually, let me reconsider: is there a concrete trigger? When stopping, `handleAudit` returns an error → `run` returns error → `Capture` returns error. If clabwire ever emits `Failed` on stdin close, the "context ended is not an error" contract breaks. But this is unverified external behavior; and even if clabwire did, reporting a real failure is defensible. Coverage note.
2. `held`/`emitted` unbounded during ≤10s overlap at very high rates — bounded by overlap duration × packet rate; ≤10s × e.g. 1M pps would be significant, but realistic trigger is narrow; also snap length caps memory per packet. P4 at best. Hmm, is it actionable? `held` is bounded by `capture.out` backpressure? Let me think: held packets are packets from `next` before `active` ends — they come through the events channel (buf 256) and get appended to `c.held`. There's no bound. With a 10s overlap and heavy traffic (e.g., 1M pps × 256 KiB snap... realistically IPFIX-sized), memory could spike. But `emit` for active writes through `c.capture.out` which has backpressure? Let me not overstate. I could report as P4 optional improvement with a concrete note. Actually, I earlier flagged it as potential P4. Let me keep it as a P4 finding: `c.held` accumulates without bound for the ≤10s overlap while `c.active` streams live; at high packet rates this is memory. But is it actionable/desired? The overlap is bounded by `maxCaptureOverlap` (10s) — the held set is bounded by packets stamped in ~10s window. For a 10Gbps line-rate capture with full snap length that could be ~GBs. It's a legit P4 observation. Hmm, but do I have evidence that emit path has backpressure that would also bound it? c.capture.out.Written exists; output has limit logic. If PacketLimit set, once limit reached, emit returns stop → chain returns. Without limit, no backpressure. I'll include as P4.

Wait — but one root-cause rule: one finding per root cause. This one is real: `c.held` and `c.emitted` grow unbounded between `startNext` and the switch. During the overlap, packets from `next` are appended to `c.held` until `active` ends (up to overlap). At very high rates this can be large. P4 (realistic but extreme trigger; bounded in time).

Is it actually true that during overlap held grows? handlePacket for next segment: packets are held until active ends. Yes (line 933 loop drains). So between startNext and switch, `c.held` accumulates all of next's packets. Bounded by overlap (~10s) × rate. OK, P4.

3. Anything else? During my earlier reads (per summary) the analyses concluded the code is largely correct. I haven't identified P1-P3 defects with confidence. Let me do a couple more quick verifications on things that might be real defects:

a) `cmd/capture.go` — check `RunE` error handling and `-w -` behavior, and whether interrupts (second Ctrl+C) produce exit(1) truncating the pcap file. Contract: SIGINT ends capture with exit 0 and valid file. cmd/context.go FinishOnCancel: first signal cancels, second exits(1). Fine.

b) Check `capture/local.go` snapshot length validation with `--snap-length` bounds 64..1048576 documented; default 0 → 256KiB. Verified in output.go ValidateRequest per summary.

c) One thing worth double-checking: in `runReorder` test helper and `Reorder.Flush` — fine.

d) `packetKey` truncates InterfaceID to 16 bits — fine for small interface counts (P4-ish, but not worth flagging; Karpathy rules: not actionable).

e) The smoke test `33-capture.robot` "Capture to stdout stops at the packet limit" uses `sudo ${runtime} exec` with `sleep 1 &&` — fine.

f) Schema check: no topology schema changes needed (no new topology keys; capture is a runtime/CLI feature). `tests/01-smoke/33-capture.clab.yml` includes `$schema` reference — fine.

g) Docs: `docs/cmd/capture.md` comprehensive; mkdocs.yml nav entry added; wireshark.md cross-link added; clabernetes/runtime.md updated. Good.

h) One potential correctness item worth verifying: in `run` (chain), when `ctx` ends (done branch), `c.stop(timer)` closes stdin of active and next; then events continue to be processed. If the *next* segment (not yet started) ends with an error event while `c.stopping`, line 758 suppresses it. But the follow-up that already started and then reports `Failed` audit → error. Same audit case. OK.

i) `handle` when `event.done` and `event.err != nil && c.stopping` → swallowed, falls to `if segment != c.active return nil` → if segment is active → `switchSegments` → active done → `c.active.done` true → return true, nil (stop). Good.

So final findings: one P4 (held/emitted memory bound during segment overlap). Maybe also consider whether to include anything else from prior candidate list... The summary said "Remaining candidate defects identified (see Important Details)" — the list was: audit error while stopping (speculative), held/emitted growth (P4), packetKey 16-bit truncation (fine). I'll report the P4 and put the audit behavior in coverage notes.

Actually, let me reconsider the P4 more carefully to give a precise location. Let me find where held is appended in handlePacket. Let me grep quickly.
All diff regions (lines 1–7018) are now covered and the key head files, tests, and docs have been read. Let me pin down the exact location of the one remaining finding candidate before finalizing.
grep · completed

Input

{
  "path": "/source/head/labruntime/clabernetes/capture.go",
  "pattern": "c\\.held = append|held\\b.*=|startNext|overlap"
}

Output

Found 23 matches
/source/head/labruntime/clabernetes/capture.go:
  Line 452: // one starts before the current one ends, and the stream switches at a cut in the overlap. See

  Line 453: // captureChain for how packets of the overlap are kept once.

  Line 502: 	run.overlap = min(maxCaptureOverlap, run.segment/3)

  Line 503: 	run.window = min(maxCaptureCutWindow, run.overlap/4)

  Line 509: 			req.Duration+run.overlap+captureEndGrace)

  Line 541: 	overlap  time.Duration

  Line 588: // Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both

  Line 591: // cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by

  Line 667: 				c.startNext(segmentsCtx)

  Line 731: 	return max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)

  Line 734: func (c *captureChain) startNext(ctx context.Context) {

  Line 737: 	c.held = nil

  Line 821: // setCut places the cut in the middle of the overlap of the active and the next segment, both

  Line 824: 	overlapStart := c.next.started

  Line 825: 	overlapEnd := c.active.plannedEnd()

  Line 826: 	if overlapEnd.Sub(overlapStart) < 2*c.capture.window {

  Line 827: 		// the overlap is too short to match packets around a cut: the switch is reported as a

  Line 832: 	c.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()

  Line 864: 		c.held = append(c.held, packet)

  Line 889: 		c.next, c.held, c.emitted, c.cut = nil, nil, nil, 0

  Line 902: 			Reason: "the follow-up capture did not overlap the previous one",

  Line 918: 		c.next, c.held, c.emitted, c.cut = nil, nil, nil, 0

  Line 952: 	c.held, c.emitted, c.cut = nil, nil, 0
Tool metadata
{
  "type": "tool",
  "id": "prt_19654c125001Sc0Q3CiX1y0XUu",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196549448001WpxHDY5Re1V0HR",
  "callID": "call_9a53ffb2430c48c6a4db1c50",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/labruntime/clabernetes/capture.go",
      "pattern": "c\\.held = append|held\\b.*=|startNext|overlap"
    },
    "output": "Found 23 matches\n/source/head/labruntime/clabernetes/capture.go:\n  Line 452: // one starts before the current one ends, and the stream switches at a cut in the overlap. See\n\n  Line 453: // captureChain for how packets of the overlap are kept once.\n\n  Line 502: \trun.overlap = min(maxCaptureOverlap, run.segment/3)\n\n  Line 503: \trun.window = min(maxCaptureCutWindow, run.overlap/4)\n\n  Line 509: \t\t\treq.Duration+run.overlap+captureEndGrace)\n\n  Line 541: \toverlap  time.Duration\n\n  Line 588: // Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both\n\n  Line 591: // cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by\n\n  Line 667: \t\t\t\tc.startNext(segmentsCtx)\n\n  Line 731: \treturn max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)\n\n  Line 734: func (c *captureChain) startNext(ctx context.Context) {\n\n  Line 737: \tc.held = nil\n\n  Line 821: // setCut places the cut in the middle of the overlap of the active and the next segment, both\n\n  Line 824: \toverlapStart := c.next.started\n\n  Line 825: \toverlapEnd := c.active.plannedEnd()\n\n  Line 826: \tif overlapEnd.Sub(overlapStart) < 2*c.capture.window {\n\n  Line 827: \t\t// the overlap is too short to match packets around a cut: the switch is reported as a\n\n  Line 832: \tc.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()\n\n  Line 864: \t\tc.held = append(c.held, packet)\n\n  Line 889: \t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n\n  Line 902: \t\t\tReason: \"the follow-up capture did not overlap the previous one\",\n\n  Line 918: \t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n\n  Line 952: \tc.held, c.emitted, c.cut = nil, nil, 0\n",
    "title": "c\\.held = append|held\\b.*=|startNext|overlap",
    "metadata": {
      "matches": 23,
      "truncated": false
    },
    "time": {
      "start": 1793523499306,
      "end": 1793523499317
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19654c137001y9nrR20eNOJjJx",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_196549448001WpxHDY5Re1V0HR",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 48305,
    "input": 3343,
    "output": 85,
    "reasoning": 1357,
    "cache": {
      "read": 43520,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196549448001WpxHDY5Re1V0HR",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523487816,
    "completed": 1793523499322
  },
  "parentID": "msg_1965436e6001620KypTRi1ley5",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 48305,
    "input": 3343,
    "output": 85,
    "reasoning": 1357,
    "cache": {
      "read": 43520,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 63
step-start
{
  "type": "step-start",
  "id": "prt_19654c909001jptW3dj6qPKQU2",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19654c1490017C72SZCgq1bWsE"
}
Reasoning
Confirmed: line 864 appends to `c.held` without any cap; the overlap is `min(maxCaptureOverlap, segment/3)` (≤10s). During the overlap, all of `next`'s packets accumulate in `c.held` until `active` ends and `switchSegments` drains them. At high packet rates with a large snap length this is bounded only by 10s × rate × snaplen — potentially large, though temporally bounded. Also `c.emitted` holds one entry per distinct packet content written by active since next started (bounded by rate in that span too).

That's a legitimate P4 (optional improvement — e.g., cap held backlog or note the bound). Given the ponytail rules (YAGNI), maybe this is over-engineering to flag. It is a real, explainable memory characteristic; P4 with a suggestion to either cap the held buffer or document the bound. I'll include it as P4.

Coverage notes:
- Snapshot read-only; no tests executed; review is source-only. Test files reviewed for coverage, not run.
- Full diff (7018 lines, 37 paths) and all new head files reviewed; no remaining unread regions.
- Unresolved uncertainty: whether clabwire emits a `Failed` audit record when its stdin closes during a stop; if it does, `handleAudit` (capture.go:799-800) would surface an error despite the "context ended is not an error" contract (runtime.go PacketCapturer doc). Left in coverage notes as unverifiable external behavior.
- `packetKey` truncates InterfaceID to 16 bits — safe at current scale, noted as accepted tradeoff.
- No topology schema changes required; capture is CLI/runtime API, not a schema-domain change.

Now write final Markdown review + JSON.

Permalink roots:
head: https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/
base: https://github.com/srl-labs/containerlab/blob/00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4/

Finding: P4 held/emitted growth — location head/labruntime/clabernetes/capture.go lines 860-870 (append) — let me use 855-870 as range. Actually line 864 is `c.held = append(...)`. Use start 855 end 870.

Summary table: one finding P4. Plus coverage notes with the audit uncertainty.
# PR Review: Packet capture (capture command, capture package, c9s clabwire integration)

## Review Summary

This PR adds a `containerlab capture` command with a new self-contained `capture` package (pcapng codec, timestamp-order reorder buffer, local afpacket capture), wires it into `core.CLab`, `cmd`, and the c9s runtime (chained clabwire segments with content-based dedup at the switch), plus unit tests, a Go cluster integration test, two smoke/robot suites, and docs. I traced the full diff (all 7018 lines), the head implementations, and the test suites.

Overall this is a high-quality, well-tested change. The control flow I traced holds up: `Output.Emit` limit handling is correct; `Reorder` ordering/deadlock behavior is sound; the local capture drain-on-end logic only writes packets stamped before the end; the c9s chain state machine (start/dedupe/switch/stop) is coherent and heavily covered by `fakeClabwire` tests; stdout purity for `-w -` is guaranteed by `log.SetOutput(os.Stderr)` in `cmd/root.go`; docs, `mkdocs.yml` nav, and CI (tshark install, `"33*.robot"` glob) are all updated consistently. No topology schema change is needed (the feature is CLI/runtime API, not a topology schema domain).

I found one optional improvement; the remaining uncertainty is recorded in the coverage notes.

## Findings

| Priority | Count | Summary |
|---|---|---|
| P0 | 0 | — |
| P1 | 0 | — |
| P2 | 0 | — |
| P3 | 0 | — |
| P4 | 1 | Unbounded `held`/`emitted` backlog during c9s segment overlap |

### P4 — `captureChain.held` and `emitted` grow without a cap during the segment overlap

**Location:** [labruntime/clabernetes/capture.go L855-L870](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/labruntime/clabernetes/capture.go#L855-L870) (append to `c.held` at line 864; reset in `switchSegments` at [L932-L952](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/labruntime/clabernetes/capture.go#L932-L952))

**Problem:** During the chaining overlap (at most `maxCaptureOverlap` = 10 s, per `run.overlap = min(maxCaptureOverlap, run.segment/3)` at [L502](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/labruntime/clabernetes/capture.go#L502)), every packet delivered by the follow-up segment is appended to `c.held` until the active segment ends, and every packet the active segment writes goes into `c.emitted` as a content key. Neither slice/map has a size cap or backpressure tied to the consumer.

**Trigger:** A chained c9s capture (duration > 1 h, or `CLAB_C9S_CAPTURE_SEGMENT` shorter) on a link with high packet rate. The memory footprint is temporally bounded (≈ overlap × packet rate × min(snap length, frame size)), but at line-rate traffic with the default 256 KiB snap length it can reach hundreds of MB to GBs of transient memory in the containerlab process before `switchSegments` drains it.

**Impact:** Transient memory spike on a long-running capture of a busy link. No data loss or deadlock — the drain loop at [L932-L952](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/labruntime/clabernetes/capture.go#L932-L952) releases everything, and the same pattern exists for `Reorder`'s window (bounded by timestamp, not count). This is an optional hardening item, not a correctness defect.

**Suggestion:** If maintainers want a hard bound, cap `c.held` (for example, drop-to-gap beyond a byte budget, which would surface as a `CaptureGap`) or shrink the effective overlap under observed rate. Otherwise, a one-line comment noting the overlap-bound memory characteristic would prevent future surprise. Either way this can wait; do not block the merge on it.

## Coverage Notes

- **Execution limitation:** this is a read-only source snapshot; no tests, builds, or formatters were run. All conclusions are from source inspection. The Go unit tests (`capture/*_test.go`, `cmd/capture_test.go`, `core/capture_test.go`), the cluster integration test (`core/labruntime_cluster_test.go` with `TestC9sClusterCapture`), the `fakeClabwire` harness (`labruntime/clabernetes/capture_test.go`), the smoke suite (`tests/01-smoke/33-capture.robot` + summary script), and the c9s robot additions (`tests/14-clabernetes/01-linux-lifecycle.robot`, `clabwire-captures.sh`) were reviewed for coverage and look comprehensive: ordering, dedup, gaps, stdin-close stop, unsupported clabwire version, RBAC denial, and node restart reattach are all covered.
- **Unresolved uncertainty (not a finding):** `handleAudit` at [capture.go L799-L800](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/labruntime/clabernetes/capture.go#L799-L800) returns a `captureAuditError` for `Denied`/`Failed` regardless of `c.stopping`. If a clabwire build ever reported `Failed` *as a consequence of* stdin-close during a Ctrl+C stop, the `PacketCapturer.Capture` contract ("the context ended … is not an error", documented at [labruntime/runtime.go L452-L459](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/labruntime/runtime.go#L452-L459)) would surface an error on a clean exit. Whether clabwire does so cannot be verified from this snapshot (it is an external service); the fake in tests does not. Flagging in case the clabwire contract should guarantee `Succeeded` on stdin-close stop.
- `packetKey` truncates `InterfaceID` to 16 bits for hashing ([capture.go L973-L982](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/labruntime/clabernetes/capture.go#L973-L982)); safe at realistic interface counts, accepted tradeoff.
- `setCut`'s zero-cut branch is effectively unreachable in production because `window = min(500ms, overlap/4)` always satisfies `2*window < overlap`; it is a defensive path, consistent with the "overlap too short" gap reporting.

```json
{
  "version": 1,
  "findings": [
    {
      "priority": "P4",
      "title": "`captureChain.held`/`emitted` grow without a cap during the c9s segment overlap",
      "location": {
        "revision": "head",
        "path": "labruntime/clabernetes/capture.go",
        "start": 855,
        "end": 870
      },
      "problem": "During the chaining overlap, every packet of the follow-up segment is appended to `c.held` (line 864) and every packet the active segment writes adds an entry to `c.emitted`, with no size cap or consumer backpressure; they are only released when `switchSegments` runs after the active segment ends.",
      "trigger": "A chained c9s capture (duration over one hour, or `CLAB_C9S_CAPTURE_SEGMENT` set) on a link with a high packet rate; the overlap is at most `maxCaptureOverlap` (10 seconds, set at line 502 as `min(maxCaptureOverlap, run.segment/3)`).",
      "impact": "Transient memory in the containerlab process bounded only by overlap duration times packet rate times snap length; at line rate with the default 256 KiB snap length this can reach large sizes before draining. No data loss or deadlock: the drain loop at lines 932-952 releases everything. This is an optional hardening item, not a correctness defect.",
      "suggestion": "Either cap `c.held` (for example, exceed a byte budget and report it as a `CaptureGap`) or reduce the effective overlap under observed rate; at minimum add a comment documenting the overlap-bound memory characteristic. Do not block the merge on this."
    }
  ],
  "coverage": {
    "complete": true,
    "notes": [
      "The full diff (7018 lines, 37 changed paths) was traversed, including all regions previously unread (6076-6357 and 6475-7018), plus the head implementations, unit tests (capture, cmd, core), the fakeClabwire c9s test harness, the cluster integration test, both robot suites, docs, mkdocs.yml, and the CI workflow changes.",
      "This is a read-only snapshot review: no tests, builds, or formatters were executed; all conclusions are from source inspection.",
      "Unresolved uncertainty: `handleAudit` (labruntime/clabernetes/capture.go lines 799-800) returns a `captureAuditError` for `Denied`/`Failed` even when `c.stopping` is set. If an external clabwire build reported `Failed` as a consequence of stdin-close during a Ctrl+C stop, the `PacketCapturer.Capture` contract documented in labruntime/runtime.go (context ended is not an error) would surface an error on a clean exit. Whether clabwire does this cannot be verified from the snapshot; the test fake does not. Raised as a coverage note rather than a finding.",
      "`packetKey` truncates `InterfaceID` to 16 bits for content hashing (capture.go lines 973-982); safe at realistic interface counts, recorded as an accepted tradeoff.",
      "`setCut`'s zero-cut branch is effectively unreachable in production because `window = min(maxCaptureCutWindow, overlap/4)` always satisfies `2*window < overlap`; it is a defensive path consistent with the 'overlap too short' gap reporting.",
      "No topology schema changes are required: the feature is a CLI and runtime API addition, outside the clab.schema.json domain, and the new smoke topology references the existing schema."
    ]
  }
}
```
step-finish
{
  "type": "step-finish",
  "id": "prt_19655024a00150SF0ApaGpH9MY",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "messageID": "msg_19654c1490017C72SZCgq1bWsE",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 51789,
    "input": 711,
    "output": 2399,
    "reasoning": 551,
    "cache": {
      "read": 48128,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19654c1490017C72SZCgq1bWsE",
  "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
  "time": {
    "created": 1793523499337,
    "completed": 1793523515983
  },
  "parentID": "msg_1965436e6001620KypTRi1ley5",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-RDQspZ",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 51789,
    "input": 711,
    "output": 2399,
    "reasoning": 551,
    "cache": {
      "read": 48128,
      "write": 0
    }
  },
  "finish": "stop"
}