{
  "version": 1,
  "repository": "srl-labs/containerlab",
  "head": "657b1700664a99c5e12c60b4cfd179eb11889bae",
  "updatedAt": "2026-11-01T08:58:36.101Z",
  "state": "completed",
  "info": {
    "id": "ses_e69af794bffepNbEhVAv4WOoCS",
    "title": "ToFaRev review",
    "slug": "misty-circuit",
    "projectID": "global",
    "directory": "/tmp/tofarev-review-RDQspZ",
    "path": "tmp/tofarev-review-RDQspZ",
    "summary": {
      "additions": 0,
      "deletions": 0,
      "files": 0
    },
    "cost": 0,
    "tokens": {
      "input": 640589,
      "output": 13397,
      "reasoning": 17443,
      "cache": {
        "read": 1894720,
        "write": 0
      }
    },
    "agent": "tofarev",
    "model": {
      "id": "zai-org/GLM-5.3-Flash",
      "providerID": "tofarev",
      "variant": "default"
    },
    "version": "1.19.3",
    "time": {
      "created": 1793523222196,
      "updated": 1793523516007
    }
  },
  "messages": [
    {
      "info": {
        "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"
        }
      },
      "parts": [
        {
          "type": "text",
          "id": "prt_196508bc60016n5kzExosK09YJ",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196508bbe001tLsHPkKW57hw60",
          "text": "Review the read-only PR snapshot at /source.\nRead 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.\nHead: 657b1700664a99c5e12c60b4cfd179eb11889bae. Comparison base: 00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4. Target base: 00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4.\nGitHub permalink roots: head=https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/; base=https://github.com/srl-labs/containerlab/blob/00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4/.\nSnapshot incomplete: false. The full inventory and omission details are in manifest.json; consult it when needed. "
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196509271001vDxLvDj7w3DTb6",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196508dfc001Wl9eZDy77pkKXg"
        },
        {
          "type": "reasoning",
          "id": "prt_196509275001q7Tb79bhU71DCB",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196508dfc001Wl9eZDy77pkKXg",
          "text": "Let me start by exploring the source directory structure and reading standards.json and diff.txt.",
          "time": {
            "start": 1793523225205,
            "end": 1793523225307
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196509758001Oi6fuAMhq4bDYk",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196509323001BDtPyZbpQXpNCn"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196509c0a001xJqlZjqh8KBPj0",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965097c9001saIYtHzqO7p3aW"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19650a8000013ubzqzLivXBjEA",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196509cac001qwe5hzZrXtg7xQ"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19650b2ad001y2LI1XaMOpP5IJ",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19650a855001ooGiCUj8bm23MA"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19650be2d001kXVIYjg6EPUaeo",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19650b315001ndmMoYOP5TaOov"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19650ca460014LGH6kgJV9DwwX",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19650be85001Eha5NBjsp4KX8c"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
        }
      },
      "parts": [
        {
          "type": "compaction",
          "id": "prt_19650ca9f001ldxkWnALzGGr2C",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19650ca9e001IiM7d0o0iQV8Vc",
          "auto": true,
          "overflow": false,
          "tail_start_id": "msg_19650be85001Eha5NBjsp4KX8c"
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19650ced0001VEwWcmIG7H7ogG",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19650caae001bNbVQhE16Qm2EW"
        },
        {
          "type": "reasoning",
          "id": "prt_19650ced2001dkazxOskqxKGrC",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19650caae001bNbVQhE16Qm2EW",
          "text": "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.\n\nHead: 657b1700664a99c5e12c60b4cfd179eb11889bae, base: 00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4.",
          "time": {
            "start": 1793523240658,
            "end": 1793523241314
          }
        },
        {
          "type": "text",
          "id": "prt_19650d1650018PhOs9VvcKV39V",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19650caae001bNbVQhE16Qm2EW",
          "text": "## Objective\n- 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.\n\n## Important Details\n- Head commit: `657b1700664a99c5e12c60b4cfd179eb11889bae`; comparison base and target base: `00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4`.\n- GitHub permalink roots: head=`https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/`; base=`https://github.com/srl-labs/containerlab/blob/00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4/`.\n- Snapshot incomplete: false; full inventory/omission details are in `/source/manifest.json` (consult when needed).\n- Source-only review is acceptable without executing tests; limitation must be disclosed in the final result.\n- Use read offsets for truncated outputs; group independent tool calls; use glob/grep for surrounding code.\n- `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).\n- Direct `read` of `/source` directory itself is denied by permission rules; read individual files under `/source/*` instead.\n- 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.\n\n## Work State\n### Completed\n- Read `/source/standards.json` (lists the two rule files).\n- Read `/source/standards/karpathy-guidelines.mdc` and `/source/standards/ponytail.mdc` (behavioral standards for the review).\n- 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`.\n- 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).\n- 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).\n\n### Active\n- Reading through `diff.txt` progressively via offsets; diff.txt is large (~4800+ lines) and more changed files remain unreviewed.\n- 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`.\n- After diff review: examine head/base files for callers, tests, docs, and schema impact per changed path.\n\n### Blocked\n- Diff output truncation requires sequential offset reads; large diff not yet fully traversed.\n- No changes to code are possible (read-only snapshot review); tests cannot be executed — must be disclosed in final result.\n\n## Next Move\n1. 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.\n2. 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.\n\n## Relevant Files\n- `/source/standards.json` — maps rule files to apply (karpathy-guidelines, ponytail).\n- `/source/standards/karpathy-guidelines.mdc` — review standard: surgical changes, simplicity.\n- `/source/standards/ponytail.mdc` — review standard: YAGNI, reuse, shortest diff.\n- `/source/diff.txt` — full PR diff; large, needs offset-based sequential reading.\n- `/source/manifest.json` — full inventory and omission details for the snapshot.\n- `/source/capture/local.go` — new capture implementation file (review target).\n- `/source/core/test_data/capture.clab.yml` — new test topology for capture feature.\n- `/source/docs/cmd/capture.md` — new docs for `capture` command.\n- `/source/.github/workflows/clabernetes-tests.yml` — adds tshark install step.\n- `/source/.github/workflows/smoke-tests.yml` — adds `33*.robot` test glob.",
          "time": {
            "start": 1793523241317,
            "end": 1793523247244
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
        }
      },
      "parts": [
        {
          "type": "text",
          "id": "prt_19650e89b001KqUefmAyuw2XG5",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19650e899001051OTPpm7MOch6",
          "text": "Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.",
          "synthetic": true,
          "time": {
            "start": 1793523247259,
            "end": 1793523247259
          },
          "metadata": {
            "compaction_continue": true
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19650efd7001XnUvq9cd0HnVqy",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19650e8a200111L08HO3uUnqfB"
        },
        {
          "type": "reasoning",
          "id": "prt_19650efd9001mT77S1Y1pzQxij",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19650e8a200111L08HO3uUnqfB",
          "text": "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.\n\nNow 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.",
          "time": {
            "start": 1793523249113,
            "end": 1793523251157
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_1965102640015UcjN1Ud9tzaRh",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19650f8770016P9cVjb21SKWei"
        },
        {
          "type": "reasoning",
          "id": "prt_196510266001xVzkdit5ryBEW0",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19650f8770016P9cVjb21SKWei",
          "text": "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.\n\nNow 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.\n\nGiven 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.",
          "time": {
            "start": 1793523253862,
            "end": 1793523255859
          }
        },
        {
          "type": "text",
          "id": "prt_196510a35001DmWNniNDr2zM9k",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19650f8770016P9cVjb21SKWei",
          "text": "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.",
          "time": {
            "start": 1793523255861,
            "end": 1793523256360
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_1965113510018g53CW8w6hHHuQ",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196510c3a001TWXRc4E0bury6D"
        },
        {
          "type": "reasoning",
          "id": "prt_196511354001WXUWD2NgxUm4cd",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196510c3a001TWXRc4E0bury6D",
          "text": "The files may be organized differently. Let me list the snapshot directory contents.",
          "time": {
            "start": 1793523258196,
            "end": 1793523258455
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196511f55001joHw3UBL1uuRNU",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196511473001Mcyul0Xt2XB0L4"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_1965126e5001idIaKvEjIZJhQl",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196511fd2001AsYcbxyXFxM3HK"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196512d7d001W8O2RkiSu7KY7l",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965127650017wFkuC8x5Fl7Gc"
        },
        {
          "type": "reasoning",
          "id": "prt_196512d800014P0xpHiwsVKcEK",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965127650017wFkuC8x5Fl7Gc",
          "text": "Notable observations so far:\n\n1. `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.\n\n2. `localReader.run`: on ctx done, drain; but note when `r.out.Emit` returns `!more` (packet limit reached), reader returns without drain — fine.\n\n3. `Output.Emit`: increments `written` before push; if `reorder.Push` fails, count already added. Minor.\n\n4. `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.\n\n5. `Reorder.writeDue` holds: computes min timestamp among holds; packets with Timestamp > limit wait. OK.\n\n6. `Output.Close` calls cancelRun then waits, then Flush — but Flush writes remaining packets ignoring holds (flushes all). Good.\n\n7. 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.\n\n8. `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.\n\n9. In `drain`, `info.Timestamp.After(end)` returns, dropping packets stamped after end — reasonable.\n\n10. capture/local.go reopen: after ctx done reports gap with To zero. OK.\n\nPotential bug: In `localCapture.run`, when `NewOutput` fails, closes sources and returns — but the `captureCtx` cancel timers are deferred, fine.\n\nPotential 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.\n\n11. 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.\n\nAlso `if binary.BigEndian.Uint32(magic) == pcapngByteOrderMagic` — big-endian section detection. OK.\n\n12. 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.\n\n13. `pcapngBlock` — total = 12+len(body). Block = 4 type + 4 length + body + 4 total. Good.\n\n14. appendPCAPNGOption padding: appends value then padding of len(value) — correct.\n\n15. `WritePacket` timestamp: `uint64(packet.Timestamp)` — if Timestamp negative (pre-1970), wraps. nolint noted. Minor.\n\n16. Reorder.Run wait computation: `next.Sub(q.now())` could be negative? It computes max(..., time.Millisecond). OK.\n\n17. `resetTimer` — standard.\n\nNow, 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.",
          "time": {
            "start": 1793523264896,
            "end": 1793523271989
          }
        },
        {
          "type": "text",
          "id": "prt_19651493800194LotE3QkHdxIc",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965127650017wFkuC8x5Fl7Gc",
          "text": "The `capture` package looks well-structured. Now let me review the command layer and core integration.",
          "time": {
            "start": 1793523271992,
            "end": 1793523272199
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_1965152aa001BrOSpRqnuOmCRf",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196514a21001Ayu8dXKBiaV3GA"
        },
        {
          "type": "reasoning",
          "id": "prt_1965152ac001LvvT7urmwg47Ki",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196514a21001Ayu8dXKBiaV3GA",
          "text": "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.",
          "time": {
            "start": 1793523274412,
            "end": 1793523274595
          }
        },
        {
          "type": "text",
          "id": "prt_196515364001YyRXTUvIyojI89",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196514a21001Ayu8dXKBiaV3GA",
          "text": "Now the largest new file — the c9s runtime capture implementation.",
          "time": {
            "start": 1793523274596,
            "end": 1793523274722
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196515d9b001ndYhMbWblOja6a",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965153f5001Rc1pht8HI7IZpm"
        },
        {
          "type": "reasoning",
          "id": "prt_196515d9e001YPxfCpym6c7qwJ",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965153f5001Rc1pht8HI7IZpm",
          "text": "This is a very intricate piece of code. Let me note potential issues:\n\n1. `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.\n\n2. 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).\n\n3. `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.\n\n4. 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.\n\nBut 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.\n\n5. `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.\n\nBut: `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.\n\n6. 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.\n\nWait — 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.\n\n7. `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.\n\nActually, 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.\n\n8. `c.emitted` map keyed by fnv64 hash of interface+data — used only while next exists. Cleared at startNext and at switch. Fine.\n\n9. 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.\n\nBut 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.\n\nHmm, 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.\n\n10. 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.\n\n11. `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.\n\n12. 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.\n\n13. Reorder window interplay: the c9s capture uses window default 250ms. Held packets emitted after active ends — with hold at T-W. OK.\n\n14. `readSegment` returns nil on ErrUnexpectedEOF — treats a cut mid-block as clean end. OK by design.\n\n15. `auditLineWriter.line` — json.Unmarshal on every line; audit only when schemaVersion matches. OK.\n\n16. `stderrSuffix` fine.\n\nNow `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.",
          "time": {
            "start": 1793523277214,
            "end": 1793523292105
          }
        },
        {
          "type": "text",
          "id": "prt_1965197cc0011jRR9jO01Rd448",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965153f5001Rc1pht8HI7IZpm",
          "text": "This is a complex chaining implementation. Let me examine the remaining c9s files and the diff hunks for the modified `cmd/` files.",
          "time": {
            "start": 1793523292108,
            "end": 1793523292350
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19651a117001i99VMIDSUum1Q2",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965198db001prIIeKml33BCWn"
        },
        {
          "type": "reasoning",
          "id": "prt_19651a119001NcKEX5c5U3bw4C",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965198db001prIIeKml33BCWn",
          "text": "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.\n\nWait — 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.\n\nAlso 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.\n\nMore significant: `captureFn` sets `o.Global.FinishOnCancel.Store(true)` AFTER checking targets and creating `c`, but before creating the file. Then arms. Fine.\n\nLet me now read the head cmd/context.go fully to understand the signal handling flow.",
          "time": {
            "start": 1793523294489,
            "end": 1793523296536
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19651b146001TI2Ujyz82BCHuR",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19651a93c00145gf5iHrMk55rq"
        },
        {
          "type": "reasoning",
          "id": "prt_19651b149001j07GIjgjuc8auU",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19651a93c00145gf5iHrMk55rq",
          "text": "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.\n\nHowever, there's a subtle issue: the second signal during \"stopping\" exits with code 1 — reasonable.\n\nAnother 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.\n\nBut 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.\n\nNow 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.\n\nI'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.",
          "time": {
            "start": 1793523298633,
            "end": 1793523301312
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19651c4b5001gkQMs6vlaZBBEx",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19651bc1e001AQP4o3Kun6N68z"
        },
        {
          "type": "reasoning",
          "id": "prt_19651c4b7001R9sVfiGFvPVtpP",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19651bc1e001AQP4o3Kun6N68z",
          "text": "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).\n\nAlso 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.\n\nNow let me focus on hunting for real defects. Key areas to check:\n\n1. **`Output.Emit` packet limit counting vs. written**: limit counts handed-to-stream, fine.\n\n2. **Reorder `Push` when `q.err != nil`**: returns q.err. OK.\n\n3. **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.\n\n4. **`writeDue` holds scan**: iterates `q.holds` map each call — fine, few holds.\n\n5. **`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.\n\nBut 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.\n\nBut wait: what about a packet written directly when window <= 0 — cursor never advances, irrelevant.\n\nAnother 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.\n\n6. **`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.\n\n7. **Potential goroutine leak in `Output`**: runDone closed on cancelRun; reorder.Run returns on ctx done. OK.\n\n8. **`Reorder.Push` after `Flush`**: In c9s Capture, after out.Close()... chains already done. OK.\n\n9. **`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.\n\n10. **`localReader.run` ctx check**: after `stop()` (packet limit reached), Emit returns false → return without drain. Fine.\n\n11. **CaptureLocal openAll**: if `l.open` returns fewer/more sources... only with test stubs. Fine.\n\n12. **`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.\n\n13. **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.\n\n14. **pcapng `Writer.WritePacket`**: body cap `20+len+3` — padding at most 3. Good.\n\n15. **`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.\n\n16. **`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.\n\n17. **`Reader` interface dedup between segments**: interfaces reset on new section. Packets reference ID per current section. OK.\n\n18. **`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.\n\n19. **`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.\n\nHowever — 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.\n\n20. **`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.\n\nBut note: after `c.next = nil; resetTimer(timer, time.Second)` — the timer that fired was the next-start timer; fine.\n\nHmm, 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.\n\n21. **`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.\n\n22. **`captureChain.run` — `c.active = c.start(segmentsCtx, ...)`; timer := NewTimer(c.nextStartIn())`. nextStartIn marks final if deadline near. OK.\n\n23. **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.\n\n24. **`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.\n\n25. **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.\n\n26. **`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.\n\nBut careful: the watcher goroutine `select { case <-execDone: return; case <-segmentCtx.Done(): }` — after segmentCtx done, closes stdin, waits grace, cancels exec. Fine.\n\n27. **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.\n\nBut 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.\n\n28. **`CaptureLocal` with `wg.Go`** — Go 1.25 `sync.WaitGroup.Go`. Fine.\n\n29. **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.\n\n30. **`captureFn` file Sync but no explicit Close error handling** — defer file.Close; error ignored. Minor.\n\n31. **`printCaptureInterfaces` table**: fine.\n\n32. **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.\n\nNow 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.",
          "time": {
            "start": 1793523303607,
            "end": 1793523323618
          }
        },
        {
          "type": "text",
          "id": "prt_1965212e5001lnL9DtogH44mMw",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19651bc1e001AQP4o3Kun6N68z",
          "text": "Let me check a few supporting pieces: `commandSkipsRoot`, log output destination (purity of stdout pcapng), and the docs that were added.",
          "time": {
            "start": 1793523323621,
            "end": 1793523324070
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
        }
      },
      "parts": [
        {
          "type": "compaction",
          "id": "prt_1965214bd001KGLCCFEDlx60mc",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965214bc001V4qO87RkNunl5l",
          "auto": true,
          "overflow": false,
          "tail_start_id": "msg_1965198db001prIIeKml33BCWn"
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196521b4b001STAM5ft73BrjG5",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965214cd001OiEB6AGoktsxhx"
        },
        {
          "type": "reasoning",
          "id": "prt_196521b4c001LSEPnoGeZVQts5",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965214cd001OiEB6AGoktsxhx",
          "text": "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.",
          "time": {
            "start": 1793523325772,
            "end": 1793523326070
          }
        },
        {
          "type": "text",
          "id": "prt_196521c78001kiKkebdLHXMJ0m",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965214cd001OiEB6AGoktsxhx",
          "text": "## Objective\n- 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.\n\n## Important Details\n- Head commit: `657b1700664a99c5e12c60b4cfd179eb11889bae`; base/mergeBase: `00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4`.\n- Permalink roots: head=`https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/`; base=`https://github.com/srl-labs/containerlab/blob/00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4/`.\n- Snapshot incomplete: false; full inventory in `/source/manifest.json` (head at `657b170...`, confirmed).\n- Source-only review; cannot execute tests — disclose limitation in final result.\n- Standards: `.cursor/rules/karpathy-guidelines.mdc` (surgical changes, simplicity) and `.cursor/rules/ponytail.mdc` (YAGNI, reuse, shortest diff).\n- 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/...`.\n- 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.\n- 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+).\n- 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.\n\n## Work State\n### Completed\n- Read `standards.json` and both referenced rule files.\n- Full diff.txt traversed via overlapping offset reads (1, 1702, 3478, 4780, 6410) covering all 7018 lines; grep enumerated 37 `diff --git` headers.\n- Read `manifest.json` (head/base/mergeBase hashes, ~20 of 37 changed paths visible before truncation).\n- 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).\n- 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).\n- Initial defect-scan notes collected (see Active).\n\n### Active\n- 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.\n- 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).\n- 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.\n\n### Blocked\n- Cannot execute tests (read-only snapshot) — must be disclosed in final result.\n- 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).\n\n## Next Move\n1. 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.\n2. 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.\n\n## Relevant Files\n- `/source/standards.json`, `/source/standards/karpathy-guidelines.mdc`, `/source/standards/ponytail.mdc` — review standards (read).\n- `/source/diff.txt` — full 7018-line PR diff (fully traversed).\n- `/source/manifest.json` — full 37-path inventory (partially shown; head hash `657b1700664a99c5e12c60b4cfd179eb11889bae`).\n- `/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).\n- `/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).\n- `/source/head/core/{capture.go, capture_local.go, capture_test.go, labruntime_cluster_test.go}` — core integration (capture.go, capture_local.go read).\n- `/source/head/labruntime/clabernetes/{capture.go, capture_interfaces.go, clabernetes.go, runtime.go}` — c9s capture implementation (capture.go + capture_interfaces.go partially read).\n- `/source/core/test_data/capture.clab.yml` — new test topology (2× nokia_srlinux + alpine:3, 4 links incl. host + mgmt-net).\n- `/source/docs/cmd/capture.md`, `/source/docs/cmd/inspect/interfaces.md`, `/source/docs/manual/clabernetes/runtime.md`, `/source/docs/manual/wireshark.md` — documentation changes.\n- `/source/.github/workflows/{clabernetes-tests.yml, smoke-tests.yml}` — CI changes (tshark install; `\"33*.robot\"` glob).",
          "time": {
            "start": 1793523326072,
            "end": 1793523336526
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
        }
      },
      "parts": [
        {
          "type": "text",
          "id": "prt_19652455d0014R32HMDcpR72ne",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19652455c001bTBRfavhAuXSsP",
          "text": "Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.",
          "synthetic": true,
          "time": {
            "start": 1793523336541,
            "end": 1793523336541
          },
          "metadata": {
            "compaction_continue": true
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196524d1e001QYuBFiifSUGAdH",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196524566001amBVNvfJ9FiMxm"
        },
        {
          "type": "reasoning",
          "id": "prt_196524d20001V3M9OX8i6hIoDk",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196524566001amBVNvfJ9FiMxm",
          "text": "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.\n\nLet 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.\n\nAlso 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.\n\nLet me proceed reading the remaining diff.",
          "time": {
            "start": 1793523338528,
            "end": 1793523340038
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196525aa3001brz9AfFT54QZyV",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19652532d001VBllmmBAf5BXgY"
        },
        {
          "type": "reasoning",
          "id": "prt_196525aa6001oFa0TiYR6K2vUE",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19652532d001VBllmmBAf5BXgY",
          "text": "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).",
          "time": {
            "start": 1793523341990,
            "end": 1793523342231
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19652664d001VwXsdfGlj92Won",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196525bfc001zLWkm9tE0OVysO"
        },
        {
          "type": "reasoning",
          "id": "prt_19652664f001e4jk0dTNnFzus5",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196525bfc001zLWkm9tE0OVysO",
          "text": "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.",
          "time": {
            "start": 1793523344975,
            "end": 1793523345470
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19652702f001w3o0oFIkyqfb16",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196526863001CoB4SCcGn05S5b"
        },
        {
          "type": "reasoning",
          "id": "prt_196527032001kYX5EScSo1N6UK",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196526863001CoB4SCcGn05S5b",
          "text": "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`.\n\nLet me read /source/head/labruntime/clabernetes/capture.go in a few chunks.",
          "time": {
            "start": 1793523347506,
            "end": 1793523348652
          }
        },
        {
          "type": "text",
          "id": "prt_1965274ae001T0HixDwhUo1O19",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196526863001CoB4SCcGn05S5b",
          "text": "Now let me read the full c9s capture implementation to verify the chain state machine and merge logic.",
          "time": {
            "start": 1793523348654,
            "end": 1793523348956
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196527d9e001D6Vd2x7IZ67CqM",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965275f0001jy0JtWtHQA7Mlj"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19652851a001KJ5c6Wo158LK6K",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196527e22001cp2k6GtKVWT0Tb"
        },
        {
          "type": "reasoning",
          "id": "prt_19652851b001BL0zkCM6gn0Ya4",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196527e22001cp2k6GtKVWT0Tb",
          "text": "I've now seen the full capture.go. Let me analyze key issues:\n\n1. **`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.\n\n2. **`switchSegments` retry case**: `c.next.started.IsZero()` and error → retry. But what if the retry exhausts (retries == captureStartRetries) — returns error \"failed\". OK.\n\n3. **Potential issue in `handlePacket` for `c.next` when stopping**: held appended; but if next is the segment that ended while stopping — handled.\n\n4. **`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.\n\n5. **`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.\n\n6. **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.\n\n7. **`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.\n\n8. **`r.connect(ctx, req.Identity)`** — reassigns r; fine.\n\n9. **`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.\n\n10. **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.\n\n11. **`readSegment` interface order check**: clabwire writes IDBs in requested order — contract. OK.\n\n12. **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.\n\nWait, 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.\n\nOne issue: `drain()` runs `c.wg.Wait()` and consumes events concurrently; the exec goroutine sends `done` — handled by drain (dropped). Good.\n\n13. **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.\n\nBut 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.\n\nAnother: 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.\n\n14. **`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.\n\n15. **`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.\n\n16. **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.\n\nLet 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.",
          "time": {
            "start": 1793523352859,
            "end": 1793523372421
          }
        },
        {
          "type": "text",
          "id": "prt_19652d1870016Hs8CA2aaabP1j",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196527e22001cp2k6GtKVWT0Tb",
          "text": "Now let me re-verify the `capture` package internals (`output.go`, `reorder.go`, `local.go`, `pcapng.go`) against the c9s usage.",
          "time": {
            "start": 1793523372423,
            "end": 1793523372739
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19652dadc001rDPHLemyEURPn0",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19652d2df0012coQNQ8TBiw02W"
        },
        {
          "type": "reasoning",
          "id": "prt_19652dade001uC4rY8oNf1Tfig",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19652d2df0012coQNQ8TBiw02W",
          "text": "Analysis of reorder.go / output.go:\n\n**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.\n\n**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.\n\n**Issue C — `Reorder.Flush` doesn't wake; fine since called after Run ended.**\n\nBut 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.\n\n**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.\n\n**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.\n\n**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.\n\n**Issue G — packet with Timestamp == 0?** c9s packets always have timestamps from clabwire. Local packets from afpacket have kernel timestamps. OK.\n\n**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.\n\n**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.\n\n**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.\n\n**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).\n\nNow the local capture — let me re-read local.go fully to verify the drain/openAll concerns and the ctx semantics.",
          "time": {
            "start": 1793523374814,
            "end": 1793523381670
          }
        },
        {
          "type": "text",
          "id": "prt_19652f5a8001w20zs9IH1iEyQz",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19652d2df0012coQNQ8TBiw02W",
          "text": "Now let me re-read `capture/local.go` in full to verify the reader lifecycle, drain logic, and error paths.",
          "time": {
            "start": 1793523381672,
            "end": 1793523381898
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_1965304ee001GNu17N0hNvTk7s",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19652f69d001xsI2OBDEJpPxOR"
        },
        {
          "type": "reasoning",
          "id": "prt_1965304f0001bMV2u5zEXe1GTa",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19652f69d001xsI2OBDEJpPxOR",
          "text": "Verification of local.go concerns:\n\n1. **`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.\n\n2. **`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.\n\nNote: `drain` is called with `time.Now()` — but the ctx check happens at loop top; packets read before... fine.\n\n3. **`drain` after packet limit stop**: Emit returns !more → return. OK.\n\n4. **`run` after `reopen` returns nil (ctx done)**: returns. OK.\n\n5. **`reopen` blocks on timer only — checks ctx.Done only every reopenInterval (200ms). Acceptable.\n\n6. **`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.\n\n7. **CaptureInfo.Timestamp**: afpacket ZeroCopyReadPacketData returns the kernel timestamp. Good.\n\n8. **`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.\n\nNow pcapng.go — let me verify the Reader.Next clean-EOF concern and Writer. Let me read pcapng.go fully.",
          "time": {
            "start": 1793523385584,
            "end": 1793523388717
          }
        },
        {
          "type": "text",
          "id": "prt_196531141001Vpx74e7GuTp5Ta",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19652f69d001xsI2OBDEJpPxOR",
          "text": "Now the pcapng codec:",
          "time": {
            "start": 1793523388737,
            "end": 1793523388813
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196531993001goJWooJ1f4MRK7",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965311a7001k6hdWxAPXEGpKv"
        },
        {
          "type": "reasoning",
          "id": "prt_1965319950011iqRyqwAqbAovN",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965311a7001k6hdWxAPXEGpKv",
          "text": "pcapng.go verification:\n\n- **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.\n\n- **`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.\n\n- **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.\n\n- **Writer.WriteHeader section**: major version 1, minor 0. `section = make([]byte, 16)` — but SHB body must be 4 (magic) + 2 + 2 + 8 = 16. Yes.\n\n- **`WritePacket` negative timestamp**: nolint'd; packets have positive timestamps in practice.\n\n- **`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.\n\n- **EPB timestamp**: high 32 bits at body[4:8] (timestamp_high), low at body[8:12]. Correct per pcapng.\n\nNow `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.\n\nNow 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.\n\nLet me check `LocateNode` ordering guarantee — search in clabernetes runtime for LocateNode.",
          "time": {
            "start": 1793523390870,
            "end": 1793523395066
          }
        },
        {
          "type": "text",
          "id": "prt_1965329fc001Ea0PNEncsjGCxA",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965311a7001k6hdWxAPXEGpKv",
          "text": "The codec looks sound. Let me verify the `LocateNode` ordering assumption in `resolveCaptureTargets` and check the c9s `capture_interfaces.go` and tests.",
          "time": {
            "start": 1793523395068,
            "end": 1793523395517
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19653344c001eXBlwN87qHPgEF",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196532bd60015VpspkwCnYfZ04"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196533c3e001Es0bHwVuSSB3Dg",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965334ca001giLxtUX7G0lyvT"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_1965344210019wibHgr81cJajP",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196533ca2001DbAdTJgSwNGYuM"
        },
        {
          "type": "reasoning",
          "id": "prt_196534423001PeXC8H40ieB6ls",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196533ca2001DbAdTJgSwNGYuM",
          "text": "`LocateNode` preserves the request order for named nodes. Good — `resolveCaptureTargets`'s `byRequest` mapping is safe.\n\nAlso note: in `resolveCaptureTargets`, if a node's pod is empty (not running), `listed` would fail via `listCaptureInterfaces` (which errors if pod empty). Good.\n\nBut wait: in `resolveCaptureTargets`, `locations` includes all requested nodes; `listCaptureInterfaces(ctx, req.Name, locations)` errors if any node has no pod. Good.\n\nOne 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.\n\nNow, `CaptureInterfaces` in c9s — one potential mismatch: in `resolveCaptureTargets`, if `req.Nodes` filter in NodeRequest... fine.\n\nNext: check the remaining pieces I haven't verified:\n1. `capture_interfaces.go` (c9s InspectInterfaces implementation).\n2. `capture_test.go` for c9s (1050 lines) — skim.\n3. capture package tests (local_test, pcapng_test, reorder_test) — skim.\n4. `cmd/inspect_interfaces.go` head — the lab-runtime branch calls `printContainerInterfaces` — check that function exists and handles format.\n5. `streamPodExec` in capture_interfaces.go.\n6. `.github/workflows` changes (seen at diff 1–36).\n7. `mkdocs.yml` change (nav entry for capture docs).\n\nAlso verify `commandSkipsRoot` in root.go — what does it return for c9s?",
          "time": {
            "start": 1793523401763,
            "end": 1793523404050
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196536126001krtZ1vtL1tv4bW",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196534de3001UGgBavNO6PpMwe"
        },
        {
          "type": "reasoning",
          "id": "prt_196536128001N5TkIQKRDl0ldA",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196534de3001UGgBavNO6PpMwe",
          "text": "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.",
          "time": {
            "start": 1793523409192,
            "end": 1793523409812
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196536d46001W59OEF6T1rzIo9",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965363cb001Jt6GT07TwpYY9F"
        },
        {
          "type": "reasoning",
          "id": "prt_196536d48001M7GomodmWWt4mL",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965363cb001Jt6GT07TwpYY9F",
          "text": "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.",
          "time": {
            "start": 1793523412296,
            "end": 1793523412642
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_1965377da001yjxJEvE1r121PF",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196536ec3001DYhMjZBrLlaEIj"
        },
        {
          "type": "reasoning",
          "id": "prt_1965377dc001Vz0hJ04P8qNRyB",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196536ec3001DYhMjZBrLlaEIj",
          "text": "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).",
          "time": {
            "start": 1793523415004,
            "end": 1793523415534
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
        }
      },
      "parts": [
        {
          "type": "compaction",
          "id": "prt_196537a0b001R92mMVVaplpkHa",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196537a0a0019rqr0jWnsviNLW",
          "auto": true,
          "overflow": false,
          "tail_start_id": "msg_196534de3001UGgBavNO6PpMwe"
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_1965382d2001cz7FLq6F54T9RZ",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196537a1e00101MSdjyJmQE5e5"
        },
        {
          "type": "reasoning",
          "id": "prt_1965382d6001M5ClF32145LyWZ",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196537a1e00101MSdjyJmQE5e5",
          "text": "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.\n\nRefined analysis notes:\n- setCut cut==0 duplication case effectively unreachable with computed overlap/window values (window = min(500ms, overlap/4) → 2*window < overlap always) — defensive only.\n- 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).\n- Reorder/Output analysis: backpressure chain OK, Emit counts before limit check correctly, late packet cursor benign.\n- pcapng codec verified sound (SHB min body 16, EPB timestamp layout correct, padding handled).\n- Local.go: openAll count assumption safe, drain deadline logic OK, reopen 200ms.\n- `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).\n- 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.",
          "time": {
            "start": 1793523417814,
            "end": 1793523420267
          }
        },
        {
          "type": "text",
          "id": "prt_196538c6d001h5AL2qIhdJ0saK",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196537a1e00101MSdjyJmQE5e5",
          "text": "## Objective\n- 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).\n\n## Important Details\n- Head commit: `657b1700664a99c5e12c60b4cfd179eb11889bae`; base/mergeBase: `00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4`.\n- Permalink roots: head=`https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/`; base=`https://github.com/srl-labs/containerlab/blob/00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4/`.\n- Snapshot incomplete: false; full inventory in `/source/manifest.json`. Source-only review; cannot execute tests — disclose limitation in final result.\n- Standards: `.cursor/rules/karpathy-guidelines.mdc` (surgical changes, simplicity) and `.cursor/rules/ponytail.mdc` (YAGNI, reuse, shortest diff).\n- **Head files live under `/source/head/...`** (not `/source/capture/...`). Direct read of `/source` dir itself denied; read individual files.\n- 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.\n- 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.\n- 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.\n- `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.\n\n## Work State\n### Completed\n- 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.\n- 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`.\n- Verified analysis conclusions:\n  - `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.\n  - 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).\n  - 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).\n  - `packetKey` truncates InterfaceID to 16 bits (fnv over `id[0]`/`id[1]`) — fine for small interface counts.\n  - c9s `Capture` wraps `captureCtx` with `WithTimeout(req.Duration+overlap+captureEndGrace)`; `defer stop()` cancels original ctx which propagates — OK.\n\n### Active\n- 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.\n- 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.\n\n### Blocked\n- Cannot execute tests (read-only snapshot) — must be disclosed in final result.\n- manifest.json truncated in tool output; remaining changed paths must be enumerated from diff headers (lines 3900–7018 mapping incomplete).\n\n## Next Move\n1. 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).\n2. 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.\n\n## Relevant Files\n- `/source/standards.json`, `/source/standards/karpathy-guidelines.mdc`, `/source/standards/ponytail.mdc` — review standards (read).\n- `/source/diff.txt` — full 7018-line PR diff (traversed; targeted re-reads done; 3900–7018 path mapping incomplete).\n- `/source/manifest.json` — inventory (head hash `657b1700664a99c5e12c60b4cfd179eb11889bae`).\n- `/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).\n- `/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).\n- `/source/head/core/{capture.go, capture_local.go, capture_test.go, labruntime_cluster_test.go}` — core integration (capture.go, capture_local.go verified).\n- `/source/head/labruntime/clabernetes/{capture.go, capture_interfaces.go, access.go, clabernetes.go}` — c9s capture implementation (read & verified); `capture_test.go` not yet read.\n- `/source/head/labruntime/runtime.go` — PacketCapturer/CaptureRequest/NodeRequest interface additions (diff tail 6410–6474 seen).\n- `/source/cmd/root.go:163` — `log.SetOutput(os.Stderr)` (stdout purity for `-w -`).\n- `/source/core/test_data/capture.clab.yml` — new test topology (seen in diff 3490–3510).\n- `/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).\n- `/source/.github/workflows/{clabernetes-tests.yml, smoke-tests.yml}` — CI changes (partially seen).\n- `/source/mkdocs.yml` — nav entry for capture docs (not yet checked).",
          "time": {
            "start": 1793523420269,
            "end": 1793523429661
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
        }
      },
      "parts": [
        {
          "type": "text",
          "id": "prt_19653b12b001wQhhAULjP6bb42",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653b129001cj4QAfxRVtxTFM",
          "text": "Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.",
          "synthetic": true,
          "time": {
            "start": 1793523429675,
            "end": 1793523429675
          },
          "metadata": {
            "compaction_continue": true
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19653b8f3001Ajdj8ireQVK0ex",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653b137001Ukh1qsEi71RUoZ"
        },
        {
          "type": "reasoning",
          "id": "prt_19653b8f5001HtgNZP5MlLgT9L",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653b137001Ukh1qsEi71RUoZ",
          "text": "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.",
          "time": {
            "start": 1793523431669,
            "end": 1793523432632
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19653c45d0011k16q1v1tBwpto",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653bcde001mt4UfEP9687WC6"
        },
        {
          "type": "reasoning",
          "id": "prt_19653c460001P0cG7lqjXvz0Rt",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653bcde001mt4UfEP9687WC6",
          "text": "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.",
          "time": {
            "start": 1793523434592,
            "end": 1793523435179
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19653cdf90017a3bT5TFVdiey8",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653c6d2001LmjgFru5WWr30l"
        },
        {
          "type": "reasoning",
          "id": "prt_19653cdfb001dkvb9NnfQ7VEel",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653c6d2001LmjgFru5WWr30l",
          "text": "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.\n\nOne thing to check: `o.Capture.Write` default \"-\" but in captureFn: `if o.Capture.Write != \"\" && o.Capture.Write != \"-\"` — fine.\n\nAlso `parseCaptureTargets` allows `srl1:e1-1,ethernet-1/2` — good.\n\nNow let me continue reading the diff: 2766-3490 (core/capture.go, capture_local.go, capture_test.go, labruntime_cluster_test.go, test_data).",
          "time": {
            "start": 1793523437051,
            "end": 1793523438048
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19653d92c001k7MtqkKOPekgfe",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653d207001b0N0fJzxFIZN83"
        },
        {
          "type": "reasoning",
          "id": "prt_19653d92e001QSO60tBMOMRam1",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653d207001b0N0fJzxFIZN83",
          "text": "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.",
          "time": {
            "start": 1793523439918,
            "end": 1793523440313
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19653e29d001Q1NMpiqQNMEhIL",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653dadf001LqnYSf5AYwEOrw"
        },
        {
          "type": "reasoning",
          "id": "prt_19653e2a0001Jq3jc7SeNKFejU",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653dadf001LqnYSf5AYwEOrw",
          "text": "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.",
          "time": {
            "start": 1793523442336,
            "end": 1793523442715
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19653ecfb0015VYKo2vJbgMOtO",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653e445001J6rvVNoreYHJnq"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19653f622001EOcX9VYZ1hTET1",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653ed5a001JQ2uENCIAXE6MW"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19653ff25001h3Lgeare2p9Vw4",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653f6770018dflKPj7YadEFZ"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
        }
      },
      "parts": [
        {
          "type": "compaction",
          "id": "prt_19653ff7f001N1mHakc00nFvsN",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653ff7e001McEi21advBqMyE",
          "auto": true,
          "overflow": false,
          "tail_start_id": "msg_19653f6770018dflKPj7YadEFZ"
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_1965405d7001tWmzs4f1059FK5",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653ff8f001spWXGnVQFRdXem"
        },
        {
          "type": "reasoning",
          "id": "prt_1965405d9001Ar5LF55ASEZgn9",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653ff8f001spWXGnVQFRdXem",
          "text": "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.\n\nUpdate 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.\n\nKeep 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.\n\nUpdate Next Move accordingly.",
          "time": {
            "start": 1793523451353,
            "end": 1793523453925
          }
        },
        {
          "type": "text",
          "id": "prt_196540fe7001t1UjKwgjhWWdWg",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19653ff8f001spWXGnVQFRdXem",
          "text": "## Objective\n- 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).\n\n## Important Details\n- Head commit: `657b1700664a99c5e12c60b4cfd179eb11889bae`; base/mergeBase: `00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4`.\n- Permalink roots: head=`https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/`; base=`https://github.com/srl-labs/containerlab/blob/00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4/`.\n- Snapshot incomplete: false; full inventory in `/source/manifest.json`. Source-only review; cannot execute tests — disclose limitation in final result.\n- Standards: `.cursor/rules/karpathy-guidelines.mdc` (surgical changes, simplicity) and `.cursor/rules/ponytail.mdc` (YAGNI, reuse, shortest diff).\n- **Head files live under `/source/head/...`** (not `/source/capture/...`). Direct read of `/source` dir itself denied; read individual files.\n- 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.\n- 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.\n- 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.\n- `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.\n- 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\".\n- Verified analysis conclusions:\n  - `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.\n  - 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).\n  - Potential P4: `held`/`emitted` in captureChain grow unbounded during the ≤10s overlap at very high packet rates.\n  - `packetKey` truncates InterfaceID to 16 bits (fnv over `id[0]`/`id[1]`) — fine for small interface counts.\n  - c9s `Capture` wraps `captureCtx` with `WithTimeout(req.Duration+overlap+captureEndGrace)`; `defer stop()` cancels original ctx which propagates — OK.\n  - 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.\n- 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\".\n- 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`.\n\n## Work State\n### Completed\n- 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.\n- 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`.\n- Workflow changes verified in diff: clabernetes-tests.yml installs tshark (apt-get) before robot tests; smoke-tests.yml adds `\"33*.robot\"` glob.\n- Remaining candidate defects identified (see Important Details) with reasoning.\n\n### Active\n- 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`).\n- 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.\n- 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.\n\n### Blocked\n- Cannot execute tests (read-only snapshot) — must be disclosed in final result.\n- manifest.json truncated in tool output; remaining changed paths must be enumerated from diff headers (lines 6475–7018 mapping incomplete).\n\n## Next Move\n1. 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.).\n2. 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.\n\n## Relevant Files\n- `/source/standards.json`, `/source/standards/karpathy-guidelines.mdc`, `/source/standards/ponytail.mdc` — review standards (read).\n- `/source/diff.txt` — full 7018-line PR diff (traversed except ~6076–6357 and 6475–7018).\n- `/source/manifest.json` — inventory (head hash `657b1700664a99c5e12c60b4cfd179eb11889bae`).\n- `/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).\n- `/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).\n- `/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).\n- `/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).\n- `/source/head/labruntime/runtime.go` — PacketCapturer/CaptureRequest/NodeRequest interface additions (diff tail 6410–6474 seen).\n- `/source/cmd/root.go:163` — `log.SetOutput(os.Stderr)` (stdout purity for `-w -`).\n- `/source/core/test_data/capture.clab.yml` — new test topology (seen in diff 3490–3510).\n- `/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).\n- `/source/.github/workflows/{clabernetes-tests.yml, smoke-tests.yml}` — CI changes verified (tshark install; `\"33*.robot\"`).\n- `/source/mkdocs.yml` — nav entry for capture docs (not yet checked).",
          "time": {
            "start": 1793523453927,
            "end": 1793523463896
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
        }
      },
      "parts": [
        {
          "type": "text",
          "id": "prt_1965436e7001EUrLpQz7acfuVA",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965436e6001620KypTRi1ley5",
          "text": "Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.",
          "synthetic": true,
          "time": {
            "start": 1793523463911,
            "end": 1793523463911
          },
          "metadata": {
            "compaction_continue": true
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196543e42001wFaTuHzWrf1zH8",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965436f30019ghHotYqzFR5jH"
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_1965445880013QdweB6rSoaD5f",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196543ecb001f61Y3euhR027F8"
        },
        {
          "type": "reasoning",
          "id": "prt_19654458a001pbMf4zNOAnDLtv",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196543ecb001f61Y3euhR027F8",
          "text": "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.\n\nLet me read capture tests in parallel.",
          "time": {
            "start": 1793523467658,
            "end": 1793523468210
          }
        },
        {
          "type": "text",
          "id": "prt_1965447b4001w6jfS1zdd2RB1S",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196543ecb001f61Y3euhR027F8",
          "text": "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.",
          "time": {
            "start": 1793523468212,
            "end": 1793523468621
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196545037001HGGvwhfItTn1Ee",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196544960001jOFhFncIdgj9Pi"
        },
        {
          "type": "reasoning",
          "id": "prt_196545039001oh4iCI46Sp4pzZ",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196544960001jOFhFncIdgj9Pi",
          "text": "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.",
          "time": {
            "start": 1793523470393,
            "end": 1793523470863
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196545d77001f6IyJMCVemWuoO",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196545269001hgrDfxsl6X7Rxi"
        },
        {
          "type": "reasoning",
          "id": "prt_196545d79001FoEc7fvq44gG1O",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196545269001hgrDfxsl6X7Rxi",
          "text": "Test coverage is thorough. Let me do the final remaining checks:\n\n1. 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).\n\n2. 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).\n\nLet me quickly verify a couple of things I flagged:\n\nCandidate findings so far:\n1. 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.\n2. 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.)\n3. Maybe check cmd/options.go diff for anything.\n4. Check pcapng_test.go / reorder_test.go briefly for coverage notes.\n\nAlso I should verify the captureAudit error-when-stopping claim by reading the relevant code. Let me grep for captureAuditError and the stopping check.",
          "time": {
            "start": 1793523473785,
            "end": 1793523476557
          }
        },
        {
          "type": "text",
          "id": "prt_19654684f0017BifztvrDY3clU",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196545269001hgrDfxsl6X7Rxi",
          "text": "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.",
          "time": {
            "start": 1793523476559,
            "end": 1793523476938
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196546fe4001NnpoJbZmSpCY1S",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965469dd001abKSHVc0hGYfzy"
        },
        {
          "type": "reasoning",
          "id": "prt_196546fe6001QIeJ0ML12RC5S4",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965469dd001abKSHVc0hGYfzy",
          "text": "Let me look at the audit handling code around lines 758-810 in capture.go to confirm the stopping/audit-error behavior.",
          "time": {
            "start": 1793523478502,
            "end": 1793523478766
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19654785c001lf2gmbS0DLTLp9",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965471090010I0XCBAsYtLHBt"
        },
        {
          "type": "reasoning",
          "id": "prt_19654785d0014S2vKNEB2eXm9E",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_1965471090010I0XCBAsYtLHBt",
          "text": "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).\n\nLet me read lines 600-700 and 940-1000 to see error flow at stop.",
          "time": {
            "start": 1793523480669,
            "end": 1793523481716
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19654838e001c7VCDo5GvER70H",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196547cf3001gxJqoFK10D4pNC"
        },
        {
          "type": "reasoning",
          "id": "prt_196548390001GVOb7OKl1eRJlC",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196547cf3001gxJqoFK10D4pNC",
          "text": "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)\".\n\nBut 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.\n\nNow let me finish remaining checks:\n1. `capture/output.go` written/Written atomic — fine.\n2. 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.\n3. Remaining unread diff regions: none — 1 to 7018 fully covered now.\n\nRemaining 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).\n\nLet 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.\n\nOne more candidate: in the smoke test 33-capture.robot \"The capture reattaches...\" test uses `containerlab restart -t ${topo} --node l2` — fine.\n\nLet me quickly check pcapng_test.go coverage and the docs/manual/wireshark.md diff hunk (between 3879 and 3900).",
          "time": {
            "start": 1793523483536,
            "end": 1793523487714
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_196549a9f00153PK2myeTtgYcS",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196549448001WpxHDY5Re1V0HR"
        },
        {
          "type": "reasoning",
          "id": "prt_196549aa2001SFmZVVyFFgGhLT",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196549448001WpxHDY5Re1V0HR",
          "text": "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.\n\nNow finalize. Findings assessment:\n\nCandidate findings considered across the review:\n1. 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.\n2. `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.\n\nWait — 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).\n\nIs 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.\n\n3. 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:\n\na) `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.\n\nb) Check `capture/local.go` snapshot length validation with `--snap-length` bounds 64..1048576 documented; default 0 → 256KiB. Verified in output.go ValidateRequest per summary.\n\nc) One thing worth double-checking: in `runReorder` test helper and `Reorder.Flush` — fine.\n\nd) `packetKey` truncates InterfaceID to 16 bits — fine for small interface counts (P4-ish, but not worth flagging; Karpathy rules: not actionable).\n\ne) The smoke test `33-capture.robot` \"Capture to stdout stops at the packet limit\" uses `sudo ${runtime} exec` with `sleep 1 &&` — fine.\n\nf) 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.\n\ng) Docs: `docs/cmd/capture.md` comprehensive; mkdocs.yml nav entry added; wireshark.md cross-link added; clabernetes/runtime.md updated. Good.\n\nh) 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.\n\ni) `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.\n\nSo 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.\n\nActually, 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.",
          "time": {
            "start": 1793523489442,
            "end": 1793523498819
          }
        },
        {
          "type": "text",
          "id": "prt_19654bf450011IQkj03RBnWn2x",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_196549448001WpxHDY5Re1V0HR",
          "text": "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.",
          "time": {
            "start": 1793523498821,
            "end": 1793523499308
          }
        },
        {
          "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
            }
          }
        },
        {
          "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
            }
          }
        }
      ]
    },
    {
      "info": {
        "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"
      },
      "parts": [
        {
          "type": "step-start",
          "id": "prt_19654c909001jptW3dj6qPKQU2",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19654c1490017C72SZCgq1bWsE"
        },
        {
          "type": "reasoning",
          "id": "prt_19654c90b001nb8hdAkzZGGNwS",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19654c1490017C72SZCgq1bWsE",
          "text": "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).\n\nThat'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.\n\nCoverage notes:\n- Snapshot read-only; no tests executed; review is source-only. Test files reviewed for coverage, not run.\n- Full diff (7018 lines, 37 paths) and all new head files reviewed; no remaining unread regions.\n- 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.\n- `packetKey` truncates InterfaceID to 16 bits — safe at current scale, noted as accepted tradeoff.\n- No topology schema changes required; capture is CLI/runtime API, not a schema-domain change.\n\nNow write final Markdown review + JSON.\n\nPermalink roots:\nhead: https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/\nbase: https://github.com/srl-labs/containerlab/blob/00c0f8f4a551466e9e0e0cc79a3e48d2510adfd4/\n\nFinding: 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.\n\nSummary table: one finding P4. Plus coverage notes with the audit uncertainty.",
          "time": {
            "start": 1793523501323,
            "end": 1793523504846
          }
        },
        {
          "type": "text",
          "id": "prt_19654d6d1001WOMvsqxP5gdIwO",
          "sessionID": "ses_e69af794bffepNbEhVAv4WOoCS",
          "messageID": "msg_19654c1490017C72SZCgq1bWsE",
          "text": "# PR Review: Packet capture (capture command, capture package, c9s clabwire integration)\n\n## Review Summary\n\nThis 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.\n\nOverall 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).\n\nI found one optional improvement; the remaining uncertainty is recorded in the coverage notes.\n\n## Findings\n\n| Priority | Count | Summary |\n|---|---|---|\n| P0 | 0 | — |\n| P1 | 0 | — |\n| P2 | 0 | — |\n| P3 | 0 | — |\n| P4 | 1 | Unbounded `held`/`emitted` backlog during c9s segment overlap |\n\n### P4 — `captureChain.held` and `emitted` grow without a cap during the segment overlap\n\n**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))\n\n**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.\n\n**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.\n\n**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.\n\n**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.\n\n## Coverage Notes\n\n- **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.\n- **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.\n- `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.\n- `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.\n\n```json\n{\n  \"version\": 1,\n  \"findings\": [\n    {\n      \"priority\": \"P4\",\n      \"title\": \"`captureChain.held`/`emitted` grow without a cap during the c9s segment overlap\",\n      \"location\": {\n        \"revision\": \"head\",\n        \"path\": \"labruntime/clabernetes/capture.go\",\n        \"start\": 855,\n        \"end\": 870\n      },\n      \"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.\",\n      \"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)`).\",\n      \"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.\",\n      \"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.\"\n    }\n  ],\n  \"coverage\": {\n    \"complete\": true,\n    \"notes\": [\n      \"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.\",\n      \"This is a read-only snapshot review: no tests, builds, or formatters were executed; all conclusions are from source inspection.\",\n      \"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.\",\n      \"`packetKey` truncates `InterfaceID` to 16 bits for content hashing (capture.go lines 973-982); safe at realistic interface counts, recorded as an accepted tradeoff.\",\n      \"`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.\",\n      \"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.\"\n    ]\n  }\n}\n```",
          "time": {
            "start": 1793523504849,
            "end": 1793523515974
          }
        },
        {
          "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
            }
          }
        }
      ]
    }
  ],
  "report": "# ToFaRev review\n\nReview complete within the supplied scope.\n\nSource inspection only; PR code, tests, and benchmarks were not executed.\n\n| Finding | Location |\n| --- | --- |\n| **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) |\n\n## P4 - `captureChain.held`/`emitted` grow without a cap during the c9s segment overlap\n\n**Location:** [labruntime/clabernetes/capture.go:855-870](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/labruntime/clabernetes/capture.go#L855-L870)\n\n**Problem:** During the chaining overlap, every packet of the follow-up segment is appended to `c.held` &#40;line 864&#41; 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.\n\n**Trigger:** A chained c9s capture &#40;duration over one hour, or `CLAB_C9S_CAPTURE_SEGMENT` set&#41; on a link with a high packet rate; the overlap is at most `maxCaptureOverlap` &#40;10 seconds, set at line 502 as `min(maxCaptureOverlap, run.segment/3)`&#41;.\n\n**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&#58; the drain loop at lines 932-952 releases everything. This is an optional hardening item, not a correctness defect.\n\n**Suggested correction:** Either cap `c.held` &#40;for example, exceed a byte budget and report it as a `CaptureGap`&#41; 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.\n\n\n## Coverage\n\n- The full diff &#40;7018 lines, 37 changed paths&#41; was traversed, including all regions previously unread &#40;6076-6357 and 6475-7018&#41;, plus the head implementations, unit tests &#40;capture, cmd, core&#41;, 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.\n- This is a read-only snapshot review&#58; no tests, builds, or formatters were executed; all conclusions are from source inspection.\n- Unresolved uncertainty&#58; `handleAudit` &#40;[`labruntime/clabernetes/capture.go`](https://github.com/srl-labs/containerlab/blob/657b1700664a99c5e12c60b4cfd179eb11889bae/labruntime/clabernetes/capture.go#L1-L1) lines 799-800&#41; 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) &#40;context ended is not an error&#41; 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.\n- `packetKey` truncates `InterfaceID` to 16 bits for content hashing &#40;`capture.go` lines 973-982&#41;; safe at realistic interface counts, recorded as an accepted tradeoff.\n- `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.\n- 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.\n\n---\nPowered 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>\n\n```json\n{\n  \"version\": 1,\n  \"findings\": [\n    {\n      \"priority\": \"P4\",\n      \"title\": \"`captureChain.held`/`emitted` grow without a cap during the c9s segment overlap\",\n      \"location\": {\n        \"revision\": \"head\",\n        \"path\": \"labruntime/clabernetes/capture.go\",\n        \"start\": 855,\n        \"end\": 870\n      },\n      \"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.\",\n      \"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)`).\",\n      \"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.\",\n      \"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.\"\n    }\n  ],\n  \"coverage\": {\n    \"complete\": true,\n    \"notes\": [\n      \"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.\",\n      \"This is a read-only snapshot review: no tests, builds, or formatters were executed; all conclusions are from source inspection.\",\n      \"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.\",\n      \"`packetKey` truncates `InterfaceID` to 16 bits for content hashing (`capture.go` lines 973-982); safe at realistic interface counts, recorded as an accepted tradeoff.\",\n      \"`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.\",\n      \"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.\"\n    ]\n  }\n}\n```"
}
