ToFaRev sessions

ToFaRev review

srl-labs/containerlab · 1566c3b8e3cb

completed · 48 messages · 63 tool calls

Last snapshot:

Download session JSON · Full transcript

Final review

# ToFaRev review

Review complete within the supplied scope.

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

No supported findings were reported within the reviewed scope.


## Coverage

- No tests or commands were executed; the snapshot is read-only and execution is not permitted. All conclusions come from source inspection of the head/base trees and the full diff.
- All 26 changed paths from `manifest.json` were confirmed and examined; the diff was read in full, including hunks for [`core/events/netlink.go`](https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/core/events/netlink.go#L1-L1), [`core/events/stream.go`](https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/core/events/stream.go#L1-L1), [`core/labruntime.go`](https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/core/labruntime.go#L1-L1), the three docs files, all clabernetes runtime sources, and the robot suite.
- Callers and contracts were traced: `setTopologySourceFile` ([`plan.go`](https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/labruntime/clabernetes/plan.go#L1-L1)), `removeTopologySourceFile` ([`manifests.go`](https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/labruntime/clabernetes/manifests.go#L1-L1), [`primitives.go`](https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/labruntime/clabernetes/primitives.go#L1-L1)), `carryOverNodeTopologyFile` ([`reconcile.go`](https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/labruntime/clabernetes/reconcile.go#L1-L1)), `labNotFoundError` handling in [`container_events.go`](https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/labruntime/clabernetes/container_events.go#L1-L1), `events.go`, and `lifecycle.go`, plus errs/`errCh` channel sizing and nil-channel select patterns in [`stream.go`](https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/core/events/stream.go#L1-L1).
- Candidate issues raised during investigation were each resolved by surrounding code or tests: empty state attributes are dropped by the formatter, errs channels are sized to writer count, the `c9s.run`/`originalNodeName` and `c9s.run`/direct-node-uid contracts match tests and docs, `managementAddress` handles plain-IP and CIDR forms, and the `containerFromLabNode` `NodeType` override matches documented -t behavior.
- Docs were cross-checked against the implementation: inspect interfaces eth0/lo inclusion and their non-capturability, the `containerlab.dev`/topo-file recording and carry-over rules, k8s:// fallbacks, and the health: starting status convention ([`core/labruntime.go`](https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/core/labruntime.go#L1-L1), [`cmd/inspect.go`](https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/cmd/inspect.go#L1-L1), parity test, and the [`runtime.md`](https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/docs/manual/clabernetes/runtime.md#L1-L1) table all agree).
- Test files were read and surveyed for coverage of the changed behavior (tracker transitions, poller suppression and dedup, topology-file recording/carry-over, namespace scoping) but not executed, so test correctness is asserted from reading them rather than from a run.
- No [`clab.schema.json`](https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/schemas/clab.schema.json#L1-L1) change is required: the new annotation lives on c9s CRD resources, which are outside the topology schema's domain; c9s API shapes were referenced only via the existing GVR constants and testdata `OpenAPI` fixtures.

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

```json
{
  "version": 1,
  "findings": [],
  "coverage": {
    "complete": true,
    "notes": [
      "No tests or commands were executed; the snapshot is read-only and execution is not permitted. All conclusions come from source inspection of the head/base trees and the full diff.",
      "All 26 changed paths from `manifest.json` were confirmed and examined; the diff was read in full, including hunks for `core/events/netlink.go`, `core/events/stream.go`, `core/labruntime.go`, the three docs files, all clabernetes runtime sources, and the robot suite.",
      "Callers and contracts were traced: `setTopologySourceFile` (`plan.go`), `removeTopologySourceFile` (`manifests.go`, `primitives.go`), `carryOverNodeTopologyFile` (`reconcile.go`), `labNotFoundError` handling in `container_events.go`, `events.go`, and `lifecycle.go`, plus errs/`errCh` channel sizing and nil-channel select patterns in `stream.go`.",
      "Candidate issues raised during investigation were each resolved by surrounding code or tests: empty state attributes are dropped by the formatter, errs channels are sized to writer count, the `c9s.run`/`originalNodeName` and `c9s.run`/direct-node-uid contracts match tests and docs, `managementAddress` handles plain-IP and CIDR forms, and the `containerFromLabNode` `NodeType` override matches documented -t behavior.",
      "Docs were cross-checked against the implementation: inspect interfaces eth0/lo inclusion and their non-capturability, the `containerlab.dev`/topo-file recording and carry-over rules, k8s:// fallbacks, and the health: starting status convention (`core/labruntime.go`, `cmd/inspect.go`, parity test, and the `runtime.md` table all agree).",
      "Test files were read and surveyed for coverage of the changed behavior (tracker transitions, poller suppression and dedup, topology-file recording/carry-over, namespace scoping) but not executed, so test correctness is asserted from reading them rather than from a run.",
      "No `clab.schema.json` change is required: the new annotation lives on c9s CRD resources, which are outside the topology schema's domain; c9s API shapes were referenced only via the existing GVR constants and testdata `OpenAPI` fixtures."
    ]
  }
}
```
User · 1
Review the read-only PR snapshot at /source.
Read standards.json and its referenced rules, then diff.txt and relevant head/ and base/ files. Track all 26 changed paths from the diff. Complete checks for each changed path and relevant callers, tests, docs, and schema before finalizing. Source-only review can be complete without executing tests; disclose that limitation. Use read offsets for truncated output and group independent tool calls. Use glob/grep for surrounding code. Return the trusted result schema.
Head: 1566c3b8e3cb58c82d238dedbfa3b319249bab0a. Comparison base: b4de5d55cf17262e39325a7e125a6d3cb2c89318. Target base: b4de5d55cf17262e39325a7e125a6d3cb2c89318.
GitHub permalink roots: head=https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/; base=https://github.com/srl-labs/containerlab/blob/b4de5d55cf17262e39325a7e125a6d3cb2c89318/.
Snapshot incomplete: false. The full inventory and omission details are in manifest.json; consult it when needed. 
Message metadata
{
  "role": "user",
  "id": "msg_19674becc001poQpu47cHvtM8V",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525595852
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 2
step-start
{
  "type": "step-start",
  "id": "prt_19674c700001g0UJMsRNhhILkw",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674c172001w09Ra1bf5ktLDN"
}
Reasoning
Let me start by exploring the review environment.
read · error

Input

{
  "filePath": "/source"
}

Output

The user has specified a rule which prevents you from using this specific tool call. Here are some of the relevant rules [{"permission":"*","action":"allow","pattern":"*"},{"permission":"read","pattern":"*","action":"allow"},{"permission":"read","pattern":"*.env","action":"ask"},{"permission":"read","pattern":"*.env.*","action":"ask"},{"permission":"read","pattern":"*.env.example","action":"allow"},{"permission":"*","action":"deny","pattern":"*"},{"permission":"read","pattern":"*","action":"deny"},{"permission":"read","pattern":"source/*","action":"allow"},{"permission":"*","action":"deny","pattern":"*"},{"permission":"read","pattern":"*","action":"deny"},{"permission":"read","pattern":"source/*","action":"allow"}]
Tool metadata
{
  "type": "tool",
  "id": "prt_19674c7470010SbJ7Tg8AHeK2W",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674c172001w09Ra1bf5ktLDN",
  "callID": "call_6fce6948a43e43d2adcd4789",
  "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": 1793525598034,
      "end": 1793525598042
    }
  }
}
read · completed

Input

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

Output

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

(End of file - total 12 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19674c766001vmNqnOZ9TLqmYV",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674c172001w09Ra1bf5ktLDN",
  "callID": "call_aea4b2fde8e549209cbe2a5d",
  "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\": \"b4de5d55cf17262e39325a7e125a6d3cb2c89318\",\n5:     \"file\": \"standards/karpathy-guidelines.mdc\"\n6:   },\n7:   {\n8:     \"path\": \".cursor/rules/ponytail.mdc\",\n9:     \"revision\": \"b4de5d55cf17262e39325a7e125a6d3cb2c89318\",\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\": \"b4de5d55cf17262e39325a7e125a6d3cb2c89318\",\n    \"file\": \"standards/karpathy-guidelines.mdc\"\n  },\n  {\n    \"path\": \".cursor/rules/ponytail.mdc\",\n    \"revision\": \"b4de5d55cf17262e39325a7e125a6d3cb2c89318\",\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\": \"b4de5d55cf17262e39325a7e125a6d3cb2c89318\",\n    \"file\": \"standards/karpathy-guidelines.mdc\"\n  },\n  {\n    \"path\": \".cursor/rules/ponytail.mdc\",\n    \"revision\": \"b4de5d55cf17262e39325a7e125a6d3cb2c89318\",\n    \"file\": \"standards/ponytail.mdc\"\n  }\n]",
        "lineStart": 1,
        "lineEnd": 12,
        "totalLines": 12,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525598060,
      "end": 1793525598085
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19674c78f001x9YO4MvHCGObUJ",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674c172001w09Ra1bf5ktLDN",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 3300,
    "input": 387,
    "output": 23,
    "reasoning": 10,
    "cache": {
      "read": 2880,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19674c172001w09Ra1bf5ktLDN",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525596530,
    "completed": 1793525598103
  },
  "parentID": "msg_19674becc001poQpu47cHvtM8V",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 3300,
    "input": 387,
    "output": 23,
    "reasoning": 10,
    "cache": {
      "read": 2880,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 3
step-start
{
  "type": "step-start",
  "id": "prt_19674cbdf001p5xvd5cWsO8AGQ",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674c79a001gjHUT18UiSAEMW"
}
read · completed

Input

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

Output

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

(End of file - total 75 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19674cc0f001zb96IJGE98bcE5",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674c79a001gjHUT18UiSAEMW",
  "callID": "call_59d72174226c49efa73722af",
  "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": 1793525599253,
      "end": 1793525599291
    }
  }
}
read · completed

Input

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

Output

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

(End of file - total 36 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19674cc51001ELr5y9eJOPwYmQ",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674c79a001gjHUT18UiSAEMW",
  "callID": "call_8bd0d8b108ce4b33a60f0d24",
  "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": 1793525599318,
      "end": 1793525599626
    }
  }
}
read · completed

Input

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

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1: diff --git a/core/events/netlink.go b/core/events/netlink.go
2: index 150b71d..1654a4a 100644
3: --- a/core/events/netlink.go
4: +++ b/core/events/netlink.go
5: @@ -12,10 +12,11 @@ import (
6:  
7:  	"github.com/charmbracelet/log"
8:  	gotc "github.com/florianl/go-tc"
9:  	clabconstants "github.com/srl-labs/containerlab/constants"
10:  	clabcore "github.com/srl-labs/containerlab/core"
11: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
12:  	clablinks "github.com/srl-labs/containerlab/links"
13:  	clabnetem "github.com/srl-labs/containerlab/netem"
14:  	clabruntime "github.com/srl-labs/containerlab/runtime"
15:  	clabutils "github.com/srl-labs/containerlab/utils"
16:  	"github.com/vishvananda/netlink"
17: @@ -642,31 +643,99 @@ func containerLabel(container *clabruntime.GenericContainer) string {
18:  	}
19:  
20:  	return container.Labels[clabconstants.Containerlab]
21:  }
22:  
23: -func interfaceAttributes(
24: -	container *clabruntime.GenericContainer,
25: -	snapshot ifaceSnapshot,
26: -) map[string]string {
27: +// interfaceSnapshotAttributes are the attributes every interface event reports for the
28: +// interface itself.
29: +func interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {
30:  	attributes := map[string]string{
31:  		"ifname": snapshot.Name,
32:  		"index":  strconv.Itoa(snapshot.Index),
33:  		"mtu":    strconv.Itoa(snapshot.MTU),
34:  		"state":  snapshot.OperState,
35:  		"type":   snapshot.Type,
36: -		"origin": "netlink",
37:  	}
38:  
39:  	if snapshot.Alias != "" {
40:  		attributes["alias"] = snapshot.Alias
41:  	}
42:  
43:  	if snapshot.MAC != "" {
44:  		attributes["mac"] = snapshot.MAC
45:  	}
46:  
47: +	return attributes
48: +}
49: +
50: +// interfaceStatsAttributes adds the counters and rates of a stats event.
51: +func interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {
52: +	attributes["rx_bytes"] = strconv.FormatUint(metrics.RxBytes, 10)
53: +	attributes["tx_bytes"] = strconv.FormatUint(metrics.TxBytes, 10)
54: +	attributes["rx_packets"] = strconv.FormatUint(metrics.RxPackets, 10)
55: +	attributes["tx_packets"] = strconv.FormatUint(metrics.TxPackets, 10)
56: +	attributes["rx_bps"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)
57: +	attributes["tx_bps"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)
58: +	attributes["rx_pps"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)
59: +	attributes["tx_pps"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)
60: +	attributes["interval_seconds"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)
61: +}
62: +
63: +// labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those
64: +// of the netlink interface events, for the node the runtime runs. Values the runtime could not
65: +// read (no index or MTU without a shell in the node) are left out rather than reported as 0.
66: +func labRuntimeInterfaceAttributes(
67: +	lab, name string,
68: +	iface *clablabruntime.InterfaceEventData,
69: +) map[string]string {
70: +	attributes := interfaceSnapshotAttributes(ifaceSnapshot{
71: +		Index:     iface.Index,
72: +		Name:      iface.Name,
73: +		Alias:     iface.Alias,
74: +		MTU:       iface.MTU,
75: +		MAC:       iface.MAC,
76: +		OperState: iface.OperState,
77: +		Type:      iface.Type,
78: +	})
79: +	if iface.Index <= 0 {
80: +		delete(attributes, "index")
81: +	}
82: +	if iface.MTU <= 0 {
83: +		delete(attributes, "mtu")
84: +	}
85: +
86: +	if lab != "" {
87: +		attributes["lab"] = lab
88: +	}
89: +	if name != "" {
90: +		attributes["name"] = name
91: +	}
92: +
93: +	if stats := iface.Stats; stats != nil {
94: +		interfaceStatsAttributes(attributes, ifaceStatsMetrics{
95: +			RxBytes:   stats.RxBytes,
96: +			TxBytes:   stats.TxBytes,
97: +			RxPackets: stats.RxPackets,
98: +			TxPackets: stats.TxPackets,
99: +			RxBps:     stats.RxBps,
100: +			TxBps:     stats.TxBps,
101: +			RxPps:     stats.RxPps,
102: +			TxPps:     stats.TxPps,
103: +			Interval:  stats.Interval,
104: +		})
105: +	}
106: +
107: +	return attributes
108: +}
109: +
110: +func interfaceAttributes(
111: +	container *clabruntime.GenericContainer,
112: +	snapshot ifaceSnapshot,
113: +) map[string]string {
114: +	attributes := interfaceSnapshotAttributes(snapshot)
115: +	attributes["origin"] = "netlink"
116: +
117:  	if lab := containerLabel(container); lab != "" {
118:  		attributes["lab"] = lab
119:  	}
120:  
121:  	if name := firstContainerName(container); name != "" {
122: @@ -811,19 +880,11 @@ func (r *netlinkRegistry) emitInterfaceStatsEvent(
123:  	if !r.includeStats || container == nil || !snapshot.HasStats {
124:  		return
125:  	}
126:  
127:  	attributes := interfaceAttributes(container, snapshot)
128: -	attributes["rx_bytes"] = strconv.FormatUint(metrics.RxBytes, 10)
129: -	attributes["tx_bytes"] = strconv.FormatUint(metrics.TxBytes, 10)
130: -	attributes["rx_packets"] = strconv.FormatUint(metrics.RxPackets, 10)
131: -	attributes["tx_packets"] = strconv.FormatUint(metrics.TxPackets, 10)
132: -	attributes["rx_bps"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)
133: -	attributes["tx_bps"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)
134: -	attributes["rx_pps"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)
135: -	attributes["tx_pps"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)
136: -	attributes["interval_seconds"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)
137: +	interfaceStatsAttributes(attributes, metrics)
138:  
139:  	event := aggregatedEvent{
140:  		Timestamp:   metrics.Timestamp,
141:  		Type:        "interface",
142:  		Action:      "stats",
143: diff --git a/core/events/parity_test.go b/core/events/parity_test.go
144: new file mode 100644
145: index 0000000..855365b
146: --- /dev/null
147: +++ b/core/events/parity_test.go
148: @@ -0,0 +1,553 @@
149: +package events
150: +
151: +import (
152: +	"context"
153: +	"os"
154: +	"path/filepath"
155: +	"sort"
156: +	"strings"
157: +	"testing"
158: +	"time"
159: +
160: +	dockerEvents "github.com/docker/docker/api/types/events"
161: +	clabconstants "github.com/srl-labs/containerlab/constants"
162: +	clabcore "github.com/srl-labs/containerlab/core"
163: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
164: +	clabruntime "github.com/srl-labs/containerlab/runtime"
165: +	clabtypes "github.com/srl-labs/containerlab/types"
166: +	clabutils "github.com/srl-labs/containerlab/utils"
167: +)
168: +
169: +// These tests build the events the Docker runtime and the c9s lab runtime report for the same
170: +// node and compare them: every attribute a Docker event carries is in the c9s event, with the
171: +// same meaning, apart from the ones c9s has no equivalent for.
172: +
173: +// dockerOnlyContainerAttributes are the Docker container event attributes c9s has no
174: +// equivalent for: the Docker event scope, the Docker management bridge, and the exit code and
175: +// run time of a container process, which Kubernetes does not keep once the pod is gone.
176: +var dockerOnlyContainerAttributes = map[string]bool{ //nolint:gochecknoglobals
177: +	"scope":                     true,
178: +	clabconstants.NodeMgmtNetBr: true,
179: +	clabconstants.NodeLabDir:    true,
180: +	"exitCode":                  true,
181: +	"execDuration":              true,
182: +}
183: +
184: +const parityTopology = `name: parity
185: +mgmt:
186: +  network: clab
187: +topology:
188: +  nodes:
189: +    client:
190: +      kind: linux
191: +      image: ghcr.io/srl-labs/network-multitool
192: +    srl1:
193: +      kind: nokia_srlinux
194: +      image: ghcr.io/nokia/srlinux:25.10
195: +  links:
196: +    - endpoints: ["client:eth1", "srl1:ethernet-1/1"]
197: +`
198: +
199: +// parityLab loads the topology as a Docker deploy does and returns its labels per node.
200: +func parityLab(t *testing.T) (string, *clabcore.CLab) {
201: +	t.Helper()
202: +
203: +	dir := t.TempDir()
204: +	path := filepath.Join(dir, "parity.clab.yml")
205: +	if err := os.WriteFile(path, []byte(parityTopology), 0o600); err != nil {
206: +		t.Fatal(err)
207: +	}
208: +	t.Setenv("USER", "alice")
209: +	t.Setenv("SUDO_USER", "")
210: +
211: +	c, err := clabcore.NewContainerLab(clabcore.WithTopoPath(path, nil))
212: +	if err != nil {
213: +		t.Fatal(err)
214: +	}
215: +
216: +	return path, c
217: +}
218: +
219: +// fakeDockerRuntime answers the container lookup the events command makes for a Docker event.
220: +type fakeDockerRuntime struct {
221: +	clabruntime.ContainerRuntime
222: +	container clabruntime.GenericContainer
223: +}
224: +
225: +func (f *fakeDockerRuntime) ListContainers(
226: +	context.Context,
227: +	[]*clabtypes.GenericFilter,
228: +) ([]clabruntime.GenericContainer, error) {
229: +	return []clabruntime.GenericContainer{f.container}, nil
230: +}
231: +
232: +// dockerContainer is the container Docker runs for a node.
233: +func dockerContainer(t *testing.T, c *clabcore.CLab, node string) clabruntime.GenericContainer {
234: +	t.Helper()
235: +
236: +	cfg := c.Nodes[node].Config()
237: +	labels := cloneStringMap(cfg.Labels)
238: +	labels[clabconstants.NodeMgmtNetBr] = "br-92bb9fb46cd2"
239: +
240: +	return clabruntime.GenericContainer{
241: +		Names:   []string{cfg.LongName},
242: +		ID:      "57b7763f3b4d97ff0c96b1dab8294b836199628a2d9400549948a963732e185a",
243: +		ShortID: "57b7763f3b4d",
244: +		Image:   cfg.Image,
245: +		State:   "running",
246: +		Status:  "Up 19 seconds",
247: +		Labels:  labels,
248: +		NetworkSettings: clabruntime.GenericMgmtIPs{
249: +			IPv4addr: "172.20.20.2", IPv4pLen: 24, IPv6addr: "3fff:172:20:20::2", IPv6pLen: 64,
250: +		},
251: +		NetworkName: "clab",
252: +		Ports: []*clabtypes.GenericPortBinding{
253: +			{ContainerPort: 22, Protocol: "tcp"}, {ContainerPort: 80, Protocol: "tcp"},
254: +		},
255: +	}
256: +}
257: +
258: +// dockerContainerEvent is a Docker container event as `containerlab events` reports it: the
259: +// Docker message (container labels, image and name as attributes, plus the action's own) through
260: +// the events command's conversion and enrichment.
261: +func dockerContainerEvent(
262: +	t *testing.T,
263: +	container clabruntime.GenericContainer,
264: +	action string,
265: +	extra map[string]string,
266: +) aggregatedEvent {
267: +	t.Helper()
268: +
269: +	attributes := cloneStringMap(container.Labels)
270: +	attributes["image"] = container.Image
271: +	attributes["name"] = container.Names[0]
272: +	for k, v := range extra {
273: +		attributes[k] = v
274: +	}
275: +	data := clabutils.DockerMessageToEventData(dockerEvents.Message{
276: +		Type:     dockerEvents.ContainerEventType,
277: +		Action:   dockerEvents.Action(action),
278: +		Actor:    dockerEvents.Actor{ID: container.ID, Attributes: attributes},
279: +		Scope:    "local",
280: +		TimeNano: time.Now().UnixNano(),
281: +	})
282: +
283: +	return aggregatedEventFromContainerEvent(context.Background(),
284: +		&fakeDockerRuntime{container: container},
285: +		clabruntime.ContainerEvent{
286: +			Timestamp: data.Timestamp, Type: data.Type, Action: data.Action,
287: +			ActorID: data.ActorID, ActorName: data.ActorName, ActorFullID: data.ActorFullID,
288: +			Attributes: data.Attributes,
289: +		})
290: +}
291: +
292: +// c9sNode is the same node as the c9s runtime reports it, deployed from the same file.
293: +func c9sNode(
294: +	c *clabcore.CLab,
295: +	path, node string,
296: +) (*clablabruntime.LabState, clablabruntime.NodeState) {
297: +	cfg := c.Nodes[node].Config()
298: +	state := &clablabruntime.LabState{
299: +		Name: "parity", Namespace: "c9s-parity", Owner: "alice", TopologyPath: path,
300: +		State: "running", Ready: true,
301: +	}
302: +	nodeState := clablabruntime.NodeState{
303: +		Name: node, Kind: cfg.Kind, Image: cfg.Image, State: "ready", Ready: true,
304: +		ContainerState:  clablabruntime.ContainerStateRunning,
305: +		Health:          clablabruntime.ContainerHealthHealthy,
306: +		MgmtIPv4Address: "172.20.20.84/24", MgmtIPv6Address: "3fff:172:20:20::84/64",
307: +		Pod: node + "-88598986c-rbdfq", Container: "node-" + node, NodeUID: "uid-" + node,
308: +		ExposedPorts: []clablabruntime.ExposedPort{
309: +			{
310: +				Port:       22,
311: +				ExposePort: 22,
312: +				Protocol:   "tcp",
313: +			},
314: +			{Port: 80, ExposePort: 80, Protocol: "tcp"},
315: +		},
316: +	}
317: +	state.Nodes = []clablabruntime.NodeState{nodeState}
318: +
319: +	return state, nodeState
320: +}
321: +
322: +// c9sContainerEvent is the event the c9s runtime emits, as `containerlab events` reports it.
323: +func c9sContainerEvent(
324: +	clab *clabcore.CLab,
325: +	state *clablabruntime.LabState,
326: +	node clablabruntime.NodeState,
327: +	action, containerState string,
328: +	extra map[string]string,
329: +) aggregatedEvent {
330: +	key := state.Namespace + "/" + state.Name + "/" + node.Name
331: +	attributes := map[string]string{
332: +		"namespace": state.Namespace, "lab": state.Name, "node": node.Name, "pod": node.Pod,
333: +		"state": containerState,
334: +	}
335: +	for k, v := range extra {
336: +		attributes[k] = v
337: +	}
338: +
339: +	return aggregatedEventFromLabRuntimeEvent(clab, clablabruntime.Event{
340: +		Type: clablabruntime.EventTypeContainer, Action: action,
341: +		ActorID: key, ActorName: state.Name + "-" + node.Name, ActorFullID: key,
342: +		Attributes: attributes, Lab: state, Node: &node,
343: +	})
344: +}
345: +
346: +func attributeKeys(attributes map[string]string) []string {
347: +	keys := make([]string, 0, len(attributes))
348: +	for key := range attributes {
349: +		keys = append(keys, key)
350: +	}
351: +	sort.Strings(keys)
352: +
353: +	return keys
354: +}
355: +
356: +// assertAttributeParity checks that the c9s event carries every attribute of the Docker event,
357: +// apart from the ones listed.
358: +func assertAttributeParity(t *testing.T, docker, c9s aggregatedEvent, dockerOnly map[string]bool) {
359: +	t.Helper()
360: +
361: +	dockerAttributes := mergedEventAttributes(docker)
362: +	c9sAttributes := mergedEventAttributes(c9s)
363: +	var missing []string
364: +	for key := range dockerAttributes {
365: +		if _, ok := c9sAttributes[key]; !ok && !dockerOnly[key] {
366: +			missing = append(missing, key)
367: +		}
368: +	}
369: +	if len(missing) != 0 {
370: +		sort.Strings(missing)
371: +		t.Fatalf("c9s %s %s lacks %v\ndocker: %v\nc9s:    %v", c9s.Type, c9s.Action, missing,
372: +			attributeKeys(dockerAttributes), attributeKeys(c9sAttributes))
373: +	}
374: +}
375: +
376: +// TestContainerEventParity compares the container events of a node's lifecycle, with the c9s
377: +// lab read with its topology file (events -t) and without it (events --name), where the
378: +// attributes come from the cluster alone.
379: +func TestContainerEventParity(t *testing.T) {
380: +	path, dockerLab := parityLab(t)
381: +	byName, err := clabcore.NewContainerLab(clabcore.WithLabNameOnly("parity"))
382: +	if err != nil {
383: +		t.Fatal(err)
384: +	}
385: +
386: +	for _, mode := range []struct {
387: +		name string
388: +		lab  *clabcore.CLab
389: +	}{{"with the topology", dockerLab}, {"by name", byName}} {
390: +		t.Run(mode.name, func(t *testing.T) {
391: +			assertContainerEventParity(t, path, dockerLab, mode.lab, mode.lab == byName)
392: +		})
393: +	}
394: +}
395: +
396: +func assertContainerEventParity(
397: +	t *testing.T,
398: +	path string,
399: +	dockerLab, c9sLab *clabcore.CLab,
400: +	byName bool,
401: +) {
402: +	t.Helper()
403: +
404: +	for _, node := range []string{"client", "srl1"} {
405: +		container := dockerContainer(t, dockerLab, node)
406: +		state, nodeState := c9sNode(dockerLab, path, node)
407: +		dockerOnly := dockerOnlyContainerAttributes
408: +		if byName && node == "srl1" {
409: +			// The type is the SR Linux default; the cluster has only the types a topology
410: +			// sets, so a lab read by name does not know it.
411: +			dockerOnly = map[string]bool{clabconstants.NodeType: true}
412: +			for key := range dockerOnlyContainerAttributes {
413: +				dockerOnly[key] = true
414: +			}
415: +		}
416: +
417: +		for _, tt := range []struct {
418: +			action, state string
419: +			extra         map[string]string
420: +		}{
421: +			{"create", "created", nil},
422: +			{"start", "running", nil},
423: +			{"kill", "running", map[string]string{"signal": "15"}},
424: +			{"stop", "exited", nil},
425: +			{"die", "exited", map[string]string{"exitCode": "137", "execDuration": "3"}},
426: +			{"health_status: healthy", "running", nil},
427: +			{"destroy", "exited", nil},
428: +		} {
429: +			docker := dockerContainerEvent(t, container, tt.action, tt.extra)
430: +			var c9sExtra map[string]string
431: +			if tt.action == "kill" {
432: +				c9sExtra = tt.extra
433: +			}
434: +			c9s := c9sContainerEvent(c9sLab, state, nodeState, tt.action, tt.state, c9sExtra)
435: +			assertAttributeParity(t, docker, c9s, dockerOnly)
436: +
437: +			got := mergedEventAttributes(c9s)
438: +			want := map[string]string{
439: +				clabconstants.Containerlab: "parity",
440: +				clabconstants.NodeName:     node,
441: +				clabconstants.LongName:     "parity-" + node,
442: +				clabconstants.NodeKind:     dockerLab.Nodes[node].Config().Kind,
443: +				clabconstants.TopoFile:     path,
444: +				clabconstants.Owner:        "alice",
445: +				"image":                    container.Image,
446: +				"name":                     "parity-" + node,
447: +				"id":                       "c9s-parity/parity/" + node,
448: +				"mgmt_ipv4":                "172.20.20.84/24",
449: +				"mgmt_ipv6":                "3fff:172:20:20::84/64",
450: +				"ports":                    "22/tcp;80/tcp",
451: +				"state":                    tt.state,
452: +			}
453: +			for key, value := range want {
454: +				if got[key] != value {
455: +					t.Fatalf("%s %s: %s = %q, want %q", node, tt.action, key, got[key], value)
456: +				}
457: +			}
458: +			// the label values have Docker's format
459: +			dockerAttributes := mergedEventAttributes(docker)
460: +			for _, key := range []string{
461: +				clabconstants.Containerlab, clabconstants.NodeName, clabconstants.NodeKind,
462: +				clabconstants.NodeType, clabconstants.TopoFile, clabconstants.Owner, "image",
463: +				"ports",
464: +			} {
465: +				if dockerOnly[key] {
466: +					continue
467: +				}
468: +				if got[key] != dockerAttributes[key] {
469: +					t.Fatalf("%s %s: %s = %q, docker %q", node, tt.action, key, got[key],
470: +						dockerAttributes[key])
471: +				}
472: +			}
473: +			if c9s.ActorID != c9s.ActorFullID || c9s.ActorName != "parity-"+node {
474: +				t.Fatalf("%s %s: actor = %+v", node, tt.action, c9s)
475: +			}
476: +		}
477: +	}
478: +}
479: +
480: +// TestContainerSnapshotParity compares the --initial-state events of a running node, with the
481: +// c9s lab read with its topology file.
482: +func TestContainerSnapshotParity(t *testing.T) {
483: +	path, dockerLab := parityLab(t)
484: +	c9sLab := dockerLab
485: +
486: +	for _, node := range []string{"client", "srl1"} {
487: +		container := dockerContainer(t, dockerLab, node)
488: +		docker := aggregatedEventFromContainerSnapshot(&container)
489: +
490: +		state, nodeState := c9sNode(dockerLab, path, node)
491: +		c9s := c9sContainerEvent(c9sLab, state, nodeState, "running", "running",
492: +			map[string]string{"origin": clablabruntime.EventOriginSnapshot})
493: +
494: +		assertAttributeParity(t, docker, c9s, dockerOnlyContainerAttributes)
495: +		got := mergedEventAttributes(c9s)
496: +		if docker.Action != c9s.Action || got["origin"] != "snapshot" ||
497: +			got["state"] != "running" ||
498: +			got["status"] != "healthy" ||
499: +			got["network"] != "c9s-parity" {
500: +			t.Fatalf("%s snapshot = %s %v", node, c9s.Action, got)
501: +		}
502: +	}
503: +}
504: +
505: +// TestContainerStateUsesDockerVocabulary checks the state and status of every node state c9s
506: +// reports, in events and inspect.
507: +func TestContainerStateUsesDockerVocabulary(t *testing.T) {
508: +	t.Parallel()
509: +
510: +	c9sLab, err := clabcore.NewContainerLab(clabcore.WithLabNameOnly("parity"))
511: +	if err != nil {
512: +		t.Fatal(err)
513: +	}
514: +
515: +	state := &clablabruntime.LabState{Name: "parity", Namespace: "c9s-parity"}
516: +	tests := []struct {
517: +		node          clablabruntime.NodeState
518: +		state, status string
519: +	}{
520: +		{
521: +			clablabruntime.NodeState{Name: "a", ContainerState: "created", State: "notready"},
522: +			"created", "Created",
523: +		},
524: +		{clablabruntime.NodeState{
525: +			Name: "b", ContainerState: "running", Health: "starting",
526: +			State: "notready",
527: +		}, "running", "health: starting"},
528: +		{clablabruntime.NodeState{
529: +			Name: "c", ContainerState: "running", Health: "healthy",
530: +			State: "ready", Ready: true,
531: +		}, "running", "healthy"},
532: +		{
533: +			clablabruntime.NodeState{Name: "d", ContainerState: "exited", State: "stopped"},
534: +			"exited", "Exited",
535: +		},
536: +	}
537: +	for _, tt := range tests {
538: +		container := c9sLab.LabRuntimeContainer(state, tt.node)
539: +		if container.State != tt.state || container.Status != tt.status {
540: +			t.Fatalf("%s: %s / %s, want %s / %s", tt.node.Name, container.State, container.Status,
541: +				tt.state, tt.status)
542: +		}
543: +	}
544: +}
545: +
546: +// dockerInterfaceEvent is a netlink interface event of a Docker container.
547: +func dockerInterfaceEvent(
548: +	container clabruntime.GenericContainer,
549: +	action string,
550: +	snapshot ifaceSnapshot,
551: +	stats *ifaceStatsMetrics,
552: +) aggregatedEvent {
553: +	attributes := interfaceAttributes(&container, snapshot)
554: +	if stats != nil {
555: +		interfaceStatsAttributes(attributes, *stats)
556: +	}
557: +
558: +	return aggregatedEvent{
559: +		Type: "interface", Action: action, ActorID: container.ShortID,
560: +		ActorName: container.Names[0], ActorFullID: container.ID, Attributes: attributes,
561: +	}
562: +}
563: +
564: +func c9sInterfaceEvent(
565: +	state *clablabruntime.LabState,
566: +	node clablabruntime.NodeState,
567: +	action string,
568: +	iface clablabruntime.InterfaceEventData,
569: +) aggregatedEvent {
570: +	key := state.Namespace + "/" + state.Name + "/" + node.Name
571: +
572: +	return aggregatedEventFromLabRuntimeEvent(nil, clablabruntime.Event{
573: +		Type: clablabruntime.EventTypeInterface, Action: action,
574: +		ActorID: key, ActorName: state.Name + "-" + node.Name, ActorFullID: key,
575: +		Attributes: map[string]string{
576: +			"namespace": state.Namespace, "lab": state.Name, "node": node.Name, "pod": node.Pod,
577: +			"origin": "clabernetes",
578: +		},
579: +		Lab: state, Node: &node, Interface: &iface,
580: +	})
581: +}
582: +
583: +// TestInterfaceEventParity compares the interface events of the lab link (linux eth1, SR Linux
584: +// e1-1 with its alias ethernet-1/1), the management interface and loopback.
585: +func TestInterfaceEventParity(t *testing.T) {
586: +	path, dockerLab := parityLab(t)
587: +
588: +	tests := []struct {
589: +		node string
590: +		data clablabruntime.InterfaceEventData
591: +	}{
592: +		{
593: +			"client",
594: +			clablabruntime.InterfaceEventData{
595: +				Name:      "eth1",
596: +				Index:     7,
597: +				MTU:       9500,
598: +				MAC:       "aa:c1:ab:56:aa:46",
599: +				OperState: "up",
600: +				Type:      "veth",
601: +			},
602: +		},
603: +		{"srl1", clablabruntime.InterfaceEventData{
604: +			Name: "e1-1", Alias: "ethernet-1/1", Index: 7, MTU: 9500, MAC: "aa:c1:ab:56:aa:47",
605: +			OperState: "lower-layer-down", Type: "veth",
606: +		}},
607: +		{
608: +			"client",
609: +			clablabruntime.InterfaceEventData{
610: +				Name:      "eth0",
611: +				Index:     4,
612: +				MTU:       1500,
613: +				MAC:       "02:42:ac:14:14:02",
614: +				OperState: "up",
615: +				Type:      "veth",
616: +			},
617: +		},
618: +		{"client", clablabruntime.InterfaceEventData{
619: +			Name: "lo", Index: 1, MTU: 65536, OperState: "unknown", Type: "device",
620: +		}},
621: +	}
622: +	for _, tt := range tests {
623: +		container := dockerContainer(t, dockerLab, tt.node)
624: +		state, nodeState := c9sNode(dockerLab, path, tt.node)
625: +		snapshot := ifaceSnapshot{
626: +			Index: tt.data.Index, Name: tt.data.Name, Alias: tt.data.Alias, MTU: tt.data.MTU,
627: +			MAC: tt.data.MAC, OperState: tt.data.OperState, Type: tt.data.Type,
628: +		}
629: +		metrics := ifaceStatsMetrics{
630: +			RxBytes: 2000, TxBytes: 3000, RxPackets: 20, TxPackets: 30,
631: +			RxBps: 8000, TxBps: 12000, RxPps: 10, TxPps: 15, Interval: 2 * time.Second,
632: +		}
633: +
634: +		for _, action := range []string{"snapshot", "create", "update", "delete", "stats"} {
635: +			var stats *ifaceStatsMetrics
636: +			data := tt.data
637: +			if action == "stats" {
638: +				stats = &metrics
639: +				data.Stats = &clablabruntime.InterfaceStats{
640: +					RxBytes: 2000, TxBytes: 3000, RxPackets: 20, TxPackets: 30,
641: +					RxBps: 8000, TxBps: 12000, RxPps: 10, TxPps: 15, Interval: 2 * time.Second,
642: +				}
643: +			}
644: +			docker := dockerInterfaceEvent(container, action, snapshot, stats)
645: +			c9s := c9sInterfaceEvent(state, nodeState, action, data)
646: +			assertAttributeParity(t, docker, c9s, nil)
647: +
648: +			dockerAttributes := mergedEventAttributes(docker)
649: +			got := mergedEventAttributes(c9s)
650: +			for key, value := range dockerAttributes {
651: +				switch key {
652: +				case "id", "name", "lab", "origin":
653: +					// the node's own ID, name and lab; the source of the event
654: +					continue
655: +				}
656: +				if got[key] != value {
657: +					t.Fatalf("%s %s %s: %s = %q, docker %q", tt.node, tt.data.Name, action, key,
658: +						got[key], value)
659: +				}
660: +			}
661: +			if got["name"] != "parity-"+tt.node || got["lab"] != "parity" ||
662: +				got["id"] != "c9s-parity/parity/"+tt.node {
663: +				t.Fatalf("%s %s %s: node attributes %v", tt.node, tt.data.Name, action, got)
664: +			}
665: +		}
666: +	}
667: +}
668: +
669: +// TestInterfaceEventOmitsUnknownValues checks that values the runtime could not read are left
670: +// out: an index of 0 would make clients take two interfaces for one.
671: +func TestInterfaceEventOmitsUnknownValues(t *testing.T) {
672: +	t.Parallel()
673: +
674: +	state := &clablabruntime.LabState{Name: "parity", Namespace: "c9s-parity"}
675: +	ev := c9sInterfaceEvent(state, clablabruntime.NodeState{Name: "client"}, "stats",
676: +		clablabruntime.InterfaceEventData{
677: +			Name: "eth1", Type: "veth",
678: +			Stats: &clablabruntime.InterfaceStats{RxBytes: 1, Interval: time.Second},
679: +		})
680: +	got := mergedEventAttributes(ev)
681: +	for _, key := range []string{"index", "mtu", "state", "mac", "alias"} {
682: +		if _, ok := got[key]; ok {
683: +			t.Fatalf("%s reported without a value: %v", key, got)
684: +		}
685: +	}
686: +	if got["ifname"] != "eth1" || got["rx_bytes"] != "1" || got["interval_seconds"] != "1" {
687: +		t.Fatalf("stats = %v", got)
688: +	}
689: +}
690: +
691: +func TestLabRuntimeTopologyEventsKeepTheirAttributes(t *testing.T) {
692: +	t.Parallel()
693: +
694: +	ev := aggregatedEventFromLabRuntimeEvent(nil, clablabruntime.Event{
695: +		Type: "topology", Action: "modified", ActorID: "c9s-parity/parity", ActorName: "parity",
696: +		Attributes: map[string]string{"lab": "parity", "state": "running"},
697: +	})
698: +	if !strings.EqualFold(ev.Attributes["lab"], "parity") || len(ev.Attributes) != 2 {
699: +		t.Fatalf("topology event = %+v", ev)
700: +	}
701: +}
702: diff --git a/core/events/stream.go b/core/events/stream.go
703: index a944edc..9ba6c87 100644
704: --- a/core/events/stream.go
705: +++ b/core/events/stream.go
706: @@ -128,11 +128,11 @@ func streamLabRuntimeEvents(ctx context.Context, clab *clabcore.CLab, opts Optio
707:  				runtimeEvents = nil
708:  
709:  				continue
710:  			}
711:  
712: -			if err := printer(aggregatedEventFromLabRuntimeEvent(ev)); err != nil {
713: +			if err := printer(aggregatedEventFromLabRuntimeEvent(clab, ev)); err != nil {
714:  				log.Debugf("failed to write event: %v", err)
715:  			}
716:  		case err, ok := <-runtimeErrs:
717:  			if !ok {
718:  				runtimeErrs = nil
719: @@ -168,27 +168,90 @@ func labRuntimeEventStreamRequest(
720:  		IncludeInterfaceStats: opts.IncludeInterfaceStats,
721:  		StatsInterval:         opts.StatsInterval,
722:  	}
723:  }
724:  
725: -func aggregatedEventFromLabRuntimeEvent(ev clablabruntime.Event) aggregatedEvent {
726: +// aggregatedEventFromLabRuntimeEvent reports a lab runtime event with the attributes the
727: +// container runtimes' events have. A container event describes its node with the container
728: +// record inspect reports for it, the way a Docker event carries the container's labels: as a
729: +// snapshot like the snapshots of local containers, otherwise with the labels, image,
730: +// management addresses and ports a Docker event and its enrichment carry. An interface event
731: +// carries the attributes of the netlink interface events. The runtime's own attributes come on
732: +// top.
733: +func aggregatedEventFromLabRuntimeEvent(
734: +	clab *clabcore.CLab,
735: +	ev clablabruntime.Event,
736: +) aggregatedEvent {
737:  	ts := ev.Timestamp
738:  	if ts.IsZero() {
739:  		ts = time.Now()
740:  	}
741:  
742: +	var attributes map[string]string
743: +	switch {
744: +	case ev.Type == clablabruntime.EventTypeContainer && ev.Lab != nil && ev.Node != nil &&
745: +		clab != nil:
746: +		container := clab.LabRuntimeContainer(ev.Lab, *ev.Node)
747: +		if ev.Attributes["origin"] == clablabruntime.EventOriginSnapshot {
748: +			attributes = aggregatedEventFromContainerSnapshot(&container).Attributes
749: +		} else {
750: +			attributes = containerAttributes(&container)
751: +		}
752: +	case ev.Type == clablabruntime.EventTypeInterface && ev.Interface != nil:
753: +		lab := ev.Attributes["lab"]
754: +		if ev.Lab != nil {
755: +			lab = ev.Lab.Name
756: +		}
757: +		attributes = labRuntimeInterfaceAttributes(lab, ev.ActorName, ev.Interface)
758: +	}
759: +
760: +	for key, value := range ev.Attributes {
761: +		if attributes == nil {
762: +			attributes = make(map[string]string, len(ev.Attributes))
763: +		}
764: +		attributes[key] = value
765: +	}
766: +
767:  	return aggregatedEvent{
768:  		Timestamp:   ts,
769:  		Type:        ev.Type,
770:  		Action:      ev.Action,
771:  		ActorID:     ev.ActorID,
772:  		ActorName:   ev.ActorName,
773:  		ActorFullID: ev.ActorFullID,
774: -		Attributes:  cloneStringMap(ev.Attributes),
775: +		Attributes:  attributes,
776:  	}
777:  }
778:  
779: +// containerAttributes are the attributes a container event reports for a container: its labels
780: +// and image, which Docker puts on every container event, and the management addresses and
781: +// ports the events command adds.
782: +func containerAttributes(container *clabruntime.GenericContainer) map[string]string {
783: +	attributes := cloneStringMap(container.Labels)
784: +	if attributes == nil {
785: +		attributes = make(map[string]string)
786: +	}
787: +
788: +	if container.Image != "" {
789: +		attributes["image"] = container.Image
790: +	}
791: +
792: +	if container.NetworkSettings.IPv4addr != "" {
793: +		attributes["mgmt_ipv4"] = container.GetContainerIPv4()
794: +	}
795: +
796: +	if container.NetworkSettings.IPv6addr != "" {
797: +		attributes["mgmt_ipv6"] = container.GetContainerIPv6()
798: +	}
799: +
800: +	if ports := exposedPortsAttributeValue(container.Ports); ports != "" {
801: +		attributes["ports"] = ports
802: +	}
803: +
804: +	return attributes
805: +}
806: +
807:  func forwardRuntimeEvents(
808:  	ctx context.Context,
809:  	runtime clabruntime.ContainerRuntime,
810:  	registry *netlinkRegistry,
811:  	runtimeEvents <-chan clabruntime.ContainerEvent,
812: @@ -437,23 +500,16 @@ func aggregatedEventFromContainerSnapshot(
813:  	short := container.ShortID
814:  	if short == "" {
815:  		short = clabutils.ShortID(container.ID)
816:  	}
817:  
818: -	attributes := cloneStringMap(container.Labels)
819: -	if attributes == nil {
820: -		attributes = make(map[string]string)
821: -	}
822: +	attributes := containerAttributes(container)
823:  
824:  	if _, ok := attributes["origin"]; !ok {
825:  		attributes["origin"] = "snapshot"
826:  	}
827:  
828: -	if container.Image != "" {
829: -		attributes["image"] = container.Image
830: -	}
831: -
832:  	if container.Status != "" {
833:  		attributes["status"] = container.Status
834:  	}
835:  
836:  	if state != "" {
837: @@ -462,22 +518,10 @@ func aggregatedEventFromContainerSnapshot(
838:  
839:  	if container.NetworkName != "" {
840:  		attributes["network"] = container.NetworkName
841:  	}
842:  
843: -	if container.NetworkSettings.IPv4addr != "" {
844: -		attributes["mgmt_ipv4"] = container.GetContainerIPv4()
845: -	}
846: -
847: -	if container.NetworkSettings.IPv6addr != "" {
848: -		attributes["mgmt_ipv6"] = container.GetContainerIPv6()
849: -	}
850: -
851: -	if ports := exposedPortsAttributeValue(container.Ports); ports != "" {
852: -		attributes["ports"] = ports
853: -	}
854: -
855:  	if len(attributes) == 0 {
856:  		attributes = nil
857:  	}
858:  
859:  	actorName := firstContainerName(container)
860: diff --git a/core/labruntime.go b/core/labruntime.go
861: index eff4bd2..ade83f4 100644
862: --- a/core/labruntime.go
863: +++ b/core/labruntime.go
864: @@ -448,49 +448,68 @@ func (c *CLab) containersFromLabState(
865:  	}
866:  
867:  	return containers
868:  }
869:  
870: +// LabRuntimeContainer describes a lab runtime node as a container record, the way inspect
871: +// reports it. The events command describes lab runtime nodes with it too.
872: +func (c *CLab) LabRuntimeContainer(
873: +	state *clablabruntime.LabState,
874: +	node clablabruntime.NodeState,
875: +) clabruntime.GenericContainer {
876: +	return c.containerFromLabNode(state, node)
877: +}
878: +
879:  func (c *CLab) containerFromLabNode(
880:  	state *clablabruntime.LabState,
881:  	node clablabruntime.NodeState,
882:  ) clabruntime.GenericContainer {
883:  	nodeName := fmt.Sprintf("%s-%s", state.Name, node.Name)
884: -	containerState := node.State
885: -	containerStatus := node.State
886: -	if containerState == "" {
887: -		containerState = state.State
888: +	containerState, containerStatus := labRuntimeContainerState(state, node)
889: +
890: +	topologyNode := node.Name
891: +	if node.TopologyName != "" {
892: +		topologyNode = node.TopologyName
893:  	}
894: -	if node.Ready {
895: -		containerState = "running"
896: -		containerStatus = "healthy"
897: +	if c.Config.Topology != nil {
898: +		topologyNode = c.topologyNodeName(topologyNode)
899:  	}
900:  
901:  	labels := map[string]string{
902:  		clabconstants.Containerlab: state.Name,
903: -		clabconstants.NodeName:     node.Name,
904: +		clabconstants.NodeName:     topologyNode,
905:  		clabconstants.LongName:     nodeName,
906:  		clabconstants.TopoFile:     labRuntimeTopologyPath(c, state),
907:  	}
908:  
909:  	var image string
910:  	if c.Config.Topology != nil {
911: -		topologyNode := c.topologyNodeName(node.Name)
912:  		labels[clabconstants.NodeKind] = c.Config.Topology.GetNodeKind(topologyNode)
913:  		image = c.Config.Topology.GetNodeImage(topologyNode)
914: -
915: -		if group := c.Config.Topology.GetNodeGroup(topologyNode); group != "" {
916: -			labels[clabconstants.NodeGroup] = group
917: -		}
918:  	}
919:  	if node.Kind != "" {
920:  		labels[clabconstants.NodeKind] = node.Kind
921:  	}
922:  	if node.Image != "" {
923:  		image = node.Image
924:  	}
925:  
926: +	// The node's type and group: from the loaded topology's node, with the kind's defaults the
927: +	// local runtimes report too, otherwise as the topology set them on the runtime's node.
928: +	nodeType, group := node.Type, node.Group
929: +	if topologyNodeConfig, ok := c.Nodes[topologyNode]; ok {
930: +		nodeType, group = topologyNodeConfig.Config().NodeType, topologyNodeConfig.Config().Group
931: +	} else if c.Config.Topology != nil && group == "" {
932: +		group = c.Config.Topology.GetNodeGroup(topologyNode)
933: +	}
934: +	if nodeType != "" {
935: +		labels[clabconstants.NodeType] = nodeType
936: +	}
937: +	if group != "" {
938: +		labels[clabconstants.NodeGroup] = group
939: +	}
940: +
941:  	if state.Owner != "" {
942:  		labels[clabconstants.Owner] = state.Owner
943:  	} else if c.customOwner != "" {
944:  		labels[clabconstants.Owner] = c.customOwner
945:  	}
946: @@ -507,10 +526,11 @@ func (c *CLab) containerFromLabNode(
947:  		State:           containerState,
948:  		Status:          containerStatus,
949:  		Labels:          labels,
950:  		NetworkName:     state.Namespace,
951:  		NetworkSettings: managementAddress(node),
952: +		Ports:           labRuntimePorts(node.ExposedPorts),
953:  		Workload: &clabtypes.LabRuntimeWorkload{
954:  			Namespace:           state.Namespace,
955:  			Pod:                 node.Pod,
956:  			Container:           node.Container,
957:  			NodeUID:             node.NodeUID,
958: @@ -518,10 +538,60 @@ func (c *CLab) containerFromLabNode(
959:  			LoadBalancerAddress: node.LoadBalancerAddress,
960:  		},
961:  	}
962:  }
963:  
964: +// labRuntimeContainerState is a lab runtime node's state and status in the vocabulary of the
965: +// container runtimes: state created, running or exited; status healthy or "health: starting"
966: +// for a running node, as inspect shortens a Docker status line with a healthcheck, Created or
967: +// Exited otherwise. A runtime that reports no container state keeps its own state.
968: +func labRuntimeContainerState(
969: +	state *clablabruntime.LabState,
970: +	node clablabruntime.NodeState,
971: +) (string, string) {
972: +	switch node.ContainerState {
973: +	case clablabruntime.ContainerStateRunning:
974: +		if node.Health == clablabruntime.ContainerHealthHealthy {
975: +			return node.ContainerState, "healthy"
976: +		}
977: +
978: +		return node.ContainerState, "health: starting"
979: +	case clablabruntime.ContainerStateCreated:
980: +		return node.ContainerState, "Created"
981: +	case clablabruntime.ContainerStateExited:
982: +		return node.ContainerState, "Exited"
983: +	}
984: +
985: +	if node.Ready {
986: +		return clablabruntime.ContainerStateRunning, "healthy"
987: +	}
988: +	if node.State == "" {
989: +		return state.State, ""
990: +	}
991: +
992: +	return node.State, node.State
993: +}
994: +
995: +// labRuntimePorts reports the ports a lab runtime exposes for a node as the ports a container
996: +// exposes without publishing them on the host: the node is reached through the runtime (a
997: +// Service, a port-forward), never on a port of this machine.
998: +func labRuntimePorts(ports []clablabruntime.ExposedPort) []*clabtypes.GenericPortBinding {
999: +	if len(ports) == 0 {
1000: +		return nil
1001: +	}
1002: +
1003: +	bindings := make([]*clabtypes.GenericPortBinding, 0, len(ports))
1004: +	for _, port := range ports {
1005: +		bindings = append(bindings, &clabtypes.GenericPortBinding{
1006: +			ContainerPort: port.Port,
1007: +			Protocol:      port.Protocol,
1008: +		})
1009: +	}
1010: +
1011: +	return bindings
1012: +}
1013: +
1014:  // labRuntimeContainerID is the ID of a lab runtime node: <namespace>/<lab>/<node>.
1015:  func labRuntimeContainerID(namespace, lab, node string) string {
1016:  	return fmt.Sprintf("%s/%s/%s", namespace, lab, node)
1017:  }
1018:  
1019: diff --git a/core/labruntime_gaps_test.go b/core/labruntime_gaps_test.go
1020: index 791f068..87c0251 100644
1021: --- a/core/labruntime_gaps_test.go
1022: +++ b/core/labruntime_gaps_test.go
1023: @@ -114,5 +114,50 @@ func TestCheckConnectivitySkipsLocalRuntimesForLabRuntimes(t *testing.T) {
1024:  	c := &CLab{LabRuntime: &recordingDestroyLabRuntime{}}
1025:  	if err := c.CheckConnectivity(context.Background()); err != nil {
1026:  		t.Fatalf("CheckConnectivity() = %v, want nil for a lab runtime", err)
1027:  	}
1028:  }
1029: +
1030: +// TestContainerFromLabNodeReportsTheTopologyNode checks the labels a lab runtime node reports
1031: +// without its topology file: the node name the topology spells, the type and group the
1032: +// topology set, the recorded topology file, and its ports as unpublished container ports.
1033: +func TestContainerFromLabNodeReportsTheTopologyNode(t *testing.T) {
1034: +	t.Parallel()
1035: +
1036: +	c := &CLab{Config: &Config{Name: "lab1"}, TopoPaths: &clabtypes.TopoPaths{}}
1037: +	container := c.containerFromLabNode(
1038: +		&clablabruntime.LabState{
1039: +			Name: "lab1", Namespace: "c9s-lab1", TopologyPath: "/home/alice/lab1.clab.yml",
1040: +		},
1041: +		clablabruntime.NodeState{
1042: +			Name: "r1", TopologyName: "R1", Kind: "nokia_srlinux", Type: "ixr-h2",
1043: +			Group: "spines", ContainerState: "running", Health: "healthy",
1044: +			ExposedPorts: []clablabruntime.ExposedPort{
1045: +				{Port: 57400, ExposePort: 57400, Protocol: "tcp"},
1046: +			},
1047: +		},
1048: +	)
1049: +
1050: +	want := map[string]string{
1051: +		"clab-node-name":     "R1",
1052: +		"clab-node-longname": "lab1-r1",
1053: +		"clab-node-kind":     "nokia_srlinux",
1054: +		"clab-node-type":     "ixr-h2",
1055: +		"clab-node-group":    "spines",
1056: +		"clab-topo-file":     "/home/alice/lab1.clab.yml",
1057: +		"containerlab":       "lab1",
1058: +	}
1059: +	for key, value := range want {
1060: +		if container.Labels[key] != value {
1061: +			t.Fatalf("label %s = %q, want %q (%v)", key, container.Labels[key], value,
1062: +				container.Labels)
1063: +		}
1064: +	}
1065: +	if container.State != "running" || container.Status != "healthy" ||
1066: +		container.Names[0] != "lab1-r1" {
1067: +		t.Fatalf("container = %s %s %v", container.State, container.Status, container.Names)
1068: +	}
1069: +	if len(container.Ports) != 1 || container.Ports[0].ContainerPort != 57400 ||
1070: +		container.Ports[0].HostPort != 0 || container.Ports[0].Protocol != "tcp" {
1071: +		t.Fatalf("ports = %+v", container.Ports)
1072: +	}
1073: +}
1074: diff --git a/docs/cmd/events.md b/docs/cmd/events.md
1075: index 92d51ed..23d9eef 100644
1076: --- a/docs/cmd/events.md
1077: +++ b/docs/cmd/events.md
1078: @@ -75,19 +75,25 @@ Currently supported runtimes:
1079:  
1080:  - `docker`
1081:  - `c9s`
1082:  
1083:  With `--runtime c9s`, events are backed by kubernetes watches for Clabernetes
1084: -`Topology` and `Node` resources and labeled Pods. Interface state (`interface up`
1085: -and `interface down` events) and statistics are sampled inside the device
1086: -containers, not through local host netlink. The stream covers every namespace by
1087: -default; `--namespace` (or `CLAB_KUBE_NAMESPACE`) limits it to one namespace,
1088: -and `-t`/`--name` to one lab. With Docker and Podman the lab selection is ignored
1089: -and every lab is streamed.
1090: +`Topology` and `Node` resources and labeled Pods. They use the actions and
1091: +attributes of the Docker runtime: a node is a container (`create`, `start`,
1092: +`kill`, `stop`, `die`, `destroy`, `health_status: …`) described by the same
1093: +labels, and the interface events (`snapshot`, `create`, `update`, `delete`,
1094: +`stats`) report the node's lab link interfaces, `eth0` and `lo` under the names
1095: +a Docker container of the node has. Interface state and statistics are sampled
1096: +inside the device containers, not through local host netlink. The stream covers
1097: +every namespace by default; `--namespace` (or `CLAB_KUBE_NAMESPACE`) limits it
1098: +to one namespace, and `-t`/`--name` to one lab. With Docker and Podman the lab
1099: +selection is ignored and every lab is streamed. The
1100: +[c9s runtime manual](../manual/clabernetes/runtime.md#events) lists the
1101: +attributes and the few Docker attributes c9s has no equivalent for.
1102:  
1103:  Runtimes that do not implement the `events` API, or are not yet supported by Containerlab, will exit with an explanatory error.
1104:  
1105:  ## See also
1106:  
1107:  - [`inspect interfaces`](inspect/interfaces.md) – produces a point-in-time view of the same interface details that `events` reports continuously.
1108: -- [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md) - explains how c9s events differ from Docker events.
1109: +- [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md#events) - describes c9s events and how they map onto Docker events.
1110:  - `docker events` – the raw runtime feed that Containerlab builds upon.
1111: diff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md
1112: index 2354dc1..43fbb9a 100644
1113: --- a/docs/cmd/inspect/interfaces.md
1114: +++ b/docs/cmd/inspect/interfaces.md
1115: @@ -3,11 +3,11 @@
1116:  ### Description
1117:  
1118:  The `inspect interfaces` subcommand provides information about the network interfaces of deployed nodes of a deployed lab.
1119:  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.
1120:  
1121: -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.
1122: +With the [c9s runtime](../../manual/clabernetes/runtime.md#interface-events), the listing covers the interfaces a Docker container of the node has: the lab link interfaces of each running node (the ones [`capture`](../capture.md) accepts) with the alias the topology used, the management interface `eth0` and the loopback `lo`, with the MAC address, index, MTU and operational state read in the node's device container. The pod's own interfaces are not listed. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields and values (`veth`/`device`, netlink state names) are the same as with Docker. `eth0` and `lo` cannot be captured on c9s.
1123:  
1124:  ### Usage
1125:  
1126:  `containerlab [global-flags] inspect interfaces [local-flags]`
1127:  
1128: diff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md
1129: index 8174c98..751ccf1 100644
1130: --- a/docs/manual/clabernetes/runtime.md
1131: +++ b/docs/manual/clabernetes/runtime.md
1132: @@ -543,10 +543,45 @@ port-forward without working out the pod themselves:
1133:  
1134:  These fields are only present for lab runtimes; Docker and Podman output is
1135:  unchanged. Fields without a value, such as `pod` for a stopped node, are left
1136:  out. `--details` keeps printing the raw records.
1137:  
1138: +The other fields mean what they mean for Docker and Podman, so clients can treat
1139: +c9s nodes like containers:
1140: +
1141: +| Field | c9s value |
1142: +|---|---|
1143: +| `state` | `created` while the node's pod is scheduled and prepared, `running` once its device containers run, `exited` once the node is stopped (or its pod ends or is replaced) |
1144: +| `status` | `healthy` once the node is ready or its device containers are, `health: starting` while a running device boots, `Created`, `Exited` |
1145: +| `labPath`, `absLabPath` | the topology file the lab was deployed from (see below) |
1146: +| `name` | `<lab>-<node>`, the name events use as `actor_name` |
1147: +
1148: +### Topology file
1149: +
1150: +A deploy records the absolute path of the topology file, on the machine that
1151: +deployed it, in the annotation `containerlab.dev/topo-file`:
1152: +
1153: +- with a `Topology` resource, on the `Topology`; every deploy records the file
1154: +  it read
1155: +- with `--no-topology-cr`, on every `Node`. clabernetes copies a Node's
1156: +  annotations into its pod, so a Node keeps the file it was created from: a
1157: +  later deploy from another file does not change it and does not restart the
1158: +  node. Destroy and deploy again to record a new file.
1159: +
1160: +`inspect` reports the recorded file as `labPath` and `absLabPath` (shortened
1161: +for the table, as for Docker), and events as `clab-topo-file`, so a client
1162: +matches a running lab to its file the same way for every runtime. The file is a
1163: +path on the deploying machine; a client on another machine cannot assume it
1164: +exists there.
1165: +
1166: +A lab that containerlab did not deploy from a file, for example one applied from
1167: +`deploy --emit-crs` output with `kubectl` (the emitted manifests do not carry
1168: +the annotation), has no recorded file. It reports where its definition lives in
1169: +the cluster: `k8s://<namespace>/topologies/<lab>`, or
1170: +`k8s://<namespace>/labs/<lab>` without a `Topology` resource. With `-t`,
1171: +`inspect` reports the given file.
1172: +
1173:  Useful kubernetes checks for the same state are:
1174:  
1175:  ```bash
1176:  kubectl -n <namespace> get node.c9s.run,link.c9s.run,nodeprofile.c9s.run,deploy,pod,svc,cm,pvc \
1177:    -l c9s.run/topologyOwner=<lab>
1178: @@ -697,12 +732,18 @@ stopped node is started by the same patch.
1179:  What a stopped node keeps and loses:
1180:  
1181:  - The `Node`, its Services, PersistentVolumeClaims and Links stay. Saved
1182:    configuration survives a stop and start.
1183:  - Its links go carrier-down on every peer, like an unplugged cable;
1184: -  `events` reports them as interface `down` events.
1185: -- `inspect` shows the node as `stopped` (`stopping` while its Pod terminates).
1186: +  `events` reports an interface `update` with state `lower-layer-down` on the
1187: +  peers, and deletes the stopped node's interfaces.
1188: +- `inspect` shows the node as `exited` with status `Exited`.
1189: +- `events` reports the container actions Docker reports for `containerlab stop`
1190: +  and `start`: `kill`, `stop` and `die` when the node's pod goes, `start` when
1191: +  its new pod runs, then `health_status: starting` and
1192: +  `health_status: healthy` as the device boots. A restart reports `kill`,
1193: +  `stop`, `die` and `start`.
1194:  - clabernetes keeps a running peer of a stopped node `notready`: its
1195:    connectivity sidecar waits for the far end of the wire. Deploy, apply, start
1196:    and restart treat such a node as settled when its containers are ready, and
1197:    log `link peers stopped: <nodes>` instead of waiting for it.
1198:  
1199: @@ -754,12 +795,14 @@ For example:
1200:  files, the c9s runtime has nothing to copy for that node.
1201:  ///
1202:  
1203:  ## Events
1204:  
1205: -The c9s runtime can stream Node, Topology, pod, interface state and
1206: -interface-stat events:
1207: +The c9s runtime streams container, interface state and interface-stat events
1208: +with the actions and attributes the Docker runtime reports, so a client that
1209: +reads Docker events reads c9s events the same way. It also streams `topology`
1210: +events, which only c9s has:
1211:  
1212:  ```bash
1213:  containerlab --runtime c9s events --format json
1214:  containerlab --runtime c9s events --initial-state
1215:  containerlab --runtime c9s events --interface-stats --format json
1216: @@ -772,10 +815,12 @@ watches:
1217:  
1218:  - c9s `Node` resources carrying `c9s.run/topologyOwner`
1219:  - `Topology` resources
1220:  - Pods labeled with `c9s.run/topologyOwner`
1221:  
1222: +and reads a lab again whenever one of them changes.
1223: +
1224:  What the stream covers:
1225:  
1226:  | Invocation | Scope |
1227:  |---|---|
1228:  | `events` | every namespace |
1229: @@ -783,65 +828,155 @@ What the stream covers:
1230:  | `events -t <topo>` or `events --name <lab>` | that lab, in its namespace (`c9s-<lab>`, or the namespace override) |
1231:  
1232:  An identity whose RBAC only covers one namespace needs one of the scoped forms;
1233:  watching every namespace requires cluster-wide `list` and `watch`.
1234:  
1235: -With `--initial-state`, the stream starts with synthetic events for the current
1236: -c9s node state and the state of every interface, then continues with live
1237: -watches.
1238: +### Container events
1239: +
1240: +Each node is reported as a container. Its state follows its pod: `created`
1241: +while the pod is scheduled and prepared, `running` once the device containers
1242: +run, `exited` once the node is stopped, or its pod ends or is replaced. A change
1243: +is reported with the actions Docker reports for the same change:
1244: +
1245: +| Change | Actions |
1246: +|---|---|
1247: +| the node appears (deploy, apply) | `create`, then `start` once its pod runs |
1248: +| the device boots, is ready, is not ready anymore | `health_status: starting`, `health_status: healthy`, `health_status: unhealthy` |
1249: +| `stop` | `kill`, `stop`, `die` |
1250: +| `start` | `start` |
1251: +| `restart`, or the pod is replaced | `kill`, `stop`, `die`, `start` |
1252: +| the node is removed (destroy, apply) | `kill`, `die` (when it ran), `destroy` |
1253: +
1254: +With `--initial-state`, the stream starts with one event per node whose action
1255: +is its state (`running`, `exited`, `created`) and `origin` `snapshot`, like the
1256: +snapshot of a Docker container.
1257:  
1258: -Container events use the node's `<namespace>/<lab>/<node>` ID as actor, the
1259: -`container_id` inspect reports.
1260: +Every container event describes the node with the attributes of a Docker
1261: +container event, taken from the record `inspect` reports for the node:
1262: +
1263: +```json
1264: +{
1265: +  "timestamp": "2026-10-27T10:15:02.123456789Z",
1266: +  "type": "container",
1267: +  "action": "start",
1268: +  "actor_id": "c9s-clos/clos/srl1",
1269: +  "actor_name": "clos-srl1",
1270: +  "actor_full_id": "c9s-clos/clos/srl1",
1271: +  "attributes": {
1272: +    "containerlab": "clos",
1273: +    "clab-node-name": "srl1",
1274: +    "clab-node-longname": "clos-srl1",
1275: +    "clab-node-kind": "nokia_srlinux",
1276: +    "clab-node-type": "ixr-d2l",
1277: +    "clab-topo-file": "/home/user/clos.clab.yml",
1278: +    "clab-owner": "alice",
1279: +    "image": "ghcr.io/nokia/srlinux",
1280: +    "mgmt_ipv4": "172.20.20.11/24",
1281: +    "ports": "22/tcp;57400/tcp",
1282: +    "state": "running",
1283: +    "id": "c9s-clos/clos/srl1",
1284: +    "name": "clos-srl1",
1285: +    "lab": "clos",
1286: +    "node": "srl1",
1287: +    "namespace": "c9s-clos",
1288: +    "pod": "srl1-7d9c6b5f4-x2k8p"
1289: +  }
1290: +}
1291: +```
1292: +
1293: +- The actor ID is the node's `<namespace>/<lab>/<node>` ID, the `container_id`
1294: +  inspect reports, and `actor_name` and `name` are the inspect `name`.
1295: +- `clab-node-name` is the node name as the topology spells it.
1296: +- `clab-topo-file` is the file the lab was deployed from (see
1297: +  [Topology file](#topology-file)).
1298: +- `state` is the container state after the event: `created`, `running` or
1299: +  `exited`. Docker leaves it to the client to derive it from the action; c9s
1300: +  reports it on every container event.
1301: +- `ports` lists the node's exposed ports without a host binding: they are
1302: +  reached through the node's Service or a port-forward, not on a port of the
1303: +  local machine.
1304: +- `kill` carries `signal` `15`; Kubernetes stops containers with SIGTERM.
1305: +- `create` can come before the controller has allocated the node's management
1306: +  address and Service, so it may lack `mgmt_ipv4`, `mgmt_ipv6` and `ports`;
1307: +  the following events carry them.
1308: +- `namespace`, `lab`, `node` and `pod` are c9s attributes on top.
1309: +
1310: +Docker attributes c9s does not report: `scope`, `clab-mgmt-net-bridge` (no
1311: +Docker bridge), `clab-node-lab-dir` (a c9s lab has no lab directory on the
1312: +deploying machine; node state lives in the cluster), and `exitCode` and
1313: +`execDuration` on `die`. `clab-node-type` and `clab-node-group` are reported
1314: +when the topology sets them, and with `-t` also a kind's default type; read by
1315: +`--name` alone, a default type such as SR Linux's `ixr-d2l` is not known.
1316:  
1317:  ### Interface events
1318:  
1319:  Containerlab samples the interfaces of every running node by exec into its
1320:  device container. One exec per node and interval reads `/proc/net/dev` and
1321:  `/sys/class/net/*/operstate` (with index, MTU, MAC address, flags and alias).
1322: -All containers of a device pod share one network namespace, so the samples
1323: -cover the node's pod interfaces.
1324:  
1325: -Interface state events are always streamed. They use the same schema as the
1326: -interface events of the local runtimes, with the operational state as action:
1327: +It reports the interfaces a Docker container of the same node kind has, named
1328: +as in that container:
1329: +
1330: +- the node's lab link interfaces, with the names and aliases clabwire lists for
1331: +  them (`containerlab capture --list`): `eth1` for a linux node, `e1-1` with
1332: +  alias `ethernet-1/1` for SR Linux, so a client finds a link's interface by
1333: +  the endpoint name in the topology or its alias
1334: +- the management interface `eth0`
1335: +- the loopback `lo`
1336: +
1337: +The pod's own interfaces (the pod network interface `c9s0`, clabernetes'
1338: +interposition interfaces `c9sr0` and `c9sm0`, and the link transport interfaces
1339: +`c9ss*`) are not reported, and neither are the aliases clabernetes sets for its
1340: +own use (`c9s:…`).
1341: +
1342: +Interface state events are always streamed, with the actions and attributes of
1343: +the local runtimes' netlink events:
1344:  
1345:  ```json
1346:  {
1347:    "timestamp": "2026-10-27T10:15:02.123456789Z",
1348:    "type": "interface",
1349: -  "action": "down",
1350: +  "action": "update",
1351:    "actor_id": "c9s-clos/clos/srl1",
1352:    "actor_name": "clos-srl1",
1353: -  "actor_full_id": "srl1-7d9c6b5f4-x2k8p",
1354: +  "actor_full_id": "c9s-clos/clos/srl1",
1355:    "attributes": {
1356:      "ifname": "e1-1",
1357: -    "state": "lowerlayerdown",
1358: +    "alias": "ethernet-1/1",
1359: +    "state": "lower-layer-down",
1360: +    "type": "veth",
1361:      "index": "7",

(Output capped at 50 KB. Showing lines 1-1361. Use offset=1362 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19674cc69001hWMMtep91QL0Ld",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674c79a001gjHUT18UiSAEMW",
  "callID": "call_c0a87fa8681f49ff84960f45",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt"
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n1: diff --git a/core/events/netlink.go b/core/events/netlink.go\n2: index 150b71d..1654a4a 100644\n3: --- a/core/events/netlink.go\n4: +++ b/core/events/netlink.go\n5: @@ -12,10 +12,11 @@ import (\n6:  \n7:  \t\"github.com/charmbracelet/log\"\n8:  \tgotc \"github.com/florianl/go-tc\"\n9:  \tclabconstants \"github.com/srl-labs/containerlab/constants\"\n10:  \tclabcore \"github.com/srl-labs/containerlab/core\"\n11: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n12:  \tclablinks \"github.com/srl-labs/containerlab/links\"\n13:  \tclabnetem \"github.com/srl-labs/containerlab/netem\"\n14:  \tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n15:  \tclabutils \"github.com/srl-labs/containerlab/utils\"\n16:  \t\"github.com/vishvananda/netlink\"\n17: @@ -642,31 +643,99 @@ func containerLabel(container *clabruntime.GenericContainer) string {\n18:  \t}\n19:  \n20:  \treturn container.Labels[clabconstants.Containerlab]\n21:  }\n22:  \n23: -func interfaceAttributes(\n24: -\tcontainer *clabruntime.GenericContainer,\n25: -\tsnapshot ifaceSnapshot,\n26: -) map[string]string {\n27: +// interfaceSnapshotAttributes are the attributes every interface event reports for the\n28: +// interface itself.\n29: +func interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {\n30:  \tattributes := map[string]string{\n31:  \t\t\"ifname\": snapshot.Name,\n32:  \t\t\"index\":  strconv.Itoa(snapshot.Index),\n33:  \t\t\"mtu\":    strconv.Itoa(snapshot.MTU),\n34:  \t\t\"state\":  snapshot.OperState,\n35:  \t\t\"type\":   snapshot.Type,\n36: -\t\t\"origin\": \"netlink\",\n37:  \t}\n38:  \n39:  \tif snapshot.Alias != \"\" {\n40:  \t\tattributes[\"alias\"] = snapshot.Alias\n41:  \t}\n42:  \n43:  \tif snapshot.MAC != \"\" {\n44:  \t\tattributes[\"mac\"] = snapshot.MAC\n45:  \t}\n46:  \n47: +\treturn attributes\n48: +}\n49: +\n50: +// interfaceStatsAttributes adds the counters and rates of a stats event.\n51: +func interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {\n52: +\tattributes[\"rx_bytes\"] = strconv.FormatUint(metrics.RxBytes, 10)\n53: +\tattributes[\"tx_bytes\"] = strconv.FormatUint(metrics.TxBytes, 10)\n54: +\tattributes[\"rx_packets\"] = strconv.FormatUint(metrics.RxPackets, 10)\n55: +\tattributes[\"tx_packets\"] = strconv.FormatUint(metrics.TxPackets, 10)\n56: +\tattributes[\"rx_bps\"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)\n57: +\tattributes[\"tx_bps\"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)\n58: +\tattributes[\"rx_pps\"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)\n59: +\tattributes[\"tx_pps\"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)\n60: +\tattributes[\"interval_seconds\"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)\n61: +}\n62: +\n63: +// labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those\n64: +// of the netlink interface events, for the node the runtime runs. Values the runtime could not\n65: +// read (no index or MTU without a shell in the node) are left out rather than reported as 0.\n66: +func labRuntimeInterfaceAttributes(\n67: +\tlab, name string,\n68: +\tiface *clablabruntime.InterfaceEventData,\n69: +) map[string]string {\n70: +\tattributes := interfaceSnapshotAttributes(ifaceSnapshot{\n71: +\t\tIndex:     iface.Index,\n72: +\t\tName:      iface.Name,\n73: +\t\tAlias:     iface.Alias,\n74: +\t\tMTU:       iface.MTU,\n75: +\t\tMAC:       iface.MAC,\n76: +\t\tOperState: iface.OperState,\n77: +\t\tType:      iface.Type,\n78: +\t})\n79: +\tif iface.Index <= 0 {\n80: +\t\tdelete(attributes, \"index\")\n81: +\t}\n82: +\tif iface.MTU <= 0 {\n83: +\t\tdelete(attributes, \"mtu\")\n84: +\t}\n85: +\n86: +\tif lab != \"\" {\n87: +\t\tattributes[\"lab\"] = lab\n88: +\t}\n89: +\tif name != \"\" {\n90: +\t\tattributes[\"name\"] = name\n91: +\t}\n92: +\n93: +\tif stats := iface.Stats; stats != nil {\n94: +\t\tinterfaceStatsAttributes(attributes, ifaceStatsMetrics{\n95: +\t\t\tRxBytes:   stats.RxBytes,\n96: +\t\t\tTxBytes:   stats.TxBytes,\n97: +\t\t\tRxPackets: stats.RxPackets,\n98: +\t\t\tTxPackets: stats.TxPackets,\n99: +\t\t\tRxBps:     stats.RxBps,\n100: +\t\t\tTxBps:     stats.TxBps,\n101: +\t\t\tRxPps:     stats.RxPps,\n102: +\t\t\tTxPps:     stats.TxPps,\n103: +\t\t\tInterval:  stats.Interval,\n104: +\t\t})\n105: +\t}\n106: +\n107: +\treturn attributes\n108: +}\n109: +\n110: +func interfaceAttributes(\n111: +\tcontainer *clabruntime.GenericContainer,\n112: +\tsnapshot ifaceSnapshot,\n113: +) map[string]string {\n114: +\tattributes := interfaceSnapshotAttributes(snapshot)\n115: +\tattributes[\"origin\"] = \"netlink\"\n116: +\n117:  \tif lab := containerLabel(container); lab != \"\" {\n118:  \t\tattributes[\"lab\"] = lab\n119:  \t}\n120:  \n121:  \tif name := firstContainerName(container); name != \"\" {\n122: @@ -811,19 +880,11 @@ func (r *netlinkRegistry) emitInterfaceStatsEvent(\n123:  \tif !r.includeStats || container == nil || !snapshot.HasStats {\n124:  \t\treturn\n125:  \t}\n126:  \n127:  \tattributes := interfaceAttributes(container, snapshot)\n128: -\tattributes[\"rx_bytes\"] = strconv.FormatUint(metrics.RxBytes, 10)\n129: -\tattributes[\"tx_bytes\"] = strconv.FormatUint(metrics.TxBytes, 10)\n130: -\tattributes[\"rx_packets\"] = strconv.FormatUint(metrics.RxPackets, 10)\n131: -\tattributes[\"tx_packets\"] = strconv.FormatUint(metrics.TxPackets, 10)\n132: -\tattributes[\"rx_bps\"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)\n133: -\tattributes[\"tx_bps\"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)\n134: -\tattributes[\"rx_pps\"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)\n135: -\tattributes[\"tx_pps\"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)\n136: -\tattributes[\"interval_seconds\"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)\n137: +\tinterfaceStatsAttributes(attributes, metrics)\n138:  \n139:  \tevent := aggregatedEvent{\n140:  \t\tTimestamp:   metrics.Timestamp,\n141:  \t\tType:        \"interface\",\n142:  \t\tAction:      \"stats\",\n143: diff --git a/core/events/parity_test.go b/core/events/parity_test.go\n144: new file mode 100644\n145: index 0000000..855365b\n146: --- /dev/null\n147: +++ b/core/events/parity_test.go\n148: @@ -0,0 +1,553 @@\n149: +package events\n150: +\n151: +import (\n152: +\t\"context\"\n153: +\t\"os\"\n154: +\t\"path/filepath\"\n155: +\t\"sort\"\n156: +\t\"strings\"\n157: +\t\"testing\"\n158: +\t\"time\"\n159: +\n160: +\tdockerEvents \"github.com/docker/docker/api/types/events\"\n161: +\tclabconstants \"github.com/srl-labs/containerlab/constants\"\n162: +\tclabcore \"github.com/srl-labs/containerlab/core\"\n163: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n164: +\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n165: +\tclabtypes \"github.com/srl-labs/containerlab/types\"\n166: +\tclabutils \"github.com/srl-labs/containerlab/utils\"\n167: +)\n168: +\n169: +// These tests build the events the Docker runtime and the c9s lab runtime report for the same\n170: +// node and compare them: every attribute a Docker event carries is in the c9s event, with the\n171: +// same meaning, apart from the ones c9s has no equivalent for.\n172: +\n173: +// dockerOnlyContainerAttributes are the Docker container event attributes c9s has no\n174: +// equivalent for: the Docker event scope, the Docker management bridge, and the exit code and\n175: +// run time of a container process, which Kubernetes does not keep once the pod is gone.\n176: +var dockerOnlyContainerAttributes = map[string]bool{ //nolint:gochecknoglobals\n177: +\t\"scope\":                     true,\n178: +\tclabconstants.NodeMgmtNetBr: true,\n179: +\tclabconstants.NodeLabDir:    true,\n180: +\t\"exitCode\":                  true,\n181: +\t\"execDuration\":              true,\n182: +}\n183: +\n184: +const parityTopology = `name: parity\n185: +mgmt:\n186: +  network: clab\n187: +topology:\n188: +  nodes:\n189: +    client:\n190: +      kind: linux\n191: +      image: ghcr.io/srl-labs/network-multitool\n192: +    srl1:\n193: +      kind: nokia_srlinux\n194: +      image: ghcr.io/nokia/srlinux:25.10\n195: +  links:\n196: +    - endpoints: [\"client:eth1\", \"srl1:ethernet-1/1\"]\n197: +`\n198: +\n199: +// parityLab loads the topology as a Docker deploy does and returns its labels per node.\n200: +func parityLab(t *testing.T) (string, *clabcore.CLab) {\n201: +\tt.Helper()\n202: +\n203: +\tdir := t.TempDir()\n204: +\tpath := filepath.Join(dir, \"parity.clab.yml\")\n205: +\tif err := os.WriteFile(path, []byte(parityTopology), 0o600); err != nil {\n206: +\t\tt.Fatal(err)\n207: +\t}\n208: +\tt.Setenv(\"USER\", \"alice\")\n209: +\tt.Setenv(\"SUDO_USER\", \"\")\n210: +\n211: +\tc, err := clabcore.NewContainerLab(clabcore.WithTopoPath(path, nil))\n212: +\tif err != nil {\n213: +\t\tt.Fatal(err)\n214: +\t}\n215: +\n216: +\treturn path, c\n217: +}\n218: +\n219: +// fakeDockerRuntime answers the container lookup the events command makes for a Docker event.\n220: +type fakeDockerRuntime struct {\n221: +\tclabruntime.ContainerRuntime\n222: +\tcontainer clabruntime.GenericContainer\n223: +}\n224: +\n225: +func (f *fakeDockerRuntime) ListContainers(\n226: +\tcontext.Context,\n227: +\t[]*clabtypes.GenericFilter,\n228: +) ([]clabruntime.GenericContainer, error) {\n229: +\treturn []clabruntime.GenericContainer{f.container}, nil\n230: +}\n231: +\n232: +// dockerContainer is the container Docker runs for a node.\n233: +func dockerContainer(t *testing.T, c *clabcore.CLab, node string) clabruntime.GenericContainer {\n234: +\tt.Helper()\n235: +\n236: +\tcfg := c.Nodes[node].Config()\n237: +\tlabels := cloneStringMap(cfg.Labels)\n238: +\tlabels[clabconstants.NodeMgmtNetBr] = \"br-92bb9fb46cd2\"\n239: +\n240: +\treturn clabruntime.GenericContainer{\n241: +\t\tNames:   []string{cfg.LongName},\n242: +\t\tID:      \"57b7763f3b4d97ff0c96b1dab8294b836199628a2d9400549948a963732e185a\",\n243: +\t\tShortID: \"57b7763f3b4d\",\n244: +\t\tImage:   cfg.Image,\n245: +\t\tState:   \"running\",\n246: +\t\tStatus:  \"Up 19 seconds\",\n247: +\t\tLabels:  labels,\n248: +\t\tNetworkSettings: clabruntime.GenericMgmtIPs{\n249: +\t\t\tIPv4addr: \"172.20.20.2\", IPv4pLen: 24, IPv6addr: \"3fff:172:20:20::2\", IPv6pLen: 64,\n250: +\t\t},\n251: +\t\tNetworkName: \"clab\",\n252: +\t\tPorts: []*clabtypes.GenericPortBinding{\n253: +\t\t\t{ContainerPort: 22, Protocol: \"tcp\"}, {ContainerPort: 80, Protocol: \"tcp\"},\n254: +\t\t},\n255: +\t}\n256: +}\n257: +\n258: +// dockerContainerEvent is a Docker container event as `containerlab events` reports it: the\n259: +// Docker message (container labels, image and name as attributes, plus the action's own) through\n260: +// the events command's conversion and enrichment.\n261: +func dockerContainerEvent(\n262: +\tt *testing.T,\n263: +\tcontainer clabruntime.GenericContainer,\n264: +\taction string,\n265: +\textra map[string]string,\n266: +) aggregatedEvent {\n267: +\tt.Helper()\n268: +\n269: +\tattributes := cloneStringMap(container.Labels)\n270: +\tattributes[\"image\"] = container.Image\n271: +\tattributes[\"name\"] = container.Names[0]\n272: +\tfor k, v := range extra {\n273: +\t\tattributes[k] = v\n274: +\t}\n275: +\tdata := clabutils.DockerMessageToEventData(dockerEvents.Message{\n276: +\t\tType:     dockerEvents.ContainerEventType,\n277: +\t\tAction:   dockerEvents.Action(action),\n278: +\t\tActor:    dockerEvents.Actor{ID: container.ID, Attributes: attributes},\n279: +\t\tScope:    \"local\",\n280: +\t\tTimeNano: time.Now().UnixNano(),\n281: +\t})\n282: +\n283: +\treturn aggregatedEventFromContainerEvent(context.Background(),\n284: +\t\t&fakeDockerRuntime{container: container},\n285: +\t\tclabruntime.ContainerEvent{\n286: +\t\t\tTimestamp: data.Timestamp, Type: data.Type, Action: data.Action,\n287: +\t\t\tActorID: data.ActorID, ActorName: data.ActorName, ActorFullID: data.ActorFullID,\n288: +\t\t\tAttributes: data.Attributes,\n289: +\t\t})\n290: +}\n291: +\n292: +// c9sNode is the same node as the c9s runtime reports it, deployed from the same file.\n293: +func c9sNode(\n294: +\tc *clabcore.CLab,\n295: +\tpath, node string,\n296: +) (*clablabruntime.LabState, clablabruntime.NodeState) {\n297: +\tcfg := c.Nodes[node].Config()\n298: +\tstate := &clablabruntime.LabState{\n299: +\t\tName: \"parity\", Namespace: \"c9s-parity\", Owner: \"alice\", TopologyPath: path,\n300: +\t\tState: \"running\", Ready: true,\n301: +\t}\n302: +\tnodeState := clablabruntime.NodeState{\n303: +\t\tName: node, Kind: cfg.Kind, Image: cfg.Image, State: \"ready\", Ready: true,\n304: +\t\tContainerState:  clablabruntime.ContainerStateRunning,\n305: +\t\tHealth:          clablabruntime.ContainerHealthHealthy,\n306: +\t\tMgmtIPv4Address: \"172.20.20.84/24\", MgmtIPv6Address: \"3fff:172:20:20::84/64\",\n307: +\t\tPod: node + \"-88598986c-rbdfq\", Container: \"node-\" + node, NodeUID: \"uid-\" + node,\n308: +\t\tExposedPorts: []clablabruntime.ExposedPort{\n309: +\t\t\t{\n310: +\t\t\t\tPort:       22,\n311: +\t\t\t\tExposePort: 22,\n312: +\t\t\t\tProtocol:   \"tcp\",\n313: +\t\t\t},\n314: +\t\t\t{Port: 80, ExposePort: 80, Protocol: \"tcp\"},\n315: +\t\t},\n316: +\t}\n317: +\tstate.Nodes = []clablabruntime.NodeState{nodeState}\n318: +\n319: +\treturn state, nodeState\n320: +}\n321: +\n322: +// c9sContainerEvent is the event the c9s runtime emits, as `containerlab events` reports it.\n323: +func c9sContainerEvent(\n324: +\tclab *clabcore.CLab,\n325: +\tstate *clablabruntime.LabState,\n326: +\tnode clablabruntime.NodeState,\n327: +\taction, containerState string,\n328: +\textra map[string]string,\n329: +) aggregatedEvent {\n330: +\tkey := state.Namespace + \"/\" + state.Name + \"/\" + node.Name\n331: +\tattributes := map[string]string{\n332: +\t\t\"namespace\": state.Namespace, \"lab\": state.Name, \"node\": node.Name, \"pod\": node.Pod,\n333: +\t\t\"state\": containerState,\n334: +\t}\n335: +\tfor k, v := range extra {\n336: +\t\tattributes[k] = v\n337: +\t}\n338: +\n339: +\treturn aggregatedEventFromLabRuntimeEvent(clab, clablabruntime.Event{\n340: +\t\tType: clablabruntime.EventTypeContainer, Action: action,\n341: +\t\tActorID: key, ActorName: state.Name + \"-\" + node.Name, ActorFullID: key,\n342: +\t\tAttributes: attributes, Lab: state, Node: &node,\n343: +\t})\n344: +}\n345: +\n346: +func attributeKeys(attributes map[string]string) []string {\n347: +\tkeys := make([]string, 0, len(attributes))\n348: +\tfor key := range attributes {\n349: +\t\tkeys = append(keys, key)\n350: +\t}\n351: +\tsort.Strings(keys)\n352: +\n353: +\treturn keys\n354: +}\n355: +\n356: +// assertAttributeParity checks that the c9s event carries every attribute of the Docker event,\n357: +// apart from the ones listed.\n358: +func assertAttributeParity(t *testing.T, docker, c9s aggregatedEvent, dockerOnly map[string]bool) {\n359: +\tt.Helper()\n360: +\n361: +\tdockerAttributes := mergedEventAttributes(docker)\n362: +\tc9sAttributes := mergedEventAttributes(c9s)\n363: +\tvar missing []string\n364: +\tfor key := range dockerAttributes {\n365: +\t\tif _, ok := c9sAttributes[key]; !ok && !dockerOnly[key] {\n366: +\t\t\tmissing = append(missing, key)\n367: +\t\t}\n368: +\t}\n369: +\tif len(missing) != 0 {\n370: +\t\tsort.Strings(missing)\n371: +\t\tt.Fatalf(\"c9s %s %s lacks %v\\ndocker: %v\\nc9s:    %v\", c9s.Type, c9s.Action, missing,\n372: +\t\t\tattributeKeys(dockerAttributes), attributeKeys(c9sAttributes))\n373: +\t}\n374: +}\n375: +\n376: +// TestContainerEventParity compares the container events of a node's lifecycle, with the c9s\n377: +// lab read with its topology file (events -t) and without it (events --name), where the\n378: +// attributes come from the cluster alone.\n379: +func TestContainerEventParity(t *testing.T) {\n380: +\tpath, dockerLab := parityLab(t)\n381: +\tbyName, err := clabcore.NewContainerLab(clabcore.WithLabNameOnly(\"parity\"))\n382: +\tif err != nil {\n383: +\t\tt.Fatal(err)\n384: +\t}\n385: +\n386: +\tfor _, mode := range []struct {\n387: +\t\tname string\n388: +\t\tlab  *clabcore.CLab\n389: +\t}{{\"with the topology\", dockerLab}, {\"by name\", byName}} {\n390: +\t\tt.Run(mode.name, func(t *testing.T) {\n391: +\t\t\tassertContainerEventParity(t, path, dockerLab, mode.lab, mode.lab == byName)\n392: +\t\t})\n393: +\t}\n394: +}\n395: +\n396: +func assertContainerEventParity(\n397: +\tt *testing.T,\n398: +\tpath string,\n399: +\tdockerLab, c9sLab *clabcore.CLab,\n400: +\tbyName bool,\n401: +) {\n402: +\tt.Helper()\n403: +\n404: +\tfor _, node := range []string{\"client\", \"srl1\"} {\n405: +\t\tcontainer := dockerContainer(t, dockerLab, node)\n406: +\t\tstate, nodeState := c9sNode(dockerLab, path, node)\n407: +\t\tdockerOnly := dockerOnlyContainerAttributes\n408: +\t\tif byName && node == \"srl1\" {\n409: +\t\t\t// The type is the SR Linux default; the cluster has only the types a topology\n410: +\t\t\t// sets, so a lab read by name does not know it.\n411: +\t\t\tdockerOnly = map[string]bool{clabconstants.NodeType: true}\n412: +\t\t\tfor key := range dockerOnlyContainerAttributes {\n413: +\t\t\t\tdockerOnly[key] = true\n414: +\t\t\t}\n415: +\t\t}\n416: +\n417: +\t\tfor _, tt := range []struct {\n418: +\t\t\taction, state string\n419: +\t\t\textra         map[string]string\n420: +\t\t}{\n421: +\t\t\t{\"create\", \"created\", nil},\n422: +\t\t\t{\"start\", \"running\", nil},\n423: +\t\t\t{\"kill\", \"running\", map[string]string{\"signal\": \"15\"}},\n424: +\t\t\t{\"stop\", \"exited\", nil},\n425: +\t\t\t{\"die\", \"exited\", map[string]string{\"exitCode\": \"137\", \"execDuration\": \"3\"}},\n426: +\t\t\t{\"health_status: healthy\", \"running\", nil},\n427: +\t\t\t{\"destroy\", \"exited\", nil},\n428: +\t\t} {\n429: +\t\t\tdocker := dockerContainerEvent(t, container, tt.action, tt.extra)\n430: +\t\t\tvar c9sExtra map[string]string\n431: +\t\t\tif tt.action == \"kill\" {\n432: +\t\t\t\tc9sExtra = tt.extra\n433: +\t\t\t}\n434: +\t\t\tc9s := c9sContainerEvent(c9sLab, state, nodeState, tt.action, tt.state, c9sExtra)\n435: +\t\t\tassertAttributeParity(t, docker, c9s, dockerOnly)\n436: +\n437: +\t\t\tgot := mergedEventAttributes(c9s)\n438: +\t\t\twant := map[string]string{\n439: +\t\t\t\tclabconstants.Containerlab: \"parity\",\n440: +\t\t\t\tclabconstants.NodeName:     node,\n441: +\t\t\t\tclabconstants.LongName:     \"parity-\" + node,\n442: +\t\t\t\tclabconstants.NodeKind:     dockerLab.Nodes[node].Config().Kind,\n443: +\t\t\t\tclabconstants.TopoFile:     path,\n444: +\t\t\t\tclabconstants.Owner:        \"alice\",\n445: +\t\t\t\t\"image\":                    container.Image,\n446: +\t\t\t\t\"name\":                     \"parity-\" + node,\n447: +\t\t\t\t\"id\":                       \"c9s-parity/parity/\" + node,\n448: +\t\t\t\t\"mgmt_ipv4\":                \"172.20.20.84/24\",\n449: +\t\t\t\t\"mgmt_ipv6\":                \"3fff:172:20:20::84/64\",\n450: +\t\t\t\t\"ports\":                    \"22/tcp;80/tcp\",\n451: +\t\t\t\t\"state\":                    tt.state,\n452: +\t\t\t}\n453: +\t\t\tfor key, value := range want {\n454: +\t\t\t\tif got[key] != value {\n455: +\t\t\t\t\tt.Fatalf(\"%s %s: %s = %q, want %q\", node, tt.action, key, got[key], value)\n456: +\t\t\t\t}\n457: +\t\t\t}\n458: +\t\t\t// the label values have Docker's format\n459: +\t\t\tdockerAttributes := mergedEventAttributes(docker)\n460: +\t\t\tfor _, key := range []string{\n461: +\t\t\t\tclabconstants.Containerlab, clabconstants.NodeName, clabconstants.NodeKind,\n462: +\t\t\t\tclabconstants.NodeType, clabconstants.TopoFile, clabconstants.Owner, \"image\",\n463: +\t\t\t\t\"ports\",\n464: +\t\t\t} {\n465: +\t\t\t\tif dockerOnly[key] {\n466: +\t\t\t\t\tcontinue\n467: +\t\t\t\t}\n468: +\t\t\t\tif got[key] != dockerAttributes[key] {\n469: +\t\t\t\t\tt.Fatalf(\"%s %s: %s = %q, docker %q\", node, tt.action, key, got[key],\n470: +\t\t\t\t\t\tdockerAttributes[key])\n471: +\t\t\t\t}\n472: +\t\t\t}\n473: +\t\t\tif c9s.ActorID != c9s.ActorFullID || c9s.ActorName != \"parity-\"+node {\n474: +\t\t\t\tt.Fatalf(\"%s %s: actor = %+v\", node, tt.action, c9s)\n475: +\t\t\t}\n476: +\t\t}\n477: +\t}\n478: +}\n479: +\n480: +// TestContainerSnapshotParity compares the --initial-state events of a running node, with the\n481: +// c9s lab read with its topology file.\n482: +func TestContainerSnapshotParity(t *testing.T) {\n483: +\tpath, dockerLab := parityLab(t)\n484: +\tc9sLab := dockerLab\n485: +\n486: +\tfor _, node := range []string{\"client\", \"srl1\"} {\n487: +\t\tcontainer := dockerContainer(t, dockerLab, node)\n488: +\t\tdocker := aggregatedEventFromContainerSnapshot(&container)\n489: +\n490: +\t\tstate, nodeState := c9sNode(dockerLab, path, node)\n491: +\t\tc9s := c9sContainerEvent(c9sLab, state, nodeState, \"running\", \"running\",\n492: +\t\t\tmap[string]string{\"origin\": clablabruntime.EventOriginSnapshot})\n493: +\n494: +\t\tassertAttributeParity(t, docker, c9s, dockerOnlyContainerAttributes)\n495: +\t\tgot := mergedEventAttributes(c9s)\n496: +\t\tif docker.Action != c9s.Action || got[\"origin\"] != \"snapshot\" ||\n497: +\t\t\tgot[\"state\"] != \"running\" ||\n498: +\t\t\tgot[\"status\"] != \"healthy\" ||\n499: +\t\t\tgot[\"network\"] != \"c9s-parity\" {\n500: +\t\t\tt.Fatalf(\"%s snapshot = %s %v\", node, c9s.Action, got)\n501: +\t\t}\n502: +\t}\n503: +}\n504: +\n505: +// TestContainerStateUsesDockerVocabulary checks the state and status of every node state c9s\n506: +// reports, in events and inspect.\n507: +func TestContainerStateUsesDockerVocabulary(t *testing.T) {\n508: +\tt.Parallel()\n509: +\n510: +\tc9sLab, err := clabcore.NewContainerLab(clabcore.WithLabNameOnly(\"parity\"))\n511: +\tif err != nil {\n512: +\t\tt.Fatal(err)\n513: +\t}\n514: +\n515: +\tstate := &clablabruntime.LabState{Name: \"parity\", Namespace: \"c9s-parity\"}\n516: +\ttests := []struct {\n517: +\t\tnode          clablabruntime.NodeState\n518: +\t\tstate, status string\n519: +\t}{\n520: +\t\t{\n521: +\t\t\tclablabruntime.NodeState{Name: \"a\", ContainerState: \"created\", State: \"notready\"},\n522: +\t\t\t\"created\", \"Created\",\n523: +\t\t},\n524: +\t\t{clablabruntime.NodeState{\n525: +\t\t\tName: \"b\", ContainerState: \"running\", Health: \"starting\",\n526: +\t\t\tState: \"notready\",\n527: +\t\t}, \"running\", \"health: starting\"},\n528: +\t\t{clablabruntime.NodeState{\n529: +\t\t\tName: \"c\", ContainerState: \"running\", Health: \"healthy\",\n530: +\t\t\tState: \"ready\", Ready: true,\n531: +\t\t}, \"running\", \"healthy\"},\n532: +\t\t{\n533: +\t\t\tclablabruntime.NodeState{Name: \"d\", ContainerState: \"exited\", State: \"stopped\"},\n534: +\t\t\t\"exited\", \"Exited\",\n535: +\t\t},\n536: +\t}\n537: +\tfor _, tt := range tests {\n538: +\t\tcontainer := c9sLab.LabRuntimeContainer(state, tt.node)\n539: +\t\tif container.State != tt.state || container.Status != tt.status {\n540: +\t\t\tt.Fatalf(\"%s: %s / %s, want %s / %s\", tt.node.Name, container.State, container.Status,\n541: +\t\t\t\ttt.state, tt.status)\n542: +\t\t}\n543: +\t}\n544: +}\n545: +\n546: +// dockerInterfaceEvent is a netlink interface event of a Docker container.\n547: +func dockerInterfaceEvent(\n548: +\tcontainer clabruntime.GenericContainer,\n549: +\taction string,\n550: +\tsnapshot ifaceSnapshot,\n551: +\tstats *ifaceStatsMetrics,\n552: +) aggregatedEvent {\n553: +\tattributes := interfaceAttributes(&container, snapshot)\n554: +\tif stats != nil {\n555: +\t\tinterfaceStatsAttributes(attributes, *stats)\n556: +\t}\n557: +\n558: +\treturn aggregatedEvent{\n559: +\t\tType: \"interface\", Action: action, ActorID: container.ShortID,\n560: +\t\tActorName: container.Names[0], ActorFullID: container.ID, Attributes: attributes,\n561: +\t}\n562: +}\n563: +\n564: +func c9sInterfaceEvent(\n565: +\tstate *clablabruntime.LabState,\n566: +\tnode clablabruntime.NodeState,\n567: +\taction string,\n568: +\tiface clablabruntime.InterfaceEventData,\n569: +) aggregatedEvent {\n570: +\tkey := state.Namespace + \"/\" + state.Name + \"/\" + node.Name\n571: +\n572: +\treturn aggregatedEventFromLabRuntimeEvent(nil, clablabruntime.Event{\n573: +\t\tType: clablabruntime.EventTypeInterface, Action: action,\n574: +\t\tActorID: key, ActorName: state.Name + \"-\" + node.Name, ActorFullID: key,\n575: +\t\tAttributes: map[string]string{\n576: +\t\t\t\"namespace\": state.Namespace, \"lab\": state.Name, \"node\": node.Name, \"pod\": node.Pod,\n577: +\t\t\t\"origin\": \"clabernetes\",\n578: +\t\t},\n579: +\t\tLab: state, Node: &node, Interface: &iface,\n580: +\t})\n581: +}\n582: +\n583: +// TestInterfaceEventParity compares the interface events of the lab link (linux eth1, SR Linux\n584: +// e1-1 with its alias ethernet-1/1), the management interface and loopback.\n585: +func TestInterfaceEventParity(t *testing.T) {\n586: +\tpath, dockerLab := parityLab(t)\n587: +\n588: +\ttests := []struct {\n589: +\t\tnode string\n590: +\t\tdata clablabruntime.InterfaceEventData\n591: +\t}{\n592: +\t\t{\n593: +\t\t\t\"client\",\n594: +\t\t\tclablabruntime.InterfaceEventData{\n595: +\t\t\t\tName:      \"eth1\",\n596: +\t\t\t\tIndex:     7,\n597: +\t\t\t\tMTU:       9500,\n598: +\t\t\t\tMAC:       \"aa:c1:ab:56:aa:46\",\n599: +\t\t\t\tOperState: \"up\",\n600: +\t\t\t\tType:      \"veth\",\n601: +\t\t\t},\n602: +\t\t},\n603: +\t\t{\"srl1\", clablabruntime.InterfaceEventData{\n604: +\t\t\tName: \"e1-1\", Alias: \"ethernet-1/1\", Index: 7, MTU: 9500, MAC: \"aa:c1:ab:56:aa:47\",\n605: +\t\t\tOperState: \"lower-layer-down\", Type: \"veth\",\n606: +\t\t}},\n607: +\t\t{\n608: +\t\t\t\"client\",\n609: +\t\t\tclablabruntime.InterfaceEventData{\n610: +\t\t\t\tName:      \"eth0\",\n611: +\t\t\t\tIndex:     4,\n612: +\t\t\t\tMTU:       1500,\n613: +\t\t\t\tMAC:       \"02:42:ac:14:14:02\",\n614: +\t\t\t\tOperState: \"up\",\n615: +\t\t\t\tType:      \"veth\",\n616: +\t\t\t},\n617: +\t\t},\n618: +\t\t{\"client\", clablabruntime.InterfaceEventData{\n619: +\t\t\tName: \"lo\", Index: 1, MTU: 65536, OperState: \"unknown\", Type: \"device\",\n620: +\t\t}},\n621: +\t}\n622: +\tfor _, tt := range tests {\n623: +\t\tcontainer := dockerContainer(t, dockerLab, tt.node)\n624: +\t\tstate, nodeState := c9sNode(dockerLab, path, tt.node)\n625: +\t\tsnapshot := ifaceSnapshot{\n626: +\t\t\tIndex: tt.data.Index, Name: tt.data.Name, Alias: tt.data.Alias, MTU: tt.data.MTU,\n627: +\t\t\tMAC: tt.data.MAC, OperState: tt.data.OperState, Type: tt.data.Type,\n628: +\t\t}\n629: +\t\tmetrics := ifaceStatsMetrics{\n630: +\t\t\tRxBytes: 2000, TxBytes: 3000, RxPackets: 20, TxPackets: 30,\n631: +\t\t\tRxBps: 8000, TxBps: 12000, RxPps: 10, TxPps: 15, Interval: 2 * time.Second,\n632: +\t\t}\n633: +\n634: +\t\tfor _, action := range []string{\"snapshot\", \"create\", \"update\", \"delete\", \"stats\"} {\n635: +\t\t\tvar stats *ifaceStatsMetrics\n636: +\t\t\tdata := tt.data\n637: +\t\t\tif action == \"stats\" {\n638: +\t\t\t\tstats = &metrics\n639: +\t\t\t\tdata.Stats = &clablabruntime.InterfaceStats{\n640: +\t\t\t\t\tRxBytes: 2000, TxBytes: 3000, RxPackets: 20, TxPackets: 30,\n641: +\t\t\t\t\tRxBps: 8000, TxBps: 12000, RxPps: 10, TxPps: 15, Interval: 2 * time.Second,\n642: +\t\t\t\t}\n643: +\t\t\t}\n644: +\t\t\tdocker := dockerInterfaceEvent(container, action, snapshot, stats)\n645: +\t\t\tc9s := c9sInterfaceEvent(state, nodeState, action, data)\n646: +\t\t\tassertAttributeParity(t, docker, c9s, nil)\n647: +\n648: +\t\t\tdockerAttributes := mergedEventAttributes(docker)\n649: +\t\t\tgot := mergedEventAttributes(c9s)\n650: +\t\t\tfor key, value := range dockerAttributes {\n651: +\t\t\t\tswitch key {\n652: +\t\t\t\tcase \"id\", \"name\", \"lab\", \"origin\":\n653: +\t\t\t\t\t// the node's own ID, name and lab; the source of the event\n654: +\t\t\t\t\tcontinue\n655: +\t\t\t\t}\n656: +\t\t\t\tif got[key] != value {\n657: +\t\t\t\t\tt.Fatalf(\"%s %s %s: %s = %q, docker %q\", tt.node, tt.data.Name, action, key,\n658: +\t\t\t\t\t\tgot[key], value)\n659: +\t\t\t\t}\n660: +\t\t\t}\n661: +\t\t\tif got[\"name\"] != \"parity-\"+tt.node || got[\"lab\"] != \"parity\" ||\n662: +\t\t\t\tgot[\"id\"] != \"c9s-parity/parity/\"+tt.node {\n663: +\t\t\t\tt.Fatalf(\"%s %s %s: node attributes %v\", tt.node, tt.data.Name, action, got)\n664: +\t\t\t}\n665: +\t\t}\n666: +\t}\n667: +}\n668: +\n669: +// TestInterfaceEventOmitsUnknownValues checks that values the runtime could not read are left\n670: +// out: an index of 0 would make clients take two interfaces for one.\n671: +func TestInterfaceEventOmitsUnknownValues(t *testing.T) {\n672: +\tt.Parallel()\n673: +\n674: +\tstate := &clablabruntime.LabState{Name: \"parity\", Namespace: \"c9s-parity\"}\n675: +\tev := c9sInterfaceEvent(state, clablabruntime.NodeState{Name: \"client\"}, \"stats\",\n676: +\t\tclablabruntime.InterfaceEventData{\n677: +\t\t\tName: \"eth1\", Type: \"veth\",\n678: +\t\t\tStats: &clablabruntime.InterfaceStats{RxBytes: 1, Interval: time.Second},\n679: +\t\t})\n680: +\tgot := mergedEventAttributes(ev)\n681: +\tfor _, key := range []string{\"index\", \"mtu\", \"state\", \"mac\", \"alias\"} {\n682: +\t\tif _, ok := got[key]; ok {\n683: +\t\t\tt.Fatalf(\"%s reported without a value: %v\", key, got)\n684: +\t\t}\n685: +\t}\n686: +\tif got[\"ifname\"] != \"eth1\" || got[\"rx_bytes\"] != \"1\" || got[\"interval_seconds\"] != \"1\" {\n687: +\t\tt.Fatalf(\"stats = %v\", got)\n688: +\t}\n689: +}\n690: +\n691: +func TestLabRuntimeTopologyEventsKeepTheirAttributes(t *testing.T) {\n692: +\tt.Parallel()\n693: +\n694: +\tev := aggregatedEventFromLabRuntimeEvent(nil, clablabruntime.Event{\n695: +\t\tType: \"topology\", Action: \"modified\", ActorID: \"c9s-parity/parity\", ActorName: \"parity\",\n696: +\t\tAttributes: map[string]string{\"lab\": \"parity\", \"state\": \"running\"},\n697: +\t})\n698: +\tif !strings.EqualFold(ev.Attributes[\"lab\"], \"parity\") || len(ev.Attributes) != 2 {\n699: +\t\tt.Fatalf(\"topology event = %+v\", ev)\n700: +\t}\n701: +}\n702: diff --git a/core/events/stream.go b/core/events/stream.go\n703: index a944edc..9ba6c87 100644\n704: --- a/core/events/stream.go\n705: +++ b/core/events/stream.go\n706: @@ -128,11 +128,11 @@ func streamLabRuntimeEvents(ctx context.Context, clab *clabcore.CLab, opts Optio\n707:  \t\t\t\truntimeEvents = nil\n708:  \n709:  \t\t\t\tcontinue\n710:  \t\t\t}\n711:  \n712: -\t\t\tif err := printer(aggregatedEventFromLabRuntimeEvent(ev)); err != nil {\n713: +\t\t\tif err := printer(aggregatedEventFromLabRuntimeEvent(clab, ev)); err != nil {\n714:  \t\t\t\tlog.Debugf(\"failed to write event: %v\", err)\n715:  \t\t\t}\n716:  \t\tcase err, ok := <-runtimeErrs:\n717:  \t\t\tif !ok {\n718:  \t\t\t\truntimeErrs = nil\n719: @@ -168,27 +168,90 @@ func labRuntimeEventStreamRequest(\n720:  \t\tIncludeInterfaceStats: opts.IncludeInterfaceStats,\n721:  \t\tStatsInterval:         opts.StatsInterval,\n722:  \t}\n723:  }\n724:  \n725: -func aggregatedEventFromLabRuntimeEvent(ev clablabruntime.Event) aggregatedEvent {\n726: +// aggregatedEventFromLabRuntimeEvent reports a lab runtime event with the attributes the\n727: +// container runtimes' events have. A container event describes its node with the container\n728: +// record inspect reports for it, the way a Docker event carries the container's labels: as a\n729: +// snapshot like the snapshots of local containers, otherwise with the labels, image,\n730: +// management addresses and ports a Docker event and its enrichment carry. An interface event\n731: +// carries the attributes of the netlink interface events. The runtime's own attributes come on\n732: +// top.\n733: +func aggregatedEventFromLabRuntimeEvent(\n734: +\tclab *clabcore.CLab,\n735: +\tev clablabruntime.Event,\n736: +) aggregatedEvent {\n737:  \tts := ev.Timestamp\n738:  \tif ts.IsZero() {\n739:  \t\tts = time.Now()\n740:  \t}\n741:  \n742: +\tvar attributes map[string]string\n743: +\tswitch {\n744: +\tcase ev.Type == clablabruntime.EventTypeContainer && ev.Lab != nil && ev.Node != nil &&\n745: +\t\tclab != nil:\n746: +\t\tcontainer := clab.LabRuntimeContainer(ev.Lab, *ev.Node)\n747: +\t\tif ev.Attributes[\"origin\"] == clablabruntime.EventOriginSnapshot {\n748: +\t\t\tattributes = aggregatedEventFromContainerSnapshot(&container).Attributes\n749: +\t\t} else {\n750: +\t\t\tattributes = containerAttributes(&container)\n751: +\t\t}\n752: +\tcase ev.Type == clablabruntime.EventTypeInterface && ev.Interface != nil:\n753: +\t\tlab := ev.Attributes[\"lab\"]\n754: +\t\tif ev.Lab != nil {\n755: +\t\t\tlab = ev.Lab.Name\n756: +\t\t}\n757: +\t\tattributes = labRuntimeInterfaceAttributes(lab, ev.ActorName, ev.Interface)\n758: +\t}\n759: +\n760: +\tfor key, value := range ev.Attributes {\n761: +\t\tif attributes == nil {\n762: +\t\t\tattributes = make(map[string]string, len(ev.Attributes))\n763: +\t\t}\n764: +\t\tattributes[key] = value\n765: +\t}\n766: +\n767:  \treturn aggregatedEvent{\n768:  \t\tTimestamp:   ts,\n769:  \t\tType:        ev.Type,\n770:  \t\tAction:      ev.Action,\n771:  \t\tActorID:     ev.ActorID,\n772:  \t\tActorName:   ev.ActorName,\n773:  \t\tActorFullID: ev.ActorFullID,\n774: -\t\tAttributes:  cloneStringMap(ev.Attributes),\n775: +\t\tAttributes:  attributes,\n776:  \t}\n777:  }\n778:  \n779: +// containerAttributes are the attributes a container event reports for a container: its labels\n780: +// and image, which Docker puts on every container event, and the management addresses and\n781: +// ports the events command adds.\n782: +func containerAttributes(container *clabruntime.GenericContainer) map[string]string {\n783: +\tattributes := cloneStringMap(container.Labels)\n784: +\tif attributes == nil {\n785: +\t\tattributes = make(map[string]string)\n786: +\t}\n787: +\n788: +\tif container.Image != \"\" {\n789: +\t\tattributes[\"image\"] = container.Image\n790: +\t}\n791: +\n792: +\tif container.NetworkSettings.IPv4addr != \"\" {\n793: +\t\tattributes[\"mgmt_ipv4\"] = container.GetContainerIPv4()\n794: +\t}\n795: +\n796: +\tif container.NetworkSettings.IPv6addr != \"\" {\n797: +\t\tattributes[\"mgmt_ipv6\"] = container.GetContainerIPv6()\n798: +\t}\n799: +\n800: +\tif ports := exposedPortsAttributeValue(container.Ports); ports != \"\" {\n801: +\t\tattributes[\"ports\"] = ports\n802: +\t}\n803: +\n804: +\treturn attributes\n805: +}\n806: +\n807:  func forwardRuntimeEvents(\n808:  \tctx context.Context,\n809:  \truntime clabruntime.ContainerRuntime,\n810:  \tregistry *netlinkRegistry,\n811:  \truntimeEvents <-chan clabruntime.ContainerEvent,\n812: @@ -437,23 +500,16 @@ func aggregatedEventFromContainerSnapshot(\n813:  \tshort := container.ShortID\n814:  \tif short == \"\" {\n815:  \t\tshort = clabutils.ShortID(container.ID)\n816:  \t}\n817:  \n818: -\tattributes := cloneStringMap(container.Labels)\n819: -\tif attributes == nil {\n820: -\t\tattributes = make(map[string]string)\n821: -\t}\n822: +\tattributes := containerAttributes(container)\n823:  \n824:  \tif _, ok := attributes[\"origin\"]; !ok {\n825:  \t\tattributes[\"origin\"] = \"snapshot\"\n826:  \t}\n827:  \n828: -\tif container.Image != \"\" {\n829: -\t\tattributes[\"image\"] = container.Image\n830: -\t}\n831: -\n832:  \tif container.Status != \"\" {\n833:  \t\tattributes[\"status\"] = container.Status\n834:  \t}\n835:  \n836:  \tif state != \"\" {\n837: @@ -462,22 +518,10 @@ func aggregatedEventFromContainerSnapshot(\n838:  \n839:  \tif container.NetworkName != \"\" {\n840:  \t\tattributes[\"network\"] = container.NetworkName\n841:  \t}\n842:  \n843: -\tif container.NetworkSettings.IPv4addr != \"\" {\n844: -\t\tattributes[\"mgmt_ipv4\"] = container.GetContainerIPv4()\n845: -\t}\n846: -\n847: -\tif container.NetworkSettings.IPv6addr != \"\" {\n848: -\t\tattributes[\"mgmt_ipv6\"] = container.GetContainerIPv6()\n849: -\t}\n850: -\n851: -\tif ports := exposedPortsAttributeValue(container.Ports); ports != \"\" {\n852: -\t\tattributes[\"ports\"] = ports\n853: -\t}\n854: -\n855:  \tif len(attributes) == 0 {\n856:  \t\tattributes = nil\n857:  \t}\n858:  \n859:  \tactorName := firstContainerName(container)\n860: diff --git a/core/labruntime.go b/core/labruntime.go\n861: index eff4bd2..ade83f4 100644\n862: --- a/core/labruntime.go\n863: +++ b/core/labruntime.go\n864: @@ -448,49 +448,68 @@ func (c *CLab) containersFromLabState(\n865:  \t}\n866:  \n867:  \treturn containers\n868:  }\n869:  \n870: +// LabRuntimeContainer describes a lab runtime node as a container record, the way inspect\n871: +// reports it. The events command describes lab runtime nodes with it too.\n872: +func (c *CLab) LabRuntimeContainer(\n873: +\tstate *clablabruntime.LabState,\n874: +\tnode clablabruntime.NodeState,\n875: +) clabruntime.GenericContainer {\n876: +\treturn c.containerFromLabNode(state, node)\n877: +}\n878: +\n879:  func (c *CLab) containerFromLabNode(\n880:  \tstate *clablabruntime.LabState,\n881:  \tnode clablabruntime.NodeState,\n882:  ) clabruntime.GenericContainer {\n883:  \tnodeName := fmt.Sprintf(\"%s-%s\", state.Name, node.Name)\n884: -\tcontainerState := node.State\n885: -\tcontainerStatus := node.State\n886: -\tif containerState == \"\" {\n887: -\t\tcontainerState = state.State\n888: +\tcontainerState, containerStatus := labRuntimeContainerState(state, node)\n889: +\n890: +\ttopologyNode := node.Name\n891: +\tif node.TopologyName != \"\" {\n892: +\t\ttopologyNode = node.TopologyName\n893:  \t}\n894: -\tif node.Ready {\n895: -\t\tcontainerState = \"running\"\n896: -\t\tcontainerStatus = \"healthy\"\n897: +\tif c.Config.Topology != nil {\n898: +\t\ttopologyNode = c.topologyNodeName(topologyNode)\n899:  \t}\n900:  \n901:  \tlabels := map[string]string{\n902:  \t\tclabconstants.Containerlab: state.Name,\n903: -\t\tclabconstants.NodeName:     node.Name,\n904: +\t\tclabconstants.NodeName:     topologyNode,\n905:  \t\tclabconstants.LongName:     nodeName,\n906:  \t\tclabconstants.TopoFile:     labRuntimeTopologyPath(c, state),\n907:  \t}\n908:  \n909:  \tvar image string\n910:  \tif c.Config.Topology != nil {\n911: -\t\ttopologyNode := c.topologyNodeName(node.Name)\n912:  \t\tlabels[clabconstants.NodeKind] = c.Config.Topology.GetNodeKind(topologyNode)\n913:  \t\timage = c.Config.Topology.GetNodeImage(topologyNode)\n914: -\n915: -\t\tif group := c.Config.Topology.GetNodeGroup(topologyNode); group != \"\" {\n916: -\t\t\tlabels[clabconstants.NodeGroup] = group\n917: -\t\t}\n918:  \t}\n919:  \tif node.Kind != \"\" {\n920:  \t\tlabels[clabconstants.NodeKind] = node.Kind\n921:  \t}\n922:  \tif node.Image != \"\" {\n923:  \t\timage = node.Image\n924:  \t}\n925:  \n926: +\t// The node's type and group: from the loaded topology's node, with the kind's defaults the\n927: +\t// local runtimes report too, otherwise as the topology set them on the runtime's node.\n928: +\tnodeType, group := node.Type, node.Group\n929: +\tif topologyNodeConfig, ok := c.Nodes[topologyNode]; ok {\n930: +\t\tnodeType, group = topologyNodeConfig.Config().NodeType, topologyNodeConfig.Config().Group\n931: +\t} else if c.Config.Topology != nil && group == \"\" {\n932: +\t\tgroup = c.Config.Topology.GetNodeGroup(topologyNode)\n933: +\t}\n934: +\tif nodeType != \"\" {\n935: +\t\tlabels[clabconstants.NodeType] = nodeType\n936: +\t}\n937: +\tif group != \"\" {\n938: +\t\tlabels[clabconstants.NodeGroup] = group\n939: +\t}\n940: +\n941:  \tif state.Owner != \"\" {\n942:  \t\tlabels[clabconstants.Owner] = state.Owner\n943:  \t} else if c.customOwner != \"\" {\n944:  \t\tlabels[clabconstants.Owner] = c.customOwner\n945:  \t}\n946: @@ -507,10 +526,11 @@ func (c *CLab) containerFromLabNode(\n947:  \t\tState:           containerState,\n948:  \t\tStatus:          containerStatus,\n949:  \t\tLabels:          labels,\n950:  \t\tNetworkName:     state.Namespace,\n951:  \t\tNetworkSettings: managementAddress(node),\n952: +\t\tPorts:           labRuntimePorts(node.ExposedPorts),\n953:  \t\tWorkload: &clabtypes.LabRuntimeWorkload{\n954:  \t\t\tNamespace:           state.Namespace,\n955:  \t\t\tPod:                 node.Pod,\n956:  \t\t\tContainer:           node.Container,\n957:  \t\t\tNodeUID:             node.NodeUID,\n958: @@ -518,10 +538,60 @@ func (c *CLab) containerFromLabNode(\n959:  \t\t\tLoadBalancerAddress: node.LoadBalancerAddress,\n960:  \t\t},\n961:  \t}\n962:  }\n963:  \n964: +// labRuntimeContainerState is a lab runtime node's state and status in the vocabulary of the\n965: +// container runtimes: state created, running or exited; status healthy or \"health: starting\"\n966: +// for a running node, as inspect shortens a Docker status line with a healthcheck, Created or\n967: +// Exited otherwise. A runtime that reports no container state keeps its own state.\n968: +func labRuntimeContainerState(\n969: +\tstate *clablabruntime.LabState,\n970: +\tnode clablabruntime.NodeState,\n971: +) (string, string) {\n972: +\tswitch node.ContainerState {\n973: +\tcase clablabruntime.ContainerStateRunning:\n974: +\t\tif node.Health == clablabruntime.ContainerHealthHealthy {\n975: +\t\t\treturn node.ContainerState, \"healthy\"\n976: +\t\t}\n977: +\n978: +\t\treturn node.ContainerState, \"health: starting\"\n979: +\tcase clablabruntime.ContainerStateCreated:\n980: +\t\treturn node.ContainerState, \"Created\"\n981: +\tcase clablabruntime.ContainerStateExited:\n982: +\t\treturn node.ContainerState, \"Exited\"\n983: +\t}\n984: +\n985: +\tif node.Ready {\n986: +\t\treturn clablabruntime.ContainerStateRunning, \"healthy\"\n987: +\t}\n988: +\tif node.State == \"\" {\n989: +\t\treturn state.State, \"\"\n990: +\t}\n991: +\n992: +\treturn node.State, node.State\n993: +}\n994: +\n995: +// labRuntimePorts reports the ports a lab runtime exposes for a node as the ports a container\n996: +// exposes without publishing them on the host: the node is reached through the runtime (a\n997: +// Service, a port-forward), never on a port of this machine.\n998: +func labRuntimePorts(ports []clablabruntime.ExposedPort) []*clabtypes.GenericPortBinding {\n999: +\tif len(ports) == 0 {\n1000: +\t\treturn nil\n1001: +\t}\n1002: +\n1003: +\tbindings := make([]*clabtypes.GenericPortBinding, 0, len(ports))\n1004: +\tfor _, port := range ports {\n1005: +\t\tbindings = append(bindings, &clabtypes.GenericPortBinding{\n1006: +\t\t\tContainerPort: port.Port,\n1007: +\t\t\tProtocol:      port.Protocol,\n1008: +\t\t})\n1009: +\t}\n1010: +\n1011: +\treturn bindings\n1012: +}\n1013: +\n1014:  // labRuntimeContainerID is the ID of a lab runtime node: <namespace>/<lab>/<node>.\n1015:  func labRuntimeContainerID(namespace, lab, node string) string {\n1016:  \treturn fmt.Sprintf(\"%s/%s/%s\", namespace, lab, node)\n1017:  }\n1018:  \n1019: diff --git a/core/labruntime_gaps_test.go b/core/labruntime_gaps_test.go\n1020: index 791f068..87c0251 100644\n1021: --- a/core/labruntime_gaps_test.go\n1022: +++ b/core/labruntime_gaps_test.go\n1023: @@ -114,5 +114,50 @@ func TestCheckConnectivitySkipsLocalRuntimesForLabRuntimes(t *testing.T) {\n1024:  \tc := &CLab{LabRuntime: &recordingDestroyLabRuntime{}}\n1025:  \tif err := c.CheckConnectivity(context.Background()); err != nil {\n1026:  \t\tt.Fatalf(\"CheckConnectivity() = %v, want nil for a lab runtime\", err)\n1027:  \t}\n1028:  }\n1029: +\n1030: +// TestContainerFromLabNodeReportsTheTopologyNode checks the labels a lab runtime node reports\n1031: +// without its topology file: the node name the topology spells, the type and group the\n1032: +// topology set, the recorded topology file, and its ports as unpublished container ports.\n1033: +func TestContainerFromLabNodeReportsTheTopologyNode(t *testing.T) {\n1034: +\tt.Parallel()\n1035: +\n1036: +\tc := &CLab{Config: &Config{Name: \"lab1\"}, TopoPaths: &clabtypes.TopoPaths{}}\n1037: +\tcontainer := c.containerFromLabNode(\n1038: +\t\t&clablabruntime.LabState{\n1039: +\t\t\tName: \"lab1\", Namespace: \"c9s-lab1\", TopologyPath: \"/home/alice/lab1.clab.yml\",\n1040: +\t\t},\n1041: +\t\tclablabruntime.NodeState{\n1042: +\t\t\tName: \"r1\", TopologyName: \"R1\", Kind: \"nokia_srlinux\", Type: \"ixr-h2\",\n1043: +\t\t\tGroup: \"spines\", ContainerState: \"running\", Health: \"healthy\",\n1044: +\t\t\tExposedPorts: []clablabruntime.ExposedPort{\n1045: +\t\t\t\t{Port: 57400, ExposePort: 57400, Protocol: \"tcp\"},\n1046: +\t\t\t},\n1047: +\t\t},\n1048: +\t)\n1049: +\n1050: +\twant := map[string]string{\n1051: +\t\t\"clab-node-name\":     \"R1\",\n1052: +\t\t\"clab-node-longname\": \"lab1-r1\",\n1053: +\t\t\"clab-node-kind\":     \"nokia_srlinux\",\n1054: +\t\t\"clab-node-type\":     \"ixr-h2\",\n1055: +\t\t\"clab-node-group\":    \"spines\",\n1056: +\t\t\"clab-topo-file\":     \"/home/alice/lab1.clab.yml\",\n1057: +\t\t\"containerlab\":       \"lab1\",\n1058: +\t}\n1059: +\tfor key, value := range want {\n1060: +\t\tif container.Labels[key] != value {\n1061: +\t\t\tt.Fatalf(\"label %s = %q, want %q (%v)\", key, container.Labels[key], value,\n1062: +\t\t\t\tcontainer.Labels)\n1063: +\t\t}\n1064: +\t}\n1065: +\tif container.State != \"running\" || container.Status != \"healthy\" ||\n1066: +\t\tcontainer.Names[0] != \"lab1-r1\" {\n1067: +\t\tt.Fatalf(\"container = %s %s %v\", container.State, container.Status, container.Names)\n1068: +\t}\n1069: +\tif len(container.Ports) != 1 || container.Ports[0].ContainerPort != 57400 ||\n1070: +\t\tcontainer.Ports[0].HostPort != 0 || container.Ports[0].Protocol != \"tcp\" {\n1071: +\t\tt.Fatalf(\"ports = %+v\", container.Ports)\n1072: +\t}\n1073: +}\n1074: diff --git a/docs/cmd/events.md b/docs/cmd/events.md\n1075: index 92d51ed..23d9eef 100644\n1076: --- a/docs/cmd/events.md\n1077: +++ b/docs/cmd/events.md\n1078: @@ -75,19 +75,25 @@ Currently supported runtimes:\n1079:  \n1080:  - `docker`\n1081:  - `c9s`\n1082:  \n1083:  With `--runtime c9s`, events are backed by kubernetes watches for Clabernetes\n1084: -`Topology` and `Node` resources and labeled Pods. Interface state (`interface up`\n1085: -and `interface down` events) and statistics are sampled inside the device\n1086: -containers, not through local host netlink. The stream covers every namespace by\n1087: -default; `--namespace` (or `CLAB_KUBE_NAMESPACE`) limits it to one namespace,\n1088: -and `-t`/`--name` to one lab. With Docker and Podman the lab selection is ignored\n1089: -and every lab is streamed.\n1090: +`Topology` and `Node` resources and labeled Pods. They use the actions and\n1091: +attributes of the Docker runtime: a node is a container (`create`, `start`,\n1092: +`kill`, `stop`, `die`, `destroy`, `health_status: …`) described by the same\n1093: +labels, and the interface events (`snapshot`, `create`, `update`, `delete`,\n1094: +`stats`) report the node's lab link interfaces, `eth0` and `lo` under the names\n1095: +a Docker container of the node has. Interface state and statistics are sampled\n1096: +inside the device containers, not through local host netlink. The stream covers\n1097: +every namespace by default; `--namespace` (or `CLAB_KUBE_NAMESPACE`) limits it\n1098: +to one namespace, and `-t`/`--name` to one lab. With Docker and Podman the lab\n1099: +selection is ignored and every lab is streamed. The\n1100: +[c9s runtime manual](../manual/clabernetes/runtime.md#events) lists the\n1101: +attributes and the few Docker attributes c9s has no equivalent for.\n1102:  \n1103:  Runtimes that do not implement the `events` API, or are not yet supported by Containerlab, will exit with an explanatory error.\n1104:  \n1105:  ## See also\n1106:  \n1107:  - [`inspect interfaces`](inspect/interfaces.md) – produces a point-in-time view of the same interface details that `events` reports continuously.\n1108: -- [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md) - explains how c9s events differ from Docker events.\n1109: +- [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md#events) - describes c9s events and how they map onto Docker events.\n1110:  - `docker events` – the raw runtime feed that Containerlab builds upon.\n1111: diff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md\n1112: index 2354dc1..43fbb9a 100644\n1113: --- a/docs/cmd/inspect/interfaces.md\n1114: +++ b/docs/cmd/inspect/interfaces.md\n1115: @@ -3,11 +3,11 @@\n1116:  ### Description\n1117:  \n1118:  The `inspect interfaces` subcommand provides information about the network interfaces of deployed nodes of a deployed lab.\n1119:  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.\n1120:  \n1121: -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.\n1122: +With the [c9s runtime](../../manual/clabernetes/runtime.md#interface-events), the listing covers the interfaces a Docker container of the node has: the lab link interfaces of each running node (the ones [`capture`](../capture.md) accepts) with the alias the topology used, the management interface `eth0` and the loopback `lo`, with the MAC address, index, MTU and operational state read in the node's device container. The pod's own interfaces are not listed. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields and values (`veth`/`device`, netlink state names) are the same as with Docker. `eth0` and `lo` cannot be captured on c9s.\n1123:  \n1124:  ### Usage\n1125:  \n1126:  `containerlab [global-flags] inspect interfaces [local-flags]`\n1127:  \n1128: diff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md\n1129: index 8174c98..751ccf1 100644\n1130: --- a/docs/manual/clabernetes/runtime.md\n1131: +++ b/docs/manual/clabernetes/runtime.md\n1132: @@ -543,10 +543,45 @@ port-forward without working out the pod themselves:\n1133:  \n1134:  These fields are only present for lab runtimes; Docker and Podman output is\n1135:  unchanged. Fields without a value, such as `pod` for a stopped node, are left\n1136:  out. `--details` keeps printing the raw records.\n1137:  \n1138: +The other fields mean what they mean for Docker and Podman, so clients can treat\n1139: +c9s nodes like containers:\n1140: +\n1141: +| Field | c9s value |\n1142: +|---|---|\n1143: +| `state` | `created` while the node's pod is scheduled and prepared, `running` once its device containers run, `exited` once the node is stopped (or its pod ends or is replaced) |\n1144: +| `status` | `healthy` once the node is ready or its device containers are, `health: starting` while a running device boots, `Created`, `Exited` |\n1145: +| `labPath`, `absLabPath` | the topology file the lab was deployed from (see below) |\n1146: +| `name` | `<lab>-<node>`, the name events use as `actor_name` |\n1147: +\n1148: +### Topology file\n1149: +\n1150: +A deploy records the absolute path of the topology file, on the machine that\n1151: +deployed it, in the annotation `containerlab.dev/topo-file`:\n1152: +\n1153: +- with a `Topology` resource, on the `Topology`; every deploy records the file\n1154: +  it read\n1155: +- with `--no-topology-cr`, on every `Node`. clabernetes copies a Node's\n1156: +  annotations into its pod, so a Node keeps the file it was created from: a\n1157: +  later deploy from another file does not change it and does not restart the\n1158: +  node. Destroy and deploy again to record a new file.\n1159: +\n1160: +`inspect` reports the recorded file as `labPath` and `absLabPath` (shortened\n1161: +for the table, as for Docker), and events as `clab-topo-file`, so a client\n1162: +matches a running lab to its file the same way for every runtime. The file is a\n1163: +path on the deploying machine; a client on another machine cannot assume it\n1164: +exists there.\n1165: +\n1166: +A lab that containerlab did not deploy from a file, for example one applied from\n1167: +`deploy --emit-crs` output with `kubectl` (the emitted manifests do not carry\n1168: +the annotation), has no recorded file. It reports where its definition lives in\n1169: +the cluster: `k8s://<namespace>/topologies/<lab>`, or\n1170: +`k8s://<namespace>/labs/<lab>` without a `Topology` resource. With `-t`,\n1171: +`inspect` reports the given file.\n1172: +\n1173:  Useful kubernetes checks for the same state are:\n1174:  \n1175:  ```bash\n1176:  kubectl -n <namespace> get node.c9s.run,link.c9s.run,nodeprofile.c9s.run,deploy,pod,svc,cm,pvc \\\n1177:    -l c9s.run/topologyOwner=<lab>\n1178: @@ -697,12 +732,18 @@ stopped node is started by the same patch.\n1179:  What a stopped node keeps and loses:\n1180:  \n1181:  - The `Node`, its Services, PersistentVolumeClaims and Links stay. Saved\n1182:    configuration survives a stop and start.\n1183:  - Its links go carrier-down on every peer, like an unplugged cable;\n1184: -  `events` reports them as interface `down` events.\n1185: -- `inspect` shows the node as `stopped` (`stopping` while its Pod terminates).\n1186: +  `events` reports an interface `update` with state `lower-layer-down` on the\n1187: +  peers, and deletes the stopped node's interfaces.\n1188: +- `inspect` shows the node as `exited` with status `Exited`.\n1189: +- `events` reports the container actions Docker reports for `containerlab stop`\n1190: +  and `start`: `kill`, `stop` and `die` when the node's pod goes, `start` when\n1191: +  its new pod runs, then `health_status: starting` and\n1192: +  `health_status: healthy` as the device boots. A restart reports `kill`,\n1193: +  `stop`, `die` and `start`.\n1194:  - clabernetes keeps a running peer of a stopped node `notready`: its\n1195:    connectivity sidecar waits for the far end of the wire. Deploy, apply, start\n1196:    and restart treat such a node as settled when its containers are ready, and\n1197:    log `link peers stopped: <nodes>` instead of waiting for it.\n1198:  \n1199: @@ -754,12 +795,14 @@ For example:\n1200:  files, the c9s runtime has nothing to copy for that node.\n1201:  ///\n1202:  \n1203:  ## Events\n1204:  \n1205: -The c9s runtime can stream Node, Topology, pod, interface state and\n1206: -interface-stat events:\n1207: +The c9s runtime streams container, interface state and interface-stat events\n1208: +with the actions and attributes the Docker runtime reports, so a client that\n1209: +reads Docker events reads c9s events the same way. It also streams `topology`\n1210: +events, which only c9s has:\n1211:  \n1212:  ```bash\n1213:  containerlab --runtime c9s events --format json\n1214:  containerlab --runtime c9s events --initial-state\n1215:  containerlab --runtime c9s events --interface-stats --format json\n1216: @@ -772,10 +815,12 @@ watches:\n1217:  \n1218:  - c9s `Node` resources carrying `c9s.run/topologyOwner`\n1219:  - `Topology` resources\n1220:  - Pods labeled with `c9s.run/topologyOwner`\n1221:  \n1222: +and reads a lab again whenever one of them changes.\n1223: +\n1224:  What the stream covers:\n1225:  \n1226:  | Invocation | Scope |\n1227:  |---|---|\n1228:  | `events` | every namespace |\n1229: @@ -783,65 +828,155 @@ What the stream covers:\n1230:  | `events -t <topo>` or `events --name <lab>` | that lab, in its namespace (`c9s-<lab>`, or the namespace override) |\n1231:  \n1232:  An identity whose RBAC only covers one namespace needs one of the scoped forms;\n1233:  watching every namespace requires cluster-wide `list` and `watch`.\n1234:  \n1235: -With `--initial-state`, the stream starts with synthetic events for the current\n1236: -c9s node state and the state of every interface, then continues with live\n1237: -watches.\n1238: +### Container events\n1239: +\n1240: +Each node is reported as a container. Its state follows its pod: `created`\n1241: +while the pod is scheduled and prepared, `running` once the device containers\n1242: +run, `exited` once the node is stopped, or its pod ends or is replaced. A change\n1243: +is reported with the actions Docker reports for the same change:\n1244: +\n1245: +| Change | Actions |\n1246: +|---|---|\n1247: +| the node appears (deploy, apply) | `create`, then `start` once its pod runs |\n1248: +| the device boots, is ready, is not ready anymore | `health_status: starting`, `health_status: healthy`, `health_status: unhealthy` |\n1249: +| `stop` | `kill`, `stop`, `die` |\n1250: +| `start` | `start` |\n1251: +| `restart`, or the pod is replaced | `kill`, `stop`, `die`, `start` |\n1252: +| the node is removed (destroy, apply) | `kill`, `die` (when it ran), `destroy` |\n1253: +\n1254: +With `--initial-state`, the stream starts with one event per node whose action\n1255: +is its state (`running`, `exited`, `created`) and `origin` `snapshot`, like the\n1256: +snapshot of a Docker container.\n1257:  \n1258: -Container events use the node's `<namespace>/<lab>/<node>` ID as actor, the\n1259: -`container_id` inspect reports.\n1260: +Every container event describes the node with the attributes of a Docker\n1261: +container event, taken from the record `inspect` reports for the node:\n1262: +\n1263: +```json\n1264: +{\n1265: +  \"timestamp\": \"2026-10-27T10:15:02.123456789Z\",\n1266: +  \"type\": \"container\",\n1267: +  \"action\": \"start\",\n1268: +  \"actor_id\": \"c9s-clos/clos/srl1\",\n1269: +  \"actor_name\": \"clos-srl1\",\n1270: +  \"actor_full_id\": \"c9s-clos/clos/srl1\",\n1271: +  \"attributes\": {\n1272: +    \"containerlab\": \"clos\",\n1273: +    \"clab-node-name\": \"srl1\",\n1274: +    \"clab-node-longname\": \"clos-srl1\",\n1275: +    \"clab-node-kind\": \"nokia_srlinux\",\n1276: +    \"clab-node-type\": \"ixr-d2l\",\n1277: +    \"clab-topo-file\": \"/home/user/clos.clab.yml\",\n1278: +    \"clab-owner\": \"alice\",\n1279: +    \"image\": \"ghcr.io/nokia/srlinux\",\n1280: +    \"mgmt_ipv4\": \"172.20.20.11/24\",\n1281: +    \"ports\": \"22/tcp;57400/tcp\",\n1282: +    \"state\": \"running\",\n1283: +    \"id\": \"c9s-clos/clos/srl1\",\n1284: +    \"name\": \"clos-srl1\",\n1285: +    \"lab\": \"clos\",\n1286: +    \"node\": \"srl1\",\n1287: +    \"namespace\": \"c9s-clos\",\n1288: +    \"pod\": \"srl1-7d9c6b5f4-x2k8p\"\n1289: +  }\n1290: +}\n1291: +```\n1292: +\n1293: +- The actor ID is the node's `<namespace>/<lab>/<node>` ID, the `container_id`\n1294: +  inspect reports, and `actor_name` and `name` are the inspect `name`.\n1295: +- `clab-node-name` is the node name as the topology spells it.\n1296: +- `clab-topo-file` is the file the lab was deployed from (see\n1297: +  [Topology file](#topology-file)).\n1298: +- `state` is the container state after the event: `created`, `running` or\n1299: +  `exited`. Docker leaves it to the client to derive it from the action; c9s\n1300: +  reports it on every container event.\n1301: +- `ports` lists the node's exposed ports without a host binding: they are\n1302: +  reached through the node's Service or a port-forward, not on a port of the\n1303: +  local machine.\n1304: +- `kill` carries `signal` `15`; Kubernetes stops containers with SIGTERM.\n1305: +- `create` can come before the controller has allocated the node's management\n1306: +  address and Service, so it may lack `mgmt_ipv4`, `mgmt_ipv6` and `ports`;\n1307: +  the following events carry them.\n1308: +- `namespace`, `lab`, `node` and `pod` are c9s attributes on top.\n1309: +\n1310: +Docker attributes c9s does not report: `scope`, `clab-mgmt-net-bridge` (no\n1311: +Docker bridge), `clab-node-lab-dir` (a c9s lab has no lab directory on the\n1312: +deploying machine; node state lives in the cluster), and `exitCode` and\n1313: +`execDuration` on `die`. `clab-node-type` and `clab-node-group` are reported\n1314: +when the topology sets them, and with `-t` also a kind's default type; read by\n1315: +`--name` alone, a default type such as SR Linux's `ixr-d2l` is not known.\n1316:  \n1317:  ### Interface events\n1318:  \n1319:  Containerlab samples the interfaces of every running node by exec into its\n1320:  device container. One exec per node and interval reads `/proc/net/dev` and\n1321:  `/sys/class/net/*/operstate` (with index, MTU, MAC address, flags and alias).\n1322: -All containers of a device pod share one network namespace, so the samples\n1323: -cover the node's pod interfaces.\n1324:  \n1325: -Interface state events are always streamed. They use the same schema as the\n1326: -interface events of the local runtimes, with the operational state as action:\n1327: +It reports the interfaces a Docker container of the same node kind has, named\n1328: +as in that container:\n1329: +\n1330: +- the node's lab link interfaces, with the names and aliases clabwire lists for\n1331: +  them (`containerlab capture --list`): `eth1` for a linux node, `e1-1` with\n1332: +  alias `ethernet-1/1` for SR Linux, so a client finds a link's interface by\n1333: +  the endpoint name in the topology or its alias\n1334: +- the management interface `eth0`\n1335: +- the loopback `lo`\n1336: +\n1337: +The pod's own interfaces (the pod network interface `c9s0`, clabernetes'\n1338: +interposition interfaces `c9sr0` and `c9sm0`, and the link transport interfaces\n1339: +`c9ss*`) are not reported, and neither are the aliases clabernetes sets for its\n1340: +own use (`c9s:…`).\n1341: +\n1342: +Interface state events are always streamed, with the actions and attributes of\n1343: +the local runtimes' netlink events:\n1344:  \n1345:  ```json\n1346:  {\n1347:    \"timestamp\": \"2026-10-27T10:15:02.123456789Z\",\n1348:    \"type\": \"interface\",\n1349: -  \"action\": \"down\",\n1350: +  \"action\": \"update\",\n1351:    \"actor_id\": \"c9s-clos/clos/srl1\",\n1352:    \"actor_name\": \"clos-srl1\",\n1353: -  \"actor_full_id\": \"srl1-7d9c6b5f4-x2k8p\",\n1354: +  \"actor_full_id\": \"c9s-clos/clos/srl1\",\n1355:    \"attributes\": {\n1356:      \"ifname\": \"e1-1\",\n1357: -    \"state\": \"lowerlayerdown\",\n1358: +    \"alias\": \"ethernet-1/1\",\n1359: +    \"state\": \"lower-layer-down\",\n1360: +    \"type\": \"veth\",\n1361:      \"index\": \"7\",\n\n(Output capped at 50 KB. Showing lines 1-1361. Use offset=1362 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "diff --git a/core/events/netlink.go b/core/events/netlink.go\nindex 150b71d..1654a4a 100644\n--- a/core/events/netlink.go\n+++ b/core/events/netlink.go\n@@ -12,10 +12,11 @@ import (\n \n \t\"github.com/charmbracelet/log\"\n \tgotc \"github.com/florianl/go-tc\"\n \tclabconstants \"github.com/srl-labs/containerlab/constants\"\n \tclabcore \"github.com/srl-labs/containerlab/core\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n \tclablinks \"github.com/srl-labs/containerlab/links\"\n \tclabnetem \"github.com/srl-labs/containerlab/netem\"\n \tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n \tclabutils \"github.com/srl-labs/containerlab/utils\"\n \t\"github.com/vishvananda/netlink\"\n@@ -642,31 +643,99 @@ func containerLabel(container *clabruntime.GenericContainer) string {\n \t}\n \n \treturn container.Labels[clabconstants.Containerlab]",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "diff --git a/core/events/netlink.go b/core/events/netlink.go\nindex 150b71d..1654a4a 100644\n--- a/core/events/netlink.go\n+++ b/core/events/netlink.go\n@@ -12,10 +12,11 @@ import (\n \n \t\"github.com/charmbracelet/log\"\n \tgotc \"github.com/florianl/go-tc\"\n \tclabconstants \"github.com/srl-labs/containerlab/constants\"\n \tclabcore \"github.com/srl-labs/containerlab/core\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n \tclablinks \"github.com/srl-labs/containerlab/links\"\n \tclabnetem \"github.com/srl-labs/containerlab/netem\"\n \tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n \tclabutils \"github.com/srl-labs/containerlab/utils\"\n \t\"github.com/vishvananda/netlink\"\n@@ -642,31 +643,99 @@ func containerLabel(container *clabruntime.GenericContainer) string {\n \t}\n \n \treturn container.Labels[clabconstants.Containerlab]\n }\n \n-func interfaceAttributes(\n-\tcontainer *clabruntime.GenericContainer,\n-\tsnapshot ifaceSnapshot,\n-) map[string]string {\n+// interfaceSnapshotAttributes are the attributes every interface event reports for the\n+// interface itself.\n+func interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {\n \tattributes := map[string]string{\n \t\t\"ifname\": snapshot.Name,\n \t\t\"index\":  strconv.Itoa(snapshot.Index),\n \t\t\"mtu\":    strconv.Itoa(snapshot.MTU),\n \t\t\"state\":  snapshot.OperState,\n \t\t\"type\":   snapshot.Type,\n-\t\t\"origin\": \"netlink\",\n \t}\n \n \tif snapshot.Alias != \"\" {\n \t\tattributes[\"alias\"] = snapshot.Alias\n \t}\n \n \tif snapshot.MAC != \"\" {\n \t\tattributes[\"mac\"] = snapshot.MAC\n \t}\n \n+\treturn attributes\n+}\n+\n+// interfaceStatsAttributes adds the counters and rates of a stats event.\n+func interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {\n+\tattributes[\"rx_bytes\"] = strconv.FormatUint(metrics.RxBytes, 10)\n+\tattributes[\"tx_bytes\"] = strconv.FormatUint(metrics.TxBytes, 10)\n+\tattributes[\"rx_packets\"] = strconv.FormatUint(metrics.RxPackets, 10)\n+\tattributes[\"tx_packets\"] = strconv.FormatUint(metrics.TxPackets, 10)\n+\tattributes[\"rx_bps\"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)\n+\tattributes[\"tx_bps\"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)\n+\tattributes[\"rx_pps\"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)\n+\tattributes[\"tx_pps\"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)\n+\tattributes[\"interval_seconds\"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)\n+}\n+\n+// labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those\n+// of the netlink interface events, for the node the runtime runs. Values the runtime could not\n+// read (no index or MTU without a shell in the node) are left out rather than reported as 0.\n+func labRuntimeInterfaceAttributes(\n+\tlab, name string,\n+\tiface *clablabruntime.InterfaceEventData,\n+) map[string]string {\n+\tattributes := interfaceSnapshotAttributes(ifaceSnapshot{\n+\t\tIndex:     iface.Index,\n+\t\tName:      iface.Name,\n+\t\tAlias:     iface.Alias,\n+\t\tMTU:       iface.MTU,\n+\t\tMAC:       iface.MAC,\n+\t\tOperState: iface.OperState,\n+\t\tType:      iface.Type,\n+\t})\n+\tif iface.Index <= 0 {\n+\t\tdelete(attributes, \"index\")\n+\t}\n+\tif iface.MTU <= 0 {\n+\t\tdelete(attributes, \"mtu\")\n+\t}\n+\n+\tif lab != \"\" {\n+\t\tattributes[\"lab\"] = lab\n+\t}\n+\tif name != \"\" {\n+\t\tattributes[\"name\"] = name\n+\t}\n+\n+\tif stats := iface.Stats; stats != nil {\n+\t\tinterfaceStatsAttributes(attributes, ifaceStatsMetrics{\n+\t\t\tRxBytes:   stats.RxBytes,\n+\t\t\tTxBytes:   stats.TxBytes,\n+\t\t\tRxPackets: stats.RxPackets,\n+\t\t\tTxPackets: stats.TxPackets,\n+\t\t\tRxBps:     stats.RxBps,\n+\t\t\tTxBps:     stats.TxBps,\n+\t\t\tRxPps:     stats.RxPps,\n+\t\t\tTxPps:     stats.TxPps,\n+\t\t\tInterval:  stats.Interval,\n+\t\t})\n+\t}\n+\n+\treturn attributes\n+}\n+\n+func interfaceAttributes(\n+\tcontainer *clabruntime.GenericContainer,\n+\tsnapshot ifaceSnapshot,\n+) map[string]string {\n+\tattributes := interfaceSnapshotAttributes(snapshot)\n+\tattributes[\"origin\"] = \"netlink\"\n+\n \tif lab := containerLabel(container); lab != \"\" {\n \t\tattributes[\"lab\"] = lab\n \t}\n \n \tif name := firstContainerName(container); name != \"\" {\n@@ -811,19 +880,11 @@ func (r *netlinkRegistry) emitInterfaceStatsEvent(\n \tif !r.includeStats || container == nil || !snapshot.HasStats {\n \t\treturn\n \t}\n \n \tattributes := interfaceAttributes(container, snapshot)\n-\tattributes[\"rx_bytes\"] = strconv.FormatUint(metrics.RxBytes, 10)\n-\tattributes[\"tx_bytes\"] = strconv.FormatUint(metrics.TxBytes, 10)\n-\tattributes[\"rx_packets\"] = strconv.FormatUint(metrics.RxPackets, 10)\n-\tattributes[\"tx_packets\"] = strconv.FormatUint(metrics.TxPackets, 10)\n-\tattributes[\"rx_bps\"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)\n-\tattributes[\"tx_bps\"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)\n-\tattributes[\"rx_pps\"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)\n-\tattributes[\"tx_pps\"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)\n-\tattributes[\"interval_seconds\"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)\n+\tinterfaceStatsAttributes(attributes, metrics)\n \n \tevent := aggregatedEvent{\n \t\tTimestamp:   metrics.Timestamp,\n \t\tType:        \"interface\",\n \t\tAction:      \"stats\",\ndiff --git a/core/events/parity_test.go b/core/events/parity_test.go\nnew file mode 100644\nindex 0000000..855365b\n--- /dev/null\n+++ b/core/events/parity_test.go\n@@ -0,0 +1,553 @@\n+package events\n+\n+import (\n+\t\"context\"\n+\t\"os\"\n+\t\"path/filepath\"\n+\t\"sort\"\n+\t\"strings\"\n+\t\"testing\"\n+\t\"time\"\n+\n+\tdockerEvents \"github.com/docker/docker/api/types/events\"\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+\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n+\tclabtypes \"github.com/srl-labs/containerlab/types\"\n+\tclabutils \"github.com/srl-labs/containerlab/utils\"\n+)\n+\n+// These tests build the events the Docker runtime and the c9s lab runtime report for the same\n+// node and compare them: every attribute a Docker event carries is in the c9s event, with the\n+// same meaning, apart from the ones c9s has no equivalent for.\n+\n+// dockerOnlyContainerAttributes are the Docker container event attributes c9s has no\n+// equivalent for: the Docker event scope, the Docker management bridge, and the exit code and\n+// run time of a container process, which Kubernetes does not keep once the pod is gone.\n+var dockerOnlyContainerAttributes = map[string]bool{ //nolint:gochecknoglobals\n+\t\"scope\":                     true,\n+\tclabconstants.NodeMgmtNetBr: true,\n+\tclabconstants.NodeLabDir:    true,\n+\t\"exitCode\":                  true,\n+\t\"execDuration\":              true,\n+}\n+\n+const parityTopology = `name: parity\n+mgmt:\n+  network: clab\n+topology:\n+  nodes:\n+    client:\n+      kind: linux\n+      image: ghcr.io/srl-labs/network-multitool\n+    srl1:\n+      kind: nokia_srlinux\n+      image: ghcr.io/nokia/srlinux:25.10\n+  links:\n+    - endpoints: [\"client:eth1\", \"srl1:ethernet-1/1\"]\n+`\n+\n+// parityLab loads the topology as a Docker deploy does and returns its labels per node.\n+func parityLab(t *testing.T) (string, *clabcore.CLab) {\n+\tt.Helper()\n+\n+\tdir := t.TempDir()\n+\tpath := filepath.Join(dir, \"parity.clab.yml\")\n+\tif err := os.WriteFile(path, []byte(parityTopology), 0o600); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tt.Setenv(\"USER\", \"alice\")\n+\tt.Setenv(\"SUDO_USER\", \"\")\n+\n+\tc, err := clabcore.NewContainerLab(clabcore.WithTopoPath(path, nil))\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\n+\treturn path, c\n+}\n+\n+// fakeDockerRuntime answers the container lookup the events command makes for a Docker event.\n+type fakeDockerRuntime struct {\n+\tclabruntime.ContainerRuntime\n+\tcontainer clabruntime.GenericContainer\n+}\n+\n+func (f *fakeDockerRuntime) ListContainers(\n+\tcontext.Context,\n+\t[]*clabtypes.GenericFilter,\n+) ([]clabruntime.GenericContainer, error) {\n+\treturn []clabruntime.GenericContainer{f.container}, nil\n+}\n+\n+// dockerContainer is the container Docker runs for a node.\n+func dockerContainer(t *testing.T, c *clabcore.CLab, node string) clabruntime.GenericContainer {\n+\tt.Helper()\n+\n+\tcfg := c.Nodes[node].Config()\n+\tlabels := cloneStringMap(cfg.Labels)\n+\tlabels[clabconstants.NodeMgmtNetBr] = \"br-92bb9fb46cd2\"\n+\n+\treturn clabruntime.GenericContainer{\n+\t\tNames:   []string{cfg.LongName},\n+\t\tID:      \"57b7763f3b4d97ff0c96b1dab8294b836199628a2d9400549948a963732e185a\",\n+\t\tShortID: \"57b7763f3b4d\",\n+\t\tImage:   cfg.Image,\n+\t\tState:   \"running\",\n+\t\tStatus:  \"Up 19 seconds\",\n+\t\tLabels:  labels,\n+\t\tNetworkSettings: clabruntime.GenericMgmtIPs{\n+\t\t\tIPv4addr: \"172.20.20.2\", IPv4pLen: 24, IPv6addr: \"3fff:172:20:20::2\", IPv6pLen: 64,\n+\t\t},\n+\t\tNetworkName: \"clab\",\n+\t\tPorts: []*clabtypes.GenericPortBinding{\n+\t\t\t{ContainerPort: 22, Protocol: \"tcp\"}, {ContainerPort: 80, Protocol: \"tcp\"},\n+\t\t},\n+\t}\n+}\n+\n+// dockerContainerEvent is a Docker container event as `containerlab events` reports it: the\n+// Docker message (container labels, image and name as attributes, plus the action's own) through\n+// the events command's conversion and enrichment.\n+func dockerContainerEvent(\n+\tt *testing.T,\n+\tcontainer clabruntime.GenericContainer,\n+\taction string,\n+\textra map[string]string,\n+) aggregatedEvent {\n+\tt.Helper()\n+\n+\tattributes := cloneStringMap(container.Labels)\n+\tattributes[\"image\"] = container.Image\n+\tattributes[\"name\"] = container.Names[0]\n+\tfor k, v := range extra {\n+\t\tattributes[k] = v\n+\t}\n+\tdata := clabutils.DockerMessageToEventData(dockerEvents.Message{\n+\t\tType:     dockerEvents.ContainerEventType,\n+\t\tAction:   dockerEvents.Action(action),\n+\t\tActor:    dockerEvents.Actor{ID: container.ID, Attributes: attributes},\n+\t\tScope:    \"local\",\n+\t\tTimeNano: time.Now().UnixNano(),\n+\t})\n+\n+\treturn aggregatedEventFromContainerEvent(context.Background(),\n+\t\t&fakeDockerRuntime{container: container},\n+\t\tclabruntime.ContainerEvent{\n+\t\t\tTimestamp: data.Timestamp, Type: data.Type, Action: data.Action,\n+\t\t\tActorID: data.ActorID, ActorName: data.ActorName, ActorFullID: data.ActorFullID,\n+\t\t\tAttributes: data.Attributes,\n+\t\t})\n+}\n+\n+// c9sNode is the same node as the c9s runtime reports it, deployed from the same file.\n+func c9sNode(\n+\tc *clabcore.CLab,\n+\tpath, node string,\n+) (*clablabruntime.LabState, clablabruntime.NodeState) {\n+\tcfg := c.Nodes[node].Config()\n+\tstate := &clablabruntime.LabState{\n+\t\tName: \"parity\", Namespace: \"c9s-parity\", Owner: \"alice\", TopologyPath: path,\n+\t\tState: \"running\", Ready: true,\n+\t}\n+\tnodeState := clablabruntime.NodeState{\n+\t\tName: node, Kind: cfg.Kind, Image: cfg.Image, State: \"ready\", Ready: true,\n+\t\tContainerState:  clablabruntime.ContainerStateRunning,\n+\t\tHealth:          clablabruntime.ContainerHealthHealthy,\n+\t\tMgmtIPv4Address: \"172.20.20.84/24\", MgmtIPv6Address: \"3fff:172:20:20::84/64\",\n+\t\tPod: node + \"-88598986c-rbdfq\", Container: \"node-\" + node, NodeUID: \"uid-\" + node,\n+\t\tExposedPorts: []clablabruntime.ExposedPort{\n+\t\t\t{\n+\t\t\t\tPort:       22,\n+\t\t\t\tExposePort: 22,\n+\t\t\t\tProtocol:   \"tcp\",\n+\t\t\t},\n+\t\t\t{Port: 80, ExposePort: 80, Protocol: \"tcp\"},\n+\t\t},\n+\t}\n+\tstate.Nodes = []clablabruntime.NodeState{nodeState}\n+\n+\treturn state, nodeState\n+}\n+\n+// c9sContainerEvent is the event the c9s runtime emits, as `containerlab events` reports it.\n+func c9sContainerEvent(\n+\tclab *clabcore.CLab,\n+\tstate *clablabruntime.LabState,\n+\tnode clablabruntime.NodeState,\n+\taction, containerState string,\n+\textra map[string]string,\n+) aggregatedEvent {\n+\tkey := state.Namespace + \"/\" + state.Name + \"/\" + node.Name\n+\tattributes := map[string]string{\n+\t\t\"namespace\": state.Namespace, \"lab\": state.Name, \"node\": node.Name, \"pod\": node.Pod,\n+\t\t\"state\": containerState,\n+\t}\n+\tfor k, v := range extra {\n+\t\tattributes[k] = v\n+\t}\n+\n+\treturn aggregatedEventFromLabRuntimeEvent(clab, clablabruntime.Event{\n+\t\tType: clablabruntime.EventTypeContainer, Action: action,\n+\t\tActorID: key, ActorName: state.Name + \"-\" + node.Name, ActorFullID: key,\n+\t\tAttributes: attributes, Lab: state, Node: &node,\n+\t})\n+}\n+\n+func attributeKeys(attributes map[string]string) []string {\n+\tkeys := make([]string, 0, len(attributes))\n+\tfor key := range attributes {\n+\t\tkeys = append(keys, key)\n+\t}\n+\tsort.Strings(keys)\n+\n+\treturn keys\n+}\n+\n+// assertAttributeParity checks that the c9s event carries every attribute of the Docker event,\n+// apart from the ones listed.\n+func assertAttributeParity(t *testing.T, docker, c9s aggregatedEvent, dockerOnly map[string]bool) {\n+\tt.Helper()\n+\n+\tdockerAttributes := mergedEventAttributes(docker)\n+\tc9sAttributes := mergedEventAttributes(c9s)\n+\tvar missing []string\n+\tfor key := range dockerAttributes {\n+\t\tif _, ok := c9sAttributes[key]; !ok && !dockerOnly[key] {\n+\t\t\tmissing = append(missing, key)\n+\t\t}\n+\t}\n+\tif len(missing) != 0 {\n+\t\tsort.Strings(missing)\n+\t\tt.Fatalf(\"c9s %s %s lacks %v\\ndocker: %v\\nc9s:    %v\", c9s.Type, c9s.Action, missing,\n+\t\t\tattributeKeys(dockerAttributes), attributeKeys(c9sAttributes))\n+\t}\n+}\n+\n+// TestContainerEventParity compares the container events of a node's lifecycle, with the c9s\n+// lab read with its topology file (events -t) and without it (events --name), where the\n+// attributes come from the cluster alone.\n+func TestContainerEventParity(t *testing.T) {\n+\tpath, dockerLab := parityLab(t)\n+\tbyName, err := clabcore.NewContainerLab(clabcore.WithLabNameOnly(\"parity\"))\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\n+\tfor _, mode := range []struct {\n+\t\tname string\n+\t\tlab  *clabcore.CLab\n+\t}{{\"with the topology\", dockerLab}, {\"by name\", byName}} {\n+\t\tt.Run(mode.name, func(t *testing.T) {\n+\t\t\tassertContainerEventParity(t, path, dockerLab, mode.lab, mode.lab == byName)\n+\t\t})\n+\t}\n+}\n+\n+func assertContainerEventParity(\n+\tt *testing.T,\n+\tpath string,\n+\tdockerLab, c9sLab *clabcore.CLab,\n+\tbyName bool,\n+) {\n+\tt.Helper()\n+\n+\tfor _, node := range []string{\"client\", \"srl1\"} {\n+\t\tcontainer := dockerContainer(t, dockerLab, node)\n+\t\tstate, nodeState := c9sNode(dockerLab, path, node)\n+\t\tdockerOnly := dockerOnlyContainerAttributes\n+\t\tif byName && node == \"srl1\" {\n+\t\t\t// The type is the SR Linux default; the cluster has only the types a topology\n+\t\t\t// sets, so a lab read by name does not know it.\n+\t\t\tdockerOnly = map[string]bool{clabconstants.NodeType: true}\n+\t\t\tfor key := range dockerOnlyContainerAttributes {\n+\t\t\t\tdockerOnly[key] = true\n+\t\t\t}\n+\t\t}\n+\n+\t\tfor _, tt := range []struct {\n+\t\t\taction, state string\n+\t\t\textra         map[string]string\n+\t\t}{\n+\t\t\t{\"create\", \"created\", nil},\n+\t\t\t{\"start\", \"running\", nil},\n+\t\t\t{\"kill\", \"running\", map[string]string{\"signal\": \"15\"}},\n+\t\t\t{\"stop\", \"exited\", nil},\n+\t\t\t{\"die\", \"exited\", map[string]string{\"exitCode\": \"137\", \"execDuration\": \"3\"}},\n+\t\t\t{\"health_status: healthy\", \"running\", nil},\n+\t\t\t{\"destroy\", \"exited\", nil},\n+\t\t} {\n+\t\t\tdocker := dockerContainerEvent(t, container, tt.action, tt.extra)\n+\t\t\tvar c9sExtra map[string]string\n+\t\t\tif tt.action == \"kill\" {\n+\t\t\t\tc9sExtra = tt.extra\n+\t\t\t}\n+\t\t\tc9s := c9sContainerEvent(c9sLab, state, nodeState, tt.action, tt.state, c9sExtra)\n+\t\t\tassertAttributeParity(t, docker, c9s, dockerOnly)\n+\n+\t\t\tgot := mergedEventAttributes(c9s)\n+\t\t\twant := map[string]string{\n+\t\t\t\tclabconstants.Containerlab: \"parity\",\n+\t\t\t\tclabconstants.NodeName:     node,\n+\t\t\t\tclabconstants.LongName:     \"parity-\" + node,\n+\t\t\t\tclabconstants.NodeKind:     dockerLab.Nodes[node].Config().Kind,\n+\t\t\t\tclabconstants.TopoFile:     path,\n+\t\t\t\tclabconstants.Owner:        \"alice\",\n+\t\t\t\t\"image\":                    container.Image,\n+\t\t\t\t\"name\":                     \"parity-\" + node,\n+\t\t\t\t\"id\":                       \"c9s-parity/parity/\" + node,\n+\t\t\t\t\"mgmt_ipv4\":                \"172.20.20.84/24\",\n+\t\t\t\t\"mgmt_ipv6\":                \"3fff:172:20:20::84/64\",\n+\t\t\t\t\"ports\":                    \"22/tcp;80/tcp\",\n+\t\t\t\t\"state\":                    tt.state,\n+\t\t\t}\n+\t\t\tfor key, value := range want {\n+\t\t\t\tif got[key] != value {\n+\t\t\t\t\tt.Fatalf(\"%s %s: %s = %q, want %q\", node, tt.action, key, got[key], value)\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\t// the label values have Docker's format\n+\t\t\tdockerAttributes := mergedEventAttributes(docker)\n+\t\t\tfor _, key := range []string{\n+\t\t\t\tclabconstants.Containerlab, clabconstants.NodeName, clabconstants.NodeKind,\n+\t\t\t\tclabconstants.NodeType, clabconstants.TopoFile, clabconstants.Owner, \"image\",\n+\t\t\t\t\"ports\",\n+\t\t\t} {\n+\t\t\t\tif dockerOnly[key] {\n+\t\t\t\t\tcontinue\n+\t\t\t\t}\n+\t\t\t\tif got[key] != dockerAttributes[key] {\n+\t\t\t\t\tt.Fatalf(\"%s %s: %s = %q, docker %q\", node, tt.action, key, got[key],\n+\t\t\t\t\t\tdockerAttributes[key])\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tif c9s.ActorID != c9s.ActorFullID || c9s.ActorName != \"parity-\"+node {\n+\t\t\t\tt.Fatalf(\"%s %s: actor = %+v\", node, tt.action, c9s)\n+\t\t\t}\n+\t\t}\n+\t}\n+}\n+\n+// TestContainerSnapshotParity compares the --initial-state events of a running node, with the\n+// c9s lab read with its topology file.\n+func TestContainerSnapshotParity(t *testing.T) {\n+\tpath, dockerLab := parityLab(t)\n+\tc9sLab := dockerLab\n+\n+\tfor _, node := range []string{\"client\", \"srl1\"} {\n+\t\tcontainer := dockerContainer(t, dockerLab, node)\n+\t\tdocker := aggregatedEventFromContainerSnapshot(&container)\n+\n+\t\tstate, nodeState := c9sNode(dockerLab, path, node)\n+\t\tc9s := c9sContainerEvent(c9sLab, state, nodeState, \"running\", \"running\",\n+\t\t\tmap[string]string{\"origin\": clablabruntime.EventOriginSnapshot})\n+\n+\t\tassertAttributeParity(t, docker, c9s, dockerOnlyContainerAttributes)\n+\t\tgot := mergedEventAttributes(c9s)\n+\t\tif docker.Action != c9s.Action || got[\"origin\"] != \"snapshot\" ||\n+\t\t\tgot[\"state\"] != \"running\" ||\n+\t\t\tgot[\"status\"] != \"healthy\" ||\n+\t\t\tgot[\"network\"] != \"c9s-parity\" {\n+\t\t\tt.Fatalf(\"%s snapshot = %s %v\", node, c9s.Action, got)\n+\t\t}\n+\t}\n+}\n+\n+// TestContainerStateUsesDockerVocabulary checks the state and status of every node state c9s\n+// reports, in events and inspect.\n+func TestContainerStateUsesDockerVocabulary(t *testing.T) {\n+\tt.Parallel()\n+\n+\tc9sLab, err := clabcore.NewContainerLab(clabcore.WithLabNameOnly(\"parity\"))\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\n+\tstate := &clablabruntime.LabState{Name: \"parity\", Namespace: \"c9s-parity\"}\n+\ttests := []struct {\n+\t\tnode          clablabruntime.NodeState\n+\t\tstate, status string\n+\t}{\n+\t\t{\n+\t\t\tclablabruntime.NodeState{Name: \"a\", ContainerState: \"created\", State: \"notready\"},\n+\t\t\t\"created\", \"Created\",\n+\t\t},\n+\t\t{clablabruntime.NodeState{\n+\t\t\tName: \"b\", ContainerState: \"running\", Health: \"starting\",\n+\t\t\tState: \"notready\",\n+\t\t}, \"running\", \"health: starting\"},\n+\t\t{clablabruntime.NodeState{\n+\t\t\tName: \"c\", ContainerState: \"running\", Health: \"healthy\",\n+\t\t\tState: \"ready\", Ready: true,\n+\t\t}, \"running\", \"healthy\"},\n+\t\t{\n+\t\t\tclablabruntime.NodeState{Name: \"d\", ContainerState: \"exited\", State: \"stopped\"},\n+\t\t\t\"exited\", \"Exited\",\n+\t\t},\n+\t}\n+\tfor _, tt := range tests {\n+\t\tcontainer := c9sLab.LabRuntimeContainer(state, tt.node)\n+\t\tif container.State != tt.state || container.Status != tt.status {\n+\t\t\tt.Fatalf(\"%s: %s / %s, want %s / %s\", tt.node.Name, container.State, container.Status,\n+\t\t\t\ttt.state, tt.status)\n+\t\t}\n+\t}\n+}\n+\n+// dockerInterfaceEvent is a netlink interface event of a Docker container.\n+func dockerInterfaceEvent(\n+\tcontainer clabruntime.GenericContainer,\n+\taction string,\n+\tsnapshot ifaceSnapshot,\n+\tstats *ifaceStatsMetrics,\n+) aggregatedEvent {\n+\tattributes := interfaceAttributes(&container, snapshot)\n+\tif stats != nil {\n+\t\tinterfaceStatsAttributes(attributes, *stats)\n+\t}\n+\n+\treturn aggregatedEvent{\n+\t\tType: \"interface\", Action: action, ActorID: container.ShortID,\n+\t\tActorName: container.Names[0], ActorFullID: container.ID, Attributes: attributes,\n+\t}\n+}\n+\n+func c9sInterfaceEvent(\n+\tstate *clablabruntime.LabState,\n+\tnode clablabruntime.NodeState,\n+\taction string,\n+\tiface clablabruntime.InterfaceEventData,\n+) aggregatedEvent {\n+\tkey := state.Namespace + \"/\" + state.Name + \"/\" + node.Name\n+\n+\treturn aggregatedEventFromLabRuntimeEvent(nil, clablabruntime.Event{\n+\t\tType: clablabruntime.EventTypeInterface, Action: action,\n+\t\tActorID: key, ActorName: state.Name + \"-\" + node.Name, ActorFullID: key,\n+\t\tAttributes: map[string]string{\n+\t\t\t\"namespace\": state.Namespace, \"lab\": state.Name, \"node\": node.Name, \"pod\": node.Pod,\n+\t\t\t\"origin\": \"clabernetes\",\n+\t\t},\n+\t\tLab: state, Node: &node, Interface: &iface,\n+\t})\n+}\n+\n+// TestInterfaceEventParity compares the interface events of the lab link (linux eth1, SR Linux\n+// e1-1 with its alias ethernet-1/1), the management interface and loopback.\n+func TestInterfaceEventParity(t *testing.T) {\n+\tpath, dockerLab := parityLab(t)\n+\n+\ttests := []struct {\n+\t\tnode string\n+\t\tdata clablabruntime.InterfaceEventData\n+\t}{\n+\t\t{\n+\t\t\t\"client\",\n+\t\t\tclablabruntime.InterfaceEventData{\n+\t\t\t\tName:      \"eth1\",\n+\t\t\t\tIndex:     7,\n+\t\t\t\tMTU:       9500,\n+\t\t\t\tMAC:       \"aa:c1:ab:56:aa:46\",\n+\t\t\t\tOperState: \"up\",\n+\t\t\t\tType:      \"veth\",\n+\t\t\t},\n+\t\t},\n+\t\t{\"srl1\", clablabruntime.InterfaceEventData{\n+\t\t\tName: \"e1-1\", Alias: \"ethernet-1/1\", Index: 7, MTU: 9500, MAC: \"aa:c1:ab:56:aa:47\",\n+\t\t\tOperState: \"lower-layer-down\", Type: \"veth\",\n+\t\t}},\n+\t\t{\n+\t\t\t\"client\",\n+\t\t\tclablabruntime.InterfaceEventData{\n+\t\t\t\tName:      \"eth0\",\n+\t\t\t\tIndex:     4,\n+\t\t\t\tMTU:       1500,\n+\t\t\t\tMAC:       \"02:42:ac:14:14:02\",\n+\t\t\t\tOperState: \"up\",\n+\t\t\t\tType:      \"veth\",\n+\t\t\t},\n+\t\t},\n+\t\t{\"client\", clablabruntime.InterfaceEventData{\n+\t\t\tName: \"lo\", Index: 1, MTU: 65536, OperState: \"unknown\", Type: \"device\",\n+\t\t}},\n+\t}\n+\tfor _, tt := range tests {\n+\t\tcontainer := dockerContainer(t, dockerLab, tt.node)\n+\t\tstate, nodeState := c9sNode(dockerLab, path, tt.node)\n+\t\tsnapshot := ifaceSnapshot{\n+\t\t\tIndex: tt.data.Index, Name: tt.data.Name, Alias: tt.data.Alias, MTU: tt.data.MTU,\n+\t\t\tMAC: tt.data.MAC, OperState: tt.data.OperState, Type: tt.data.Type,\n+\t\t}\n+\t\tmetrics := ifaceStatsMetrics{\n+\t\t\tRxBytes: 2000, TxBytes: 3000, RxPackets: 20, TxPackets: 30,\n+\t\t\tRxBps: 8000, TxBps: 12000, RxPps: 10, TxPps: 15, Interval: 2 * time.Second,\n+\t\t}\n+\n+\t\tfor _, action := range []string{\"snapshot\", \"create\", \"update\", \"delete\", \"stats\"} {\n+\t\t\tvar stats *ifaceStatsMetrics\n+\t\t\tdata := tt.data\n+\t\t\tif action == \"stats\" {\n+\t\t\t\tstats = &metrics\n+\t\t\t\tdata.Stats = &clablabruntime.InterfaceStats{\n+\t\t\t\t\tRxBytes: 2000, TxBytes: 3000, RxPackets: 20, TxPackets: 30,\n+\t\t\t\t\tRxBps: 8000, TxBps: 12000, RxPps: 10, TxPps: 15, Interval: 2 * time.Second,\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tdocker := dockerInterfaceEvent(container, action, snapshot, stats)\n+\t\t\tc9s := c9sInterfaceEvent(state, nodeState, action, data)\n+\t\t\tassertAttributeParity(t, docker, c9s, nil)\n+\n+\t\t\tdockerAttributes := mergedEventAttributes(docker)\n+\t\t\tgot := mergedEventAttributes(c9s)\n+\t\t\tfor key, value := range dockerAttributes {\n+\t\t\t\tswitch key {\n+\t\t\t\tcase \"id\", \"name\", \"lab\", \"origin\":\n+\t\t\t\t\t// the node's own ID, name and lab; the source of the event\n+\t\t\t\t\tcontinue\n+\t\t\t\t}\n+\t\t\t\tif got[key] != value {\n+\t\t\t\t\tt.Fatalf(\"%s %s %s: %s = %q, docker %q\", tt.node, tt.data.Name, action, key,\n+\t\t\t\t\t\tgot[key], value)\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tif got[\"name\"] != \"parity-\"+tt.node || got[\"lab\"] != \"parity\" ||\n+\t\t\t\tgot[\"id\"] != \"c9s-parity/parity/\"+tt.node {\n+\t\t\t\tt.Fatalf(\"%s %s %s: node attributes %v\", tt.node, tt.data.Name, action, got)\n+\t\t\t}\n+\t\t}\n+\t}\n+}\n+\n+// TestInterfaceEventOmitsUnknownValues checks that values the runtime could not read are left\n+// out: an index of 0 would make clients take two interfaces for one.\n+func TestInterfaceEventOmitsUnknownValues(t *testing.T) {\n+\tt.Parallel()\n+\n+\tstate := &clablabruntime.LabState{Name: \"parity\", Namespace: \"c9s-parity\"}\n+\tev := c9sInterfaceEvent(state, clablabruntime.NodeState{Name: \"client\"}, \"stats\",\n+\t\tclablabruntime.InterfaceEventData{\n+\t\t\tName: \"eth1\", Type: \"veth\",\n+\t\t\tStats: &clablabruntime.InterfaceStats{RxBytes: 1, Interval: time.Second},\n+\t\t})\n+\tgot := mergedEventAttributes(ev)\n+\tfor _, key := range []string{\"index\", \"mtu\", \"state\", \"mac\", \"alias\"} {\n+\t\tif _, ok := got[key]; ok {\n+\t\t\tt.Fatalf(\"%s reported without a value: %v\", key, got)\n+\t\t}\n+\t}\n+\tif got[\"ifname\"] != \"eth1\" || got[\"rx_bytes\"] != \"1\" || got[\"interval_seconds\"] != \"1\" {\n+\t\tt.Fatalf(\"stats = %v\", got)\n+\t}\n+}\n+\n+func TestLabRuntimeTopologyEventsKeepTheirAttributes(t *testing.T) {\n+\tt.Parallel()\n+\n+\tev := aggregatedEventFromLabRuntimeEvent(nil, clablabruntime.Event{\n+\t\tType: \"topology\", Action: \"modified\", ActorID: \"c9s-parity/parity\", ActorName: \"parity\",\n+\t\tAttributes: map[string]string{\"lab\": \"parity\", \"state\": \"running\"},\n+\t})\n+\tif !strings.EqualFold(ev.Attributes[\"lab\"], \"parity\") || len(ev.Attributes) != 2 {\n+\t\tt.Fatalf(\"topology event = %+v\", ev)\n+\t}\n+}\ndiff --git a/core/events/stream.go b/core/events/stream.go\nindex a944edc..9ba6c87 100644\n--- a/core/events/stream.go\n+++ b/core/events/stream.go\n@@ -128,11 +128,11 @@ func streamLabRuntimeEvents(ctx context.Context, clab *clabcore.CLab, opts Optio\n \t\t\t\truntimeEvents = nil\n \n \t\t\t\tcontinue\n \t\t\t}\n \n-\t\t\tif err := printer(aggregatedEventFromLabRuntimeEvent(ev)); err != nil {\n+\t\t\tif err := printer(aggregatedEventFromLabRuntimeEvent(clab, ev)); err != nil {\n \t\t\t\tlog.Debugf(\"failed to write event: %v\", err)\n \t\t\t}\n \t\tcase err, ok := <-runtimeErrs:\n \t\t\tif !ok {\n \t\t\t\truntimeErrs = nil\n@@ -168,27 +168,90 @@ func labRuntimeEventStreamRequest(\n \t\tIncludeInterfaceStats: opts.IncludeInterfaceStats,\n \t\tStatsInterval:         opts.StatsInterval,\n \t}\n }\n \n-func aggregatedEventFromLabRuntimeEvent(ev clablabruntime.Event) aggregatedEvent {\n+// aggregatedEventFromLabRuntimeEvent reports a lab runtime event with the attributes the\n+// container runtimes' events have. A container event describes its node with the container\n+// record inspect reports for it, the way a Docker event carries the container's labels: as a\n+// snapshot like the snapshots of local containers, otherwise with the labels, image,\n+// management addresses and ports a Docker event and its enrichment carry. An interface event\n+// carries the attributes of the netlink interface events. The runtime's own attributes come on\n+// top.\n+func aggregatedEventFromLabRuntimeEvent(\n+\tclab *clabcore.CLab,\n+\tev clablabruntime.Event,\n+) aggregatedEvent {\n \tts := ev.Timestamp\n \tif ts.IsZero() {\n \t\tts = time.Now()\n \t}\n \n+\tvar attributes map[string]string\n+\tswitch {\n+\tcase ev.Type == clablabruntime.EventTypeContainer && ev.Lab != nil && ev.Node != nil &&\n+\t\tclab != nil:\n+\t\tcontainer := clab.LabRuntimeContainer(ev.Lab, *ev.Node)\n+\t\tif ev.Attributes[\"origin\"] == clablabruntime.EventOriginSnapshot {\n+\t\t\tattributes = aggregatedEventFromContainerSnapshot(&container).Attributes\n+\t\t} else {\n+\t\t\tattributes = containerAttributes(&container)\n+\t\t}\n+\tcase ev.Type == clablabruntime.EventTypeInterface && ev.Interface != nil:\n+\t\tlab := ev.Attributes[\"lab\"]\n+\t\tif ev.Lab != nil {\n+\t\t\tlab = ev.Lab.Name\n+\t\t}\n+\t\tattributes = labRuntimeInterfaceAttributes(lab, ev.ActorName, ev.Interface)\n+\t}\n+\n+\tfor key, value := range ev.Attributes {\n+\t\tif attributes == nil {\n+\t\t\tattributes = make(map[string]string, len(ev.Attributes))\n+\t\t}\n+\t\tattributes[key] = value\n+\t}\n+\n \treturn aggregatedEvent{\n \t\tTimestamp:   ts,\n \t\tType:        ev.Type,\n \t\tAction:      ev.Action,\n \t\tActorID:     ev.ActorID,\n \t\tActorName:   ev.ActorName,\n \t\tActorFullID: ev.ActorFullID,\n-\t\tAttributes:  cloneStringMap(ev.Attributes),\n+\t\tAttributes:  attributes,\n \t}\n }\n \n+// containerAttributes are the attributes a container event reports for a container: its labels\n+// and image, which Docker puts on every container event, and the management addresses and\n+// ports the events command adds.\n+func containerAttributes(container *clabruntime.GenericContainer) map[string]string {\n+\tattributes := cloneStringMap(container.Labels)\n+\tif attributes == nil {\n+\t\tattributes = make(map[string]string)\n+\t}\n+\n+\tif container.Image != \"\" {\n+\t\tattributes[\"image\"] = container.Image\n+\t}\n+\n+\tif container.NetworkSettings.IPv4addr != \"\" {\n+\t\tattributes[\"mgmt_ipv4\"] = container.GetContainerIPv4()\n+\t}\n+\n+\tif container.NetworkSettings.IPv6addr != \"\" {\n+\t\tattributes[\"mgmt_ipv6\"] = container.GetContainerIPv6()\n+\t}\n+\n+\tif ports := exposedPortsAttributeValue(container.Ports); ports != \"\" {\n+\t\tattributes[\"ports\"] = ports\n+\t}\n+\n+\treturn attributes\n+}\n+\n func forwardRuntimeEvents(\n \tctx context.Context,\n \truntime clabruntime.ContainerRuntime,\n \tregistry *netlinkRegistry,\n \truntimeEvents <-chan clabruntime.ContainerEvent,\n@@ -437,23 +500,16 @@ func aggregatedEventFromContainerSnapshot(\n \tshort := container.ShortID\n \tif short == \"\" {\n \t\tshort = clabutils.ShortID(container.ID)\n \t}\n \n-\tattributes := cloneStringMap(container.Labels)\n-\tif attributes == nil {\n-\t\tattributes = make(map[string]string)\n-\t}\n+\tattributes := containerAttributes(container)\n \n \tif _, ok := attributes[\"origin\"]; !ok {\n \t\tattributes[\"origin\"] = \"snapshot\"\n \t}\n \n-\tif container.Image != \"\" {\n-\t\tattributes[\"image\"] = container.Image\n-\t}\n-\n \tif container.Status != \"\" {\n \t\tattributes[\"status\"] = container.Status\n \t}\n \n \tif state != \"\" {\n@@ -462,22 +518,10 @@ func aggregatedEventFromContainerSnapshot(\n \n \tif container.NetworkName != \"\" {\n \t\tattributes[\"network\"] = container.NetworkName\n \t}\n \n-\tif container.NetworkSettings.IPv4addr != \"\" {\n-\t\tattributes[\"mgmt_ipv4\"] = container.GetContainerIPv4()\n-\t}\n-\n-\tif container.NetworkSettings.IPv6addr != \"\" {\n-\t\tattributes[\"mgmt_ipv6\"] = container.GetContainerIPv6()\n-\t}\n-\n-\tif ports := exposedPortsAttributeValue(container.Ports); ports != \"\" {\n-\t\tattributes[\"ports\"] = ports\n-\t}\n-\n \tif len(attributes) == 0 {\n \t\tattributes = nil\n \t}\n \n \tactorName := firstContainerName(container)\ndiff --git a/core/labruntime.go b/core/labruntime.go\nindex eff4bd2..ade83f4 100644\n--- a/core/labruntime.go\n+++ b/core/labruntime.go\n@@ -448,49 +448,68 @@ func (c *CLab) containersFromLabState(\n \t}\n \n \treturn containers\n }\n \n+// LabRuntimeContainer describes a lab runtime node as a container record, the way inspect\n+// reports it. The events command describes lab runtime nodes with it too.\n+func (c *CLab) LabRuntimeContainer(\n+\tstate *clablabruntime.LabState,\n+\tnode clablabruntime.NodeState,\n+) clabruntime.GenericContainer {\n+\treturn c.containerFromLabNode(state, node)\n+}\n+\n func (c *CLab) containerFromLabNode(\n \tstate *clablabruntime.LabState,\n \tnode clablabruntime.NodeState,\n ) clabruntime.GenericContainer {\n \tnodeName := fmt.Sprintf(\"%s-%s\", state.Name, node.Name)\n-\tcontainerState := node.State\n-\tcontainerStatus := node.State\n-\tif containerState == \"\" {\n-\t\tcontainerState = state.State\n+\tcontainerState, containerStatus := labRuntimeContainerState(state, node)\n+\n+\ttopologyNode := node.Name\n+\tif node.TopologyName != \"\" {\n+\t\ttopologyNode = node.TopologyName\n \t}\n-\tif node.Ready {\n-\t\tcontainerState = \"running\"\n-\t\tcontainerStatus = \"healthy\"\n+\tif c.Config.Topology != nil {\n+\t\ttopologyNode = c.topologyNodeName(topologyNode)\n \t}\n \n \tlabels := map[string]string{\n \t\tclabconstants.Containerlab: state.Name,\n-\t\tclabconstants.NodeName:     node.Name,\n+\t\tclabconstants.NodeName:     topologyNode,\n \t\tclabconstants.LongName:     nodeName,\n \t\tclabconstants.TopoFile:     labRuntimeTopologyPath(c, state),\n \t}\n \n \tvar image string\n \tif c.Config.Topology != nil {\n-\t\ttopologyNode := c.topologyNodeName(node.Name)\n \t\tlabels[clabconstants.NodeKind] = c.Config.Topology.GetNodeKind(topologyNode)\n \t\timage = c.Config.Topology.GetNodeImage(topologyNode)\n-\n-\t\tif group := c.Config.Topology.GetNodeGroup(topologyNode); group != \"\" {\n-\t\t\tlabels[clabconstants.NodeGroup] = group\n-\t\t}\n \t}\n \tif node.Kind != \"\" {\n \t\tlabels[clabconstants.NodeKind] = node.Kind\n \t}\n \tif node.Image != \"\" {\n \t\timage = node.Image\n \t}\n \n+\t// The node's type and group: from the loaded topology's node, with the kind's defaults the\n+\t// local runtimes report too, otherwise as the topology set them on the runtime's node.\n+\tnodeType, group := node.Type, node.Group\n+\tif topologyNodeConfig, ok := c.Nodes[topologyNode]; ok {\n+\t\tnodeType, group = topologyNodeConfig.Config().NodeType, topologyNodeConfig.Config().Group\n+\t} else if c.Config.Topology != nil && group == \"\" {\n+\t\tgroup = c.Config.Topology.GetNodeGroup(topologyNode)\n+\t}\n+\tif nodeType != \"\" {\n+\t\tlabels[clabconstants.NodeType] = nodeType\n+\t}\n+\tif group != \"\" {\n+\t\tlabels[clabconstants.NodeGroup] = group\n+\t}\n+\n \tif state.Owner != \"\" {\n \t\tlabels[clabconstants.Owner] = state.Owner\n \t} else if c.customOwner != \"\" {\n \t\tlabels[clabconstants.Owner] = c.customOwner\n \t}\n@@ -507,10 +526,11 @@ func (c *CLab) containerFromLabNode(\n \t\tState:           containerState,\n \t\tStatus:          containerStatus,\n \t\tLabels:          labels,\n \t\tNetworkName:     state.Namespace,\n \t\tNetworkSettings: managementAddress(node),\n+\t\tPorts:           labRuntimePorts(node.ExposedPorts),\n \t\tWorkload: &clabtypes.LabRuntimeWorkload{\n \t\t\tNamespace:           state.Namespace,\n \t\t\tPod:                 node.Pod,\n \t\t\tContainer:           node.Container,\n \t\t\tNodeUID:             node.NodeUID,\n@@ -518,10 +538,60 @@ func (c *CLab) containerFromLabNode(\n \t\t\tLoadBalancerAddress: node.LoadBalancerAddress,\n \t\t},\n \t}\n }\n \n+// labRuntimeContainerState is a lab runtime node's state and status in the vocabulary of the\n+// container runtimes: state created, running or exited; status healthy or \"health: starting\"\n+// for a running node, as inspect shortens a Docker status line with a healthcheck, Created or\n+// Exited otherwise. A runtime that reports no container state keeps its own state.\n+func labRuntimeContainerState(\n+\tstate *clablabruntime.LabState,\n+\tnode clablabruntime.NodeState,\n+) (string, string) {\n+\tswitch node.ContainerState {\n+\tcase clablabruntime.ContainerStateRunning:\n+\t\tif node.Health == clablabruntime.ContainerHealthHealthy {\n+\t\t\treturn node.ContainerState, \"healthy\"\n+\t\t}\n+\n+\t\treturn node.ContainerState, \"health: starting\"\n+\tcase clablabruntime.ContainerStateCreated:\n+\t\treturn node.ContainerState, \"Created\"\n+\tcase clablabruntime.ContainerStateExited:\n+\t\treturn node.ContainerState, \"Exited\"\n+\t}\n+\n+\tif node.Ready {\n+\t\treturn clablabruntime.ContainerStateRunning, \"healthy\"\n+\t}\n+\tif node.State == \"\" {\n+\t\treturn state.State, \"\"\n+\t}\n+\n+\treturn node.State, node.State\n+}\n+\n+// labRuntimePorts reports the ports a lab runtime exposes for a node as the ports a container\n+// exposes without publishing them on the host: the node is reached through the runtime (a\n+// Service, a port-forward), never on a port of this machine.\n+func labRuntimePorts(ports []clablabruntime.ExposedPort) []*clabtypes.GenericPortBinding {\n+\tif len(ports) == 0 {\n+\t\treturn nil\n+\t}\n+\n+\tbindings := make([]*clabtypes.GenericPortBinding, 0, len(ports))\n+\tfor _, port := range ports {\n+\t\tbindings = append(bindings, &clabtypes.GenericPortBinding{\n+\t\t\tContainerPort: port.Port,\n+\t\t\tProtocol:      port.Protocol,\n+\t\t})\n+\t}\n+\n+\treturn bindings\n+}\n+\n // labRuntimeContainerID is the ID of a lab runtime node: <namespace>/<lab>/<node>.\n func labRuntimeContainerID(namespace, lab, node string) string {\n \treturn fmt.Sprintf(\"%s/%s/%s\", namespace, lab, node)\n }\n \ndiff --git a/core/labruntime_gaps_test.go b/core/labruntime_gaps_test.go\nindex 791f068..87c0251 100644\n--- a/core/labruntime_gaps_test.go\n+++ b/core/labruntime_gaps_test.go\n@@ -114,5 +114,50 @@ func TestCheckConnectivitySkipsLocalRuntimesForLabRuntimes(t *testing.T) {\n \tc := &CLab{LabRuntime: &recordingDestroyLabRuntime{}}\n \tif err := c.CheckConnectivity(context.Background()); err != nil {\n \t\tt.Fatalf(\"CheckConnectivity() = %v, want nil for a lab runtime\", err)\n \t}\n }\n+\n+// TestContainerFromLabNodeReportsTheTopologyNode checks the labels a lab runtime node reports\n+// without its topology file: the node name the topology spells, the type and group the\n+// topology set, the recorded topology file, and its ports as unpublished container ports.\n+func TestContainerFromLabNodeReportsTheTopologyNode(t *testing.T) {\n+\tt.Parallel()\n+\n+\tc := &CLab{Config: &Config{Name: \"lab1\"}, TopoPaths: &clabtypes.TopoPaths{}}\n+\tcontainer := c.containerFromLabNode(\n+\t\t&clablabruntime.LabState{\n+\t\t\tName: \"lab1\", Namespace: \"c9s-lab1\", TopologyPath: \"/home/alice/lab1.clab.yml\",\n+\t\t},\n+\t\tclablabruntime.NodeState{\n+\t\t\tName: \"r1\", TopologyName: \"R1\", Kind: \"nokia_srlinux\", Type: \"ixr-h2\",\n+\t\t\tGroup: \"spines\", ContainerState: \"running\", Health: \"healthy\",\n+\t\t\tExposedPorts: []clablabruntime.ExposedPort{\n+\t\t\t\t{Port: 57400, ExposePort: 57400, Protocol: \"tcp\"},\n+\t\t\t},\n+\t\t},\n+\t)\n+\n+\twant := map[string]string{\n+\t\t\"clab-node-name\":     \"R1\",\n+\t\t\"clab-node-longname\": \"lab1-r1\",\n+\t\t\"clab-node-kind\":     \"nokia_srlinux\",\n+\t\t\"clab-node-type\":     \"ixr-h2\",\n+\t\t\"clab-node-group\":    \"spines\",\n+\t\t\"clab-topo-file\":     \"/home/alice/lab1.clab.yml\",\n+\t\t\"containerlab\":       \"lab1\",\n+\t}\n+\tfor key, value := range want {\n+\t\tif container.Labels[key] != value {\n+\t\t\tt.Fatalf(\"label %s = %q, want %q (%v)\", key, container.Labels[key], value,\n+\t\t\t\tcontainer.Labels)\n+\t\t}\n+\t}\n+\tif container.State != \"running\" || container.Status != \"healthy\" ||\n+\t\tcontainer.Names[0] != \"lab1-r1\" {\n+\t\tt.Fatalf(\"container = %s %s %v\", container.State, container.Status, container.Names)\n+\t}\n+\tif len(container.Ports) != 1 || container.Ports[0].ContainerPort != 57400 ||\n+\t\tcontainer.Ports[0].HostPort != 0 || container.Ports[0].Protocol != \"tcp\" {\n+\t\tt.Fatalf(\"ports = %+v\", container.Ports)\n+\t}\n+}\ndiff --git a/docs/cmd/events.md b/docs/cmd/events.md\nindex 92d51ed..23d9eef 100644\n--- a/docs/cmd/events.md\n+++ b/docs/cmd/events.md\n@@ -75,19 +75,25 @@ Currently supported runtimes:\n \n - `docker`\n - `c9s`\n \n With `--runtime c9s`, events are backed by kubernetes watches for Clabernetes\n-`Topology` and `Node` resources and labeled Pods. Interface state (`interface up`\n-and `interface down` events) and statistics are sampled inside the device\n-containers, not through local host netlink. The stream covers every namespace by\n-default; `--namespace` (or `CLAB_KUBE_NAMESPACE`) limits it to one namespace,\n-and `-t`/`--name` to one lab. With Docker and Podman the lab selection is ignored\n-and every lab is streamed.\n+`Topology` and `Node` resources and labeled Pods. They use the actions and\n+attributes of the Docker runtime: a node is a container (`create`, `start`,\n+`kill`, `stop`, `die`, `destroy`, `health_status: …`) described by the same\n+labels, and the interface events (`snapshot`, `create`, `update`, `delete`,\n+`stats`) report the node's lab link interfaces, `eth0` and `lo` under the names\n+a Docker container of the node has. Interface state and statistics are sampled\n+inside the device containers, not through local host netlink. The stream covers\n+every namespace by default; `--namespace` (or `CLAB_KUBE_NAMESPACE`) limits it\n+to one namespace, and `-t`/`--name` to one lab. With Docker and Podman the lab\n+selection is ignored and every lab is streamed. The\n+[c9s runtime manual](../manual/clabernetes/runtime.md#events) lists the\n+attributes and the few Docker attributes c9s has no equivalent for.\n \n Runtimes that do not implement the `events` API, or are not yet supported by Containerlab, will exit with an explanatory error.\n \n ## See also\n \n - [`inspect interfaces`](inspect/interfaces.md) – produces a point-in-time view of the same interface details that `events` reports continuously.\n-- [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md) - explains how c9s events differ from Docker events.\n+- [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md#events) - describes c9s events and how they map onto Docker events.\n - `docker events` – the raw runtime feed that Containerlab builds upon.\ndiff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md\nindex 2354dc1..43fbb9a 100644\n--- a/docs/cmd/inspect/interfaces.md\n+++ b/docs/cmd/inspect/interfaces.md\n@@ -3,11 +3,11 @@\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+With the [c9s runtime](../../manual/clabernetes/runtime.md#interface-events), the listing covers the interfaces a Docker container of the node has: the lab link interfaces of each running node (the ones [`capture`](../capture.md) accepts) with the alias the topology used, the management interface `eth0` and the loopback `lo`, with the MAC address, index, MTU and operational state read in the node's device container. The pod's own interfaces are not listed. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields and values (`veth`/`device`, netlink state names) are the same as with Docker. `eth0` and `lo` cannot be captured on c9s.\n \n ### Usage\n \n `containerlab [global-flags] inspect interfaces [local-flags]`\n \ndiff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md\nindex 8174c98..751ccf1 100644\n--- a/docs/manual/clabernetes/runtime.md\n+++ b/docs/manual/clabernetes/runtime.md\n@@ -543,10 +543,45 @@ port-forward without working out the pod themselves:\n \n These fields are only present for lab runtimes; Docker and Podman output is\n unchanged. Fields without a value, such as `pod` for a stopped node, are left\n out. `--details` keeps printing the raw records.\n \n+The other fields mean what they mean for Docker and Podman, so clients can treat\n+c9s nodes like containers:\n+\n+| Field | c9s value |\n+|---|---|\n+| `state` | `created` while the node's pod is scheduled and prepared, `running` once its device containers run, `exited` once the node is stopped (or its pod ends or is replaced) |\n+| `status` | `healthy` once the node is ready or its device containers are, `health: starting` while a running device boots, `Created`, `Exited` |\n+| `labPath`, `absLabPath` | the topology file the lab was deployed from (see below) |\n+| `name` | `<lab>-<node>`, the name events use as `actor_name` |\n+\n+### Topology file\n+\n+A deploy records the absolute path of the topology file, on the machine that\n+deployed it, in the annotation `containerlab.dev/topo-file`:\n+\n+- with a `Topology` resource, on the `Topology`; every deploy records the file\n+  it read\n+- with `--no-topology-cr`, on every `Node`. clabernetes copies a Node's\n+  annotations into its pod, so a Node keeps the file it was created from: a\n+  later deploy from another file does not change it and does not restart the\n+  node. Destroy and deploy again to record a new file.\n+\n+`inspect` reports the recorded file as `labPath` and `absLabPath` (shortened\n+for the table, as for Docker), and events as `clab-topo-file`, so a client\n+matches a running lab to its file the same way for every runtime. The file is a\n+path on the deploying machine; a client on another machine cannot assume it\n+exists there.\n+\n+A lab that containerlab did not deploy from a file, for example one applied from\n+`deploy --emit-crs` output with `kubectl` (the emitted manifests do not carry\n+the annotation), has no recorded file. It reports where its definition lives in\n+the cluster: `k8s://<namespace>/topologies/<lab>`, or\n+`k8s://<namespace>/labs/<lab>` without a `Topology` resource. With `-t`,\n+`inspect` reports the given file.\n+\n Useful kubernetes checks for the same state are:\n \n ```bash\n kubectl -n <namespace> get node.c9s.run,link.c9s.run,nodeprofile.c9s.run,deploy,pod,svc,cm,pvc \\\n   -l c9s.run/topologyOwner=<lab>\n@@ -697,12 +732,18 @@ stopped node is started by the same patch.\n What a stopped node keeps and loses:\n \n - The `Node`, its Services, PersistentVolumeClaims and Links stay. Saved\n   configuration survives a stop and start.\n - Its links go carrier-down on every peer, like an unplugged cable;\n-  `events` reports them as interface `down` events.\n-- `inspect` shows the node as `stopped` (`stopping` while its Pod terminates).\n+  `events` reports an interface `update` with state `lower-layer-down` on the\n+  peers, and deletes the stopped node's interfaces.\n+- `inspect` shows the node as `exited` with status `Exited`.\n+- `events` reports the container actions Docker reports for `containerlab stop`\n+  and `start`: `kill`, `stop` and `die` when the node's pod goes, `start` when\n+  its new pod runs, then `health_status: starting` and\n+  `health_status: healthy` as the device boots. A restart reports `kill`,\n+  `stop`, `die` and `start`.\n - clabernetes keeps a running peer of a stopped node `notready`: its\n   connectivity sidecar waits for the far end of the wire. Deploy, apply, start\n   and restart treat such a node as settled when its containers are ready, and\n   log `link peers stopped: <nodes>` instead of waiting for it.\n \n@@ -754,12 +795,14 @@ For example:\n files, the c9s runtime has nothing to copy for that node.\n ///\n \n ## Events\n \n-The c9s runtime can stream Node, Topology, pod, interface state and\n-interface-stat events:\n+The c9s runtime streams container, interface state and interface-stat events\n+with the actions and attributes the Docker runtime reports, so a client that\n+reads Docker events reads c9s events the same way. It also streams `topology`\n+events, which only c9s has:\n \n ```bash\n containerlab --runtime c9s events --format json\n containerlab --runtime c9s events --initial-state\n containerlab --runtime c9s events --interface-stats --format json\n@@ -772,10 +815,12 @@ watches:\n \n - c9s `Node` resources carrying `c9s.run/topologyOwner`\n - `Topology` resources\n - Pods labeled with `c9s.run/topologyOwner`\n \n+and reads a lab again whenever one of them changes.\n+\n What the stream covers:\n \n | Invocation | Scope |\n |---|---|\n | `events` | every namespace |\n@@ -783,65 +828,155 @@ What the stream covers:\n | `events -t <topo>` or `events --name <lab>` | that lab, in its namespace (`c9s-<lab>`, or the namespace override) |\n \n An identity whose RBAC only covers one namespace needs one of the scoped forms;\n watching every namespace requires cluster-wide `list` and `watch`.\n \n-With `--initial-state`, the stream starts with synthetic events for the current\n-c9s node state and the state of every interface, then continues with live\n-watches.\n+### Container events\n+\n+Each node is reported as a container. Its state follows its pod: `created`\n+while the pod is scheduled and prepared, `running` once the device containers\n+run, `exited` once the node is stopped, or its pod ends or is replaced. A change\n+is reported with the actions Docker reports for the same change:\n+\n+| Change | Actions |\n+|---|---|\n+| the node appears (deploy, apply) | `create`, then `start` once its pod runs |\n+| the device boots, is ready, is not ready anymore | `health_status: starting`, `health_status: healthy`, `health_status: unhealthy` |\n+| `stop` | `kill`, `stop`, `die` |\n+| `start` | `start` |\n+| `restart`, or the pod is replaced | `kill`, `stop`, `die`, `start` |\n+| the node is removed (destroy, apply) | `kill`, `die` (when it ran), `destroy` |\n+\n+With `--initial-state`, the stream starts with one event per node whose action\n+is its state (`running`, `exited`, `created`) and `origin` `snapshot`, like the\n+snapshot of a Docker container.\n \n-Container events use the node's `<namespace>/<lab>/<node>` ID as actor, the\n-`container_id` inspect reports.\n+Every container event describes the node with the attributes of a Docker\n+container event, taken from the record `inspect` reports for the node:\n+\n+```json\n+{\n+  \"timestamp\": \"2026-10-27T10:15:02.123456789Z\",\n+  \"type\": \"container\",\n+  \"action\": \"start\",\n+  \"actor_id\": \"c9s-clos/clos/srl1\",\n+  \"actor_name\": \"clos-srl1\",\n+  \"actor_full_id\": \"c9s-clos/clos/srl1\",\n+  \"attributes\": {\n+    \"containerlab\": \"clos\",\n+    \"clab-node-name\": \"srl1\",\n+    \"clab-node-longname\": \"clos-srl1\",\n+    \"clab-node-kind\": \"nokia_srlinux\",\n+    \"clab-node-type\": \"ixr-d2l\",\n+    \"clab-topo-file\": \"/home/user/clos.clab.yml\",\n+    \"clab-owner\": \"alice\",\n+    \"image\": \"ghcr.io/nokia/srlinux\",\n+    \"mgmt_ipv4\": \"172.20.20.11/24\",\n+    \"ports\": \"22/tcp;57400/tcp\",\n+    \"state\": \"running\",\n+    \"id\": \"c9s-clos/clos/srl1\",\n+    \"name\": \"clos-srl1\",\n+    \"lab\": \"clos\",\n+    \"node\": \"srl1\",\n+    \"namespace\": \"c9s-clos\",\n+    \"pod\": \"srl1-7d9c6b5f4-x2k8p\"\n+  }\n+}\n+```\n+\n+- The actor ID is the node's `<namespace>/<lab>/<node>` ID, the `container_id`\n+  inspect reports, and `actor_name` and `name` are the inspect `name`.\n+- `clab-node-name` is the node name as the topology spells it.\n+- `clab-topo-file` is the file the lab was deployed from (see\n+  [Topology file](#topology-file)).\n+- `state` is the container state after the event: `created`, `running` or\n+  `exited`. Docker leaves it to the client to derive it from the action; c9s\n+  reports it on every container event.\n+- `ports` lists the node's exposed ports without a host binding: they are\n+  reached through the node's Service or a port-forward, not on a port of the\n+  local machine.\n+- `kill` carries `signal` `15`; Kubernetes stops containers with SIGTERM.\n+- `create` can come before the controller has allocated the node's management\n+  address and Service, so it may lack `mgmt_ipv4`, `mgmt_ipv6` and `ports`;\n+  the following events carry them.\n+- `namespace`, `lab`, `node` and `pod` are c9s attributes on top.\n+\n+Docker attributes c9s does not report: `scope`, `clab-mgmt-net-bridge` (no\n+Docker bridge), `clab-node-lab-dir` (a c9s lab has no lab directory on the\n+deploying machine; node state lives in the cluster), and `exitCode` and\n+`execDuration` on `die`. `clab-node-type` and `clab-node-group` are reported\n+when the topology sets them, and with `-t` also a kind's default type; read by\n+`--name` alone, a default type such as SR Linux's `ixr-d2l` is not known.\n \n ### Interface events\n \n Containerlab samples the interfaces of every running node by exec into its\n device container. One exec per node and interval reads `/proc/net/dev` and\n `/sys/class/net/*/operstate` (with index, MTU, MAC address, flags and alias).\n-All containers of a device pod share one network namespace, so the samples\n-cover the node's pod interfaces.\n \n-Interface state events are always streamed. They use the same schema as the\n-interface events of the local runtimes, with the operational state as action:\n+It reports the interfaces a Docker container of the same node kind has, named\n+as in that container:\n+\n+- the node's lab link interfaces, with the names and aliases clabwire lists for\n+  them (`containerlab capture --list`): `eth1` for a linux node, `e1-1` with\n+  alias `ethernet-1/1` for SR Linux, so a client finds a link's interface by\n+  the endpoint name in the topology or its alias\n+- the management interface `eth0`\n+- the loopback `lo`\n+\n+The pod's own interfaces (the pod network interface `c9s0`, clabernetes'\n+interposition interfaces `c9sr0` and `c9sm0`, and the link transport interfaces\n+`c9ss*`) are not reported, and neither are the aliases clabernetes sets for its\n+own use (`c9s:…`).\n+\n+Interface state events are always streamed, with the actions and attributes of\n+the local runtimes' netlink events:\n \n ```json\n {\n   \"timestamp\": \"2026-10-27T10:15:02.123456789Z\",\n   \"type\": \"interface\",\n-  \"action\": \"down\",\n+  \"action\": \"update\",\n   \"actor_id\": \"c9s-clos/clos/srl1\",\n   \"actor_name\": \"clos-srl1\",\n-  \"actor_full_id\": \"srl1-7d9c6b5f4-x2k8p\",\n+  \"actor_full_id\": \"c9s-clos/clos/srl1\",\n   \"attributes\": {\n     \"ifname\": \"e1-1\",\n-    \"state\": \"lowerlayerdown\",\n+    \"alias\": \"ethernet-1/1\",\n+    \"state\": \"lower-layer-down\",\n+    \"type\": \"veth\",\n     \"index\": \"7\",",
        "lineStart": 1,
        "lineEnd": 1361,
        "totalLines": 1362,
        "truncated": true
      }
    },
    "time": {
      "start": 1793525599345,
      "end": 1793525599673
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19674cdc00014Gfmr6AeT04zay",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674c79a001gjHUT18UiSAEMW",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 3715,
    "input": 399,
    "output": 51,
    "reasoning": 1,
    "cache": {
      "read": 3264,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19674c79a001gjHUT18UiSAEMW",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525598106,
    "completed": 1793525599686
  },
  "parentID": "msg_19674becc001poQpu47cHvtM8V",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 3715,
    "input": 399,
    "output": 51,
    "reasoning": 1,
    "cache": {
      "read": 3264,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 4
step-start
{
  "type": "step-start",
  "id": "prt_19674dac70014zMrv0BOyJZiwG",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674cdcb001GeL6jU7LOAlFw9"
}
read · completed

Input

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

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1362:      "mtu": "9232",
1363:      "mac": "aa:c1:ab:5e:2f:01",
1364:      "lab": "clos",
1365: -    "node": "srl1",
1366:      "name": "clos-srl1",
1367: +    "id": "c9s-clos/clos/srl1",
1368: +    "node": "srl1",
1369:      "namespace": "c9s-clos",
1370:      "pod": "srl1-7d9c6b5f4-x2k8p",
1371:      "origin": "clabernetes"
1372:    }
1373:  }
1374:  ```
1375:  
1376: -- `action` is `up` when the operational state is `up`, or `unknown` on an
1377: -  administratively up interface (loopback, tunnels); otherwise `down`.
1378: -- `attributes.state` is the raw operational state from
1379: -  `/sys/class/net/<if>/operstate`. An interface that disappears, or whose node
1380: -  stops running, is reported once as `down` with state `notpresent`.
1381: -- An event is emitted when an interface appears, when its action or state
1382: -  changes, and, with `--initial-state`, once for every interface at the start.
1383: -- Device containers without a shell report statistics only, no interface state.
1384: +- `action` is `snapshot` for every interface at the start with
1385: +  `--initial-state`, `create` when an interface appears (for example when a
1386: +  node starts), `update` when one of its attributes changes, and `delete` when
1387: +  it disappears or its node stops running.
1388: +- `state` is the operational state in netlink's names: `up`, `down`,
1389: +  `lower-layer-down`, `unknown` (loopback), `dormant`, `testing`, `not-present`.
1390: +- `type` is `veth` for the lab link and management interfaces and `device` for
1391: +  loopback.
1392: +- Device containers without a shell report statistics only, no interface state,
1393: +  and no `index` or `mtu`.
1394:  
1395:  With `--interface-stats`, the same exec also produces `interface stats` events
1396: -with byte and packet counters and rates. They use the node ID as actor, like
1397: -the state events. `--interface-stats-interval` sets the sampling interval of
1398: -both (default 1s).
1399: +for the same interfaces, with their attributes and the byte and packet counters
1400: +and rates. `--interface-stats-interval` sets the sampling interval of both
1401: +(default 1s).
1402: +
1403: +`inspect interfaces -r c9s` lists the same interfaces with the same values.
1404:  
1405:  /// note | Polling, not netlink
1406:  c9s interface state and statistics are sampled periodically. The first sample
1407:  seeds the counters, and rates start with the second sample. Short-lived changes
1408:  between samples can be missed. Every running node gets one exec per interval,
1409: diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go
1410: index 69d4072..3d50217 100644
1411: --- a/labruntime/clabernetes/capture.go
1412: +++ b/labruntime/clabernetes/capture.go
1413: @@ -237,26 +237,15 @@ func (r *Runtime) listCaptureInterfaces(
1414:  
1415:  	var mu sync.Mutex
1416:  	result := map[string][]clabwireInterface{}
1417:  	group, groupCtx := errgroup.WithContext(ctx)
1418:  	group.SetLimit(interfaceSampleWorkers)
1419: -	exec := r.execInPodContainer()
1420:  	for _, location := range pods {
1421:  		group.Go(func() error {
1422: -			var stdout, stderr bytes.Buffer
1423: -			err := exec(groupCtx, location.Namespace, location.Pod, clabwireContainer,
1424: -				[]string{clabwireManager, "node-runtime", "packet-capture", "--list-interfaces"},
1425: -				nil, &stdout, &stderr)
1426: +			entries, err := r.listPodInterfaces(groupCtx, location.Namespace, location.Pod)
1427:  			if err != nil {
1428: -				return fmt.Errorf("failed to list the capturable interfaces of pod %s/%s: %w%s",
1429: -					location.Namespace, location.Pod, err, stderrSuffix(stderr.Bytes()))
1430: -			}
1431: -
1432: -			var entries []clabwireInterface
1433: -			if err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {
1434: -				return fmt.Errorf("failed to parse the capturable interfaces of pod %s/%s: %w",
1435: -					location.Namespace, location.Pod, err)
1436: +				return err
1437:  			}
1438:  
1439:  			mu.Lock()
1440:  			defer mu.Unlock()
1441:  			for _, entry := range entries {
1442: @@ -273,10 +262,34 @@ func (r *Runtime) listCaptureInterfaces(
1443:  	}
1444:  
1445:  	return result, nil
1446:  }
1447:  
1448: +// listPodInterfaces runs clabwire's --list-interfaces in a pod: the lab link interfaces of the
1449: +// pod's nodes, with their aliases and peers.
1450: +func (r *Runtime) listPodInterfaces(
1451: +	ctx context.Context,
1452: +	namespace, pod string,
1453: +) ([]clabwireInterface, error) {
1454: +	var stdout, stderr bytes.Buffer
1455: +	err := r.execInPodContainer()(ctx, namespace, pod, clabwireContainer,
1456: +		[]string{clabwireManager, "node-runtime", "packet-capture", "--list-interfaces"},
1457: +		nil, &stdout, &stderr)
1458: +	if err != nil {
1459: +		return nil, fmt.Errorf("failed to list the capturable interfaces of pod %s/%s: %w%s",
1460: +			namespace, pod, err, stderrSuffix(stderr.Bytes()))
1461: +	}
1462: +
1463: +	var entries []clabwireInterface
1464: +	if err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {
1465: +		return nil, fmt.Errorf("failed to parse the capturable interfaces of pod %s/%s: %w",
1466: +			namespace, pod, err)
1467: +	}
1468: +
1469: +	return entries, nil
1470: +}
1471: +
1472:  func stderrSuffix(stderr []byte) string {
1473:  	text := strings.TrimSpace(string(stderr))
1474:  	if text == "" {
1475:  		return ""
1476:  	}
1477: diff --git a/labruntime/clabernetes/capture_interfaces.go b/labruntime/clabernetes/capture_interfaces.go
1478: index 21029ed..6e3df10 100644
1479: --- a/labruntime/clabernetes/capture_interfaces.go
1480: +++ b/labruntime/clabernetes/capture_interfaces.go
1481: @@ -66,15 +66,16 @@ func (r *Runtime) streamPodExec(
1482:  	}
1483:  
1484:  	return nil
1485:  }
1486:  
1487: -// InspectInterfaces lists the capturable link interfaces of the requested nodes, or of every
1488: -// running node, in the shape of `inspect interfaces`: per node (named <lab>-<node> like in
1489: -// inspect), the interface and its alias as clabwire reports them, and the MAC address, index,
1490: +// InspectInterfaces lists the interfaces of the requested nodes, or of every running node, in
1491: +// the shape of `inspect interfaces`, with the interfaces the interface events report: the lab
1492: +// link interfaces and their aliases as clabwire lists them, the management interface and
1493: +// loopback. Per node (named <lab>-<node> like in inspect) it reports the MAC address, index,
1494:  // MTU and operational state read from sysfs in the device container. A node whose device
1495: -// container has no shell reports its interfaces without these attributes.
1496: +// container has no shell reports its link interfaces without these attributes.
1497:  func (r *Runtime) InspectInterfaces(
1498:  	ctx context.Context,
1499:  	req clablabruntime.NodeRequest,
1500:  ) ([]*clabtypes.ContainerInterfaces, error) {
1501:  	r, err := r.connect(ctx, req.Identity)
1502: @@ -109,22 +110,32 @@ func (r *Runtime) InspectInterfaces(
1503:  	for _, location := range running {
1504:  		container := &clabtypes.ContainerInterfaces{
1505:  			ContainerName: req.Name + "-" + location.NodeName,
1506:  			Interfaces:    []*clabtypes.ContainerInterfaceDetails{},
1507:  		}
1508: -		for _, entry := range listed[location.NodeName] {
1509: +		sampled, hasStates := states[location.NodeName]
1510: +		for name, alias := range reportedInterfaces(listed[location.NodeName]) {
1511: +			state, ok := sampled[name]
1512: +			if !ok {
1513: +				if hasStates || (name == managementInterface || name == loopbackInterface) {
1514: +					// not present in the node (yet), or not known without its states
1515: +					continue
1516: +				}
1517: +				state = c9sIfaceState{Name: name}
1518: +			}
1519: +
1520: +			data := interfaceEventData(state, alias)
1521:  			details := &clabtypes.ContainerInterfaceDetails{
1522: -				InterfaceName:  entry.Interface,
1523: -				InterfaceAlias: entry.Alias,
1524: -				// clabwire realizes every lab link interface as a veth pair
1525: -				InterfaceType: "veth",
1526: +				InterfaceName:  data.Name,
1527: +				InterfaceAlias: data.Alias,
1528: +				InterfaceType:  data.Type,
1529: +				InterfaceMAC:   data.MAC,
1530: +				InterfaceIndex: data.Index,
1531: +				InterfaceMTU:   data.MTU,
1532:  			}
1533: -			if state, ok := states[location.NodeName][entry.Interface]; ok {
1534: -				details.InterfaceMAC = state.MAC
1535: -				details.InterfaceIndex = state.Index
1536: -				details.InterfaceMTU = state.MTU
1537: -				details.InterfaceState = state.OperState
1538: +			if ok {
1539: +				details.InterfaceState = data.OperState
1540:  			}
1541:  			container.Interfaces = append(container.Interfaces, details)
1542:  		}
1543:  		sort.Slice(container.Interfaces, func(i, j int) bool {
1544:  			return container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName
1545: diff --git a/labruntime/clabernetes/capture_test.go b/labruntime/clabernetes/capture_test.go
1546: index 16628b5..a099566 100644
1547: --- a/labruntime/clabernetes/capture_test.go
1548: +++ b/labruntime/clabernetes/capture_test.go
1549: @@ -14,10 +14,11 @@ import (
1550:  	"testing"
1551:  	"time"
1552:  
1553:  	clabcapture "github.com/srl-labs/containerlab/capture"
1554:  	clablabruntime "github.com/srl-labs/containerlab/labruntime"
1555: +	clabtypes "github.com/srl-labs/containerlab/types"
1556:  	corev1 "k8s.io/api/core/v1"
1557:  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
1558:  	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
1559:  	k8sruntime "k8s.io/apimachinery/pkg/runtime"
1560:  )
1561: @@ -713,37 +714,56 @@ func TestCaptureValidatesTargets(t *testing.T) {
1562:  	if commands := clabwire.captureCommands(); len(commands) != 0 {
1563:  		t.Fatalf("invalid requests started captures: %v", commands)
1564:  	}
1565:  }
1566:  
1567: +// TestInspectInterfacesReportsStateFromSysfs lists what a Docker container of the node reports:
1568: +// the lab link interfaces with their topology aliases, eth0 and lo, not clabernetes' own
1569: +// interfaces, with netlink's state names.
1570:  func TestInspectInterfacesReportsStateFromSysfs(t *testing.T) {
1571:  	t.Parallel()
1572:  
1573:  	r, clabwire := captureTestRuntime(t, time.Millisecond)
1574:  	clabwire.sysfs = "Inter-|   Receive\n face |bytes\n" + interfaceSysfsMarker + "\n" +
1575: -		"e1-1\t12\t9500\taa:c1:ab:00:00:01\tup\t0x1003\t\n" +
1576: +		"lo\t1\t65536\t00:00:00:00:00:00\tunknown\t0x9\t\n" +
1577: +		"c9s0\t2\t1500\t6e:43:ce:6b:3f:dc\tup\t0x1003\t\n" +
1578: +		"eth0\t4\t1450\t3a:3b:86:d8:73:37\tup\t0x1003\tc9s:interposition:v1\n" +
1579: +		"c9ss1\t6\t9500\t3e:9c:45:56:67:2f\tup\t0x1003\tc9s:direct:v1:x\n" +
1580: +		"e1-1\t12\t9500\taa:c1:ab:00:00:01\tup\t0x1003\tc9s:direct:v1:x\n" +
1581:  		"e1-2\t13\t1500\taa:c1:ab:00:00:02\tlowerlayerdown\t0x1003\t\n"
1582:  
1583:  	interfaces, err := r.InspectInterfaces(context.Background(), clablabruntime.NodeRequest{
1584:  		Name: "lab1", Nodes: []string{"R1"},
1585:  	})
1586:  	if err != nil {
1587:  		t.Fatal(err)
1588:  	}
1589:  	if len(interfaces) != 1 || interfaces[0].ContainerName != "lab1-r1" ||
1590: -		len(interfaces[0].Interfaces) != 2 {
1591: +		len(interfaces[0].Interfaces) != 4 {
1592:  		t.Fatalf("interfaces = %+v", interfaces)
1593:  	}
1594: -	first := interfaces[0].Interfaces[0]
1595: -	if first.InterfaceName != "e1-1" || first.InterfaceAlias != "ethernet-1/1" ||
1596: +	byName := map[string]*clabtypes.ContainerInterfaceDetails{}
1597: +	for _, iface := range interfaces[0].Interfaces {
1598: +		byName[iface.InterfaceName] = iface
1599: +	}
1600: +	first := byName["e1-1"]
1601: +	if first == nil || first.InterfaceAlias != "ethernet-1/1" ||
1602:  		first.InterfaceMAC != "aa:c1:ab:00:00:01" || first.InterfaceIndex != 12 ||
1603: -		first.InterfaceMTU != 9500 || first.InterfaceState != "up" {
1604: +		first.InterfaceMTU != 9500 || first.InterfaceState != "up" || first.InterfaceType != "veth" {
1605:  		t.Fatalf("e1-1 = %+v", first)
1606:  	}
1607: -	if second := interfaces[0].Interfaces[1]; second.InterfaceState != "lowerlayerdown" {
1608: +	if second := byName["e1-2"]; second == nil || second.InterfaceState != "lower-layer-down" {
1609:  		t.Fatalf("e1-2 = %+v", second)
1610:  	}
1611: +	if eth0 := byName["eth0"]; eth0 == nil || eth0.InterfaceAlias != "" ||
1612: +		eth0.InterfaceType != "veth" {
1613: +		t.Fatalf("eth0 = %+v", eth0)
1614: +	}
1615: +	if lo := byName["lo"]; lo == nil || lo.InterfaceType != "device" || lo.InterfaceMAC != "" ||
1616: +		lo.InterfaceState != "unknown" {
1617: +		t.Fatalf("lo = %+v", lo)
1618: +	}
1619:  }
1620:  
1621:  // TestCaptureClosesStdinWhenItEnds ends every clabwire process through its stdin, whether the
1622:  // caller cancels the capture or the output fails, so no capture is left running in the pod.
1623:  // TestCaptureWritesWhatItReadWhenTheContextEnds stops a capture while the output is slow and
1624: diff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go
1625: index e869191..dc202d3 100644
1626: --- a/labruntime/clabernetes/clabernetes.go
1627: +++ b/labruntime/clabernetes/clabernetes.go
1628: @@ -35,10 +35,12 @@ const (
1629:  	clabernetesAppValue   = "clabernetes"
1630:  	// persistenceReclaimRetain keeps a node's persistent claim when its Node is deleted.
1631:  	persistenceReclaimRetain = "Retain"
1632:  	// defaultContainerAnnotation names the primary device container of a c9s pod.
1633:  	defaultContainerAnnotation = "kubectl.kubernetes.io/default-container"
1634: +	// annotationDirectNodeUID names the UID of the Node a c9s pod runs.
1635: +	annotationDirectNodeUID = "c9s.run/direct-node-uid"
1636:  )
1637:  
1638:  var topologyGVR = schema.GroupVersionResource{
1639:  	Group:    "c9s.run",
1640:  	Version:  "v1alpha1",
1641: diff --git a/labruntime/clabernetes/clabernetes_test.go b/labruntime/clabernetes/clabernetes_test.go
1642: index b6e34cd..92e07a1 100644
1643: --- a/labruntime/clabernetes/clabernetes_test.go
1644: +++ b/labruntime/clabernetes/clabernetes_test.go
1645: @@ -3734,11 +3734,11 @@ func TestForwardPodWatchReconnectsOnClosedChannel(t *testing.T) {
1646:  
1647:  	r := &Runtime{}
1648:  	if !r.forwardPodWatch(
1649:  		context.Background(),
1650:  		watcher,
1651: -		make(chan clablabruntime.Event, 1),
1652: +		make(chan labRef, 1),
1653:  		make(chan error, 1),
1654:  	) {
1655:  		t.Fatal("expected closed pod watch to request reconnect")
1656:  	}
1657:  }
1658: @@ -3752,55 +3752,49 @@ func TestForwardTopologyWatchReconnectsOnClosedChannel(t *testing.T) {
1659:  	r := &Runtime{}
1660:  	if !r.forwardTopologyWatch(
1661:  		context.Background(),
1662:  		"default",
1663:  		watcher,
1664: +		make(chan labRef, 1),
1665:  		make(chan clablabruntime.Event, 1),
1666:  		make(chan error, 1),
1667:  	) {
1668:  		t.Fatal("expected closed topology watch to request reconnect")
1669:  	}
1670:  }
1671:  
1672: -func TestForwardPodWatchEmitsPodEvent(t *testing.T) {
1673: +func TestForwardPodWatchReportsTheLabOfAPod(t *testing.T) {
1674:  	t.Parallel()
1675:  
1676:  	watcher := watch.NewFake()
1677: -	events := make(chan clablabruntime.Event, 1)
1678: +	changed := make(chan labRef, 1)
1679:  	errs := make(chan error, 1)
1680:  	ctx, cancel := context.WithCancel(context.Background())
1681:  	defer cancel()
1682:  
1683:  	r := &Runtime{}
1684:  	done := make(chan bool, 1)
1685:  	go func() {
1686: -		done <- r.forwardPodWatch(ctx, watcher, events, errs)
1687: +		done <- r.forwardPodWatch(ctx, watcher, changed, errs)
1688:  	}()
1689:  
1690: +	// a pod without the lab label is not a lab's pod
1691:  	watcher.Add(&corev1.Pod{})
1692: -	watcher.Add(&corev1.Pod{
1693: +	watcher.Modify(&corev1.Pod{
1694:  		ObjectMeta: metav1.ObjectMeta{
1695:  			Name:      "pod1",
1696:  			Namespace: "lab-ns",
1697:  			Labels: map[string]string{
1698:  				labelTopologyOwner: "lab1",
1699:  				labelTopologyNode:  "node1",
1700:  			},
1701:  		},
1702: -		Status: corev1.PodStatus{
1703: -			Phase: corev1.PodRunning,
1704: -			PodIP: "10.0.0.1",
1705: -		},
1706: +		Status: corev1.PodStatus{Phase: corev1.PodRunning},
1707:  	})
1708:  
1709: -	got := <-events
1710: -	if got.ActorID != "lab-ns/lab1/node1" ||
1711: -		got.ActorName != "lab1-node1" ||
1712: -		got.ActorFullID != "pod1" ||
1713: -		got.Attributes["phase"] != string(corev1.PodRunning) ||
1714: -		got.Attributes["pod_ip"] != "10.0.0.1" {
1715: -		t.Fatalf("unexpected pod event: %+v", got)
1716: +	if got := <-changed; got != (labRef{namespace: "lab-ns", lab: "lab1"}) {
1717: +		t.Fatalf("changed lab = %+v", got)
1718:  	}
1719:  
1720:  	cancel()
1721:  	watcher.Stop()
1722:  
1723: diff --git a/labruntime/clabernetes/container_events.go b/labruntime/clabernetes/container_events.go
1724: new file mode 100644
1725: index 0000000..ef7cf21
1726: --- /dev/null
1727: +++ b/labruntime/clabernetes/container_events.go
1728: @@ -0,0 +1,363 @@
1729: +package clabernetes
1730: +
1731: +import (
1732: +	"context"
1733: +	"errors"
1734: +	"fmt"
1735: +	"strings"
1736: +	"time"
1737: +
1738: +	"github.com/charmbracelet/log"
1739: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
1740: +)
1741: +
1742: +// Container event actions, as the Docker runtime reports them.
1743: +const (
1744: +	containerActionCreate        = "create"
1745: +	containerActionStart         = "start"
1746: +	containerActionKill          = "kill"
1747: +	containerActionStop          = "stop"
1748: +	containerActionDie           = "die"
1749: +	containerActionDestroy       = "destroy"
1750: +	containerActionHealthPrefix  = "health_status: "
1751: +	containerEventSignalSIGTERM  = "15"
1752: +	containerRefreshDelay        = 200 * time.Millisecond
1753: +	containerRefreshRetryDelay   = pollInterval
1754: +	containerEventAttributeState = "state"
1755: +)
1756: +
1757: +// trackedContainer is the last reported container state of a node.
1758: +type trackedContainer struct {
1759: +	ref    labRef
1760: +	state  string
1761: +	health string
1762: +	pod    string
1763: +	// lab and node are the last observation, which a removed node is described with.
1764: +	lab  *clablabruntime.LabState
1765: +	node clablabruntime.NodeState
1766: +}
1767: +
1768: +// containerTracker turns the node states of the labs in an event scope into the container
1769: +// events the Docker runtime emits for the same lifecycle: create and start when a node's pod
1770: +// starts, kill, stop and die when it stops (on request, or between the pods of a restart),
1771: +// destroy when the node is removed, and health_status as its device becomes ready.
1772: +type containerTracker struct {
1773: +	r     *Runtime
1774: +	sink  chan<- clablabruntime.Event
1775: +	nodes map[string]*trackedContainer
1776: +}
1777: +
1778: +// trackContainers reports the container events of a scope. It reads the labs once, reporting
1779: +// them as a snapshot when the stream includes the initial state, and then reads a lab again
1780: +// whenever its Topology, Nodes or pods change. Changes that arrive together are read once.
1781: +func (r *Runtime) trackContainers(
1782: +	ctx context.Context,
1783: +	scope eventScope,
1784: +	includeInitialState bool,
1785: +	changed <-chan labRef,
1786: +	eventSink chan<- clablabruntime.Event,
1787: +	errSink chan<- error,
1788: +) {
1789: +	tracker := &containerTracker{r: r, sink: eventSink, nodes: map[string]*trackedContainer{}}
1790: +
1791: +	states, err := r.labStates(ctx, scope)
1792: +	if err != nil {
1793: +		sendEventError(ctx, errSink, err)
1794: +		return
1795: +	}
1796: +	for _, state := range states {
1797: +		tracker.observeLab(ctx, labRef{namespace: state.Namespace, lab: state.Name}, state,
1798: +			&observeSeed{snapshot: includeInitialState})
1799: +	}
1800: +
1801: +	pending := map[labRef]bool{}
1802: +	timer := time.NewTimer(time.Hour)
1803: +	timer.Stop()
1804: +	defer timer.Stop()
1805: +	armed := false
1806: +	arm := func(delay time.Duration) {
1807: +		if !armed {
1808: +			timer.Reset(delay)
1809: +			armed = true
1810: +		}
1811: +	}
1812: +
1813: +	for {
1814: +		select {
1815: +		case <-ctx.Done():
1816: +			return
1817: +		case ref := <-changed:
1818: +			pending[ref] = true
1819: +			arm(containerRefreshDelay)
1820: +		case <-timer.C:
1821: +			armed = false
1822: +			refs := pending
1823: +			pending = map[labRef]bool{}
1824: +			for ref := range refs {
1825: +				if !tracker.refresh(ctx, ref) {
1826: +					pending[ref] = true
1827: +				}
1828: +			}
1829: +			if len(pending) != 0 {
1830: +				arm(containerRefreshRetryDelay)
1831: +			}
1832: +		}
1833: +	}
1834: +}
1835: +
1836: +// observeSeed marks the first observation of a stream: it records the node states without
1837: +// reporting changes, and reports them as a snapshot when asked to.
1838: +type observeSeed struct {
1839: +	snapshot bool
1840: +}
1841: +
1842: +// refresh reads a lab again and reports what changed for its nodes. A lab that is gone reports
1843: +// its nodes as destroyed. It returns false when the lab could not be read.
1844: +func (t *containerTracker) refresh(ctx context.Context, ref labRef) bool {
1845: +	state, err := t.r.Inspect(ctx, clablabruntime.InspectRequest{
1846: +		Name:      ref.lab,
1847: +		Namespace: ref.namespace,
1848: +	})
1849: +	if err != nil {
1850: +		var notFound *labNotFoundError
1851: +		if !errors.As(err, &notFound) {
1852: +			if ctx.Err() == nil {
1853: +				log.Debug("Failed to read a C9s lab for container events",
1854: +					"namespace", ref.namespace, "lab", ref.lab, "error", err)
1855: +			}
1856: +
1857: +			return ctx.Err() != nil
1858: +		}
1859: +		state = nil
1860: +	}
1861: +
1862: +	t.observeLab(ctx, ref, state, nil)
1863: +
1864: +	return true
1865: +}
1866: +
1867: +// observeLab compares the nodes of a lab with what was reported before and reports the
1868: +// difference. A nil state removes every node of the lab.
1869: +func (t *containerTracker) observeLab(
1870: +	ctx context.Context,
1871: +	ref labRef,
1872: +	state *clablabruntime.LabState,
1873: +	seed *observeSeed,
1874: +) {
1875: +	seen := map[string]bool{}
1876: +	if state != nil {
1877: +		for idx := range state.Nodes {
1878: +			key := c9sNodeKey(state.Namespace, state.Name, state.Nodes[idx].Name)
1879: +			seen[key] = true
1880: +			t.observeNode(ctx, ref, state, state.Nodes[idx], seed)
1881: +		}
1882: +	}
1883: +
1884: +	for key, tracked := range t.nodes {
1885: +		if tracked.ref != ref || seen[key] {
1886: +			continue
1887: +		}
1888: +
1889: +		for _, action := range containerRemovalActions(tracked) {
1890: +			t.emit(ctx, tracked.lab, tracked.node, action, nil)
1891: +		}
1892: +		delete(t.nodes, key)
1893: +	}
1894: +}
1895: +
1896: +func (t *containerTracker) observeNode(
1897: +	ctx context.Context,
1898: +	ref labRef,
1899: +	state *clablabruntime.LabState,
1900: +	node clablabruntime.NodeState,
1901: +	seed *observeSeed,
1902: +) {
1903: +	key := c9sNodeKey(state.Namespace, state.Name, node.Name)
1904: +	previous := t.nodes[key]
1905: +	if node.ContainerState == "" {
1906: +		node.ContainerState = clablabruntime.ContainerStateCreated
1907: +	}
1908: +	next := &trackedContainer{
1909: +		ref:   ref,
1910: +		state: node.ContainerState,
1911: +		pod:   node.Pod,
1912: +		lab:   state,
1913: +		node:  node,
1914: +	}
1915: +	next.health = containerHealth(previous, next, node.Health)
1916: +	t.nodes[key] = next
1917: +
1918: +	if seed != nil {
1919: +		if seed.snapshot {
1920: +			t.emit(ctx, state, node, next.state, map[string]string{
1921: +				"origin": clablabruntime.EventOriginSnapshot,
1922: +			})
1923: +		}
1924: +
1925: +		return
1926: +	}
1927: +
1928: +	for _, action := range containerTransitionActions(previous, next) {
1929: +		t.emit(ctx, state, node, action, nil)
1930: +	}
1931: +}
1932: +
1933: +// containerHealth is the health a running node reports: a node that was healthy and is not
1934: +// ready anymore in the same pod is unhealthy, as a container whose healthcheck starts failing.
1935: +func containerHealth(previous, next *trackedContainer, health string) string {
1936: +	if next.state != clablabruntime.ContainerStateRunning {
1937: +		return ""
1938: +	}
1939: +	if health == "" {
1940: +		health = clablabruntime.ContainerHealthStarting
1941: +	}
1942: +	if health == clablabruntime.ContainerHealthStarting && previous != nil &&
1943: +		previous.state == clablabruntime.ContainerStateRunning && previous.pod == next.pod &&
1944: +		(previous.health == clablabruntime.ContainerHealthHealthy ||
1945: +			previous.health == clablabruntime.ContainerHealthUnhealthy) {
1946: +		return clablabruntime.ContainerHealthUnhealthy
1947: +	}
1948: +
1949: +	return health
1950: +}
1951: +
1952: +// containerTransitionActions are the container event actions Docker reports when a container
1953: +// goes from the previous to the next state:
1954: +//
1955: +//	new node            create (+ start when it runs, + stop when it is already stopped)
1956: +//	created -> running  start
1957: +//	exited  -> running  start
1958: +//	running -> exited   kill, stop, die (stop, or the old pod of a restart ending)
1959: +//	running -> created  kill, stop, die (the replacement pod of a restart not running yet)
1960: +//	running, new pod    kill, stop, die, start (restart)
1961: +//	created -> exited   stop
1962: +//
1963: +// A started node also reports its health (health_status: starting or healthy), and a running
1964: +// node reports health changes, like a container with a healthcheck.
1965: +func containerTransitionActions(previous, next *trackedContainer) []string {
1966: +	const (
1967: +		created = clablabruntime.ContainerStateCreated
1968: +		running = clablabruntime.ContainerStateRunning
1969: +		exited  = clablabruntime.ContainerStateExited
1970: +	)
1971: +
1972: +	var actions []string
1973: +	previousState := ""
1974: +	if previous != nil {
1975: +		previousState = previous.state
1976: +	}
1977: +
1978: +	switch {
1979: +	case previous == nil:
1980: +		actions = append(actions, containerActionCreate)
1981: +		switch next.state {
1982: +		case running:
1983: +			actions = append(actions, containerActionStart)
1984: +		case exited:
1985: +			actions = append(actions, containerActionStop)
1986: +		}
1987: +	case previousState == running && next.state == running && previous.pod != next.pod:
1988: +		actions = append(actions, containerActionKill, containerActionStop, containerActionDie,
1989: +			containerActionStart)
1990: +	case previousState == running && next.state != running:
1991: +		actions = append(actions, containerActionKill, containerActionStop, containerActionDie)
1992: +	case previousState != running && next.state == running:
1993: +		actions = append(actions, containerActionStart)
1994: +	case previousState == created && next.state == exited:
1995: +		actions = append(actions, containerActionStop)
1996: +	}
1997: +
1998: +	if next.state != running {
1999: +		return actions
2000: +	}
2001: +
2002: +	started := len(actions) != 0 && actions[len(actions)-1] == containerActionStart
2003: +	if !started && previous != nil && previous.health == next.health {
2004: +		return actions
2005: +	}
2006: +	if next.health == clablabruntime.ContainerHealthStarting && !started {
2007: +		return actions
2008: +	}
2009: +
2010: +	return append(actions, containerActionHealthPrefix+next.health)
2011: +}
2012: +
2013: +// containerRemovalActions are the actions Docker reports when a container is removed: a running
2014: +// one is killed and dies first.
2015: +func containerRemovalActions(previous *trackedContainer) []string {
2016: +	if previous.state == clablabruntime.ContainerStateRunning {
2017: +		return []string{containerActionKill, containerActionDie, containerActionDestroy}
2018: +	}
2019: +
2020: +	return []string{containerActionDestroy}
2021: +}
2022: +
2023: +// containerActionState is the container state after an action, which every container event
2024: +// reports in its state attribute.
2025: +func containerActionState(action, snapshotState string) string {
2026: +	switch action {
2027: +	case containerActionCreate:
2028: +		return clablabruntime.ContainerStateCreated
2029: +	case containerActionStop, containerActionDie, containerActionDestroy:
2030: +		return clablabruntime.ContainerStateExited
2031: +	case containerActionStart, containerActionKill:
2032: +		return clablabruntime.ContainerStateRunning
2033: +	}
2034: +	if strings.HasPrefix(action, containerActionHealthPrefix) {
2035: +		return clablabruntime.ContainerStateRunning
2036: +	}
2037: +
2038: +	return snapshotState
2039: +}
2040: +
2041: +func (t *containerTracker) emit(
2042: +	ctx context.Context,
2043: +	state *clablabruntime.LabState,
2044: +	node clablabruntime.NodeState,
2045: +	action string,
2046: +	extra map[string]string,
2047: +) {
2048: +	t.r.sendEvent(ctx, t.sink, c9sContainerEvent(state, node, action, extra))
2049: +}
2050: +
2051: +// c9sContainerEvent is a container event of a node. The actor is the node, as for its interface
2052: +// events; its ID is the container_id inspect reports. Lab and Node let the events command
2053: +// describe the node with the attributes inspect and the Docker runtime report.
2054: +func c9sContainerEvent(
2055: +	state *clablabruntime.LabState,
2056: +	node clablabruntime.NodeState,
2057: +	action string,
2058: +	extra map[string]string,
2059: +) clablabruntime.Event {
2060: +	key := c9sNodeKey(state.Namespace, state.Name, node.Name)
2061: +	attributes := map[string]string{
2062: +		"namespace":                  state.Namespace,
2063: +		"lab":                        state.Name,
2064: +		"node":                       node.Name,
2065: +		containerEventAttributeState: containerActionState(action, node.ContainerState),
2066: +	}
2067: +	if node.Pod != "" {
2068: +		attributes["pod"] = node.Pod
2069: +	}
2070: +	if action == containerActionKill {
2071: +		// Kubernetes stops a pod's containers with SIGTERM.
2072: +		attributes["signal"] = containerEventSignalSIGTERM
2073: +	}
2074: +	for k, v := range extra {
2075: +		attributes[k] = v
2076: +	}
2077: +
2078: +	nodeCopy := node
2079: +
2080: +	return clablabruntime.Event{
2081: +		Timestamp:   time.Now(),
2082: +		Type:        clablabruntime.EventTypeContainer,
2083: +		Action:      action,
2084: +		ActorID:     key,
2085: +		ActorName:   fmt.Sprintf("%s-%s", state.Name, node.Name),
2086: +		ActorFullID: key,
2087: +		Attributes:  attributes,
2088: +		Lab:         state,
2089: +		Node:        &nodeCopy,
2090: +	}
2091: +}
2092: diff --git a/labruntime/clabernetes/event_parity_test.go b/labruntime/clabernetes/event_parity_test.go
2093: new file mode 100644
2094: index 0000000..faddcfe
2095: --- /dev/null
2096: +++ b/labruntime/clabernetes/event_parity_test.go
2097: @@ -0,0 +1,1008 @@
2098: +package clabernetes
2099: +
2100: +import (
2101: +	"context"
2102: +	"encoding/json"
2103: +	"io"
2104: +	"slices"
2105: +	"strings"
2106: +	"sync"
2107: +	"testing"
2108: +	"time"
2109: +
2110: +	clablabruntime "github.com/srl-labs/containerlab/labruntime"
2111: +	corev1 "k8s.io/api/core/v1"
2112: +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2113: +	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
2114: +	k8sruntime "k8s.io/apimachinery/pkg/runtime"
2115: +)
2116: +
2117: +// podInterfaces is the sysfs view of a c9s pod: the device's interfaces and clabernetes' own.
2118: +func podInterfaces(link string, linkState string) []c9sIfaceState {
2119: +	return []c9sIfaceState{
2120: +		{Name: "lo", Index: 1, MTU: 65536, MAC: zeroMAC, OperState: "unknown"},
2121: +		{Name: "c9s0", Index: 2, MTU: 1500, MAC: "6e:43:ce:6b:3f:dc", OperState: "up"},
2122: +		{
2123: +			Name: "c9sr0", Index: 3, MTU: 1450, MAC: "02:c9:20:eb:f4:ff", OperState: "up",
2124: +			Alias: "c9s:interposition:v1",
2125: +		},
2126: +		{
2127: +			Name: "eth0", Index: 4, MTU: 1450, MAC: "3a:3b:86:d8:73:37", OperState: "up",
2128: +			Alias: "c9s:interposition:v1",
2129: +		},
2130: +		{
2131: +			Name: "c9sm0", Index: 5, MTU: 1450, MAC: "06:c9:ac:14:14:54", OperState: "unknown",
2132: +			Alias: "c9s:interposition:v1",
2133: +		},
2134: +		{
2135: +			Name: "c9ss73388031", Index: 6, MTU: 9500, MAC: "3e:9c:45:56:67:2f", OperState: "up",
2136: +			Alias: "c9s:direct:v1:e332:transport:98d2",
2137: +		},
2138: +		{
2139: +			Name: link, Index: 7, MTU: 9500, MAC: "fe:0b:87:7a:1d:5a", OperState: linkState,
2140: +			Alias: "c9s:direct:v1:e332:transport:98d2",
2141: +		},
2142: +	}
2143: +}
2144: +
2145: +func interfaceTestSample(
2146: +	node string,
2147: +	ts time.Time,
2148: +	links []clabwireInterface,
2149: +	ifaces []c9sIfaceState,
2150: +) interfaceSample {
2151: +	stats := make([]c9sIfaceStats, 0, len(ifaces))
2152: +	for _, iface := range ifaces {
2153: +		stats = append(stats, c9sIfaceStats{Name: iface.Name, RxBytes: uint64(ts.Unix())})
2154: +	}
2155: +
2156: +	return interfaceSample{
2157: +		target: interfaceSampleTarget{
2158: +			state: &clablabruntime.LabState{Name: "lab1", Namespace: "c9s-lab1"},
2159: +			node: clablabruntime.NodeState{
2160: +				Name: node, Pod: "lab1-" + node + "-abc",
2161: +				ContainerState: clablabruntime.ContainerStateRunning,
2162: +			},
2163: +			pod: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "lab1-" + node + "-abc"}},
2164: +		},
2165: +		stats:     stats,
2166: +		ifaces:    ifaces,
2167: +		hasStates: true,
2168: +		links:     links,
2169: +		timestamp: ts,
2170: +	}
2171: +}
2172: +
2173: +func interfacesByName(events []clablabruntime.Event) map[string]clablabruntime.Event {
2174: +	byName := map[string]clablabruntime.Event{}
2175: +	for _, ev := range events {
2176: +		byName[ev.Interface.Name] = ev
2177: +	}
2178: +
2179: +	return byName
2180: +}
2181: +
2182: +func TestNetlinkOperState(t *testing.T) {
2183: +	t.Parallel()
2184: +
2185: +	for sysfs, want := range map[string]string{
2186: +		"up":             "up",
2187: +		"down":           "down",
2188: +		"unknown":        "unknown",
2189: +		"dormant":        "dormant",
2190: +		"testing":        "testing",
2191: +		"notpresent":     "not-present",
2192: +		"lowerlayerdown": "lower-layer-down",
2193: +		"":               "unknown",
2194: +	} {
2195: +		if got := netlinkOperState(sysfs); got != want {
2196: +			t.Fatalf("netlinkOperState(%q) = %q, want %q", sysfs, got, want)
2197: +		}
2198: +	}
2199: +}
2200: +
2201: +// TestInterfaceEventDataNamesInterfacesLikeDocker checks the names, aliases, types and states a
2202: +// Docker container of the same node kind reports: linux eth1 without an alias, SR Linux e1-1
2203: +// with the topology's ethernet-1/1, eth0 and loopback, and no clabernetes alias.
2204: +func TestInterfaceEventDataNamesInterfacesLikeDocker(t *testing.T) {
2205: +	t.Parallel()
2206: +
2207: +	ifaces := map[string]c9sIfaceState{}
2208: +	for _, iface := range podInterfaces("e1-1", "lowerlayerdown") {
2209: +		ifaces[iface.Name] = iface
2210: +	}
2211: +	ifaces["eth1"] = c9sIfaceState{
2212: +		Name: "eth1", Index: 8, MTU: 9500, OperState: "up", Alias: "c9s:direct:v1:x",
2213: +	}
2214: +
2215: +	tests := []struct {
2216: +		iface, alias string
2217: +		want         clablabruntime.InterfaceEventData
2218: +	}{
2219: +		{"eth1", "", clablabruntime.InterfaceEventData{
2220: +			Name: "eth1", Index: 8, MTU: 9500, OperState: "up", Type: "veth",
2221: +		}},
2222: +		{"e1-1", "ethernet-1/1", clablabruntime.InterfaceEventData{
2223: +			Name: "e1-1", Alias: "ethernet-1/1", Index: 7, MTU: 9500, MAC: "fe:0b:87:7a:1d:5a",
2224: +			OperState: "lower-layer-down", Type: "veth",
2225: +		}},
2226: +		{"eth0", "", clablabruntime.InterfaceEventData{
2227: +			Name: "eth0", Index: 4, MTU: 1450, MAC: "3a:3b:86:d8:73:37", OperState: "up",
2228: +			Type: "veth",
2229: +		}},
2230: +		{"lo", "", clablabruntime.InterfaceEventData{
2231: +			Name: "lo", Index: 1, MTU: 65536, OperState: "unknown", Type: "device",
2232: +		}},
2233: +	}
2234: +	for _, tt := range tests {
2235: +		if got := interfaceEventData(ifaces[tt.iface], tt.alias); got != tt.want {
2236: +			t.Fatalf("%s = %+v, want %+v", tt.iface, got, tt.want)
2237: +		}
2238: +	}
2239: +
2240: +	// an alias set inside the node is the interface's alias, as netlink reports it
2241: +	got := interfaceEventData(c9sIfaceState{Name: "eth2", Alias: "uplink"}, "")
2242: +	if got.Alias != "uplink" {
2243: +		t.Fatalf("own alias = %+v", got)
2244: +	}
2245: +}
2246: +
2247: +// TestInterfacePollerReportsTheTopologyInterfaces runs a linux and an SR Linux node through the
2248: +// poller: only the lab link interfaces (named and aliased as clabwire lists them), eth0 and lo
2249: +// are reported, with the actions of the netlink events.
2250: +func TestInterfacePollerReportsTheTopologyInterfaces(t *testing.T) {
2251: +	t.Parallel()
2252: +
2253: +	tests := []struct {
2254: +		name  string
2255: +		link  string
2256: +		alias string
2257: +	}{
2258: +		{name: "linux", link: "eth1"},
2259: +		{name: "srl", link: "e1-1", alias: "ethernet-1/1"},
2260: +	}
2261: +	for _, tt := range tests {
2262: +		t.Run(tt.name, func(t *testing.T) {
2263: +			t.Parallel()
2264: +
2265: +			links := []clabwireInterface{{
2266: +				Node: "r1", Interface: tt.link, Alias: tt.alias,
2267: +				PeerNode: "r2", PeerInterface: tt.link,
2268: +			}}
2269: +			sink := make(chan clablabruntime.Event, 64)
2270: +			p := newInterfacePoller(&Runtime{}, eventScope{},
2271: +				interfacePollOptions{includeInitialState: true}, sink)
2272: +			ctx := context.Background()
2273: +			start := time.Now()
2274: +
2275: +			p.processSample(
2276: +				ctx,
2277: +				interfaceTestSample("r1", start, links, podInterfaces(tt.link, "up")),
2278: +			)
2279: +			got := interfacesByName(drain(sink))
2280: +			if len(got) != 3 {
2281: +				t.Fatalf("first round reported %v, want %s, eth0 and lo", got, tt.link)
2282: +			}
2283: +			link := got[tt.link]
2284: +			if link.Action != interfaceActionSnapshot ||
2285: +				link.Type != clablabruntime.EventTypeInterface ||
2286: +				link.ActorID != "c9s-lab1/lab1/r1" ||
2287: +				link.ActorFullID != "c9s-lab1/lab1/r1" ||
2288: +				link.ActorName != "lab1-r1" || link.Interface.Alias != tt.alias ||
2289: +				link.Interface.OperState != "up" || link.Interface.Type != "veth" ||
2290: +				link.Lab == nil || link.Node == nil || link.Node.Name != "r1" ||
2291: +				link.Attributes["origin"] != "clabernetes" ||
2292: +				link.Attributes["pod"] != "lab1-r1-abc" ||
2293: +				link.Attributes["namespace"] != "c9s-lab1" {
2294: +				t.Fatalf("%s event = %+v", tt.link, link)
2295: +			}
2296: +			if got["lo"].Interface.Type != "device" || got["eth0"].Interface.Alias != "" {
2297: +				t.Fatalf("eth0/lo = %+v %+v", got["eth0"].Interface, got["lo"].Interface)
2298: +			}
2299: +
2300: +			// unchanged: nothing
2301: +			p.firstRound = false
2302: +			p.processSample(ctx, interfaceTestSample("r1", start.Add(time.Second), links,
2303: +				podInterfaces(tt.link, "up")))
2304: +			if events := drain(sink); len(events) != 0 {
2305: +				t.Fatalf("unchanged interfaces reported %+v", events)
2306: +			}
2307: +
2308: +			// the peer goes away: the link loses its carrier
2309: +			p.processSample(ctx, interfaceTestSample("r1", start.Add(2*time.Second), links,
2310: +				podInterfaces(tt.link, "lowerlayerdown")))
2311: +			events := drain(sink)
2312: +			if len(events) != 1 || events[0].Action != interfaceActionUpdate ||
2313: +				events[0].Interface.Name != tt.link ||
2314: +				events[0].Interface.OperState != "lower-layer-down" {
2315: +				t.Fatalf("carrier loss reported %+v", events)
2316: +			}
2317: +
2318: +			// the link interface disappears, then comes back
2319: +			withoutLink := podInterfaces(tt.link, "up")
2320: +			withoutLink = withoutLink[:len(withoutLink)-1]
2321: +			p.processSample(
2322: +				ctx,
2323: +				interfaceTestSample("r1", start.Add(3*time.Second), links, withoutLink),
2324: +			)
2325: +			events = drain(sink)
2326: +			if len(events) != 1 || events[0].Action != interfaceActionDelete ||
2327: +				events[0].Interface.Name != tt.link {
2328: +				t.Fatalf("removed link reported %+v", events)
2329: +			}
2330: +			p.processSample(ctx, interfaceTestSample("r1", start.Add(4*time.Second), links,
2331: +				podInterfaces(tt.link, "up")))
2332: +			events = drain(sink)
2333: +			if len(events) != 1 || events[0].Action != interfaceActionCreate ||
2334: +				events[0].Interface.Alias != tt.alias {
2335: +				t.Fatalf("new link reported %+v", events)
2336: +			}
2337: +
2338: +			// the node stops: its interfaces are deleted
2339: +			p.retireStoppedNodes(ctx, map[string]bool{})
2340: +			got = interfacesByName(drain(sink))
2341: +			if len(got) != 3 || got[tt.link].Action != interfaceActionDelete ||
2342: +				got["eth0"].Action != interfaceActionDelete || len(p.nodes) != 0 {
2343: +				t.Fatalf("stopped node reported %+v", got)
2344: +			}
2345: +		})
2346: +	}
2347: +}
2348: +
2349: +func TestInterfacePollerFirstRoundWithoutInitialState(t *testing.T) {
2350: +	t.Parallel()
2351: +
2352: +	sink := make(chan clablabruntime.Event, 16)
2353: +	p := newInterfacePoller(&Runtime{}, eventScope{}, interfacePollOptions{}, sink)
2354: +	links := []clabwireInterface{{Node: "r1", Interface: "eth1"}}
2355: +	p.processSample(context.Background(),
2356: +		interfaceTestSample("r1", time.Now(), links, podInterfaces("eth1", "up")))
2357: +	if events := drain(sink); len(events) != 0 {
2358: +		t.Fatalf("first round without --initial-state reported %+v", events)
2359: +	}
2360: +}
2361: +
2362: +func TestInterfacePollerStatsCoverTheReportedInterfaces(t *testing.T) {
2363: +	t.Parallel()
2364: +
2365: +	sink := make(chan clablabruntime.Event, 32)
2366: +	p := newInterfacePoller(
2367: +		&Runtime{},
2368: +		eventScope{},
2369: +		interfacePollOptions{includeStats: true},
2370: +		sink,
2371: +	)
2372: +	links := []clabwireInterface{{Node: "r1", Interface: "e1-1", Alias: "ethernet-1/1"}}
2373: +	start := time.Now()
2374: +	first := interfaceTestSample("r1", start, links, podInterfaces("e1-1", "up"))
2375: +	second := interfaceTestSample("r1", start.Add(time.Second), links, podInterfaces("e1-1", "up"))
2376: +	for idx := range second.stats {
2377: +		second.stats[idx].RxBytes = first.stats[idx].RxBytes + 1000
2378: +	}
2379: +
2380: +	p.processSample(context.Background(), first)
2381: +	_ = drain(sink)
2382: +	p.processSample(context.Background(), second)
2383: +	got := interfacesByName(drain(sink))
2384: +	if len(got) != 3 {
2385: +		t.Fatalf("stats reported for %v, want e1-1, eth0 and lo", got)
2386: +	}
2387: +	stats := got["e1-1"]
2388: +	if stats.Action != interfaceActionStats || stats.Interface.Alias != "ethernet-1/1" ||
2389: +		stats.Interface.Index != 7 || stats.Interface.OperState != "up" ||
2390: +		stats.Interface.Stats == nil || stats.Interface.Stats.RxBps != 8000 ||
2391: +		stats.Interface.Stats.Interval != time.Second {
2392: +		t.Fatalf("e1-1 stats = %+v %+v", stats, stats.Interface)
2393: +	}
2394: +}
2395: +
2396: +// listingExec answers clabwire --list-interfaces with the listing of the pod and counts the
2397: +// listings.
2398: +type listingExec struct {
2399: +	mu       sync.Mutex
2400: +	listings map[string][]clabwireInterface
2401: +	calls    int
2402: +}
2403: +
2404: +func (l *listingExec) exec(
2405: +	_ context.Context,
2406: +	_, pod, container string,
2407: +	command []string,
2408: +	_ io.Reader,
2409: +	stdout, _ io.Writer,
2410: +) error {
2411: +	l.mu.Lock()
2412: +	defer l.mu.Unlock()
2413: +
2414: +	if container != clabwireContainer || !slices.Contains(command, "--list-interfaces") {
2415: +		return nil
2416: +	}
2417: +	l.calls++
2418: +
2419: +	return json.NewEncoder(stdout).Encode(l.listings[pod])
2420: +}
2421: +
2422: +func TestInterfacePollerListsAPodOncePerInterfaceSet(t *testing.T) {
2423: +	t.Parallel()
2424: +
2425: +	listing := &listingExec{listings: map[string][]clabwireInterface{
2426: +		"lab1-r1-abc": {
2427: +			{Node: "r1", Interface: "e1-1", Alias: "ethernet-1/1"},
2428: +			{Node: "r1b", Interface: "e1-2"},
2429: +		},
2430: +	}}
2431: +	r := &Runtime{podExec: listing.exec}
2432: +	p := newInterfacePoller(
2433: +		r,
2434: +		eventScope{},
2435: +		interfacePollOptions{},
2436: +		make(chan clablabruntime.Event),
2437: +	)
2438: +	target := interfaceTestSample("r1", time.Now(), nil, nil).target
2439: +
2440: +	for range 3 {
2441: +		links, err := p.nodeLinks(context.Background(), target, "e1-1,eth0,lo")
2442: +		if err != nil {
2443: +			t.Fatal(err)
2444: +		}
2445: +		if len(links) != 1 || links[0].Alias != "ethernet-1/1" {
2446: +			t.Fatalf("links = %+v, want the node's own link", links)
2447: +		}
2448: +	}
2449: +	if listing.calls != 1 {
2450: +		t.Fatalf("listed %d times, want once while the interfaces stay the same", listing.calls)
2451: +	}
2452: +
2453: +	if _, err := p.nodeLinks(context.Background(), target, "e1-1,e1-2,eth0,lo"); err != nil {
2454: +		t.Fatal(err)
2455: +	}
2456: +	if listing.calls != 2 {
2457: +		t.Fatalf("listed %d times, want again after the interfaces changed", listing.calls)
2458: +	}
2459: +
2460: +	p.forgetListings(map[string]bool{})
2461: +	if len(p.listings) != 0 {
2462: +		t.Fatalf("listings of gone pods kept: %+v", p.listings)
2463: +	}
2464: +}
2465: +
2466: +func TestContainerTransitionActions(t *testing.T) {
2467: +	t.Parallel()
2468: +
2469: +	const (
2470: +		created = clablabruntime.ContainerStateCreated
2471: +		running = clablabruntime.ContainerStateRunning
2472: +		exited  = clablabruntime.ContainerStateExited
2473: +		healthy = clablabruntime.ContainerHealthHealthy
2474: +		start   = clablabruntime.ContainerHealthStarting
2475: +		sick    = clablabruntime.ContainerHealthUnhealthy
2476: +	)
2477: +	tracked := func(state, health, pod string) *trackedContainer {
2478: +		return &trackedContainer{state: state, health: health, pod: pod}
2479: +	}
2480: +
2481: +	tests := []struct {
2482: +		name     string
2483: +		previous *trackedContainer
2484: +		next     *trackedContainer
2485: +		want     string
2486: +	}{
2487: +		{"new pending node", nil, tracked(created, "", ""), "create"},
2488: +		{
2489: +			"new running node", nil, tracked(running, start, "p1"),
2490: +			"create,start,health_status: starting",
2491: +		},
2492: +		{
2493: +			"new ready node", nil, tracked(running, healthy, "p1"),
2494: +			"create,start,health_status: healthy",
2495: +		},
2496: +		{"new stopped node", nil, tracked(exited, "", ""), "create,stop"},
2497: +		{
2498: +			"pod starts", tracked(created, "", "p1"), tracked(running, start, "p1"),
2499: +			"start,health_status: starting",
2500: +		},
2501: +		{
2502: +			"device ready", tracked(running, start, "p1"), tracked(running, healthy, "p1"),
2503: +			"health_status: healthy",
2504: +		},
2505: +		{"still booting", tracked(running, start, "p1"), tracked(running, start, "p1"), ""},
2506: +		{"no change", tracked(running, healthy, "p1"), tracked(running, healthy, "p1"), ""},
2507: +		{
2508: +			"device not ready again", tracked(running, healthy, "p1"), tracked(running, sick, "p1"),
2509: +			"health_status: unhealthy",
2510: +		},
2511: +		{"stop", tracked(running, healthy, "p1"), tracked(exited, "", ""), "kill,stop,die"},
2512: +		{
2513: +			"start", tracked(exited, "", ""), tracked(running, healthy, "p2"),
2514: +			"start,health_status: healthy",
2515: +		},
2516: +		{
2517: +			"restart, new pod pending", tracked(running, healthy, "p1"), tracked(created, "", "p2"),
2518: +			"kill,stop,die",
2519: +		},
2520: +		{
2521: +			"restart, new pod running", tracked(running, healthy, "p1"),
2522: +			tracked(running, start, "p2"), "kill,stop,die,start,health_status: starting",
2523: +		},
2524: +		{"stopped before it ran", tracked(created, "", "p1"), tracked(exited, "", ""), "stop"},
2525: +		{"stopped node rescheduled", tracked(exited, "", ""), tracked(created, "", "p2"), ""},
2526: +	}
2527: +	for _, tt := range tests {
2528: +		got := strings.Join(containerTransitionActions(tt.previous, tt.next), ",")
2529: +		if got != tt.want {
2530: +			t.Fatalf("%s: actions = %q, want %q", tt.name, got, tt.want)
2531: +		}
2532: +	}
2533: +
2534: +	if got := strings.Join(containerRemovalActions(tracked(running, healthy, "p1")), ","); got !=
2535: +		"kill,die,destroy" {
2536: +		t.Fatalf("removal of a running node = %q", got)
2537: +	}
2538: +	if got := strings.Join(
2539: +		containerRemovalActions(tracked(exited, "", "")),
2540: +		",",
2541: +	); got != "destroy" {
2542: +		t.Fatalf("removal of a stopped node = %q", got)
2543: +	}
2544: +
2545: +	// health: a running node that was healthy and is not ready anymore in the same pod is
2546: +	// unhealthy; in a new pod it starts again
2547: +	previous := tracked(running, healthy, "p1")
2548: +	if got := containerHealth(previous, tracked(running, "", "p1"), start); got != sick {
2549: +		t.Fatalf("health in the same pod = %q", got)
2550: +	}
2551: +	if got := containerHealth(previous, tracked(running, "", "p2"), start); got != start {
2552: +		t.Fatalf("health in a new pod = %q", got)
2553: +	}
2554: +}
2555: +
2556: +// trackerTestNode is a Node of lab1 in lab-ns.
2557: +func trackerTestNode(
2558: +	name string,
2559: +	runState string,
2560: +	conditions ...map[string]any,
2561: +) *unstructured.Unstructured {
2562: +	status := map[string]any{
2563: +		"readiness":        "notready",
2564: +		"directContainers": []any{map[string]any{"name": "node-" + name, "id": name}},
2565: +	}
2566: +	rawConditions := []any{}
2567: +	for _, condition := range conditions {
2568: +		rawConditions = append(rawConditions, condition)
2569: +		if condition["type"] == "Ready" && condition["status"] == "True" {
2570: +			status["readiness"] = "ready"
2571: +		}
2572: +	}
2573: +	status["conditions"] = rawConditions
2574: +
2575: +	return &unstructured.Unstructured{Object: map[string]any{
2576: +		"apiVersion": c9sAPIVersion,
2577: +		"kind":       "Node",
2578: +		"metadata": map[string]any{
2579: +			"name": name, "namespace": "lab-ns", "uid": "uid-" + name,
2580: +			"labels": map[string]any{
2581: +				labelTopologyOwner: "lab1", labelOriginalNodeName: strings.ToUpper(name),
2582: +			},
2583: +		},
2584: +		"spec":   map[string]any{"kind": "linux", "image": "alpine", "runState": runState},
2585: +		"status": status,
2586: +	}}
2587: +}
2588: +
2589: +func condition(conditionType, status string) map[string]any {
2590: +	return map[string]any{"type": conditionType, "status": status}
2591: +}
2592: +
2593: +func trackerTestPod(name string, phase corev1.PodPhase) *corev1.Pod {
2594: +	pod := captureTestPod(name, "r1")
2595: +	pod.Status.Phase = phase
2596: +
2597: +	return pod
2598: +}
2599: +
2600: +type trackerHarness struct {
2601: +	t       *testing.T
2602: +	r       *Runtime
2603: +	tracker *containerTracker
2604: +	sink    chan clablabruntime.Event
2605: +}
2606: +
2607: +func newTrackerHarness(
2608: +	t *testing.T,
2609: +	node *unstructured.Unstructured,
2610: +	pods ...*corev1.Pod,
2611: +) *trackerHarness {
2612: +	t.Helper()
2613: +
2614: +	kubeObjects := make([]k8sruntime.Object, 0, len(pods))
2615: +	for _, pod := range pods {
2616: +		kubeObjects = append(kubeObjects, pod)
2617: +	}
2618: +	r := newTestRuntimeWithKubeObjects([]*unstructured.Unstructured{node}, kubeObjects)
2619: +	r.labNamespaceOverride = "lab-ns"
2620: +	sink := make(chan clablabruntime.Event, 64)
2621: +
2622: +	return &trackerHarness{
2623: +		t: t, r: r, sink: sink,
2624: +		tracker: &containerTracker{r: r, sink: sink, nodes: map[string]*trackedContainer{}},
2625: +	}
2626: +}
2627: +
2628: +func (h *trackerHarness) seed(snapshot bool) {
2629: +	h.t.Helper()
2630: +
2631: +	state, err := h.r.Inspect(context.Background(), clablabruntime.InspectRequest{Name: "lab1"})
2632: +	if err != nil {
2633: +		h.t.Fatal(err)
2634: +	}
2635: +	h.tracker.observeLab(context.Background(), labRef{namespace: "lab-ns", lab: "lab1"}, state,
2636: +		&observeSeed{snapshot: snapshot})
2637: +}
2638: +
2639: +func (h *trackerHarness) setNode(node *unstructured.Unstructured) {
2640: +	h.t.Helper()
2641: +
2642: +	if _, err := h.r.client.Resource(nodeGVR).Namespace("lab-ns").
2643: +		Update(context.Background(), node, metav1.UpdateOptions{}); err != nil {
2644: +		h.t.Fatal(err)
2645: +	}
2646: +}
2647: +
2648: +func (h *trackerHarness) deletePod(name string) {
2649: +	h.t.Helper()
2650: +
2651: +	if err := h.r.kubeClient.CoreV1().Pods("lab-ns").
2652: +		Delete(context.Background(), name, metav1.DeleteOptions{}); err != nil {
2653: +		h.t.Fatal(err)
2654: +	}
2655: +}
2656: +
2657: +func (h *trackerHarness) addPod(pod *corev1.Pod) {
2658: +	h.t.Helper()
2659: +
2660: +	if _, err := h.r.kubeClient.CoreV1().Pods("lab-ns").
2661: +		Create(context.Background(), pod, metav1.CreateOptions{}); err != nil {
2662: +		h.t.Fatal(err)
2663: +	}
2664: +}
2665: +
2666: +// refresh reads lab1 again and returns the reported actions with their state attribute.
2667: +func (h *trackerHarness) refresh() string {
2668: +	h.t.Helper()
2669: +
2670: +	if !h.tracker.refresh(context.Background(), labRef{namespace: "lab-ns", lab: "lab1"}) {
2671: +		h.t.Fatal("refresh failed")
2672: +	}
2673: +
2674: +	var actions []string
2675: +	for _, ev := range drain(h.sink) {
2676: +		if ev.Type != clablabruntime.EventTypeContainer || ev.ActorID != "lab-ns/lab1/r1" ||
2677: +			ev.ActorFullID != "lab-ns/lab1/r1" || ev.ActorName != "lab1-r1" ||
2678: +			ev.Lab == nil || ev.Node == nil || ev.Node.TopologyName != "R1" ||
2679: +			ev.Attributes["lab"] != "lab1" || ev.Attributes["node"] != "r1" ||
2680: +			ev.Attributes["namespace"] != "lab-ns" {
2681: +			h.t.Fatalf("container event = %+v", ev)
2682: +		}
2683: +		action := ev.Action + "=" + ev.Attributes["state"]
2684: +		if signal := ev.Attributes["signal"]; signal != "" {
2685: +			action += "/" + signal
2686: +		}
2687: +		actions = append(actions, action)
2688: +	}
2689: +
2690: +	return strings.Join(actions, ",")
2691: +}
2692: +
2693: +// TestContainerTrackerReportsTheNodeLifecycle drives one node through boot, readiness, stop,
2694: +// start, restart and removal on the fake cluster and checks the Docker container events.
2695: +func TestContainerTrackerReportsTheNodeLifecycle(t *testing.T) {
2696: +	t.Parallel()
2697: +
2698: +	node := trackerTestNode("r1", nodeRunStateRunning)
2699: +	h := newTrackerHarness(t, node, trackerTestPod("lab1-r1-a", corev1.PodPending))
2700: +	h.seed(true)
2701: +	snapshot := drain(h.sink)
2702: +	if len(snapshot) != 1 || snapshot[0].Action != "created" ||
2703: +		snapshot[0].Attributes["origin"] != clablabruntime.EventOriginSnapshot ||
2704: +		snapshot[0].Attributes["state"] != "created" {
2705: +		t.Fatalf("snapshot = %+v", snapshot)
2706: +	}
2707: +
2708: +	// the pod runs, the device boots
2709: +	h.deletePod("lab1-r1-a")
2710: +	h.addPod(trackerTestPod("lab1-r1-a", corev1.PodRunning))
2711: +	if got := h.refresh(); got != "start=running,health_status: starting=running" {
2712: +		t.Fatalf("pod running: %s", got)
2713: +	}
2714: +
2715: +	// the device is ready
2716: +	h.setNode(trackerTestNode("r1", nodeRunStateRunning,
2717: +		condition("Ready", "True"), condition(nodeConditionContainersReady, "True")))
2718: +	if got := h.refresh(); got != "health_status: healthy=running" {
2719: +		t.Fatalf("ready: %s", got)
2720: +	}
2721: +	if got := h.refresh(); got != "" {
2722: +		t.Fatalf("unchanged: %s", got)
2723: +	}
2724: +
2725: +	// stop: the Node is stopped and its pod goes
2726: +	h.setNode(trackerTestNode("r1", nodeRunStateStopped,
2727: +		condition(nodeConditionStopped, "True")))
2728: +	h.deletePod("lab1-r1-a")
2729: +	if got := h.refresh(); got != "kill=running/15,stop=exited,die=exited" {
2730: +		t.Fatalf("stop: %s", got)
2731: +	}
2732: +
2733: +	// start: a new pod
2734: +	h.setNode(trackerTestNode("r1", nodeRunStateRunning))
2735: +	h.addPod(trackerTestPod("lab1-r1-b", corev1.PodPending))
2736: +	if got := h.refresh(); got != "" {
2737: +		t.Fatalf("start requested: %s", got)
2738: +	}
2739: +	h.deletePod("lab1-r1-b")
2740: +	h.addPod(trackerTestPod("lab1-r1-b", corev1.PodRunning))
2741: +	h.setNode(
2742: +		trackerTestNode("r1", nodeRunStateRunning, condition(nodeConditionContainersReady, "True")),
2743: +	)
2744: +	if got := h.refresh(); got != "start=running,health_status: healthy=running" {
2745: +		t.Fatalf("started: %s", got)
2746: +	}
2747: +
2748: +	// restart: the pod is replaced
2749: +	h.deletePod("lab1-r1-b")
2750: +	h.addPod(trackerTestPod("lab1-r1-c", corev1.PodRunning))
2751: +	if got := h.refresh(); got !=
2752: +		"kill=running/15,stop=exited,die=exited,start=running,health_status: healthy=running" {
2753: +		t.Fatalf("restart: %s", got)
2754: +	}
2755: +
2756: +	// destroy
2757: +	if err := h.r.client.Resource(nodeGVR).Namespace("lab-ns").
2758: +		Delete(context.Background(), "r1", metav1.DeleteOptions{}); err != nil {
2759: +		t.Fatal(err)
2760: +	}
2761: +	if got := h.refresh(); got != "kill=running/15,die=exited,destroy=exited" {
2762: +		t.Fatalf("destroy: %s", got)
2763: +	}
2764: +	if len(h.tracker.nodes) != 0 {
2765: +		t.Fatalf("destroyed node still tracked: %+v", h.tracker.nodes)
2766: +	}
2767: +}
2768: +
2769: +func TestContainerTrackerSeedsWithoutSnapshot(t *testing.T) {
2770: +	t.Parallel()
2771: +
2772: +	h := newTrackerHarness(t, trackerTestNode("r1", nodeRunStateRunning,
2773: +		condition("Ready", "True")), trackerTestPod("lab1-r1-a", corev1.PodRunning))
2774: +	h.seed(false)
2775: +	if events := drain(h.sink); len(events) != 0 {
2776: +		t.Fatalf("seed without --initial-state reported %+v", events)
2777: +	}
2778: +	if got := h.refresh(); got != "" {
2779: +		t.Fatalf("unchanged after seed: %s", got)
2780: +	}
2781: +}
2782: +
2783: +func TestNodeContainerState(t *testing.T) {
2784: +	t.Parallel()
2785: +
2786: +	deleting := metav1.NewTime(time.Now())
2787: +	pod := func(phase corev1.PodPhase, deleted bool) *corev1.Pod {
2788: +		p := &corev1.Pod{Status: corev1.PodStatus{Phase: phase}}
2789: +		if deleted {
2790: +			p.DeletionTimestamp = &deleting
2791: +		}
2792: +
2793: +		return p
2794: +	}
2795: +
2796: +	tests := []struct {
2797: +		name          string
2798: +		stopRequested bool
2799: +		pod           *corev1.Pod
2800: +		want          string
2801: +	}{
2802: +		{"no pod yet", false, nil, "created"},
2803: +		{"pod scheduled, init containers", false, pod(corev1.PodPending, false), "created"},
2804: +		{"device containers run", false, pod(corev1.PodRunning, false), "running"},
2805: +		{"pod being deleted (restart)", false, pod(corev1.PodRunning, true), "exited"},
2806: +		{"pod ended", false, pod(corev1.PodFailed, false), "exited"},
2807: +		{"stop requested, pod terminating", true, pod(corev1.PodRunning, true), "exited"},
2808: +		{"stopped", true, nil, "exited"},
2809: +	}
2810: +	for _, tt := range tests {
2811: +		if got := nodeContainerState(tt.stopRequested, tt.pod); got != tt.want {
2812: +			t.Fatalf("%s: %q, want %q", tt.name, got, tt.want)
2813: +		}
2814: +	}
2815: +}
2816: +
2817: +func TestNewestPodPrefersAPodThatIsNotDeleted(t *testing.T) {
2818: +	t.Parallel()
2819: +
2820: +	now := time.Now()
2821: +	deleting := metav1.NewTime(now)
2822: +	old := &corev1.Pod{
2823: +		ObjectMeta: metav1.ObjectMeta{
2824: +			Name: "old", CreationTimestamp: metav1.NewTime(now.Add(-time.Hour)),
2825: +			DeletionTimestamp: &deleting,
2826: +		},
2827: +		Status: corev1.PodStatus{Phase: corev1.PodRunning},
2828: +	}
2829: +	replacement := &corev1.Pod{
2830: +		ObjectMeta: metav1.ObjectMeta{Name: "new", CreationTimestamp: metav1.NewTime(now)},
2831: +		Status:     corev1.PodStatus{Phase: corev1.PodPending},
2832: +	}
2833: +	if got := newestPod(old, replacement); got != replacement {
2834: +		t.Fatalf("newestPod = %s, want the replacement", got.Name)
2835: +	}
2836: +	if got := newestPod(replacement, old); got != replacement {
2837: +		t.Fatalf("newestPod = %s, want the replacement", got.Name)
2838: +	}
2839: +}
2840: +
2841: +func TestEnrichStateReportsContainerStateAndHealth(t *testing.T) {
2842: +	t.Parallel()
2843: +
2844: +	r := newTestRuntimeWithKubeObjects(

(Output capped at 50 KB. Showing lines 1362-2844. Use offset=2845 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19674daca001qRNDybSWWrT2kP",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674cdcb001GeL6jU7LOAlFw9",
  "callID": "call_bab4329839ed41d59ceaed01",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "offset": 1362
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n1362:      \"mtu\": \"9232\",\n1363:      \"mac\": \"aa:c1:ab:5e:2f:01\",\n1364:      \"lab\": \"clos\",\n1365: -    \"node\": \"srl1\",\n1366:      \"name\": \"clos-srl1\",\n1367: +    \"id\": \"c9s-clos/clos/srl1\",\n1368: +    \"node\": \"srl1\",\n1369:      \"namespace\": \"c9s-clos\",\n1370:      \"pod\": \"srl1-7d9c6b5f4-x2k8p\",\n1371:      \"origin\": \"clabernetes\"\n1372:    }\n1373:  }\n1374:  ```\n1375:  \n1376: -- `action` is `up` when the operational state is `up`, or `unknown` on an\n1377: -  administratively up interface (loopback, tunnels); otherwise `down`.\n1378: -- `attributes.state` is the raw operational state from\n1379: -  `/sys/class/net/<if>/operstate`. An interface that disappears, or whose node\n1380: -  stops running, is reported once as `down` with state `notpresent`.\n1381: -- An event is emitted when an interface appears, when its action or state\n1382: -  changes, and, with `--initial-state`, once for every interface at the start.\n1383: -- Device containers without a shell report statistics only, no interface state.\n1384: +- `action` is `snapshot` for every interface at the start with\n1385: +  `--initial-state`, `create` when an interface appears (for example when a\n1386: +  node starts), `update` when one of its attributes changes, and `delete` when\n1387: +  it disappears or its node stops running.\n1388: +- `state` is the operational state in netlink's names: `up`, `down`,\n1389: +  `lower-layer-down`, `unknown` (loopback), `dormant`, `testing`, `not-present`.\n1390: +- `type` is `veth` for the lab link and management interfaces and `device` for\n1391: +  loopback.\n1392: +- Device containers without a shell report statistics only, no interface state,\n1393: +  and no `index` or `mtu`.\n1394:  \n1395:  With `--interface-stats`, the same exec also produces `interface stats` events\n1396: -with byte and packet counters and rates. They use the node ID as actor, like\n1397: -the state events. `--interface-stats-interval` sets the sampling interval of\n1398: -both (default 1s).\n1399: +for the same interfaces, with their attributes and the byte and packet counters\n1400: +and rates. `--interface-stats-interval` sets the sampling interval of both\n1401: +(default 1s).\n1402: +\n1403: +`inspect interfaces -r c9s` lists the same interfaces with the same values.\n1404:  \n1405:  /// note | Polling, not netlink\n1406:  c9s interface state and statistics are sampled periodically. The first sample\n1407:  seeds the counters, and rates start with the second sample. Short-lived changes\n1408:  between samples can be missed. Every running node gets one exec per interval,\n1409: diff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go\n1410: index 69d4072..3d50217 100644\n1411: --- a/labruntime/clabernetes/capture.go\n1412: +++ b/labruntime/clabernetes/capture.go\n1413: @@ -237,26 +237,15 @@ func (r *Runtime) listCaptureInterfaces(\n1414:  \n1415:  \tvar mu sync.Mutex\n1416:  \tresult := map[string][]clabwireInterface{}\n1417:  \tgroup, groupCtx := errgroup.WithContext(ctx)\n1418:  \tgroup.SetLimit(interfaceSampleWorkers)\n1419: -\texec := r.execInPodContainer()\n1420:  \tfor _, location := range pods {\n1421:  \t\tgroup.Go(func() error {\n1422: -\t\t\tvar stdout, stderr bytes.Buffer\n1423: -\t\t\terr := exec(groupCtx, location.Namespace, location.Pod, clabwireContainer,\n1424: -\t\t\t\t[]string{clabwireManager, \"node-runtime\", \"packet-capture\", \"--list-interfaces\"},\n1425: -\t\t\t\tnil, &stdout, &stderr)\n1426: +\t\t\tentries, err := r.listPodInterfaces(groupCtx, location.Namespace, location.Pod)\n1427:  \t\t\tif err != nil {\n1428: -\t\t\t\treturn fmt.Errorf(\"failed to list the capturable interfaces of pod %s/%s: %w%s\",\n1429: -\t\t\t\t\tlocation.Namespace, location.Pod, err, stderrSuffix(stderr.Bytes()))\n1430: -\t\t\t}\n1431: -\n1432: -\t\t\tvar entries []clabwireInterface\n1433: -\t\t\tif err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {\n1434: -\t\t\t\treturn fmt.Errorf(\"failed to parse the capturable interfaces of pod %s/%s: %w\",\n1435: -\t\t\t\t\tlocation.Namespace, location.Pod, err)\n1436: +\t\t\t\treturn err\n1437:  \t\t\t}\n1438:  \n1439:  \t\t\tmu.Lock()\n1440:  \t\t\tdefer mu.Unlock()\n1441:  \t\t\tfor _, entry := range entries {\n1442: @@ -273,10 +262,34 @@ func (r *Runtime) listCaptureInterfaces(\n1443:  \t}\n1444:  \n1445:  \treturn result, nil\n1446:  }\n1447:  \n1448: +// listPodInterfaces runs clabwire's --list-interfaces in a pod: the lab link interfaces of the\n1449: +// pod's nodes, with their aliases and peers.\n1450: +func (r *Runtime) listPodInterfaces(\n1451: +\tctx context.Context,\n1452: +\tnamespace, pod string,\n1453: +) ([]clabwireInterface, error) {\n1454: +\tvar stdout, stderr bytes.Buffer\n1455: +\terr := r.execInPodContainer()(ctx, namespace, pod, clabwireContainer,\n1456: +\t\t[]string{clabwireManager, \"node-runtime\", \"packet-capture\", \"--list-interfaces\"},\n1457: +\t\tnil, &stdout, &stderr)\n1458: +\tif err != nil {\n1459: +\t\treturn nil, fmt.Errorf(\"failed to list the capturable interfaces of pod %s/%s: %w%s\",\n1460: +\t\t\tnamespace, pod, err, stderrSuffix(stderr.Bytes()))\n1461: +\t}\n1462: +\n1463: +\tvar entries []clabwireInterface\n1464: +\tif err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {\n1465: +\t\treturn nil, fmt.Errorf(\"failed to parse the capturable interfaces of pod %s/%s: %w\",\n1466: +\t\t\tnamespace, pod, err)\n1467: +\t}\n1468: +\n1469: +\treturn entries, nil\n1470: +}\n1471: +\n1472:  func stderrSuffix(stderr []byte) string {\n1473:  \ttext := strings.TrimSpace(string(stderr))\n1474:  \tif text == \"\" {\n1475:  \t\treturn \"\"\n1476:  \t}\n1477: diff --git a/labruntime/clabernetes/capture_interfaces.go b/labruntime/clabernetes/capture_interfaces.go\n1478: index 21029ed..6e3df10 100644\n1479: --- a/labruntime/clabernetes/capture_interfaces.go\n1480: +++ b/labruntime/clabernetes/capture_interfaces.go\n1481: @@ -66,15 +66,16 @@ func (r *Runtime) streamPodExec(\n1482:  \t}\n1483:  \n1484:  \treturn nil\n1485:  }\n1486:  \n1487: -// InspectInterfaces lists the capturable link interfaces of the requested nodes, or of every\n1488: -// running node, in the shape of `inspect interfaces`: per node (named <lab>-<node> like in\n1489: -// inspect), the interface and its alias as clabwire reports them, and the MAC address, index,\n1490: +// InspectInterfaces lists the interfaces of the requested nodes, or of every running node, in\n1491: +// the shape of `inspect interfaces`, with the interfaces the interface events report: the lab\n1492: +// link interfaces and their aliases as clabwire lists them, the management interface and\n1493: +// loopback. Per node (named <lab>-<node> like in inspect) it reports the MAC address, index,\n1494:  // MTU and operational state read from sysfs in the device container. A node whose device\n1495: -// container has no shell reports its interfaces without these attributes.\n1496: +// container has no shell reports its link interfaces without these attributes.\n1497:  func (r *Runtime) InspectInterfaces(\n1498:  \tctx context.Context,\n1499:  \treq clablabruntime.NodeRequest,\n1500:  ) ([]*clabtypes.ContainerInterfaces, error) {\n1501:  \tr, err := r.connect(ctx, req.Identity)\n1502: @@ -109,22 +110,32 @@ func (r *Runtime) InspectInterfaces(\n1503:  \tfor _, location := range running {\n1504:  \t\tcontainer := &clabtypes.ContainerInterfaces{\n1505:  \t\t\tContainerName: req.Name + \"-\" + location.NodeName,\n1506:  \t\t\tInterfaces:    []*clabtypes.ContainerInterfaceDetails{},\n1507:  \t\t}\n1508: -\t\tfor _, entry := range listed[location.NodeName] {\n1509: +\t\tsampled, hasStates := states[location.NodeName]\n1510: +\t\tfor name, alias := range reportedInterfaces(listed[location.NodeName]) {\n1511: +\t\t\tstate, ok := sampled[name]\n1512: +\t\t\tif !ok {\n1513: +\t\t\t\tif hasStates || (name == managementInterface || name == loopbackInterface) {\n1514: +\t\t\t\t\t// not present in the node (yet), or not known without its states\n1515: +\t\t\t\t\tcontinue\n1516: +\t\t\t\t}\n1517: +\t\t\t\tstate = c9sIfaceState{Name: name}\n1518: +\t\t\t}\n1519: +\n1520: +\t\t\tdata := interfaceEventData(state, alias)\n1521:  \t\t\tdetails := &clabtypes.ContainerInterfaceDetails{\n1522: -\t\t\t\tInterfaceName:  entry.Interface,\n1523: -\t\t\t\tInterfaceAlias: entry.Alias,\n1524: -\t\t\t\t// clabwire realizes every lab link interface as a veth pair\n1525: -\t\t\t\tInterfaceType: \"veth\",\n1526: +\t\t\t\tInterfaceName:  data.Name,\n1527: +\t\t\t\tInterfaceAlias: data.Alias,\n1528: +\t\t\t\tInterfaceType:  data.Type,\n1529: +\t\t\t\tInterfaceMAC:   data.MAC,\n1530: +\t\t\t\tInterfaceIndex: data.Index,\n1531: +\t\t\t\tInterfaceMTU:   data.MTU,\n1532:  \t\t\t}\n1533: -\t\t\tif state, ok := states[location.NodeName][entry.Interface]; ok {\n1534: -\t\t\t\tdetails.InterfaceMAC = state.MAC\n1535: -\t\t\t\tdetails.InterfaceIndex = state.Index\n1536: -\t\t\t\tdetails.InterfaceMTU = state.MTU\n1537: -\t\t\t\tdetails.InterfaceState = state.OperState\n1538: +\t\t\tif ok {\n1539: +\t\t\t\tdetails.InterfaceState = data.OperState\n1540:  \t\t\t}\n1541:  \t\t\tcontainer.Interfaces = append(container.Interfaces, details)\n1542:  \t\t}\n1543:  \t\tsort.Slice(container.Interfaces, func(i, j int) bool {\n1544:  \t\t\treturn container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName\n1545: diff --git a/labruntime/clabernetes/capture_test.go b/labruntime/clabernetes/capture_test.go\n1546: index 16628b5..a099566 100644\n1547: --- a/labruntime/clabernetes/capture_test.go\n1548: +++ b/labruntime/clabernetes/capture_test.go\n1549: @@ -14,10 +14,11 @@ import (\n1550:  \t\"testing\"\n1551:  \t\"time\"\n1552:  \n1553:  \tclabcapture \"github.com/srl-labs/containerlab/capture\"\n1554:  \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n1555: +\tclabtypes \"github.com/srl-labs/containerlab/types\"\n1556:  \tcorev1 \"k8s.io/api/core/v1\"\n1557:  \tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n1558:  \t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n1559:  \tk8sruntime \"k8s.io/apimachinery/pkg/runtime\"\n1560:  )\n1561: @@ -713,37 +714,56 @@ func TestCaptureValidatesTargets(t *testing.T) {\n1562:  \tif commands := clabwire.captureCommands(); len(commands) != 0 {\n1563:  \t\tt.Fatalf(\"invalid requests started captures: %v\", commands)\n1564:  \t}\n1565:  }\n1566:  \n1567: +// TestInspectInterfacesReportsStateFromSysfs lists what a Docker container of the node reports:\n1568: +// the lab link interfaces with their topology aliases, eth0 and lo, not clabernetes' own\n1569: +// interfaces, with netlink's state names.\n1570:  func TestInspectInterfacesReportsStateFromSysfs(t *testing.T) {\n1571:  \tt.Parallel()\n1572:  \n1573:  \tr, clabwire := captureTestRuntime(t, time.Millisecond)\n1574:  \tclabwire.sysfs = \"Inter-|   Receive\\n face |bytes\\n\" + interfaceSysfsMarker + \"\\n\" +\n1575: -\t\t\"e1-1\\t12\\t9500\\taa:c1:ab:00:00:01\\tup\\t0x1003\\t\\n\" +\n1576: +\t\t\"lo\\t1\\t65536\\t00:00:00:00:00:00\\tunknown\\t0x9\\t\\n\" +\n1577: +\t\t\"c9s0\\t2\\t1500\\t6e:43:ce:6b:3f:dc\\tup\\t0x1003\\t\\n\" +\n1578: +\t\t\"eth0\\t4\\t1450\\t3a:3b:86:d8:73:37\\tup\\t0x1003\\tc9s:interposition:v1\\n\" +\n1579: +\t\t\"c9ss1\\t6\\t9500\\t3e:9c:45:56:67:2f\\tup\\t0x1003\\tc9s:direct:v1:x\\n\" +\n1580: +\t\t\"e1-1\\t12\\t9500\\taa:c1:ab:00:00:01\\tup\\t0x1003\\tc9s:direct:v1:x\\n\" +\n1581:  \t\t\"e1-2\\t13\\t1500\\taa:c1:ab:00:00:02\\tlowerlayerdown\\t0x1003\\t\\n\"\n1582:  \n1583:  \tinterfaces, err := r.InspectInterfaces(context.Background(), clablabruntime.NodeRequest{\n1584:  \t\tName: \"lab1\", Nodes: []string{\"R1\"},\n1585:  \t})\n1586:  \tif err != nil {\n1587:  \t\tt.Fatal(err)\n1588:  \t}\n1589:  \tif len(interfaces) != 1 || interfaces[0].ContainerName != \"lab1-r1\" ||\n1590: -\t\tlen(interfaces[0].Interfaces) != 2 {\n1591: +\t\tlen(interfaces[0].Interfaces) != 4 {\n1592:  \t\tt.Fatalf(\"interfaces = %+v\", interfaces)\n1593:  \t}\n1594: -\tfirst := interfaces[0].Interfaces[0]\n1595: -\tif first.InterfaceName != \"e1-1\" || first.InterfaceAlias != \"ethernet-1/1\" ||\n1596: +\tbyName := map[string]*clabtypes.ContainerInterfaceDetails{}\n1597: +\tfor _, iface := range interfaces[0].Interfaces {\n1598: +\t\tbyName[iface.InterfaceName] = iface\n1599: +\t}\n1600: +\tfirst := byName[\"e1-1\"]\n1601: +\tif first == nil || first.InterfaceAlias != \"ethernet-1/1\" ||\n1602:  \t\tfirst.InterfaceMAC != \"aa:c1:ab:00:00:01\" || first.InterfaceIndex != 12 ||\n1603: -\t\tfirst.InterfaceMTU != 9500 || first.InterfaceState != \"up\" {\n1604: +\t\tfirst.InterfaceMTU != 9500 || first.InterfaceState != \"up\" || first.InterfaceType != \"veth\" {\n1605:  \t\tt.Fatalf(\"e1-1 = %+v\", first)\n1606:  \t}\n1607: -\tif second := interfaces[0].Interfaces[1]; second.InterfaceState != \"lowerlayerdown\" {\n1608: +\tif second := byName[\"e1-2\"]; second == nil || second.InterfaceState != \"lower-layer-down\" {\n1609:  \t\tt.Fatalf(\"e1-2 = %+v\", second)\n1610:  \t}\n1611: +\tif eth0 := byName[\"eth0\"]; eth0 == nil || eth0.InterfaceAlias != \"\" ||\n1612: +\t\teth0.InterfaceType != \"veth\" {\n1613: +\t\tt.Fatalf(\"eth0 = %+v\", eth0)\n1614: +\t}\n1615: +\tif lo := byName[\"lo\"]; lo == nil || lo.InterfaceType != \"device\" || lo.InterfaceMAC != \"\" ||\n1616: +\t\tlo.InterfaceState != \"unknown\" {\n1617: +\t\tt.Fatalf(\"lo = %+v\", lo)\n1618: +\t}\n1619:  }\n1620:  \n1621:  // TestCaptureClosesStdinWhenItEnds ends every clabwire process through its stdin, whether the\n1622:  // caller cancels the capture or the output fails, so no capture is left running in the pod.\n1623:  // TestCaptureWritesWhatItReadWhenTheContextEnds stops a capture while the output is slow and\n1624: diff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go\n1625: index e869191..dc202d3 100644\n1626: --- a/labruntime/clabernetes/clabernetes.go\n1627: +++ b/labruntime/clabernetes/clabernetes.go\n1628: @@ -35,10 +35,12 @@ const (\n1629:  \tclabernetesAppValue   = \"clabernetes\"\n1630:  \t// persistenceReclaimRetain keeps a node's persistent claim when its Node is deleted.\n1631:  \tpersistenceReclaimRetain = \"Retain\"\n1632:  \t// defaultContainerAnnotation names the primary device container of a c9s pod.\n1633:  \tdefaultContainerAnnotation = \"kubectl.kubernetes.io/default-container\"\n1634: +\t// annotationDirectNodeUID names the UID of the Node a c9s pod runs.\n1635: +\tannotationDirectNodeUID = \"c9s.run/direct-node-uid\"\n1636:  )\n1637:  \n1638:  var topologyGVR = schema.GroupVersionResource{\n1639:  \tGroup:    \"c9s.run\",\n1640:  \tVersion:  \"v1alpha1\",\n1641: diff --git a/labruntime/clabernetes/clabernetes_test.go b/labruntime/clabernetes/clabernetes_test.go\n1642: index b6e34cd..92e07a1 100644\n1643: --- a/labruntime/clabernetes/clabernetes_test.go\n1644: +++ b/labruntime/clabernetes/clabernetes_test.go\n1645: @@ -3734,11 +3734,11 @@ func TestForwardPodWatchReconnectsOnClosedChannel(t *testing.T) {\n1646:  \n1647:  \tr := &Runtime{}\n1648:  \tif !r.forwardPodWatch(\n1649:  \t\tcontext.Background(),\n1650:  \t\twatcher,\n1651: -\t\tmake(chan clablabruntime.Event, 1),\n1652: +\t\tmake(chan labRef, 1),\n1653:  \t\tmake(chan error, 1),\n1654:  \t) {\n1655:  \t\tt.Fatal(\"expected closed pod watch to request reconnect\")\n1656:  \t}\n1657:  }\n1658: @@ -3752,55 +3752,49 @@ func TestForwardTopologyWatchReconnectsOnClosedChannel(t *testing.T) {\n1659:  \tr := &Runtime{}\n1660:  \tif !r.forwardTopologyWatch(\n1661:  \t\tcontext.Background(),\n1662:  \t\t\"default\",\n1663:  \t\twatcher,\n1664: +\t\tmake(chan labRef, 1),\n1665:  \t\tmake(chan clablabruntime.Event, 1),\n1666:  \t\tmake(chan error, 1),\n1667:  \t) {\n1668:  \t\tt.Fatal(\"expected closed topology watch to request reconnect\")\n1669:  \t}\n1670:  }\n1671:  \n1672: -func TestForwardPodWatchEmitsPodEvent(t *testing.T) {\n1673: +func TestForwardPodWatchReportsTheLabOfAPod(t *testing.T) {\n1674:  \tt.Parallel()\n1675:  \n1676:  \twatcher := watch.NewFake()\n1677: -\tevents := make(chan clablabruntime.Event, 1)\n1678: +\tchanged := make(chan labRef, 1)\n1679:  \terrs := make(chan error, 1)\n1680:  \tctx, cancel := context.WithCancel(context.Background())\n1681:  \tdefer cancel()\n1682:  \n1683:  \tr := &Runtime{}\n1684:  \tdone := make(chan bool, 1)\n1685:  \tgo func() {\n1686: -\t\tdone <- r.forwardPodWatch(ctx, watcher, events, errs)\n1687: +\t\tdone <- r.forwardPodWatch(ctx, watcher, changed, errs)\n1688:  \t}()\n1689:  \n1690: +\t// a pod without the lab label is not a lab's pod\n1691:  \twatcher.Add(&corev1.Pod{})\n1692: -\twatcher.Add(&corev1.Pod{\n1693: +\twatcher.Modify(&corev1.Pod{\n1694:  \t\tObjectMeta: metav1.ObjectMeta{\n1695:  \t\t\tName:      \"pod1\",\n1696:  \t\t\tNamespace: \"lab-ns\",\n1697:  \t\t\tLabels: map[string]string{\n1698:  \t\t\t\tlabelTopologyOwner: \"lab1\",\n1699:  \t\t\t\tlabelTopologyNode:  \"node1\",\n1700:  \t\t\t},\n1701:  \t\t},\n1702: -\t\tStatus: corev1.PodStatus{\n1703: -\t\t\tPhase: corev1.PodRunning,\n1704: -\t\t\tPodIP: \"10.0.0.1\",\n1705: -\t\t},\n1706: +\t\tStatus: corev1.PodStatus{Phase: corev1.PodRunning},\n1707:  \t})\n1708:  \n1709: -\tgot := <-events\n1710: -\tif got.ActorID != \"lab-ns/lab1/node1\" ||\n1711: -\t\tgot.ActorName != \"lab1-node1\" ||\n1712: -\t\tgot.ActorFullID != \"pod1\" ||\n1713: -\t\tgot.Attributes[\"phase\"] != string(corev1.PodRunning) ||\n1714: -\t\tgot.Attributes[\"pod_ip\"] != \"10.0.0.1\" {\n1715: -\t\tt.Fatalf(\"unexpected pod event: %+v\", got)\n1716: +\tif got := <-changed; got != (labRef{namespace: \"lab-ns\", lab: \"lab1\"}) {\n1717: +\t\tt.Fatalf(\"changed lab = %+v\", got)\n1718:  \t}\n1719:  \n1720:  \tcancel()\n1721:  \twatcher.Stop()\n1722:  \n1723: diff --git a/labruntime/clabernetes/container_events.go b/labruntime/clabernetes/container_events.go\n1724: new file mode 100644\n1725: index 0000000..ef7cf21\n1726: --- /dev/null\n1727: +++ b/labruntime/clabernetes/container_events.go\n1728: @@ -0,0 +1,363 @@\n1729: +package clabernetes\n1730: +\n1731: +import (\n1732: +\t\"context\"\n1733: +\t\"errors\"\n1734: +\t\"fmt\"\n1735: +\t\"strings\"\n1736: +\t\"time\"\n1737: +\n1738: +\t\"github.com/charmbracelet/log\"\n1739: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n1740: +)\n1741: +\n1742: +// Container event actions, as the Docker runtime reports them.\n1743: +const (\n1744: +\tcontainerActionCreate        = \"create\"\n1745: +\tcontainerActionStart         = \"start\"\n1746: +\tcontainerActionKill          = \"kill\"\n1747: +\tcontainerActionStop          = \"stop\"\n1748: +\tcontainerActionDie           = \"die\"\n1749: +\tcontainerActionDestroy       = \"destroy\"\n1750: +\tcontainerActionHealthPrefix  = \"health_status: \"\n1751: +\tcontainerEventSignalSIGTERM  = \"15\"\n1752: +\tcontainerRefreshDelay        = 200 * time.Millisecond\n1753: +\tcontainerRefreshRetryDelay   = pollInterval\n1754: +\tcontainerEventAttributeState = \"state\"\n1755: +)\n1756: +\n1757: +// trackedContainer is the last reported container state of a node.\n1758: +type trackedContainer struct {\n1759: +\tref    labRef\n1760: +\tstate  string\n1761: +\thealth string\n1762: +\tpod    string\n1763: +\t// lab and node are the last observation, which a removed node is described with.\n1764: +\tlab  *clablabruntime.LabState\n1765: +\tnode clablabruntime.NodeState\n1766: +}\n1767: +\n1768: +// containerTracker turns the node states of the labs in an event scope into the container\n1769: +// events the Docker runtime emits for the same lifecycle: create and start when a node's pod\n1770: +// starts, kill, stop and die when it stops (on request, or between the pods of a restart),\n1771: +// destroy when the node is removed, and health_status as its device becomes ready.\n1772: +type containerTracker struct {\n1773: +\tr     *Runtime\n1774: +\tsink  chan<- clablabruntime.Event\n1775: +\tnodes map[string]*trackedContainer\n1776: +}\n1777: +\n1778: +// trackContainers reports the container events of a scope. It reads the labs once, reporting\n1779: +// them as a snapshot when the stream includes the initial state, and then reads a lab again\n1780: +// whenever its Topology, Nodes or pods change. Changes that arrive together are read once.\n1781: +func (r *Runtime) trackContainers(\n1782: +\tctx context.Context,\n1783: +\tscope eventScope,\n1784: +\tincludeInitialState bool,\n1785: +\tchanged <-chan labRef,\n1786: +\teventSink chan<- clablabruntime.Event,\n1787: +\terrSink chan<- error,\n1788: +) {\n1789: +\ttracker := &containerTracker{r: r, sink: eventSink, nodes: map[string]*trackedContainer{}}\n1790: +\n1791: +\tstates, err := r.labStates(ctx, scope)\n1792: +\tif err != nil {\n1793: +\t\tsendEventError(ctx, errSink, err)\n1794: +\t\treturn\n1795: +\t}\n1796: +\tfor _, state := range states {\n1797: +\t\ttracker.observeLab(ctx, labRef{namespace: state.Namespace, lab: state.Name}, state,\n1798: +\t\t\t&observeSeed{snapshot: includeInitialState})\n1799: +\t}\n1800: +\n1801: +\tpending := map[labRef]bool{}\n1802: +\ttimer := time.NewTimer(time.Hour)\n1803: +\ttimer.Stop()\n1804: +\tdefer timer.Stop()\n1805: +\tarmed := false\n1806: +\tarm := func(delay time.Duration) {\n1807: +\t\tif !armed {\n1808: +\t\t\ttimer.Reset(delay)\n1809: +\t\t\tarmed = true\n1810: +\t\t}\n1811: +\t}\n1812: +\n1813: +\tfor {\n1814: +\t\tselect {\n1815: +\t\tcase <-ctx.Done():\n1816: +\t\t\treturn\n1817: +\t\tcase ref := <-changed:\n1818: +\t\t\tpending[ref] = true\n1819: +\t\t\tarm(containerRefreshDelay)\n1820: +\t\tcase <-timer.C:\n1821: +\t\t\tarmed = false\n1822: +\t\t\trefs := pending\n1823: +\t\t\tpending = map[labRef]bool{}\n1824: +\t\t\tfor ref := range refs {\n1825: +\t\t\t\tif !tracker.refresh(ctx, ref) {\n1826: +\t\t\t\t\tpending[ref] = true\n1827: +\t\t\t\t}\n1828: +\t\t\t}\n1829: +\t\t\tif len(pending) != 0 {\n1830: +\t\t\t\tarm(containerRefreshRetryDelay)\n1831: +\t\t\t}\n1832: +\t\t}\n1833: +\t}\n1834: +}\n1835: +\n1836: +// observeSeed marks the first observation of a stream: it records the node states without\n1837: +// reporting changes, and reports them as a snapshot when asked to.\n1838: +type observeSeed struct {\n1839: +\tsnapshot bool\n1840: +}\n1841: +\n1842: +// refresh reads a lab again and reports what changed for its nodes. A lab that is gone reports\n1843: +// its nodes as destroyed. It returns false when the lab could not be read.\n1844: +func (t *containerTracker) refresh(ctx context.Context, ref labRef) bool {\n1845: +\tstate, err := t.r.Inspect(ctx, clablabruntime.InspectRequest{\n1846: +\t\tName:      ref.lab,\n1847: +\t\tNamespace: ref.namespace,\n1848: +\t})\n1849: +\tif err != nil {\n1850: +\t\tvar notFound *labNotFoundError\n1851: +\t\tif !errors.As(err, &notFound) {\n1852: +\t\t\tif ctx.Err() == nil {\n1853: +\t\t\t\tlog.Debug(\"Failed to read a C9s lab for container events\",\n1854: +\t\t\t\t\t\"namespace\", ref.namespace, \"lab\", ref.lab, \"error\", err)\n1855: +\t\t\t}\n1856: +\n1857: +\t\t\treturn ctx.Err() != nil\n1858: +\t\t}\n1859: +\t\tstate = nil\n1860: +\t}\n1861: +\n1862: +\tt.observeLab(ctx, ref, state, nil)\n1863: +\n1864: +\treturn true\n1865: +}\n1866: +\n1867: +// observeLab compares the nodes of a lab with what was reported before and reports the\n1868: +// difference. A nil state removes every node of the lab.\n1869: +func (t *containerTracker) observeLab(\n1870: +\tctx context.Context,\n1871: +\tref labRef,\n1872: +\tstate *clablabruntime.LabState,\n1873: +\tseed *observeSeed,\n1874: +) {\n1875: +\tseen := map[string]bool{}\n1876: +\tif state != nil {\n1877: +\t\tfor idx := range state.Nodes {\n1878: +\t\t\tkey := c9sNodeKey(state.Namespace, state.Name, state.Nodes[idx].Name)\n1879: +\t\t\tseen[key] = true\n1880: +\t\t\tt.observeNode(ctx, ref, state, state.Nodes[idx], seed)\n1881: +\t\t}\n1882: +\t}\n1883: +\n1884: +\tfor key, tracked := range t.nodes {\n1885: +\t\tif tracked.ref != ref || seen[key] {\n1886: +\t\t\tcontinue\n1887: +\t\t}\n1888: +\n1889: +\t\tfor _, action := range containerRemovalActions(tracked) {\n1890: +\t\t\tt.emit(ctx, tracked.lab, tracked.node, action, nil)\n1891: +\t\t}\n1892: +\t\tdelete(t.nodes, key)\n1893: +\t}\n1894: +}\n1895: +\n1896: +func (t *containerTracker) observeNode(\n1897: +\tctx context.Context,\n1898: +\tref labRef,\n1899: +\tstate *clablabruntime.LabState,\n1900: +\tnode clablabruntime.NodeState,\n1901: +\tseed *observeSeed,\n1902: +) {\n1903: +\tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n1904: +\tprevious := t.nodes[key]\n1905: +\tif node.ContainerState == \"\" {\n1906: +\t\tnode.ContainerState = clablabruntime.ContainerStateCreated\n1907: +\t}\n1908: +\tnext := &trackedContainer{\n1909: +\t\tref:   ref,\n1910: +\t\tstate: node.ContainerState,\n1911: +\t\tpod:   node.Pod,\n1912: +\t\tlab:   state,\n1913: +\t\tnode:  node,\n1914: +\t}\n1915: +\tnext.health = containerHealth(previous, next, node.Health)\n1916: +\tt.nodes[key] = next\n1917: +\n1918: +\tif seed != nil {\n1919: +\t\tif seed.snapshot {\n1920: +\t\t\tt.emit(ctx, state, node, next.state, map[string]string{\n1921: +\t\t\t\t\"origin\": clablabruntime.EventOriginSnapshot,\n1922: +\t\t\t})\n1923: +\t\t}\n1924: +\n1925: +\t\treturn\n1926: +\t}\n1927: +\n1928: +\tfor _, action := range containerTransitionActions(previous, next) {\n1929: +\t\tt.emit(ctx, state, node, action, nil)\n1930: +\t}\n1931: +}\n1932: +\n1933: +// containerHealth is the health a running node reports: a node that was healthy and is not\n1934: +// ready anymore in the same pod is unhealthy, as a container whose healthcheck starts failing.\n1935: +func containerHealth(previous, next *trackedContainer, health string) string {\n1936: +\tif next.state != clablabruntime.ContainerStateRunning {\n1937: +\t\treturn \"\"\n1938: +\t}\n1939: +\tif health == \"\" {\n1940: +\t\thealth = clablabruntime.ContainerHealthStarting\n1941: +\t}\n1942: +\tif health == clablabruntime.ContainerHealthStarting && previous != nil &&\n1943: +\t\tprevious.state == clablabruntime.ContainerStateRunning && previous.pod == next.pod &&\n1944: +\t\t(previous.health == clablabruntime.ContainerHealthHealthy ||\n1945: +\t\t\tprevious.health == clablabruntime.ContainerHealthUnhealthy) {\n1946: +\t\treturn clablabruntime.ContainerHealthUnhealthy\n1947: +\t}\n1948: +\n1949: +\treturn health\n1950: +}\n1951: +\n1952: +// containerTransitionActions are the container event actions Docker reports when a container\n1953: +// goes from the previous to the next state:\n1954: +//\n1955: +//\tnew node            create (+ start when it runs, + stop when it is already stopped)\n1956: +//\tcreated -> running  start\n1957: +//\texited  -> running  start\n1958: +//\trunning -> exited   kill, stop, die (stop, or the old pod of a restart ending)\n1959: +//\trunning -> created  kill, stop, die (the replacement pod of a restart not running yet)\n1960: +//\trunning, new pod    kill, stop, die, start (restart)\n1961: +//\tcreated -> exited   stop\n1962: +//\n1963: +// A started node also reports its health (health_status: starting or healthy), and a running\n1964: +// node reports health changes, like a container with a healthcheck.\n1965: +func containerTransitionActions(previous, next *trackedContainer) []string {\n1966: +\tconst (\n1967: +\t\tcreated = clablabruntime.ContainerStateCreated\n1968: +\t\trunning = clablabruntime.ContainerStateRunning\n1969: +\t\texited  = clablabruntime.ContainerStateExited\n1970: +\t)\n1971: +\n1972: +\tvar actions []string\n1973: +\tpreviousState := \"\"\n1974: +\tif previous != nil {\n1975: +\t\tpreviousState = previous.state\n1976: +\t}\n1977: +\n1978: +\tswitch {\n1979: +\tcase previous == nil:\n1980: +\t\tactions = append(actions, containerActionCreate)\n1981: +\t\tswitch next.state {\n1982: +\t\tcase running:\n1983: +\t\t\tactions = append(actions, containerActionStart)\n1984: +\t\tcase exited:\n1985: +\t\t\tactions = append(actions, containerActionStop)\n1986: +\t\t}\n1987: +\tcase previousState == running && next.state == running && previous.pod != next.pod:\n1988: +\t\tactions = append(actions, containerActionKill, containerActionStop, containerActionDie,\n1989: +\t\t\tcontainerActionStart)\n1990: +\tcase previousState == running && next.state != running:\n1991: +\t\tactions = append(actions, containerActionKill, containerActionStop, containerActionDie)\n1992: +\tcase previousState != running && next.state == running:\n1993: +\t\tactions = append(actions, containerActionStart)\n1994: +\tcase previousState == created && next.state == exited:\n1995: +\t\tactions = append(actions, containerActionStop)\n1996: +\t}\n1997: +\n1998: +\tif next.state != running {\n1999: +\t\treturn actions\n2000: +\t}\n2001: +\n2002: +\tstarted := len(actions) != 0 && actions[len(actions)-1] == containerActionStart\n2003: +\tif !started && previous != nil && previous.health == next.health {\n2004: +\t\treturn actions\n2005: +\t}\n2006: +\tif next.health == clablabruntime.ContainerHealthStarting && !started {\n2007: +\t\treturn actions\n2008: +\t}\n2009: +\n2010: +\treturn append(actions, containerActionHealthPrefix+next.health)\n2011: +}\n2012: +\n2013: +// containerRemovalActions are the actions Docker reports when a container is removed: a running\n2014: +// one is killed and dies first.\n2015: +func containerRemovalActions(previous *trackedContainer) []string {\n2016: +\tif previous.state == clablabruntime.ContainerStateRunning {\n2017: +\t\treturn []string{containerActionKill, containerActionDie, containerActionDestroy}\n2018: +\t}\n2019: +\n2020: +\treturn []string{containerActionDestroy}\n2021: +}\n2022: +\n2023: +// containerActionState is the container state after an action, which every container event\n2024: +// reports in its state attribute.\n2025: +func containerActionState(action, snapshotState string) string {\n2026: +\tswitch action {\n2027: +\tcase containerActionCreate:\n2028: +\t\treturn clablabruntime.ContainerStateCreated\n2029: +\tcase containerActionStop, containerActionDie, containerActionDestroy:\n2030: +\t\treturn clablabruntime.ContainerStateExited\n2031: +\tcase containerActionStart, containerActionKill:\n2032: +\t\treturn clablabruntime.ContainerStateRunning\n2033: +\t}\n2034: +\tif strings.HasPrefix(action, containerActionHealthPrefix) {\n2035: +\t\treturn clablabruntime.ContainerStateRunning\n2036: +\t}\n2037: +\n2038: +\treturn snapshotState\n2039: +}\n2040: +\n2041: +func (t *containerTracker) emit(\n2042: +\tctx context.Context,\n2043: +\tstate *clablabruntime.LabState,\n2044: +\tnode clablabruntime.NodeState,\n2045: +\taction string,\n2046: +\textra map[string]string,\n2047: +) {\n2048: +\tt.r.sendEvent(ctx, t.sink, c9sContainerEvent(state, node, action, extra))\n2049: +}\n2050: +\n2051: +// c9sContainerEvent is a container event of a node. The actor is the node, as for its interface\n2052: +// events; its ID is the container_id inspect reports. Lab and Node let the events command\n2053: +// describe the node with the attributes inspect and the Docker runtime report.\n2054: +func c9sContainerEvent(\n2055: +\tstate *clablabruntime.LabState,\n2056: +\tnode clablabruntime.NodeState,\n2057: +\taction string,\n2058: +\textra map[string]string,\n2059: +) clablabruntime.Event {\n2060: +\tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n2061: +\tattributes := map[string]string{\n2062: +\t\t\"namespace\":                  state.Namespace,\n2063: +\t\t\"lab\":                        state.Name,\n2064: +\t\t\"node\":                       node.Name,\n2065: +\t\tcontainerEventAttributeState: containerActionState(action, node.ContainerState),\n2066: +\t}\n2067: +\tif node.Pod != \"\" {\n2068: +\t\tattributes[\"pod\"] = node.Pod\n2069: +\t}\n2070: +\tif action == containerActionKill {\n2071: +\t\t// Kubernetes stops a pod's containers with SIGTERM.\n2072: +\t\tattributes[\"signal\"] = containerEventSignalSIGTERM\n2073: +\t}\n2074: +\tfor k, v := range extra {\n2075: +\t\tattributes[k] = v\n2076: +\t}\n2077: +\n2078: +\tnodeCopy := node\n2079: +\n2080: +\treturn clablabruntime.Event{\n2081: +\t\tTimestamp:   time.Now(),\n2082: +\t\tType:        clablabruntime.EventTypeContainer,\n2083: +\t\tAction:      action,\n2084: +\t\tActorID:     key,\n2085: +\t\tActorName:   fmt.Sprintf(\"%s-%s\", state.Name, node.Name),\n2086: +\t\tActorFullID: key,\n2087: +\t\tAttributes:  attributes,\n2088: +\t\tLab:         state,\n2089: +\t\tNode:        &nodeCopy,\n2090: +\t}\n2091: +}\n2092: diff --git a/labruntime/clabernetes/event_parity_test.go b/labruntime/clabernetes/event_parity_test.go\n2093: new file mode 100644\n2094: index 0000000..faddcfe\n2095: --- /dev/null\n2096: +++ b/labruntime/clabernetes/event_parity_test.go\n2097: @@ -0,0 +1,1008 @@\n2098: +package clabernetes\n2099: +\n2100: +import (\n2101: +\t\"context\"\n2102: +\t\"encoding/json\"\n2103: +\t\"io\"\n2104: +\t\"slices\"\n2105: +\t\"strings\"\n2106: +\t\"sync\"\n2107: +\t\"testing\"\n2108: +\t\"time\"\n2109: +\n2110: +\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n2111: +\tcorev1 \"k8s.io/api/core/v1\"\n2112: +\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n2113: +\t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n2114: +\tk8sruntime \"k8s.io/apimachinery/pkg/runtime\"\n2115: +)\n2116: +\n2117: +// podInterfaces is the sysfs view of a c9s pod: the device's interfaces and clabernetes' own.\n2118: +func podInterfaces(link string, linkState string) []c9sIfaceState {\n2119: +\treturn []c9sIfaceState{\n2120: +\t\t{Name: \"lo\", Index: 1, MTU: 65536, MAC: zeroMAC, OperState: \"unknown\"},\n2121: +\t\t{Name: \"c9s0\", Index: 2, MTU: 1500, MAC: \"6e:43:ce:6b:3f:dc\", OperState: \"up\"},\n2122: +\t\t{\n2123: +\t\t\tName: \"c9sr0\", Index: 3, MTU: 1450, MAC: \"02:c9:20:eb:f4:ff\", OperState: \"up\",\n2124: +\t\t\tAlias: \"c9s:interposition:v1\",\n2125: +\t\t},\n2126: +\t\t{\n2127: +\t\t\tName: \"eth0\", Index: 4, MTU: 1450, MAC: \"3a:3b:86:d8:73:37\", OperState: \"up\",\n2128: +\t\t\tAlias: \"c9s:interposition:v1\",\n2129: +\t\t},\n2130: +\t\t{\n2131: +\t\t\tName: \"c9sm0\", Index: 5, MTU: 1450, MAC: \"06:c9:ac:14:14:54\", OperState: \"unknown\",\n2132: +\t\t\tAlias: \"c9s:interposition:v1\",\n2133: +\t\t},\n2134: +\t\t{\n2135: +\t\t\tName: \"c9ss73388031\", Index: 6, MTU: 9500, MAC: \"3e:9c:45:56:67:2f\", OperState: \"up\",\n2136: +\t\t\tAlias: \"c9s:direct:v1:e332:transport:98d2\",\n2137: +\t\t},\n2138: +\t\t{\n2139: +\t\t\tName: link, Index: 7, MTU: 9500, MAC: \"fe:0b:87:7a:1d:5a\", OperState: linkState,\n2140: +\t\t\tAlias: \"c9s:direct:v1:e332:transport:98d2\",\n2141: +\t\t},\n2142: +\t}\n2143: +}\n2144: +\n2145: +func interfaceTestSample(\n2146: +\tnode string,\n2147: +\tts time.Time,\n2148: +\tlinks []clabwireInterface,\n2149: +\tifaces []c9sIfaceState,\n2150: +) interfaceSample {\n2151: +\tstats := make([]c9sIfaceStats, 0, len(ifaces))\n2152: +\tfor _, iface := range ifaces {\n2153: +\t\tstats = append(stats, c9sIfaceStats{Name: iface.Name, RxBytes: uint64(ts.Unix())})\n2154: +\t}\n2155: +\n2156: +\treturn interfaceSample{\n2157: +\t\ttarget: interfaceSampleTarget{\n2158: +\t\t\tstate: &clablabruntime.LabState{Name: \"lab1\", Namespace: \"c9s-lab1\"},\n2159: +\t\t\tnode: clablabruntime.NodeState{\n2160: +\t\t\t\tName: node, Pod: \"lab1-\" + node + \"-abc\",\n2161: +\t\t\t\tContainerState: clablabruntime.ContainerStateRunning,\n2162: +\t\t\t},\n2163: +\t\t\tpod: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"lab1-\" + node + \"-abc\"}},\n2164: +\t\t},\n2165: +\t\tstats:     stats,\n2166: +\t\tifaces:    ifaces,\n2167: +\t\thasStates: true,\n2168: +\t\tlinks:     links,\n2169: +\t\ttimestamp: ts,\n2170: +\t}\n2171: +}\n2172: +\n2173: +func interfacesByName(events []clablabruntime.Event) map[string]clablabruntime.Event {\n2174: +\tbyName := map[string]clablabruntime.Event{}\n2175: +\tfor _, ev := range events {\n2176: +\t\tbyName[ev.Interface.Name] = ev\n2177: +\t}\n2178: +\n2179: +\treturn byName\n2180: +}\n2181: +\n2182: +func TestNetlinkOperState(t *testing.T) {\n2183: +\tt.Parallel()\n2184: +\n2185: +\tfor sysfs, want := range map[string]string{\n2186: +\t\t\"up\":             \"up\",\n2187: +\t\t\"down\":           \"down\",\n2188: +\t\t\"unknown\":        \"unknown\",\n2189: +\t\t\"dormant\":        \"dormant\",\n2190: +\t\t\"testing\":        \"testing\",\n2191: +\t\t\"notpresent\":     \"not-present\",\n2192: +\t\t\"lowerlayerdown\": \"lower-layer-down\",\n2193: +\t\t\"\":               \"unknown\",\n2194: +\t} {\n2195: +\t\tif got := netlinkOperState(sysfs); got != want {\n2196: +\t\t\tt.Fatalf(\"netlinkOperState(%q) = %q, want %q\", sysfs, got, want)\n2197: +\t\t}\n2198: +\t}\n2199: +}\n2200: +\n2201: +// TestInterfaceEventDataNamesInterfacesLikeDocker checks the names, aliases, types and states a\n2202: +// Docker container of the same node kind reports: linux eth1 without an alias, SR Linux e1-1\n2203: +// with the topology's ethernet-1/1, eth0 and loopback, and no clabernetes alias.\n2204: +func TestInterfaceEventDataNamesInterfacesLikeDocker(t *testing.T) {\n2205: +\tt.Parallel()\n2206: +\n2207: +\tifaces := map[string]c9sIfaceState{}\n2208: +\tfor _, iface := range podInterfaces(\"e1-1\", \"lowerlayerdown\") {\n2209: +\t\tifaces[iface.Name] = iface\n2210: +\t}\n2211: +\tifaces[\"eth1\"] = c9sIfaceState{\n2212: +\t\tName: \"eth1\", Index: 8, MTU: 9500, OperState: \"up\", Alias: \"c9s:direct:v1:x\",\n2213: +\t}\n2214: +\n2215: +\ttests := []struct {\n2216: +\t\tiface, alias string\n2217: +\t\twant         clablabruntime.InterfaceEventData\n2218: +\t}{\n2219: +\t\t{\"eth1\", \"\", clablabruntime.InterfaceEventData{\n2220: +\t\t\tName: \"eth1\", Index: 8, MTU: 9500, OperState: \"up\", Type: \"veth\",\n2221: +\t\t}},\n2222: +\t\t{\"e1-1\", \"ethernet-1/1\", clablabruntime.InterfaceEventData{\n2223: +\t\t\tName: \"e1-1\", Alias: \"ethernet-1/1\", Index: 7, MTU: 9500, MAC: \"fe:0b:87:7a:1d:5a\",\n2224: +\t\t\tOperState: \"lower-layer-down\", Type: \"veth\",\n2225: +\t\t}},\n2226: +\t\t{\"eth0\", \"\", clablabruntime.InterfaceEventData{\n2227: +\t\t\tName: \"eth0\", Index: 4, MTU: 1450, MAC: \"3a:3b:86:d8:73:37\", OperState: \"up\",\n2228: +\t\t\tType: \"veth\",\n2229: +\t\t}},\n2230: +\t\t{\"lo\", \"\", clablabruntime.InterfaceEventData{\n2231: +\t\t\tName: \"lo\", Index: 1, MTU: 65536, OperState: \"unknown\", Type: \"device\",\n2232: +\t\t}},\n2233: +\t}\n2234: +\tfor _, tt := range tests {\n2235: +\t\tif got := interfaceEventData(ifaces[tt.iface], tt.alias); got != tt.want {\n2236: +\t\t\tt.Fatalf(\"%s = %+v, want %+v\", tt.iface, got, tt.want)\n2237: +\t\t}\n2238: +\t}\n2239: +\n2240: +\t// an alias set inside the node is the interface's alias, as netlink reports it\n2241: +\tgot := interfaceEventData(c9sIfaceState{Name: \"eth2\", Alias: \"uplink\"}, \"\")\n2242: +\tif got.Alias != \"uplink\" {\n2243: +\t\tt.Fatalf(\"own alias = %+v\", got)\n2244: +\t}\n2245: +}\n2246: +\n2247: +// TestInterfacePollerReportsTheTopologyInterfaces runs a linux and an SR Linux node through the\n2248: +// poller: only the lab link interfaces (named and aliased as clabwire lists them), eth0 and lo\n2249: +// are reported, with the actions of the netlink events.\n2250: +func TestInterfacePollerReportsTheTopologyInterfaces(t *testing.T) {\n2251: +\tt.Parallel()\n2252: +\n2253: +\ttests := []struct {\n2254: +\t\tname  string\n2255: +\t\tlink  string\n2256: +\t\talias string\n2257: +\t}{\n2258: +\t\t{name: \"linux\", link: \"eth1\"},\n2259: +\t\t{name: \"srl\", link: \"e1-1\", alias: \"ethernet-1/1\"},\n2260: +\t}\n2261: +\tfor _, tt := range tests {\n2262: +\t\tt.Run(tt.name, func(t *testing.T) {\n2263: +\t\t\tt.Parallel()\n2264: +\n2265: +\t\t\tlinks := []clabwireInterface{{\n2266: +\t\t\t\tNode: \"r1\", Interface: tt.link, Alias: tt.alias,\n2267: +\t\t\t\tPeerNode: \"r2\", PeerInterface: tt.link,\n2268: +\t\t\t}}\n2269: +\t\t\tsink := make(chan clablabruntime.Event, 64)\n2270: +\t\t\tp := newInterfacePoller(&Runtime{}, eventScope{},\n2271: +\t\t\t\tinterfacePollOptions{includeInitialState: true}, sink)\n2272: +\t\t\tctx := context.Background()\n2273: +\t\t\tstart := time.Now()\n2274: +\n2275: +\t\t\tp.processSample(\n2276: +\t\t\t\tctx,\n2277: +\t\t\t\tinterfaceTestSample(\"r1\", start, links, podInterfaces(tt.link, \"up\")),\n2278: +\t\t\t)\n2279: +\t\t\tgot := interfacesByName(drain(sink))\n2280: +\t\t\tif len(got) != 3 {\n2281: +\t\t\t\tt.Fatalf(\"first round reported %v, want %s, eth0 and lo\", got, tt.link)\n2282: +\t\t\t}\n2283: +\t\t\tlink := got[tt.link]\n2284: +\t\t\tif link.Action != interfaceActionSnapshot ||\n2285: +\t\t\t\tlink.Type != clablabruntime.EventTypeInterface ||\n2286: +\t\t\t\tlink.ActorID != \"c9s-lab1/lab1/r1\" ||\n2287: +\t\t\t\tlink.ActorFullID != \"c9s-lab1/lab1/r1\" ||\n2288: +\t\t\t\tlink.ActorName != \"lab1-r1\" || link.Interface.Alias != tt.alias ||\n2289: +\t\t\t\tlink.Interface.OperState != \"up\" || link.Interface.Type != \"veth\" ||\n2290: +\t\t\t\tlink.Lab == nil || link.Node == nil || link.Node.Name != \"r1\" ||\n2291: +\t\t\t\tlink.Attributes[\"origin\"] != \"clabernetes\" ||\n2292: +\t\t\t\tlink.Attributes[\"pod\"] != \"lab1-r1-abc\" ||\n2293: +\t\t\t\tlink.Attributes[\"namespace\"] != \"c9s-lab1\" {\n2294: +\t\t\t\tt.Fatalf(\"%s event = %+v\", tt.link, link)\n2295: +\t\t\t}\n2296: +\t\t\tif got[\"lo\"].Interface.Type != \"device\" || got[\"eth0\"].Interface.Alias != \"\" {\n2297: +\t\t\t\tt.Fatalf(\"eth0/lo = %+v %+v\", got[\"eth0\"].Interface, got[\"lo\"].Interface)\n2298: +\t\t\t}\n2299: +\n2300: +\t\t\t// unchanged: nothing\n2301: +\t\t\tp.firstRound = false\n2302: +\t\t\tp.processSample(ctx, interfaceTestSample(\"r1\", start.Add(time.Second), links,\n2303: +\t\t\t\tpodInterfaces(tt.link, \"up\")))\n2304: +\t\t\tif events := drain(sink); len(events) != 0 {\n2305: +\t\t\t\tt.Fatalf(\"unchanged interfaces reported %+v\", events)\n2306: +\t\t\t}\n2307: +\n2308: +\t\t\t// the peer goes away: the link loses its carrier\n2309: +\t\t\tp.processSample(ctx, interfaceTestSample(\"r1\", start.Add(2*time.Second), links,\n2310: +\t\t\t\tpodInterfaces(tt.link, \"lowerlayerdown\")))\n2311: +\t\t\tevents := drain(sink)\n2312: +\t\t\tif len(events) != 1 || events[0].Action != interfaceActionUpdate ||\n2313: +\t\t\t\tevents[0].Interface.Name != tt.link ||\n2314: +\t\t\t\tevents[0].Interface.OperState != \"lower-layer-down\" {\n2315: +\t\t\t\tt.Fatalf(\"carrier loss reported %+v\", events)\n2316: +\t\t\t}\n2317: +\n2318: +\t\t\t// the link interface disappears, then comes back\n2319: +\t\t\twithoutLink := podInterfaces(tt.link, \"up\")\n2320: +\t\t\twithoutLink = withoutLink[:len(withoutLink)-1]\n2321: +\t\t\tp.processSample(\n2322: +\t\t\t\tctx,\n2323: +\t\t\t\tinterfaceTestSample(\"r1\", start.Add(3*time.Second), links, withoutLink),\n2324: +\t\t\t)\n2325: +\t\t\tevents = drain(sink)\n2326: +\t\t\tif len(events) != 1 || events[0].Action != interfaceActionDelete ||\n2327: +\t\t\t\tevents[0].Interface.Name != tt.link {\n2328: +\t\t\t\tt.Fatalf(\"removed link reported %+v\", events)\n2329: +\t\t\t}\n2330: +\t\t\tp.processSample(ctx, interfaceTestSample(\"r1\", start.Add(4*time.Second), links,\n2331: +\t\t\t\tpodInterfaces(tt.link, \"up\")))\n2332: +\t\t\tevents = drain(sink)\n2333: +\t\t\tif len(events) != 1 || events[0].Action != interfaceActionCreate ||\n2334: +\t\t\t\tevents[0].Interface.Alias != tt.alias {\n2335: +\t\t\t\tt.Fatalf(\"new link reported %+v\", events)\n2336: +\t\t\t}\n2337: +\n2338: +\t\t\t// the node stops: its interfaces are deleted\n2339: +\t\t\tp.retireStoppedNodes(ctx, map[string]bool{})\n2340: +\t\t\tgot = interfacesByName(drain(sink))\n2341: +\t\t\tif len(got) != 3 || got[tt.link].Action != interfaceActionDelete ||\n2342: +\t\t\t\tgot[\"eth0\"].Action != interfaceActionDelete || len(p.nodes) != 0 {\n2343: +\t\t\t\tt.Fatalf(\"stopped node reported %+v\", got)\n2344: +\t\t\t}\n2345: +\t\t})\n2346: +\t}\n2347: +}\n2348: +\n2349: +func TestInterfacePollerFirstRoundWithoutInitialState(t *testing.T) {\n2350: +\tt.Parallel()\n2351: +\n2352: +\tsink := make(chan clablabruntime.Event, 16)\n2353: +\tp := newInterfacePoller(&Runtime{}, eventScope{}, interfacePollOptions{}, sink)\n2354: +\tlinks := []clabwireInterface{{Node: \"r1\", Interface: \"eth1\"}}\n2355: +\tp.processSample(context.Background(),\n2356: +\t\tinterfaceTestSample(\"r1\", time.Now(), links, podInterfaces(\"eth1\", \"up\")))\n2357: +\tif events := drain(sink); len(events) != 0 {\n2358: +\t\tt.Fatalf(\"first round without --initial-state reported %+v\", events)\n2359: +\t}\n2360: +}\n2361: +\n2362: +func TestInterfacePollerStatsCoverTheReportedInterfaces(t *testing.T) {\n2363: +\tt.Parallel()\n2364: +\n2365: +\tsink := make(chan clablabruntime.Event, 32)\n2366: +\tp := newInterfacePoller(\n2367: +\t\t&Runtime{},\n2368: +\t\teventScope{},\n2369: +\t\tinterfacePollOptions{includeStats: true},\n2370: +\t\tsink,\n2371: +\t)\n2372: +\tlinks := []clabwireInterface{{Node: \"r1\", Interface: \"e1-1\", Alias: \"ethernet-1/1\"}}\n2373: +\tstart := time.Now()\n2374: +\tfirst := interfaceTestSample(\"r1\", start, links, podInterfaces(\"e1-1\", \"up\"))\n2375: +\tsecond := interfaceTestSample(\"r1\", start.Add(time.Second), links, podInterfaces(\"e1-1\", \"up\"))\n2376: +\tfor idx := range second.stats {\n2377: +\t\tsecond.stats[idx].RxBytes = first.stats[idx].RxBytes + 1000\n2378: +\t}\n2379: +\n2380: +\tp.processSample(context.Background(), first)\n2381: +\t_ = drain(sink)\n2382: +\tp.processSample(context.Background(), second)\n2383: +\tgot := interfacesByName(drain(sink))\n2384: +\tif len(got) != 3 {\n2385: +\t\tt.Fatalf(\"stats reported for %v, want e1-1, eth0 and lo\", got)\n2386: +\t}\n2387: +\tstats := got[\"e1-1\"]\n2388: +\tif stats.Action != interfaceActionStats || stats.Interface.Alias != \"ethernet-1/1\" ||\n2389: +\t\tstats.Interface.Index != 7 || stats.Interface.OperState != \"up\" ||\n2390: +\t\tstats.Interface.Stats == nil || stats.Interface.Stats.RxBps != 8000 ||\n2391: +\t\tstats.Interface.Stats.Interval != time.Second {\n2392: +\t\tt.Fatalf(\"e1-1 stats = %+v %+v\", stats, stats.Interface)\n2393: +\t}\n2394: +}\n2395: +\n2396: +// listingExec answers clabwire --list-interfaces with the listing of the pod and counts the\n2397: +// listings.\n2398: +type listingExec struct {\n2399: +\tmu       sync.Mutex\n2400: +\tlistings map[string][]clabwireInterface\n2401: +\tcalls    int\n2402: +}\n2403: +\n2404: +func (l *listingExec) exec(\n2405: +\t_ context.Context,\n2406: +\t_, pod, container string,\n2407: +\tcommand []string,\n2408: +\t_ io.Reader,\n2409: +\tstdout, _ io.Writer,\n2410: +) error {\n2411: +\tl.mu.Lock()\n2412: +\tdefer l.mu.Unlock()\n2413: +\n2414: +\tif container != clabwireContainer || !slices.Contains(command, \"--list-interfaces\") {\n2415: +\t\treturn nil\n2416: +\t}\n2417: +\tl.calls++\n2418: +\n2419: +\treturn json.NewEncoder(stdout).Encode(l.listings[pod])\n2420: +}\n2421: +\n2422: +func TestInterfacePollerListsAPodOncePerInterfaceSet(t *testing.T) {\n2423: +\tt.Parallel()\n2424: +\n2425: +\tlisting := &listingExec{listings: map[string][]clabwireInterface{\n2426: +\t\t\"lab1-r1-abc\": {\n2427: +\t\t\t{Node: \"r1\", Interface: \"e1-1\", Alias: \"ethernet-1/1\"},\n2428: +\t\t\t{Node: \"r1b\", Interface: \"e1-2\"},\n2429: +\t\t},\n2430: +\t}}\n2431: +\tr := &Runtime{podExec: listing.exec}\n2432: +\tp := newInterfacePoller(\n2433: +\t\tr,\n2434: +\t\teventScope{},\n2435: +\t\tinterfacePollOptions{},\n2436: +\t\tmake(chan clablabruntime.Event),\n2437: +\t)\n2438: +\ttarget := interfaceTestSample(\"r1\", time.Now(), nil, nil).target\n2439: +\n2440: +\tfor range 3 {\n2441: +\t\tlinks, err := p.nodeLinks(context.Background(), target, \"e1-1,eth0,lo\")\n2442: +\t\tif err != nil {\n2443: +\t\t\tt.Fatal(err)\n2444: +\t\t}\n2445: +\t\tif len(links) != 1 || links[0].Alias != \"ethernet-1/1\" {\n2446: +\t\t\tt.Fatalf(\"links = %+v, want the node's own link\", links)\n2447: +\t\t}\n2448: +\t}\n2449: +\tif listing.calls != 1 {\n2450: +\t\tt.Fatalf(\"listed %d times, want once while the interfaces stay the same\", listing.calls)\n2451: +\t}\n2452: +\n2453: +\tif _, err := p.nodeLinks(context.Background(), target, \"e1-1,e1-2,eth0,lo\"); err != nil {\n2454: +\t\tt.Fatal(err)\n2455: +\t}\n2456: +\tif listing.calls != 2 {\n2457: +\t\tt.Fatalf(\"listed %d times, want again after the interfaces changed\", listing.calls)\n2458: +\t}\n2459: +\n2460: +\tp.forgetListings(map[string]bool{})\n2461: +\tif len(p.listings) != 0 {\n2462: +\t\tt.Fatalf(\"listings of gone pods kept: %+v\", p.listings)\n2463: +\t}\n2464: +}\n2465: +\n2466: +func TestContainerTransitionActions(t *testing.T) {\n2467: +\tt.Parallel()\n2468: +\n2469: +\tconst (\n2470: +\t\tcreated = clablabruntime.ContainerStateCreated\n2471: +\t\trunning = clablabruntime.ContainerStateRunning\n2472: +\t\texited  = clablabruntime.ContainerStateExited\n2473: +\t\thealthy = clablabruntime.ContainerHealthHealthy\n2474: +\t\tstart   = clablabruntime.ContainerHealthStarting\n2475: +\t\tsick    = clablabruntime.ContainerHealthUnhealthy\n2476: +\t)\n2477: +\ttracked := func(state, health, pod string) *trackedContainer {\n2478: +\t\treturn &trackedContainer{state: state, health: health, pod: pod}\n2479: +\t}\n2480: +\n2481: +\ttests := []struct {\n2482: +\t\tname     string\n2483: +\t\tprevious *trackedContainer\n2484: +\t\tnext     *trackedContainer\n2485: +\t\twant     string\n2486: +\t}{\n2487: +\t\t{\"new pending node\", nil, tracked(created, \"\", \"\"), \"create\"},\n2488: +\t\t{\n2489: +\t\t\t\"new running node\", nil, tracked(running, start, \"p1\"),\n2490: +\t\t\t\"create,start,health_status: starting\",\n2491: +\t\t},\n2492: +\t\t{\n2493: +\t\t\t\"new ready node\", nil, tracked(running, healthy, \"p1\"),\n2494: +\t\t\t\"create,start,health_status: healthy\",\n2495: +\t\t},\n2496: +\t\t{\"new stopped node\", nil, tracked(exited, \"\", \"\"), \"create,stop\"},\n2497: +\t\t{\n2498: +\t\t\t\"pod starts\", tracked(created, \"\", \"p1\"), tracked(running, start, \"p1\"),\n2499: +\t\t\t\"start,health_status: starting\",\n2500: +\t\t},\n2501: +\t\t{\n2502: +\t\t\t\"device ready\", tracked(running, start, \"p1\"), tracked(running, healthy, \"p1\"),\n2503: +\t\t\t\"health_status: healthy\",\n2504: +\t\t},\n2505: +\t\t{\"still booting\", tracked(running, start, \"p1\"), tracked(running, start, \"p1\"), \"\"},\n2506: +\t\t{\"no change\", tracked(running, healthy, \"p1\"), tracked(running, healthy, \"p1\"), \"\"},\n2507: +\t\t{\n2508: +\t\t\t\"device not ready again\", tracked(running, healthy, \"p1\"), tracked(running, sick, \"p1\"),\n2509: +\t\t\t\"health_status: unhealthy\",\n2510: +\t\t},\n2511: +\t\t{\"stop\", tracked(running, healthy, \"p1\"), tracked(exited, \"\", \"\"), \"kill,stop,die\"},\n2512: +\t\t{\n2513: +\t\t\t\"start\", tracked(exited, \"\", \"\"), tracked(running, healthy, \"p2\"),\n2514: +\t\t\t\"start,health_status: healthy\",\n2515: +\t\t},\n2516: +\t\t{\n2517: +\t\t\t\"restart, new pod pending\", tracked(running, healthy, \"p1\"), tracked(created, \"\", \"p2\"),\n2518: +\t\t\t\"kill,stop,die\",\n2519: +\t\t},\n2520: +\t\t{\n2521: +\t\t\t\"restart, new pod running\", tracked(running, healthy, \"p1\"),\n2522: +\t\t\ttracked(running, start, \"p2\"), \"kill,stop,die,start,health_status: starting\",\n2523: +\t\t},\n2524: +\t\t{\"stopped before it ran\", tracked(created, \"\", \"p1\"), tracked(exited, \"\", \"\"), \"stop\"},\n2525: +\t\t{\"stopped node rescheduled\", tracked(exited, \"\", \"\"), tracked(created, \"\", \"p2\"), \"\"},\n2526: +\t}\n2527: +\tfor _, tt := range tests {\n2528: +\t\tgot := strings.Join(containerTransitionActions(tt.previous, tt.next), \",\")\n2529: +\t\tif got != tt.want {\n2530: +\t\t\tt.Fatalf(\"%s: actions = %q, want %q\", tt.name, got, tt.want)\n2531: +\t\t}\n2532: +\t}\n2533: +\n2534: +\tif got := strings.Join(containerRemovalActions(tracked(running, healthy, \"p1\")), \",\"); got !=\n2535: +\t\t\"kill,die,destroy\" {\n2536: +\t\tt.Fatalf(\"removal of a running node = %q\", got)\n2537: +\t}\n2538: +\tif got := strings.Join(\n2539: +\t\tcontainerRemovalActions(tracked(exited, \"\", \"\")),\n2540: +\t\t\",\",\n2541: +\t); got != \"destroy\" {\n2542: +\t\tt.Fatalf(\"removal of a stopped node = %q\", got)\n2543: +\t}\n2544: +\n2545: +\t// health: a running node that was healthy and is not ready anymore in the same pod is\n2546: +\t// unhealthy; in a new pod it starts again\n2547: +\tprevious := tracked(running, healthy, \"p1\")\n2548: +\tif got := containerHealth(previous, tracked(running, \"\", \"p1\"), start); got != sick {\n2549: +\t\tt.Fatalf(\"health in the same pod = %q\", got)\n2550: +\t}\n2551: +\tif got := containerHealth(previous, tracked(running, \"\", \"p2\"), start); got != start {\n2552: +\t\tt.Fatalf(\"health in a new pod = %q\", got)\n2553: +\t}\n2554: +}\n2555: +\n2556: +// trackerTestNode is a Node of lab1 in lab-ns.\n2557: +func trackerTestNode(\n2558: +\tname string,\n2559: +\trunState string,\n2560: +\tconditions ...map[string]any,\n2561: +) *unstructured.Unstructured {\n2562: +\tstatus := map[string]any{\n2563: +\t\t\"readiness\":        \"notready\",\n2564: +\t\t\"directContainers\": []any{map[string]any{\"name\": \"node-\" + name, \"id\": name}},\n2565: +\t}\n2566: +\trawConditions := []any{}\n2567: +\tfor _, condition := range conditions {\n2568: +\t\trawConditions = append(rawConditions, condition)\n2569: +\t\tif condition[\"type\"] == \"Ready\" && condition[\"status\"] == \"True\" {\n2570: +\t\t\tstatus[\"readiness\"] = \"ready\"\n2571: +\t\t}\n2572: +\t}\n2573: +\tstatus[\"conditions\"] = rawConditions\n2574: +\n2575: +\treturn &unstructured.Unstructured{Object: map[string]any{\n2576: +\t\t\"apiVersion\": c9sAPIVersion,\n2577: +\t\t\"kind\":       \"Node\",\n2578: +\t\t\"metadata\": map[string]any{\n2579: +\t\t\t\"name\": name, \"namespace\": \"lab-ns\", \"uid\": \"uid-\" + name,\n2580: +\t\t\t\"labels\": map[string]any{\n2581: +\t\t\t\tlabelTopologyOwner: \"lab1\", labelOriginalNodeName: strings.ToUpper(name),\n2582: +\t\t\t},\n2583: +\t\t},\n2584: +\t\t\"spec\":   map[string]any{\"kind\": \"linux\", \"image\": \"alpine\", \"runState\": runState},\n2585: +\t\t\"status\": status,\n2586: +\t}}\n2587: +}\n2588: +\n2589: +func condition(conditionType, status string) map[string]any {\n2590: +\treturn map[string]any{\"type\": conditionType, \"status\": status}\n2591: +}\n2592: +\n2593: +func trackerTestPod(name string, phase corev1.PodPhase) *corev1.Pod {\n2594: +\tpod := captureTestPod(name, \"r1\")\n2595: +\tpod.Status.Phase = phase\n2596: +\n2597: +\treturn pod\n2598: +}\n2599: +\n2600: +type trackerHarness struct {\n2601: +\tt       *testing.T\n2602: +\tr       *Runtime\n2603: +\ttracker *containerTracker\n2604: +\tsink    chan clablabruntime.Event\n2605: +}\n2606: +\n2607: +func newTrackerHarness(\n2608: +\tt *testing.T,\n2609: +\tnode *unstructured.Unstructured,\n2610: +\tpods ...*corev1.Pod,\n2611: +) *trackerHarness {\n2612: +\tt.Helper()\n2613: +\n2614: +\tkubeObjects := make([]k8sruntime.Object, 0, len(pods))\n2615: +\tfor _, pod := range pods {\n2616: +\t\tkubeObjects = append(kubeObjects, pod)\n2617: +\t}\n2618: +\tr := newTestRuntimeWithKubeObjects([]*unstructured.Unstructured{node}, kubeObjects)\n2619: +\tr.labNamespaceOverride = \"lab-ns\"\n2620: +\tsink := make(chan clablabruntime.Event, 64)\n2621: +\n2622: +\treturn &trackerHarness{\n2623: +\t\tt: t, r: r, sink: sink,\n2624: +\t\ttracker: &containerTracker{r: r, sink: sink, nodes: map[string]*trackedContainer{}},\n2625: +\t}\n2626: +}\n2627: +\n2628: +func (h *trackerHarness) seed(snapshot bool) {\n2629: +\th.t.Helper()\n2630: +\n2631: +\tstate, err := h.r.Inspect(context.Background(), clablabruntime.InspectRequest{Name: \"lab1\"})\n2632: +\tif err != nil {\n2633: +\t\th.t.Fatal(err)\n2634: +\t}\n2635: +\th.tracker.observeLab(context.Background(), labRef{namespace: \"lab-ns\", lab: \"lab1\"}, state,\n2636: +\t\t&observeSeed{snapshot: snapshot})\n2637: +}\n2638: +\n2639: +func (h *trackerHarness) setNode(node *unstructured.Unstructured) {\n2640: +\th.t.Helper()\n2641: +\n2642: +\tif _, err := h.r.client.Resource(nodeGVR).Namespace(\"lab-ns\").\n2643: +\t\tUpdate(context.Background(), node, metav1.UpdateOptions{}); err != nil {\n2644: +\t\th.t.Fatal(err)\n2645: +\t}\n2646: +}\n2647: +\n2648: +func (h *trackerHarness) deletePod(name string) {\n2649: +\th.t.Helper()\n2650: +\n2651: +\tif err := h.r.kubeClient.CoreV1().Pods(\"lab-ns\").\n2652: +\t\tDelete(context.Background(), name, metav1.DeleteOptions{}); err != nil {\n2653: +\t\th.t.Fatal(err)\n2654: +\t}\n2655: +}\n2656: +\n2657: +func (h *trackerHarness) addPod(pod *corev1.Pod) {\n2658: +\th.t.Helper()\n2659: +\n2660: +\tif _, err := h.r.kubeClient.CoreV1().Pods(\"lab-ns\").\n2661: +\t\tCreate(context.Background(), pod, metav1.CreateOptions{}); err != nil {\n2662: +\t\th.t.Fatal(err)\n2663: +\t}\n2664: +}\n2665: +\n2666: +// refresh reads lab1 again and returns the reported actions with their state attribute.\n2667: +func (h *trackerHarness) refresh() string {\n2668: +\th.t.Helper()\n2669: +\n2670: +\tif !h.tracker.refresh(context.Background(), labRef{namespace: \"lab-ns\", lab: \"lab1\"}) {\n2671: +\t\th.t.Fatal(\"refresh failed\")\n2672: +\t}\n2673: +\n2674: +\tvar actions []string\n2675: +\tfor _, ev := range drain(h.sink) {\n2676: +\t\tif ev.Type != clablabruntime.EventTypeContainer || ev.ActorID != \"lab-ns/lab1/r1\" ||\n2677: +\t\t\tev.ActorFullID != \"lab-ns/lab1/r1\" || ev.ActorName != \"lab1-r1\" ||\n2678: +\t\t\tev.Lab == nil || ev.Node == nil || ev.Node.TopologyName != \"R1\" ||\n2679: +\t\t\tev.Attributes[\"lab\"] != \"lab1\" || ev.Attributes[\"node\"] != \"r1\" ||\n2680: +\t\t\tev.Attributes[\"namespace\"] != \"lab-ns\" {\n2681: +\t\t\th.t.Fatalf(\"container event = %+v\", ev)\n2682: +\t\t}\n2683: +\t\taction := ev.Action + \"=\" + ev.Attributes[\"state\"]\n2684: +\t\tif signal := ev.Attributes[\"signal\"]; signal != \"\" {\n2685: +\t\t\taction += \"/\" + signal\n2686: +\t\t}\n2687: +\t\tactions = append(actions, action)\n2688: +\t}\n2689: +\n2690: +\treturn strings.Join(actions, \",\")\n2691: +}\n2692: +\n2693: +// TestContainerTrackerReportsTheNodeLifecycle drives one node through boot, readiness, stop,\n2694: +// start, restart and removal on the fake cluster and checks the Docker container events.\n2695: +func TestContainerTrackerReportsTheNodeLifecycle(t *testing.T) {\n2696: +\tt.Parallel()\n2697: +\n2698: +\tnode := trackerTestNode(\"r1\", nodeRunStateRunning)\n2699: +\th := newTrackerHarness(t, node, trackerTestPod(\"lab1-r1-a\", corev1.PodPending))\n2700: +\th.seed(true)\n2701: +\tsnapshot := drain(h.sink)\n2702: +\tif len(snapshot) != 1 || snapshot[0].Action != \"created\" ||\n2703: +\t\tsnapshot[0].Attributes[\"origin\"] != clablabruntime.EventOriginSnapshot ||\n2704: +\t\tsnapshot[0].Attributes[\"state\"] != \"created\" {\n2705: +\t\tt.Fatalf(\"snapshot = %+v\", snapshot)\n2706: +\t}\n2707: +\n2708: +\t// the pod runs, the device boots\n2709: +\th.deletePod(\"lab1-r1-a\")\n2710: +\th.addPod(trackerTestPod(\"lab1-r1-a\", corev1.PodRunning))\n2711: +\tif got := h.refresh(); got != \"start=running,health_status: starting=running\" {\n2712: +\t\tt.Fatalf(\"pod running: %s\", got)\n2713: +\t}\n2714: +\n2715: +\t// the device is ready\n2716: +\th.setNode(trackerTestNode(\"r1\", nodeRunStateRunning,\n2717: +\t\tcondition(\"Ready\", \"True\"), condition(nodeConditionContainersReady, \"True\")))\n2718: +\tif got := h.refresh(); got != \"health_status: healthy=running\" {\n2719: +\t\tt.Fatalf(\"ready: %s\", got)\n2720: +\t}\n2721: +\tif got := h.refresh(); got != \"\" {\n2722: +\t\tt.Fatalf(\"unchanged: %s\", got)\n2723: +\t}\n2724: +\n2725: +\t// stop: the Node is stopped and its pod goes\n2726: +\th.setNode(trackerTestNode(\"r1\", nodeRunStateStopped,\n2727: +\t\tcondition(nodeConditionStopped, \"True\")))\n2728: +\th.deletePod(\"lab1-r1-a\")\n2729: +\tif got := h.refresh(); got != \"kill=running/15,stop=exited,die=exited\" {\n2730: +\t\tt.Fatalf(\"stop: %s\", got)\n2731: +\t}\n2732: +\n2733: +\t// start: a new pod\n2734: +\th.setNode(trackerTestNode(\"r1\", nodeRunStateRunning))\n2735: +\th.addPod(trackerTestPod(\"lab1-r1-b\", corev1.PodPending))\n2736: +\tif got := h.refresh(); got != \"\" {\n2737: +\t\tt.Fatalf(\"start requested: %s\", got)\n2738: +\t}\n2739: +\th.deletePod(\"lab1-r1-b\")\n2740: +\th.addPod(trackerTestPod(\"lab1-r1-b\", corev1.PodRunning))\n2741: +\th.setNode(\n2742: +\t\ttrackerTestNode(\"r1\", nodeRunStateRunning, condition(nodeConditionContainersReady, \"True\")),\n2743: +\t)\n2744: +\tif got := h.refresh(); got != \"start=running,health_status: healthy=running\" {\n2745: +\t\tt.Fatalf(\"started: %s\", got)\n2746: +\t}\n2747: +\n2748: +\t// restart: the pod is replaced\n2749: +\th.deletePod(\"lab1-r1-b\")\n2750: +\th.addPod(trackerTestPod(\"lab1-r1-c\", corev1.PodRunning))\n2751: +\tif got := h.refresh(); got !=\n2752: +\t\t\"kill=running/15,stop=exited,die=exited,start=running,health_status: healthy=running\" {\n2753: +\t\tt.Fatalf(\"restart: %s\", got)\n2754: +\t}\n2755: +\n2756: +\t// destroy\n2757: +\tif err := h.r.client.Resource(nodeGVR).Namespace(\"lab-ns\").\n2758: +\t\tDelete(context.Background(), \"r1\", metav1.DeleteOptions{}); err != nil {\n2759: +\t\tt.Fatal(err)\n2760: +\t}\n2761: +\tif got := h.refresh(); got != \"kill=running/15,die=exited,destroy=exited\" {\n2762: +\t\tt.Fatalf(\"destroy: %s\", got)\n2763: +\t}\n2764: +\tif len(h.tracker.nodes) != 0 {\n2765: +\t\tt.Fatalf(\"destroyed node still tracked: %+v\", h.tracker.nodes)\n2766: +\t}\n2767: +}\n2768: +\n2769: +func TestContainerTrackerSeedsWithoutSnapshot(t *testing.T) {\n2770: +\tt.Parallel()\n2771: +\n2772: +\th := newTrackerHarness(t, trackerTestNode(\"r1\", nodeRunStateRunning,\n2773: +\t\tcondition(\"Ready\", \"True\")), trackerTestPod(\"lab1-r1-a\", corev1.PodRunning))\n2774: +\th.seed(false)\n2775: +\tif events := drain(h.sink); len(events) != 0 {\n2776: +\t\tt.Fatalf(\"seed without --initial-state reported %+v\", events)\n2777: +\t}\n2778: +\tif got := h.refresh(); got != \"\" {\n2779: +\t\tt.Fatalf(\"unchanged after seed: %s\", got)\n2780: +\t}\n2781: +}\n2782: +\n2783: +func TestNodeContainerState(t *testing.T) {\n2784: +\tt.Parallel()\n2785: +\n2786: +\tdeleting := metav1.NewTime(time.Now())\n2787: +\tpod := func(phase corev1.PodPhase, deleted bool) *corev1.Pod {\n2788: +\t\tp := &corev1.Pod{Status: corev1.PodStatus{Phase: phase}}\n2789: +\t\tif deleted {\n2790: +\t\t\tp.DeletionTimestamp = &deleting\n2791: +\t\t}\n2792: +\n2793: +\t\treturn p\n2794: +\t}\n2795: +\n2796: +\ttests := []struct {\n2797: +\t\tname          string\n2798: +\t\tstopRequested bool\n2799: +\t\tpod           *corev1.Pod\n2800: +\t\twant          string\n2801: +\t}{\n2802: +\t\t{\"no pod yet\", false, nil, \"created\"},\n2803: +\t\t{\"pod scheduled, init containers\", false, pod(corev1.PodPending, false), \"created\"},\n2804: +\t\t{\"device containers run\", false, pod(corev1.PodRunning, false), \"running\"},\n2805: +\t\t{\"pod being deleted (restart)\", false, pod(corev1.PodRunning, true), \"exited\"},\n2806: +\t\t{\"pod ended\", false, pod(corev1.PodFailed, false), \"exited\"},\n2807: +\t\t{\"stop requested, pod terminating\", true, pod(corev1.PodRunning, true), \"exited\"},\n2808: +\t\t{\"stopped\", true, nil, \"exited\"},\n2809: +\t}\n2810: +\tfor _, tt := range tests {\n2811: +\t\tif got := nodeContainerState(tt.stopRequested, tt.pod); got != tt.want {\n2812: +\t\t\tt.Fatalf(\"%s: %q, want %q\", tt.name, got, tt.want)\n2813: +\t\t}\n2814: +\t}\n2815: +}\n2816: +\n2817: +func TestNewestPodPrefersAPodThatIsNotDeleted(t *testing.T) {\n2818: +\tt.Parallel()\n2819: +\n2820: +\tnow := time.Now()\n2821: +\tdeleting := metav1.NewTime(now)\n2822: +\told := &corev1.Pod{\n2823: +\t\tObjectMeta: metav1.ObjectMeta{\n2824: +\t\t\tName: \"old\", CreationTimestamp: metav1.NewTime(now.Add(-time.Hour)),\n2825: +\t\t\tDeletionTimestamp: &deleting,\n2826: +\t\t},\n2827: +\t\tStatus: corev1.PodStatus{Phase: corev1.PodRunning},\n2828: +\t}\n2829: +\treplacement := &corev1.Pod{\n2830: +\t\tObjectMeta: metav1.ObjectMeta{Name: \"new\", CreationTimestamp: metav1.NewTime(now)},\n2831: +\t\tStatus:     corev1.PodStatus{Phase: corev1.PodPending},\n2832: +\t}\n2833: +\tif got := newestPod(old, replacement); got != replacement {\n2834: +\t\tt.Fatalf(\"newestPod = %s, want the replacement\", got.Name)\n2835: +\t}\n2836: +\tif got := newestPod(replacement, old); got != replacement {\n2837: +\t\tt.Fatalf(\"newestPod = %s, want the replacement\", got.Name)\n2838: +\t}\n2839: +}\n2840: +\n2841: +func TestEnrichStateReportsContainerStateAndHealth(t *testing.T) {\n2842: +\tt.Parallel()\n2843: +\n2844: +\tr := newTestRuntimeWithKubeObjects(\n\n(Output capped at 50 KB. Showing lines 1362-2844. Use offset=2845 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "     \"mtu\": \"9232\",\n     \"mac\": \"aa:c1:ab:5e:2f:01\",\n     \"lab\": \"clos\",\n-    \"node\": \"srl1\",\n     \"name\": \"clos-srl1\",\n+    \"id\": \"c9s-clos/clos/srl1\",\n+    \"node\": \"srl1\",\n     \"namespace\": \"c9s-clos\",\n     \"pod\": \"srl1-7d9c6b5f4-x2k8p\",\n     \"origin\": \"clabernetes\"\n   }\n }\n ```\n \n-- `action` is `up` when the operational state is `up`, or `unknown` on an\n-  administratively up interface (loopback, tunnels); otherwise `down`.\n-- `attributes.state` is the raw operational state from\n-  `/sys/class/net/<if>/operstate`. An interface that disappears, or whose node\n-  stops running, is reported once as `down` with state `notpresent`.\n-- An event is emitted when an interface appears, when its action or state",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "     \"mtu\": \"9232\",\n     \"mac\": \"aa:c1:ab:5e:2f:01\",\n     \"lab\": \"clos\",\n-    \"node\": \"srl1\",\n     \"name\": \"clos-srl1\",\n+    \"id\": \"c9s-clos/clos/srl1\",\n+    \"node\": \"srl1\",\n     \"namespace\": \"c9s-clos\",\n     \"pod\": \"srl1-7d9c6b5f4-x2k8p\",\n     \"origin\": \"clabernetes\"\n   }\n }\n ```\n \n-- `action` is `up` when the operational state is `up`, or `unknown` on an\n-  administratively up interface (loopback, tunnels); otherwise `down`.\n-- `attributes.state` is the raw operational state from\n-  `/sys/class/net/<if>/operstate`. An interface that disappears, or whose node\n-  stops running, is reported once as `down` with state `notpresent`.\n-- An event is emitted when an interface appears, when its action or state\n-  changes, and, with `--initial-state`, once for every interface at the start.\n-- Device containers without a shell report statistics only, no interface state.\n+- `action` is `snapshot` for every interface at the start with\n+  `--initial-state`, `create` when an interface appears (for example when a\n+  node starts), `update` when one of its attributes changes, and `delete` when\n+  it disappears or its node stops running.\n+- `state` is the operational state in netlink's names: `up`, `down`,\n+  `lower-layer-down`, `unknown` (loopback), `dormant`, `testing`, `not-present`.\n+- `type` is `veth` for the lab link and management interfaces and `device` for\n+  loopback.\n+- Device containers without a shell report statistics only, no interface state,\n+  and no `index` or `mtu`.\n \n With `--interface-stats`, the same exec also produces `interface stats` events\n-with byte and packet counters and rates. They use the node ID as actor, like\n-the state events. `--interface-stats-interval` sets the sampling interval of\n-both (default 1s).\n+for the same interfaces, with their attributes and the byte and packet counters\n+and rates. `--interface-stats-interval` sets the sampling interval of both\n+(default 1s).\n+\n+`inspect interfaces -r c9s` lists the same interfaces with the same values.\n \n /// note | Polling, not netlink\n c9s interface state and statistics are sampled periodically. The first sample\n seeds the counters, and rates start with the second sample. Short-lived changes\n between samples can be missed. Every running node gets one exec per interval,\ndiff --git a/labruntime/clabernetes/capture.go b/labruntime/clabernetes/capture.go\nindex 69d4072..3d50217 100644\n--- a/labruntime/clabernetes/capture.go\n+++ b/labruntime/clabernetes/capture.go\n@@ -237,26 +237,15 @@ func (r *Runtime) listCaptureInterfaces(\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\tentries, err := r.listPodInterfaces(groupCtx, location.Namespace, location.Pod)\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\treturn 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@@ -273,10 +262,34 @@ func (r *Runtime) listCaptureInterfaces(\n \t}\n \n \treturn result, nil\n }\n \n+// listPodInterfaces runs clabwire's --list-interfaces in a pod: the lab link interfaces of the\n+// pod's nodes, with their aliases and peers.\n+func (r *Runtime) listPodInterfaces(\n+\tctx context.Context,\n+\tnamespace, pod string,\n+) ([]clabwireInterface, error) {\n+\tvar stdout, stderr bytes.Buffer\n+\terr := r.execInPodContainer()(ctx, namespace, pod, clabwireContainer,\n+\t\t[]string{clabwireManager, \"node-runtime\", \"packet-capture\", \"--list-interfaces\"},\n+\t\tnil, &stdout, &stderr)\n+\tif err != nil {\n+\t\treturn nil, fmt.Errorf(\"failed to list the capturable interfaces of pod %s/%s: %w%s\",\n+\t\t\tnamespace, pod, err, stderrSuffix(stderr.Bytes()))\n+\t}\n+\n+\tvar entries []clabwireInterface\n+\tif err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {\n+\t\treturn nil, fmt.Errorf(\"failed to parse the capturable interfaces of pod %s/%s: %w\",\n+\t\t\tnamespace, pod, err)\n+\t}\n+\n+\treturn entries, nil\n+}\n+\n func stderrSuffix(stderr []byte) string {\n \ttext := strings.TrimSpace(string(stderr))\n \tif text == \"\" {\n \t\treturn \"\"\n \t}\ndiff --git a/labruntime/clabernetes/capture_interfaces.go b/labruntime/clabernetes/capture_interfaces.go\nindex 21029ed..6e3df10 100644\n--- a/labruntime/clabernetes/capture_interfaces.go\n+++ b/labruntime/clabernetes/capture_interfaces.go\n@@ -66,15 +66,16 @@ func (r *Runtime) streamPodExec(\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+// InspectInterfaces lists the interfaces of the requested nodes, or of every running node, in\n+// the shape of `inspect interfaces`, with the interfaces the interface events report: the lab\n+// link interfaces and their aliases as clabwire lists them, the management interface and\n+// loopback. Per node (named <lab>-<node> like in inspect) it reports 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+// container has no shell reports its link 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@@ -109,22 +110,32 @@ func (r *Runtime) InspectInterfaces(\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\tsampled, hasStates := states[location.NodeName]\n+\t\tfor name, alias := range reportedInterfaces(listed[location.NodeName]) {\n+\t\t\tstate, ok := sampled[name]\n+\t\t\tif !ok {\n+\t\t\t\tif hasStates || (name == managementInterface || name == loopbackInterface) {\n+\t\t\t\t\t// not present in the node (yet), or not known without its states\n+\t\t\t\t\tcontinue\n+\t\t\t\t}\n+\t\t\t\tstate = c9sIfaceState{Name: name}\n+\t\t\t}\n+\n+\t\t\tdata := interfaceEventData(state, alias)\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\tInterfaceName:  data.Name,\n+\t\t\t\tInterfaceAlias: data.Alias,\n+\t\t\t\tInterfaceType:  data.Type,\n+\t\t\t\tInterfaceMAC:   data.MAC,\n+\t\t\t\tInterfaceIndex: data.Index,\n+\t\t\t\tInterfaceMTU:   data.MTU,\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\tif ok {\n+\t\t\t\tdetails.InterfaceState = data.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\ndiff --git a/labruntime/clabernetes/capture_test.go b/labruntime/clabernetes/capture_test.go\nindex 16628b5..a099566 100644\n--- a/labruntime/clabernetes/capture_test.go\n+++ b/labruntime/clabernetes/capture_test.go\n@@ -14,10 +14,11 @@ import (\n \t\"testing\"\n \t\"time\"\n \n \tclabcapture \"github.com/srl-labs/containerlab/capture\"\n \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+\tclabtypes \"github.com/srl-labs/containerlab/types\"\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@@ -713,37 +714,56 @@ func TestCaptureValidatesTargets(t *testing.T) {\n \tif commands := clabwire.captureCommands(); len(commands) != 0 {\n \t\tt.Fatalf(\"invalid requests started captures: %v\", commands)\n \t}\n }\n \n+// TestInspectInterfacesReportsStateFromSysfs lists what a Docker container of the node reports:\n+// the lab link interfaces with their topology aliases, eth0 and lo, not clabernetes' own\n+// interfaces, with netlink's state names.\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\"lo\\t1\\t65536\\t00:00:00:00:00:00\\tunknown\\t0x9\\t\\n\" +\n+\t\t\"c9s0\\t2\\t1500\\t6e:43:ce:6b:3f:dc\\tup\\t0x1003\\t\\n\" +\n+\t\t\"eth0\\t4\\t1450\\t3a:3b:86:d8:73:37\\tup\\t0x1003\\tc9s:interposition:v1\\n\" +\n+\t\t\"c9ss1\\t6\\t9500\\t3e:9c:45:56:67:2f\\tup\\t0x1003\\tc9s:direct:v1:x\\n\" +\n+\t\t\"e1-1\\t12\\t9500\\taa:c1:ab:00:00:01\\tup\\t0x1003\\tc9s:direct:v1:x\\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\tlen(interfaces[0].Interfaces) != 4 {\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+\tbyName := map[string]*clabtypes.ContainerInterfaceDetails{}\n+\tfor _, iface := range interfaces[0].Interfaces {\n+\t\tbyName[iface.InterfaceName] = iface\n+\t}\n+\tfirst := byName[\"e1-1\"]\n+\tif first == nil || 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\tfirst.InterfaceMTU != 9500 || first.InterfaceState != \"up\" || first.InterfaceType != \"veth\" {\n \t\tt.Fatalf(\"e1-1 = %+v\", first)\n \t}\n-\tif second := interfaces[0].Interfaces[1]; second.InterfaceState != \"lowerlayerdown\" {\n+\tif second := byName[\"e1-2\"]; second == nil || second.InterfaceState != \"lower-layer-down\" {\n \t\tt.Fatalf(\"e1-2 = %+v\", second)\n \t}\n+\tif eth0 := byName[\"eth0\"]; eth0 == nil || eth0.InterfaceAlias != \"\" ||\n+\t\teth0.InterfaceType != \"veth\" {\n+\t\tt.Fatalf(\"eth0 = %+v\", eth0)\n+\t}\n+\tif lo := byName[\"lo\"]; lo == nil || lo.InterfaceType != \"device\" || lo.InterfaceMAC != \"\" ||\n+\t\tlo.InterfaceState != \"unknown\" {\n+\t\tt.Fatalf(\"lo = %+v\", lo)\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\ndiff --git a/labruntime/clabernetes/clabernetes.go b/labruntime/clabernetes/clabernetes.go\nindex e869191..dc202d3 100644\n--- a/labruntime/clabernetes/clabernetes.go\n+++ b/labruntime/clabernetes/clabernetes.go\n@@ -35,10 +35,12 @@ const (\n \tclabernetesAppValue   = \"clabernetes\"\n \t// persistenceReclaimRetain keeps a node's persistent claim when its Node is deleted.\n \tpersistenceReclaimRetain = \"Retain\"\n \t// defaultContainerAnnotation names the primary device container of a c9s pod.\n \tdefaultContainerAnnotation = \"kubectl.kubernetes.io/default-container\"\n+\t// annotationDirectNodeUID names the UID of the Node a c9s pod runs.\n+\tannotationDirectNodeUID = \"c9s.run/direct-node-uid\"\n )\n \n var topologyGVR = schema.GroupVersionResource{\n \tGroup:    \"c9s.run\",\n \tVersion:  \"v1alpha1\",\ndiff --git a/labruntime/clabernetes/clabernetes_test.go b/labruntime/clabernetes/clabernetes_test.go\nindex b6e34cd..92e07a1 100644\n--- a/labruntime/clabernetes/clabernetes_test.go\n+++ b/labruntime/clabernetes/clabernetes_test.go\n@@ -3734,11 +3734,11 @@ func TestForwardPodWatchReconnectsOnClosedChannel(t *testing.T) {\n \n \tr := &Runtime{}\n \tif !r.forwardPodWatch(\n \t\tcontext.Background(),\n \t\twatcher,\n-\t\tmake(chan clablabruntime.Event, 1),\n+\t\tmake(chan labRef, 1),\n \t\tmake(chan error, 1),\n \t) {\n \t\tt.Fatal(\"expected closed pod watch to request reconnect\")\n \t}\n }\n@@ -3752,55 +3752,49 @@ func TestForwardTopologyWatchReconnectsOnClosedChannel(t *testing.T) {\n \tr := &Runtime{}\n \tif !r.forwardTopologyWatch(\n \t\tcontext.Background(),\n \t\t\"default\",\n \t\twatcher,\n+\t\tmake(chan labRef, 1),\n \t\tmake(chan clablabruntime.Event, 1),\n \t\tmake(chan error, 1),\n \t) {\n \t\tt.Fatal(\"expected closed topology watch to request reconnect\")\n \t}\n }\n \n-func TestForwardPodWatchEmitsPodEvent(t *testing.T) {\n+func TestForwardPodWatchReportsTheLabOfAPod(t *testing.T) {\n \tt.Parallel()\n \n \twatcher := watch.NewFake()\n-\tevents := make(chan clablabruntime.Event, 1)\n+\tchanged := make(chan labRef, 1)\n \terrs := make(chan error, 1)\n \tctx, cancel := context.WithCancel(context.Background())\n \tdefer cancel()\n \n \tr := &Runtime{}\n \tdone := make(chan bool, 1)\n \tgo func() {\n-\t\tdone <- r.forwardPodWatch(ctx, watcher, events, errs)\n+\t\tdone <- r.forwardPodWatch(ctx, watcher, changed, errs)\n \t}()\n \n+\t// a pod without the lab label is not a lab's pod\n \twatcher.Add(&corev1.Pod{})\n-\twatcher.Add(&corev1.Pod{\n+\twatcher.Modify(&corev1.Pod{\n \t\tObjectMeta: metav1.ObjectMeta{\n \t\t\tName:      \"pod1\",\n \t\t\tNamespace: \"lab-ns\",\n \t\t\tLabels: map[string]string{\n \t\t\t\tlabelTopologyOwner: \"lab1\",\n \t\t\t\tlabelTopologyNode:  \"node1\",\n \t\t\t},\n \t\t},\n-\t\tStatus: corev1.PodStatus{\n-\t\t\tPhase: corev1.PodRunning,\n-\t\t\tPodIP: \"10.0.0.1\",\n-\t\t},\n+\t\tStatus: corev1.PodStatus{Phase: corev1.PodRunning},\n \t})\n \n-\tgot := <-events\n-\tif got.ActorID != \"lab-ns/lab1/node1\" ||\n-\t\tgot.ActorName != \"lab1-node1\" ||\n-\t\tgot.ActorFullID != \"pod1\" ||\n-\t\tgot.Attributes[\"phase\"] != string(corev1.PodRunning) ||\n-\t\tgot.Attributes[\"pod_ip\"] != \"10.0.0.1\" {\n-\t\tt.Fatalf(\"unexpected pod event: %+v\", got)\n+\tif got := <-changed; got != (labRef{namespace: \"lab-ns\", lab: \"lab1\"}) {\n+\t\tt.Fatalf(\"changed lab = %+v\", got)\n \t}\n \n \tcancel()\n \twatcher.Stop()\n \ndiff --git a/labruntime/clabernetes/container_events.go b/labruntime/clabernetes/container_events.go\nnew file mode 100644\nindex 0000000..ef7cf21\n--- /dev/null\n+++ b/labruntime/clabernetes/container_events.go\n@@ -0,0 +1,363 @@\n+package clabernetes\n+\n+import (\n+\t\"context\"\n+\t\"errors\"\n+\t\"fmt\"\n+\t\"strings\"\n+\t\"time\"\n+\n+\t\"github.com/charmbracelet/log\"\n+\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n+)\n+\n+// Container event actions, as the Docker runtime reports them.\n+const (\n+\tcontainerActionCreate        = \"create\"\n+\tcontainerActionStart         = \"start\"\n+\tcontainerActionKill          = \"kill\"\n+\tcontainerActionStop          = \"stop\"\n+\tcontainerActionDie           = \"die\"\n+\tcontainerActionDestroy       = \"destroy\"\n+\tcontainerActionHealthPrefix  = \"health_status: \"\n+\tcontainerEventSignalSIGTERM  = \"15\"\n+\tcontainerRefreshDelay        = 200 * time.Millisecond\n+\tcontainerRefreshRetryDelay   = pollInterval\n+\tcontainerEventAttributeState = \"state\"\n+)\n+\n+// trackedContainer is the last reported container state of a node.\n+type trackedContainer struct {\n+\tref    labRef\n+\tstate  string\n+\thealth string\n+\tpod    string\n+\t// lab and node are the last observation, which a removed node is described with.\n+\tlab  *clablabruntime.LabState\n+\tnode clablabruntime.NodeState\n+}\n+\n+// containerTracker turns the node states of the labs in an event scope into the container\n+// events the Docker runtime emits for the same lifecycle: create and start when a node's pod\n+// starts, kill, stop and die when it stops (on request, or between the pods of a restart),\n+// destroy when the node is removed, and health_status as its device becomes ready.\n+type containerTracker struct {\n+\tr     *Runtime\n+\tsink  chan<- clablabruntime.Event\n+\tnodes map[string]*trackedContainer\n+}\n+\n+// trackContainers reports the container events of a scope. It reads the labs once, reporting\n+// them as a snapshot when the stream includes the initial state, and then reads a lab again\n+// whenever its Topology, Nodes or pods change. Changes that arrive together are read once.\n+func (r *Runtime) trackContainers(\n+\tctx context.Context,\n+\tscope eventScope,\n+\tincludeInitialState bool,\n+\tchanged <-chan labRef,\n+\teventSink chan<- clablabruntime.Event,\n+\terrSink chan<- error,\n+) {\n+\ttracker := &containerTracker{r: r, sink: eventSink, nodes: map[string]*trackedContainer{}}\n+\n+\tstates, err := r.labStates(ctx, scope)\n+\tif err != nil {\n+\t\tsendEventError(ctx, errSink, err)\n+\t\treturn\n+\t}\n+\tfor _, state := range states {\n+\t\ttracker.observeLab(ctx, labRef{namespace: state.Namespace, lab: state.Name}, state,\n+\t\t\t&observeSeed{snapshot: includeInitialState})\n+\t}\n+\n+\tpending := map[labRef]bool{}\n+\ttimer := time.NewTimer(time.Hour)\n+\ttimer.Stop()\n+\tdefer timer.Stop()\n+\tarmed := false\n+\tarm := func(delay time.Duration) {\n+\t\tif !armed {\n+\t\t\ttimer.Reset(delay)\n+\t\t\tarmed = true\n+\t\t}\n+\t}\n+\n+\tfor {\n+\t\tselect {\n+\t\tcase <-ctx.Done():\n+\t\t\treturn\n+\t\tcase ref := <-changed:\n+\t\t\tpending[ref] = true\n+\t\t\tarm(containerRefreshDelay)\n+\t\tcase <-timer.C:\n+\t\t\tarmed = false\n+\t\t\trefs := pending\n+\t\t\tpending = map[labRef]bool{}\n+\t\t\tfor ref := range refs {\n+\t\t\t\tif !tracker.refresh(ctx, ref) {\n+\t\t\t\t\tpending[ref] = true\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tif len(pending) != 0 {\n+\t\t\t\tarm(containerRefreshRetryDelay)\n+\t\t\t}\n+\t\t}\n+\t}\n+}\n+\n+// observeSeed marks the first observation of a stream: it records the node states without\n+// reporting changes, and reports them as a snapshot when asked to.\n+type observeSeed struct {\n+\tsnapshot bool\n+}\n+\n+// refresh reads a lab again and reports what changed for its nodes. A lab that is gone reports\n+// its nodes as destroyed. It returns false when the lab could not be read.\n+func (t *containerTracker) refresh(ctx context.Context, ref labRef) bool {\n+\tstate, err := t.r.Inspect(ctx, clablabruntime.InspectRequest{\n+\t\tName:      ref.lab,\n+\t\tNamespace: ref.namespace,\n+\t})\n+\tif err != nil {\n+\t\tvar notFound *labNotFoundError\n+\t\tif !errors.As(err, &notFound) {\n+\t\t\tif ctx.Err() == nil {\n+\t\t\t\tlog.Debug(\"Failed to read a C9s lab for container events\",\n+\t\t\t\t\t\"namespace\", ref.namespace, \"lab\", ref.lab, \"error\", err)\n+\t\t\t}\n+\n+\t\t\treturn ctx.Err() != nil\n+\t\t}\n+\t\tstate = nil\n+\t}\n+\n+\tt.observeLab(ctx, ref, state, nil)\n+\n+\treturn true\n+}\n+\n+// observeLab compares the nodes of a lab with what was reported before and reports the\n+// difference. A nil state removes every node of the lab.\n+func (t *containerTracker) observeLab(\n+\tctx context.Context,\n+\tref labRef,\n+\tstate *clablabruntime.LabState,\n+\tseed *observeSeed,\n+) {\n+\tseen := map[string]bool{}\n+\tif state != nil {\n+\t\tfor idx := range state.Nodes {\n+\t\t\tkey := c9sNodeKey(state.Namespace, state.Name, state.Nodes[idx].Name)\n+\t\t\tseen[key] = true\n+\t\t\tt.observeNode(ctx, ref, state, state.Nodes[idx], seed)\n+\t\t}\n+\t}\n+\n+\tfor key, tracked := range t.nodes {\n+\t\tif tracked.ref != ref || seen[key] {\n+\t\t\tcontinue\n+\t\t}\n+\n+\t\tfor _, action := range containerRemovalActions(tracked) {\n+\t\t\tt.emit(ctx, tracked.lab, tracked.node, action, nil)\n+\t\t}\n+\t\tdelete(t.nodes, key)\n+\t}\n+}\n+\n+func (t *containerTracker) observeNode(\n+\tctx context.Context,\n+\tref labRef,\n+\tstate *clablabruntime.LabState,\n+\tnode clablabruntime.NodeState,\n+\tseed *observeSeed,\n+) {\n+\tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n+\tprevious := t.nodes[key]\n+\tif node.ContainerState == \"\" {\n+\t\tnode.ContainerState = clablabruntime.ContainerStateCreated\n+\t}\n+\tnext := &trackedContainer{\n+\t\tref:   ref,\n+\t\tstate: node.ContainerState,\n+\t\tpod:   node.Pod,\n+\t\tlab:   state,\n+\t\tnode:  node,\n+\t}\n+\tnext.health = containerHealth(previous, next, node.Health)\n+\tt.nodes[key] = next\n+\n+\tif seed != nil {\n+\t\tif seed.snapshot {\n+\t\t\tt.emit(ctx, state, node, next.state, map[string]string{\n+\t\t\t\t\"origin\": clablabruntime.EventOriginSnapshot,\n+\t\t\t})\n+\t\t}\n+\n+\t\treturn\n+\t}\n+\n+\tfor _, action := range containerTransitionActions(previous, next) {\n+\t\tt.emit(ctx, state, node, action, nil)\n+\t}\n+}\n+\n+// containerHealth is the health a running node reports: a node that was healthy and is not\n+// ready anymore in the same pod is unhealthy, as a container whose healthcheck starts failing.\n+func containerHealth(previous, next *trackedContainer, health string) string {\n+\tif next.state != clablabruntime.ContainerStateRunning {\n+\t\treturn \"\"\n+\t}\n+\tif health == \"\" {\n+\t\thealth = clablabruntime.ContainerHealthStarting\n+\t}\n+\tif health == clablabruntime.ContainerHealthStarting && previous != nil &&\n+\t\tprevious.state == clablabruntime.ContainerStateRunning && previous.pod == next.pod &&\n+\t\t(previous.health == clablabruntime.ContainerHealthHealthy ||\n+\t\t\tprevious.health == clablabruntime.ContainerHealthUnhealthy) {\n+\t\treturn clablabruntime.ContainerHealthUnhealthy\n+\t}\n+\n+\treturn health\n+}\n+\n+// containerTransitionActions are the container event actions Docker reports when a container\n+// goes from the previous to the next state:\n+//\n+//\tnew node            create (+ start when it runs, + stop when it is already stopped)\n+//\tcreated -> running  start\n+//\texited  -> running  start\n+//\trunning -> exited   kill, stop, die (stop, or the old pod of a restart ending)\n+//\trunning -> created  kill, stop, die (the replacement pod of a restart not running yet)\n+//\trunning, new pod    kill, stop, die, start (restart)\n+//\tcreated -> exited   stop\n+//\n+// A started node also reports its health (health_status: starting or healthy), and a running\n+// node reports health changes, like a container with a healthcheck.\n+func containerTransitionActions(previous, next *trackedContainer) []string {\n+\tconst (\n+\t\tcreated = clablabruntime.ContainerStateCreated\n+\t\trunning = clablabruntime.ContainerStateRunning\n+\t\texited  = clablabruntime.ContainerStateExited\n+\t)\n+\n+\tvar actions []string\n+\tpreviousState := \"\"\n+\tif previous != nil {\n+\t\tpreviousState = previous.state\n+\t}\n+\n+\tswitch {\n+\tcase previous == nil:\n+\t\tactions = append(actions, containerActionCreate)\n+\t\tswitch next.state {\n+\t\tcase running:\n+\t\t\tactions = append(actions, containerActionStart)\n+\t\tcase exited:\n+\t\t\tactions = append(actions, containerActionStop)\n+\t\t}\n+\tcase previousState == running && next.state == running && previous.pod != next.pod:\n+\t\tactions = append(actions, containerActionKill, containerActionStop, containerActionDie,\n+\t\t\tcontainerActionStart)\n+\tcase previousState == running && next.state != running:\n+\t\tactions = append(actions, containerActionKill, containerActionStop, containerActionDie)\n+\tcase previousState != running && next.state == running:\n+\t\tactions = append(actions, containerActionStart)\n+\tcase previousState == created && next.state == exited:\n+\t\tactions = append(actions, containerActionStop)\n+\t}\n+\n+\tif next.state != running {\n+\t\treturn actions\n+\t}\n+\n+\tstarted := len(actions) != 0 && actions[len(actions)-1] == containerActionStart\n+\tif !started && previous != nil && previous.health == next.health {\n+\t\treturn actions\n+\t}\n+\tif next.health == clablabruntime.ContainerHealthStarting && !started {\n+\t\treturn actions\n+\t}\n+\n+\treturn append(actions, containerActionHealthPrefix+next.health)\n+}\n+\n+// containerRemovalActions are the actions Docker reports when a container is removed: a running\n+// one is killed and dies first.\n+func containerRemovalActions(previous *trackedContainer) []string {\n+\tif previous.state == clablabruntime.ContainerStateRunning {\n+\t\treturn []string{containerActionKill, containerActionDie, containerActionDestroy}\n+\t}\n+\n+\treturn []string{containerActionDestroy}\n+}\n+\n+// containerActionState is the container state after an action, which every container event\n+// reports in its state attribute.\n+func containerActionState(action, snapshotState string) string {\n+\tswitch action {\n+\tcase containerActionCreate:\n+\t\treturn clablabruntime.ContainerStateCreated\n+\tcase containerActionStop, containerActionDie, containerActionDestroy:\n+\t\treturn clablabruntime.ContainerStateExited\n+\tcase containerActionStart, containerActionKill:\n+\t\treturn clablabruntime.ContainerStateRunning\n+\t}\n+\tif strings.HasPrefix(action, containerActionHealthPrefix) {\n+\t\treturn clablabruntime.ContainerStateRunning\n+\t}\n+\n+\treturn snapshotState\n+}\n+\n+func (t *containerTracker) emit(\n+\tctx context.Context,\n+\tstate *clablabruntime.LabState,\n+\tnode clablabruntime.NodeState,\n+\taction string,\n+\textra map[string]string,\n+) {\n+\tt.r.sendEvent(ctx, t.sink, c9sContainerEvent(state, node, action, extra))\n+}\n+\n+// c9sContainerEvent is a container event of a node. The actor is the node, as for its interface\n+// events; its ID is the container_id inspect reports. Lab and Node let the events command\n+// describe the node with the attributes inspect and the Docker runtime report.\n+func c9sContainerEvent(\n+\tstate *clablabruntime.LabState,\n+\tnode clablabruntime.NodeState,\n+\taction string,\n+\textra map[string]string,\n+) clablabruntime.Event {\n+\tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n+\tattributes := map[string]string{\n+\t\t\"namespace\":                  state.Namespace,\n+\t\t\"lab\":                        state.Name,\n+\t\t\"node\":                       node.Name,\n+\t\tcontainerEventAttributeState: containerActionState(action, node.ContainerState),\n+\t}\n+\tif node.Pod != \"\" {\n+\t\tattributes[\"pod\"] = node.Pod\n+\t}\n+\tif action == containerActionKill {\n+\t\t// Kubernetes stops a pod's containers with SIGTERM.\n+\t\tattributes[\"signal\"] = containerEventSignalSIGTERM\n+\t}\n+\tfor k, v := range extra {\n+\t\tattributes[k] = v\n+\t}\n+\n+\tnodeCopy := node\n+\n+\treturn clablabruntime.Event{\n+\t\tTimestamp:   time.Now(),\n+\t\tType:        clablabruntime.EventTypeContainer,\n+\t\tAction:      action,\n+\t\tActorID:     key,\n+\t\tActorName:   fmt.Sprintf(\"%s-%s\", state.Name, node.Name),\n+\t\tActorFullID: key,\n+\t\tAttributes:  attributes,\n+\t\tLab:         state,\n+\t\tNode:        &nodeCopy,\n+\t}\n+}\ndiff --git a/labruntime/clabernetes/event_parity_test.go b/labruntime/clabernetes/event_parity_test.go\nnew file mode 100644\nindex 0000000..faddcfe\n--- /dev/null\n+++ b/labruntime/clabernetes/event_parity_test.go\n@@ -0,0 +1,1008 @@\n+package clabernetes\n+\n+import (\n+\t\"context\"\n+\t\"encoding/json\"\n+\t\"io\"\n+\t\"slices\"\n+\t\"strings\"\n+\t\"sync\"\n+\t\"testing\"\n+\t\"time\"\n+\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+// podInterfaces is the sysfs view of a c9s pod: the device's interfaces and clabernetes' own.\n+func podInterfaces(link string, linkState string) []c9sIfaceState {\n+\treturn []c9sIfaceState{\n+\t\t{Name: \"lo\", Index: 1, MTU: 65536, MAC: zeroMAC, OperState: \"unknown\"},\n+\t\t{Name: \"c9s0\", Index: 2, MTU: 1500, MAC: \"6e:43:ce:6b:3f:dc\", OperState: \"up\"},\n+\t\t{\n+\t\t\tName: \"c9sr0\", Index: 3, MTU: 1450, MAC: \"02:c9:20:eb:f4:ff\", OperState: \"up\",\n+\t\t\tAlias: \"c9s:interposition:v1\",\n+\t\t},\n+\t\t{\n+\t\t\tName: \"eth0\", Index: 4, MTU: 1450, MAC: \"3a:3b:86:d8:73:37\", OperState: \"up\",\n+\t\t\tAlias: \"c9s:interposition:v1\",\n+\t\t},\n+\t\t{\n+\t\t\tName: \"c9sm0\", Index: 5, MTU: 1450, MAC: \"06:c9:ac:14:14:54\", OperState: \"unknown\",\n+\t\t\tAlias: \"c9s:interposition:v1\",\n+\t\t},\n+\t\t{\n+\t\t\tName: \"c9ss73388031\", Index: 6, MTU: 9500, MAC: \"3e:9c:45:56:67:2f\", OperState: \"up\",\n+\t\t\tAlias: \"c9s:direct:v1:e332:transport:98d2\",\n+\t\t},\n+\t\t{\n+\t\t\tName: link, Index: 7, MTU: 9500, MAC: \"fe:0b:87:7a:1d:5a\", OperState: linkState,\n+\t\t\tAlias: \"c9s:direct:v1:e332:transport:98d2\",\n+\t\t},\n+\t}\n+}\n+\n+func interfaceTestSample(\n+\tnode string,\n+\tts time.Time,\n+\tlinks []clabwireInterface,\n+\tifaces []c9sIfaceState,\n+) interfaceSample {\n+\tstats := make([]c9sIfaceStats, 0, len(ifaces))\n+\tfor _, iface := range ifaces {\n+\t\tstats = append(stats, c9sIfaceStats{Name: iface.Name, RxBytes: uint64(ts.Unix())})\n+\t}\n+\n+\treturn interfaceSample{\n+\t\ttarget: interfaceSampleTarget{\n+\t\t\tstate: &clablabruntime.LabState{Name: \"lab1\", Namespace: \"c9s-lab1\"},\n+\t\t\tnode: clablabruntime.NodeState{\n+\t\t\t\tName: node, Pod: \"lab1-\" + node + \"-abc\",\n+\t\t\t\tContainerState: clablabruntime.ContainerStateRunning,\n+\t\t\t},\n+\t\t\tpod: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"lab1-\" + node + \"-abc\"}},\n+\t\t},\n+\t\tstats:     stats,\n+\t\tifaces:    ifaces,\n+\t\thasStates: true,\n+\t\tlinks:     links,\n+\t\ttimestamp: ts,\n+\t}\n+}\n+\n+func interfacesByName(events []clablabruntime.Event) map[string]clablabruntime.Event {\n+\tbyName := map[string]clablabruntime.Event{}\n+\tfor _, ev := range events {\n+\t\tbyName[ev.Interface.Name] = ev\n+\t}\n+\n+\treturn byName\n+}\n+\n+func TestNetlinkOperState(t *testing.T) {\n+\tt.Parallel()\n+\n+\tfor sysfs, want := range map[string]string{\n+\t\t\"up\":             \"up\",\n+\t\t\"down\":           \"down\",\n+\t\t\"unknown\":        \"unknown\",\n+\t\t\"dormant\":        \"dormant\",\n+\t\t\"testing\":        \"testing\",\n+\t\t\"notpresent\":     \"not-present\",\n+\t\t\"lowerlayerdown\": \"lower-layer-down\",\n+\t\t\"\":               \"unknown\",\n+\t} {\n+\t\tif got := netlinkOperState(sysfs); got != want {\n+\t\t\tt.Fatalf(\"netlinkOperState(%q) = %q, want %q\", sysfs, got, want)\n+\t\t}\n+\t}\n+}\n+\n+// TestInterfaceEventDataNamesInterfacesLikeDocker checks the names, aliases, types and states a\n+// Docker container of the same node kind reports: linux eth1 without an alias, SR Linux e1-1\n+// with the topology's ethernet-1/1, eth0 and loopback, and no clabernetes alias.\n+func TestInterfaceEventDataNamesInterfacesLikeDocker(t *testing.T) {\n+\tt.Parallel()\n+\n+\tifaces := map[string]c9sIfaceState{}\n+\tfor _, iface := range podInterfaces(\"e1-1\", \"lowerlayerdown\") {\n+\t\tifaces[iface.Name] = iface\n+\t}\n+\tifaces[\"eth1\"] = c9sIfaceState{\n+\t\tName: \"eth1\", Index: 8, MTU: 9500, OperState: \"up\", Alias: \"c9s:direct:v1:x\",\n+\t}\n+\n+\ttests := []struct {\n+\t\tiface, alias string\n+\t\twant         clablabruntime.InterfaceEventData\n+\t}{\n+\t\t{\"eth1\", \"\", clablabruntime.InterfaceEventData{\n+\t\t\tName: \"eth1\", Index: 8, MTU: 9500, OperState: \"up\", Type: \"veth\",\n+\t\t}},\n+\t\t{\"e1-1\", \"ethernet-1/1\", clablabruntime.InterfaceEventData{\n+\t\t\tName: \"e1-1\", Alias: \"ethernet-1/1\", Index: 7, MTU: 9500, MAC: \"fe:0b:87:7a:1d:5a\",\n+\t\t\tOperState: \"lower-layer-down\", Type: \"veth\",\n+\t\t}},\n+\t\t{\"eth0\", \"\", clablabruntime.InterfaceEventData{\n+\t\t\tName: \"eth0\", Index: 4, MTU: 1450, MAC: \"3a:3b:86:d8:73:37\", OperState: \"up\",\n+\t\t\tType: \"veth\",\n+\t\t}},\n+\t\t{\"lo\", \"\", clablabruntime.InterfaceEventData{\n+\t\t\tName: \"lo\", Index: 1, MTU: 65536, OperState: \"unknown\", Type: \"device\",\n+\t\t}},\n+\t}\n+\tfor _, tt := range tests {\n+\t\tif got := interfaceEventData(ifaces[tt.iface], tt.alias); got != tt.want {\n+\t\t\tt.Fatalf(\"%s = %+v, want %+v\", tt.iface, got, tt.want)\n+\t\t}\n+\t}\n+\n+\t// an alias set inside the node is the interface's alias, as netlink reports it\n+\tgot := interfaceEventData(c9sIfaceState{Name: \"eth2\", Alias: \"uplink\"}, \"\")\n+\tif got.Alias != \"uplink\" {\n+\t\tt.Fatalf(\"own alias = %+v\", got)\n+\t}\n+}\n+\n+// TestInterfacePollerReportsTheTopologyInterfaces runs a linux and an SR Linux node through the\n+// poller: only the lab link interfaces (named and aliased as clabwire lists them), eth0 and lo\n+// are reported, with the actions of the netlink events.\n+func TestInterfacePollerReportsTheTopologyInterfaces(t *testing.T) {\n+\tt.Parallel()\n+\n+\ttests := []struct {\n+\t\tname  string\n+\t\tlink  string\n+\t\talias string\n+\t}{\n+\t\t{name: \"linux\", link: \"eth1\"},\n+\t\t{name: \"srl\", link: \"e1-1\", alias: \"ethernet-1/1\"},\n+\t}\n+\tfor _, tt := range tests {\n+\t\tt.Run(tt.name, func(t *testing.T) {\n+\t\t\tt.Parallel()\n+\n+\t\t\tlinks := []clabwireInterface{{\n+\t\t\t\tNode: \"r1\", Interface: tt.link, Alias: tt.alias,\n+\t\t\t\tPeerNode: \"r2\", PeerInterface: tt.link,\n+\t\t\t}}\n+\t\t\tsink := make(chan clablabruntime.Event, 64)\n+\t\t\tp := newInterfacePoller(&Runtime{}, eventScope{},\n+\t\t\t\tinterfacePollOptions{includeInitialState: true}, sink)\n+\t\t\tctx := context.Background()\n+\t\t\tstart := time.Now()\n+\n+\t\t\tp.processSample(\n+\t\t\t\tctx,\n+\t\t\t\tinterfaceTestSample(\"r1\", start, links, podInterfaces(tt.link, \"up\")),\n+\t\t\t)\n+\t\t\tgot := interfacesByName(drain(sink))\n+\t\t\tif len(got) != 3 {\n+\t\t\t\tt.Fatalf(\"first round reported %v, want %s, eth0 and lo\", got, tt.link)\n+\t\t\t}\n+\t\t\tlink := got[tt.link]\n+\t\t\tif link.Action != interfaceActionSnapshot ||\n+\t\t\t\tlink.Type != clablabruntime.EventTypeInterface ||\n+\t\t\t\tlink.ActorID != \"c9s-lab1/lab1/r1\" ||\n+\t\t\t\tlink.ActorFullID != \"c9s-lab1/lab1/r1\" ||\n+\t\t\t\tlink.ActorName != \"lab1-r1\" || link.Interface.Alias != tt.alias ||\n+\t\t\t\tlink.Interface.OperState != \"up\" || link.Interface.Type != \"veth\" ||\n+\t\t\t\tlink.Lab == nil || link.Node == nil || link.Node.Name != \"r1\" ||\n+\t\t\t\tlink.Attributes[\"origin\"] != \"clabernetes\" ||\n+\t\t\t\tlink.Attributes[\"pod\"] != \"lab1-r1-abc\" ||\n+\t\t\t\tlink.Attributes[\"namespace\"] != \"c9s-lab1\" {\n+\t\t\t\tt.Fatalf(\"%s event = %+v\", tt.link, link)\n+\t\t\t}\n+\t\t\tif got[\"lo\"].Interface.Type != \"device\" || got[\"eth0\"].Interface.Alias != \"\" {\n+\t\t\t\tt.Fatalf(\"eth0/lo = %+v %+v\", got[\"eth0\"].Interface, got[\"lo\"].Interface)\n+\t\t\t}\n+\n+\t\t\t// unchanged: nothing\n+\t\t\tp.firstRound = false\n+\t\t\tp.processSample(ctx, interfaceTestSample(\"r1\", start.Add(time.Second), links,\n+\t\t\t\tpodInterfaces(tt.link, \"up\")))\n+\t\t\tif events := drain(sink); len(events) != 0 {\n+\t\t\t\tt.Fatalf(\"unchanged interfaces reported %+v\", events)\n+\t\t\t}\n+\n+\t\t\t// the peer goes away: the link loses its carrier\n+\t\t\tp.processSample(ctx, interfaceTestSample(\"r1\", start.Add(2*time.Second), links,\n+\t\t\t\tpodInterfaces(tt.link, \"lowerlayerdown\")))\n+\t\t\tevents := drain(sink)\n+\t\t\tif len(events) != 1 || events[0].Action != interfaceActionUpdate ||\n+\t\t\t\tevents[0].Interface.Name != tt.link ||\n+\t\t\t\tevents[0].Interface.OperState != \"lower-layer-down\" {\n+\t\t\t\tt.Fatalf(\"carrier loss reported %+v\", events)\n+\t\t\t}\n+\n+\t\t\t// the link interface disappears, then comes back\n+\t\t\twithoutLink := podInterfaces(tt.link, \"up\")\n+\t\t\twithoutLink = withoutLink[:len(withoutLink)-1]\n+\t\t\tp.processSample(\n+\t\t\t\tctx,\n+\t\t\t\tinterfaceTestSample(\"r1\", start.Add(3*time.Second), links, withoutLink),\n+\t\t\t)\n+\t\t\tevents = drain(sink)\n+\t\t\tif len(events) != 1 || events[0].Action != interfaceActionDelete ||\n+\t\t\t\tevents[0].Interface.Name != tt.link {\n+\t\t\t\tt.Fatalf(\"removed link reported %+v\", events)\n+\t\t\t}\n+\t\t\tp.processSample(ctx, interfaceTestSample(\"r1\", start.Add(4*time.Second), links,\n+\t\t\t\tpodInterfaces(tt.link, \"up\")))\n+\t\t\tevents = drain(sink)\n+\t\t\tif len(events) != 1 || events[0].Action != interfaceActionCreate ||\n+\t\t\t\tevents[0].Interface.Alias != tt.alias {\n+\t\t\t\tt.Fatalf(\"new link reported %+v\", events)\n+\t\t\t}\n+\n+\t\t\t// the node stops: its interfaces are deleted\n+\t\t\tp.retireStoppedNodes(ctx, map[string]bool{})\n+\t\t\tgot = interfacesByName(drain(sink))\n+\t\t\tif len(got) != 3 || got[tt.link].Action != interfaceActionDelete ||\n+\t\t\t\tgot[\"eth0\"].Action != interfaceActionDelete || len(p.nodes) != 0 {\n+\t\t\t\tt.Fatalf(\"stopped node reported %+v\", got)\n+\t\t\t}\n+\t\t})\n+\t}\n+}\n+\n+func TestInterfacePollerFirstRoundWithoutInitialState(t *testing.T) {\n+\tt.Parallel()\n+\n+\tsink := make(chan clablabruntime.Event, 16)\n+\tp := newInterfacePoller(&Runtime{}, eventScope{}, interfacePollOptions{}, sink)\n+\tlinks := []clabwireInterface{{Node: \"r1\", Interface: \"eth1\"}}\n+\tp.processSample(context.Background(),\n+\t\tinterfaceTestSample(\"r1\", time.Now(), links, podInterfaces(\"eth1\", \"up\")))\n+\tif events := drain(sink); len(events) != 0 {\n+\t\tt.Fatalf(\"first round without --initial-state reported %+v\", events)\n+\t}\n+}\n+\n+func TestInterfacePollerStatsCoverTheReportedInterfaces(t *testing.T) {\n+\tt.Parallel()\n+\n+\tsink := make(chan clablabruntime.Event, 32)\n+\tp := newInterfacePoller(\n+\t\t&Runtime{},\n+\t\teventScope{},\n+\t\tinterfacePollOptions{includeStats: true},\n+\t\tsink,\n+\t)\n+\tlinks := []clabwireInterface{{Node: \"r1\", Interface: \"e1-1\", Alias: \"ethernet-1/1\"}}\n+\tstart := time.Now()\n+\tfirst := interfaceTestSample(\"r1\", start, links, podInterfaces(\"e1-1\", \"up\"))\n+\tsecond := interfaceTestSample(\"r1\", start.Add(time.Second), links, podInterfaces(\"e1-1\", \"up\"))\n+\tfor idx := range second.stats {\n+\t\tsecond.stats[idx].RxBytes = first.stats[idx].RxBytes + 1000\n+\t}\n+\n+\tp.processSample(context.Background(), first)\n+\t_ = drain(sink)\n+\tp.processSample(context.Background(), second)\n+\tgot := interfacesByName(drain(sink))\n+\tif len(got) != 3 {\n+\t\tt.Fatalf(\"stats reported for %v, want e1-1, eth0 and lo\", got)\n+\t}\n+\tstats := got[\"e1-1\"]\n+\tif stats.Action != interfaceActionStats || stats.Interface.Alias != \"ethernet-1/1\" ||\n+\t\tstats.Interface.Index != 7 || stats.Interface.OperState != \"up\" ||\n+\t\tstats.Interface.Stats == nil || stats.Interface.Stats.RxBps != 8000 ||\n+\t\tstats.Interface.Stats.Interval != time.Second {\n+\t\tt.Fatalf(\"e1-1 stats = %+v %+v\", stats, stats.Interface)\n+\t}\n+}\n+\n+// listingExec answers clabwire --list-interfaces with the listing of the pod and counts the\n+// listings.\n+type listingExec struct {\n+\tmu       sync.Mutex\n+\tlistings map[string][]clabwireInterface\n+\tcalls    int\n+}\n+\n+func (l *listingExec) exec(\n+\t_ context.Context,\n+\t_, pod, container string,\n+\tcommand []string,\n+\t_ io.Reader,\n+\tstdout, _ io.Writer,\n+) error {\n+\tl.mu.Lock()\n+\tdefer l.mu.Unlock()\n+\n+\tif container != clabwireContainer || !slices.Contains(command, \"--list-interfaces\") {\n+\t\treturn nil\n+\t}\n+\tl.calls++\n+\n+\treturn json.NewEncoder(stdout).Encode(l.listings[pod])\n+}\n+\n+func TestInterfacePollerListsAPodOncePerInterfaceSet(t *testing.T) {\n+\tt.Parallel()\n+\n+\tlisting := &listingExec{listings: map[string][]clabwireInterface{\n+\t\t\"lab1-r1-abc\": {\n+\t\t\t{Node: \"r1\", Interface: \"e1-1\", Alias: \"ethernet-1/1\"},\n+\t\t\t{Node: \"r1b\", Interface: \"e1-2\"},\n+\t\t},\n+\t}}\n+\tr := &Runtime{podExec: listing.exec}\n+\tp := newInterfacePoller(\n+\t\tr,\n+\t\teventScope{},\n+\t\tinterfacePollOptions{},\n+\t\tmake(chan clablabruntime.Event),\n+\t)\n+\ttarget := interfaceTestSample(\"r1\", time.Now(), nil, nil).target\n+\n+\tfor range 3 {\n+\t\tlinks, err := p.nodeLinks(context.Background(), target, \"e1-1,eth0,lo\")\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\tif len(links) != 1 || links[0].Alias != \"ethernet-1/1\" {\n+\t\t\tt.Fatalf(\"links = %+v, want the node's own link\", links)\n+\t\t}\n+\t}\n+\tif listing.calls != 1 {\n+\t\tt.Fatalf(\"listed %d times, want once while the interfaces stay the same\", listing.calls)\n+\t}\n+\n+\tif _, err := p.nodeLinks(context.Background(), target, \"e1-1,e1-2,eth0,lo\"); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif listing.calls != 2 {\n+\t\tt.Fatalf(\"listed %d times, want again after the interfaces changed\", listing.calls)\n+\t}\n+\n+\tp.forgetListings(map[string]bool{})\n+\tif len(p.listings) != 0 {\n+\t\tt.Fatalf(\"listings of gone pods kept: %+v\", p.listings)\n+\t}\n+}\n+\n+func TestContainerTransitionActions(t *testing.T) {\n+\tt.Parallel()\n+\n+\tconst (\n+\t\tcreated = clablabruntime.ContainerStateCreated\n+\t\trunning = clablabruntime.ContainerStateRunning\n+\t\texited  = clablabruntime.ContainerStateExited\n+\t\thealthy = clablabruntime.ContainerHealthHealthy\n+\t\tstart   = clablabruntime.ContainerHealthStarting\n+\t\tsick    = clablabruntime.ContainerHealthUnhealthy\n+\t)\n+\ttracked := func(state, health, pod string) *trackedContainer {\n+\t\treturn &trackedContainer{state: state, health: health, pod: pod}\n+\t}\n+\n+\ttests := []struct {\n+\t\tname     string\n+\t\tprevious *trackedContainer\n+\t\tnext     *trackedContainer\n+\t\twant     string\n+\t}{\n+\t\t{\"new pending node\", nil, tracked(created, \"\", \"\"), \"create\"},\n+\t\t{\n+\t\t\t\"new running node\", nil, tracked(running, start, \"p1\"),\n+\t\t\t\"create,start,health_status: starting\",\n+\t\t},\n+\t\t{\n+\t\t\t\"new ready node\", nil, tracked(running, healthy, \"p1\"),\n+\t\t\t\"create,start,health_status: healthy\",\n+\t\t},\n+\t\t{\"new stopped node\", nil, tracked(exited, \"\", \"\"), \"create,stop\"},\n+\t\t{\n+\t\t\t\"pod starts\", tracked(created, \"\", \"p1\"), tracked(running, start, \"p1\"),\n+\t\t\t\"start,health_status: starting\",\n+\t\t},\n+\t\t{\n+\t\t\t\"device ready\", tracked(running, start, \"p1\"), tracked(running, healthy, \"p1\"),\n+\t\t\t\"health_status: healthy\",\n+\t\t},\n+\t\t{\"still booting\", tracked(running, start, \"p1\"), tracked(running, start, \"p1\"), \"\"},\n+\t\t{\"no change\", tracked(running, healthy, \"p1\"), tracked(running, healthy, \"p1\"), \"\"},\n+\t\t{\n+\t\t\t\"device not ready again\", tracked(running, healthy, \"p1\"), tracked(running, sick, \"p1\"),\n+\t\t\t\"health_status: unhealthy\",\n+\t\t},\n+\t\t{\"stop\", tracked(running, healthy, \"p1\"), tracked(exited, \"\", \"\"), \"kill,stop,die\"},\n+\t\t{\n+\t\t\t\"start\", tracked(exited, \"\", \"\"), tracked(running, healthy, \"p2\"),\n+\t\t\t\"start,health_status: healthy\",\n+\t\t},\n+\t\t{\n+\t\t\t\"restart, new pod pending\", tracked(running, healthy, \"p1\"), tracked(created, \"\", \"p2\"),\n+\t\t\t\"kill,stop,die\",\n+\t\t},\n+\t\t{\n+\t\t\t\"restart, new pod running\", tracked(running, healthy, \"p1\"),\n+\t\t\ttracked(running, start, \"p2\"), \"kill,stop,die,start,health_status: starting\",\n+\t\t},\n+\t\t{\"stopped before it ran\", tracked(created, \"\", \"p1\"), tracked(exited, \"\", \"\"), \"stop\"},\n+\t\t{\"stopped node rescheduled\", tracked(exited, \"\", \"\"), tracked(created, \"\", \"p2\"), \"\"},\n+\t}\n+\tfor _, tt := range tests {\n+\t\tgot := strings.Join(containerTransitionActions(tt.previous, tt.next), \",\")\n+\t\tif got != tt.want {\n+\t\t\tt.Fatalf(\"%s: actions = %q, want %q\", tt.name, got, tt.want)\n+\t\t}\n+\t}\n+\n+\tif got := strings.Join(containerRemovalActions(tracked(running, healthy, \"p1\")), \",\"); got !=\n+\t\t\"kill,die,destroy\" {\n+\t\tt.Fatalf(\"removal of a running node = %q\", got)\n+\t}\n+\tif got := strings.Join(\n+\t\tcontainerRemovalActions(tracked(exited, \"\", \"\")),\n+\t\t\",\",\n+\t); got != \"destroy\" {\n+\t\tt.Fatalf(\"removal of a stopped node = %q\", got)\n+\t}\n+\n+\t// health: a running node that was healthy and is not ready anymore in the same pod is\n+\t// unhealthy; in a new pod it starts again\n+\tprevious := tracked(running, healthy, \"p1\")\n+\tif got := containerHealth(previous, tracked(running, \"\", \"p1\"), start); got != sick {\n+\t\tt.Fatalf(\"health in the same pod = %q\", got)\n+\t}\n+\tif got := containerHealth(previous, tracked(running, \"\", \"p2\"), start); got != start {\n+\t\tt.Fatalf(\"health in a new pod = %q\", got)\n+\t}\n+}\n+\n+// trackerTestNode is a Node of lab1 in lab-ns.\n+func trackerTestNode(\n+\tname string,\n+\trunState string,\n+\tconditions ...map[string]any,\n+) *unstructured.Unstructured {\n+\tstatus := map[string]any{\n+\t\t\"readiness\":        \"notready\",\n+\t\t\"directContainers\": []any{map[string]any{\"name\": \"node-\" + name, \"id\": name}},\n+\t}\n+\trawConditions := []any{}\n+\tfor _, condition := range conditions {\n+\t\trawConditions = append(rawConditions, condition)\n+\t\tif condition[\"type\"] == \"Ready\" && condition[\"status\"] == \"True\" {\n+\t\t\tstatus[\"readiness\"] = \"ready\"\n+\t\t}\n+\t}\n+\tstatus[\"conditions\"] = rawConditions\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,\n+\t\t\t\"labels\": map[string]any{\n+\t\t\t\tlabelTopologyOwner: \"lab1\", labelOriginalNodeName: strings.ToUpper(name),\n+\t\t\t},\n+\t\t},\n+\t\t\"spec\":   map[string]any{\"kind\": \"linux\", \"image\": \"alpine\", \"runState\": runState},\n+\t\t\"status\": status,\n+\t}}\n+}\n+\n+func condition(conditionType, status string) map[string]any {\n+\treturn map[string]any{\"type\": conditionType, \"status\": status}\n+}\n+\n+func trackerTestPod(name string, phase corev1.PodPhase) *corev1.Pod {\n+\tpod := captureTestPod(name, \"r1\")\n+\tpod.Status.Phase = phase\n+\n+\treturn pod\n+}\n+\n+type trackerHarness struct {\n+\tt       *testing.T\n+\tr       *Runtime\n+\ttracker *containerTracker\n+\tsink    chan clablabruntime.Event\n+}\n+\n+func newTrackerHarness(\n+\tt *testing.T,\n+\tnode *unstructured.Unstructured,\n+\tpods ...*corev1.Pod,\n+) *trackerHarness {\n+\tt.Helper()\n+\n+\tkubeObjects := make([]k8sruntime.Object, 0, len(pods))\n+\tfor _, pod := range pods {\n+\t\tkubeObjects = append(kubeObjects, pod)\n+\t}\n+\tr := newTestRuntimeWithKubeObjects([]*unstructured.Unstructured{node}, kubeObjects)\n+\tr.labNamespaceOverride = \"lab-ns\"\n+\tsink := make(chan clablabruntime.Event, 64)\n+\n+\treturn &trackerHarness{\n+\t\tt: t, r: r, sink: sink,\n+\t\ttracker: &containerTracker{r: r, sink: sink, nodes: map[string]*trackedContainer{}},\n+\t}\n+}\n+\n+func (h *trackerHarness) seed(snapshot bool) {\n+\th.t.Helper()\n+\n+\tstate, err := h.r.Inspect(context.Background(), clablabruntime.InspectRequest{Name: \"lab1\"})\n+\tif err != nil {\n+\t\th.t.Fatal(err)\n+\t}\n+\th.tracker.observeLab(context.Background(), labRef{namespace: \"lab-ns\", lab: \"lab1\"}, state,\n+\t\t&observeSeed{snapshot: snapshot})\n+}\n+\n+func (h *trackerHarness) setNode(node *unstructured.Unstructured) {\n+\th.t.Helper()\n+\n+\tif _, err := h.r.client.Resource(nodeGVR).Namespace(\"lab-ns\").\n+\t\tUpdate(context.Background(), node, metav1.UpdateOptions{}); err != nil {\n+\t\th.t.Fatal(err)\n+\t}\n+}\n+\n+func (h *trackerHarness) deletePod(name string) {\n+\th.t.Helper()\n+\n+\tif err := h.r.kubeClient.CoreV1().Pods(\"lab-ns\").\n+\t\tDelete(context.Background(), name, metav1.DeleteOptions{}); err != nil {\n+\t\th.t.Fatal(err)\n+\t}\n+}\n+\n+func (h *trackerHarness) addPod(pod *corev1.Pod) {\n+\th.t.Helper()\n+\n+\tif _, err := h.r.kubeClient.CoreV1().Pods(\"lab-ns\").\n+\t\tCreate(context.Background(), pod, metav1.CreateOptions{}); err != nil {\n+\t\th.t.Fatal(err)\n+\t}\n+}\n+\n+// refresh reads lab1 again and returns the reported actions with their state attribute.\n+func (h *trackerHarness) refresh() string {\n+\th.t.Helper()\n+\n+\tif !h.tracker.refresh(context.Background(), labRef{namespace: \"lab-ns\", lab: \"lab1\"}) {\n+\t\th.t.Fatal(\"refresh failed\")\n+\t}\n+\n+\tvar actions []string\n+\tfor _, ev := range drain(h.sink) {\n+\t\tif ev.Type != clablabruntime.EventTypeContainer || ev.ActorID != \"lab-ns/lab1/r1\" ||\n+\t\t\tev.ActorFullID != \"lab-ns/lab1/r1\" || ev.ActorName != \"lab1-r1\" ||\n+\t\t\tev.Lab == nil || ev.Node == nil || ev.Node.TopologyName != \"R1\" ||\n+\t\t\tev.Attributes[\"lab\"] != \"lab1\" || ev.Attributes[\"node\"] != \"r1\" ||\n+\t\t\tev.Attributes[\"namespace\"] != \"lab-ns\" {\n+\t\t\th.t.Fatalf(\"container event = %+v\", ev)\n+\t\t}\n+\t\taction := ev.Action + \"=\" + ev.Attributes[\"state\"]\n+\t\tif signal := ev.Attributes[\"signal\"]; signal != \"\" {\n+\t\t\taction += \"/\" + signal\n+\t\t}\n+\t\tactions = append(actions, action)\n+\t}\n+\n+\treturn strings.Join(actions, \",\")\n+}\n+\n+// TestContainerTrackerReportsTheNodeLifecycle drives one node through boot, readiness, stop,\n+// start, restart and removal on the fake cluster and checks the Docker container events.\n+func TestContainerTrackerReportsTheNodeLifecycle(t *testing.T) {\n+\tt.Parallel()\n+\n+\tnode := trackerTestNode(\"r1\", nodeRunStateRunning)\n+\th := newTrackerHarness(t, node, trackerTestPod(\"lab1-r1-a\", corev1.PodPending))\n+\th.seed(true)\n+\tsnapshot := drain(h.sink)\n+\tif len(snapshot) != 1 || snapshot[0].Action != \"created\" ||\n+\t\tsnapshot[0].Attributes[\"origin\"] != clablabruntime.EventOriginSnapshot ||\n+\t\tsnapshot[0].Attributes[\"state\"] != \"created\" {\n+\t\tt.Fatalf(\"snapshot = %+v\", snapshot)\n+\t}\n+\n+\t// the pod runs, the device boots\n+\th.deletePod(\"lab1-r1-a\")\n+\th.addPod(trackerTestPod(\"lab1-r1-a\", corev1.PodRunning))\n+\tif got := h.refresh(); got != \"start=running,health_status: starting=running\" {\n+\t\tt.Fatalf(\"pod running: %s\", got)\n+\t}\n+\n+\t// the device is ready\n+\th.setNode(trackerTestNode(\"r1\", nodeRunStateRunning,\n+\t\tcondition(\"Ready\", \"True\"), condition(nodeConditionContainersReady, \"True\")))\n+\tif got := h.refresh(); got != \"health_status: healthy=running\" {\n+\t\tt.Fatalf(\"ready: %s\", got)\n+\t}\n+\tif got := h.refresh(); got != \"\" {\n+\t\tt.Fatalf(\"unchanged: %s\", got)\n+\t}\n+\n+\t// stop: the Node is stopped and its pod goes\n+\th.setNode(trackerTestNode(\"r1\", nodeRunStateStopped,\n+\t\tcondition(nodeConditionStopped, \"True\")))\n+\th.deletePod(\"lab1-r1-a\")\n+\tif got := h.refresh(); got != \"kill=running/15,stop=exited,die=exited\" {\n+\t\tt.Fatalf(\"stop: %s\", got)\n+\t}\n+\n+\t// start: a new pod\n+\th.setNode(trackerTestNode(\"r1\", nodeRunStateRunning))\n+\th.addPod(trackerTestPod(\"lab1-r1-b\", corev1.PodPending))\n+\tif got := h.refresh(); got != \"\" {\n+\t\tt.Fatalf(\"start requested: %s\", got)\n+\t}\n+\th.deletePod(\"lab1-r1-b\")\n+\th.addPod(trackerTestPod(\"lab1-r1-b\", corev1.PodRunning))\n+\th.setNode(\n+\t\ttrackerTestNode(\"r1\", nodeRunStateRunning, condition(nodeConditionContainersReady, \"True\")),\n+\t)\n+\tif got := h.refresh(); got != \"start=running,health_status: healthy=running\" {\n+\t\tt.Fatalf(\"started: %s\", got)\n+\t}\n+\n+\t// restart: the pod is replaced\n+\th.deletePod(\"lab1-r1-b\")\n+\th.addPod(trackerTestPod(\"lab1-r1-c\", corev1.PodRunning))\n+\tif got := h.refresh(); got !=\n+\t\t\"kill=running/15,stop=exited,die=exited,start=running,health_status: healthy=running\" {\n+\t\tt.Fatalf(\"restart: %s\", got)\n+\t}\n+\n+\t// destroy\n+\tif err := h.r.client.Resource(nodeGVR).Namespace(\"lab-ns\").\n+\t\tDelete(context.Background(), \"r1\", metav1.DeleteOptions{}); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif got := h.refresh(); got != \"kill=running/15,die=exited,destroy=exited\" {\n+\t\tt.Fatalf(\"destroy: %s\", got)\n+\t}\n+\tif len(h.tracker.nodes) != 0 {\n+\t\tt.Fatalf(\"destroyed node still tracked: %+v\", h.tracker.nodes)\n+\t}\n+}\n+\n+func TestContainerTrackerSeedsWithoutSnapshot(t *testing.T) {\n+\tt.Parallel()\n+\n+\th := newTrackerHarness(t, trackerTestNode(\"r1\", nodeRunStateRunning,\n+\t\tcondition(\"Ready\", \"True\")), trackerTestPod(\"lab1-r1-a\", corev1.PodRunning))\n+\th.seed(false)\n+\tif events := drain(h.sink); len(events) != 0 {\n+\t\tt.Fatalf(\"seed without --initial-state reported %+v\", events)\n+\t}\n+\tif got := h.refresh(); got != \"\" {\n+\t\tt.Fatalf(\"unchanged after seed: %s\", got)\n+\t}\n+}\n+\n+func TestNodeContainerState(t *testing.T) {\n+\tt.Parallel()\n+\n+\tdeleting := metav1.NewTime(time.Now())\n+\tpod := func(phase corev1.PodPhase, deleted bool) *corev1.Pod {\n+\t\tp := &corev1.Pod{Status: corev1.PodStatus{Phase: phase}}\n+\t\tif deleted {\n+\t\t\tp.DeletionTimestamp = &deleting\n+\t\t}\n+\n+\t\treturn p\n+\t}\n+\n+\ttests := []struct {\n+\t\tname          string\n+\t\tstopRequested bool\n+\t\tpod           *corev1.Pod\n+\t\twant          string\n+\t}{\n+\t\t{\"no pod yet\", false, nil, \"created\"},\n+\t\t{\"pod scheduled, init containers\", false, pod(corev1.PodPending, false), \"created\"},\n+\t\t{\"device containers run\", false, pod(corev1.PodRunning, false), \"running\"},\n+\t\t{\"pod being deleted (restart)\", false, pod(corev1.PodRunning, true), \"exited\"},\n+\t\t{\"pod ended\", false, pod(corev1.PodFailed, false), \"exited\"},\n+\t\t{\"stop requested, pod terminating\", true, pod(corev1.PodRunning, true), \"exited\"},\n+\t\t{\"stopped\", true, nil, \"exited\"},\n+\t}\n+\tfor _, tt := range tests {\n+\t\tif got := nodeContainerState(tt.stopRequested, tt.pod); got != tt.want {\n+\t\t\tt.Fatalf(\"%s: %q, want %q\", tt.name, got, tt.want)\n+\t\t}\n+\t}\n+}\n+\n+func TestNewestPodPrefersAPodThatIsNotDeleted(t *testing.T) {\n+\tt.Parallel()\n+\n+\tnow := time.Now()\n+\tdeleting := metav1.NewTime(now)\n+\told := &corev1.Pod{\n+\t\tObjectMeta: metav1.ObjectMeta{\n+\t\t\tName: \"old\", CreationTimestamp: metav1.NewTime(now.Add(-time.Hour)),\n+\t\t\tDeletionTimestamp: &deleting,\n+\t\t},\n+\t\tStatus: corev1.PodStatus{Phase: corev1.PodRunning},\n+\t}\n+\treplacement := &corev1.Pod{\n+\t\tObjectMeta: metav1.ObjectMeta{Name: \"new\", CreationTimestamp: metav1.NewTime(now)},\n+\t\tStatus:     corev1.PodStatus{Phase: corev1.PodPending},\n+\t}\n+\tif got := newestPod(old, replacement); got != replacement {\n+\t\tt.Fatalf(\"newestPod = %s, want the replacement\", got.Name)\n+\t}\n+\tif got := newestPod(replacement, old); got != replacement {\n+\t\tt.Fatalf(\"newestPod = %s, want the replacement\", got.Name)\n+\t}\n+}\n+\n+func TestEnrichStateReportsContainerStateAndHealth(t *testing.T) {\n+\tt.Parallel()\n+\n+\tr := newTestRuntimeWithKubeObjects(",
        "lineStart": 1362,
        "lineEnd": 2844,
        "totalLines": 2845,
        "truncated": true
      }
    },
    "time": {
      "start": 1793525603023,
      "end": 1793525603081
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19674db0f001bL94buLQLg1Ind",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674cdcb001GeL6jU7LOAlFw9",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 24150,
    "input": 21249,
    "output": 20,
    "reasoning": 1,
    "cache": {
      "read": 2880,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19674cdcb001GeL6jU7LOAlFw9",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525599691,
    "completed": 1793525603093
  },
  "parentID": "msg_19674becc001poQpu47cHvtM8V",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 24150,
    "input": 21249,
    "output": 20,
    "reasoning": 1,
    "cache": {
      "read": 2880,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 5
step-start
{
  "type": "step-start",
  "id": "prt_19674e46f001OfHelxUIXZ1QUc",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674db1a001T4BNzcGimXgvil"
}
read · completed

Input

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

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
2845: +		[]*unstructured.Unstructured{
2846: +			trackerTestNode("r1", nodeRunStateRunning, condition("Ready", "True")),
2847: +			// its peer is stopped: not ready, but the device is
2848: +			trackerTestNode("r2", nodeRunStateRunning,
2849: +				condition(nodeConditionContainersReady, "True")),
2850: +			trackerTestNode("r3", nodeRunStateRunning),
2851: +			trackerTestNode("r4", nodeRunStateStopped, condition(nodeConditionStopped, "True")),
2852: +		},
2853: +		[]k8sruntime.Object{
2854: +			captureTestPod("lab1-r1-a", "r1"),
2855: +			captureTestPod("lab1-r2-a", "r2"),
2856: +			withNodeUID(captureTestPod("lab1-r3-a", "r3"), "uid-r3"),
2857: +			// the newer pod of an earlier Node r3 that still terminates is not r3's pod
2858: +			withNodeUID(withCreation(captureTestPod("lab1-r3-stale", "r3"), time.Hour), "uid-old"),
2859: +		},
2860: +	)
2861: +
2862: +	state := &clablabruntime.LabState{Name: "lab1", Namespace: "lab-ns"}
2863: +	if err := r.enrichState(context.Background(), state); err != nil {
2864: +		t.Fatal(err)
2865: +	}
2866: +
2867: +	want := map[string]string{
2868: +		"r1": "running/healthy", "r2": "running/healthy", "r3": "running/starting", "r4": "exited/",
2869: +	}
2870: +	for _, node := range state.Nodes {
2871: +		if node.Name == "r3" && node.Pod != "lab1-r3-a" {
2872: +			t.Fatalf("r3 pod = %q, want its own Node's pod", node.Pod)
2873: +		}
2874: +		if got := node.ContainerState + "/" + node.Health; got != want[node.Name] {
2875: +			t.Fatalf("%s = %s, want %s", node.Name, got, want[node.Name])
2876: +		}
2877: +		if node.TopologyName != strings.ToUpper(node.Name) {
2878: +			t.Fatalf("%s topology name = %q", node.Name, node.TopologyName)
2879: +		}
2880: +	}
2881: +}
2882: +
2883: +const sourceDefinition = `name: lab1
2884: +topology:
2885: +  nodes:
2886: +    node1:
2887: +      kind: linux
2888: +      image: alpine:latest
2889: +    node2:
2890: +      kind: linux
2891: +      image: alpine:latest
2892: +  links:
2893: +    - endpoints: ["node1:eth1", "node2:eth1"]
2894: +`
2895: +
2896: +func sourceDeployRequest(path string, noTopologyCR bool) clablabruntime.DeployRequest {
2897: +	return clablabruntime.DeployRequest{
2898: +		Name:               "lab1",
2899: +		Namespace:          "lab-ns",
2900: +		TopologyFile:       path,
2901: +		TopologyDefinition: []byte(sourceDefinition),
2902: +		NoTopologyCR:       noTopologyCR,
2903: +	}
2904: +}
2905: +
2906: +// TestDeployRecordsTheTopologyFile checks where a deploy records the topology file and that
2907: +// inspect reports it, with and without a Topology resource.
2908: +func TestDeployRecordsTheTopologyFile(t *testing.T) {
2909: +	t.Parallel()
2910: +
2911: +	// with a Topology resource: on the Topology, updated by every deploy
2912: +	r := newTestRuntime()
2913: +	if _, err := r.Deploy(context.Background(),
2914: +		sourceDeployRequest("/home/alice/labs/lab1.clab.yml", false)); err != nil {
2915: +		t.Fatal(err)
2916: +	}
2917: +	topology := getTestTopology(t, r, "lab-ns", "lab1")
2918: +	if got := topology.GetAnnotations()[annotationTopologyFile]; got != "/home/alice/labs/lab1.clab.yml" {
2919: +		t.Fatalf("Topology annotation = %q", got)
2920: +	}
2921: +	state, err := r.Inspect(context.Background(),
2922: +		clablabruntime.InspectRequest{Name: "lab1", Namespace: "lab-ns"})
2923: +	if err != nil {
2924: +		t.Fatal(err)
2925: +	}
2926: +	if state.TopologyPath != "/home/alice/labs/lab1.clab.yml" {
2927: +		t.Fatalf("TopologyPath = %q", state.TopologyPath)
2928: +	}
2929: +
2930: +	if _, err := r.Deploy(context.Background(),
2931: +		sourceDeployRequest("/srv/labs/lab1.clab.yml", false)); err != nil {
2932: +		t.Fatal(err)
2933: +	}
2934: +	topology = getTestTopology(t, r, "lab-ns", "lab1")
2935: +	if got := topology.GetAnnotations()[annotationTopologyFile]; got != "/srv/labs/lab1.clab.yml" {
2936: +		t.Fatalf("Topology annotation after a deploy from another file = %q", got)
2937: +	}
2938: +
2939: +	// without a Topology resource: on the Nodes only, kept from their creation
2940: +	r = newTestRuntime()
2941: +	if _, err := r.Deploy(context.Background(),
2942: +		sourceDeployRequest("/home/alice/labs/lab1.clab.yml", true)); err != nil {
2943: +		t.Fatal(err)
2944: +	}
2945: +	assertPrimitiveTopologyFile(t, r, "/home/alice/labs/lab1.clab.yml")
2946: +	state, err = r.Inspect(context.Background(),
2947: +		clablabruntime.InspectRequest{Name: "lab1", Namespace: "lab-ns"})
2948: +	if err != nil {
2949: +		t.Fatal(err)
2950: +	}
2951: +	if state.TopologyPath != "/home/alice/labs/lab1.clab.yml" {
2952: +		t.Fatalf("TopologyPath without a Topology = %q", state.TopologyPath)
2953: +	}
2954: +
2955: +	plan, err := r.Plan(context.Background(),
2956: +		sourceDeployRequest("/srv/labs/lab1.clab.yml", true))
2957: +	if err != nil {
2958: +		t.Fatal(err)
2959: +	}
2960: +	for _, change := range plan.Changes {
2961: +		if change.Kind == "Node" {
2962: +			t.Fatalf("a deploy from another file would change %+v and replace its pod", change)
2963: +		}
2964: +	}
2965: +	if _, err := r.Deploy(context.Background(),
2966: +		sourceDeployRequest("/srv/labs/lab1.clab.yml", true)); err != nil {
2967: +		t.Fatal(err)
2968: +	}
2969: +	assertPrimitiveTopologyFile(t, r, "/home/alice/labs/lab1.clab.yml")
2970: +}
2971: +
2972: +func assertPrimitiveTopologyFile(t *testing.T, r *Runtime, want string) {
2973: +	t.Helper()
2974: +
2975: +	for _, gvr := range []struct {
2976: +		name string
2977: +		want string
2978: +	}{{"nodes", want}, {"links", ""}, {"nodeprofiles", ""}} {
2979: +		resource := nodeGVR
2980: +		switch gvr.name {
2981: +		case "links":
2982: +			resource = linkGVR
2983: +		case "nodeprofiles":
2984: +			resource = nodeProfileGVR
2985: +		}
2986: +		list, err := r.client.Resource(resource).Namespace("lab-ns").
2987: +			List(context.Background(), metav1.ListOptions{})
2988: +		if err != nil {
2989: +			t.Fatal(err)
2990: +		}
2991: +		for idx := range list.Items {
2992: +			if got := list.Items[idx].GetAnnotations()[annotationTopologyFile]; got != gvr.want {
2993: +				t.Fatalf("%s %s annotation = %q, want %q", gvr.name, list.Items[idx].GetName(),
2994: +					got, gvr.want)
2995: +			}
2996: +		}
2997: +	}
2998: +}
2999: +
3000: +func TestCarryOverNodeTopologyFile(t *testing.T) {
3001: +	t.Parallel()
3002: +
3003: +	node := func(annotations map[string]any) *unstructured.Unstructured {
3004: +		metadata := map[string]any{"name": "node1"}
3005: +		if annotations != nil {
3006: +			metadata["annotations"] = annotations
3007: +		}
3008: +
3009: +		return &unstructured.Unstructured{Object: map[string]any{
3010: +			"apiVersion": c9sAPIVersion, "kind": "Node", "metadata": metadata,
3011: +			"spec": map[string]any{"image": "alpine"},
3012: +		}}
3013: +	}
3014: +	desired := node(map[string]any{annotationTopologyFile: "/new.clab.yml"})
3015: +
3016: +	updated := reconciledPrimitiveObject(
3017: +		node(map[string]any{annotationTopologyFile: "/old.clab.yml"}),
3018: +		desired,
3019: +	)
3020: +	if got := updated.GetAnnotations()[annotationTopologyFile]; got != "/old.clab.yml" {
3021: +		t.Fatalf("existing Node file = %q, want it kept", got)
3022: +	}
3023: +
3024: +	// a Node deployed before containerlab recorded files does not get one
3025: +	existing := node(nil)
3026: +	updated = reconciledPrimitiveObject(existing, desired)
3027: +	if _, ok := updated.GetAnnotations()[annotationTopologyFile]; ok ||
3028: +		!primitiveObjectsConform(existing, updated) {
3029: +		t.Fatalf("Node without a file = %+v", updated.GetAnnotations())
3030: +	}
3031: +
3032: +	// the Topology always records the latest file
3033: +	topology := topologyObject("lab1", "lab-ns", "", "topology:\n")
3034: +	setTopologySourceFile(topology, "/old.clab.yml")
3035: +	newTopology := topologyObject("lab1", "lab-ns", "", "topology:\n")
3036: +	setTopologySourceFile(newTopology, "/new.clab.yml")
3037: +	updated = reconciledPrimitiveObject(topology, newTopology)
3038: +	if got := updated.GetAnnotations()[annotationTopologyFile]; got != "/new.clab.yml" {
3039: +		t.Fatalf("Topology file = %q", got)
3040: +	}
3041: +}
3042: +
3043: +func TestManifestsCarryNoTopologyFile(t *testing.T) {
3044: +	t.Parallel()
3045: +
3046: +	for _, noTopologyCR := range []bool{false, true} {
3047: +		manifests, err := (&Runtime{}).Manifests(context.Background(),
3048: +			sourceDeployRequest("/home/alice/labs/lab1.clab.yml", noTopologyCR))
3049: +		if err != nil {
3050: +			t.Fatal(err)
3051: +		}
3052: +		for _, manifest := range manifests {
3053: +			data, _ := json.Marshal(manifest.Object)
3054: +			if strings.Contains(string(data), annotationTopologyFile) {
3055: +				t.Fatalf("no-topology-cr=%t: %s %s carries the file", noTopologyCR,
3056: +					manifest.Kind, manifest.Name)
3057: +			}
3058: +		}
3059: +	}
3060: +}
3061: +
3062: +func TestStateReportsTheRecordedTopologyFile(t *testing.T) {
3063: +	t.Parallel()
3064: +
3065: +	topology := topologyObject("lab1", "lab-ns", "", "topology:\n")
3066: +	if got := stateFromTopology(
3067: +		topology,
3068: +		"lab-ns",
3069: +	).TopologyPath; got != "k8s://lab-ns/topologies/lab1" {
3070: +		t.Fatalf("lab created by other means = %q", got)
3071: +	}
3072: +	setTopologySourceFile(topology, "/home/alice/lab1.clab.yml")
3073: +	if got := stateFromTopology(
3074: +		topology,
3075: +		"lab-ns",
3076: +	).TopologyPath; got != "/home/alice/lab1.clab.yml" {
3077: +		t.Fatalf("deployed lab = %q", got)
3078: +	}
3079: +
3080: +	nodes := []unstructured.Unstructured{*trackerTestNode("r1", nodeRunStateRunning)}
3081: +	if got := stateFromNodeResources("lab1", "lab-ns", nodes).TopologyPath; got !=
3082: +		"k8s://lab-ns/labs/lab1" {
3083: +		t.Fatalf("Nodes created by other means = %q", got)
3084: +	}
3085: +	nodes[0].SetAnnotations(map[string]string{annotationTopologyFile: "/home/alice/lab1.clab.yml"})
3086: +	if got := stateFromNodeResources("lab1", "lab-ns", nodes).TopologyPath; got !=
3087: +		"/home/alice/lab1.clab.yml" {
3088: +		t.Fatalf("deployed Nodes = %q", got)
3089: +	}
3090: +}
3091: +
3092: +func withNodeUID(pod *corev1.Pod, uid string) *corev1.Pod {
3093: +	if pod.Annotations == nil {
3094: +		pod.Annotations = map[string]string{}
3095: +	}
3096: +	pod.Annotations[annotationDirectNodeUID] = uid
3097: +
3098: +	return pod
3099: +}
3100: +
3101: +func withCreation(pod *corev1.Pod, age time.Duration) *corev1.Pod {
3102: +	pod.CreationTimestamp = metav1.NewTime(time.Now().Add(age))
3103: +
3104: +	return pod
3105: +}
3106: diff --git a/labruntime/clabernetes/events.go b/labruntime/clabernetes/events.go
3107: index 37548dc..b06dc9d 100644
3108: --- a/labruntime/clabernetes/events.go
3109: +++ b/labruntime/clabernetes/events.go
3110: @@ -30,31 +30,49 @@ func (r *Runtime) StreamEvents(
3111:  	if err != nil {
3112:  		return nil, nil, err
3113:  	}
3114:  
3115:  	events := make(chan clablabruntime.Event, 128)
3116: -	errs := make(chan error, 3)
3117: +	errs := make(chan error, 4)
3118: +	// changed carries the labs whose Topology, Nodes or pods changed; the container tracker
3119: +	// reads them again and reports what changed for their nodes.
3120: +	changed := make(chan labRef, 256)
3121:  
3122: -	if req.IncludeInitialState {
3123: -		go r.emitInitialEvents(ctx, scope, events, errs)
3124: -	}
3125: +	go r.trackContainers(ctx, scope, req.IncludeInitialState, changed, events, errs)
3126:  
3127:  	// Interface state events are always reported, like the netlink-backed events of the local
3128:  	// runtimes; statistics only on request. Both come from the same exec per node.
3129:  	go r.pollInterfaces(ctx, scope, interfacePollOptions{
3130:  		interval:            req.StatsInterval,
3131:  		includeStats:        req.IncludeInterfaceStats,
3132:  		includeInitialState: req.IncludeInitialState,
3133:  	}, events)
3134:  
3135: -	go r.watchTopologies(ctx, scope, events, errs)
3136: -	go r.watchNodes(ctx, scope, events, errs)
3137: -	go r.watchPods(ctx, scope, events, errs)
3138: +	go r.watchTopologies(ctx, scope, changed, events, errs)
3139: +	go r.watchNodes(ctx, scope, changed, errs)
3140: +	go r.watchPods(ctx, scope, changed, errs)
3141:  
3142:  	return events, errs, nil
3143:  }
3144:  
3145: +// labRef names a lab in a namespace.
3146: +type labRef struct {
3147: +	namespace string
3148: +	lab       string
3149: +}
3150: +
3151: +func sendChangedLab(ctx context.Context, changed chan<- labRef, ref labRef) {
3152: +	if ref.lab == "" {
3153: +		return
3154: +	}
3155: +
3156: +	select {
3157: +	case changed <- ref:
3158: +	case <-ctx.Done():
3159: +	}
3160: +}
3161: +
3162:  // eventScope is the namespace and, optionally, the single lab an event stream covers.
3163:  type eventScope struct {
3164:  	namespace string
3165:  	lab       string
3166:  }
3167: @@ -123,11 +141,11 @@ func (r *Runtime) labStates(
3168:  }
3169:  
3170:  func (r *Runtime) watchNodes(
3171:  	ctx context.Context,
3172:  	scope eventScope,
3173: -	eventSink chan<- clablabruntime.Event,
3174: +	changed chan<- labRef,
3175:  	errSink chan<- error,
3176:  ) {
3177:  	resource := r.client.Resource(nodeGVR).Namespace(scope.namespace)
3178:  
3179:  	for {
3180: @@ -141,24 +159,25 @@ func (r *Runtime) watchNodes(
3181:  
3182:  			sendEventError(ctx, errSink, fmt.Errorf("failed to watch c9s nodes: %w", err))
3183:  			return
3184:  		}
3185:  
3186: -		if !r.forwardNodeWatch(ctx, watcher, eventSink, errSink) {
3187: +		if !r.forwardNodeWatch(ctx, watcher, changed, errSink) {
3188:  			return
3189:  		}
3190:  
3191:  		if !sleepContext(ctx, pollInterval) {
3192:  			return
3193:  		}
3194:  	}
3195:  }
3196:  
3197: +// forwardNodeWatch reports the lab of every changed Node to the container tracker.
3198:  func (r *Runtime) forwardNodeWatch(
3199:  	ctx context.Context,
3200:  	watcher watch.Interface,
3201: -	eventSink chan<- clablabruntime.Event,
3202: +	changed chan<- labRef,
3203:  	errSink chan<- error,
3204:  ) bool {
3205:  	defer watcher.Stop()
3206:  
3207:  	for {
3208: @@ -178,73 +197,22 @@ func (r *Runtime) forwardNodeWatch(
3209:  			node, ok := ev.Object.(*unstructured.Unstructured)
3210:  			if !ok {
3211:  				continue
3212:  			}
3213:  
3214: -			labName := node.GetLabels()[labelTopologyOwner]
3215: -			if labName == "" {
3216: -				continue
3217: -			}
3218: -			readiness, _, _ := unstructured.NestedString(node.Object, "status", "readiness")
3219: -			r.sendEvent(ctx, eventSink, clablabruntime.Event{
3220: -				Timestamp: time.Now(),
3221: -				Type:      "container",
3222: -				Action:    strings.ToLower(string(ev.Type)),
3223: -				ActorID:   fmt.Sprintf("%s/%s/%s", node.GetNamespace(), labName, node.GetName()),
3224: -				ActorName: fmt.Sprintf("%s-%s", labName, node.GetName()),
3225: -				Attributes: map[string]string{
3226: -					"namespace": node.GetNamespace(),
3227: -					"lab":       labName,
3228: -					"node":      node.GetName(),
3229: -					"state":     readiness,
3230: -				},
3231: -			})
3232: -		}
3233: -	}
3234: -}
3235: -
3236: -func (r *Runtime) emitInitialEvents(
3237: -	ctx context.Context,
3238: -	scope eventScope,
3239: -	eventSink chan<- clablabruntime.Event,
3240: -	errSink chan<- error,
3241: -) {
3242: -	states, err := r.labStates(ctx, scope)
3243: -	if err != nil {
3244: -		sendEventError(ctx, errSink, err)
3245: -		return
3246: -	}
3247: -
3248: -	for _, state := range states {
3249: -		for _, node := range state.Nodes {
3250: -			action := node.State
3251: -			if node.Ready {
3252: -				action = "running"
3253: -			}
3254: -			if action == "" {
3255: -				action = state.State
3256: -			}
3257: -			r.sendEvent(ctx, eventSink, clablabruntime.Event{
3258: -				Timestamp: time.Now(),
3259: -				Type:      "container",
3260: -				Action:    action,
3261: -				ActorID:   fmt.Sprintf("%s/%s/%s", state.Namespace, state.Name, node.Name),
3262: -				ActorName: fmt.Sprintf("%s-%s", state.Name, node.Name),
3263: -				Attributes: map[string]string{
3264: -					"namespace": state.Namespace,
3265: -					"lab":       state.Name,
3266: -					"node":      node.Name,
3267: -					"state":     node.State,
3268: -				},
3269: +			sendChangedLab(ctx, changed, labRef{
3270: +				namespace: node.GetNamespace(),
3271: +				lab:       node.GetLabels()[labelTopologyOwner],
3272:  			})
3273:  		}
3274:  	}
3275:  }
3276:  
3277:  func (r *Runtime) watchTopologies(
3278:  	ctx context.Context,
3279:  	scope eventScope,
3280: +	changed chan<- labRef,
3281:  	eventSink chan<- clablabruntime.Event,
3282:  	errSink chan<- error,
3283:  ) {
3284:  	resource := r.client.Resource(topologyGVR).Namespace(scope.namespace)
3285:  
3286: @@ -261,24 +229,27 @@ func (r *Runtime) watchTopologies(
3287:  				fmt.Errorf("failed to watch clabernetes topologies: %w", err),
3288:  			)
3289:  			return
3290:  		}
3291:  
3292: -		if !r.forwardTopologyWatch(ctx, scope.namespace, watcher, eventSink, errSink) {
3293: +		if !r.forwardTopologyWatch(ctx, scope.namespace, watcher, changed, eventSink, errSink) {
3294:  			return
3295:  		}
3296:  
3297:  		if !sleepContext(ctx, pollInterval) {
3298:  			return
3299:  		}
3300:  	}
3301:  }
3302:  
3303: +// forwardTopologyWatch reports Topology changes as topology events, which only c9s has, and
3304: +// reports the lab to the container tracker.
3305:  func (r *Runtime) forwardTopologyWatch(
3306:  	ctx context.Context,
3307:  	namespace string,
3308:  	watcher watch.Interface,
3309: +	changed chan<- labRef,
3310:  	eventSink chan<- clablabruntime.Event,
3311:  	errSink chan<- error,
3312:  ) bool {
3313:  	defer watcher.Stop()
3314:  
3315: @@ -317,18 +288,19 @@ func (r *Runtime) forwardTopologyWatch(
3316:  					"lab":       state.Name,
3317:  					"state":     state.State,
3318:  					"ready":     fmt.Sprintf("%t", state.Ready),
3319:  				},
3320:  			})
3321: +			sendChangedLab(ctx, changed, labRef{namespace: state.Namespace, lab: state.Name})
3322:  		}
3323:  	}
3324:  }
3325:  
3326:  func (r *Runtime) watchPods(
3327:  	ctx context.Context,
3328:  	scope eventScope,
3329: -	eventSink chan<- clablabruntime.Event,
3330: +	changed chan<- labRef,
3331:  	errSink chan<- error,
3332:  ) {
3333:  	for {
3334:  		watcher, err := r.kubeClient.CoreV1().Pods(scope.namespace).Watch(ctx, metav1.ListOptions{
3335:  			LabelSelector: scope.labelSelector(),
3336: @@ -341,24 +313,25 @@ func (r *Runtime) watchPods(
3337:  			sendEventError(ctx, errSink, fmt.Errorf(
3338:  				"failed to watch clabernetes pods: %w", err))
3339:  			return
3340:  		}
3341:  
3342: -		if !r.forwardPodWatch(ctx, watcher, eventSink, errSink) {
3343: +		if !r.forwardPodWatch(ctx, watcher, changed, errSink) {
3344:  			return
3345:  		}
3346:  
3347:  		if !sleepContext(ctx, pollInterval) {
3348:  			return
3349:  		}
3350:  	}
3351:  }
3352:  
3353: +// forwardPodWatch reports the lab of every changed pod to the container tracker.
3354:  func (r *Runtime) forwardPodWatch(
3355:  	ctx context.Context,
3356:  	watcher watch.Interface,
3357: -	eventSink chan<- clablabruntime.Event,
3358: +	changed chan<- labRef,
3359:  	errSink chan<- error,
3360:  ) bool {
3361:  	defer watcher.Stop()
3362:  
3363:  	for {
3364: @@ -379,31 +352,13 @@ func (r *Runtime) forwardPodWatch(
3365:  			pod, ok := ev.Object.(*corev1.Pod)
3366:  			if !ok {
3367:  				continue
3368:  			}
3369:  
3370: -			labName := pod.Labels[labelTopologyOwner]
3371: -			nodeName := pod.Labels[labelTopologyNode]
3372: -			if labName == "" || nodeName == "" {
3373: -				continue
3374: -			}
3375: -
3376: -			r.sendEvent(ctx, eventSink, clablabruntime.Event{
3377: -				Timestamp:   time.Now(),
3378: -				Type:        "container",
3379: -				Action:      strings.ToLower(string(ev.Type)),
3380: -				ActorID:     fmt.Sprintf("%s/%s/%s", pod.Namespace, labName, nodeName),
3381: -				ActorName:   fmt.Sprintf("%s-%s", labName, nodeName),
3382: -				ActorFullID: pod.Name,
3383: -				Attributes: map[string]string{
3384: -					"namespace": pod.Namespace,
3385: -					"lab":       labName,
3386: -					"node":      nodeName,
3387: -					"pod":       pod.Name,
3388: -					"phase":     string(pod.Status.Phase),
3389: -					"pod_ip":    pod.Status.PodIP,
3390: -				},
3391: +			sendChangedLab(ctx, changed, labRef{
3392: +				namespace: pod.Namespace,
3393: +				lab:       pod.Labels[labelTopologyOwner],
3394:  			})
3395:  		}
3396:  	}
3397:  }
3398:  
3399: diff --git a/labruntime/clabernetes/iface_stats.go b/labruntime/clabernetes/iface_stats.go
3400: index 09abca3..a6c72b0 100644
3401: --- a/labruntime/clabernetes/iface_stats.go
3402: +++ b/labruntime/clabernetes/iface_stats.go
3403: @@ -1,10 +1,11 @@
3404:  package clabernetes
3405:  
3406:  import (
3407:  	"context"
3408:  	"fmt"
3409: +	"sort"
3410:  	"strconv"
3411:  	"strings"
3412:  	"sync"
3413:  	"time"
3414:  
3415: @@ -28,16 +29,31 @@ const (
3416:  		`"$(cat "$d/flags")" "$(cat "$d/ifalias")"; done 2>/dev/null`
3417:  
3418:  	// interfaceSampleWorkers bounds the concurrent execs of one sampling round.
3419:  	interfaceSampleWorkers = 16
3420:  
3421: -	// interfaceStateNotPresent is the operational state reported for an interface that
3422: -	// disappeared, or whose node stopped running (RFC 2863 "notPresent").
3423: -	interfaceStateNotPresent = "notpresent"
3424: -
3425: -	// iffUp is the IFF_UP bit of /sys/class/net/<if>/flags.
3426: -	iffUp = 0x1
3427: +	// managementInterface is a node's management interface in its pod, the interface the
3428: +	// clabernetes planner gives the management address by default. It has the name the
3429: +	// management interface has in a container of the local runtimes.
3430: +	managementInterface = "eth0"
3431: +	// loopbackInterface is reported like the local runtimes report it.
3432: +	loopbackInterface = "lo"
3433: +	// clabernetesAliasPrefix starts the interface aliases clabernetes marks its own interfaces
3434: +	// and the lab links it wires with. They are not the topology's names, so they are not
3435: +	// reported.
3436: +	clabernetesAliasPrefix = "c9s:"
3437: +	// zeroMAC is the hardware address sysfs reports for interfaces without one (loopback).
3438: +	zeroMAC = "00:00:00:00:00:00"
3439: +
3440: +	// Interface event actions and link types, as the local runtimes report them.
3441: +	interfaceActionSnapshot = "snapshot"
3442: +	interfaceActionCreate   = "create"
3443: +	interfaceActionUpdate   = "update"
3444: +	interfaceActionDelete   = "delete"
3445: +	interfaceActionStats    = "stats"
3446: +	interfaceTypeVeth       = "veth"
3447: +	interfaceTypeDevice     = "device"
3448:  
3449:  	// shell exit codes of a command that cannot be found or executed.
3450:  	exitCommandNotExecutable = 126
3451:  	exitCommandNotFound      = 127
3452:  )
3453: @@ -70,35 +86,16 @@ type c9sIfaceState struct {
3454:  	OperState string
3455:  	Flags     uint64
3456:  	Alias     string
3457:  }
3458:  
3459: -// action maps the interface state onto the up/down action of interface state events. An
3460: -// "unknown" operational state (loopback, tunnels) counts as up when the interface is
3461: -// administratively up.
3462: -func (s c9sIfaceState) action() string {
3463: -	if s.OperState == "up" || (s.OperState == "unknown" && s.Flags&iffUp != 0) {
3464: -		return "up"
3465: -	}
3466: -
3467: -	return "down"
3468: -}
3469: -
3470: -// trackedIface is the last reported state of an interface.
3471: -type trackedIface struct {
3472: -	state  c9sIfaceState
3473: -	action string
3474: -}
3475: -
3476: -// trackedNode remembers the interfaces last reported for a node, so their removal can be
3477: -// reported when the node stops running.
3478: +// trackedNode remembers the interfaces last reported for a node, so their changes and their
3479: +// removal can be reported, also when the node stops running.
3480:  type trackedNode struct {
3481: -	namespace string
3482: -	lab       string
3483: -	node      string
3484: -	pod       string
3485: -	ifaces    map[string]trackedIface
3486: +	lab    *clablabruntime.LabState
3487: +	node   clablabruntime.NodeState
3488: +	ifaces map[string]clablabruntime.InterfaceEventData
3489:  }
3490:  
3491:  type interfaceSampleTarget struct {
3492:  	state *clablabruntime.LabState
3493:  	node  clablabruntime.NodeState
3494: @@ -108,16 +105,28 @@ type interfaceSampleTarget struct {
3495:  type interfaceSample struct {
3496:  	target    interfaceSampleTarget
3497:  	stats     []c9sIfaceStats
3498:  	ifaces    []c9sIfaceState
3499:  	hasStates bool
3500: +	// links are the node's lab link interfaces as clabwire lists them.
3501: +	links     []clabwireInterface
3502:  	timestamp time.Time
3503:  	err       error
3504:  }
3505:  
3506: +// podInterfaceListing is the clabwire interface listing of a pod, per node. It is listed again
3507: +// when the pod's interfaces change.
3508: +type podInterfaceListing struct {
3509: +	names  string
3510: +	byNode map[string][]clabwireInterface
3511: +}
3512: +
3513:  // interfacePoller samples the interfaces of every running node in an event scope and turns the
3514: -// samples into interface state and statistics events.
3515: +// samples into interface events. It reports the interfaces a container of the local runtimes
3516: +// has for the same node: the node's lab link interfaces, with the names and aliases clabwire
3517: +// lists for them, the management interface and loopback. The pod's own interfaces (the pod
3518: +// network, clabernetes' interposition and link transport interfaces) are not reported.
3519:  type interfacePoller struct {
3520:  	r     *Runtime
3521:  	scope eventScope
3522:  	opts  interfacePollOptions
3523:  	sink  chan<- clablabruntime.Event
3524: @@ -128,10 +137,14 @@ type interfacePoller struct {
3525:  	noShellMu sync.Mutex
3526:  	// noShell holds the pods whose device container has no shell; they are sampled with a
3527:  	// plain cat of /proc/net/dev and report statistics without interface state.
3528:  	noShell map[string]bool
3529:  
3530: +	listingsMu sync.Mutex
3531: +	// listings holds the clabwire interface listing per pod (namespace/pod).
3532: +	listings map[string]*podInterfaceListing
3533: +
3534:  	firstRound bool
3535:  }
3536:  
3537:  func (r *Runtime) pollInterfaces(
3538:  	ctx context.Context,
3539: @@ -141,21 +154,11 @@ func (r *Runtime) pollInterfaces(
3540:  ) {
3541:  	if opts.interval <= 0 {
3542:  		opts.interval = time.Second
3543:  	}
3544:  
3545: -	poller := &interfacePoller{
3546: -		r:            r,
3547: -		scope:        scope,
3548: -		opts:         opts,
3549: -		sink:         eventSink,
3550: -		statsSamples: map[string]c9sIfaceStatsSample{},
3551: -		nodes:        map[string]*trackedNode{},
3552: -		noShell:      map[string]bool{},
3553: -		firstRound:   true,
3554: -	}
3555: -
3556: +	poller := newInterfacePoller(r, scope, opts, eventSink)
3557:  	poller.round(ctx)
3558:  
3559:  	ticker := time.NewTicker(opts.interval)
3560:  	defer ticker.Stop()
3561:  
3562: @@ -167,28 +170,50 @@ func (r *Runtime) pollInterfaces(
3563:  			poller.round(ctx)
3564:  		}
3565:  	}
3566:  }
3567:  
3568: +func newInterfacePoller(
3569: +	r *Runtime,
3570: +	scope eventScope,
3571: +	opts interfacePollOptions,
3572: +	eventSink chan<- clablabruntime.Event,
3573: +) *interfacePoller {
3574: +	return &interfacePoller{
3575: +		r:            r,
3576: +		scope:        scope,
3577: +		opts:         opts,
3578: +		sink:         eventSink,
3579: +		statsSamples: map[string]c9sIfaceStatsSample{},
3580: +		nodes:        map[string]*trackedNode{},
3581: +		noShell:      map[string]bool{},
3582: +		listings:     map[string]*podInterfaceListing{},
3583: +		firstRound:   true,
3584: +	}
3585: +}
3586: +
3587:  func (p *interfacePoller) round(ctx context.Context) {
3588:  	defer func() { p.firstRound = false }()
3589:  
3590:  	states, err := p.r.labStates(ctx, p.scope)
3591:  	if err != nil {
3592:  		log.Debug("failed to list C9s labs for interface events", "error", err)
3593:  		return
3594:  	}
3595:  
3596:  	running := map[string]bool{}
3597: +	pods := map[string]bool{}
3598:  	var targets []interfaceSampleTarget
3599:  	for _, state := range states {
3600:  		for _, node := range state.Nodes {
3601: -			if !node.Ready || node.Pod == "" || node.Container == "" {
3602: +			if node.ContainerState != clablabruntime.ContainerStateRunning || node.Pod == "" ||
3603: +				node.Container == "" {
3604:  				continue
3605:  			}
3606:  
3607:  			running[c9sNodeKey(state.Namespace, state.Name, node.Name)] = true
3608: +			pods[state.Namespace+"/"+node.Pod] = true
3609:  			targets = append(targets, interfaceSampleTarget{
3610:  				state: state,
3611:  				node:  node,
3612:  				pod: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{
3613:  					Name:      node.Pod,
3614: @@ -215,29 +240,41 @@ func (p *interfacePoller) round(ctx context.Context) {
3615:  
3616:  		p.processSample(ctx, sample)
3617:  	}
3618:  
3619:  	p.retireStoppedNodes(ctx, running)
3620: +	p.forgetListings(pods)
3621:  }
3622:  
3623:  // retireStoppedNodes reports the interfaces of nodes that stopped running, or were removed, as
3624: -// down: they are gone with the node's pod.
3625: +// deleted: they are gone with the node's pod.
3626:  func (p *interfacePoller) retireStoppedNodes(ctx context.Context, running map[string]bool) {
3627:  	for key, tracked := range p.nodes {
3628:  		if running[key] {
3629:  			continue
3630:  		}
3631:  
3632: -		for name, iface := range tracked.ifaces {
3633: -			iface.state.OperState = interfaceStateNotPresent
3634: -			p.emitState(ctx, tracked, iface.state, time.Now())
3635: +		for _, name := range sortedInterfaceNames(tracked.ifaces) {
3636: +			p.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], time.Now())
3637:  			p.forgetStats(tracked, name)
3638:  		}
3639:  		delete(p.nodes, key)
3640:  	}
3641:  }
3642:  
3643: +// forgetListings drops the interface listings of pods that are gone.
3644: +func (p *interfacePoller) forgetListings(pods map[string]bool) {
3645: +	p.listingsMu.Lock()
3646: +	defer p.listingsMu.Unlock()
3647: +
3648: +	for key := range p.listings {
3649: +		if !pods[key] {
3650: +			delete(p.listings, key)
3651: +		}
3652: +	}
3653: +}
3654: +
3655:  func (p *interfacePoller) sampleAll(
3656:  	ctx context.Context,
3657:  	targets []interfaceSampleTarget,
3658:  ) []interfaceSample {
3659:  	samples := make([]interfaceSample, len(targets))
3660: @@ -298,152 +335,318 @@ func (p *interfacePoller) sample(
3661:  	case rc != 0:
3662:  		sample.err = fmt.Errorf("exit code %d: %s", rc, strings.TrimSpace(string(stderr)))
3663:  	default:
3664:  		sample.stats, sample.ifaces, sample.hasStates, sample.err = parseInterfaceSample(stdout)
3665:  	}
3666: +	if sample.err != nil {
3667: +		return sample
3668: +	}
3669: +
3670: +	sample.links, sample.err = p.nodeLinks(ctx, target, sampledInterfaceNames(sample))
3671:  
3672:  	return sample
3673:  }
3674:  
3675: +// sampledInterfaceNames lists the interface names a sample saw, sorted and comma-joined.
3676: +func sampledInterfaceNames(sample interfaceSample) string {
3677: +	names := make([]string, 0, len(sample.stats)+len(sample.ifaces))
3678: +	seen := map[string]bool{}
3679: +	for _, iface := range sample.ifaces {
3680: +		if !seen[iface.Name] {
3681: +			seen[iface.Name] = true
3682: +			names = append(names, iface.Name)
3683: +		}
3684: +	}
3685: +	for _, stat := range sample.stats {
3686: +		if !seen[stat.Name] {
3687: +			seen[stat.Name] = true
3688: +			names = append(names, stat.Name)
3689: +		}
3690: +	}
3691: +	sort.Strings(names)
3692: +
3693: +	return strings.Join(names, ",")
3694: +}
3695: +
3696: +// nodeLinks returns the lab link interfaces of a node from its pod's clabwire listing. A pod is
3697: +// listed once, and again when its interfaces change (a pod gets its link interfaces as clabwire
3698: +// wires them).
3699: +func (p *interfacePoller) nodeLinks(
3700: +	ctx context.Context,
3701: +	target interfaceSampleTarget,
3702: +	names string,
3703: +) ([]clabwireInterface, error) {
3704: +	key := target.pod.Namespace + "/" + target.pod.Name
3705: +
3706: +	p.listingsMu.Lock()
3707: +	listing := p.listings[key]
3708: +	p.listingsMu.Unlock()
3709: +
3710: +	if listing == nil || listing.names != names {
3711: +		entries, err := p.r.listPodInterfaces(ctx, target.pod.Namespace, target.pod.Name)
3712: +		if err != nil {
3713: +			return nil, err
3714: +		}
3715: +
3716: +		listing = &podInterfaceListing{
3717: +			names:  names,
3718: +			byNode: map[string][]clabwireInterface{},
3719: +		}
3720: +		for _, entry := range entries {
3721: +			listing.byNode[entry.Node] = append(listing.byNode[entry.Node], entry)
3722: +		}
3723: +
3724: +		p.listingsMu.Lock()
3725: +		p.listings[key] = listing
3726: +		p.listingsMu.Unlock()
3727: +	}
3728: +
3729: +	return listing.byNode[target.node.Name], nil
3730: +}
3731: +
3732:  // commandNotExecutable reports an exec that failed because the command does not exist in the
3733:  // container.
3734:  func commandNotExecutable(rc int, err error) bool {
3735:  	if rc == exitCommandNotExecutable || rc == exitCommandNotFound {
3736:  		return true
3737:  	}
3738:  
3739:  	return err != nil && strings.Contains(err.Error(), "executable file not found")
3740:  }
3741:  
3742: +// reportedInterfaces are the interfaces reported for a node, by name, with the alias the
3743: +// topology gave them: its lab link interfaces, the management interface and loopback.
3744: +func reportedInterfaces(links []clabwireInterface) map[string]string {
3745: +	reported := map[string]string{
3746: +		loopbackInterface:   "",
3747: +		managementInterface: "",
3748: +	}
3749: +	for _, link := range links {
3750: +		reported[link.Interface] = link.Alias
3751: +	}
3752: +
3753: +	return reported
3754: +}
3755: +
3756: +// interfaceEventData describes an interface the way the local runtimes' netlink events do: the
3757: +// alias is the topology's name for the interface (an alias clabernetes set for its own use is
3758: +// not reported), the operational state uses netlink's names, lab link and management
3759: +// interfaces are veth pairs, loopback a device, and loopback has no hardware address.
3760: +func interfaceEventData(iface c9sIfaceState, alias string) clablabruntime.InterfaceEventData {
3761: +	if alias == "" && !strings.HasPrefix(iface.Alias, clabernetesAliasPrefix) {
3762: +		alias = iface.Alias
3763: +	}
3764: +
3765: +	mac := iface.MAC
3766: +	if mac == zeroMAC {
3767: +		mac = ""
3768: +	}
3769: +
3770: +	linkType := interfaceTypeVeth
3771: +	if iface.Name == loopbackInterface {
3772: +		linkType = interfaceTypeDevice
3773: +	}
3774: +
3775: +	return clablabruntime.InterfaceEventData{
3776: +		Name:      iface.Name,
3777: +		Alias:     alias,
3778: +		Index:     iface.Index,
3779: +		MTU:       iface.MTU,
3780: +		MAC:       mac,
3781: +		OperState: netlinkOperState(iface.OperState),
3782: +		Type:      linkType,
3783: +	}
3784: +}
3785: +
3786: +// netlinkOperState names an operational state from sysfs (RFC 2863, as in
3787: +// /sys/class/net/<if>/operstate) the way netlink, and so the local runtimes' events, name it.
3788: +func netlinkOperState(operState string) string {
3789: +	switch operState {
3790: +	case "notpresent":
3791: +		return "not-present"
3792: +	case "lowerlayerdown":
3793: +		return "lower-layer-down"
3794: +	case "":
3795: +		return "unknown"
3796: +	default:
3797: +		return operState
3798: +	}
3799: +}
3800: +
3801:  func (p *interfacePoller) processSample(ctx context.Context, sample interfaceSample) {
3802:  	state := sample.target.state
3803:  	node := sample.target.node
3804:  	key := c9sNodeKey(state.Namespace, state.Name, node.Name)
3805:  
3806:  	tracked, known := p.nodes[key]
3807:  	if !known {
3808: -		tracked = &trackedNode{
3809: -			namespace: state.Namespace,
3810: -			lab:       state.Name,
3811: -			node:      node.Name,
3812: -			ifaces:    map[string]trackedIface{},
3813: -		}
3814: +		tracked = &trackedNode{ifaces: map[string]clablabruntime.InterfaceEventData{}}
3815:  		p.nodes[key] = tracked
3816:  	}
3817: -	tracked.pod = node.Pod
3818: -
3819: -	if p.opts.includeStats {
3820: -		for _, stat := range sample.stats {
3821: -			statsKey := c9sIfaceStatsKey(state.Namespace, state.Name, node.Name, stat.Name)
3822: -			current := c9sIfaceStatsSample{Stats: stat, Timestamp: sample.timestamp}
3823: +	tracked.lab = state
3824: +	tracked.node = node
3825:  
3826: -			if previous, ok := p.statsSamples[statsKey]; ok {
3827: -				p.r.sendEvent(ctx, p.sink,
3828: -					c9sIfaceStatsEvent(state, node, sample.target.pod, stat, previous, current))
3829: -			}
3830: +	reported := reportedInterfaces(sample.links)
3831:  
3832: -			p.statsSamples[statsKey] = current
3833: -		}
3834: +	if sample.hasStates {
3835: +		p.processStates(ctx, tracked, reported, sample)
3836:  	}
3837:  
3838: -	if !sample.hasStates {
3839: +	if !p.opts.includeStats {
3840:  		return
3841:  	}
3842: +	for _, stat := range sample.stats {
3843: +		alias, ok := reported[stat.Name]
3844: +		if !ok {
3845: +			continue
3846: +		}
3847: +
3848: +		statsKey := c9sIfaceStatsKey(state.Namespace, state.Name, node.Name, stat.Name)
3849: +		current := c9sIfaceStatsSample{Stats: stat, Timestamp: sample.timestamp}
3850: +		if previous, ok := p.statsSamples[statsKey]; ok {
3851: +			data, ok := tracked.ifaces[stat.Name]
3852: +			if !ok {
3853: +				data = interfaceEventData(c9sIfaceState{Name: stat.Name}, alias)
3854: +				data.OperState = ""
3855: +			}
3856: +			data.Stats = c9sIfaceStatsData(previous, current)
3857: +			p.emit(ctx, tracked, interfaceActionStats, data, current.Timestamp)
3858: +		}
3859:  
3860: -	present := make(map[string]bool, len(sample.ifaces))
3861: +		p.statsSamples[statsKey] = current
3862: +	}
3863: +}
3864: +
3865: +// processStates reports the interfaces that appeared (snapshot in the first round with
3866: +// --initial-state, create later), changed (update) or disappeared (delete) since the last
3867: +// sample, like the netlink events of the local runtimes.
3868: +func (p *interfacePoller) processStates(
3869: +	ctx context.Context,
3870: +	tracked *trackedNode,
3871: +	reported map[string]string,
3872: +	sample interfaceSample,
3873: +) {
3874: +	present := map[string]bool{}
3875:  	for _, iface := range sample.ifaces {
3876: -		present[iface.Name] = true
3877: +		alias, ok := reported[iface.Name]
3878: +		if !ok {
3879: +			continue
3880: +		}
3881:  
3882: -		action := iface.action()
3883: +		data := interfaceEventData(iface, alias)
3884: +		present[iface.Name] = true
3885:  		previous, seen := tracked.ifaces[iface.Name]
3886: -		tracked.ifaces[iface.Name] = trackedIface{state: iface, action: action}
3887: +		tracked.ifaces[iface.Name] = data
3888:  
3889:  		switch {
3890: -		case seen && previous.action == action &&
3891: -			previous.state.OperState == iface.OperState:
3892: -			continue
3893: -		case !seen && p.firstRound && !p.opts.includeInitialState:
3894: +		case seen && previous == data:
3895: +		case !seen && p.firstRound:
3896:  			// Interfaces that exist when the stream starts are only reported with
3897:  			// --initial-state; later changes are always reported.
3898: -			continue
3899: +			if p.opts.includeInitialState {
3900: +				p.emit(ctx, tracked, interfaceActionSnapshot, data, sample.timestamp)
3901: +			}
3902: +		case !seen:
3903: +			p.emit(ctx, tracked, interfaceActionCreate, data, sample.timestamp)
3904: +		default:
3905: +			p.emit(ctx, tracked, interfaceActionUpdate, data, sample.timestamp)
3906:  		}
3907: -
3908: -		p.emitState(ctx, tracked, iface, sample.timestamp)
3909:  	}
3910:  
3911: -	for name, iface := range tracked.ifaces {
3912: +	for _, name := range sortedInterfaceNames(tracked.ifaces) {
3913:  		if present[name] {
3914:  			continue
3915:  		}
3916:  
3917: -		iface.state.OperState = interfaceStateNotPresent
3918: -		p.emitState(ctx, tracked, iface.state, sample.timestamp)
3919: +		p.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], sample.timestamp)
3920:  		p.forgetStats(tracked, name)
3921:  		delete(tracked.ifaces, name)
3922:  	}
3923:  }
3924:  
3925: +func sortedInterfaceNames(ifaces map[string]clablabruntime.InterfaceEventData) []string {
3926: +	names := make([]string, 0, len(ifaces))
3927: +	for name := range ifaces {
3928: +		names = append(names, name)
3929: +	}
3930: +	sort.Strings(names)
3931: +
3932: +	return names
3933: +}
3934: +
3935:  func (p *interfacePoller) forgetStats(tracked *trackedNode, ifName string) {
3936: -	delete(p.statsSamples, c9sIfaceStatsKey(tracked.namespace, tracked.lab, tracked.node, ifName))
3937: +	delete(p.statsSamples,
3938: +		c9sIfaceStatsKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name, ifName))
3939:  }
3940:  
3941: -func (p *interfacePoller) emitState(
3942: +func (p *interfacePoller) emit(
3943:  	ctx context.Context,
3944:  	tracked *trackedNode,
3945: -	iface c9sIfaceState,
3946: +	action string,
3947: +	data clablabruntime.InterfaceEventData,
3948:  	timestamp time.Time,
3949:  ) {
3950: -	p.r.sendEvent(ctx, p.sink, c9sIfaceStateEvent(tracked, iface, timestamp))
3951: +	p.r.sendEvent(ctx, p.sink, c9sInterfaceEvent(tracked, action, data, timestamp))
3952:  }
3953:  
3954: -// c9sIfaceStateEvent reports the operational state of an interface. The actor is the node, as
3955: -// for the container events of the lab and the interface events of the local runtimes.
3956: -func c9sIfaceStateEvent(
3957: +// c9sInterfaceEvent is an interface event of a node. The actor is the node, as for its container
3958: +// events. The interface itself is in Interface; the events command reports it with the
3959: +// attributes of the local runtimes' interface events.
3960: +func c9sInterfaceEvent(
3961:  	tracked *trackedNode,
3962: -	iface c9sIfaceState,
3963: +	action string,
3964: +	data clablabruntime.InterfaceEventData,
3965:  	timestamp time.Time,
3966:  ) clablabruntime.Event {
3967: -	actorName := fmt.Sprintf("%s-%s", tracked.lab, tracked.node)
3968: +	key := c9sNodeKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name)
3969:  
3970:  	attributes := map[string]string{
3971: -		"namespace": tracked.namespace,
3972: -		"lab":       tracked.lab,
3973: -		"node":      tracked.node,
3974: -		"name":      actorName,
3975: -		"ifname":    iface.Name,
3976: -		"state":     iface.OperState,
3977: -		"origin":    "clabernetes",
3978: -	}
3979: -	if tracked.pod != "" {
3980: -		attributes["pod"] = tracked.pod
3981: -	}
3982: -	if iface.Index > 0 {
3983: -		attributes["index"] = strconv.Itoa(iface.Index)
3984: -	}
3985: -	if iface.MTU > 0 {
3986: -		attributes["mtu"] = strconv.Itoa(iface.MTU)
3987: +		"namespace": tracked.lab.Namespace,
3988: +		"lab":       tracked.lab.Name,
3989: +		"node":      tracked.node.Name,
3990: +		"origin":    clabernetesAppValue,
3991:  	}
3992: -	if iface.MAC != "" {
3993: -		attributes["mac"] = iface.MAC
3994: -	}
3995: -	if iface.Alias != "" {
3996: -		attributes["alias"] = iface.Alias
3997: +	if tracked.node.Pod != "" {
3998: +		attributes["pod"] = tracked.node.Pod
3999:  	}
4000:  
4001: -	action := iface.action()
4002: -	if iface.OperState == interfaceStateNotPresent {
4003: -		action = "down"
4004: -	}
4005: +	node := tracked.node
4006:  
4007:  	return clablabruntime.Event{
4008:  		Timestamp:   timestamp,
4009: -		Type:        "interface",
4010: +		Type:        clablabruntime.EventTypeInterface,
4011:  		Action:      action,
4012: -		ActorID:     c9sNodeKey(tracked.namespace, tracked.lab, tracked.node),
4013: -		ActorName:   actorName,
4014: -		ActorFullID: tracked.pod,
4015: +		ActorID:     key,
4016: +		ActorName:   fmt.Sprintf("%s-%s", tracked.lab.Name, tracked.node.Name),
4017: +		ActorFullID: key,
4018:  		Attributes:  attributes,
4019: +		Lab:         tracked.lab,
4020: +		Node:        &node,
4021: +		Interface:   &data,
4022: +	}
4023: +}
4024: +
4025: +// c9sIfaceStatsData computes the counters and rates of a stats event from two samples.
4026: +func c9sIfaceStatsData(previous, current c9sIfaceStatsSample) *clablabruntime.InterfaceStats {
4027: +	interval := current.Timestamp.Sub(previous.Timestamp)
4028: +	if interval <= 0 {
4029: +		interval = time.Second
4030: +	}
4031: +
4032: +	seconds := interval.Seconds()
4033: +	stat := current.Stats
4034: +
4035: +	return &clablabruntime.InterfaceStats{
4036: +		RxBytes:   stat.RxBytes,
4037: +		TxBytes:   stat.TxBytes,
4038: +		RxPackets: stat.RxPackets,
4039: +		TxPackets: stat.TxPackets,
4040: +		RxBps:     float64(counterDelta(stat.RxBytes, previous.Stats.RxBytes)*8) / seconds,
4041: +		TxBps:     float64(counterDelta(stat.TxBytes, previous.Stats.TxBytes)*8) / seconds,
4042: +		RxPps:     float64(counterDelta(stat.RxPackets, previous.Stats.RxPackets)) / seconds,
4043: +		TxPps:     float64(counterDelta(stat.TxPackets, previous.Stats.TxPackets)) / seconds,
4044: +		Interval:  interval,
4045:  	}
4046:  }
4047:  
4048:  // parseInterfaceSample splits the output of interfaceSampleScript into the /proc/net/dev
4049:  // counters and the sysfs interface states. hasStates is false for output without the sysfs
4050: @@ -559,63 +762,10 @@ func c9sNodeKey(namespace, lab, node string) string {
4051:  
4052:  func c9sIfaceStatsKey(namespace, lab, node, ifName string) string {
4053:  	return c9sNodeKey(namespace, lab, node) + "/" + ifName
4054:  }
4055:  
4056: -func c9sIfaceStatsEvent(
4057: -	state *clablabruntime.LabState,
4058: -	node clablabruntime.NodeState,
4059: -	pod *corev1.Pod,
4060: -	stat c9sIfaceStats,
4061: -	previous,
4062: -	current c9sIfaceStatsSample,
4063: -) clablabruntime.Event {
4064: -	interval := current.Timestamp.Sub(previous.Timestamp)
4065: -	if interval <= 0 {
4066: -		interval = time.Second
4067: -	}
4068: -
4069: -	seconds := interval.Seconds()
4070: -	rxBytesDelta := counterDelta(stat.RxBytes, previous.Stats.RxBytes)
4071: -	txBytesDelta := counterDelta(stat.TxBytes, previous.Stats.TxBytes)
4072: -	rxPacketsDelta := counterDelta(stat.RxPackets, previous.Stats.RxPackets)
4073: -	txPacketsDelta := counterDelta(stat.TxPackets, previous.Stats.TxPackets)
4074: -
4075: -	actorName := fmt.Sprintf("%s-%s", state.Name, node.Name)
4076: -	podName := ""
4077: -	if pod != nil {
4078: -		podName = pod.Name
4079: -	}
4080: -
4081: -	return clablabruntime.Event{
4082: -		Timestamp:   current.Timestamp,
4083: -		Type:        "interface",
4084: -		Action:      "stats",
4085: -		ActorID:     c9sNodeKey(state.Namespace, state.Name, node.Name),
4086: -		ActorName:   actorName,
4087: -		ActorFullID: podName,
4088: -		Attributes: map[string]string{
4089: -			"namespace":        state.Namespace,
4090: -			"lab":              state.Name,
4091: -			"node":             node.Name,
4092: -			"name":             actorName,
4093: -			"pod":              podName,
4094: -			"ifname":           stat.Name,
4095: -			"origin":           "clabernetes",
4096: -			"rx_bytes":         strconv.FormatUint(stat.RxBytes, 10),
4097: -			"tx_bytes":         strconv.FormatUint(stat.TxBytes, 10),
4098: -			"rx_packets":       strconv.FormatUint(stat.RxPackets, 10),
4099: -			"tx_packets":       strconv.FormatUint(stat.TxPackets, 10),
4100: -			"rx_bps":           strconv.FormatFloat(float64(rxBytesDelta*8)/seconds, 'f', -1, 64),
4101: -			"tx_bps":           strconv.FormatFloat(float64(txBytesDelta*8)/seconds, 'f', -1, 64),
4102: -			"rx_pps":           strconv.FormatFloat(float64(rxPacketsDelta)/seconds, 'f', -1, 64),
4103: -			"tx_pps":           strconv.FormatFloat(float64(txPacketsDelta)/seconds, 'f', -1, 64),
4104: -			"interval_seconds": strconv.FormatFloat(seconds, 'f', -1, 64),
4105: -		},
4106: -	}
4107: -}
4108: -
4109:  func counterDelta(current, previous uint64) uint64 {
4110:  	if current < previous {
4111:  		return 0
4112:  	}
4113:  
4114: diff --git a/labruntime/clabernetes/manifests.go b/labruntime/clabernetes/manifests.go
4115: index 7d4d36b..8512cab 100644
4116: --- a/labruntime/clabernetes/manifests.go
4117: +++ b/labruntime/clabernetes/manifests.go
4118: @@ -38,10 +38,19 @@ func (r *Runtime) Manifests(
4119:  	prepared, err := prepareDesiredDeployment(ctx, req, namespace)
4120:  	if err != nil {
4121:  		return nil, err
4122:  	}
4123:  
4124: +	// The manifests are applied by other means than this deploy, so they do not carry the path
4125: +	// of the topology file on this machine; such a lab reports where its definition lives.
4126: +	removeTopologySourceFile(prepared.topology)
4127: +	for _, group := range prepared.primitives.groups() {
4128: +		for _, obj := range group.objects {
4129: +			removeTopologySourceFile(obj)
4130: +		}
4131: +	}
4132: +
4133:  	manifests := []clablabruntime.Manifest{}
4134:  
4135:  	// A namespace override must already exist, matching the deploy contract; only the
4136:  	// canonical per-lab namespace is created by containerlab and therefore emitted.
4137:  	if req.Namespace == "" && r.labNamespaceOverride == "" {
4138: diff --git a/labruntime/clabernetes/plan.go b/labruntime/clabernetes/plan.go
4139: index 258bd01..0f0862b 100644
4140: --- a/labruntime/clabernetes/plan.go
4141: +++ b/labruntime/clabernetes/plan.go
4142: @@ -51,10 +51,11 @@ func prepareDesiredDeployment(
4143:  		topologyWithNaming(naming),
4144:  		topologyWithImagePullSecret(req.ImagePullSecret),
4145:  		topologyWithExposeType(exposeType),
4146:  		topologyWithPersistence(!req.NoPersistence),
4147:  	)
4148: +	setTopologySourceFile(desiredTopology, req.TopologyFile)
4149:  	if err := setTopologyFilesFromConfigMaps(desiredTopology, stagedConfigMaps); err != nil {
4150:  		return nil, err
4151:  	}
4152:  	primitives, err := compilePrimitiveResources(desiredTopology)
4153:  	if err != nil {
4154: diff --git a/labruntime/clabernetes/primitives.go b/labruntime/clabernetes/primitives.go
4155: index cc5a59b..f03b288 100644
4156: --- a/labruntime/clabernetes/primitives.go
4157: +++ b/labruntime/clabernetes/primitives.go
4158: @@ -218,10 +218,15 @@ func primitiveObject(
4159:  		// the spec, which the Node schema does not have: the API server prunes them, and
4160:  		// keeping them would make every apply and plan report the Node as changed.
4161:  		unstructured.RemoveNestedField(obj.Object, "spec", "labels")
4162:  	}
4163:  
4164: +	if kind != "Node" {
4165: +		// Only Nodes carry the lab's topology file, which inspect reads without a Topology.
4166: +		removeTopologySourceFile(obj)
4167: +	}
4168: +
4169:  	if owner := desiredTopology.GetAnnotations()[clabconstants.Owner]; owner != "" {
4170:  		annotations := obj.GetAnnotations()
4171:  		if annotations == nil {
4172:  			annotations = map[string]string{}
4173:  		}
4174: diff --git a/labruntime/clabernetes/reconcile.go b/labruntime/clabernetes/reconcile.go
4175: index a4889b5..d9cc952 100644
4176: --- a/labruntime/clabernetes/reconcile.go
4177: +++ b/labruntime/clabernetes/reconcile.go
4178: @@ -195,14 +195,34 @@ func reconciledPrimitiveObject(
4179:  
4180:  	updated.SetLabels(mergeDesiredMetadata(existing.GetLabels(), desired.GetLabels()))
4181:  	updated.SetAnnotations(
4182:  		mergeDesiredMetadata(existing.GetAnnotations(), desired.GetAnnotations()),
4183:  	)
4184: +	carryOverNodeTopologyFile(existing, updated)
4185:  
4186:  	return updated
4187:  }
4188:  
4189: +// carryOverNodeTopologyFile keeps the topology file an existing Node recorded, or its absence.
4190: +// clabernetes copies a Node's annotations into its pod template, so changing the annotation
4191: +// would replace the node's pod although nothing about the node changed. A Node therefore keeps
4192: +// the file the lab was deployed from when the Node was created. The Topology resource has no
4193: +// such effect and always records the file of the latest deploy.
4194: +func carryOverNodeTopologyFile(existing, updated *unstructured.Unstructured) {
4195: +	if existing.GetKind() != "Node" || existing.GetAPIVersion() != c9sAPIVersion {
4196: +		return
4197: +	}
4198: +
4199: +	path, found := existing.GetAnnotations()[annotationTopologyFile]
4200: +	if !found {
4201: +		removeTopologySourceFile(updated)
4202: +		return
4203: +	}
4204: +
4205: +	setTopologySourceFile(updated, path)
4206: +}
4207: +
4208:  // carryOverNodeRunState keeps the run state of an existing Node. spec.runState is operational
4209:  // state that stop and start own, not part of the compiled definition: the compiler never sets
4210:  // it, so replacing the spec would start a stopped node on every apply, and the API default
4211:  // (Running) would otherwise count as drift on every plan. Restart requests live in annotations,
4212:  // which the merge keeps.
4213: diff --git a/labruntime/clabernetes/runtime_gaps_test.go b/labruntime/clabernetes/runtime_gaps_test.go
4214: index aef6f01..1b8d366 100644
4215: --- a/labruntime/clabernetes/runtime_gaps_test.go
4216: +++ b/labruntime/clabernetes/runtime_gaps_test.go
4217: @@ -386,21 +386,12 @@ func TestParseInterfaceSample(t *testing.T) {
4218:  	}
4219:  	if stats[1].Name != "eth1" || stats[1].RxBytes != 2000 || stats[1].TxPackets != 30 {
4220:  		t.Fatalf("eth1 stats = %+v", stats[1])
4221:  	}
4222:  
4223: -	wantActions := map[string]string{"eth1": "up", "eth2": "down", "lo": "up", "dummy0": "down"}
4224: -	for _, state := range states {
4225: -		if got := state.action(); got != wantActions[state.Name] {
4226: -			t.Fatalf(
4227: -				"%s action = %q, want %q (%+v)",
4228: -				state.Name,
4229: -				got,
4230: -				wantActions[state.Name],
4231: -				state,
4232: -			)
4233: -		}
4234: +	if states[1].OperState != "lowerlayerdown" || states[2].OperState != "unknown" {
4235: +		t.Fatalf("operational states = %+v", states)
4236:  	}
4237:  	if states[0].Index != 3 || states[0].MTU != 9500 || states[0].MAC != "aa:c1:ab:00:00:01" ||
4238:  		states[0].Alias != "to server" || states[0].Flags != 0x1003 {
4239:  		t.Fatalf("eth1 state = %+v", states[0])
4240:  	}
4241: @@ -424,131 +415,10 @@ func TestCommandNotExecutable(t *testing.T) {
4242:  	if commandNotExecutable(1, errors.New("connection refused")) {
4243:  		t.Fatal("other failures are not a missing command")
4244:  	}
4245:  }
4246:  
4247: -func TestInterfacePollerEmitsStateChanges(t *testing.T) {
4248: -	t.Parallel()
4249: -
4250: -	newSample := func(ts time.Time, ifaces ...c9sIfaceState) interfaceSample {
4251: -		return interfaceSample{
4252: -			target: interfaceSampleTarget{
4253: -				state: &clablabruntime.LabState{Name: "lab1", Namespace: "c9s-lab1"},
4254: -				node:  clablabruntime.NodeState{Name: "r1", Pod: "lab1-r1-abc"},
4255: -				pod:   &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "lab1-r1-abc"}},
4256: -			},
4257: -			stats: []c9sIfaceStats{
4258: -				{Name: "eth1", RxBytes: uint64(ts.Unix())},
4259: -			},
4260: -			ifaces:    ifaces,
4261: -			hasStates: true,
4262: -			timestamp: ts,
4263: -		}
4264: -	}
4265: -	up := c9sIfaceState{Name: "eth1", Index: 3, MTU: 9500, OperState: "up", Flags: 0x1003}
4266: -	down := c9sIfaceState{Name: "eth1", Index: 3, MTU: 9500, OperState: "down", Flags: 0x1002}
4267: -	eth2 := c9sIfaceState{Name: "eth2", Index: 4, OperState: "up", Flags: 0x1003}
4268: -
4269: -	for _, initialState := range []bool{false, true} {
4270: -		sink := make(chan clablabruntime.Event, 32)
4271: -		p := &interfacePoller{
4272: -			r:            &Runtime{},
4273: -			opts:         interfacePollOptions{includeInitialState: initialState},
4274: -			sink:         sink,
4275: -			statsSamples: map[string]c9sIfaceStatsSample{},
4276: -			nodes:        map[string]*trackedNode{},
4277: -			noShell:      map[string]bool{},
4278: -			firstRound:   true,
4279: -		}
4280: -		ctx := context.Background()
4281: -		start := time.Now()
4282: -
4283: -		p.processSample(ctx, newSample(start, up))
4284: -		if got := drain(sink); initialState != (len(got) == 1) {
4285: -			t.Fatalf("initial-state=%t: first round emitted %+v", initialState, got)
4286: -		}
4287: -
4288: -		p.firstRound = false
4289: -		p.processSample(ctx, newSample(start.Add(time.Second), up))
4290: -		if got := drain(sink); len(got) != 0 {
4291: -			t.Fatalf("unchanged interface emitted %+v", got)
4292: -		}
4293: -
4294: -		p.processSample(ctx, newSample(start.Add(2*time.Second), down, eth2))
4295: -		got := drain(sink)
4296: -		if len(got) != 2 {
4297: -			t.Fatalf("change emitted %+v, want eth1 down and new eth2 up", got)
4298: -		}
4299: -		byIf := map[string]clablabruntime.Event{}
4300: -		for _, ev := range got {
4301: -			byIf[ev.Attributes["ifname"]] = ev
4302: -		}
4303: -		ev := byIf["eth1"]
4304: -		if ev.Type != "interface" || ev.Action != "down" || ev.ActorID != "c9s-lab1/lab1/r1" ||
4305: -			ev.ActorName != "lab1-r1" || ev.ActorFullID != "lab1-r1-abc" ||
4306: -			ev.Attributes["state"] != "down" || ev.Attributes["index"] != "3" ||
4307: -			ev.Attributes["mtu"] != "9500" || ev.Attributes["origin"] != "clabernetes" ||
4308: -			ev.Attributes["lab"] != "lab1" || ev.Attributes["node"] != "r1" ||
4309: -			ev.Attributes["namespace"] != "c9s-lab1" || ev.Attributes["pod"] != "lab1-r1-abc" {
4310: -			t.Fatalf("eth1 event = %+v", ev)
4311: -		}
4312: -		if byIf["eth2"].Action != "up" {
4313: -			t.Fatalf("eth2 event = %+v", byIf["eth2"])
4314: -		}
4315: -
4316: -		// eth2 disappears
4317: -		p.processSample(ctx, newSample(start.Add(3*time.Second), down))
4318: -		got = drain(sink)
4319: -		if len(got) != 1 || got[0].Action != "down" ||
4320: -			got[0].Attributes["state"] != interfaceStateNotPresent {
4321: -			t.Fatalf("removed interface emitted %+v", got)
4322: -		}
4323: -
4324: -		// the node stops running
4325: -		p.retireStoppedNodes(ctx, map[string]bool{})
4326: -		got = drain(sink)
4327: -		if len(got) != 1 || got[0].Attributes["ifname"] != "eth1" ||
4328: -			got[0].Attributes["state"] != interfaceStateNotPresent || len(p.nodes) != 0 {
4329: -			t.Fatalf("stopped node emitted %+v, tracked %+v", got, p.nodes)
4330: -		}
4331: -	}
4332: -}
4333: -
4334: -func TestInterfacePollerStatsUseTheNodeAsActor(t *testing.T) {
4335: -	t.Parallel()
4336: -
4337: -	sink := make(chan clablabruntime.Event, 8)
4338: -	p := &interfacePoller{
4339: -		r:            &Runtime{},
4340: -		opts:         interfacePollOptions{includeStats: true},
4341: -		sink:         sink,
4342: -		statsSamples: map[string]c9sIfaceStatsSample{},
4343: -		nodes:        map[string]*trackedNode{},
4344: -		noShell:      map[string]bool{},
4345: -	}
4346: -	target := interfaceSampleTarget{
4347: -		state: &clablabruntime.LabState{Name: "lab1", Namespace: "c9s-lab1"},
4348: -		node:  clablabruntime.NodeState{Name: "r1", Pod: "lab1-r1-abc"},
4349: -		pod:   &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "lab1-r1-abc"}},
4350: -	}
4351: -	start := time.Now()
4352: -	p.processSample(context.Background(), interfaceSample{
4353: -		target: target, timestamp: start,
4354: -		stats: []c9sIfaceStats{{Name: "eth1", RxBytes: 1000}},
4355: -	})
4356: -	p.processSample(context.Background(), interfaceSample{
4357: -		target: target, timestamp: start.Add(time.Second),
4358: -		stats: []c9sIfaceStats{{Name: "eth1", RxBytes: 2000}},
4359: -	})
4360: -
4361: -	got := drain(sink)
4362: -	if len(got) != 1 || got[0].Action != "stats" || got[0].ActorID != "c9s-lab1/lab1/r1" ||
4363: -		got[0].Attributes["rx_bps"] != "8000" {
4364: -		t.Fatalf("stats events = %+v", got)
4365: -	}
4366: -}
4367: -
4368:  func drain(sink chan clablabruntime.Event) []clablabruntime.Event {
4369:  	var events []clablabruntime.Event
4370:  	for {
4371:  		select {
4372:  		case ev := <-sink:
4373: diff --git a/labruntime/clabernetes/state.go b/labruntime/clabernetes/state.go
4374: index ead2c45..d06385c 100644
4375: --- a/labruntime/clabernetes/state.go
4376: +++ b/labruntime/clabernetes/state.go
4377: @@ -22,10 +22,17 @@ func stateFromNodeResources(
4378:  	state := &clablabruntime.LabState{
4379:  		Name:         name,
4380:  		Namespace:    namespace,
4381:  		TopologyPath: fmt.Sprintf("k8s://%s/labs/%s", namespace, name),
4382:  	}
4383: +	// Without a Topology resource the Nodes record the file the lab was deployed from.
4384: +	for idx := range nodeResources {
4385: +		if path := nodeResources[idx].GetAnnotations()[annotationTopologyFile]; path != "" {
4386: +			state.TopologyPath = path
4387: +			break
4388: +		}
4389: +	}
4390:  	if len(nodeResources) != 0 {
4391:  		state.Owner = nodeResources[0].GetLabels()[clabconstants.Owner]
4392:  		if state.Owner == "" {
4393:  			state.Owner = nodeResources[0].GetAnnotations()[clabconstants.Owner]
4394:  		}
4395: @@ -42,15 +49,20 @@ func stateFromNodeResources(

(Output capped at 50 KB. Showing lines 2845-4395. Use offset=4396 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19674e4b8001BKT4O5PFhvBA1l",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674db1a001T4BNzcGimXgvil",
  "callID": "call_6d3e53c8495145129c18674e",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "offset": 2845
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n2845: +\t\t[]*unstructured.Unstructured{\n2846: +\t\t\ttrackerTestNode(\"r1\", nodeRunStateRunning, condition(\"Ready\", \"True\")),\n2847: +\t\t\t// its peer is stopped: not ready, but the device is\n2848: +\t\t\ttrackerTestNode(\"r2\", nodeRunStateRunning,\n2849: +\t\t\t\tcondition(nodeConditionContainersReady, \"True\")),\n2850: +\t\t\ttrackerTestNode(\"r3\", nodeRunStateRunning),\n2851: +\t\t\ttrackerTestNode(\"r4\", nodeRunStateStopped, condition(nodeConditionStopped, \"True\")),\n2852: +\t\t},\n2853: +\t\t[]k8sruntime.Object{\n2854: +\t\t\tcaptureTestPod(\"lab1-r1-a\", \"r1\"),\n2855: +\t\t\tcaptureTestPod(\"lab1-r2-a\", \"r2\"),\n2856: +\t\t\twithNodeUID(captureTestPod(\"lab1-r3-a\", \"r3\"), \"uid-r3\"),\n2857: +\t\t\t// the newer pod of an earlier Node r3 that still terminates is not r3's pod\n2858: +\t\t\twithNodeUID(withCreation(captureTestPod(\"lab1-r3-stale\", \"r3\"), time.Hour), \"uid-old\"),\n2859: +\t\t},\n2860: +\t)\n2861: +\n2862: +\tstate := &clablabruntime.LabState{Name: \"lab1\", Namespace: \"lab-ns\"}\n2863: +\tif err := r.enrichState(context.Background(), state); err != nil {\n2864: +\t\tt.Fatal(err)\n2865: +\t}\n2866: +\n2867: +\twant := map[string]string{\n2868: +\t\t\"r1\": \"running/healthy\", \"r2\": \"running/healthy\", \"r3\": \"running/starting\", \"r4\": \"exited/\",\n2869: +\t}\n2870: +\tfor _, node := range state.Nodes {\n2871: +\t\tif node.Name == \"r3\" && node.Pod != \"lab1-r3-a\" {\n2872: +\t\t\tt.Fatalf(\"r3 pod = %q, want its own Node's pod\", node.Pod)\n2873: +\t\t}\n2874: +\t\tif got := node.ContainerState + \"/\" + node.Health; got != want[node.Name] {\n2875: +\t\t\tt.Fatalf(\"%s = %s, want %s\", node.Name, got, want[node.Name])\n2876: +\t\t}\n2877: +\t\tif node.TopologyName != strings.ToUpper(node.Name) {\n2878: +\t\t\tt.Fatalf(\"%s topology name = %q\", node.Name, node.TopologyName)\n2879: +\t\t}\n2880: +\t}\n2881: +}\n2882: +\n2883: +const sourceDefinition = `name: lab1\n2884: +topology:\n2885: +  nodes:\n2886: +    node1:\n2887: +      kind: linux\n2888: +      image: alpine:latest\n2889: +    node2:\n2890: +      kind: linux\n2891: +      image: alpine:latest\n2892: +  links:\n2893: +    - endpoints: [\"node1:eth1\", \"node2:eth1\"]\n2894: +`\n2895: +\n2896: +func sourceDeployRequest(path string, noTopologyCR bool) clablabruntime.DeployRequest {\n2897: +\treturn clablabruntime.DeployRequest{\n2898: +\t\tName:               \"lab1\",\n2899: +\t\tNamespace:          \"lab-ns\",\n2900: +\t\tTopologyFile:       path,\n2901: +\t\tTopologyDefinition: []byte(sourceDefinition),\n2902: +\t\tNoTopologyCR:       noTopologyCR,\n2903: +\t}\n2904: +}\n2905: +\n2906: +// TestDeployRecordsTheTopologyFile checks where a deploy records the topology file and that\n2907: +// inspect reports it, with and without a Topology resource.\n2908: +func TestDeployRecordsTheTopologyFile(t *testing.T) {\n2909: +\tt.Parallel()\n2910: +\n2911: +\t// with a Topology resource: on the Topology, updated by every deploy\n2912: +\tr := newTestRuntime()\n2913: +\tif _, err := r.Deploy(context.Background(),\n2914: +\t\tsourceDeployRequest(\"/home/alice/labs/lab1.clab.yml\", false)); err != nil {\n2915: +\t\tt.Fatal(err)\n2916: +\t}\n2917: +\ttopology := getTestTopology(t, r, \"lab-ns\", \"lab1\")\n2918: +\tif got := topology.GetAnnotations()[annotationTopologyFile]; got != \"/home/alice/labs/lab1.clab.yml\" {\n2919: +\t\tt.Fatalf(\"Topology annotation = %q\", got)\n2920: +\t}\n2921: +\tstate, err := r.Inspect(context.Background(),\n2922: +\t\tclablabruntime.InspectRequest{Name: \"lab1\", Namespace: \"lab-ns\"})\n2923: +\tif err != nil {\n2924: +\t\tt.Fatal(err)\n2925: +\t}\n2926: +\tif state.TopologyPath != \"/home/alice/labs/lab1.clab.yml\" {\n2927: +\t\tt.Fatalf(\"TopologyPath = %q\", state.TopologyPath)\n2928: +\t}\n2929: +\n2930: +\tif _, err := r.Deploy(context.Background(),\n2931: +\t\tsourceDeployRequest(\"/srv/labs/lab1.clab.yml\", false)); err != nil {\n2932: +\t\tt.Fatal(err)\n2933: +\t}\n2934: +\ttopology = getTestTopology(t, r, \"lab-ns\", \"lab1\")\n2935: +\tif got := topology.GetAnnotations()[annotationTopologyFile]; got != \"/srv/labs/lab1.clab.yml\" {\n2936: +\t\tt.Fatalf(\"Topology annotation after a deploy from another file = %q\", got)\n2937: +\t}\n2938: +\n2939: +\t// without a Topology resource: on the Nodes only, kept from their creation\n2940: +\tr = newTestRuntime()\n2941: +\tif _, err := r.Deploy(context.Background(),\n2942: +\t\tsourceDeployRequest(\"/home/alice/labs/lab1.clab.yml\", true)); err != nil {\n2943: +\t\tt.Fatal(err)\n2944: +\t}\n2945: +\tassertPrimitiveTopologyFile(t, r, \"/home/alice/labs/lab1.clab.yml\")\n2946: +\tstate, err = r.Inspect(context.Background(),\n2947: +\t\tclablabruntime.InspectRequest{Name: \"lab1\", Namespace: \"lab-ns\"})\n2948: +\tif err != nil {\n2949: +\t\tt.Fatal(err)\n2950: +\t}\n2951: +\tif state.TopologyPath != \"/home/alice/labs/lab1.clab.yml\" {\n2952: +\t\tt.Fatalf(\"TopologyPath without a Topology = %q\", state.TopologyPath)\n2953: +\t}\n2954: +\n2955: +\tplan, err := r.Plan(context.Background(),\n2956: +\t\tsourceDeployRequest(\"/srv/labs/lab1.clab.yml\", true))\n2957: +\tif err != nil {\n2958: +\t\tt.Fatal(err)\n2959: +\t}\n2960: +\tfor _, change := range plan.Changes {\n2961: +\t\tif change.Kind == \"Node\" {\n2962: +\t\t\tt.Fatalf(\"a deploy from another file would change %+v and replace its pod\", change)\n2963: +\t\t}\n2964: +\t}\n2965: +\tif _, err := r.Deploy(context.Background(),\n2966: +\t\tsourceDeployRequest(\"/srv/labs/lab1.clab.yml\", true)); err != nil {\n2967: +\t\tt.Fatal(err)\n2968: +\t}\n2969: +\tassertPrimitiveTopologyFile(t, r, \"/home/alice/labs/lab1.clab.yml\")\n2970: +}\n2971: +\n2972: +func assertPrimitiveTopologyFile(t *testing.T, r *Runtime, want string) {\n2973: +\tt.Helper()\n2974: +\n2975: +\tfor _, gvr := range []struct {\n2976: +\t\tname string\n2977: +\t\twant string\n2978: +\t}{{\"nodes\", want}, {\"links\", \"\"}, {\"nodeprofiles\", \"\"}} {\n2979: +\t\tresource := nodeGVR\n2980: +\t\tswitch gvr.name {\n2981: +\t\tcase \"links\":\n2982: +\t\t\tresource = linkGVR\n2983: +\t\tcase \"nodeprofiles\":\n2984: +\t\t\tresource = nodeProfileGVR\n2985: +\t\t}\n2986: +\t\tlist, err := r.client.Resource(resource).Namespace(\"lab-ns\").\n2987: +\t\t\tList(context.Background(), metav1.ListOptions{})\n2988: +\t\tif err != nil {\n2989: +\t\t\tt.Fatal(err)\n2990: +\t\t}\n2991: +\t\tfor idx := range list.Items {\n2992: +\t\t\tif got := list.Items[idx].GetAnnotations()[annotationTopologyFile]; got != gvr.want {\n2993: +\t\t\t\tt.Fatalf(\"%s %s annotation = %q, want %q\", gvr.name, list.Items[idx].GetName(),\n2994: +\t\t\t\t\tgot, gvr.want)\n2995: +\t\t\t}\n2996: +\t\t}\n2997: +\t}\n2998: +}\n2999: +\n3000: +func TestCarryOverNodeTopologyFile(t *testing.T) {\n3001: +\tt.Parallel()\n3002: +\n3003: +\tnode := func(annotations map[string]any) *unstructured.Unstructured {\n3004: +\t\tmetadata := map[string]any{\"name\": \"node1\"}\n3005: +\t\tif annotations != nil {\n3006: +\t\t\tmetadata[\"annotations\"] = annotations\n3007: +\t\t}\n3008: +\n3009: +\t\treturn &unstructured.Unstructured{Object: map[string]any{\n3010: +\t\t\t\"apiVersion\": c9sAPIVersion, \"kind\": \"Node\", \"metadata\": metadata,\n3011: +\t\t\t\"spec\": map[string]any{\"image\": \"alpine\"},\n3012: +\t\t}}\n3013: +\t}\n3014: +\tdesired := node(map[string]any{annotationTopologyFile: \"/new.clab.yml\"})\n3015: +\n3016: +\tupdated := reconciledPrimitiveObject(\n3017: +\t\tnode(map[string]any{annotationTopologyFile: \"/old.clab.yml\"}),\n3018: +\t\tdesired,\n3019: +\t)\n3020: +\tif got := updated.GetAnnotations()[annotationTopologyFile]; got != \"/old.clab.yml\" {\n3021: +\t\tt.Fatalf(\"existing Node file = %q, want it kept\", got)\n3022: +\t}\n3023: +\n3024: +\t// a Node deployed before containerlab recorded files does not get one\n3025: +\texisting := node(nil)\n3026: +\tupdated = reconciledPrimitiveObject(existing, desired)\n3027: +\tif _, ok := updated.GetAnnotations()[annotationTopologyFile]; ok ||\n3028: +\t\t!primitiveObjectsConform(existing, updated) {\n3029: +\t\tt.Fatalf(\"Node without a file = %+v\", updated.GetAnnotations())\n3030: +\t}\n3031: +\n3032: +\t// the Topology always records the latest file\n3033: +\ttopology := topologyObject(\"lab1\", \"lab-ns\", \"\", \"topology:\\n\")\n3034: +\tsetTopologySourceFile(topology, \"/old.clab.yml\")\n3035: +\tnewTopology := topologyObject(\"lab1\", \"lab-ns\", \"\", \"topology:\\n\")\n3036: +\tsetTopologySourceFile(newTopology, \"/new.clab.yml\")\n3037: +\tupdated = reconciledPrimitiveObject(topology, newTopology)\n3038: +\tif got := updated.GetAnnotations()[annotationTopologyFile]; got != \"/new.clab.yml\" {\n3039: +\t\tt.Fatalf(\"Topology file = %q\", got)\n3040: +\t}\n3041: +}\n3042: +\n3043: +func TestManifestsCarryNoTopologyFile(t *testing.T) {\n3044: +\tt.Parallel()\n3045: +\n3046: +\tfor _, noTopologyCR := range []bool{false, true} {\n3047: +\t\tmanifests, err := (&Runtime{}).Manifests(context.Background(),\n3048: +\t\t\tsourceDeployRequest(\"/home/alice/labs/lab1.clab.yml\", noTopologyCR))\n3049: +\t\tif err != nil {\n3050: +\t\t\tt.Fatal(err)\n3051: +\t\t}\n3052: +\t\tfor _, manifest := range manifests {\n3053: +\t\t\tdata, _ := json.Marshal(manifest.Object)\n3054: +\t\t\tif strings.Contains(string(data), annotationTopologyFile) {\n3055: +\t\t\t\tt.Fatalf(\"no-topology-cr=%t: %s %s carries the file\", noTopologyCR,\n3056: +\t\t\t\t\tmanifest.Kind, manifest.Name)\n3057: +\t\t\t}\n3058: +\t\t}\n3059: +\t}\n3060: +}\n3061: +\n3062: +func TestStateReportsTheRecordedTopologyFile(t *testing.T) {\n3063: +\tt.Parallel()\n3064: +\n3065: +\ttopology := topologyObject(\"lab1\", \"lab-ns\", \"\", \"topology:\\n\")\n3066: +\tif got := stateFromTopology(\n3067: +\t\ttopology,\n3068: +\t\t\"lab-ns\",\n3069: +\t).TopologyPath; got != \"k8s://lab-ns/topologies/lab1\" {\n3070: +\t\tt.Fatalf(\"lab created by other means = %q\", got)\n3071: +\t}\n3072: +\tsetTopologySourceFile(topology, \"/home/alice/lab1.clab.yml\")\n3073: +\tif got := stateFromTopology(\n3074: +\t\ttopology,\n3075: +\t\t\"lab-ns\",\n3076: +\t).TopologyPath; got != \"/home/alice/lab1.clab.yml\" {\n3077: +\t\tt.Fatalf(\"deployed lab = %q\", got)\n3078: +\t}\n3079: +\n3080: +\tnodes := []unstructured.Unstructured{*trackerTestNode(\"r1\", nodeRunStateRunning)}\n3081: +\tif got := stateFromNodeResources(\"lab1\", \"lab-ns\", nodes).TopologyPath; got !=\n3082: +\t\t\"k8s://lab-ns/labs/lab1\" {\n3083: +\t\tt.Fatalf(\"Nodes created by other means = %q\", got)\n3084: +\t}\n3085: +\tnodes[0].SetAnnotations(map[string]string{annotationTopologyFile: \"/home/alice/lab1.clab.yml\"})\n3086: +\tif got := stateFromNodeResources(\"lab1\", \"lab-ns\", nodes).TopologyPath; got !=\n3087: +\t\t\"/home/alice/lab1.clab.yml\" {\n3088: +\t\tt.Fatalf(\"deployed Nodes = %q\", got)\n3089: +\t}\n3090: +}\n3091: +\n3092: +func withNodeUID(pod *corev1.Pod, uid string) *corev1.Pod {\n3093: +\tif pod.Annotations == nil {\n3094: +\t\tpod.Annotations = map[string]string{}\n3095: +\t}\n3096: +\tpod.Annotations[annotationDirectNodeUID] = uid\n3097: +\n3098: +\treturn pod\n3099: +}\n3100: +\n3101: +func withCreation(pod *corev1.Pod, age time.Duration) *corev1.Pod {\n3102: +\tpod.CreationTimestamp = metav1.NewTime(time.Now().Add(age))\n3103: +\n3104: +\treturn pod\n3105: +}\n3106: diff --git a/labruntime/clabernetes/events.go b/labruntime/clabernetes/events.go\n3107: index 37548dc..b06dc9d 100644\n3108: --- a/labruntime/clabernetes/events.go\n3109: +++ b/labruntime/clabernetes/events.go\n3110: @@ -30,31 +30,49 @@ func (r *Runtime) StreamEvents(\n3111:  \tif err != nil {\n3112:  \t\treturn nil, nil, err\n3113:  \t}\n3114:  \n3115:  \tevents := make(chan clablabruntime.Event, 128)\n3116: -\terrs := make(chan error, 3)\n3117: +\terrs := make(chan error, 4)\n3118: +\t// changed carries the labs whose Topology, Nodes or pods changed; the container tracker\n3119: +\t// reads them again and reports what changed for their nodes.\n3120: +\tchanged := make(chan labRef, 256)\n3121:  \n3122: -\tif req.IncludeInitialState {\n3123: -\t\tgo r.emitInitialEvents(ctx, scope, events, errs)\n3124: -\t}\n3125: +\tgo r.trackContainers(ctx, scope, req.IncludeInitialState, changed, events, errs)\n3126:  \n3127:  \t// Interface state events are always reported, like the netlink-backed events of the local\n3128:  \t// runtimes; statistics only on request. Both come from the same exec per node.\n3129:  \tgo r.pollInterfaces(ctx, scope, interfacePollOptions{\n3130:  \t\tinterval:            req.StatsInterval,\n3131:  \t\tincludeStats:        req.IncludeInterfaceStats,\n3132:  \t\tincludeInitialState: req.IncludeInitialState,\n3133:  \t}, events)\n3134:  \n3135: -\tgo r.watchTopologies(ctx, scope, events, errs)\n3136: -\tgo r.watchNodes(ctx, scope, events, errs)\n3137: -\tgo r.watchPods(ctx, scope, events, errs)\n3138: +\tgo r.watchTopologies(ctx, scope, changed, events, errs)\n3139: +\tgo r.watchNodes(ctx, scope, changed, errs)\n3140: +\tgo r.watchPods(ctx, scope, changed, errs)\n3141:  \n3142:  \treturn events, errs, nil\n3143:  }\n3144:  \n3145: +// labRef names a lab in a namespace.\n3146: +type labRef struct {\n3147: +\tnamespace string\n3148: +\tlab       string\n3149: +}\n3150: +\n3151: +func sendChangedLab(ctx context.Context, changed chan<- labRef, ref labRef) {\n3152: +\tif ref.lab == \"\" {\n3153: +\t\treturn\n3154: +\t}\n3155: +\n3156: +\tselect {\n3157: +\tcase changed <- ref:\n3158: +\tcase <-ctx.Done():\n3159: +\t}\n3160: +}\n3161: +\n3162:  // eventScope is the namespace and, optionally, the single lab an event stream covers.\n3163:  type eventScope struct {\n3164:  \tnamespace string\n3165:  \tlab       string\n3166:  }\n3167: @@ -123,11 +141,11 @@ func (r *Runtime) labStates(\n3168:  }\n3169:  \n3170:  func (r *Runtime) watchNodes(\n3171:  \tctx context.Context,\n3172:  \tscope eventScope,\n3173: -\teventSink chan<- clablabruntime.Event,\n3174: +\tchanged chan<- labRef,\n3175:  \terrSink chan<- error,\n3176:  ) {\n3177:  \tresource := r.client.Resource(nodeGVR).Namespace(scope.namespace)\n3178:  \n3179:  \tfor {\n3180: @@ -141,24 +159,25 @@ func (r *Runtime) watchNodes(\n3181:  \n3182:  \t\t\tsendEventError(ctx, errSink, fmt.Errorf(\"failed to watch c9s nodes: %w\", err))\n3183:  \t\t\treturn\n3184:  \t\t}\n3185:  \n3186: -\t\tif !r.forwardNodeWatch(ctx, watcher, eventSink, errSink) {\n3187: +\t\tif !r.forwardNodeWatch(ctx, watcher, changed, errSink) {\n3188:  \t\t\treturn\n3189:  \t\t}\n3190:  \n3191:  \t\tif !sleepContext(ctx, pollInterval) {\n3192:  \t\t\treturn\n3193:  \t\t}\n3194:  \t}\n3195:  }\n3196:  \n3197: +// forwardNodeWatch reports the lab of every changed Node to the container tracker.\n3198:  func (r *Runtime) forwardNodeWatch(\n3199:  \tctx context.Context,\n3200:  \twatcher watch.Interface,\n3201: -\teventSink chan<- clablabruntime.Event,\n3202: +\tchanged chan<- labRef,\n3203:  \terrSink chan<- error,\n3204:  ) bool {\n3205:  \tdefer watcher.Stop()\n3206:  \n3207:  \tfor {\n3208: @@ -178,73 +197,22 @@ func (r *Runtime) forwardNodeWatch(\n3209:  \t\t\tnode, ok := ev.Object.(*unstructured.Unstructured)\n3210:  \t\t\tif !ok {\n3211:  \t\t\t\tcontinue\n3212:  \t\t\t}\n3213:  \n3214: -\t\t\tlabName := node.GetLabels()[labelTopologyOwner]\n3215: -\t\t\tif labName == \"\" {\n3216: -\t\t\t\tcontinue\n3217: -\t\t\t}\n3218: -\t\t\treadiness, _, _ := unstructured.NestedString(node.Object, \"status\", \"readiness\")\n3219: -\t\t\tr.sendEvent(ctx, eventSink, clablabruntime.Event{\n3220: -\t\t\t\tTimestamp: time.Now(),\n3221: -\t\t\t\tType:      \"container\",\n3222: -\t\t\t\tAction:    strings.ToLower(string(ev.Type)),\n3223: -\t\t\t\tActorID:   fmt.Sprintf(\"%s/%s/%s\", node.GetNamespace(), labName, node.GetName()),\n3224: -\t\t\t\tActorName: fmt.Sprintf(\"%s-%s\", labName, node.GetName()),\n3225: -\t\t\t\tAttributes: map[string]string{\n3226: -\t\t\t\t\t\"namespace\": node.GetNamespace(),\n3227: -\t\t\t\t\t\"lab\":       labName,\n3228: -\t\t\t\t\t\"node\":      node.GetName(),\n3229: -\t\t\t\t\t\"state\":     readiness,\n3230: -\t\t\t\t},\n3231: -\t\t\t})\n3232: -\t\t}\n3233: -\t}\n3234: -}\n3235: -\n3236: -func (r *Runtime) emitInitialEvents(\n3237: -\tctx context.Context,\n3238: -\tscope eventScope,\n3239: -\teventSink chan<- clablabruntime.Event,\n3240: -\terrSink chan<- error,\n3241: -) {\n3242: -\tstates, err := r.labStates(ctx, scope)\n3243: -\tif err != nil {\n3244: -\t\tsendEventError(ctx, errSink, err)\n3245: -\t\treturn\n3246: -\t}\n3247: -\n3248: -\tfor _, state := range states {\n3249: -\t\tfor _, node := range state.Nodes {\n3250: -\t\t\taction := node.State\n3251: -\t\t\tif node.Ready {\n3252: -\t\t\t\taction = \"running\"\n3253: -\t\t\t}\n3254: -\t\t\tif action == \"\" {\n3255: -\t\t\t\taction = state.State\n3256: -\t\t\t}\n3257: -\t\t\tr.sendEvent(ctx, eventSink, clablabruntime.Event{\n3258: -\t\t\t\tTimestamp: time.Now(),\n3259: -\t\t\t\tType:      \"container\",\n3260: -\t\t\t\tAction:    action,\n3261: -\t\t\t\tActorID:   fmt.Sprintf(\"%s/%s/%s\", state.Namespace, state.Name, node.Name),\n3262: -\t\t\t\tActorName: fmt.Sprintf(\"%s-%s\", state.Name, node.Name),\n3263: -\t\t\t\tAttributes: map[string]string{\n3264: -\t\t\t\t\t\"namespace\": state.Namespace,\n3265: -\t\t\t\t\t\"lab\":       state.Name,\n3266: -\t\t\t\t\t\"node\":      node.Name,\n3267: -\t\t\t\t\t\"state\":     node.State,\n3268: -\t\t\t\t},\n3269: +\t\t\tsendChangedLab(ctx, changed, labRef{\n3270: +\t\t\t\tnamespace: node.GetNamespace(),\n3271: +\t\t\t\tlab:       node.GetLabels()[labelTopologyOwner],\n3272:  \t\t\t})\n3273:  \t\t}\n3274:  \t}\n3275:  }\n3276:  \n3277:  func (r *Runtime) watchTopologies(\n3278:  \tctx context.Context,\n3279:  \tscope eventScope,\n3280: +\tchanged chan<- labRef,\n3281:  \teventSink chan<- clablabruntime.Event,\n3282:  \terrSink chan<- error,\n3283:  ) {\n3284:  \tresource := r.client.Resource(topologyGVR).Namespace(scope.namespace)\n3285:  \n3286: @@ -261,24 +229,27 @@ func (r *Runtime) watchTopologies(\n3287:  \t\t\t\tfmt.Errorf(\"failed to watch clabernetes topologies: %w\", err),\n3288:  \t\t\t)\n3289:  \t\t\treturn\n3290:  \t\t}\n3291:  \n3292: -\t\tif !r.forwardTopologyWatch(ctx, scope.namespace, watcher, eventSink, errSink) {\n3293: +\t\tif !r.forwardTopologyWatch(ctx, scope.namespace, watcher, changed, eventSink, errSink) {\n3294:  \t\t\treturn\n3295:  \t\t}\n3296:  \n3297:  \t\tif !sleepContext(ctx, pollInterval) {\n3298:  \t\t\treturn\n3299:  \t\t}\n3300:  \t}\n3301:  }\n3302:  \n3303: +// forwardTopologyWatch reports Topology changes as topology events, which only c9s has, and\n3304: +// reports the lab to the container tracker.\n3305:  func (r *Runtime) forwardTopologyWatch(\n3306:  \tctx context.Context,\n3307:  \tnamespace string,\n3308:  \twatcher watch.Interface,\n3309: +\tchanged chan<- labRef,\n3310:  \teventSink chan<- clablabruntime.Event,\n3311:  \terrSink chan<- error,\n3312:  ) bool {\n3313:  \tdefer watcher.Stop()\n3314:  \n3315: @@ -317,18 +288,19 @@ func (r *Runtime) forwardTopologyWatch(\n3316:  \t\t\t\t\t\"lab\":       state.Name,\n3317:  \t\t\t\t\t\"state\":     state.State,\n3318:  \t\t\t\t\t\"ready\":     fmt.Sprintf(\"%t\", state.Ready),\n3319:  \t\t\t\t},\n3320:  \t\t\t})\n3321: +\t\t\tsendChangedLab(ctx, changed, labRef{namespace: state.Namespace, lab: state.Name})\n3322:  \t\t}\n3323:  \t}\n3324:  }\n3325:  \n3326:  func (r *Runtime) watchPods(\n3327:  \tctx context.Context,\n3328:  \tscope eventScope,\n3329: -\teventSink chan<- clablabruntime.Event,\n3330: +\tchanged chan<- labRef,\n3331:  \terrSink chan<- error,\n3332:  ) {\n3333:  \tfor {\n3334:  \t\twatcher, err := r.kubeClient.CoreV1().Pods(scope.namespace).Watch(ctx, metav1.ListOptions{\n3335:  \t\t\tLabelSelector: scope.labelSelector(),\n3336: @@ -341,24 +313,25 @@ func (r *Runtime) watchPods(\n3337:  \t\t\tsendEventError(ctx, errSink, fmt.Errorf(\n3338:  \t\t\t\t\"failed to watch clabernetes pods: %w\", err))\n3339:  \t\t\treturn\n3340:  \t\t}\n3341:  \n3342: -\t\tif !r.forwardPodWatch(ctx, watcher, eventSink, errSink) {\n3343: +\t\tif !r.forwardPodWatch(ctx, watcher, changed, errSink) {\n3344:  \t\t\treturn\n3345:  \t\t}\n3346:  \n3347:  \t\tif !sleepContext(ctx, pollInterval) {\n3348:  \t\t\treturn\n3349:  \t\t}\n3350:  \t}\n3351:  }\n3352:  \n3353: +// forwardPodWatch reports the lab of every changed pod to the container tracker.\n3354:  func (r *Runtime) forwardPodWatch(\n3355:  \tctx context.Context,\n3356:  \twatcher watch.Interface,\n3357: -\teventSink chan<- clablabruntime.Event,\n3358: +\tchanged chan<- labRef,\n3359:  \terrSink chan<- error,\n3360:  ) bool {\n3361:  \tdefer watcher.Stop()\n3362:  \n3363:  \tfor {\n3364: @@ -379,31 +352,13 @@ func (r *Runtime) forwardPodWatch(\n3365:  \t\t\tpod, ok := ev.Object.(*corev1.Pod)\n3366:  \t\t\tif !ok {\n3367:  \t\t\t\tcontinue\n3368:  \t\t\t}\n3369:  \n3370: -\t\t\tlabName := pod.Labels[labelTopologyOwner]\n3371: -\t\t\tnodeName := pod.Labels[labelTopologyNode]\n3372: -\t\t\tif labName == \"\" || nodeName == \"\" {\n3373: -\t\t\t\tcontinue\n3374: -\t\t\t}\n3375: -\n3376: -\t\t\tr.sendEvent(ctx, eventSink, clablabruntime.Event{\n3377: -\t\t\t\tTimestamp:   time.Now(),\n3378: -\t\t\t\tType:        \"container\",\n3379: -\t\t\t\tAction:      strings.ToLower(string(ev.Type)),\n3380: -\t\t\t\tActorID:     fmt.Sprintf(\"%s/%s/%s\", pod.Namespace, labName, nodeName),\n3381: -\t\t\t\tActorName:   fmt.Sprintf(\"%s-%s\", labName, nodeName),\n3382: -\t\t\t\tActorFullID: pod.Name,\n3383: -\t\t\t\tAttributes: map[string]string{\n3384: -\t\t\t\t\t\"namespace\": pod.Namespace,\n3385: -\t\t\t\t\t\"lab\":       labName,\n3386: -\t\t\t\t\t\"node\":      nodeName,\n3387: -\t\t\t\t\t\"pod\":       pod.Name,\n3388: -\t\t\t\t\t\"phase\":     string(pod.Status.Phase),\n3389: -\t\t\t\t\t\"pod_ip\":    pod.Status.PodIP,\n3390: -\t\t\t\t},\n3391: +\t\t\tsendChangedLab(ctx, changed, labRef{\n3392: +\t\t\t\tnamespace: pod.Namespace,\n3393: +\t\t\t\tlab:       pod.Labels[labelTopologyOwner],\n3394:  \t\t\t})\n3395:  \t\t}\n3396:  \t}\n3397:  }\n3398:  \n3399: diff --git a/labruntime/clabernetes/iface_stats.go b/labruntime/clabernetes/iface_stats.go\n3400: index 09abca3..a6c72b0 100644\n3401: --- a/labruntime/clabernetes/iface_stats.go\n3402: +++ b/labruntime/clabernetes/iface_stats.go\n3403: @@ -1,10 +1,11 @@\n3404:  package clabernetes\n3405:  \n3406:  import (\n3407:  \t\"context\"\n3408:  \t\"fmt\"\n3409: +\t\"sort\"\n3410:  \t\"strconv\"\n3411:  \t\"strings\"\n3412:  \t\"sync\"\n3413:  \t\"time\"\n3414:  \n3415: @@ -28,16 +29,31 @@ const (\n3416:  \t\t`\"$(cat \"$d/flags\")\" \"$(cat \"$d/ifalias\")\"; done 2>/dev/null`\n3417:  \n3418:  \t// interfaceSampleWorkers bounds the concurrent execs of one sampling round.\n3419:  \tinterfaceSampleWorkers = 16\n3420:  \n3421: -\t// interfaceStateNotPresent is the operational state reported for an interface that\n3422: -\t// disappeared, or whose node stopped running (RFC 2863 \"notPresent\").\n3423: -\tinterfaceStateNotPresent = \"notpresent\"\n3424: -\n3425: -\t// iffUp is the IFF_UP bit of /sys/class/net/<if>/flags.\n3426: -\tiffUp = 0x1\n3427: +\t// managementInterface is a node's management interface in its pod, the interface the\n3428: +\t// clabernetes planner gives the management address by default. It has the name the\n3429: +\t// management interface has in a container of the local runtimes.\n3430: +\tmanagementInterface = \"eth0\"\n3431: +\t// loopbackInterface is reported like the local runtimes report it.\n3432: +\tloopbackInterface = \"lo\"\n3433: +\t// clabernetesAliasPrefix starts the interface aliases clabernetes marks its own interfaces\n3434: +\t// and the lab links it wires with. They are not the topology's names, so they are not\n3435: +\t// reported.\n3436: +\tclabernetesAliasPrefix = \"c9s:\"\n3437: +\t// zeroMAC is the hardware address sysfs reports for interfaces without one (loopback).\n3438: +\tzeroMAC = \"00:00:00:00:00:00\"\n3439: +\n3440: +\t// Interface event actions and link types, as the local runtimes report them.\n3441: +\tinterfaceActionSnapshot = \"snapshot\"\n3442: +\tinterfaceActionCreate   = \"create\"\n3443: +\tinterfaceActionUpdate   = \"update\"\n3444: +\tinterfaceActionDelete   = \"delete\"\n3445: +\tinterfaceActionStats    = \"stats\"\n3446: +\tinterfaceTypeVeth       = \"veth\"\n3447: +\tinterfaceTypeDevice     = \"device\"\n3448:  \n3449:  \t// shell exit codes of a command that cannot be found or executed.\n3450:  \texitCommandNotExecutable = 126\n3451:  \texitCommandNotFound      = 127\n3452:  )\n3453: @@ -70,35 +86,16 @@ type c9sIfaceState struct {\n3454:  \tOperState string\n3455:  \tFlags     uint64\n3456:  \tAlias     string\n3457:  }\n3458:  \n3459: -// action maps the interface state onto the up/down action of interface state events. An\n3460: -// \"unknown\" operational state (loopback, tunnels) counts as up when the interface is\n3461: -// administratively up.\n3462: -func (s c9sIfaceState) action() string {\n3463: -\tif s.OperState == \"up\" || (s.OperState == \"unknown\" && s.Flags&iffUp != 0) {\n3464: -\t\treturn \"up\"\n3465: -\t}\n3466: -\n3467: -\treturn \"down\"\n3468: -}\n3469: -\n3470: -// trackedIface is the last reported state of an interface.\n3471: -type trackedIface struct {\n3472: -\tstate  c9sIfaceState\n3473: -\taction string\n3474: -}\n3475: -\n3476: -// trackedNode remembers the interfaces last reported for a node, so their removal can be\n3477: -// reported when the node stops running.\n3478: +// trackedNode remembers the interfaces last reported for a node, so their changes and their\n3479: +// removal can be reported, also when the node stops running.\n3480:  type trackedNode struct {\n3481: -\tnamespace string\n3482: -\tlab       string\n3483: -\tnode      string\n3484: -\tpod       string\n3485: -\tifaces    map[string]trackedIface\n3486: +\tlab    *clablabruntime.LabState\n3487: +\tnode   clablabruntime.NodeState\n3488: +\tifaces map[string]clablabruntime.InterfaceEventData\n3489:  }\n3490:  \n3491:  type interfaceSampleTarget struct {\n3492:  \tstate *clablabruntime.LabState\n3493:  \tnode  clablabruntime.NodeState\n3494: @@ -108,16 +105,28 @@ type interfaceSampleTarget struct {\n3495:  type interfaceSample struct {\n3496:  \ttarget    interfaceSampleTarget\n3497:  \tstats     []c9sIfaceStats\n3498:  \tifaces    []c9sIfaceState\n3499:  \thasStates bool\n3500: +\t// links are the node's lab link interfaces as clabwire lists them.\n3501: +\tlinks     []clabwireInterface\n3502:  \ttimestamp time.Time\n3503:  \terr       error\n3504:  }\n3505:  \n3506: +// podInterfaceListing is the clabwire interface listing of a pod, per node. It is listed again\n3507: +// when the pod's interfaces change.\n3508: +type podInterfaceListing struct {\n3509: +\tnames  string\n3510: +\tbyNode map[string][]clabwireInterface\n3511: +}\n3512: +\n3513:  // interfacePoller samples the interfaces of every running node in an event scope and turns the\n3514: -// samples into interface state and statistics events.\n3515: +// samples into interface events. It reports the interfaces a container of the local runtimes\n3516: +// has for the same node: the node's lab link interfaces, with the names and aliases clabwire\n3517: +// lists for them, the management interface and loopback. The pod's own interfaces (the pod\n3518: +// network, clabernetes' interposition and link transport interfaces) are not reported.\n3519:  type interfacePoller struct {\n3520:  \tr     *Runtime\n3521:  \tscope eventScope\n3522:  \topts  interfacePollOptions\n3523:  \tsink  chan<- clablabruntime.Event\n3524: @@ -128,10 +137,14 @@ type interfacePoller struct {\n3525:  \tnoShellMu sync.Mutex\n3526:  \t// noShell holds the pods whose device container has no shell; they are sampled with a\n3527:  \t// plain cat of /proc/net/dev and report statistics without interface state.\n3528:  \tnoShell map[string]bool\n3529:  \n3530: +\tlistingsMu sync.Mutex\n3531: +\t// listings holds the clabwire interface listing per pod (namespace/pod).\n3532: +\tlistings map[string]*podInterfaceListing\n3533: +\n3534:  \tfirstRound bool\n3535:  }\n3536:  \n3537:  func (r *Runtime) pollInterfaces(\n3538:  \tctx context.Context,\n3539: @@ -141,21 +154,11 @@ func (r *Runtime) pollInterfaces(\n3540:  ) {\n3541:  \tif opts.interval <= 0 {\n3542:  \t\topts.interval = time.Second\n3543:  \t}\n3544:  \n3545: -\tpoller := &interfacePoller{\n3546: -\t\tr:            r,\n3547: -\t\tscope:        scope,\n3548: -\t\topts:         opts,\n3549: -\t\tsink:         eventSink,\n3550: -\t\tstatsSamples: map[string]c9sIfaceStatsSample{},\n3551: -\t\tnodes:        map[string]*trackedNode{},\n3552: -\t\tnoShell:      map[string]bool{},\n3553: -\t\tfirstRound:   true,\n3554: -\t}\n3555: -\n3556: +\tpoller := newInterfacePoller(r, scope, opts, eventSink)\n3557:  \tpoller.round(ctx)\n3558:  \n3559:  \tticker := time.NewTicker(opts.interval)\n3560:  \tdefer ticker.Stop()\n3561:  \n3562: @@ -167,28 +170,50 @@ func (r *Runtime) pollInterfaces(\n3563:  \t\t\tpoller.round(ctx)\n3564:  \t\t}\n3565:  \t}\n3566:  }\n3567:  \n3568: +func newInterfacePoller(\n3569: +\tr *Runtime,\n3570: +\tscope eventScope,\n3571: +\topts interfacePollOptions,\n3572: +\teventSink chan<- clablabruntime.Event,\n3573: +) *interfacePoller {\n3574: +\treturn &interfacePoller{\n3575: +\t\tr:            r,\n3576: +\t\tscope:        scope,\n3577: +\t\topts:         opts,\n3578: +\t\tsink:         eventSink,\n3579: +\t\tstatsSamples: map[string]c9sIfaceStatsSample{},\n3580: +\t\tnodes:        map[string]*trackedNode{},\n3581: +\t\tnoShell:      map[string]bool{},\n3582: +\t\tlistings:     map[string]*podInterfaceListing{},\n3583: +\t\tfirstRound:   true,\n3584: +\t}\n3585: +}\n3586: +\n3587:  func (p *interfacePoller) round(ctx context.Context) {\n3588:  \tdefer func() { p.firstRound = false }()\n3589:  \n3590:  \tstates, err := p.r.labStates(ctx, p.scope)\n3591:  \tif err != nil {\n3592:  \t\tlog.Debug(\"failed to list C9s labs for interface events\", \"error\", err)\n3593:  \t\treturn\n3594:  \t}\n3595:  \n3596:  \trunning := map[string]bool{}\n3597: +\tpods := map[string]bool{}\n3598:  \tvar targets []interfaceSampleTarget\n3599:  \tfor _, state := range states {\n3600:  \t\tfor _, node := range state.Nodes {\n3601: -\t\t\tif !node.Ready || node.Pod == \"\" || node.Container == \"\" {\n3602: +\t\t\tif node.ContainerState != clablabruntime.ContainerStateRunning || node.Pod == \"\" ||\n3603: +\t\t\t\tnode.Container == \"\" {\n3604:  \t\t\t\tcontinue\n3605:  \t\t\t}\n3606:  \n3607:  \t\t\trunning[c9sNodeKey(state.Namespace, state.Name, node.Name)] = true\n3608: +\t\t\tpods[state.Namespace+\"/\"+node.Pod] = true\n3609:  \t\t\ttargets = append(targets, interfaceSampleTarget{\n3610:  \t\t\t\tstate: state,\n3611:  \t\t\t\tnode:  node,\n3612:  \t\t\t\tpod: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{\n3613:  \t\t\t\t\tName:      node.Pod,\n3614: @@ -215,29 +240,41 @@ func (p *interfacePoller) round(ctx context.Context) {\n3615:  \n3616:  \t\tp.processSample(ctx, sample)\n3617:  \t}\n3618:  \n3619:  \tp.retireStoppedNodes(ctx, running)\n3620: +\tp.forgetListings(pods)\n3621:  }\n3622:  \n3623:  // retireStoppedNodes reports the interfaces of nodes that stopped running, or were removed, as\n3624: -// down: they are gone with the node's pod.\n3625: +// deleted: they are gone with the node's pod.\n3626:  func (p *interfacePoller) retireStoppedNodes(ctx context.Context, running map[string]bool) {\n3627:  \tfor key, tracked := range p.nodes {\n3628:  \t\tif running[key] {\n3629:  \t\t\tcontinue\n3630:  \t\t}\n3631:  \n3632: -\t\tfor name, iface := range tracked.ifaces {\n3633: -\t\t\tiface.state.OperState = interfaceStateNotPresent\n3634: -\t\t\tp.emitState(ctx, tracked, iface.state, time.Now())\n3635: +\t\tfor _, name := range sortedInterfaceNames(tracked.ifaces) {\n3636: +\t\t\tp.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], time.Now())\n3637:  \t\t\tp.forgetStats(tracked, name)\n3638:  \t\t}\n3639:  \t\tdelete(p.nodes, key)\n3640:  \t}\n3641:  }\n3642:  \n3643: +// forgetListings drops the interface listings of pods that are gone.\n3644: +func (p *interfacePoller) forgetListings(pods map[string]bool) {\n3645: +\tp.listingsMu.Lock()\n3646: +\tdefer p.listingsMu.Unlock()\n3647: +\n3648: +\tfor key := range p.listings {\n3649: +\t\tif !pods[key] {\n3650: +\t\t\tdelete(p.listings, key)\n3651: +\t\t}\n3652: +\t}\n3653: +}\n3654: +\n3655:  func (p *interfacePoller) sampleAll(\n3656:  \tctx context.Context,\n3657:  \ttargets []interfaceSampleTarget,\n3658:  ) []interfaceSample {\n3659:  \tsamples := make([]interfaceSample, len(targets))\n3660: @@ -298,152 +335,318 @@ func (p *interfacePoller) sample(\n3661:  \tcase rc != 0:\n3662:  \t\tsample.err = fmt.Errorf(\"exit code %d: %s\", rc, strings.TrimSpace(string(stderr)))\n3663:  \tdefault:\n3664:  \t\tsample.stats, sample.ifaces, sample.hasStates, sample.err = parseInterfaceSample(stdout)\n3665:  \t}\n3666: +\tif sample.err != nil {\n3667: +\t\treturn sample\n3668: +\t}\n3669: +\n3670: +\tsample.links, sample.err = p.nodeLinks(ctx, target, sampledInterfaceNames(sample))\n3671:  \n3672:  \treturn sample\n3673:  }\n3674:  \n3675: +// sampledInterfaceNames lists the interface names a sample saw, sorted and comma-joined.\n3676: +func sampledInterfaceNames(sample interfaceSample) string {\n3677: +\tnames := make([]string, 0, len(sample.stats)+len(sample.ifaces))\n3678: +\tseen := map[string]bool{}\n3679: +\tfor _, iface := range sample.ifaces {\n3680: +\t\tif !seen[iface.Name] {\n3681: +\t\t\tseen[iface.Name] = true\n3682: +\t\t\tnames = append(names, iface.Name)\n3683: +\t\t}\n3684: +\t}\n3685: +\tfor _, stat := range sample.stats {\n3686: +\t\tif !seen[stat.Name] {\n3687: +\t\t\tseen[stat.Name] = true\n3688: +\t\t\tnames = append(names, stat.Name)\n3689: +\t\t}\n3690: +\t}\n3691: +\tsort.Strings(names)\n3692: +\n3693: +\treturn strings.Join(names, \",\")\n3694: +}\n3695: +\n3696: +// nodeLinks returns the lab link interfaces of a node from its pod's clabwire listing. A pod is\n3697: +// listed once, and again when its interfaces change (a pod gets its link interfaces as clabwire\n3698: +// wires them).\n3699: +func (p *interfacePoller) nodeLinks(\n3700: +\tctx context.Context,\n3701: +\ttarget interfaceSampleTarget,\n3702: +\tnames string,\n3703: +) ([]clabwireInterface, error) {\n3704: +\tkey := target.pod.Namespace + \"/\" + target.pod.Name\n3705: +\n3706: +\tp.listingsMu.Lock()\n3707: +\tlisting := p.listings[key]\n3708: +\tp.listingsMu.Unlock()\n3709: +\n3710: +\tif listing == nil || listing.names != names {\n3711: +\t\tentries, err := p.r.listPodInterfaces(ctx, target.pod.Namespace, target.pod.Name)\n3712: +\t\tif err != nil {\n3713: +\t\t\treturn nil, err\n3714: +\t\t}\n3715: +\n3716: +\t\tlisting = &podInterfaceListing{\n3717: +\t\t\tnames:  names,\n3718: +\t\t\tbyNode: map[string][]clabwireInterface{},\n3719: +\t\t}\n3720: +\t\tfor _, entry := range entries {\n3721: +\t\t\tlisting.byNode[entry.Node] = append(listing.byNode[entry.Node], entry)\n3722: +\t\t}\n3723: +\n3724: +\t\tp.listingsMu.Lock()\n3725: +\t\tp.listings[key] = listing\n3726: +\t\tp.listingsMu.Unlock()\n3727: +\t}\n3728: +\n3729: +\treturn listing.byNode[target.node.Name], nil\n3730: +}\n3731: +\n3732:  // commandNotExecutable reports an exec that failed because the command does not exist in the\n3733:  // container.\n3734:  func commandNotExecutable(rc int, err error) bool {\n3735:  \tif rc == exitCommandNotExecutable || rc == exitCommandNotFound {\n3736:  \t\treturn true\n3737:  \t}\n3738:  \n3739:  \treturn err != nil && strings.Contains(err.Error(), \"executable file not found\")\n3740:  }\n3741:  \n3742: +// reportedInterfaces are the interfaces reported for a node, by name, with the alias the\n3743: +// topology gave them: its lab link interfaces, the management interface and loopback.\n3744: +func reportedInterfaces(links []clabwireInterface) map[string]string {\n3745: +\treported := map[string]string{\n3746: +\t\tloopbackInterface:   \"\",\n3747: +\t\tmanagementInterface: \"\",\n3748: +\t}\n3749: +\tfor _, link := range links {\n3750: +\t\treported[link.Interface] = link.Alias\n3751: +\t}\n3752: +\n3753: +\treturn reported\n3754: +}\n3755: +\n3756: +// interfaceEventData describes an interface the way the local runtimes' netlink events do: the\n3757: +// alias is the topology's name for the interface (an alias clabernetes set for its own use is\n3758: +// not reported), the operational state uses netlink's names, lab link and management\n3759: +// interfaces are veth pairs, loopback a device, and loopback has no hardware address.\n3760: +func interfaceEventData(iface c9sIfaceState, alias string) clablabruntime.InterfaceEventData {\n3761: +\tif alias == \"\" && !strings.HasPrefix(iface.Alias, clabernetesAliasPrefix) {\n3762: +\t\talias = iface.Alias\n3763: +\t}\n3764: +\n3765: +\tmac := iface.MAC\n3766: +\tif mac == zeroMAC {\n3767: +\t\tmac = \"\"\n3768: +\t}\n3769: +\n3770: +\tlinkType := interfaceTypeVeth\n3771: +\tif iface.Name == loopbackInterface {\n3772: +\t\tlinkType = interfaceTypeDevice\n3773: +\t}\n3774: +\n3775: +\treturn clablabruntime.InterfaceEventData{\n3776: +\t\tName:      iface.Name,\n3777: +\t\tAlias:     alias,\n3778: +\t\tIndex:     iface.Index,\n3779: +\t\tMTU:       iface.MTU,\n3780: +\t\tMAC:       mac,\n3781: +\t\tOperState: netlinkOperState(iface.OperState),\n3782: +\t\tType:      linkType,\n3783: +\t}\n3784: +}\n3785: +\n3786: +// netlinkOperState names an operational state from sysfs (RFC 2863, as in\n3787: +// /sys/class/net/<if>/operstate) the way netlink, and so the local runtimes' events, name it.\n3788: +func netlinkOperState(operState string) string {\n3789: +\tswitch operState {\n3790: +\tcase \"notpresent\":\n3791: +\t\treturn \"not-present\"\n3792: +\tcase \"lowerlayerdown\":\n3793: +\t\treturn \"lower-layer-down\"\n3794: +\tcase \"\":\n3795: +\t\treturn \"unknown\"\n3796: +\tdefault:\n3797: +\t\treturn operState\n3798: +\t}\n3799: +}\n3800: +\n3801:  func (p *interfacePoller) processSample(ctx context.Context, sample interfaceSample) {\n3802:  \tstate := sample.target.state\n3803:  \tnode := sample.target.node\n3804:  \tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n3805:  \n3806:  \ttracked, known := p.nodes[key]\n3807:  \tif !known {\n3808: -\t\ttracked = &trackedNode{\n3809: -\t\t\tnamespace: state.Namespace,\n3810: -\t\t\tlab:       state.Name,\n3811: -\t\t\tnode:      node.Name,\n3812: -\t\t\tifaces:    map[string]trackedIface{},\n3813: -\t\t}\n3814: +\t\ttracked = &trackedNode{ifaces: map[string]clablabruntime.InterfaceEventData{}}\n3815:  \t\tp.nodes[key] = tracked\n3816:  \t}\n3817: -\ttracked.pod = node.Pod\n3818: -\n3819: -\tif p.opts.includeStats {\n3820: -\t\tfor _, stat := range sample.stats {\n3821: -\t\t\tstatsKey := c9sIfaceStatsKey(state.Namespace, state.Name, node.Name, stat.Name)\n3822: -\t\t\tcurrent := c9sIfaceStatsSample{Stats: stat, Timestamp: sample.timestamp}\n3823: +\ttracked.lab = state\n3824: +\ttracked.node = node\n3825:  \n3826: -\t\t\tif previous, ok := p.statsSamples[statsKey]; ok {\n3827: -\t\t\t\tp.r.sendEvent(ctx, p.sink,\n3828: -\t\t\t\t\tc9sIfaceStatsEvent(state, node, sample.target.pod, stat, previous, current))\n3829: -\t\t\t}\n3830: +\treported := reportedInterfaces(sample.links)\n3831:  \n3832: -\t\t\tp.statsSamples[statsKey] = current\n3833: -\t\t}\n3834: +\tif sample.hasStates {\n3835: +\t\tp.processStates(ctx, tracked, reported, sample)\n3836:  \t}\n3837:  \n3838: -\tif !sample.hasStates {\n3839: +\tif !p.opts.includeStats {\n3840:  \t\treturn\n3841:  \t}\n3842: +\tfor _, stat := range sample.stats {\n3843: +\t\talias, ok := reported[stat.Name]\n3844: +\t\tif !ok {\n3845: +\t\t\tcontinue\n3846: +\t\t}\n3847: +\n3848: +\t\tstatsKey := c9sIfaceStatsKey(state.Namespace, state.Name, node.Name, stat.Name)\n3849: +\t\tcurrent := c9sIfaceStatsSample{Stats: stat, Timestamp: sample.timestamp}\n3850: +\t\tif previous, ok := p.statsSamples[statsKey]; ok {\n3851: +\t\t\tdata, ok := tracked.ifaces[stat.Name]\n3852: +\t\t\tif !ok {\n3853: +\t\t\t\tdata = interfaceEventData(c9sIfaceState{Name: stat.Name}, alias)\n3854: +\t\t\t\tdata.OperState = \"\"\n3855: +\t\t\t}\n3856: +\t\t\tdata.Stats = c9sIfaceStatsData(previous, current)\n3857: +\t\t\tp.emit(ctx, tracked, interfaceActionStats, data, current.Timestamp)\n3858: +\t\t}\n3859:  \n3860: -\tpresent := make(map[string]bool, len(sample.ifaces))\n3861: +\t\tp.statsSamples[statsKey] = current\n3862: +\t}\n3863: +}\n3864: +\n3865: +// processStates reports the interfaces that appeared (snapshot in the first round with\n3866: +// --initial-state, create later), changed (update) or disappeared (delete) since the last\n3867: +// sample, like the netlink events of the local runtimes.\n3868: +func (p *interfacePoller) processStates(\n3869: +\tctx context.Context,\n3870: +\ttracked *trackedNode,\n3871: +\treported map[string]string,\n3872: +\tsample interfaceSample,\n3873: +) {\n3874: +\tpresent := map[string]bool{}\n3875:  \tfor _, iface := range sample.ifaces {\n3876: -\t\tpresent[iface.Name] = true\n3877: +\t\talias, ok := reported[iface.Name]\n3878: +\t\tif !ok {\n3879: +\t\t\tcontinue\n3880: +\t\t}\n3881:  \n3882: -\t\taction := iface.action()\n3883: +\t\tdata := interfaceEventData(iface, alias)\n3884: +\t\tpresent[iface.Name] = true\n3885:  \t\tprevious, seen := tracked.ifaces[iface.Name]\n3886: -\t\ttracked.ifaces[iface.Name] = trackedIface{state: iface, action: action}\n3887: +\t\ttracked.ifaces[iface.Name] = data\n3888:  \n3889:  \t\tswitch {\n3890: -\t\tcase seen && previous.action == action &&\n3891: -\t\t\tprevious.state.OperState == iface.OperState:\n3892: -\t\t\tcontinue\n3893: -\t\tcase !seen && p.firstRound && !p.opts.includeInitialState:\n3894: +\t\tcase seen && previous == data:\n3895: +\t\tcase !seen && p.firstRound:\n3896:  \t\t\t// Interfaces that exist when the stream starts are only reported with\n3897:  \t\t\t// --initial-state; later changes are always reported.\n3898: -\t\t\tcontinue\n3899: +\t\t\tif p.opts.includeInitialState {\n3900: +\t\t\t\tp.emit(ctx, tracked, interfaceActionSnapshot, data, sample.timestamp)\n3901: +\t\t\t}\n3902: +\t\tcase !seen:\n3903: +\t\t\tp.emit(ctx, tracked, interfaceActionCreate, data, sample.timestamp)\n3904: +\t\tdefault:\n3905: +\t\t\tp.emit(ctx, tracked, interfaceActionUpdate, data, sample.timestamp)\n3906:  \t\t}\n3907: -\n3908: -\t\tp.emitState(ctx, tracked, iface, sample.timestamp)\n3909:  \t}\n3910:  \n3911: -\tfor name, iface := range tracked.ifaces {\n3912: +\tfor _, name := range sortedInterfaceNames(tracked.ifaces) {\n3913:  \t\tif present[name] {\n3914:  \t\t\tcontinue\n3915:  \t\t}\n3916:  \n3917: -\t\tiface.state.OperState = interfaceStateNotPresent\n3918: -\t\tp.emitState(ctx, tracked, iface.state, sample.timestamp)\n3919: +\t\tp.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], sample.timestamp)\n3920:  \t\tp.forgetStats(tracked, name)\n3921:  \t\tdelete(tracked.ifaces, name)\n3922:  \t}\n3923:  }\n3924:  \n3925: +func sortedInterfaceNames(ifaces map[string]clablabruntime.InterfaceEventData) []string {\n3926: +\tnames := make([]string, 0, len(ifaces))\n3927: +\tfor name := range ifaces {\n3928: +\t\tnames = append(names, name)\n3929: +\t}\n3930: +\tsort.Strings(names)\n3931: +\n3932: +\treturn names\n3933: +}\n3934: +\n3935:  func (p *interfacePoller) forgetStats(tracked *trackedNode, ifName string) {\n3936: -\tdelete(p.statsSamples, c9sIfaceStatsKey(tracked.namespace, tracked.lab, tracked.node, ifName))\n3937: +\tdelete(p.statsSamples,\n3938: +\t\tc9sIfaceStatsKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name, ifName))\n3939:  }\n3940:  \n3941: -func (p *interfacePoller) emitState(\n3942: +func (p *interfacePoller) emit(\n3943:  \tctx context.Context,\n3944:  \ttracked *trackedNode,\n3945: -\tiface c9sIfaceState,\n3946: +\taction string,\n3947: +\tdata clablabruntime.InterfaceEventData,\n3948:  \ttimestamp time.Time,\n3949:  ) {\n3950: -\tp.r.sendEvent(ctx, p.sink, c9sIfaceStateEvent(tracked, iface, timestamp))\n3951: +\tp.r.sendEvent(ctx, p.sink, c9sInterfaceEvent(tracked, action, data, timestamp))\n3952:  }\n3953:  \n3954: -// c9sIfaceStateEvent reports the operational state of an interface. The actor is the node, as\n3955: -// for the container events of the lab and the interface events of the local runtimes.\n3956: -func c9sIfaceStateEvent(\n3957: +// c9sInterfaceEvent is an interface event of a node. The actor is the node, as for its container\n3958: +// events. The interface itself is in Interface; the events command reports it with the\n3959: +// attributes of the local runtimes' interface events.\n3960: +func c9sInterfaceEvent(\n3961:  \ttracked *trackedNode,\n3962: -\tiface c9sIfaceState,\n3963: +\taction string,\n3964: +\tdata clablabruntime.InterfaceEventData,\n3965:  \ttimestamp time.Time,\n3966:  ) clablabruntime.Event {\n3967: -\tactorName := fmt.Sprintf(\"%s-%s\", tracked.lab, tracked.node)\n3968: +\tkey := c9sNodeKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name)\n3969:  \n3970:  \tattributes := map[string]string{\n3971: -\t\t\"namespace\": tracked.namespace,\n3972: -\t\t\"lab\":       tracked.lab,\n3973: -\t\t\"node\":      tracked.node,\n3974: -\t\t\"name\":      actorName,\n3975: -\t\t\"ifname\":    iface.Name,\n3976: -\t\t\"state\":     iface.OperState,\n3977: -\t\t\"origin\":    \"clabernetes\",\n3978: -\t}\n3979: -\tif tracked.pod != \"\" {\n3980: -\t\tattributes[\"pod\"] = tracked.pod\n3981: -\t}\n3982: -\tif iface.Index > 0 {\n3983: -\t\tattributes[\"index\"] = strconv.Itoa(iface.Index)\n3984: -\t}\n3985: -\tif iface.MTU > 0 {\n3986: -\t\tattributes[\"mtu\"] = strconv.Itoa(iface.MTU)\n3987: +\t\t\"namespace\": tracked.lab.Namespace,\n3988: +\t\t\"lab\":       tracked.lab.Name,\n3989: +\t\t\"node\":      tracked.node.Name,\n3990: +\t\t\"origin\":    clabernetesAppValue,\n3991:  \t}\n3992: -\tif iface.MAC != \"\" {\n3993: -\t\tattributes[\"mac\"] = iface.MAC\n3994: -\t}\n3995: -\tif iface.Alias != \"\" {\n3996: -\t\tattributes[\"alias\"] = iface.Alias\n3997: +\tif tracked.node.Pod != \"\" {\n3998: +\t\tattributes[\"pod\"] = tracked.node.Pod\n3999:  \t}\n4000:  \n4001: -\taction := iface.action()\n4002: -\tif iface.OperState == interfaceStateNotPresent {\n4003: -\t\taction = \"down\"\n4004: -\t}\n4005: +\tnode := tracked.node\n4006:  \n4007:  \treturn clablabruntime.Event{\n4008:  \t\tTimestamp:   timestamp,\n4009: -\t\tType:        \"interface\",\n4010: +\t\tType:        clablabruntime.EventTypeInterface,\n4011:  \t\tAction:      action,\n4012: -\t\tActorID:     c9sNodeKey(tracked.namespace, tracked.lab, tracked.node),\n4013: -\t\tActorName:   actorName,\n4014: -\t\tActorFullID: tracked.pod,\n4015: +\t\tActorID:     key,\n4016: +\t\tActorName:   fmt.Sprintf(\"%s-%s\", tracked.lab.Name, tracked.node.Name),\n4017: +\t\tActorFullID: key,\n4018:  \t\tAttributes:  attributes,\n4019: +\t\tLab:         tracked.lab,\n4020: +\t\tNode:        &node,\n4021: +\t\tInterface:   &data,\n4022: +\t}\n4023: +}\n4024: +\n4025: +// c9sIfaceStatsData computes the counters and rates of a stats event from two samples.\n4026: +func c9sIfaceStatsData(previous, current c9sIfaceStatsSample) *clablabruntime.InterfaceStats {\n4027: +\tinterval := current.Timestamp.Sub(previous.Timestamp)\n4028: +\tif interval <= 0 {\n4029: +\t\tinterval = time.Second\n4030: +\t}\n4031: +\n4032: +\tseconds := interval.Seconds()\n4033: +\tstat := current.Stats\n4034: +\n4035: +\treturn &clablabruntime.InterfaceStats{\n4036: +\t\tRxBytes:   stat.RxBytes,\n4037: +\t\tTxBytes:   stat.TxBytes,\n4038: +\t\tRxPackets: stat.RxPackets,\n4039: +\t\tTxPackets: stat.TxPackets,\n4040: +\t\tRxBps:     float64(counterDelta(stat.RxBytes, previous.Stats.RxBytes)*8) / seconds,\n4041: +\t\tTxBps:     float64(counterDelta(stat.TxBytes, previous.Stats.TxBytes)*8) / seconds,\n4042: +\t\tRxPps:     float64(counterDelta(stat.RxPackets, previous.Stats.RxPackets)) / seconds,\n4043: +\t\tTxPps:     float64(counterDelta(stat.TxPackets, previous.Stats.TxPackets)) / seconds,\n4044: +\t\tInterval:  interval,\n4045:  \t}\n4046:  }\n4047:  \n4048:  // parseInterfaceSample splits the output of interfaceSampleScript into the /proc/net/dev\n4049:  // counters and the sysfs interface states. hasStates is false for output without the sysfs\n4050: @@ -559,63 +762,10 @@ func c9sNodeKey(namespace, lab, node string) string {\n4051:  \n4052:  func c9sIfaceStatsKey(namespace, lab, node, ifName string) string {\n4053:  \treturn c9sNodeKey(namespace, lab, node) + \"/\" + ifName\n4054:  }\n4055:  \n4056: -func c9sIfaceStatsEvent(\n4057: -\tstate *clablabruntime.LabState,\n4058: -\tnode clablabruntime.NodeState,\n4059: -\tpod *corev1.Pod,\n4060: -\tstat c9sIfaceStats,\n4061: -\tprevious,\n4062: -\tcurrent c9sIfaceStatsSample,\n4063: -) clablabruntime.Event {\n4064: -\tinterval := current.Timestamp.Sub(previous.Timestamp)\n4065: -\tif interval <= 0 {\n4066: -\t\tinterval = time.Second\n4067: -\t}\n4068: -\n4069: -\tseconds := interval.Seconds()\n4070: -\trxBytesDelta := counterDelta(stat.RxBytes, previous.Stats.RxBytes)\n4071: -\ttxBytesDelta := counterDelta(stat.TxBytes, previous.Stats.TxBytes)\n4072: -\trxPacketsDelta := counterDelta(stat.RxPackets, previous.Stats.RxPackets)\n4073: -\ttxPacketsDelta := counterDelta(stat.TxPackets, previous.Stats.TxPackets)\n4074: -\n4075: -\tactorName := fmt.Sprintf(\"%s-%s\", state.Name, node.Name)\n4076: -\tpodName := \"\"\n4077: -\tif pod != nil {\n4078: -\t\tpodName = pod.Name\n4079: -\t}\n4080: -\n4081: -\treturn clablabruntime.Event{\n4082: -\t\tTimestamp:   current.Timestamp,\n4083: -\t\tType:        \"interface\",\n4084: -\t\tAction:      \"stats\",\n4085: -\t\tActorID:     c9sNodeKey(state.Namespace, state.Name, node.Name),\n4086: -\t\tActorName:   actorName,\n4087: -\t\tActorFullID: podName,\n4088: -\t\tAttributes: map[string]string{\n4089: -\t\t\t\"namespace\":        state.Namespace,\n4090: -\t\t\t\"lab\":              state.Name,\n4091: -\t\t\t\"node\":             node.Name,\n4092: -\t\t\t\"name\":             actorName,\n4093: -\t\t\t\"pod\":              podName,\n4094: -\t\t\t\"ifname\":           stat.Name,\n4095: -\t\t\t\"origin\":           \"clabernetes\",\n4096: -\t\t\t\"rx_bytes\":         strconv.FormatUint(stat.RxBytes, 10),\n4097: -\t\t\t\"tx_bytes\":         strconv.FormatUint(stat.TxBytes, 10),\n4098: -\t\t\t\"rx_packets\":       strconv.FormatUint(stat.RxPackets, 10),\n4099: -\t\t\t\"tx_packets\":       strconv.FormatUint(stat.TxPackets, 10),\n4100: -\t\t\t\"rx_bps\":           strconv.FormatFloat(float64(rxBytesDelta*8)/seconds, 'f', -1, 64),\n4101: -\t\t\t\"tx_bps\":           strconv.FormatFloat(float64(txBytesDelta*8)/seconds, 'f', -1, 64),\n4102: -\t\t\t\"rx_pps\":           strconv.FormatFloat(float64(rxPacketsDelta)/seconds, 'f', -1, 64),\n4103: -\t\t\t\"tx_pps\":           strconv.FormatFloat(float64(txPacketsDelta)/seconds, 'f', -1, 64),\n4104: -\t\t\t\"interval_seconds\": strconv.FormatFloat(seconds, 'f', -1, 64),\n4105: -\t\t},\n4106: -\t}\n4107: -}\n4108: -\n4109:  func counterDelta(current, previous uint64) uint64 {\n4110:  \tif current < previous {\n4111:  \t\treturn 0\n4112:  \t}\n4113:  \n4114: diff --git a/labruntime/clabernetes/manifests.go b/labruntime/clabernetes/manifests.go\n4115: index 7d4d36b..8512cab 100644\n4116: --- a/labruntime/clabernetes/manifests.go\n4117: +++ b/labruntime/clabernetes/manifests.go\n4118: @@ -38,10 +38,19 @@ func (r *Runtime) Manifests(\n4119:  \tprepared, err := prepareDesiredDeployment(ctx, req, namespace)\n4120:  \tif err != nil {\n4121:  \t\treturn nil, err\n4122:  \t}\n4123:  \n4124: +\t// The manifests are applied by other means than this deploy, so they do not carry the path\n4125: +\t// of the topology file on this machine; such a lab reports where its definition lives.\n4126: +\tremoveTopologySourceFile(prepared.topology)\n4127: +\tfor _, group := range prepared.primitives.groups() {\n4128: +\t\tfor _, obj := range group.objects {\n4129: +\t\t\tremoveTopologySourceFile(obj)\n4130: +\t\t}\n4131: +\t}\n4132: +\n4133:  \tmanifests := []clablabruntime.Manifest{}\n4134:  \n4135:  \t// A namespace override must already exist, matching the deploy contract; only the\n4136:  \t// canonical per-lab namespace is created by containerlab and therefore emitted.\n4137:  \tif req.Namespace == \"\" && r.labNamespaceOverride == \"\" {\n4138: diff --git a/labruntime/clabernetes/plan.go b/labruntime/clabernetes/plan.go\n4139: index 258bd01..0f0862b 100644\n4140: --- a/labruntime/clabernetes/plan.go\n4141: +++ b/labruntime/clabernetes/plan.go\n4142: @@ -51,10 +51,11 @@ func prepareDesiredDeployment(\n4143:  \t\ttopologyWithNaming(naming),\n4144:  \t\ttopologyWithImagePullSecret(req.ImagePullSecret),\n4145:  \t\ttopologyWithExposeType(exposeType),\n4146:  \t\ttopologyWithPersistence(!req.NoPersistence),\n4147:  \t)\n4148: +\tsetTopologySourceFile(desiredTopology, req.TopologyFile)\n4149:  \tif err := setTopologyFilesFromConfigMaps(desiredTopology, stagedConfigMaps); err != nil {\n4150:  \t\treturn nil, err\n4151:  \t}\n4152:  \tprimitives, err := compilePrimitiveResources(desiredTopology)\n4153:  \tif err != nil {\n4154: diff --git a/labruntime/clabernetes/primitives.go b/labruntime/clabernetes/primitives.go\n4155: index cc5a59b..f03b288 100644\n4156: --- a/labruntime/clabernetes/primitives.go\n4157: +++ b/labruntime/clabernetes/primitives.go\n4158: @@ -218,10 +218,15 @@ func primitiveObject(\n4159:  \t\t// the spec, which the Node schema does not have: the API server prunes them, and\n4160:  \t\t// keeping them would make every apply and plan report the Node as changed.\n4161:  \t\tunstructured.RemoveNestedField(obj.Object, \"spec\", \"labels\")\n4162:  \t}\n4163:  \n4164: +\tif kind != \"Node\" {\n4165: +\t\t// Only Nodes carry the lab's topology file, which inspect reads without a Topology.\n4166: +\t\tremoveTopologySourceFile(obj)\n4167: +\t}\n4168: +\n4169:  \tif owner := desiredTopology.GetAnnotations()[clabconstants.Owner]; owner != \"\" {\n4170:  \t\tannotations := obj.GetAnnotations()\n4171:  \t\tif annotations == nil {\n4172:  \t\t\tannotations = map[string]string{}\n4173:  \t\t}\n4174: diff --git a/labruntime/clabernetes/reconcile.go b/labruntime/clabernetes/reconcile.go\n4175: index a4889b5..d9cc952 100644\n4176: --- a/labruntime/clabernetes/reconcile.go\n4177: +++ b/labruntime/clabernetes/reconcile.go\n4178: @@ -195,14 +195,34 @@ func reconciledPrimitiveObject(\n4179:  \n4180:  \tupdated.SetLabels(mergeDesiredMetadata(existing.GetLabels(), desired.GetLabels()))\n4181:  \tupdated.SetAnnotations(\n4182:  \t\tmergeDesiredMetadata(existing.GetAnnotations(), desired.GetAnnotations()),\n4183:  \t)\n4184: +\tcarryOverNodeTopologyFile(existing, updated)\n4185:  \n4186:  \treturn updated\n4187:  }\n4188:  \n4189: +// carryOverNodeTopologyFile keeps the topology file an existing Node recorded, or its absence.\n4190: +// clabernetes copies a Node's annotations into its pod template, so changing the annotation\n4191: +// would replace the node's pod although nothing about the node changed. A Node therefore keeps\n4192: +// the file the lab was deployed from when the Node was created. The Topology resource has no\n4193: +// such effect and always records the file of the latest deploy.\n4194: +func carryOverNodeTopologyFile(existing, updated *unstructured.Unstructured) {\n4195: +\tif existing.GetKind() != \"Node\" || existing.GetAPIVersion() != c9sAPIVersion {\n4196: +\t\treturn\n4197: +\t}\n4198: +\n4199: +\tpath, found := existing.GetAnnotations()[annotationTopologyFile]\n4200: +\tif !found {\n4201: +\t\tremoveTopologySourceFile(updated)\n4202: +\t\treturn\n4203: +\t}\n4204: +\n4205: +\tsetTopologySourceFile(updated, path)\n4206: +}\n4207: +\n4208:  // carryOverNodeRunState keeps the run state of an existing Node. spec.runState is operational\n4209:  // state that stop and start own, not part of the compiled definition: the compiler never sets\n4210:  // it, so replacing the spec would start a stopped node on every apply, and the API default\n4211:  // (Running) would otherwise count as drift on every plan. Restart requests live in annotations,\n4212:  // which the merge keeps.\n4213: diff --git a/labruntime/clabernetes/runtime_gaps_test.go b/labruntime/clabernetes/runtime_gaps_test.go\n4214: index aef6f01..1b8d366 100644\n4215: --- a/labruntime/clabernetes/runtime_gaps_test.go\n4216: +++ b/labruntime/clabernetes/runtime_gaps_test.go\n4217: @@ -386,21 +386,12 @@ func TestParseInterfaceSample(t *testing.T) {\n4218:  \t}\n4219:  \tif stats[1].Name != \"eth1\" || stats[1].RxBytes != 2000 || stats[1].TxPackets != 30 {\n4220:  \t\tt.Fatalf(\"eth1 stats = %+v\", stats[1])\n4221:  \t}\n4222:  \n4223: -\twantActions := map[string]string{\"eth1\": \"up\", \"eth2\": \"down\", \"lo\": \"up\", \"dummy0\": \"down\"}\n4224: -\tfor _, state := range states {\n4225: -\t\tif got := state.action(); got != wantActions[state.Name] {\n4226: -\t\t\tt.Fatalf(\n4227: -\t\t\t\t\"%s action = %q, want %q (%+v)\",\n4228: -\t\t\t\tstate.Name,\n4229: -\t\t\t\tgot,\n4230: -\t\t\t\twantActions[state.Name],\n4231: -\t\t\t\tstate,\n4232: -\t\t\t)\n4233: -\t\t}\n4234: +\tif states[1].OperState != \"lowerlayerdown\" || states[2].OperState != \"unknown\" {\n4235: +\t\tt.Fatalf(\"operational states = %+v\", states)\n4236:  \t}\n4237:  \tif states[0].Index != 3 || states[0].MTU != 9500 || states[0].MAC != \"aa:c1:ab:00:00:01\" ||\n4238:  \t\tstates[0].Alias != \"to server\" || states[0].Flags != 0x1003 {\n4239:  \t\tt.Fatalf(\"eth1 state = %+v\", states[0])\n4240:  \t}\n4241: @@ -424,131 +415,10 @@ func TestCommandNotExecutable(t *testing.T) {\n4242:  \tif commandNotExecutable(1, errors.New(\"connection refused\")) {\n4243:  \t\tt.Fatal(\"other failures are not a missing command\")\n4244:  \t}\n4245:  }\n4246:  \n4247: -func TestInterfacePollerEmitsStateChanges(t *testing.T) {\n4248: -\tt.Parallel()\n4249: -\n4250: -\tnewSample := func(ts time.Time, ifaces ...c9sIfaceState) interfaceSample {\n4251: -\t\treturn interfaceSample{\n4252: -\t\t\ttarget: interfaceSampleTarget{\n4253: -\t\t\t\tstate: &clablabruntime.LabState{Name: \"lab1\", Namespace: \"c9s-lab1\"},\n4254: -\t\t\t\tnode:  clablabruntime.NodeState{Name: \"r1\", Pod: \"lab1-r1-abc\"},\n4255: -\t\t\t\tpod:   &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"lab1-r1-abc\"}},\n4256: -\t\t\t},\n4257: -\t\t\tstats: []c9sIfaceStats{\n4258: -\t\t\t\t{Name: \"eth1\", RxBytes: uint64(ts.Unix())},\n4259: -\t\t\t},\n4260: -\t\t\tifaces:    ifaces,\n4261: -\t\t\thasStates: true,\n4262: -\t\t\ttimestamp: ts,\n4263: -\t\t}\n4264: -\t}\n4265: -\tup := c9sIfaceState{Name: \"eth1\", Index: 3, MTU: 9500, OperState: \"up\", Flags: 0x1003}\n4266: -\tdown := c9sIfaceState{Name: \"eth1\", Index: 3, MTU: 9500, OperState: \"down\", Flags: 0x1002}\n4267: -\teth2 := c9sIfaceState{Name: \"eth2\", Index: 4, OperState: \"up\", Flags: 0x1003}\n4268: -\n4269: -\tfor _, initialState := range []bool{false, true} {\n4270: -\t\tsink := make(chan clablabruntime.Event, 32)\n4271: -\t\tp := &interfacePoller{\n4272: -\t\t\tr:            &Runtime{},\n4273: -\t\t\topts:         interfacePollOptions{includeInitialState: initialState},\n4274: -\t\t\tsink:         sink,\n4275: -\t\t\tstatsSamples: map[string]c9sIfaceStatsSample{},\n4276: -\t\t\tnodes:        map[string]*trackedNode{},\n4277: -\t\t\tnoShell:      map[string]bool{},\n4278: -\t\t\tfirstRound:   true,\n4279: -\t\t}\n4280: -\t\tctx := context.Background()\n4281: -\t\tstart := time.Now()\n4282: -\n4283: -\t\tp.processSample(ctx, newSample(start, up))\n4284: -\t\tif got := drain(sink); initialState != (len(got) == 1) {\n4285: -\t\t\tt.Fatalf(\"initial-state=%t: first round emitted %+v\", initialState, got)\n4286: -\t\t}\n4287: -\n4288: -\t\tp.firstRound = false\n4289: -\t\tp.processSample(ctx, newSample(start.Add(time.Second), up))\n4290: -\t\tif got := drain(sink); len(got) != 0 {\n4291: -\t\t\tt.Fatalf(\"unchanged interface emitted %+v\", got)\n4292: -\t\t}\n4293: -\n4294: -\t\tp.processSample(ctx, newSample(start.Add(2*time.Second), down, eth2))\n4295: -\t\tgot := drain(sink)\n4296: -\t\tif len(got) != 2 {\n4297: -\t\t\tt.Fatalf(\"change emitted %+v, want eth1 down and new eth2 up\", got)\n4298: -\t\t}\n4299: -\t\tbyIf := map[string]clablabruntime.Event{}\n4300: -\t\tfor _, ev := range got {\n4301: -\t\t\tbyIf[ev.Attributes[\"ifname\"]] = ev\n4302: -\t\t}\n4303: -\t\tev := byIf[\"eth1\"]\n4304: -\t\tif ev.Type != \"interface\" || ev.Action != \"down\" || ev.ActorID != \"c9s-lab1/lab1/r1\" ||\n4305: -\t\t\tev.ActorName != \"lab1-r1\" || ev.ActorFullID != \"lab1-r1-abc\" ||\n4306: -\t\t\tev.Attributes[\"state\"] != \"down\" || ev.Attributes[\"index\"] != \"3\" ||\n4307: -\t\t\tev.Attributes[\"mtu\"] != \"9500\" || ev.Attributes[\"origin\"] != \"clabernetes\" ||\n4308: -\t\t\tev.Attributes[\"lab\"] != \"lab1\" || ev.Attributes[\"node\"] != \"r1\" ||\n4309: -\t\t\tev.Attributes[\"namespace\"] != \"c9s-lab1\" || ev.Attributes[\"pod\"] != \"lab1-r1-abc\" {\n4310: -\t\t\tt.Fatalf(\"eth1 event = %+v\", ev)\n4311: -\t\t}\n4312: -\t\tif byIf[\"eth2\"].Action != \"up\" {\n4313: -\t\t\tt.Fatalf(\"eth2 event = %+v\", byIf[\"eth2\"])\n4314: -\t\t}\n4315: -\n4316: -\t\t// eth2 disappears\n4317: -\t\tp.processSample(ctx, newSample(start.Add(3*time.Second), down))\n4318: -\t\tgot = drain(sink)\n4319: -\t\tif len(got) != 1 || got[0].Action != \"down\" ||\n4320: -\t\t\tgot[0].Attributes[\"state\"] != interfaceStateNotPresent {\n4321: -\t\t\tt.Fatalf(\"removed interface emitted %+v\", got)\n4322: -\t\t}\n4323: -\n4324: -\t\t// the node stops running\n4325: -\t\tp.retireStoppedNodes(ctx, map[string]bool{})\n4326: -\t\tgot = drain(sink)\n4327: -\t\tif len(got) != 1 || got[0].Attributes[\"ifname\"] != \"eth1\" ||\n4328: -\t\t\tgot[0].Attributes[\"state\"] != interfaceStateNotPresent || len(p.nodes) != 0 {\n4329: -\t\t\tt.Fatalf(\"stopped node emitted %+v, tracked %+v\", got, p.nodes)\n4330: -\t\t}\n4331: -\t}\n4332: -}\n4333: -\n4334: -func TestInterfacePollerStatsUseTheNodeAsActor(t *testing.T) {\n4335: -\tt.Parallel()\n4336: -\n4337: -\tsink := make(chan clablabruntime.Event, 8)\n4338: -\tp := &interfacePoller{\n4339: -\t\tr:            &Runtime{},\n4340: -\t\topts:         interfacePollOptions{includeStats: true},\n4341: -\t\tsink:         sink,\n4342: -\t\tstatsSamples: map[string]c9sIfaceStatsSample{},\n4343: -\t\tnodes:        map[string]*trackedNode{},\n4344: -\t\tnoShell:      map[string]bool{},\n4345: -\t}\n4346: -\ttarget := interfaceSampleTarget{\n4347: -\t\tstate: &clablabruntime.LabState{Name: \"lab1\", Namespace: \"c9s-lab1\"},\n4348: -\t\tnode:  clablabruntime.NodeState{Name: \"r1\", Pod: \"lab1-r1-abc\"},\n4349: -\t\tpod:   &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"lab1-r1-abc\"}},\n4350: -\t}\n4351: -\tstart := time.Now()\n4352: -\tp.processSample(context.Background(), interfaceSample{\n4353: -\t\ttarget: target, timestamp: start,\n4354: -\t\tstats: []c9sIfaceStats{{Name: \"eth1\", RxBytes: 1000}},\n4355: -\t})\n4356: -\tp.processSample(context.Background(), interfaceSample{\n4357: -\t\ttarget: target, timestamp: start.Add(time.Second),\n4358: -\t\tstats: []c9sIfaceStats{{Name: \"eth1\", RxBytes: 2000}},\n4359: -\t})\n4360: -\n4361: -\tgot := drain(sink)\n4362: -\tif len(got) != 1 || got[0].Action != \"stats\" || got[0].ActorID != \"c9s-lab1/lab1/r1\" ||\n4363: -\t\tgot[0].Attributes[\"rx_bps\"] != \"8000\" {\n4364: -\t\tt.Fatalf(\"stats events = %+v\", got)\n4365: -\t}\n4366: -}\n4367: -\n4368:  func drain(sink chan clablabruntime.Event) []clablabruntime.Event {\n4369:  \tvar events []clablabruntime.Event\n4370:  \tfor {\n4371:  \t\tselect {\n4372:  \t\tcase ev := <-sink:\n4373: diff --git a/labruntime/clabernetes/state.go b/labruntime/clabernetes/state.go\n4374: index ead2c45..d06385c 100644\n4375: --- a/labruntime/clabernetes/state.go\n4376: +++ b/labruntime/clabernetes/state.go\n4377: @@ -22,10 +22,17 @@ func stateFromNodeResources(\n4378:  \tstate := &clablabruntime.LabState{\n4379:  \t\tName:         name,\n4380:  \t\tNamespace:    namespace,\n4381:  \t\tTopologyPath: fmt.Sprintf(\"k8s://%s/labs/%s\", namespace, name),\n4382:  \t}\n4383: +\t// Without a Topology resource the Nodes record the file the lab was deployed from.\n4384: +\tfor idx := range nodeResources {\n4385: +\t\tif path := nodeResources[idx].GetAnnotations()[annotationTopologyFile]; path != \"\" {\n4386: +\t\t\tstate.TopologyPath = path\n4387: +\t\t\tbreak\n4388: +\t\t}\n4389: +\t}\n4390:  \tif len(nodeResources) != 0 {\n4391:  \t\tstate.Owner = nodeResources[0].GetLabels()[clabconstants.Owner]\n4392:  \t\tif state.Owner == \"\" {\n4393:  \t\t\tstate.Owner = nodeResources[0].GetAnnotations()[clabconstants.Owner]\n4394:  \t\t}\n4395: @@ -42,15 +49,20 @@ func stateFromNodeResources(\n\n(Output capped at 50 KB. Showing lines 2845-4395. Use offset=4396 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+\t\t[]*unstructured.Unstructured{\n+\t\t\ttrackerTestNode(\"r1\", nodeRunStateRunning, condition(\"Ready\", \"True\")),\n+\t\t\t// its peer is stopped: not ready, but the device is\n+\t\t\ttrackerTestNode(\"r2\", nodeRunStateRunning,\n+\t\t\t\tcondition(nodeConditionContainersReady, \"True\")),\n+\t\t\ttrackerTestNode(\"r3\", nodeRunStateRunning),\n+\t\t\ttrackerTestNode(\"r4\", nodeRunStateStopped, condition(nodeConditionStopped, \"True\")),\n+\t\t},\n+\t\t[]k8sruntime.Object{\n+\t\t\tcaptureTestPod(\"lab1-r1-a\", \"r1\"),\n+\t\t\tcaptureTestPod(\"lab1-r2-a\", \"r2\"),\n+\t\t\twithNodeUID(captureTestPod(\"lab1-r3-a\", \"r3\"), \"uid-r3\"),\n+\t\t\t// the newer pod of an earlier Node r3 that still terminates is not r3's pod\n+\t\t\twithNodeUID(withCreation(captureTestPod(\"lab1-r3-stale\", \"r3\"), time.Hour), \"uid-old\"),\n+\t\t},\n+\t)\n+\n+\tstate := &clablabruntime.LabState{Name: \"lab1\", Namespace: \"lab-ns\"}\n+\tif err := r.enrichState(context.Background(), state); err != nil {\n+\t\tt.Fatal(err)",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+\t\t[]*unstructured.Unstructured{\n+\t\t\ttrackerTestNode(\"r1\", nodeRunStateRunning, condition(\"Ready\", \"True\")),\n+\t\t\t// its peer is stopped: not ready, but the device is\n+\t\t\ttrackerTestNode(\"r2\", nodeRunStateRunning,\n+\t\t\t\tcondition(nodeConditionContainersReady, \"True\")),\n+\t\t\ttrackerTestNode(\"r3\", nodeRunStateRunning),\n+\t\t\ttrackerTestNode(\"r4\", nodeRunStateStopped, condition(nodeConditionStopped, \"True\")),\n+\t\t},\n+\t\t[]k8sruntime.Object{\n+\t\t\tcaptureTestPod(\"lab1-r1-a\", \"r1\"),\n+\t\t\tcaptureTestPod(\"lab1-r2-a\", \"r2\"),\n+\t\t\twithNodeUID(captureTestPod(\"lab1-r3-a\", \"r3\"), \"uid-r3\"),\n+\t\t\t// the newer pod of an earlier Node r3 that still terminates is not r3's pod\n+\t\t\twithNodeUID(withCreation(captureTestPod(\"lab1-r3-stale\", \"r3\"), time.Hour), \"uid-old\"),\n+\t\t},\n+\t)\n+\n+\tstate := &clablabruntime.LabState{Name: \"lab1\", Namespace: \"lab-ns\"}\n+\tif err := r.enrichState(context.Background(), state); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\n+\twant := map[string]string{\n+\t\t\"r1\": \"running/healthy\", \"r2\": \"running/healthy\", \"r3\": \"running/starting\", \"r4\": \"exited/\",\n+\t}\n+\tfor _, node := range state.Nodes {\n+\t\tif node.Name == \"r3\" && node.Pod != \"lab1-r3-a\" {\n+\t\t\tt.Fatalf(\"r3 pod = %q, want its own Node's pod\", node.Pod)\n+\t\t}\n+\t\tif got := node.ContainerState + \"/\" + node.Health; got != want[node.Name] {\n+\t\t\tt.Fatalf(\"%s = %s, want %s\", node.Name, got, want[node.Name])\n+\t\t}\n+\t\tif node.TopologyName != strings.ToUpper(node.Name) {\n+\t\t\tt.Fatalf(\"%s topology name = %q\", node.Name, node.TopologyName)\n+\t\t}\n+\t}\n+}\n+\n+const sourceDefinition = `name: lab1\n+topology:\n+  nodes:\n+    node1:\n+      kind: linux\n+      image: alpine:latest\n+    node2:\n+      kind: linux\n+      image: alpine:latest\n+  links:\n+    - endpoints: [\"node1:eth1\", \"node2:eth1\"]\n+`\n+\n+func sourceDeployRequest(path string, noTopologyCR bool) clablabruntime.DeployRequest {\n+\treturn clablabruntime.DeployRequest{\n+\t\tName:               \"lab1\",\n+\t\tNamespace:          \"lab-ns\",\n+\t\tTopologyFile:       path,\n+\t\tTopologyDefinition: []byte(sourceDefinition),\n+\t\tNoTopologyCR:       noTopologyCR,\n+\t}\n+}\n+\n+// TestDeployRecordsTheTopologyFile checks where a deploy records the topology file and that\n+// inspect reports it, with and without a Topology resource.\n+func TestDeployRecordsTheTopologyFile(t *testing.T) {\n+\tt.Parallel()\n+\n+\t// with a Topology resource: on the Topology, updated by every deploy\n+\tr := newTestRuntime()\n+\tif _, err := r.Deploy(context.Background(),\n+\t\tsourceDeployRequest(\"/home/alice/labs/lab1.clab.yml\", false)); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\ttopology := getTestTopology(t, r, \"lab-ns\", \"lab1\")\n+\tif got := topology.GetAnnotations()[annotationTopologyFile]; got != \"/home/alice/labs/lab1.clab.yml\" {\n+\t\tt.Fatalf(\"Topology annotation = %q\", got)\n+\t}\n+\tstate, err := r.Inspect(context.Background(),\n+\t\tclablabruntime.InspectRequest{Name: \"lab1\", Namespace: \"lab-ns\"})\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif state.TopologyPath != \"/home/alice/labs/lab1.clab.yml\" {\n+\t\tt.Fatalf(\"TopologyPath = %q\", state.TopologyPath)\n+\t}\n+\n+\tif _, err := r.Deploy(context.Background(),\n+\t\tsourceDeployRequest(\"/srv/labs/lab1.clab.yml\", false)); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\ttopology = getTestTopology(t, r, \"lab-ns\", \"lab1\")\n+\tif got := topology.GetAnnotations()[annotationTopologyFile]; got != \"/srv/labs/lab1.clab.yml\" {\n+\t\tt.Fatalf(\"Topology annotation after a deploy from another file = %q\", got)\n+\t}\n+\n+\t// without a Topology resource: on the Nodes only, kept from their creation\n+\tr = newTestRuntime()\n+\tif _, err := r.Deploy(context.Background(),\n+\t\tsourceDeployRequest(\"/home/alice/labs/lab1.clab.yml\", true)); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tassertPrimitiveTopologyFile(t, r, \"/home/alice/labs/lab1.clab.yml\")\n+\tstate, err = r.Inspect(context.Background(),\n+\t\tclablabruntime.InspectRequest{Name: \"lab1\", Namespace: \"lab-ns\"})\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tif state.TopologyPath != \"/home/alice/labs/lab1.clab.yml\" {\n+\t\tt.Fatalf(\"TopologyPath without a Topology = %q\", state.TopologyPath)\n+\t}\n+\n+\tplan, err := r.Plan(context.Background(),\n+\t\tsourceDeployRequest(\"/srv/labs/lab1.clab.yml\", true))\n+\tif err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tfor _, change := range plan.Changes {\n+\t\tif change.Kind == \"Node\" {\n+\t\t\tt.Fatalf(\"a deploy from another file would change %+v and replace its pod\", change)\n+\t\t}\n+\t}\n+\tif _, err := r.Deploy(context.Background(),\n+\t\tsourceDeployRequest(\"/srv/labs/lab1.clab.yml\", true)); err != nil {\n+\t\tt.Fatal(err)\n+\t}\n+\tassertPrimitiveTopologyFile(t, r, \"/home/alice/labs/lab1.clab.yml\")\n+}\n+\n+func assertPrimitiveTopologyFile(t *testing.T, r *Runtime, want string) {\n+\tt.Helper()\n+\n+\tfor _, gvr := range []struct {\n+\t\tname string\n+\t\twant string\n+\t}{{\"nodes\", want}, {\"links\", \"\"}, {\"nodeprofiles\", \"\"}} {\n+\t\tresource := nodeGVR\n+\t\tswitch gvr.name {\n+\t\tcase \"links\":\n+\t\t\tresource = linkGVR\n+\t\tcase \"nodeprofiles\":\n+\t\t\tresource = nodeProfileGVR\n+\t\t}\n+\t\tlist, err := r.client.Resource(resource).Namespace(\"lab-ns\").\n+\t\t\tList(context.Background(), metav1.ListOptions{})\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\tfor idx := range list.Items {\n+\t\t\tif got := list.Items[idx].GetAnnotations()[annotationTopologyFile]; got != gvr.want {\n+\t\t\t\tt.Fatalf(\"%s %s annotation = %q, want %q\", gvr.name, list.Items[idx].GetName(),\n+\t\t\t\t\tgot, gvr.want)\n+\t\t\t}\n+\t\t}\n+\t}\n+}\n+\n+func TestCarryOverNodeTopologyFile(t *testing.T) {\n+\tt.Parallel()\n+\n+\tnode := func(annotations map[string]any) *unstructured.Unstructured {\n+\t\tmetadata := map[string]any{\"name\": \"node1\"}\n+\t\tif annotations != nil {\n+\t\t\tmetadata[\"annotations\"] = annotations\n+\t\t}\n+\n+\t\treturn &unstructured.Unstructured{Object: map[string]any{\n+\t\t\t\"apiVersion\": c9sAPIVersion, \"kind\": \"Node\", \"metadata\": metadata,\n+\t\t\t\"spec\": map[string]any{\"image\": \"alpine\"},\n+\t\t}}\n+\t}\n+\tdesired := node(map[string]any{annotationTopologyFile: \"/new.clab.yml\"})\n+\n+\tupdated := reconciledPrimitiveObject(\n+\t\tnode(map[string]any{annotationTopologyFile: \"/old.clab.yml\"}),\n+\t\tdesired,\n+\t)\n+\tif got := updated.GetAnnotations()[annotationTopologyFile]; got != \"/old.clab.yml\" {\n+\t\tt.Fatalf(\"existing Node file = %q, want it kept\", got)\n+\t}\n+\n+\t// a Node deployed before containerlab recorded files does not get one\n+\texisting := node(nil)\n+\tupdated = reconciledPrimitiveObject(existing, desired)\n+\tif _, ok := updated.GetAnnotations()[annotationTopologyFile]; ok ||\n+\t\t!primitiveObjectsConform(existing, updated) {\n+\t\tt.Fatalf(\"Node without a file = %+v\", updated.GetAnnotations())\n+\t}\n+\n+\t// the Topology always records the latest file\n+\ttopology := topologyObject(\"lab1\", \"lab-ns\", \"\", \"topology:\\n\")\n+\tsetTopologySourceFile(topology, \"/old.clab.yml\")\n+\tnewTopology := topologyObject(\"lab1\", \"lab-ns\", \"\", \"topology:\\n\")\n+\tsetTopologySourceFile(newTopology, \"/new.clab.yml\")\n+\tupdated = reconciledPrimitiveObject(topology, newTopology)\n+\tif got := updated.GetAnnotations()[annotationTopologyFile]; got != \"/new.clab.yml\" {\n+\t\tt.Fatalf(\"Topology file = %q\", got)\n+\t}\n+}\n+\n+func TestManifestsCarryNoTopologyFile(t *testing.T) {\n+\tt.Parallel()\n+\n+\tfor _, noTopologyCR := range []bool{false, true} {\n+\t\tmanifests, err := (&Runtime{}).Manifests(context.Background(),\n+\t\t\tsourceDeployRequest(\"/home/alice/labs/lab1.clab.yml\", noTopologyCR))\n+\t\tif err != nil {\n+\t\t\tt.Fatal(err)\n+\t\t}\n+\t\tfor _, manifest := range manifests {\n+\t\t\tdata, _ := json.Marshal(manifest.Object)\n+\t\t\tif strings.Contains(string(data), annotationTopologyFile) {\n+\t\t\t\tt.Fatalf(\"no-topology-cr=%t: %s %s carries the file\", noTopologyCR,\n+\t\t\t\t\tmanifest.Kind, manifest.Name)\n+\t\t\t}\n+\t\t}\n+\t}\n+}\n+\n+func TestStateReportsTheRecordedTopologyFile(t *testing.T) {\n+\tt.Parallel()\n+\n+\ttopology := topologyObject(\"lab1\", \"lab-ns\", \"\", \"topology:\\n\")\n+\tif got := stateFromTopology(\n+\t\ttopology,\n+\t\t\"lab-ns\",\n+\t).TopologyPath; got != \"k8s://lab-ns/topologies/lab1\" {\n+\t\tt.Fatalf(\"lab created by other means = %q\", got)\n+\t}\n+\tsetTopologySourceFile(topology, \"/home/alice/lab1.clab.yml\")\n+\tif got := stateFromTopology(\n+\t\ttopology,\n+\t\t\"lab-ns\",\n+\t).TopologyPath; got != \"/home/alice/lab1.clab.yml\" {\n+\t\tt.Fatalf(\"deployed lab = %q\", got)\n+\t}\n+\n+\tnodes := []unstructured.Unstructured{*trackerTestNode(\"r1\", nodeRunStateRunning)}\n+\tif got := stateFromNodeResources(\"lab1\", \"lab-ns\", nodes).TopologyPath; got !=\n+\t\t\"k8s://lab-ns/labs/lab1\" {\n+\t\tt.Fatalf(\"Nodes created by other means = %q\", got)\n+\t}\n+\tnodes[0].SetAnnotations(map[string]string{annotationTopologyFile: \"/home/alice/lab1.clab.yml\"})\n+\tif got := stateFromNodeResources(\"lab1\", \"lab-ns\", nodes).TopologyPath; got !=\n+\t\t\"/home/alice/lab1.clab.yml\" {\n+\t\tt.Fatalf(\"deployed Nodes = %q\", got)\n+\t}\n+}\n+\n+func withNodeUID(pod *corev1.Pod, uid string) *corev1.Pod {\n+\tif pod.Annotations == nil {\n+\t\tpod.Annotations = map[string]string{}\n+\t}\n+\tpod.Annotations[annotationDirectNodeUID] = uid\n+\n+\treturn pod\n+}\n+\n+func withCreation(pod *corev1.Pod, age time.Duration) *corev1.Pod {\n+\tpod.CreationTimestamp = metav1.NewTime(time.Now().Add(age))\n+\n+\treturn pod\n+}\ndiff --git a/labruntime/clabernetes/events.go b/labruntime/clabernetes/events.go\nindex 37548dc..b06dc9d 100644\n--- a/labruntime/clabernetes/events.go\n+++ b/labruntime/clabernetes/events.go\n@@ -30,31 +30,49 @@ func (r *Runtime) StreamEvents(\n \tif err != nil {\n \t\treturn nil, nil, err\n \t}\n \n \tevents := make(chan clablabruntime.Event, 128)\n-\terrs := make(chan error, 3)\n+\terrs := make(chan error, 4)\n+\t// changed carries the labs whose Topology, Nodes or pods changed; the container tracker\n+\t// reads them again and reports what changed for their nodes.\n+\tchanged := make(chan labRef, 256)\n \n-\tif req.IncludeInitialState {\n-\t\tgo r.emitInitialEvents(ctx, scope, events, errs)\n-\t}\n+\tgo r.trackContainers(ctx, scope, req.IncludeInitialState, changed, events, errs)\n \n \t// Interface state events are always reported, like the netlink-backed events of the local\n \t// runtimes; statistics only on request. Both come from the same exec per node.\n \tgo r.pollInterfaces(ctx, scope, interfacePollOptions{\n \t\tinterval:            req.StatsInterval,\n \t\tincludeStats:        req.IncludeInterfaceStats,\n \t\tincludeInitialState: req.IncludeInitialState,\n \t}, events)\n \n-\tgo r.watchTopologies(ctx, scope, events, errs)\n-\tgo r.watchNodes(ctx, scope, events, errs)\n-\tgo r.watchPods(ctx, scope, events, errs)\n+\tgo r.watchTopologies(ctx, scope, changed, events, errs)\n+\tgo r.watchNodes(ctx, scope, changed, errs)\n+\tgo r.watchPods(ctx, scope, changed, errs)\n \n \treturn events, errs, nil\n }\n \n+// labRef names a lab in a namespace.\n+type labRef struct {\n+\tnamespace string\n+\tlab       string\n+}\n+\n+func sendChangedLab(ctx context.Context, changed chan<- labRef, ref labRef) {\n+\tif ref.lab == \"\" {\n+\t\treturn\n+\t}\n+\n+\tselect {\n+\tcase changed <- ref:\n+\tcase <-ctx.Done():\n+\t}\n+}\n+\n // eventScope is the namespace and, optionally, the single lab an event stream covers.\n type eventScope struct {\n \tnamespace string\n \tlab       string\n }\n@@ -123,11 +141,11 @@ func (r *Runtime) labStates(\n }\n \n func (r *Runtime) watchNodes(\n \tctx context.Context,\n \tscope eventScope,\n-\teventSink chan<- clablabruntime.Event,\n+\tchanged chan<- labRef,\n \terrSink chan<- error,\n ) {\n \tresource := r.client.Resource(nodeGVR).Namespace(scope.namespace)\n \n \tfor {\n@@ -141,24 +159,25 @@ func (r *Runtime) watchNodes(\n \n \t\t\tsendEventError(ctx, errSink, fmt.Errorf(\"failed to watch c9s nodes: %w\", err))\n \t\t\treturn\n \t\t}\n \n-\t\tif !r.forwardNodeWatch(ctx, watcher, eventSink, errSink) {\n+\t\tif !r.forwardNodeWatch(ctx, watcher, changed, errSink) {\n \t\t\treturn\n \t\t}\n \n \t\tif !sleepContext(ctx, pollInterval) {\n \t\t\treturn\n \t\t}\n \t}\n }\n \n+// forwardNodeWatch reports the lab of every changed Node to the container tracker.\n func (r *Runtime) forwardNodeWatch(\n \tctx context.Context,\n \twatcher watch.Interface,\n-\teventSink chan<- clablabruntime.Event,\n+\tchanged chan<- labRef,\n \terrSink chan<- error,\n ) bool {\n \tdefer watcher.Stop()\n \n \tfor {\n@@ -178,73 +197,22 @@ func (r *Runtime) forwardNodeWatch(\n \t\t\tnode, ok := ev.Object.(*unstructured.Unstructured)\n \t\t\tif !ok {\n \t\t\t\tcontinue\n \t\t\t}\n \n-\t\t\tlabName := node.GetLabels()[labelTopologyOwner]\n-\t\t\tif labName == \"\" {\n-\t\t\t\tcontinue\n-\t\t\t}\n-\t\t\treadiness, _, _ := unstructured.NestedString(node.Object, \"status\", \"readiness\")\n-\t\t\tr.sendEvent(ctx, eventSink, clablabruntime.Event{\n-\t\t\t\tTimestamp: time.Now(),\n-\t\t\t\tType:      \"container\",\n-\t\t\t\tAction:    strings.ToLower(string(ev.Type)),\n-\t\t\t\tActorID:   fmt.Sprintf(\"%s/%s/%s\", node.GetNamespace(), labName, node.GetName()),\n-\t\t\t\tActorName: fmt.Sprintf(\"%s-%s\", labName, node.GetName()),\n-\t\t\t\tAttributes: map[string]string{\n-\t\t\t\t\t\"namespace\": node.GetNamespace(),\n-\t\t\t\t\t\"lab\":       labName,\n-\t\t\t\t\t\"node\":      node.GetName(),\n-\t\t\t\t\t\"state\":     readiness,\n-\t\t\t\t},\n-\t\t\t})\n-\t\t}\n-\t}\n-}\n-\n-func (r *Runtime) emitInitialEvents(\n-\tctx context.Context,\n-\tscope eventScope,\n-\teventSink chan<- clablabruntime.Event,\n-\terrSink chan<- error,\n-) {\n-\tstates, err := r.labStates(ctx, scope)\n-\tif err != nil {\n-\t\tsendEventError(ctx, errSink, err)\n-\t\treturn\n-\t}\n-\n-\tfor _, state := range states {\n-\t\tfor _, node := range state.Nodes {\n-\t\t\taction := node.State\n-\t\t\tif node.Ready {\n-\t\t\t\taction = \"running\"\n-\t\t\t}\n-\t\t\tif action == \"\" {\n-\t\t\t\taction = state.State\n-\t\t\t}\n-\t\t\tr.sendEvent(ctx, eventSink, clablabruntime.Event{\n-\t\t\t\tTimestamp: time.Now(),\n-\t\t\t\tType:      \"container\",\n-\t\t\t\tAction:    action,\n-\t\t\t\tActorID:   fmt.Sprintf(\"%s/%s/%s\", state.Namespace, state.Name, node.Name),\n-\t\t\t\tActorName: fmt.Sprintf(\"%s-%s\", state.Name, node.Name),\n-\t\t\t\tAttributes: map[string]string{\n-\t\t\t\t\t\"namespace\": state.Namespace,\n-\t\t\t\t\t\"lab\":       state.Name,\n-\t\t\t\t\t\"node\":      node.Name,\n-\t\t\t\t\t\"state\":     node.State,\n-\t\t\t\t},\n+\t\t\tsendChangedLab(ctx, changed, labRef{\n+\t\t\t\tnamespace: node.GetNamespace(),\n+\t\t\t\tlab:       node.GetLabels()[labelTopologyOwner],\n \t\t\t})\n \t\t}\n \t}\n }\n \n func (r *Runtime) watchTopologies(\n \tctx context.Context,\n \tscope eventScope,\n+\tchanged chan<- labRef,\n \teventSink chan<- clablabruntime.Event,\n \terrSink chan<- error,\n ) {\n \tresource := r.client.Resource(topologyGVR).Namespace(scope.namespace)\n \n@@ -261,24 +229,27 @@ func (r *Runtime) watchTopologies(\n \t\t\t\tfmt.Errorf(\"failed to watch clabernetes topologies: %w\", err),\n \t\t\t)\n \t\t\treturn\n \t\t}\n \n-\t\tif !r.forwardTopologyWatch(ctx, scope.namespace, watcher, eventSink, errSink) {\n+\t\tif !r.forwardTopologyWatch(ctx, scope.namespace, watcher, changed, eventSink, errSink) {\n \t\t\treturn\n \t\t}\n \n \t\tif !sleepContext(ctx, pollInterval) {\n \t\t\treturn\n \t\t}\n \t}\n }\n \n+// forwardTopologyWatch reports Topology changes as topology events, which only c9s has, and\n+// reports the lab to the container tracker.\n func (r *Runtime) forwardTopologyWatch(\n \tctx context.Context,\n \tnamespace string,\n \twatcher watch.Interface,\n+\tchanged chan<- labRef,\n \teventSink chan<- clablabruntime.Event,\n \terrSink chan<- error,\n ) bool {\n \tdefer watcher.Stop()\n \n@@ -317,18 +288,19 @@ func (r *Runtime) forwardTopologyWatch(\n \t\t\t\t\t\"lab\":       state.Name,\n \t\t\t\t\t\"state\":     state.State,\n \t\t\t\t\t\"ready\":     fmt.Sprintf(\"%t\", state.Ready),\n \t\t\t\t},\n \t\t\t})\n+\t\t\tsendChangedLab(ctx, changed, labRef{namespace: state.Namespace, lab: state.Name})\n \t\t}\n \t}\n }\n \n func (r *Runtime) watchPods(\n \tctx context.Context,\n \tscope eventScope,\n-\teventSink chan<- clablabruntime.Event,\n+\tchanged chan<- labRef,\n \terrSink chan<- error,\n ) {\n \tfor {\n \t\twatcher, err := r.kubeClient.CoreV1().Pods(scope.namespace).Watch(ctx, metav1.ListOptions{\n \t\t\tLabelSelector: scope.labelSelector(),\n@@ -341,24 +313,25 @@ func (r *Runtime) watchPods(\n \t\t\tsendEventError(ctx, errSink, fmt.Errorf(\n \t\t\t\t\"failed to watch clabernetes pods: %w\", err))\n \t\t\treturn\n \t\t}\n \n-\t\tif !r.forwardPodWatch(ctx, watcher, eventSink, errSink) {\n+\t\tif !r.forwardPodWatch(ctx, watcher, changed, errSink) {\n \t\t\treturn\n \t\t}\n \n \t\tif !sleepContext(ctx, pollInterval) {\n \t\t\treturn\n \t\t}\n \t}\n }\n \n+// forwardPodWatch reports the lab of every changed pod to the container tracker.\n func (r *Runtime) forwardPodWatch(\n \tctx context.Context,\n \twatcher watch.Interface,\n-\teventSink chan<- clablabruntime.Event,\n+\tchanged chan<- labRef,\n \terrSink chan<- error,\n ) bool {\n \tdefer watcher.Stop()\n \n \tfor {\n@@ -379,31 +352,13 @@ func (r *Runtime) forwardPodWatch(\n \t\t\tpod, ok := ev.Object.(*corev1.Pod)\n \t\t\tif !ok {\n \t\t\t\tcontinue\n \t\t\t}\n \n-\t\t\tlabName := pod.Labels[labelTopologyOwner]\n-\t\t\tnodeName := pod.Labels[labelTopologyNode]\n-\t\t\tif labName == \"\" || nodeName == \"\" {\n-\t\t\t\tcontinue\n-\t\t\t}\n-\n-\t\t\tr.sendEvent(ctx, eventSink, clablabruntime.Event{\n-\t\t\t\tTimestamp:   time.Now(),\n-\t\t\t\tType:        \"container\",\n-\t\t\t\tAction:      strings.ToLower(string(ev.Type)),\n-\t\t\t\tActorID:     fmt.Sprintf(\"%s/%s/%s\", pod.Namespace, labName, nodeName),\n-\t\t\t\tActorName:   fmt.Sprintf(\"%s-%s\", labName, nodeName),\n-\t\t\t\tActorFullID: pod.Name,\n-\t\t\t\tAttributes: map[string]string{\n-\t\t\t\t\t\"namespace\": pod.Namespace,\n-\t\t\t\t\t\"lab\":       labName,\n-\t\t\t\t\t\"node\":      nodeName,\n-\t\t\t\t\t\"pod\":       pod.Name,\n-\t\t\t\t\t\"phase\":     string(pod.Status.Phase),\n-\t\t\t\t\t\"pod_ip\":    pod.Status.PodIP,\n-\t\t\t\t},\n+\t\t\tsendChangedLab(ctx, changed, labRef{\n+\t\t\t\tnamespace: pod.Namespace,\n+\t\t\t\tlab:       pod.Labels[labelTopologyOwner],\n \t\t\t})\n \t\t}\n \t}\n }\n \ndiff --git a/labruntime/clabernetes/iface_stats.go b/labruntime/clabernetes/iface_stats.go\nindex 09abca3..a6c72b0 100644\n--- a/labruntime/clabernetes/iface_stats.go\n+++ b/labruntime/clabernetes/iface_stats.go\n@@ -1,10 +1,11 @@\n package clabernetes\n \n import (\n \t\"context\"\n \t\"fmt\"\n+\t\"sort\"\n \t\"strconv\"\n \t\"strings\"\n \t\"sync\"\n \t\"time\"\n \n@@ -28,16 +29,31 @@ const (\n \t\t`\"$(cat \"$d/flags\")\" \"$(cat \"$d/ifalias\")\"; done 2>/dev/null`\n \n \t// interfaceSampleWorkers bounds the concurrent execs of one sampling round.\n \tinterfaceSampleWorkers = 16\n \n-\t// interfaceStateNotPresent is the operational state reported for an interface that\n-\t// disappeared, or whose node stopped running (RFC 2863 \"notPresent\").\n-\tinterfaceStateNotPresent = \"notpresent\"\n-\n-\t// iffUp is the IFF_UP bit of /sys/class/net/<if>/flags.\n-\tiffUp = 0x1\n+\t// managementInterface is a node's management interface in its pod, the interface the\n+\t// clabernetes planner gives the management address by default. It has the name the\n+\t// management interface has in a container of the local runtimes.\n+\tmanagementInterface = \"eth0\"\n+\t// loopbackInterface is reported like the local runtimes report it.\n+\tloopbackInterface = \"lo\"\n+\t// clabernetesAliasPrefix starts the interface aliases clabernetes marks its own interfaces\n+\t// and the lab links it wires with. They are not the topology's names, so they are not\n+\t// reported.\n+\tclabernetesAliasPrefix = \"c9s:\"\n+\t// zeroMAC is the hardware address sysfs reports for interfaces without one (loopback).\n+\tzeroMAC = \"00:00:00:00:00:00\"\n+\n+\t// Interface event actions and link types, as the local runtimes report them.\n+\tinterfaceActionSnapshot = \"snapshot\"\n+\tinterfaceActionCreate   = \"create\"\n+\tinterfaceActionUpdate   = \"update\"\n+\tinterfaceActionDelete   = \"delete\"\n+\tinterfaceActionStats    = \"stats\"\n+\tinterfaceTypeVeth       = \"veth\"\n+\tinterfaceTypeDevice     = \"device\"\n \n \t// shell exit codes of a command that cannot be found or executed.\n \texitCommandNotExecutable = 126\n \texitCommandNotFound      = 127\n )\n@@ -70,35 +86,16 @@ type c9sIfaceState struct {\n \tOperState string\n \tFlags     uint64\n \tAlias     string\n }\n \n-// action maps the interface state onto the up/down action of interface state events. An\n-// \"unknown\" operational state (loopback, tunnels) counts as up when the interface is\n-// administratively up.\n-func (s c9sIfaceState) action() string {\n-\tif s.OperState == \"up\" || (s.OperState == \"unknown\" && s.Flags&iffUp != 0) {\n-\t\treturn \"up\"\n-\t}\n-\n-\treturn \"down\"\n-}\n-\n-// trackedIface is the last reported state of an interface.\n-type trackedIface struct {\n-\tstate  c9sIfaceState\n-\taction string\n-}\n-\n-// trackedNode remembers the interfaces last reported for a node, so their removal can be\n-// reported when the node stops running.\n+// trackedNode remembers the interfaces last reported for a node, so their changes and their\n+// removal can be reported, also when the node stops running.\n type trackedNode struct {\n-\tnamespace string\n-\tlab       string\n-\tnode      string\n-\tpod       string\n-\tifaces    map[string]trackedIface\n+\tlab    *clablabruntime.LabState\n+\tnode   clablabruntime.NodeState\n+\tifaces map[string]clablabruntime.InterfaceEventData\n }\n \n type interfaceSampleTarget struct {\n \tstate *clablabruntime.LabState\n \tnode  clablabruntime.NodeState\n@@ -108,16 +105,28 @@ type interfaceSampleTarget struct {\n type interfaceSample struct {\n \ttarget    interfaceSampleTarget\n \tstats     []c9sIfaceStats\n \tifaces    []c9sIfaceState\n \thasStates bool\n+\t// links are the node's lab link interfaces as clabwire lists them.\n+\tlinks     []clabwireInterface\n \ttimestamp time.Time\n \terr       error\n }\n \n+// podInterfaceListing is the clabwire interface listing of a pod, per node. It is listed again\n+// when the pod's interfaces change.\n+type podInterfaceListing struct {\n+\tnames  string\n+\tbyNode map[string][]clabwireInterface\n+}\n+\n // interfacePoller samples the interfaces of every running node in an event scope and turns the\n-// samples into interface state and statistics events.\n+// samples into interface events. It reports the interfaces a container of the local runtimes\n+// has for the same node: the node's lab link interfaces, with the names and aliases clabwire\n+// lists for them, the management interface and loopback. The pod's own interfaces (the pod\n+// network, clabernetes' interposition and link transport interfaces) are not reported.\n type interfacePoller struct {\n \tr     *Runtime\n \tscope eventScope\n \topts  interfacePollOptions\n \tsink  chan<- clablabruntime.Event\n@@ -128,10 +137,14 @@ type interfacePoller struct {\n \tnoShellMu sync.Mutex\n \t// noShell holds the pods whose device container has no shell; they are sampled with a\n \t// plain cat of /proc/net/dev and report statistics without interface state.\n \tnoShell map[string]bool\n \n+\tlistingsMu sync.Mutex\n+\t// listings holds the clabwire interface listing per pod (namespace/pod).\n+\tlistings map[string]*podInterfaceListing\n+\n \tfirstRound bool\n }\n \n func (r *Runtime) pollInterfaces(\n \tctx context.Context,\n@@ -141,21 +154,11 @@ func (r *Runtime) pollInterfaces(\n ) {\n \tif opts.interval <= 0 {\n \t\topts.interval = time.Second\n \t}\n \n-\tpoller := &interfacePoller{\n-\t\tr:            r,\n-\t\tscope:        scope,\n-\t\topts:         opts,\n-\t\tsink:         eventSink,\n-\t\tstatsSamples: map[string]c9sIfaceStatsSample{},\n-\t\tnodes:        map[string]*trackedNode{},\n-\t\tnoShell:      map[string]bool{},\n-\t\tfirstRound:   true,\n-\t}\n-\n+\tpoller := newInterfacePoller(r, scope, opts, eventSink)\n \tpoller.round(ctx)\n \n \tticker := time.NewTicker(opts.interval)\n \tdefer ticker.Stop()\n \n@@ -167,28 +170,50 @@ func (r *Runtime) pollInterfaces(\n \t\t\tpoller.round(ctx)\n \t\t}\n \t}\n }\n \n+func newInterfacePoller(\n+\tr *Runtime,\n+\tscope eventScope,\n+\topts interfacePollOptions,\n+\teventSink chan<- clablabruntime.Event,\n+) *interfacePoller {\n+\treturn &interfacePoller{\n+\t\tr:            r,\n+\t\tscope:        scope,\n+\t\topts:         opts,\n+\t\tsink:         eventSink,\n+\t\tstatsSamples: map[string]c9sIfaceStatsSample{},\n+\t\tnodes:        map[string]*trackedNode{},\n+\t\tnoShell:      map[string]bool{},\n+\t\tlistings:     map[string]*podInterfaceListing{},\n+\t\tfirstRound:   true,\n+\t}\n+}\n+\n func (p *interfacePoller) round(ctx context.Context) {\n \tdefer func() { p.firstRound = false }()\n \n \tstates, err := p.r.labStates(ctx, p.scope)\n \tif err != nil {\n \t\tlog.Debug(\"failed to list C9s labs for interface events\", \"error\", err)\n \t\treturn\n \t}\n \n \trunning := map[string]bool{}\n+\tpods := map[string]bool{}\n \tvar targets []interfaceSampleTarget\n \tfor _, state := range states {\n \t\tfor _, node := range state.Nodes {\n-\t\t\tif !node.Ready || node.Pod == \"\" || node.Container == \"\" {\n+\t\t\tif node.ContainerState != clablabruntime.ContainerStateRunning || node.Pod == \"\" ||\n+\t\t\t\tnode.Container == \"\" {\n \t\t\t\tcontinue\n \t\t\t}\n \n \t\t\trunning[c9sNodeKey(state.Namespace, state.Name, node.Name)] = true\n+\t\t\tpods[state.Namespace+\"/\"+node.Pod] = true\n \t\t\ttargets = append(targets, interfaceSampleTarget{\n \t\t\t\tstate: state,\n \t\t\t\tnode:  node,\n \t\t\t\tpod: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{\n \t\t\t\t\tName:      node.Pod,\n@@ -215,29 +240,41 @@ func (p *interfacePoller) round(ctx context.Context) {\n \n \t\tp.processSample(ctx, sample)\n \t}\n \n \tp.retireStoppedNodes(ctx, running)\n+\tp.forgetListings(pods)\n }\n \n // retireStoppedNodes reports the interfaces of nodes that stopped running, or were removed, as\n-// down: they are gone with the node's pod.\n+// deleted: they are gone with the node's pod.\n func (p *interfacePoller) retireStoppedNodes(ctx context.Context, running map[string]bool) {\n \tfor key, tracked := range p.nodes {\n \t\tif running[key] {\n \t\t\tcontinue\n \t\t}\n \n-\t\tfor name, iface := range tracked.ifaces {\n-\t\t\tiface.state.OperState = interfaceStateNotPresent\n-\t\t\tp.emitState(ctx, tracked, iface.state, time.Now())\n+\t\tfor _, name := range sortedInterfaceNames(tracked.ifaces) {\n+\t\t\tp.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], time.Now())\n \t\t\tp.forgetStats(tracked, name)\n \t\t}\n \t\tdelete(p.nodes, key)\n \t}\n }\n \n+// forgetListings drops the interface listings of pods that are gone.\n+func (p *interfacePoller) forgetListings(pods map[string]bool) {\n+\tp.listingsMu.Lock()\n+\tdefer p.listingsMu.Unlock()\n+\n+\tfor key := range p.listings {\n+\t\tif !pods[key] {\n+\t\t\tdelete(p.listings, key)\n+\t\t}\n+\t}\n+}\n+\n func (p *interfacePoller) sampleAll(\n \tctx context.Context,\n \ttargets []interfaceSampleTarget,\n ) []interfaceSample {\n \tsamples := make([]interfaceSample, len(targets))\n@@ -298,152 +335,318 @@ func (p *interfacePoller) sample(\n \tcase rc != 0:\n \t\tsample.err = fmt.Errorf(\"exit code %d: %s\", rc, strings.TrimSpace(string(stderr)))\n \tdefault:\n \t\tsample.stats, sample.ifaces, sample.hasStates, sample.err = parseInterfaceSample(stdout)\n \t}\n+\tif sample.err != nil {\n+\t\treturn sample\n+\t}\n+\n+\tsample.links, sample.err = p.nodeLinks(ctx, target, sampledInterfaceNames(sample))\n \n \treturn sample\n }\n \n+// sampledInterfaceNames lists the interface names a sample saw, sorted and comma-joined.\n+func sampledInterfaceNames(sample interfaceSample) string {\n+\tnames := make([]string, 0, len(sample.stats)+len(sample.ifaces))\n+\tseen := map[string]bool{}\n+\tfor _, iface := range sample.ifaces {\n+\t\tif !seen[iface.Name] {\n+\t\t\tseen[iface.Name] = true\n+\t\t\tnames = append(names, iface.Name)\n+\t\t}\n+\t}\n+\tfor _, stat := range sample.stats {\n+\t\tif !seen[stat.Name] {\n+\t\t\tseen[stat.Name] = true\n+\t\t\tnames = append(names, stat.Name)\n+\t\t}\n+\t}\n+\tsort.Strings(names)\n+\n+\treturn strings.Join(names, \",\")\n+}\n+\n+// nodeLinks returns the lab link interfaces of a node from its pod's clabwire listing. A pod is\n+// listed once, and again when its interfaces change (a pod gets its link interfaces as clabwire\n+// wires them).\n+func (p *interfacePoller) nodeLinks(\n+\tctx context.Context,\n+\ttarget interfaceSampleTarget,\n+\tnames string,\n+) ([]clabwireInterface, error) {\n+\tkey := target.pod.Namespace + \"/\" + target.pod.Name\n+\n+\tp.listingsMu.Lock()\n+\tlisting := p.listings[key]\n+\tp.listingsMu.Unlock()\n+\n+\tif listing == nil || listing.names != names {\n+\t\tentries, err := p.r.listPodInterfaces(ctx, target.pod.Namespace, target.pod.Name)\n+\t\tif err != nil {\n+\t\t\treturn nil, err\n+\t\t}\n+\n+\t\tlisting = &podInterfaceListing{\n+\t\t\tnames:  names,\n+\t\t\tbyNode: map[string][]clabwireInterface{},\n+\t\t}\n+\t\tfor _, entry := range entries {\n+\t\t\tlisting.byNode[entry.Node] = append(listing.byNode[entry.Node], entry)\n+\t\t}\n+\n+\t\tp.listingsMu.Lock()\n+\t\tp.listings[key] = listing\n+\t\tp.listingsMu.Unlock()\n+\t}\n+\n+\treturn listing.byNode[target.node.Name], nil\n+}\n+\n // commandNotExecutable reports an exec that failed because the command does not exist in the\n // container.\n func commandNotExecutable(rc int, err error) bool {\n \tif rc == exitCommandNotExecutable || rc == exitCommandNotFound {\n \t\treturn true\n \t}\n \n \treturn err != nil && strings.Contains(err.Error(), \"executable file not found\")\n }\n \n+// reportedInterfaces are the interfaces reported for a node, by name, with the alias the\n+// topology gave them: its lab link interfaces, the management interface and loopback.\n+func reportedInterfaces(links []clabwireInterface) map[string]string {\n+\treported := map[string]string{\n+\t\tloopbackInterface:   \"\",\n+\t\tmanagementInterface: \"\",\n+\t}\n+\tfor _, link := range links {\n+\t\treported[link.Interface] = link.Alias\n+\t}\n+\n+\treturn reported\n+}\n+\n+// interfaceEventData describes an interface the way the local runtimes' netlink events do: the\n+// alias is the topology's name for the interface (an alias clabernetes set for its own use is\n+// not reported), the operational state uses netlink's names, lab link and management\n+// interfaces are veth pairs, loopback a device, and loopback has no hardware address.\n+func interfaceEventData(iface c9sIfaceState, alias string) clablabruntime.InterfaceEventData {\n+\tif alias == \"\" && !strings.HasPrefix(iface.Alias, clabernetesAliasPrefix) {\n+\t\talias = iface.Alias\n+\t}\n+\n+\tmac := iface.MAC\n+\tif mac == zeroMAC {\n+\t\tmac = \"\"\n+\t}\n+\n+\tlinkType := interfaceTypeVeth\n+\tif iface.Name == loopbackInterface {\n+\t\tlinkType = interfaceTypeDevice\n+\t}\n+\n+\treturn clablabruntime.InterfaceEventData{\n+\t\tName:      iface.Name,\n+\t\tAlias:     alias,\n+\t\tIndex:     iface.Index,\n+\t\tMTU:       iface.MTU,\n+\t\tMAC:       mac,\n+\t\tOperState: netlinkOperState(iface.OperState),\n+\t\tType:      linkType,\n+\t}\n+}\n+\n+// netlinkOperState names an operational state from sysfs (RFC 2863, as in\n+// /sys/class/net/<if>/operstate) the way netlink, and so the local runtimes' events, name it.\n+func netlinkOperState(operState string) string {\n+\tswitch operState {\n+\tcase \"notpresent\":\n+\t\treturn \"not-present\"\n+\tcase \"lowerlayerdown\":\n+\t\treturn \"lower-layer-down\"\n+\tcase \"\":\n+\t\treturn \"unknown\"\n+\tdefault:\n+\t\treturn operState\n+\t}\n+}\n+\n func (p *interfacePoller) processSample(ctx context.Context, sample interfaceSample) {\n \tstate := sample.target.state\n \tnode := sample.target.node\n \tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n \n \ttracked, known := p.nodes[key]\n \tif !known {\n-\t\ttracked = &trackedNode{\n-\t\t\tnamespace: state.Namespace,\n-\t\t\tlab:       state.Name,\n-\t\t\tnode:      node.Name,\n-\t\t\tifaces:    map[string]trackedIface{},\n-\t\t}\n+\t\ttracked = &trackedNode{ifaces: map[string]clablabruntime.InterfaceEventData{}}\n \t\tp.nodes[key] = tracked\n \t}\n-\ttracked.pod = node.Pod\n-\n-\tif p.opts.includeStats {\n-\t\tfor _, stat := range sample.stats {\n-\t\t\tstatsKey := c9sIfaceStatsKey(state.Namespace, state.Name, node.Name, stat.Name)\n-\t\t\tcurrent := c9sIfaceStatsSample{Stats: stat, Timestamp: sample.timestamp}\n+\ttracked.lab = state\n+\ttracked.node = node\n \n-\t\t\tif previous, ok := p.statsSamples[statsKey]; ok {\n-\t\t\t\tp.r.sendEvent(ctx, p.sink,\n-\t\t\t\t\tc9sIfaceStatsEvent(state, node, sample.target.pod, stat, previous, current))\n-\t\t\t}\n+\treported := reportedInterfaces(sample.links)\n \n-\t\t\tp.statsSamples[statsKey] = current\n-\t\t}\n+\tif sample.hasStates {\n+\t\tp.processStates(ctx, tracked, reported, sample)\n \t}\n \n-\tif !sample.hasStates {\n+\tif !p.opts.includeStats {\n \t\treturn\n \t}\n+\tfor _, stat := range sample.stats {\n+\t\talias, ok := reported[stat.Name]\n+\t\tif !ok {\n+\t\t\tcontinue\n+\t\t}\n+\n+\t\tstatsKey := c9sIfaceStatsKey(state.Namespace, state.Name, node.Name, stat.Name)\n+\t\tcurrent := c9sIfaceStatsSample{Stats: stat, Timestamp: sample.timestamp}\n+\t\tif previous, ok := p.statsSamples[statsKey]; ok {\n+\t\t\tdata, ok := tracked.ifaces[stat.Name]\n+\t\t\tif !ok {\n+\t\t\t\tdata = interfaceEventData(c9sIfaceState{Name: stat.Name}, alias)\n+\t\t\t\tdata.OperState = \"\"\n+\t\t\t}\n+\t\t\tdata.Stats = c9sIfaceStatsData(previous, current)\n+\t\t\tp.emit(ctx, tracked, interfaceActionStats, data, current.Timestamp)\n+\t\t}\n \n-\tpresent := make(map[string]bool, len(sample.ifaces))\n+\t\tp.statsSamples[statsKey] = current\n+\t}\n+}\n+\n+// processStates reports the interfaces that appeared (snapshot in the first round with\n+// --initial-state, create later), changed (update) or disappeared (delete) since the last\n+// sample, like the netlink events of the local runtimes.\n+func (p *interfacePoller) processStates(\n+\tctx context.Context,\n+\ttracked *trackedNode,\n+\treported map[string]string,\n+\tsample interfaceSample,\n+) {\n+\tpresent := map[string]bool{}\n \tfor _, iface := range sample.ifaces {\n-\t\tpresent[iface.Name] = true\n+\t\talias, ok := reported[iface.Name]\n+\t\tif !ok {\n+\t\t\tcontinue\n+\t\t}\n \n-\t\taction := iface.action()\n+\t\tdata := interfaceEventData(iface, alias)\n+\t\tpresent[iface.Name] = true\n \t\tprevious, seen := tracked.ifaces[iface.Name]\n-\t\ttracked.ifaces[iface.Name] = trackedIface{state: iface, action: action}\n+\t\ttracked.ifaces[iface.Name] = data\n \n \t\tswitch {\n-\t\tcase seen && previous.action == action &&\n-\t\t\tprevious.state.OperState == iface.OperState:\n-\t\t\tcontinue\n-\t\tcase !seen && p.firstRound && !p.opts.includeInitialState:\n+\t\tcase seen && previous == data:\n+\t\tcase !seen && p.firstRound:\n \t\t\t// Interfaces that exist when the stream starts are only reported with\n \t\t\t// --initial-state; later changes are always reported.\n-\t\t\tcontinue\n+\t\t\tif p.opts.includeInitialState {\n+\t\t\t\tp.emit(ctx, tracked, interfaceActionSnapshot, data, sample.timestamp)\n+\t\t\t}\n+\t\tcase !seen:\n+\t\t\tp.emit(ctx, tracked, interfaceActionCreate, data, sample.timestamp)\n+\t\tdefault:\n+\t\t\tp.emit(ctx, tracked, interfaceActionUpdate, data, sample.timestamp)\n \t\t}\n-\n-\t\tp.emitState(ctx, tracked, iface, sample.timestamp)\n \t}\n \n-\tfor name, iface := range tracked.ifaces {\n+\tfor _, name := range sortedInterfaceNames(tracked.ifaces) {\n \t\tif present[name] {\n \t\t\tcontinue\n \t\t}\n \n-\t\tiface.state.OperState = interfaceStateNotPresent\n-\t\tp.emitState(ctx, tracked, iface.state, sample.timestamp)\n+\t\tp.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], sample.timestamp)\n \t\tp.forgetStats(tracked, name)\n \t\tdelete(tracked.ifaces, name)\n \t}\n }\n \n+func sortedInterfaceNames(ifaces map[string]clablabruntime.InterfaceEventData) []string {\n+\tnames := make([]string, 0, len(ifaces))\n+\tfor name := range ifaces {\n+\t\tnames = append(names, name)\n+\t}\n+\tsort.Strings(names)\n+\n+\treturn names\n+}\n+\n func (p *interfacePoller) forgetStats(tracked *trackedNode, ifName string) {\n-\tdelete(p.statsSamples, c9sIfaceStatsKey(tracked.namespace, tracked.lab, tracked.node, ifName))\n+\tdelete(p.statsSamples,\n+\t\tc9sIfaceStatsKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name, ifName))\n }\n \n-func (p *interfacePoller) emitState(\n+func (p *interfacePoller) emit(\n \tctx context.Context,\n \ttracked *trackedNode,\n-\tiface c9sIfaceState,\n+\taction string,\n+\tdata clablabruntime.InterfaceEventData,\n \ttimestamp time.Time,\n ) {\n-\tp.r.sendEvent(ctx, p.sink, c9sIfaceStateEvent(tracked, iface, timestamp))\n+\tp.r.sendEvent(ctx, p.sink, c9sInterfaceEvent(tracked, action, data, timestamp))\n }\n \n-// c9sIfaceStateEvent reports the operational state of an interface. The actor is the node, as\n-// for the container events of the lab and the interface events of the local runtimes.\n-func c9sIfaceStateEvent(\n+// c9sInterfaceEvent is an interface event of a node. The actor is the node, as for its container\n+// events. The interface itself is in Interface; the events command reports it with the\n+// attributes of the local runtimes' interface events.\n+func c9sInterfaceEvent(\n \ttracked *trackedNode,\n-\tiface c9sIfaceState,\n+\taction string,\n+\tdata clablabruntime.InterfaceEventData,\n \ttimestamp time.Time,\n ) clablabruntime.Event {\n-\tactorName := fmt.Sprintf(\"%s-%s\", tracked.lab, tracked.node)\n+\tkey := c9sNodeKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name)\n \n \tattributes := map[string]string{\n-\t\t\"namespace\": tracked.namespace,\n-\t\t\"lab\":       tracked.lab,\n-\t\t\"node\":      tracked.node,\n-\t\t\"name\":      actorName,\n-\t\t\"ifname\":    iface.Name,\n-\t\t\"state\":     iface.OperState,\n-\t\t\"origin\":    \"clabernetes\",\n-\t}\n-\tif tracked.pod != \"\" {\n-\t\tattributes[\"pod\"] = tracked.pod\n-\t}\n-\tif iface.Index > 0 {\n-\t\tattributes[\"index\"] = strconv.Itoa(iface.Index)\n-\t}\n-\tif iface.MTU > 0 {\n-\t\tattributes[\"mtu\"] = strconv.Itoa(iface.MTU)\n+\t\t\"namespace\": tracked.lab.Namespace,\n+\t\t\"lab\":       tracked.lab.Name,\n+\t\t\"node\":      tracked.node.Name,\n+\t\t\"origin\":    clabernetesAppValue,\n \t}\n-\tif iface.MAC != \"\" {\n-\t\tattributes[\"mac\"] = iface.MAC\n-\t}\n-\tif iface.Alias != \"\" {\n-\t\tattributes[\"alias\"] = iface.Alias\n+\tif tracked.node.Pod != \"\" {\n+\t\tattributes[\"pod\"] = tracked.node.Pod\n \t}\n \n-\taction := iface.action()\n-\tif iface.OperState == interfaceStateNotPresent {\n-\t\taction = \"down\"\n-\t}\n+\tnode := tracked.node\n \n \treturn clablabruntime.Event{\n \t\tTimestamp:   timestamp,\n-\t\tType:        \"interface\",\n+\t\tType:        clablabruntime.EventTypeInterface,\n \t\tAction:      action,\n-\t\tActorID:     c9sNodeKey(tracked.namespace, tracked.lab, tracked.node),\n-\t\tActorName:   actorName,\n-\t\tActorFullID: tracked.pod,\n+\t\tActorID:     key,\n+\t\tActorName:   fmt.Sprintf(\"%s-%s\", tracked.lab.Name, tracked.node.Name),\n+\t\tActorFullID: key,\n \t\tAttributes:  attributes,\n+\t\tLab:         tracked.lab,\n+\t\tNode:        &node,\n+\t\tInterface:   &data,\n+\t}\n+}\n+\n+// c9sIfaceStatsData computes the counters and rates of a stats event from two samples.\n+func c9sIfaceStatsData(previous, current c9sIfaceStatsSample) *clablabruntime.InterfaceStats {\n+\tinterval := current.Timestamp.Sub(previous.Timestamp)\n+\tif interval <= 0 {\n+\t\tinterval = time.Second\n+\t}\n+\n+\tseconds := interval.Seconds()\n+\tstat := current.Stats\n+\n+\treturn &clablabruntime.InterfaceStats{\n+\t\tRxBytes:   stat.RxBytes,\n+\t\tTxBytes:   stat.TxBytes,\n+\t\tRxPackets: stat.RxPackets,\n+\t\tTxPackets: stat.TxPackets,\n+\t\tRxBps:     float64(counterDelta(stat.RxBytes, previous.Stats.RxBytes)*8) / seconds,\n+\t\tTxBps:     float64(counterDelta(stat.TxBytes, previous.Stats.TxBytes)*8) / seconds,\n+\t\tRxPps:     float64(counterDelta(stat.RxPackets, previous.Stats.RxPackets)) / seconds,\n+\t\tTxPps:     float64(counterDelta(stat.TxPackets, previous.Stats.TxPackets)) / seconds,\n+\t\tInterval:  interval,\n \t}\n }\n \n // parseInterfaceSample splits the output of interfaceSampleScript into the /proc/net/dev\n // counters and the sysfs interface states. hasStates is false for output without the sysfs\n@@ -559,63 +762,10 @@ func c9sNodeKey(namespace, lab, node string) string {\n \n func c9sIfaceStatsKey(namespace, lab, node, ifName string) string {\n \treturn c9sNodeKey(namespace, lab, node) + \"/\" + ifName\n }\n \n-func c9sIfaceStatsEvent(\n-\tstate *clablabruntime.LabState,\n-\tnode clablabruntime.NodeState,\n-\tpod *corev1.Pod,\n-\tstat c9sIfaceStats,\n-\tprevious,\n-\tcurrent c9sIfaceStatsSample,\n-) clablabruntime.Event {\n-\tinterval := current.Timestamp.Sub(previous.Timestamp)\n-\tif interval <= 0 {\n-\t\tinterval = time.Second\n-\t}\n-\n-\tseconds := interval.Seconds()\n-\trxBytesDelta := counterDelta(stat.RxBytes, previous.Stats.RxBytes)\n-\ttxBytesDelta := counterDelta(stat.TxBytes, previous.Stats.TxBytes)\n-\trxPacketsDelta := counterDelta(stat.RxPackets, previous.Stats.RxPackets)\n-\ttxPacketsDelta := counterDelta(stat.TxPackets, previous.Stats.TxPackets)\n-\n-\tactorName := fmt.Sprintf(\"%s-%s\", state.Name, node.Name)\n-\tpodName := \"\"\n-\tif pod != nil {\n-\t\tpodName = pod.Name\n-\t}\n-\n-\treturn clablabruntime.Event{\n-\t\tTimestamp:   current.Timestamp,\n-\t\tType:        \"interface\",\n-\t\tAction:      \"stats\",\n-\t\tActorID:     c9sNodeKey(state.Namespace, state.Name, node.Name),\n-\t\tActorName:   actorName,\n-\t\tActorFullID: podName,\n-\t\tAttributes: map[string]string{\n-\t\t\t\"namespace\":        state.Namespace,\n-\t\t\t\"lab\":              state.Name,\n-\t\t\t\"node\":             node.Name,\n-\t\t\t\"name\":             actorName,\n-\t\t\t\"pod\":              podName,\n-\t\t\t\"ifname\":           stat.Name,\n-\t\t\t\"origin\":           \"clabernetes\",\n-\t\t\t\"rx_bytes\":         strconv.FormatUint(stat.RxBytes, 10),\n-\t\t\t\"tx_bytes\":         strconv.FormatUint(stat.TxBytes, 10),\n-\t\t\t\"rx_packets\":       strconv.FormatUint(stat.RxPackets, 10),\n-\t\t\t\"tx_packets\":       strconv.FormatUint(stat.TxPackets, 10),\n-\t\t\t\"rx_bps\":           strconv.FormatFloat(float64(rxBytesDelta*8)/seconds, 'f', -1, 64),\n-\t\t\t\"tx_bps\":           strconv.FormatFloat(float64(txBytesDelta*8)/seconds, 'f', -1, 64),\n-\t\t\t\"rx_pps\":           strconv.FormatFloat(float64(rxPacketsDelta)/seconds, 'f', -1, 64),\n-\t\t\t\"tx_pps\":           strconv.FormatFloat(float64(txPacketsDelta)/seconds, 'f', -1, 64),\n-\t\t\t\"interval_seconds\": strconv.FormatFloat(seconds, 'f', -1, 64),\n-\t\t},\n-\t}\n-}\n-\n func counterDelta(current, previous uint64) uint64 {\n \tif current < previous {\n \t\treturn 0\n \t}\n \ndiff --git a/labruntime/clabernetes/manifests.go b/labruntime/clabernetes/manifests.go\nindex 7d4d36b..8512cab 100644\n--- a/labruntime/clabernetes/manifests.go\n+++ b/labruntime/clabernetes/manifests.go\n@@ -38,10 +38,19 @@ func (r *Runtime) Manifests(\n \tprepared, err := prepareDesiredDeployment(ctx, req, namespace)\n \tif err != nil {\n \t\treturn nil, err\n \t}\n \n+\t// The manifests are applied by other means than this deploy, so they do not carry the path\n+\t// of the topology file on this machine; such a lab reports where its definition lives.\n+\tremoveTopologySourceFile(prepared.topology)\n+\tfor _, group := range prepared.primitives.groups() {\n+\t\tfor _, obj := range group.objects {\n+\t\t\tremoveTopologySourceFile(obj)\n+\t\t}\n+\t}\n+\n \tmanifests := []clablabruntime.Manifest{}\n \n \t// A namespace override must already exist, matching the deploy contract; only the\n \t// canonical per-lab namespace is created by containerlab and therefore emitted.\n \tif req.Namespace == \"\" && r.labNamespaceOverride == \"\" {\ndiff --git a/labruntime/clabernetes/plan.go b/labruntime/clabernetes/plan.go\nindex 258bd01..0f0862b 100644\n--- a/labruntime/clabernetes/plan.go\n+++ b/labruntime/clabernetes/plan.go\n@@ -51,10 +51,11 @@ func prepareDesiredDeployment(\n \t\ttopologyWithNaming(naming),\n \t\ttopologyWithImagePullSecret(req.ImagePullSecret),\n \t\ttopologyWithExposeType(exposeType),\n \t\ttopologyWithPersistence(!req.NoPersistence),\n \t)\n+\tsetTopologySourceFile(desiredTopology, req.TopologyFile)\n \tif err := setTopologyFilesFromConfigMaps(desiredTopology, stagedConfigMaps); err != nil {\n \t\treturn nil, err\n \t}\n \tprimitives, err := compilePrimitiveResources(desiredTopology)\n \tif err != nil {\ndiff --git a/labruntime/clabernetes/primitives.go b/labruntime/clabernetes/primitives.go\nindex cc5a59b..f03b288 100644\n--- a/labruntime/clabernetes/primitives.go\n+++ b/labruntime/clabernetes/primitives.go\n@@ -218,10 +218,15 @@ func primitiveObject(\n \t\t// the spec, which the Node schema does not have: the API server prunes them, and\n \t\t// keeping them would make every apply and plan report the Node as changed.\n \t\tunstructured.RemoveNestedField(obj.Object, \"spec\", \"labels\")\n \t}\n \n+\tif kind != \"Node\" {\n+\t\t// Only Nodes carry the lab's topology file, which inspect reads without a Topology.\n+\t\tremoveTopologySourceFile(obj)\n+\t}\n+\n \tif owner := desiredTopology.GetAnnotations()[clabconstants.Owner]; owner != \"\" {\n \t\tannotations := obj.GetAnnotations()\n \t\tif annotations == nil {\n \t\t\tannotations = map[string]string{}\n \t\t}\ndiff --git a/labruntime/clabernetes/reconcile.go b/labruntime/clabernetes/reconcile.go\nindex a4889b5..d9cc952 100644\n--- a/labruntime/clabernetes/reconcile.go\n+++ b/labruntime/clabernetes/reconcile.go\n@@ -195,14 +195,34 @@ func reconciledPrimitiveObject(\n \n \tupdated.SetLabels(mergeDesiredMetadata(existing.GetLabels(), desired.GetLabels()))\n \tupdated.SetAnnotations(\n \t\tmergeDesiredMetadata(existing.GetAnnotations(), desired.GetAnnotations()),\n \t)\n+\tcarryOverNodeTopologyFile(existing, updated)\n \n \treturn updated\n }\n \n+// carryOverNodeTopologyFile keeps the topology file an existing Node recorded, or its absence.\n+// clabernetes copies a Node's annotations into its pod template, so changing the annotation\n+// would replace the node's pod although nothing about the node changed. A Node therefore keeps\n+// the file the lab was deployed from when the Node was created. The Topology resource has no\n+// such effect and always records the file of the latest deploy.\n+func carryOverNodeTopologyFile(existing, updated *unstructured.Unstructured) {\n+\tif existing.GetKind() != \"Node\" || existing.GetAPIVersion() != c9sAPIVersion {\n+\t\treturn\n+\t}\n+\n+\tpath, found := existing.GetAnnotations()[annotationTopologyFile]\n+\tif !found {\n+\t\tremoveTopologySourceFile(updated)\n+\t\treturn\n+\t}\n+\n+\tsetTopologySourceFile(updated, path)\n+}\n+\n // carryOverNodeRunState keeps the run state of an existing Node. spec.runState is operational\n // state that stop and start own, not part of the compiled definition: the compiler never sets\n // it, so replacing the spec would start a stopped node on every apply, and the API default\n // (Running) would otherwise count as drift on every plan. Restart requests live in annotations,\n // which the merge keeps.\ndiff --git a/labruntime/clabernetes/runtime_gaps_test.go b/labruntime/clabernetes/runtime_gaps_test.go\nindex aef6f01..1b8d366 100644\n--- a/labruntime/clabernetes/runtime_gaps_test.go\n+++ b/labruntime/clabernetes/runtime_gaps_test.go\n@@ -386,21 +386,12 @@ func TestParseInterfaceSample(t *testing.T) {\n \t}\n \tif stats[1].Name != \"eth1\" || stats[1].RxBytes != 2000 || stats[1].TxPackets != 30 {\n \t\tt.Fatalf(\"eth1 stats = %+v\", stats[1])\n \t}\n \n-\twantActions := map[string]string{\"eth1\": \"up\", \"eth2\": \"down\", \"lo\": \"up\", \"dummy0\": \"down\"}\n-\tfor _, state := range states {\n-\t\tif got := state.action(); got != wantActions[state.Name] {\n-\t\t\tt.Fatalf(\n-\t\t\t\t\"%s action = %q, want %q (%+v)\",\n-\t\t\t\tstate.Name,\n-\t\t\t\tgot,\n-\t\t\t\twantActions[state.Name],\n-\t\t\t\tstate,\n-\t\t\t)\n-\t\t}\n+\tif states[1].OperState != \"lowerlayerdown\" || states[2].OperState != \"unknown\" {\n+\t\tt.Fatalf(\"operational states = %+v\", states)\n \t}\n \tif states[0].Index != 3 || states[0].MTU != 9500 || states[0].MAC != \"aa:c1:ab:00:00:01\" ||\n \t\tstates[0].Alias != \"to server\" || states[0].Flags != 0x1003 {\n \t\tt.Fatalf(\"eth1 state = %+v\", states[0])\n \t}\n@@ -424,131 +415,10 @@ func TestCommandNotExecutable(t *testing.T) {\n \tif commandNotExecutable(1, errors.New(\"connection refused\")) {\n \t\tt.Fatal(\"other failures are not a missing command\")\n \t}\n }\n \n-func TestInterfacePollerEmitsStateChanges(t *testing.T) {\n-\tt.Parallel()\n-\n-\tnewSample := func(ts time.Time, ifaces ...c9sIfaceState) interfaceSample {\n-\t\treturn interfaceSample{\n-\t\t\ttarget: interfaceSampleTarget{\n-\t\t\t\tstate: &clablabruntime.LabState{Name: \"lab1\", Namespace: \"c9s-lab1\"},\n-\t\t\t\tnode:  clablabruntime.NodeState{Name: \"r1\", Pod: \"lab1-r1-abc\"},\n-\t\t\t\tpod:   &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"lab1-r1-abc\"}},\n-\t\t\t},\n-\t\t\tstats: []c9sIfaceStats{\n-\t\t\t\t{Name: \"eth1\", RxBytes: uint64(ts.Unix())},\n-\t\t\t},\n-\t\t\tifaces:    ifaces,\n-\t\t\thasStates: true,\n-\t\t\ttimestamp: ts,\n-\t\t}\n-\t}\n-\tup := c9sIfaceState{Name: \"eth1\", Index: 3, MTU: 9500, OperState: \"up\", Flags: 0x1003}\n-\tdown := c9sIfaceState{Name: \"eth1\", Index: 3, MTU: 9500, OperState: \"down\", Flags: 0x1002}\n-\teth2 := c9sIfaceState{Name: \"eth2\", Index: 4, OperState: \"up\", Flags: 0x1003}\n-\n-\tfor _, initialState := range []bool{false, true} {\n-\t\tsink := make(chan clablabruntime.Event, 32)\n-\t\tp := &interfacePoller{\n-\t\t\tr:            &Runtime{},\n-\t\t\topts:         interfacePollOptions{includeInitialState: initialState},\n-\t\t\tsink:         sink,\n-\t\t\tstatsSamples: map[string]c9sIfaceStatsSample{},\n-\t\t\tnodes:        map[string]*trackedNode{},\n-\t\t\tnoShell:      map[string]bool{},\n-\t\t\tfirstRound:   true,\n-\t\t}\n-\t\tctx := context.Background()\n-\t\tstart := time.Now()\n-\n-\t\tp.processSample(ctx, newSample(start, up))\n-\t\tif got := drain(sink); initialState != (len(got) == 1) {\n-\t\t\tt.Fatalf(\"initial-state=%t: first round emitted %+v\", initialState, got)\n-\t\t}\n-\n-\t\tp.firstRound = false\n-\t\tp.processSample(ctx, newSample(start.Add(time.Second), up))\n-\t\tif got := drain(sink); len(got) != 0 {\n-\t\t\tt.Fatalf(\"unchanged interface emitted %+v\", got)\n-\t\t}\n-\n-\t\tp.processSample(ctx, newSample(start.Add(2*time.Second), down, eth2))\n-\t\tgot := drain(sink)\n-\t\tif len(got) != 2 {\n-\t\t\tt.Fatalf(\"change emitted %+v, want eth1 down and new eth2 up\", got)\n-\t\t}\n-\t\tbyIf := map[string]clablabruntime.Event{}\n-\t\tfor _, ev := range got {\n-\t\t\tbyIf[ev.Attributes[\"ifname\"]] = ev\n-\t\t}\n-\t\tev := byIf[\"eth1\"]\n-\t\tif ev.Type != \"interface\" || ev.Action != \"down\" || ev.ActorID != \"c9s-lab1/lab1/r1\" ||\n-\t\t\tev.ActorName != \"lab1-r1\" || ev.ActorFullID != \"lab1-r1-abc\" ||\n-\t\t\tev.Attributes[\"state\"] != \"down\" || ev.Attributes[\"index\"] != \"3\" ||\n-\t\t\tev.Attributes[\"mtu\"] != \"9500\" || ev.Attributes[\"origin\"] != \"clabernetes\" ||\n-\t\t\tev.Attributes[\"lab\"] != \"lab1\" || ev.Attributes[\"node\"] != \"r1\" ||\n-\t\t\tev.Attributes[\"namespace\"] != \"c9s-lab1\" || ev.Attributes[\"pod\"] != \"lab1-r1-abc\" {\n-\t\t\tt.Fatalf(\"eth1 event = %+v\", ev)\n-\t\t}\n-\t\tif byIf[\"eth2\"].Action != \"up\" {\n-\t\t\tt.Fatalf(\"eth2 event = %+v\", byIf[\"eth2\"])\n-\t\t}\n-\n-\t\t// eth2 disappears\n-\t\tp.processSample(ctx, newSample(start.Add(3*time.Second), down))\n-\t\tgot = drain(sink)\n-\t\tif len(got) != 1 || got[0].Action != \"down\" ||\n-\t\t\tgot[0].Attributes[\"state\"] != interfaceStateNotPresent {\n-\t\t\tt.Fatalf(\"removed interface emitted %+v\", got)\n-\t\t}\n-\n-\t\t// the node stops running\n-\t\tp.retireStoppedNodes(ctx, map[string]bool{})\n-\t\tgot = drain(sink)\n-\t\tif len(got) != 1 || got[0].Attributes[\"ifname\"] != \"eth1\" ||\n-\t\t\tgot[0].Attributes[\"state\"] != interfaceStateNotPresent || len(p.nodes) != 0 {\n-\t\t\tt.Fatalf(\"stopped node emitted %+v, tracked %+v\", got, p.nodes)\n-\t\t}\n-\t}\n-}\n-\n-func TestInterfacePollerStatsUseTheNodeAsActor(t *testing.T) {\n-\tt.Parallel()\n-\n-\tsink := make(chan clablabruntime.Event, 8)\n-\tp := &interfacePoller{\n-\t\tr:            &Runtime{},\n-\t\topts:         interfacePollOptions{includeStats: true},\n-\t\tsink:         sink,\n-\t\tstatsSamples: map[string]c9sIfaceStatsSample{},\n-\t\tnodes:        map[string]*trackedNode{},\n-\t\tnoShell:      map[string]bool{},\n-\t}\n-\ttarget := interfaceSampleTarget{\n-\t\tstate: &clablabruntime.LabState{Name: \"lab1\", Namespace: \"c9s-lab1\"},\n-\t\tnode:  clablabruntime.NodeState{Name: \"r1\", Pod: \"lab1-r1-abc\"},\n-\t\tpod:   &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"lab1-r1-abc\"}},\n-\t}\n-\tstart := time.Now()\n-\tp.processSample(context.Background(), interfaceSample{\n-\t\ttarget: target, timestamp: start,\n-\t\tstats: []c9sIfaceStats{{Name: \"eth1\", RxBytes: 1000}},\n-\t})\n-\tp.processSample(context.Background(), interfaceSample{\n-\t\ttarget: target, timestamp: start.Add(time.Second),\n-\t\tstats: []c9sIfaceStats{{Name: \"eth1\", RxBytes: 2000}},\n-\t})\n-\n-\tgot := drain(sink)\n-\tif len(got) != 1 || got[0].Action != \"stats\" || got[0].ActorID != \"c9s-lab1/lab1/r1\" ||\n-\t\tgot[0].Attributes[\"rx_bps\"] != \"8000\" {\n-\t\tt.Fatalf(\"stats events = %+v\", got)\n-\t}\n-}\n-\n func drain(sink chan clablabruntime.Event) []clablabruntime.Event {\n \tvar events []clablabruntime.Event\n \tfor {\n \t\tselect {\n \t\tcase ev := <-sink:\ndiff --git a/labruntime/clabernetes/state.go b/labruntime/clabernetes/state.go\nindex ead2c45..d06385c 100644\n--- a/labruntime/clabernetes/state.go\n+++ b/labruntime/clabernetes/state.go\n@@ -22,10 +22,17 @@ func stateFromNodeResources(\n \tstate := &clablabruntime.LabState{\n \t\tName:         name,\n \t\tNamespace:    namespace,\n \t\tTopologyPath: fmt.Sprintf(\"k8s://%s/labs/%s\", namespace, name),\n \t}\n+\t// Without a Topology resource the Nodes record the file the lab was deployed from.\n+\tfor idx := range nodeResources {\n+\t\tif path := nodeResources[idx].GetAnnotations()[annotationTopologyFile]; path != \"\" {\n+\t\t\tstate.TopologyPath = path\n+\t\t\tbreak\n+\t\t}\n+\t}\n \tif len(nodeResources) != 0 {\n \t\tstate.Owner = nodeResources[0].GetLabels()[clabconstants.Owner]\n \t\tif state.Owner == \"\" {\n \t\t\tstate.Owner = nodeResources[0].GetAnnotations()[clabconstants.Owner]\n \t\t}\n@@ -42,15 +49,20 @@ func stateFromNodeResources(",
        "lineStart": 2845,
        "lineEnd": 4395,
        "totalLines": 4396,
        "truncated": true
      }
    },
    "time": {
      "start": 1793525605565,
      "end": 1793525605580
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19674e4d0001BWsYCoit6cPw3v",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674db1a001T4BNzcGimXgvil",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 44722,
    "input": 20572,
    "output": 21,
    "reasoning": 1,
    "cache": {
      "read": 24128,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19674db1a001T4BNzcGimXgvil",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525603098,
    "completed": 1793525605588
  },
  "parentID": "msg_19674becc001poQpu47cHvtM8V",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 44722,
    "input": 20572,
    "output": 21,
    "reasoning": 1,
    "cache": {
      "read": 24128,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 6
step-start
{
  "type": "step-start",
  "id": "prt_19674f259001QvpKrrHKOLqwlE",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674e4d9001A37rotvZLIlfwI"
}
read · completed

Input

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

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
4396:  func nodeStateFromResource(nodeResource *unstructured.Unstructured) clablabruntime.NodeState {
4397:  	node := clablabruntime.NodeState{
4398:  		Name:    nodeResource.GetName(),
4399:  		NodeUID: string(nodeResource.GetUID()),
4400:  	}
4401: +	if original := nodeResource.GetLabels()[labelOriginalNodeName]; original != node.Name {
4402: +		node.TopologyName = original
4403: +	}
4404:  	node.ExposedPorts = nodeExposedPorts(nodeResource)
4405:  	// The same container exec targets: the observed primary device container.
4406:  	node.Container, _ = preferredDeviceContainerName(nodeResource, node.Name)
4407:  	node.Kind, _, _ = unstructured.NestedString(nodeResource.Object, "spec", "kind")
4408:  	node.Image, _, _ = unstructured.NestedString(nodeResource.Object, "spec", "image")
4409: +	node.Type, _, _ = unstructured.NestedString(nodeResource.Object, "spec", "type")
4410: +	node.Group, _, _ = unstructured.NestedString(nodeResource.Object, "spec", "group")
4411:  	node.State, _, _ = unstructured.NestedString(nodeResource.Object, "status", "readiness")
4412:  	node.Ready = node.State == "ready"
4413:  	node.LoadBalancerAddress, _, _ = unstructured.NestedString(
4414:  		nodeResource.Object,
4415:  		"status",
4416: @@ -132,17 +144,28 @@ func intField(value any) int {
4417:  	default:
4418:  		return 0
4419:  	}
4420:  }
4421:  
4422: -// newestPod prefers a running pod and, among equals, the newest one: several pods can match a
4423: -// node during a rolling update.
4424: +// newestPod prefers a pod that is not being deleted, then a running pod and, among equals, the
4425: +// newest one: several pods can match a node during a rolling update or a restart, when the old
4426: +// pod terminates while its replacement starts.
4427:  func newestPod(current, candidate *corev1.Pod) *corev1.Pod {
4428:  	if current == nil {
4429:  		return candidate
4430:  	}
4431:  
4432: +	currentDeleting := current.DeletionTimestamp != nil
4433: +	candidateDeleting := candidate.DeletionTimestamp != nil
4434: +	if currentDeleting != candidateDeleting {
4435: +		if candidateDeleting {
4436: +			return current
4437: +		}
4438: +
4439: +		return candidate
4440: +	}
4441: +
4442:  	currentRunning := current.Status.Phase == corev1.PodRunning
4443:  	candidateRunning := candidate.Status.Phase == corev1.PodRunning
4444:  	if currentRunning != candidateRunning {
4445:  		if candidateRunning {
4446:  			return candidate
4447: @@ -197,20 +220,30 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat
4448:  	for idx := range pods.Items {
4449:  		nodeName := pods.Items[idx].Labels[labelTopologyNode]
4450:  		if nodeName == "" {
4451:  			continue
4452:  		}
4453: +		// A pod of an earlier Node of the same name (a redeploy while the old pod still
4454: +		// terminates) is not this node's pod.
4455: +		if uid := pods.Items[idx].Annotations[annotationDirectNodeUID]; uid != "" {
4456: +			if resource := resourcesByName[nodeName]; resource != nil &&
4457: +				string(resource.GetUID()) != uid {
4458: +				continue
4459: +			}
4460: +		}
4461:  		podsByNode[nodeName] = newestPod(podsByNode[nodeName], &pods.Items[idx])
4462:  	}
4463:  
4464:  	// The Node's status.readiness is the authoritative device signal. The primary Node's run
4465:  	// state governs the pod a group of nodes shares: a stopped primary stops the whole group.
4466:  	// Nodes without readiness yet report their pod phase.
4467:  	for nodeName, node := range nodesByName {
4468:  		primary := resolvePrimaryNode(nodeName, networkModes)
4469: -		if primaryResource := resourcesByName[primary]; primaryResource != nil &&
4470: -			nodeRunState(primaryResource) == nodeRunStateStopped {
4471: +		primaryResource := resourcesByName[primary]
4472: +		stopRequested := primaryResource != nil &&
4473: +			nodeRunState(primaryResource) == nodeRunStateStopped
4474: +		if stopRequested {
4475:  			node.State = "stopping"
4476:  			if condition := nodeCondition(
4477:  				primaryResource,
4478:  				nodeConditionStopped,
4479:  			); condition != nil &&
4480: @@ -220,10 +253,14 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat
4481:  			node.Ready = false
4482:  		} else if pod := podsByNode[primary]; node.State == "" && pod != nil &&
4483:  			pod.Status.Phase != "" {
4484:  			node.State = strings.ToLower(string(pod.Status.Phase))
4485:  		}
4486: +		node.ContainerState = nodeContainerState(stopRequested, podsByNode[primary])
4487: +		if node.ContainerState == clablabruntime.ContainerStateRunning {
4488: +			node.Health = nodeHealth(node, resourcesByName[nodeName])
4489: +		}
4490:  		nodesByName[nodeName] = node
4491:  	}
4492:  
4493:  	// Nodes grouped through network-mode container: share the pod of the group's primary
4494:  	// node. Before the controller observed the device containers, the pod's default-container
4495: @@ -270,5 +307,46 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat
4496:  		state.Ready = false
4497:  	}
4498:  
4499:  	return nil
4500:  }
4501: +
4502: +// nodeContainerState is the state of a node in container runtime terms, from its pod: created
4503: +// while the pod is scheduled and prepared (init containers), running once the device containers
4504: +// run, and exited once the node was stopped, its pod is being deleted, or the pod ended. Between
4505: +// the pods of a restart the node is exited, then created.
4506: +func nodeContainerState(stopRequested bool, pod *corev1.Pod) string {
4507: +	switch {
4508: +	case pod == nil && stopRequested:
4509: +		return clablabruntime.ContainerStateExited
4510: +	case pod == nil:
4511: +		return clablabruntime.ContainerStateCreated
4512: +	case stopRequested || pod.DeletionTimestamp != nil:
4513: +		return clablabruntime.ContainerStateExited
4514: +	}
4515: +
4516: +	switch pod.Status.Phase {
4517: +	case corev1.PodRunning:
4518: +		return clablabruntime.ContainerStateRunning
4519: +	case corev1.PodSucceeded, corev1.PodFailed:
4520: +		return clablabruntime.ContainerStateExited
4521: +	default:
4522: +		return clablabruntime.ContainerStateCreated
4523: +	}
4524: +}
4525: +
4526: +// nodeHealth is the health of a running node: healthy once the Node is ready or its device
4527: +// containers are, starting before. Device containers are the analogue of a container
4528: +// healthcheck: a node whose links wait for a stopped peer is not ready, but its device is.
4529: +func nodeHealth(node clablabruntime.NodeState, resource *unstructured.Unstructured) string {
4530: +	if node.Ready {
4531: +		return clablabruntime.ContainerHealthHealthy
4532: +	}
4533: +	if resource != nil {
4534: +		if condition := nodeCondition(resource, nodeConditionContainersReady); condition != nil &&
4535: +			condition.status == string(metav1.ConditionTrue) {
4536: +			return clablabruntime.ContainerHealthHealthy
4537: +		}
4538: +	}
4539: +
4540: +	return clablabruntime.ContainerHealthStarting
4541: +}
4542: diff --git a/labruntime/clabernetes/topology.go b/labruntime/clabernetes/topology.go
4543: index e401ecf..db3715a 100644
4544: --- a/labruntime/clabernetes/topology.go
4545: +++ b/labruntime/clabernetes/topology.go
4546: @@ -12,10 +12,56 @@ import (
4547:  	"k8s.io/apimachinery/pkg/util/validation"
4548:  )
4549:  
4550:  type topologyObjectOption func(map[string]any)
4551:  
4552: +// annotationTopologyFile records the absolute path of the topology file a lab was deployed from,
4553: +// on the machine that deployed it. Inspect reports it as the lab's topology path and events as
4554: +// clab-topo-file, as the local runtimes do, so clients match the running lab to its file. A lab
4555: +// created by other means than a containerlab deploy has no annotation and reports where its
4556: +// definition lives in the cluster (k8s://<namespace>/topologies/<lab>).
4557: +const annotationTopologyFile = "containerlab.dev/topo-file"
4558: +
4559: +// setTopologySourceFile records the topology file a deploy reads on the Topology. An empty path
4560: +// (a definition that came from no file) records nothing.
4561: +func setTopologySourceFile(topology *unstructured.Unstructured, path string) {
4562: +	if path == "" {
4563: +		return
4564: +	}
4565: +
4566: +	annotations := topology.GetAnnotations()
4567: +	if annotations == nil {
4568: +		annotations = map[string]string{}
4569: +	}
4570: +	annotations[annotationTopologyFile] = path
4571: +	topology.SetAnnotations(annotations)
4572: +}
4573: +
4574: +// removeTopologySourceFile drops the deploying machine's file path from an object.
4575: +func removeTopologySourceFile(obj *unstructured.Unstructured) {
4576: +	annotations := obj.GetAnnotations()
4577: +	if _, ok := annotations[annotationTopologyFile]; !ok {
4578: +		return
4579: +	}
4580: +
4581: +	delete(annotations, annotationTopologyFile)
4582: +	if len(annotations) == 0 {
4583: +		annotations = nil
4584: +	}
4585: +	obj.SetAnnotations(annotations)
4586: +}
4587: +
4588: +// labTopologyPath is the topology path a lab reports: the file it was deployed from when the
4589: +// deploy recorded one, otherwise the place given.
4590: +func labTopologyPath(annotations map[string]string, fallback string) string {
4591: +	if path := annotations[annotationTopologyFile]; path != "" {
4592: +		return path
4593: +	}
4594: +
4595: +	return fallback
4596: +}
4597: +
4598:  func topologyWithNaming(naming string) topologyObjectOption {
4599:  	return func(spec map[string]any) {
4600:  		if naming != "" {
4601:  			spec["naming"] = naming
4602:  		}
4603: @@ -137,10 +183,14 @@ func stateFromTopology(obj *unstructured.Unstructured, namespace string) *clabla
4604:  	owner := obj.GetLabels()[clabconstants.Owner]
4605:  	if owner == "" {
4606:  		owner = obj.GetAnnotations()[clabconstants.Owner]
4607:  	}
4608:  	nodeSpecs := nodeSpecsFromTopology(obj)
4609: +	topologyPath := labTopologyPath(
4610: +		obj.GetAnnotations(),
4611: +		fmt.Sprintf("k8s://%s/topologies/%s", namespace, obj.GetName()),
4612: +	)
4613:  
4614:  	nodeNames := make([]string, 0, len(nodeSpecs))
4615:  	for nodeName := range nodeSpecs {
4616:  		nodeNames = append(nodeNames, nodeName)
4617:  	}
4618: @@ -158,11 +208,11 @@ func stateFromTopology(obj *unstructured.Unstructured, namespace string) *clabla
4619:  
4620:  	return &clablabruntime.LabState{
4621:  		Name:         obj.GetName(),
4622:  		Namespace:    namespace,
4623:  		Owner:        owner,
4624: -		TopologyPath: fmt.Sprintf("k8s://%s/topologies/%s", namespace, obj.GetName()),
4625: +		TopologyPath: topologyPath,
4626:  		State:        state,
4627:  		Ready:        ready,
4628:  		Nodes:        nodes,
4629:  	}
4630:  }
4631: diff --git a/labruntime/runtime.go b/labruntime/runtime.go
4632: index 367565d..0f2433a 100644
4633: --- a/labruntime/runtime.go
4634: +++ b/labruntime/runtime.go
4635: @@ -191,16 +191,42 @@ type SavedFile struct {
4636:  
4637:  type SaveResult struct {
4638:  	Files []SavedFile
4639:  }
4640:  
4641: +// Container states and health in the vocabulary of container runtimes (Docker), which inspect
4642: +// and events report for lab runtime nodes too.
4643: +const (
4644: +	ContainerStateCreated = "created"
4645: +	ContainerStateRunning = "running"
4646: +	ContainerStateExited  = "exited"
4647: +
4648: +	ContainerHealthHealthy   = "healthy"
4649: +	ContainerHealthStarting  = "starting"
4650: +	ContainerHealthUnhealthy = "unhealthy"
4651: +)
4652: +
4653:  type NodeState struct {
4654: -	Name  string
4655: -	Kind  string
4656: -	Image string
4657: +	Name string
4658: +	// TopologyName is the node name as the topology file spells it, when the runtime had to
4659: +	// carry the node under another name (Name). Empty means Name.
4660: +	TopologyName string
4661: +	Kind         string
4662: +	Image        string
4663: +	// Type and Group are the node's type and group when the topology set them.
4664: +	Type  string
4665: +	Group string
4666: +	// State is the runtime's own view of the node, such as the clabernetes Node readiness, or
4667: +	// stopped.
4668:  	State string
4669:  	Ready bool
4670: +	// ContainerState is the node's state in container runtime terms: created, running or
4671: +	// exited (the ContainerState* constants). Empty when the runtime does not report one.
4672: +	ContainerState string
4673: +	// Health is the device health of a running node in container runtime terms: healthy or
4674: +	// starting. Empty when the node does not run.
4675: +	Health string
4676:  	// MgmtIPv4Address and MgmtIPv6Address are the node's allocated management addresses in
4677:  	// CIDR notation, when the runtime reports them.
4678:  	MgmtIPv4Address     string
4679:  	MgmtIPv6Address     string
4680:  	LoadBalancerAddress string
4681: @@ -216,13 +242,16 @@ type NodeState struct {
4682:  
4683:  // ExposedPort is a node port a lab runtime publishes through a Service.
4684:  type ExposedPort = clabtypes.ExposedPort
4685:  
4686:  type LabState struct {
4687: -	Name         string
4688: -	Namespace    string
4689: -	Owner        string
4690: +	Name      string
4691: +	Namespace string
4692: +	Owner     string
4693: +	// TopologyPath is the absolute path of the topology file the lab was deployed from, on the
4694: +	// machine that deployed it. A lab the runtime did not deploy from a file reports where the
4695: +	// runtime keeps its definition instead (for c9s k8s://<namespace>/topologies/<lab>).
4696:  	TopologyPath string
4697:  	State        string
4698:  	Ready        bool
4699:  	Nodes        []NodeState
4700:  }
4701: @@ -258,11 +287,61 @@ type Event struct {
4702:  	Type        string
4703:  	Action      string
4704:  	ActorID     string
4705:  	ActorName   string
4706:  	ActorFullID string
4707: -	Attributes  map[string]string
4708: +	// Attributes are the runtime's own attributes. Event consumers add the attributes the
4709: +	// container runtimes report from Lab, Node and Interface.
4710: +	Attributes map[string]string
4711: +	// Lab and Node are the lab node a container or interface event is about, as Inspect
4712: +	// reports it. containerlab's events command describes the node from them the same way
4713: +	// inspect does, so both agree and match what the container runtimes report.
4714: +	Lab  *LabState
4715: +	Node *NodeState
4716: +	// Interface is the interface an interface event reports.
4717: +	Interface *InterfaceEventData
4718: +}
4719: +
4720: +// Event types and the origin attribute of lab runtime events.
4721: +const (
4722: +	EventTypeContainer = "container"
4723: +	EventTypeInterface = "interface"
4724: +	// EventOriginSnapshot marks the events of --initial-state, in the origin attribute.
4725: +	EventOriginSnapshot = "snapshot"
4726: +)
4727: +
4728: +// InterfaceEventData describes an interface of a node the way the container runtimes' interface
4729: +// events do (netlink).
4730: +type InterfaceEventData struct {
4731: +	// Name is the interface name inside the node.
4732: +	Name string
4733: +	// Alias is the name the topology gave the interface when the node kind maps it (for
4734: +	// example ethernet-1/1 for SR Linux e1-1).
4735: +	Alias string
4736: +	Index int
4737: +	MTU   int
4738: +	MAC   string
4739: +	// OperState is the operational state in netlink's vocabulary: up, down, lower-layer-down,
4740: +	// dormant, testing, not-present or unknown.
4741: +	OperState string
4742: +	// Type is the link type in netlink's vocabulary, such as veth or device (loopback).
4743: +	Type string
4744: +	// Stats are set on stats events.
4745: +	Stats *InterfaceStats
4746: +}
4747: +
4748: +// InterfaceStats are the counters and rates of an interface stats event.
4749: +type InterfaceStats struct {
4750: +	RxBytes   uint64
4751: +	TxBytes   uint64
4752: +	RxPackets uint64
4753: +	TxPackets uint64
4754: +	RxBps     float64
4755: +	TxBps     float64
4756: +	RxPps     float64
4757: +	TxPps     float64
4758: +	Interval  time.Duration
4759:  }
4760:  
4761:  // NodeLocation is the workload that runs a lab node.
4762:  type NodeLocation struct {
4763:  	// NodeName is the node name the runtime carries (the sanitized name).
4764: diff --git a/tests/14-clabernetes/01-linux-lifecycle.robot b/tests/14-clabernetes/01-linux-lifecycle.robot
4765: index f45a3ff..bc27828 100644
4766: --- a/tests/14-clabernetes/01-linux-lifecycle.robot
4767: +++ b/tests/14-clabernetes/01-linux-lifecycle.robot
4768: @@ -27,10 +27,15 @@ ${recovery-timeout}     180s
4769:  ${retry-interval}       5s
4770:  ${capture-file}         /tmp/clab-c9s-capture.pcapng
4771:  ${chain-file}           /tmp/clab-c9s-capture-chain.pcapng
4772:  ${stop-file}            /tmp/clab-c9s-capture-stop.pcapng
4773:  ${stop-err}             /tmp/clab-c9s-capture-stop.err
4774: +${lifecycle-log}        /tmp/clab-c9s-lifecycle-events.log
4775: +${lifecycle-err}        /tmp/clab-c9s-lifecycle-events.err
4776: +${redeploy-log}         /tmp/clab-c9s-redeploy-events.log
4777: +${redeploy-err}         /tmp/clab-c9s-redeploy-events.err
4778: +${node-image}           ghcr.io/srl-labs/network-multitool
4779:  
4780:  
4781:  *** Test Cases ***
4782:  Deploy c9s linux lab
4783:      ${output} =    Run Clab Command    deploy -t ${topo}
4784: @@ -103,10 +108,47 @@ Inspect all is scoped by the namespace override
4785:  
4786:      ${other} =    Run Clab Command    --namespace default inspect --all --format json
4787:      Should Be Equal As Integers    ${other.rc}    0
4788:      Should Not Contain    ${other.stdout}    ${lab-name}
4789:  
4790: +Inspect reports the topology file the lab was deployed from
4791: +    # the deploy recorded this machine's file on the Topology; inspect without the file reports it
4792: +    ${annotation} =    Process.Run Process
4793: +    ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} -o jsonpath\='{.metadata.annotations.containerlab\\.dev/topo-file}'
4794: +    ...    shell=True
4795: +    Should Be Equal As Integers    ${annotation.rc}    0
4796: +    Should Be Equal    ${annotation.stdout}    ${topo}
4797: +
4798: +    ${output} =    Run Clab Command    inspect --all --format json
4799: +    Should Be Equal As Integers    ${output.rc}    0
4800: +    ${labs} =    Evaluate    json.loads($output.stdout)    modules=json
4801: +    FOR    ${node}    IN    @{labs}[${lab-name}]
4802: +        Should Be Equal    ${node}[absLabPath]    ${topo}
4803: +        Should Not Start With    ${node}[labPath]    k8s://
4804: +        Should Be Equal    ${node}[state]    running
4805: +        Should Be Equal    ${node}[status]    healthy
4806: +    END
4807: +
4808: +    # manifests are applied by other means; they do not carry this machine's path
4809: +    ${emit} =    Run Offline Clab Command    deploy -t ${topo} --emit-crs
4810: +    Should Be Equal As Integers    ${emit.rc}    0
4811: +    Should Not Contain    ${emit.stdout}    containerlab.dev/topo-file
4812: +
4813: +Events carry the attributes of Docker events
4814: +    ${events} =    Collect Events    --name ${lab-name} events --format json --initial-state
4815: +    FOR    ${node}    IN    client    server
4816: +        Container Event Should Carry Docker Attributes    ${events}    ${node}    running    running
4817: +        # the interfaces a Docker container of the node has: the lab link, eth0 and lo, named
4818: +        # as in the topology, the link up
4819: +        ${ifaces} =    Interface States    ${events}    ${node}
4820: +        Should Be Equal    ${{sorted($ifaces)}}    ${{["eth0", "eth1", "lo"]}}
4821: +        Should Be Equal    ${ifaces}[eth1]    up
4822: +        Should Be Equal    ${ifaces}[eth0]    up
4823: +        Should Be Equal    ${ifaces}[lo]    unknown
4824: +    END
4825: +    Should Not Contain    ${events}    "ifname":"c9s
4826: +
4827:  Validate and emit-crs work without a kubeconfig
4828:      ${validate} =    Run Offline Clab Command    validate -t ${topo}
4829:      Should Be Equal As Integers    ${validate.rc}    0
4830:      Should Contain    ${validate.stderr}    Topology is valid for lab runtime
4831:  
4832: @@ -141,17 +183,23 @@ Inspect interfaces lists the link interfaces with their state
4833:      Should Be Equal As Integers    ${output.rc}    0
4834:      ${containers} =    Evaluate    json.loads($output.stdout)    modules=json
4835:      Length Should Be    ${containers}    2
4836:      FOR    ${container}    IN    @{containers}
4837:          Should Match Regexp    ${container}[name]    ^${lab-name}-(client|server)$
4838: -        Length Should Be    ${container}[interfaces]    1
4839: -        ${iface} =    Set Variable    ${container}[interfaces][0]
4840: +        # what a Docker container of the node lists: eth0, the lab link and loopback
4841: +        ${names} =    Evaluate    [i["name"] for i in $container["interfaces"]]
4842: +        Should Be Equal    ${names}    ${{["eth0", "eth1", "lo"]}}
4843: +        ${iface} =    Set Variable    ${container}[interfaces][1]
4844:          Should Be Equal    ${iface}[name]    eth1
4845: +        Should Be Equal    ${iface}[alias]    ${EMPTY}
4846:          Should Be Equal    ${iface}[type]    veth
4847:          Should Be Equal    ${iface}[state]    up
4848:          Should Match Regexp    ${iface}[mac]    ^([0-9a-f]{2}:){5}[0-9a-f]{2}$
4849:          Should Be True    ${iface}[ifindex] > 0 and ${iface}[mtu] > 0
4850: +        ${lo} =    Set Variable    ${container}[interfaces][2]
4851: +        Should Be Equal    ${lo}[type]    device
4852: +        Should Be Equal    ${lo}[state]    unknown
4853:      END
4854:  
4855:      ${one} =    Run Clab Command    inspect interfaces --name ${lab-name} -n client -f json
4856:      Should Be Equal As Integers    ${one.rc}    0
4857:      ${only} =    Evaluate    [c["name"] for c in json.loads($one.stdout)]    modules=json
4858: @@ -338,10 +386,19 @@ Library attaches, port-forwards, streams logs and samples stats as an impersonat
4859:      Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/stats
4860:      Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/forbidden_identity
4861:      Should Not Contain    ${result.stdout}    SKIP
4862:  
4863:  Stop server and verify dataplane interruption
4864: +    # the events of the stop and the following start are checked as they happen
4865: +    Remove File If Exists    ${lifecycle-log}
4866: +    Start Process    ${CLAB_BIN} --runtime ${runtime} --name ${lab-name} events --format json
4867: +    ...    shell=True
4868: +    ...    alias=c9s_lifecycle
4869: +    ...    stdout=${lifecycle-log}
4870: +    ...    stderr=${lifecycle-err}
4871: +    Sleep    5s
4872: +
4873:      ${output} =    Run Clab Command    stop -t ${topo} --node server
4874:      Should Be Equal As Integers    ${output.rc}    0
4875:  
4876:      # stop is a run state patch on the Node; the controller removes the Pod
4877:      ${run_state} =    Node Field    server    {.spec.runState}
4878: @@ -351,14 +408,32 @@ Stop server and verify dataplane interruption
4879:      ${pods} =    Process.Run Process
4880:      ...    kubectl -n ${lab-namespace} get pods -l c9s.run/topologyNode\=server -o name
4881:      ...    shell=True
4882:      Should Be Empty    ${pods.stdout}
4883:      ${inspect} =    Run Clab Command    inspect -t ${topo} --format json
4884: -    Should Contain    ${inspect.stdout}    "state": "stopped"
4885: +    ${states} =    Evaluate
4886: +    ...    {n["name"]: (n["state"], n["status"]) for n in json.loads($inspect.stdout)["${lab-name}"]}
4887: +    ...    modules=json
4888: +    Should Be Equal    ${states}[${lab-name}-server]    ${{("exited", "Exited")}}
4889:  
4890:      Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Fail
4891:  
4892: +Stopping a node reports the events Docker reports for containerlab stop
4893: +    # Docker: kill, stop, die; the node's interfaces go with it, its peer loses carrier
4894: +    Wait Until Keyword Succeeds    30s    1s
4895: +    ...    Container Actions Should Include In Order    ${lifecycle-log}    server
4896: +    ...    kill    stop    die
4897: +    ${events} =    Get File    ${lifecycle-log}
4898: +    Container Event Should Carry Docker Attributes    ${events}    server    die    exited
4899: +    Wait Until Keyword Succeeds    30s    1s
4900: +    ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    delete
4901: +    Wait Until Keyword Succeeds    30s    1s
4902: +    ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update
4903: +    ...    lower-layer-down    down
4904: +    ${client} =    Container Actions    ${lifecycle-log}    client
4905: +    Should Not Contain    ${client}    die
4906: +
4907:  Apply while server is stopped keeps it stopped
4908:      ${output} =    Run Clab Command    deploy -t ${applied-topo}
4909:      Should Be Equal As Integers    ${output.rc}    0
4910:      # the wait settles on the stopped node instead of waiting for it
4911:      Should Contain    ${output.stderr}    C9s lab is ready apart from stopped nodes
4912: @@ -385,10 +460,33 @@ Start server by lab name and verify dataplane restore
4913:      Should Be Equal As Integers    ${mark.rc}    0
4914:      Should Contain    ${mark_output}    applied-while-stopped
4915:  
4916:      Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed
4917:  
4918: +Starting a node reports the events Docker reports for containerlab start
4919: +    TRY
4920: +        # Docker: start; the device's readiness as a container health check
4921: +        Wait Until Keyword Succeeds    60s    1s
4922: +        ...    Container Actions Should Include In Order    ${lifecycle-log}    server
4923: +        ...    kill    stop    die    start    health_status: healthy
4924: +        ${events} =    Get File    ${lifecycle-log}
4925: +        # the lab was last deployed from the applied file, which the Topology now records
4926: +        Container Event Should Carry Docker Attributes
4927: +        ...    ${events}    server    start    running    ${applied-topo}
4928: +        Container Event Should Carry Docker Attributes
4929: +        ...    ${events}    server    health_status: healthy    running    ${applied-topo}
4930: +        Wait Until Keyword Succeeds    60s    1s
4931: +        ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    create
4932: +        Wait Until Keyword Succeeds    60s    1s
4933: +        ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update    up
4934: +        Validate JSON Lines    ${lifecycle-log}
4935: +    FINALLY
4936: +        Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True
4937: +        Remove File If Exists    ${lifecycle-log}
4938: +        Remove File If Exists    ${lifecycle-err}
4939: +    END
4940: +
4941:  Restart server and keep dataplane working
4942:      ${before} =    Server Pod Name
4943:      ${output} =    Run Clab Command    restart -t ${topo} --node server
4944:      Should Be Equal As Integers    ${output.rc}    0
4945:  
4946: @@ -445,26 +543,36 @@ Events report interface up and down
4947:          ...    stdout=${iface-events-log}
4948:          ...    stderr=${iface-events-err}
4949:          Sleep    5s
4950:          Set Client Eth1    down
4951:          Wait Until Keyword Succeeds    30s    1s
4952: -        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    down
4953: +        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    down
4954:          # the peer loses carrier
4955:          Wait Until Keyword Succeeds    30s    1s
4956: -        ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    down
4957: +        ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    update
4958: +        ...    lower-layer-down    down
4959:          Set Client Eth1    up
4960:          Wait Until Keyword Succeeds    30s    1s
4961: -        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    up
4962: +        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    up
4963:          Validate JSON Lines    ${iface-events-log}
4964:      FINALLY
4965:          Stop Events Process
4966:          Set Client Eth1    up
4967:          Remove File If Exists    ${iface-events-log}
4968:          Remove File If Exists    ${iface-events-err}
4969:      END
4970:  
4971:  Destroy without cleanup keeps the persistent claims
4972: +    # the events of the destroy and the following deploy are checked after the deploy
4973: +    Remove File If Exists    ${redeploy-log}
4974: +    Start Process    ${CLAB_BIN} --runtime ${runtime} --namespace ${lab-namespace} events --format json
4975: +    ...    shell=True
4976: +    ...    alias=c9s_redeploy
4977: +    ...    stdout=${redeploy-log}
4978: +    ...    stderr=${redeploy-err}
4979: +    Sleep    5s
4980: +
4981:      ${before} =    Persistent Claim Volumes
4982:      Should Not Be Empty    ${before}
4983:  
4984:      ${output} =    Run Clab Command    destroy -t ${topo}
4985:      Should Be Equal As Integers    ${output.rc}    0
4986: @@ -479,10 +587,36 @@ Deploy reuses the retained persistent claims
4987:      Should Be Equal As Integers    ${output.rc}    0
4988:  
4989:      ${volumes} =    Persistent Claim Volumes
4990:      Should Be Equal    ${volumes}    ${retained-volumes}
4991:  
4992: +Destroy and deploy report the events Docker reports
4993: +    TRY
4994: +        FOR    ${node}    IN    client    server
4995: +            # Docker: kill, die, destroy; then create, start (and the health check)
4996: +            Wait Until Keyword Succeeds    60s    1s
4997: +            ...    Container Actions Should Include In Order    ${redeploy-log}    ${node}
4998: +            ...    kill    die    destroy    create    start    health_status: healthy
4999: +            ${events} =    Get File    ${redeploy-log}
5000: +            # the destroyed lab was last deployed from the applied file, the new one from ${topo}
5001: +            Container Event Should Carry Docker Attributes
5002: +            ...    ${events}    ${node}    destroy    exited    ${applied-topo}
5003: +            Container Event Should Carry Docker Attributes    ${events}    ${node}    create    created
5004: +            Container Event Should Carry Docker Attributes    ${events}    ${node}    start    running
5005: +            # like Docker, the link may be created down and come up after
5006: +            Wait Until Keyword Succeeds    60s    1s
5007: +            ...    Interface Event Should Be Logged    ${redeploy-log}    ${node}    eth1    create
5008: +            Wait Until Keyword Succeeds    60s    1s
5009: +            ...    Last Interface State Should Be    ${redeploy-log}    ${node}    eth1    up
5010: +        END
5011: +        Validate JSON Lines    ${redeploy-log}
5012: +    FINALLY
5013: +        Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True
5014: +        Remove File If Exists    ${redeploy-log}
5015: +        Remove File If Exists    ${redeploy-err}
5016: +    END
5017: +
5018:  Destroy c9s linux lab
5019:      ${output} =    Run Clab Command    destroy -t ${topo} --cleanup
5020:      Should Be Equal As Integers    ${output.rc}    0
5021:  
5022:      ${inspect_all} =    Run Clab Command    inspect --all
5023: @@ -509,10 +643,18 @@ Deploy c9s linux lab without a Topology resource
5024:      ...    shell=True
5025:      Should Be Equal As Integers    ${nodes.rc}    0
5026:      Should Contain    ${nodes.stdout}    node.c9s.run/client
5027:      Should Contain    ${nodes.stdout}    node.c9s.run/server
5028:  
5029: +    # without a Topology the Nodes record the file; inspect without the file reports it
5030: +    ${annotation} =    Node Field    client    {.metadata.annotations.containerlab\\.dev/topo-file}
5031: +    Should Be Equal    ${annotation}    ${topo}
5032: +    ${output} =    Run Clab Command    inspect --name ${lab-name} --format json
5033: +    ${paths} =    Evaluate    {n["absLabPath"] for n in json.loads($output.stdout)["${lab-name}"]}
5034: +    ...    modules=json
5035: +    Should Be Equal    ${paths}    ${{{"${topo}"}}}
5036: +
5037:  Apply without a Topology resource keeps a stopped node stopped
5038:      ${output} =    Run Clab Command    stop -t ${topo} --node client
5039:      Should Be Equal As Integers    ${output.rc}    0
5040:  
5041:      ${plan} =    Run Clab Command    deploy -t ${applied-topo} --no-topology-cr --dry-run --format json
5042: @@ -549,10 +691,12 @@ Setup
5043:      ${output} =    Run Clab Command    destroy -t ${topo} --cleanup
5044:      Log    Cleanup return code: ${output.rc}
5045:  
5046:  Teardown
5047:      Stop Events Process
5048: +    Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True
5049: +    Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True
5050:      Run Clab Command    destroy -t ${topo} --cleanup
5051:      Remove File If Exists    ${events-log}
5052:      Remove File If Exists    ${events-err}
5053:  
5054:  Run Clab Command
5055: @@ -639,17 +783,80 @@ Collect Events
5056:  Set Client Eth1
5057:      [Arguments]    ${state}
5058:      Run Clab Command    exec -t ${topo} --label ${client-label} --cmd 'ip link set dev eth1 ${state}'
5059:  
5060:  Interface Event Should Be Logged
5061: -    [Arguments]    ${path}    ${node}    ${ifname}    ${action}
5062: +    [Documentation]    An interface event with the action and, when given, one of the states.
5063: +    [Arguments]    ${path}    ${node}    ${ifname}    ${action}    @{states}
5064:      ${contents} =    Get File    ${path}
5065:      ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}
5066:      ${found} =    Evaluate
5067: -    ...    ($action, $actor, $ifname) in [(e.get("action"), e.get("actor_id"), e.get("attributes", {}).get("ifname")) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get("type") == "interface"]
5068: +    ...    any([e.get("action") == $action and e.get("actor_id") == $actor and e.get("attributes", {}).get("ifname") == $ifname and (not $states or e.get("attributes", {}).get("state") in $states) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get("type") == "interface"])
5069: +    ...    modules=json
5070: +    Should Be True    ${found}    no interface ${action} event ${states} for ${node}:${ifname}
5071: +
5072: +Last Interface State Should Be
5073: +    [Arguments]    ${path}    ${node}    ${ifname}    ${state}
5074: +    ${contents} =    Get File    ${path}
5075: +    ${states} =    Interface States    ${contents}    ${node}
5076: +    Should Be Equal    ${states}[${ifname}]    ${state}
5077: +
5078: +Container Actions
5079: +    [Arguments]    ${path}    ${node}
5080: +    ${contents} =    Get File    ${path}
5081: +    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}
5082: +    ${actions} =    Evaluate
5083: +    ...    [e["action"] for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get("type") == "container" and e.get("actor_id") == $actor]
5084: +    ...    modules=json
5085: +    RETURN    ${actions}
5086: +
5087: +Container Actions Should Include In Order
5088: +    [Arguments]    ${path}    ${node}    @{expected}
5089: +    ${actions} =    Container Actions    ${path}    ${node}
5090: +    # the expected actions appear in this order, other actions may come between them
5091: +    ${in_order} =    Evaluate
5092: +    ...    re.search("\\n" + "\\n(?:.*\\n)*?".join([re.escape(a) for a in $expected]) + "\\n", "\\n" + "\\n".join($actions) + "\\n") is not None
5093: +    ...    modules=re
5094: +    Should Be True    ${in_order}    ${node} reported ${actions}, not ${expected} in this order
5095: +
5096: +Container Event Should Carry Docker Attributes
5097: +    [Documentation]    The last container event of a node with the action carries the attributes
5098: +    ...    a Docker container event of the node has, and the container state.
5099: +    [Arguments]    ${events}    ${node}    ${action}    ${state}    ${topo-file}=${topo}
5100: +    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}
5101: +    ${matching} =    Evaluate
5102: +    ...    [e for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get("type") == "container" and e.get("actor_id") == $actor and e.get("action") == $action]
5103: +    ...    modules=json
5104: +    Should Not Be Empty    ${matching}    no container ${action} event for ${node}
5105: +    ${event} =    Set Variable    ${matching}[-1]
5106: +    ${attributes} =    Set Variable    ${event}[attributes]
5107: +    Log    ${attributes}
5108: +    Should Be Equal    ${attributes}[containerlab]    ${lab-name}
5109: +    Should Be Equal    ${attributes}[clab-node-name]    ${node}
5110: +    Should Be Equal    ${attributes}[clab-node-longname]    ${lab-name}-${node}
5111: +    Should Be Equal    ${attributes}[clab-node-kind]    linux
5112: +    Should Be Equal    ${attributes}[clab-topo-file]    ${topo-file}
5113: +    Should Not Be Empty    ${attributes}[clab-owner]
5114: +    Should Be Equal    ${attributes}[image]    ${node-image}
5115: +    Should Be Equal    ${attributes}[name]    ${lab-name}-${node}
5116: +    Should Be Equal    ${attributes}[id]    ${actor}
5117: +    Should Be Equal    ${event}[actor_full_id]    ${actor}
5118: +    # a node is created before the controller allocates its management address and Service
5119: +    IF    $state != "created"
5120: +        Should Match Regexp    ${attributes}[mgmt_ipv4]    ^\\d+\\.\\d+\\.\\d+\\.\\d+/\\d+$
5121: +        Should Contain    ${attributes}[ports]    22/tcp
5122: +    END
5123: +    Should Be Equal    ${attributes}[state]    ${state}
5124: +
5125: +Interface States
5126: +    [Documentation]    The interfaces the events report for a node, with their last state.
5127: +    [Arguments]    ${events}    ${node}
5128: +    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}
5129: +    ${states} =    Evaluate
5130: +    ...    {e["attributes"]["ifname"]: e["attributes"].get("state", "") for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get("type") == "interface" and e.get("actor_id") == $actor}
5131:      ...    modules=json
5132: -    Should Be True    ${found}    no interface ${action} event for ${node}:${ifname}
5133: +    RETURN    ${states}
5134:  
5135:  Log File Should Contain
5136:      [Arguments]    ${path}    ${text}
5137:      ${contents} =    Get File    ${path}
5138:      Should Contain    ${contents}    ${text}

(End of file - total 5138 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19674f294001IcPiA3zWm0N7ms",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674e4d9001A37rotvZLIlfwI",
  "callID": "call_915b4b6ce0964e1799e21a49",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "offset": 4396
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n4396:  func nodeStateFromResource(nodeResource *unstructured.Unstructured) clablabruntime.NodeState {\n4397:  \tnode := clablabruntime.NodeState{\n4398:  \t\tName:    nodeResource.GetName(),\n4399:  \t\tNodeUID: string(nodeResource.GetUID()),\n4400:  \t}\n4401: +\tif original := nodeResource.GetLabels()[labelOriginalNodeName]; original != node.Name {\n4402: +\t\tnode.TopologyName = original\n4403: +\t}\n4404:  \tnode.ExposedPorts = nodeExposedPorts(nodeResource)\n4405:  \t// The same container exec targets: the observed primary device container.\n4406:  \tnode.Container, _ = preferredDeviceContainerName(nodeResource, node.Name)\n4407:  \tnode.Kind, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"kind\")\n4408:  \tnode.Image, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"image\")\n4409: +\tnode.Type, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"type\")\n4410: +\tnode.Group, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"group\")\n4411:  \tnode.State, _, _ = unstructured.NestedString(nodeResource.Object, \"status\", \"readiness\")\n4412:  \tnode.Ready = node.State == \"ready\"\n4413:  \tnode.LoadBalancerAddress, _, _ = unstructured.NestedString(\n4414:  \t\tnodeResource.Object,\n4415:  \t\t\"status\",\n4416: @@ -132,17 +144,28 @@ func intField(value any) int {\n4417:  \tdefault:\n4418:  \t\treturn 0\n4419:  \t}\n4420:  }\n4421:  \n4422: -// newestPod prefers a running pod and, among equals, the newest one: several pods can match a\n4423: -// node during a rolling update.\n4424: +// newestPod prefers a pod that is not being deleted, then a running pod and, among equals, the\n4425: +// newest one: several pods can match a node during a rolling update or a restart, when the old\n4426: +// pod terminates while its replacement starts.\n4427:  func newestPod(current, candidate *corev1.Pod) *corev1.Pod {\n4428:  \tif current == nil {\n4429:  \t\treturn candidate\n4430:  \t}\n4431:  \n4432: +\tcurrentDeleting := current.DeletionTimestamp != nil\n4433: +\tcandidateDeleting := candidate.DeletionTimestamp != nil\n4434: +\tif currentDeleting != candidateDeleting {\n4435: +\t\tif candidateDeleting {\n4436: +\t\t\treturn current\n4437: +\t\t}\n4438: +\n4439: +\t\treturn candidate\n4440: +\t}\n4441: +\n4442:  \tcurrentRunning := current.Status.Phase == corev1.PodRunning\n4443:  \tcandidateRunning := candidate.Status.Phase == corev1.PodRunning\n4444:  \tif currentRunning != candidateRunning {\n4445:  \t\tif candidateRunning {\n4446:  \t\t\treturn candidate\n4447: @@ -197,20 +220,30 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat\n4448:  \tfor idx := range pods.Items {\n4449:  \t\tnodeName := pods.Items[idx].Labels[labelTopologyNode]\n4450:  \t\tif nodeName == \"\" {\n4451:  \t\t\tcontinue\n4452:  \t\t}\n4453: +\t\t// A pod of an earlier Node of the same name (a redeploy while the old pod still\n4454: +\t\t// terminates) is not this node's pod.\n4455: +\t\tif uid := pods.Items[idx].Annotations[annotationDirectNodeUID]; uid != \"\" {\n4456: +\t\t\tif resource := resourcesByName[nodeName]; resource != nil &&\n4457: +\t\t\t\tstring(resource.GetUID()) != uid {\n4458: +\t\t\t\tcontinue\n4459: +\t\t\t}\n4460: +\t\t}\n4461:  \t\tpodsByNode[nodeName] = newestPod(podsByNode[nodeName], &pods.Items[idx])\n4462:  \t}\n4463:  \n4464:  \t// The Node's status.readiness is the authoritative device signal. The primary Node's run\n4465:  \t// state governs the pod a group of nodes shares: a stopped primary stops the whole group.\n4466:  \t// Nodes without readiness yet report their pod phase.\n4467:  \tfor nodeName, node := range nodesByName {\n4468:  \t\tprimary := resolvePrimaryNode(nodeName, networkModes)\n4469: -\t\tif primaryResource := resourcesByName[primary]; primaryResource != nil &&\n4470: -\t\t\tnodeRunState(primaryResource) == nodeRunStateStopped {\n4471: +\t\tprimaryResource := resourcesByName[primary]\n4472: +\t\tstopRequested := primaryResource != nil &&\n4473: +\t\t\tnodeRunState(primaryResource) == nodeRunStateStopped\n4474: +\t\tif stopRequested {\n4475:  \t\t\tnode.State = \"stopping\"\n4476:  \t\t\tif condition := nodeCondition(\n4477:  \t\t\t\tprimaryResource,\n4478:  \t\t\t\tnodeConditionStopped,\n4479:  \t\t\t); condition != nil &&\n4480: @@ -220,10 +253,14 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat\n4481:  \t\t\tnode.Ready = false\n4482:  \t\t} else if pod := podsByNode[primary]; node.State == \"\" && pod != nil &&\n4483:  \t\t\tpod.Status.Phase != \"\" {\n4484:  \t\t\tnode.State = strings.ToLower(string(pod.Status.Phase))\n4485:  \t\t}\n4486: +\t\tnode.ContainerState = nodeContainerState(stopRequested, podsByNode[primary])\n4487: +\t\tif node.ContainerState == clablabruntime.ContainerStateRunning {\n4488: +\t\t\tnode.Health = nodeHealth(node, resourcesByName[nodeName])\n4489: +\t\t}\n4490:  \t\tnodesByName[nodeName] = node\n4491:  \t}\n4492:  \n4493:  \t// Nodes grouped through network-mode container: share the pod of the group's primary\n4494:  \t// node. Before the controller observed the device containers, the pod's default-container\n4495: @@ -270,5 +307,46 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat\n4496:  \t\tstate.Ready = false\n4497:  \t}\n4498:  \n4499:  \treturn nil\n4500:  }\n4501: +\n4502: +// nodeContainerState is the state of a node in container runtime terms, from its pod: created\n4503: +// while the pod is scheduled and prepared (init containers), running once the device containers\n4504: +// run, and exited once the node was stopped, its pod is being deleted, or the pod ended. Between\n4505: +// the pods of a restart the node is exited, then created.\n4506: +func nodeContainerState(stopRequested bool, pod *corev1.Pod) string {\n4507: +\tswitch {\n4508: +\tcase pod == nil && stopRequested:\n4509: +\t\treturn clablabruntime.ContainerStateExited\n4510: +\tcase pod == nil:\n4511: +\t\treturn clablabruntime.ContainerStateCreated\n4512: +\tcase stopRequested || pod.DeletionTimestamp != nil:\n4513: +\t\treturn clablabruntime.ContainerStateExited\n4514: +\t}\n4515: +\n4516: +\tswitch pod.Status.Phase {\n4517: +\tcase corev1.PodRunning:\n4518: +\t\treturn clablabruntime.ContainerStateRunning\n4519: +\tcase corev1.PodSucceeded, corev1.PodFailed:\n4520: +\t\treturn clablabruntime.ContainerStateExited\n4521: +\tdefault:\n4522: +\t\treturn clablabruntime.ContainerStateCreated\n4523: +\t}\n4524: +}\n4525: +\n4526: +// nodeHealth is the health of a running node: healthy once the Node is ready or its device\n4527: +// containers are, starting before. Device containers are the analogue of a container\n4528: +// healthcheck: a node whose links wait for a stopped peer is not ready, but its device is.\n4529: +func nodeHealth(node clablabruntime.NodeState, resource *unstructured.Unstructured) string {\n4530: +\tif node.Ready {\n4531: +\t\treturn clablabruntime.ContainerHealthHealthy\n4532: +\t}\n4533: +\tif resource != nil {\n4534: +\t\tif condition := nodeCondition(resource, nodeConditionContainersReady); condition != nil &&\n4535: +\t\t\tcondition.status == string(metav1.ConditionTrue) {\n4536: +\t\t\treturn clablabruntime.ContainerHealthHealthy\n4537: +\t\t}\n4538: +\t}\n4539: +\n4540: +\treturn clablabruntime.ContainerHealthStarting\n4541: +}\n4542: diff --git a/labruntime/clabernetes/topology.go b/labruntime/clabernetes/topology.go\n4543: index e401ecf..db3715a 100644\n4544: --- a/labruntime/clabernetes/topology.go\n4545: +++ b/labruntime/clabernetes/topology.go\n4546: @@ -12,10 +12,56 @@ import (\n4547:  \t\"k8s.io/apimachinery/pkg/util/validation\"\n4548:  )\n4549:  \n4550:  type topologyObjectOption func(map[string]any)\n4551:  \n4552: +// annotationTopologyFile records the absolute path of the topology file a lab was deployed from,\n4553: +// on the machine that deployed it. Inspect reports it as the lab's topology path and events as\n4554: +// clab-topo-file, as the local runtimes do, so clients match the running lab to its file. A lab\n4555: +// created by other means than a containerlab deploy has no annotation and reports where its\n4556: +// definition lives in the cluster (k8s://<namespace>/topologies/<lab>).\n4557: +const annotationTopologyFile = \"containerlab.dev/topo-file\"\n4558: +\n4559: +// setTopologySourceFile records the topology file a deploy reads on the Topology. An empty path\n4560: +// (a definition that came from no file) records nothing.\n4561: +func setTopologySourceFile(topology *unstructured.Unstructured, path string) {\n4562: +\tif path == \"\" {\n4563: +\t\treturn\n4564: +\t}\n4565: +\n4566: +\tannotations := topology.GetAnnotations()\n4567: +\tif annotations == nil {\n4568: +\t\tannotations = map[string]string{}\n4569: +\t}\n4570: +\tannotations[annotationTopologyFile] = path\n4571: +\ttopology.SetAnnotations(annotations)\n4572: +}\n4573: +\n4574: +// removeTopologySourceFile drops the deploying machine's file path from an object.\n4575: +func removeTopologySourceFile(obj *unstructured.Unstructured) {\n4576: +\tannotations := obj.GetAnnotations()\n4577: +\tif _, ok := annotations[annotationTopologyFile]; !ok {\n4578: +\t\treturn\n4579: +\t}\n4580: +\n4581: +\tdelete(annotations, annotationTopologyFile)\n4582: +\tif len(annotations) == 0 {\n4583: +\t\tannotations = nil\n4584: +\t}\n4585: +\tobj.SetAnnotations(annotations)\n4586: +}\n4587: +\n4588: +// labTopologyPath is the topology path a lab reports: the file it was deployed from when the\n4589: +// deploy recorded one, otherwise the place given.\n4590: +func labTopologyPath(annotations map[string]string, fallback string) string {\n4591: +\tif path := annotations[annotationTopologyFile]; path != \"\" {\n4592: +\t\treturn path\n4593: +\t}\n4594: +\n4595: +\treturn fallback\n4596: +}\n4597: +\n4598:  func topologyWithNaming(naming string) topologyObjectOption {\n4599:  \treturn func(spec map[string]any) {\n4600:  \t\tif naming != \"\" {\n4601:  \t\t\tspec[\"naming\"] = naming\n4602:  \t\t}\n4603: @@ -137,10 +183,14 @@ func stateFromTopology(obj *unstructured.Unstructured, namespace string) *clabla\n4604:  \towner := obj.GetLabels()[clabconstants.Owner]\n4605:  \tif owner == \"\" {\n4606:  \t\towner = obj.GetAnnotations()[clabconstants.Owner]\n4607:  \t}\n4608:  \tnodeSpecs := nodeSpecsFromTopology(obj)\n4609: +\ttopologyPath := labTopologyPath(\n4610: +\t\tobj.GetAnnotations(),\n4611: +\t\tfmt.Sprintf(\"k8s://%s/topologies/%s\", namespace, obj.GetName()),\n4612: +\t)\n4613:  \n4614:  \tnodeNames := make([]string, 0, len(nodeSpecs))\n4615:  \tfor nodeName := range nodeSpecs {\n4616:  \t\tnodeNames = append(nodeNames, nodeName)\n4617:  \t}\n4618: @@ -158,11 +208,11 @@ func stateFromTopology(obj *unstructured.Unstructured, namespace string) *clabla\n4619:  \n4620:  \treturn &clablabruntime.LabState{\n4621:  \t\tName:         obj.GetName(),\n4622:  \t\tNamespace:    namespace,\n4623:  \t\tOwner:        owner,\n4624: -\t\tTopologyPath: fmt.Sprintf(\"k8s://%s/topologies/%s\", namespace, obj.GetName()),\n4625: +\t\tTopologyPath: topologyPath,\n4626:  \t\tState:        state,\n4627:  \t\tReady:        ready,\n4628:  \t\tNodes:        nodes,\n4629:  \t}\n4630:  }\n4631: diff --git a/labruntime/runtime.go b/labruntime/runtime.go\n4632: index 367565d..0f2433a 100644\n4633: --- a/labruntime/runtime.go\n4634: +++ b/labruntime/runtime.go\n4635: @@ -191,16 +191,42 @@ type SavedFile struct {\n4636:  \n4637:  type SaveResult struct {\n4638:  \tFiles []SavedFile\n4639:  }\n4640:  \n4641: +// Container states and health in the vocabulary of container runtimes (Docker), which inspect\n4642: +// and events report for lab runtime nodes too.\n4643: +const (\n4644: +\tContainerStateCreated = \"created\"\n4645: +\tContainerStateRunning = \"running\"\n4646: +\tContainerStateExited  = \"exited\"\n4647: +\n4648: +\tContainerHealthHealthy   = \"healthy\"\n4649: +\tContainerHealthStarting  = \"starting\"\n4650: +\tContainerHealthUnhealthy = \"unhealthy\"\n4651: +)\n4652: +\n4653:  type NodeState struct {\n4654: -\tName  string\n4655: -\tKind  string\n4656: -\tImage string\n4657: +\tName string\n4658: +\t// TopologyName is the node name as the topology file spells it, when the runtime had to\n4659: +\t// carry the node under another name (Name). Empty means Name.\n4660: +\tTopologyName string\n4661: +\tKind         string\n4662: +\tImage        string\n4663: +\t// Type and Group are the node's type and group when the topology set them.\n4664: +\tType  string\n4665: +\tGroup string\n4666: +\t// State is the runtime's own view of the node, such as the clabernetes Node readiness, or\n4667: +\t// stopped.\n4668:  \tState string\n4669:  \tReady bool\n4670: +\t// ContainerState is the node's state in container runtime terms: created, running or\n4671: +\t// exited (the ContainerState* constants). Empty when the runtime does not report one.\n4672: +\tContainerState string\n4673: +\t// Health is the device health of a running node in container runtime terms: healthy or\n4674: +\t// starting. Empty when the node does not run.\n4675: +\tHealth string\n4676:  \t// MgmtIPv4Address and MgmtIPv6Address are the node's allocated management addresses in\n4677:  \t// CIDR notation, when the runtime reports them.\n4678:  \tMgmtIPv4Address     string\n4679:  \tMgmtIPv6Address     string\n4680:  \tLoadBalancerAddress string\n4681: @@ -216,13 +242,16 @@ type NodeState struct {\n4682:  \n4683:  // ExposedPort is a node port a lab runtime publishes through a Service.\n4684:  type ExposedPort = clabtypes.ExposedPort\n4685:  \n4686:  type LabState struct {\n4687: -\tName         string\n4688: -\tNamespace    string\n4689: -\tOwner        string\n4690: +\tName      string\n4691: +\tNamespace string\n4692: +\tOwner     string\n4693: +\t// TopologyPath is the absolute path of the topology file the lab was deployed from, on the\n4694: +\t// machine that deployed it. A lab the runtime did not deploy from a file reports where the\n4695: +\t// runtime keeps its definition instead (for c9s k8s://<namespace>/topologies/<lab>).\n4696:  \tTopologyPath string\n4697:  \tState        string\n4698:  \tReady        bool\n4699:  \tNodes        []NodeState\n4700:  }\n4701: @@ -258,11 +287,61 @@ type Event struct {\n4702:  \tType        string\n4703:  \tAction      string\n4704:  \tActorID     string\n4705:  \tActorName   string\n4706:  \tActorFullID string\n4707: -\tAttributes  map[string]string\n4708: +\t// Attributes are the runtime's own attributes. Event consumers add the attributes the\n4709: +\t// container runtimes report from Lab, Node and Interface.\n4710: +\tAttributes map[string]string\n4711: +\t// Lab and Node are the lab node a container or interface event is about, as Inspect\n4712: +\t// reports it. containerlab's events command describes the node from them the same way\n4713: +\t// inspect does, so both agree and match what the container runtimes report.\n4714: +\tLab  *LabState\n4715: +\tNode *NodeState\n4716: +\t// Interface is the interface an interface event reports.\n4717: +\tInterface *InterfaceEventData\n4718: +}\n4719: +\n4720: +// Event types and the origin attribute of lab runtime events.\n4721: +const (\n4722: +\tEventTypeContainer = \"container\"\n4723: +\tEventTypeInterface = \"interface\"\n4724: +\t// EventOriginSnapshot marks the events of --initial-state, in the origin attribute.\n4725: +\tEventOriginSnapshot = \"snapshot\"\n4726: +)\n4727: +\n4728: +// InterfaceEventData describes an interface of a node the way the container runtimes' interface\n4729: +// events do (netlink).\n4730: +type InterfaceEventData struct {\n4731: +\t// Name is the interface name inside the node.\n4732: +\tName string\n4733: +\t// Alias is the name the topology gave the interface when the node kind maps it (for\n4734: +\t// example ethernet-1/1 for SR Linux e1-1).\n4735: +\tAlias string\n4736: +\tIndex int\n4737: +\tMTU   int\n4738: +\tMAC   string\n4739: +\t// OperState is the operational state in netlink's vocabulary: up, down, lower-layer-down,\n4740: +\t// dormant, testing, not-present or unknown.\n4741: +\tOperState string\n4742: +\t// Type is the link type in netlink's vocabulary, such as veth or device (loopback).\n4743: +\tType string\n4744: +\t// Stats are set on stats events.\n4745: +\tStats *InterfaceStats\n4746: +}\n4747: +\n4748: +// InterfaceStats are the counters and rates of an interface stats event.\n4749: +type InterfaceStats struct {\n4750: +\tRxBytes   uint64\n4751: +\tTxBytes   uint64\n4752: +\tRxPackets uint64\n4753: +\tTxPackets uint64\n4754: +\tRxBps     float64\n4755: +\tTxBps     float64\n4756: +\tRxPps     float64\n4757: +\tTxPps     float64\n4758: +\tInterval  time.Duration\n4759:  }\n4760:  \n4761:  // NodeLocation is the workload that runs a lab node.\n4762:  type NodeLocation struct {\n4763:  \t// NodeName is the node name the runtime carries (the sanitized name).\n4764: diff --git a/tests/14-clabernetes/01-linux-lifecycle.robot b/tests/14-clabernetes/01-linux-lifecycle.robot\n4765: index f45a3ff..bc27828 100644\n4766: --- a/tests/14-clabernetes/01-linux-lifecycle.robot\n4767: +++ b/tests/14-clabernetes/01-linux-lifecycle.robot\n4768: @@ -27,10 +27,15 @@ ${recovery-timeout}     180s\n4769:  ${retry-interval}       5s\n4770:  ${capture-file}         /tmp/clab-c9s-capture.pcapng\n4771:  ${chain-file}           /tmp/clab-c9s-capture-chain.pcapng\n4772:  ${stop-file}            /tmp/clab-c9s-capture-stop.pcapng\n4773:  ${stop-err}             /tmp/clab-c9s-capture-stop.err\n4774: +${lifecycle-log}        /tmp/clab-c9s-lifecycle-events.log\n4775: +${lifecycle-err}        /tmp/clab-c9s-lifecycle-events.err\n4776: +${redeploy-log}         /tmp/clab-c9s-redeploy-events.log\n4777: +${redeploy-err}         /tmp/clab-c9s-redeploy-events.err\n4778: +${node-image}           ghcr.io/srl-labs/network-multitool\n4779:  \n4780:  \n4781:  *** Test Cases ***\n4782:  Deploy c9s linux lab\n4783:      ${output} =    Run Clab Command    deploy -t ${topo}\n4784: @@ -103,10 +108,47 @@ Inspect all is scoped by the namespace override\n4785:  \n4786:      ${other} =    Run Clab Command    --namespace default inspect --all --format json\n4787:      Should Be Equal As Integers    ${other.rc}    0\n4788:      Should Not Contain    ${other.stdout}    ${lab-name}\n4789:  \n4790: +Inspect reports the topology file the lab was deployed from\n4791: +    # the deploy recorded this machine's file on the Topology; inspect without the file reports it\n4792: +    ${annotation} =    Process.Run Process\n4793: +    ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} -o jsonpath\\='{.metadata.annotations.containerlab\\\\.dev/topo-file}'\n4794: +    ...    shell=True\n4795: +    Should Be Equal As Integers    ${annotation.rc}    0\n4796: +    Should Be Equal    ${annotation.stdout}    ${topo}\n4797: +\n4798: +    ${output} =    Run Clab Command    inspect --all --format json\n4799: +    Should Be Equal As Integers    ${output.rc}    0\n4800: +    ${labs} =    Evaluate    json.loads($output.stdout)    modules=json\n4801: +    FOR    ${node}    IN    @{labs}[${lab-name}]\n4802: +        Should Be Equal    ${node}[absLabPath]    ${topo}\n4803: +        Should Not Start With    ${node}[labPath]    k8s://\n4804: +        Should Be Equal    ${node}[state]    running\n4805: +        Should Be Equal    ${node}[status]    healthy\n4806: +    END\n4807: +\n4808: +    # manifests are applied by other means; they do not carry this machine's path\n4809: +    ${emit} =    Run Offline Clab Command    deploy -t ${topo} --emit-crs\n4810: +    Should Be Equal As Integers    ${emit.rc}    0\n4811: +    Should Not Contain    ${emit.stdout}    containerlab.dev/topo-file\n4812: +\n4813: +Events carry the attributes of Docker events\n4814: +    ${events} =    Collect Events    --name ${lab-name} events --format json --initial-state\n4815: +    FOR    ${node}    IN    client    server\n4816: +        Container Event Should Carry Docker Attributes    ${events}    ${node}    running    running\n4817: +        # the interfaces a Docker container of the node has: the lab link, eth0 and lo, named\n4818: +        # as in the topology, the link up\n4819: +        ${ifaces} =    Interface States    ${events}    ${node}\n4820: +        Should Be Equal    ${{sorted($ifaces)}}    ${{[\"eth0\", \"eth1\", \"lo\"]}}\n4821: +        Should Be Equal    ${ifaces}[eth1]    up\n4822: +        Should Be Equal    ${ifaces}[eth0]    up\n4823: +        Should Be Equal    ${ifaces}[lo]    unknown\n4824: +    END\n4825: +    Should Not Contain    ${events}    \"ifname\":\"c9s\n4826: +\n4827:  Validate and emit-crs work without a kubeconfig\n4828:      ${validate} =    Run Offline Clab Command    validate -t ${topo}\n4829:      Should Be Equal As Integers    ${validate.rc}    0\n4830:      Should Contain    ${validate.stderr}    Topology is valid for lab runtime\n4831:  \n4832: @@ -141,17 +183,23 @@ Inspect interfaces lists the link interfaces with their state\n4833:      Should Be Equal As Integers    ${output.rc}    0\n4834:      ${containers} =    Evaluate    json.loads($output.stdout)    modules=json\n4835:      Length Should Be    ${containers}    2\n4836:      FOR    ${container}    IN    @{containers}\n4837:          Should Match Regexp    ${container}[name]    ^${lab-name}-(client|server)$\n4838: -        Length Should Be    ${container}[interfaces]    1\n4839: -        ${iface} =    Set Variable    ${container}[interfaces][0]\n4840: +        # what a Docker container of the node lists: eth0, the lab link and loopback\n4841: +        ${names} =    Evaluate    [i[\"name\"] for i in $container[\"interfaces\"]]\n4842: +        Should Be Equal    ${names}    ${{[\"eth0\", \"eth1\", \"lo\"]}}\n4843: +        ${iface} =    Set Variable    ${container}[interfaces][1]\n4844:          Should Be Equal    ${iface}[name]    eth1\n4845: +        Should Be Equal    ${iface}[alias]    ${EMPTY}\n4846:          Should Be Equal    ${iface}[type]    veth\n4847:          Should Be Equal    ${iface}[state]    up\n4848:          Should Match Regexp    ${iface}[mac]    ^([0-9a-f]{2}:){5}[0-9a-f]{2}$\n4849:          Should Be True    ${iface}[ifindex] > 0 and ${iface}[mtu] > 0\n4850: +        ${lo} =    Set Variable    ${container}[interfaces][2]\n4851: +        Should Be Equal    ${lo}[type]    device\n4852: +        Should Be Equal    ${lo}[state]    unknown\n4853:      END\n4854:  \n4855:      ${one} =    Run Clab Command    inspect interfaces --name ${lab-name} -n client -f json\n4856:      Should Be Equal As Integers    ${one.rc}    0\n4857:      ${only} =    Evaluate    [c[\"name\"] for c in json.loads($one.stdout)]    modules=json\n4858: @@ -338,10 +386,19 @@ Library attaches, port-forwards, streams logs and samples stats as an impersonat\n4859:      Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/stats\n4860:      Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/forbidden_identity\n4861:      Should Not Contain    ${result.stdout}    SKIP\n4862:  \n4863:  Stop server and verify dataplane interruption\n4864: +    # the events of the stop and the following start are checked as they happen\n4865: +    Remove File If Exists    ${lifecycle-log}\n4866: +    Start Process    ${CLAB_BIN} --runtime ${runtime} --name ${lab-name} events --format json\n4867: +    ...    shell=True\n4868: +    ...    alias=c9s_lifecycle\n4869: +    ...    stdout=${lifecycle-log}\n4870: +    ...    stderr=${lifecycle-err}\n4871: +    Sleep    5s\n4872: +\n4873:      ${output} =    Run Clab Command    stop -t ${topo} --node server\n4874:      Should Be Equal As Integers    ${output.rc}    0\n4875:  \n4876:      # stop is a run state patch on the Node; the controller removes the Pod\n4877:      ${run_state} =    Node Field    server    {.spec.runState}\n4878: @@ -351,14 +408,32 @@ Stop server and verify dataplane interruption\n4879:      ${pods} =    Process.Run Process\n4880:      ...    kubectl -n ${lab-namespace} get pods -l c9s.run/topologyNode\\=server -o name\n4881:      ...    shell=True\n4882:      Should Be Empty    ${pods.stdout}\n4883:      ${inspect} =    Run Clab Command    inspect -t ${topo} --format json\n4884: -    Should Contain    ${inspect.stdout}    \"state\": \"stopped\"\n4885: +    ${states} =    Evaluate\n4886: +    ...    {n[\"name\"]: (n[\"state\"], n[\"status\"]) for n in json.loads($inspect.stdout)[\"${lab-name}\"]}\n4887: +    ...    modules=json\n4888: +    Should Be Equal    ${states}[${lab-name}-server]    ${{(\"exited\", \"Exited\")}}\n4889:  \n4890:      Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Fail\n4891:  \n4892: +Stopping a node reports the events Docker reports for containerlab stop\n4893: +    # Docker: kill, stop, die; the node's interfaces go with it, its peer loses carrier\n4894: +    Wait Until Keyword Succeeds    30s    1s\n4895: +    ...    Container Actions Should Include In Order    ${lifecycle-log}    server\n4896: +    ...    kill    stop    die\n4897: +    ${events} =    Get File    ${lifecycle-log}\n4898: +    Container Event Should Carry Docker Attributes    ${events}    server    die    exited\n4899: +    Wait Until Keyword Succeeds    30s    1s\n4900: +    ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    delete\n4901: +    Wait Until Keyword Succeeds    30s    1s\n4902: +    ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update\n4903: +    ...    lower-layer-down    down\n4904: +    ${client} =    Container Actions    ${lifecycle-log}    client\n4905: +    Should Not Contain    ${client}    die\n4906: +\n4907:  Apply while server is stopped keeps it stopped\n4908:      ${output} =    Run Clab Command    deploy -t ${applied-topo}\n4909:      Should Be Equal As Integers    ${output.rc}    0\n4910:      # the wait settles on the stopped node instead of waiting for it\n4911:      Should Contain    ${output.stderr}    C9s lab is ready apart from stopped nodes\n4912: @@ -385,10 +460,33 @@ Start server by lab name and verify dataplane restore\n4913:      Should Be Equal As Integers    ${mark.rc}    0\n4914:      Should Contain    ${mark_output}    applied-while-stopped\n4915:  \n4916:      Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n4917:  \n4918: +Starting a node reports the events Docker reports for containerlab start\n4919: +    TRY\n4920: +        # Docker: start; the device's readiness as a container health check\n4921: +        Wait Until Keyword Succeeds    60s    1s\n4922: +        ...    Container Actions Should Include In Order    ${lifecycle-log}    server\n4923: +        ...    kill    stop    die    start    health_status: healthy\n4924: +        ${events} =    Get File    ${lifecycle-log}\n4925: +        # the lab was last deployed from the applied file, which the Topology now records\n4926: +        Container Event Should Carry Docker Attributes\n4927: +        ...    ${events}    server    start    running    ${applied-topo}\n4928: +        Container Event Should Carry Docker Attributes\n4929: +        ...    ${events}    server    health_status: healthy    running    ${applied-topo}\n4930: +        Wait Until Keyword Succeeds    60s    1s\n4931: +        ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    create\n4932: +        Wait Until Keyword Succeeds    60s    1s\n4933: +        ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update    up\n4934: +        Validate JSON Lines    ${lifecycle-log}\n4935: +    FINALLY\n4936: +        Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True\n4937: +        Remove File If Exists    ${lifecycle-log}\n4938: +        Remove File If Exists    ${lifecycle-err}\n4939: +    END\n4940: +\n4941:  Restart server and keep dataplane working\n4942:      ${before} =    Server Pod Name\n4943:      ${output} =    Run Clab Command    restart -t ${topo} --node server\n4944:      Should Be Equal As Integers    ${output.rc}    0\n4945:  \n4946: @@ -445,26 +543,36 @@ Events report interface up and down\n4947:          ...    stdout=${iface-events-log}\n4948:          ...    stderr=${iface-events-err}\n4949:          Sleep    5s\n4950:          Set Client Eth1    down\n4951:          Wait Until Keyword Succeeds    30s    1s\n4952: -        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    down\n4953: +        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    down\n4954:          # the peer loses carrier\n4955:          Wait Until Keyword Succeeds    30s    1s\n4956: -        ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    down\n4957: +        ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    update\n4958: +        ...    lower-layer-down    down\n4959:          Set Client Eth1    up\n4960:          Wait Until Keyword Succeeds    30s    1s\n4961: -        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    up\n4962: +        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    up\n4963:          Validate JSON Lines    ${iface-events-log}\n4964:      FINALLY\n4965:          Stop Events Process\n4966:          Set Client Eth1    up\n4967:          Remove File If Exists    ${iface-events-log}\n4968:          Remove File If Exists    ${iface-events-err}\n4969:      END\n4970:  \n4971:  Destroy without cleanup keeps the persistent claims\n4972: +    # the events of the destroy and the following deploy are checked after the deploy\n4973: +    Remove File If Exists    ${redeploy-log}\n4974: +    Start Process    ${CLAB_BIN} --runtime ${runtime} --namespace ${lab-namespace} events --format json\n4975: +    ...    shell=True\n4976: +    ...    alias=c9s_redeploy\n4977: +    ...    stdout=${redeploy-log}\n4978: +    ...    stderr=${redeploy-err}\n4979: +    Sleep    5s\n4980: +\n4981:      ${before} =    Persistent Claim Volumes\n4982:      Should Not Be Empty    ${before}\n4983:  \n4984:      ${output} =    Run Clab Command    destroy -t ${topo}\n4985:      Should Be Equal As Integers    ${output.rc}    0\n4986: @@ -479,10 +587,36 @@ Deploy reuses the retained persistent claims\n4987:      Should Be Equal As Integers    ${output.rc}    0\n4988:  \n4989:      ${volumes} =    Persistent Claim Volumes\n4990:      Should Be Equal    ${volumes}    ${retained-volumes}\n4991:  \n4992: +Destroy and deploy report the events Docker reports\n4993: +    TRY\n4994: +        FOR    ${node}    IN    client    server\n4995: +            # Docker: kill, die, destroy; then create, start (and the health check)\n4996: +            Wait Until Keyword Succeeds    60s    1s\n4997: +            ...    Container Actions Should Include In Order    ${redeploy-log}    ${node}\n4998: +            ...    kill    die    destroy    create    start    health_status: healthy\n4999: +            ${events} =    Get File    ${redeploy-log}\n5000: +            # the destroyed lab was last deployed from the applied file, the new one from ${topo}\n5001: +            Container Event Should Carry Docker Attributes\n5002: +            ...    ${events}    ${node}    destroy    exited    ${applied-topo}\n5003: +            Container Event Should Carry Docker Attributes    ${events}    ${node}    create    created\n5004: +            Container Event Should Carry Docker Attributes    ${events}    ${node}    start    running\n5005: +            # like Docker, the link may be created down and come up after\n5006: +            Wait Until Keyword Succeeds    60s    1s\n5007: +            ...    Interface Event Should Be Logged    ${redeploy-log}    ${node}    eth1    create\n5008: +            Wait Until Keyword Succeeds    60s    1s\n5009: +            ...    Last Interface State Should Be    ${redeploy-log}    ${node}    eth1    up\n5010: +        END\n5011: +        Validate JSON Lines    ${redeploy-log}\n5012: +    FINALLY\n5013: +        Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True\n5014: +        Remove File If Exists    ${redeploy-log}\n5015: +        Remove File If Exists    ${redeploy-err}\n5016: +    END\n5017: +\n5018:  Destroy c9s linux lab\n5019:      ${output} =    Run Clab Command    destroy -t ${topo} --cleanup\n5020:      Should Be Equal As Integers    ${output.rc}    0\n5021:  \n5022:      ${inspect_all} =    Run Clab Command    inspect --all\n5023: @@ -509,10 +643,18 @@ Deploy c9s linux lab without a Topology resource\n5024:      ...    shell=True\n5025:      Should Be Equal As Integers    ${nodes.rc}    0\n5026:      Should Contain    ${nodes.stdout}    node.c9s.run/client\n5027:      Should Contain    ${nodes.stdout}    node.c9s.run/server\n5028:  \n5029: +    # without a Topology the Nodes record the file; inspect without the file reports it\n5030: +    ${annotation} =    Node Field    client    {.metadata.annotations.containerlab\\\\.dev/topo-file}\n5031: +    Should Be Equal    ${annotation}    ${topo}\n5032: +    ${output} =    Run Clab Command    inspect --name ${lab-name} --format json\n5033: +    ${paths} =    Evaluate    {n[\"absLabPath\"] for n in json.loads($output.stdout)[\"${lab-name}\"]}\n5034: +    ...    modules=json\n5035: +    Should Be Equal    ${paths}    ${{{\"${topo}\"}}}\n5036: +\n5037:  Apply without a Topology resource keeps a stopped node stopped\n5038:      ${output} =    Run Clab Command    stop -t ${topo} --node client\n5039:      Should Be Equal As Integers    ${output.rc}    0\n5040:  \n5041:      ${plan} =    Run Clab Command    deploy -t ${applied-topo} --no-topology-cr --dry-run --format json\n5042: @@ -549,10 +691,12 @@ Setup\n5043:      ${output} =    Run Clab Command    destroy -t ${topo} --cleanup\n5044:      Log    Cleanup return code: ${output.rc}\n5045:  \n5046:  Teardown\n5047:      Stop Events Process\n5048: +    Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True\n5049: +    Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True\n5050:      Run Clab Command    destroy -t ${topo} --cleanup\n5051:      Remove File If Exists    ${events-log}\n5052:      Remove File If Exists    ${events-err}\n5053:  \n5054:  Run Clab Command\n5055: @@ -639,17 +783,80 @@ Collect Events\n5056:  Set Client Eth1\n5057:      [Arguments]    ${state}\n5058:      Run Clab Command    exec -t ${topo} --label ${client-label} --cmd 'ip link set dev eth1 ${state}'\n5059:  \n5060:  Interface Event Should Be Logged\n5061: -    [Arguments]    ${path}    ${node}    ${ifname}    ${action}\n5062: +    [Documentation]    An interface event with the action and, when given, one of the states.\n5063: +    [Arguments]    ${path}    ${node}    ${ifname}    ${action}    @{states}\n5064:      ${contents} =    Get File    ${path}\n5065:      ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n5066:      ${found} =    Evaluate\n5067: -    ...    ($action, $actor, $ifname) in [(e.get(\"action\"), e.get(\"actor_id\"), e.get(\"attributes\", {}).get(\"ifname\")) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"interface\"]\n5068: +    ...    any([e.get(\"action\") == $action and e.get(\"actor_id\") == $actor and e.get(\"attributes\", {}).get(\"ifname\") == $ifname and (not $states or e.get(\"attributes\", {}).get(\"state\") in $states) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"interface\"])\n5069: +    ...    modules=json\n5070: +    Should Be True    ${found}    no interface ${action} event ${states} for ${node}:${ifname}\n5071: +\n5072: +Last Interface State Should Be\n5073: +    [Arguments]    ${path}    ${node}    ${ifname}    ${state}\n5074: +    ${contents} =    Get File    ${path}\n5075: +    ${states} =    Interface States    ${contents}    ${node}\n5076: +    Should Be Equal    ${states}[${ifname}]    ${state}\n5077: +\n5078: +Container Actions\n5079: +    [Arguments]    ${path}    ${node}\n5080: +    ${contents} =    Get File    ${path}\n5081: +    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n5082: +    ${actions} =    Evaluate\n5083: +    ...    [e[\"action\"] for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"container\" and e.get(\"actor_id\") == $actor]\n5084: +    ...    modules=json\n5085: +    RETURN    ${actions}\n5086: +\n5087: +Container Actions Should Include In Order\n5088: +    [Arguments]    ${path}    ${node}    @{expected}\n5089: +    ${actions} =    Container Actions    ${path}    ${node}\n5090: +    # the expected actions appear in this order, other actions may come between them\n5091: +    ${in_order} =    Evaluate\n5092: +    ...    re.search(\"\\\\n\" + \"\\\\n(?:.*\\\\n)*?\".join([re.escape(a) for a in $expected]) + \"\\\\n\", \"\\\\n\" + \"\\\\n\".join($actions) + \"\\\\n\") is not None\n5093: +    ...    modules=re\n5094: +    Should Be True    ${in_order}    ${node} reported ${actions}, not ${expected} in this order\n5095: +\n5096: +Container Event Should Carry Docker Attributes\n5097: +    [Documentation]    The last container event of a node with the action carries the attributes\n5098: +    ...    a Docker container event of the node has, and the container state.\n5099: +    [Arguments]    ${events}    ${node}    ${action}    ${state}    ${topo-file}=${topo}\n5100: +    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n5101: +    ${matching} =    Evaluate\n5102: +    ...    [e for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get(\"type\") == \"container\" and e.get(\"actor_id\") == $actor and e.get(\"action\") == $action]\n5103: +    ...    modules=json\n5104: +    Should Not Be Empty    ${matching}    no container ${action} event for ${node}\n5105: +    ${event} =    Set Variable    ${matching}[-1]\n5106: +    ${attributes} =    Set Variable    ${event}[attributes]\n5107: +    Log    ${attributes}\n5108: +    Should Be Equal    ${attributes}[containerlab]    ${lab-name}\n5109: +    Should Be Equal    ${attributes}[clab-node-name]    ${node}\n5110: +    Should Be Equal    ${attributes}[clab-node-longname]    ${lab-name}-${node}\n5111: +    Should Be Equal    ${attributes}[clab-node-kind]    linux\n5112: +    Should Be Equal    ${attributes}[clab-topo-file]    ${topo-file}\n5113: +    Should Not Be Empty    ${attributes}[clab-owner]\n5114: +    Should Be Equal    ${attributes}[image]    ${node-image}\n5115: +    Should Be Equal    ${attributes}[name]    ${lab-name}-${node}\n5116: +    Should Be Equal    ${attributes}[id]    ${actor}\n5117: +    Should Be Equal    ${event}[actor_full_id]    ${actor}\n5118: +    # a node is created before the controller allocates its management address and Service\n5119: +    IF    $state != \"created\"\n5120: +        Should Match Regexp    ${attributes}[mgmt_ipv4]    ^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+/\\\\d+$\n5121: +        Should Contain    ${attributes}[ports]    22/tcp\n5122: +    END\n5123: +    Should Be Equal    ${attributes}[state]    ${state}\n5124: +\n5125: +Interface States\n5126: +    [Documentation]    The interfaces the events report for a node, with their last state.\n5127: +    [Arguments]    ${events}    ${node}\n5128: +    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n5129: +    ${states} =    Evaluate\n5130: +    ...    {e[\"attributes\"][\"ifname\"]: e[\"attributes\"].get(\"state\", \"\") for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get(\"type\") == \"interface\" and e.get(\"actor_id\") == $actor}\n5131:      ...    modules=json\n5132: -    Should Be True    ${found}    no interface ${action} event for ${node}:${ifname}\n5133: +    RETURN    ${states}\n5134:  \n5135:  Log File Should Contain\n5136:      [Arguments]    ${path}    ${text}\n5137:      ${contents} =    Get File    ${path}\n5138:      Should Contain    ${contents}    ${text}\n\n(End of file - total 5138 lines)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": " func nodeStateFromResource(nodeResource *unstructured.Unstructured) clablabruntime.NodeState {\n \tnode := clablabruntime.NodeState{\n \t\tName:    nodeResource.GetName(),\n \t\tNodeUID: string(nodeResource.GetUID()),\n \t}\n+\tif original := nodeResource.GetLabels()[labelOriginalNodeName]; original != node.Name {\n+\t\tnode.TopologyName = original\n+\t}\n \tnode.ExposedPorts = nodeExposedPorts(nodeResource)\n \t// The same container exec targets: the observed primary device container.\n \tnode.Container, _ = preferredDeviceContainerName(nodeResource, node.Name)\n \tnode.Kind, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"kind\")\n \tnode.Image, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"image\")\n+\tnode.Type, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"type\")\n+\tnode.Group, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"group\")\n \tnode.State, _, _ = unstructured.NestedString(nodeResource.Object, \"status\", \"readiness\")\n \tnode.Ready = node.State == \"ready\"\n \tnode.LoadBalancerAddress, _, _ = unstructured.NestedString(\n \t\tnodeResource.Object,\n \t\t\"status\",",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": " func nodeStateFromResource(nodeResource *unstructured.Unstructured) clablabruntime.NodeState {\n \tnode := clablabruntime.NodeState{\n \t\tName:    nodeResource.GetName(),\n \t\tNodeUID: string(nodeResource.GetUID()),\n \t}\n+\tif original := nodeResource.GetLabels()[labelOriginalNodeName]; original != node.Name {\n+\t\tnode.TopologyName = original\n+\t}\n \tnode.ExposedPorts = nodeExposedPorts(nodeResource)\n \t// The same container exec targets: the observed primary device container.\n \tnode.Container, _ = preferredDeviceContainerName(nodeResource, node.Name)\n \tnode.Kind, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"kind\")\n \tnode.Image, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"image\")\n+\tnode.Type, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"type\")\n+\tnode.Group, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"group\")\n \tnode.State, _, _ = unstructured.NestedString(nodeResource.Object, \"status\", \"readiness\")\n \tnode.Ready = node.State == \"ready\"\n \tnode.LoadBalancerAddress, _, _ = unstructured.NestedString(\n \t\tnodeResource.Object,\n \t\t\"status\",\n@@ -132,17 +144,28 @@ func intField(value any) int {\n \tdefault:\n \t\treturn 0\n \t}\n }\n \n-// newestPod prefers a running pod and, among equals, the newest one: several pods can match a\n-// node during a rolling update.\n+// newestPod prefers a pod that is not being deleted, then a running pod and, among equals, the\n+// newest one: several pods can match a node during a rolling update or a restart, when the old\n+// pod terminates while its replacement starts.\n func newestPod(current, candidate *corev1.Pod) *corev1.Pod {\n \tif current == nil {\n \t\treturn candidate\n \t}\n \n+\tcurrentDeleting := current.DeletionTimestamp != nil\n+\tcandidateDeleting := candidate.DeletionTimestamp != nil\n+\tif currentDeleting != candidateDeleting {\n+\t\tif candidateDeleting {\n+\t\t\treturn current\n+\t\t}\n+\n+\t\treturn candidate\n+\t}\n+\n \tcurrentRunning := current.Status.Phase == corev1.PodRunning\n \tcandidateRunning := candidate.Status.Phase == corev1.PodRunning\n \tif currentRunning != candidateRunning {\n \t\tif candidateRunning {\n \t\t\treturn candidate\n@@ -197,20 +220,30 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat\n \tfor idx := range pods.Items {\n \t\tnodeName := pods.Items[idx].Labels[labelTopologyNode]\n \t\tif nodeName == \"\" {\n \t\t\tcontinue\n \t\t}\n+\t\t// A pod of an earlier Node of the same name (a redeploy while the old pod still\n+\t\t// terminates) is not this node's pod.\n+\t\tif uid := pods.Items[idx].Annotations[annotationDirectNodeUID]; uid != \"\" {\n+\t\t\tif resource := resourcesByName[nodeName]; resource != nil &&\n+\t\t\t\tstring(resource.GetUID()) != uid {\n+\t\t\t\tcontinue\n+\t\t\t}\n+\t\t}\n \t\tpodsByNode[nodeName] = newestPod(podsByNode[nodeName], &pods.Items[idx])\n \t}\n \n \t// The Node's status.readiness is the authoritative device signal. The primary Node's run\n \t// state governs the pod a group of nodes shares: a stopped primary stops the whole group.\n \t// Nodes without readiness yet report their pod phase.\n \tfor nodeName, node := range nodesByName {\n \t\tprimary := resolvePrimaryNode(nodeName, networkModes)\n-\t\tif primaryResource := resourcesByName[primary]; primaryResource != nil &&\n-\t\t\tnodeRunState(primaryResource) == nodeRunStateStopped {\n+\t\tprimaryResource := resourcesByName[primary]\n+\t\tstopRequested := primaryResource != nil &&\n+\t\t\tnodeRunState(primaryResource) == nodeRunStateStopped\n+\t\tif stopRequested {\n \t\t\tnode.State = \"stopping\"\n \t\t\tif condition := nodeCondition(\n \t\t\t\tprimaryResource,\n \t\t\t\tnodeConditionStopped,\n \t\t\t); condition != nil &&\n@@ -220,10 +253,14 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat\n \t\t\tnode.Ready = false\n \t\t} else if pod := podsByNode[primary]; node.State == \"\" && pod != nil &&\n \t\t\tpod.Status.Phase != \"\" {\n \t\t\tnode.State = strings.ToLower(string(pod.Status.Phase))\n \t\t}\n+\t\tnode.ContainerState = nodeContainerState(stopRequested, podsByNode[primary])\n+\t\tif node.ContainerState == clablabruntime.ContainerStateRunning {\n+\t\t\tnode.Health = nodeHealth(node, resourcesByName[nodeName])\n+\t\t}\n \t\tnodesByName[nodeName] = node\n \t}\n \n \t// Nodes grouped through network-mode container: share the pod of the group's primary\n \t// node. Before the controller observed the device containers, the pod's default-container\n@@ -270,5 +307,46 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat\n \t\tstate.Ready = false\n \t}\n \n \treturn nil\n }\n+\n+// nodeContainerState is the state of a node in container runtime terms, from its pod: created\n+// while the pod is scheduled and prepared (init containers), running once the device containers\n+// run, and exited once the node was stopped, its pod is being deleted, or the pod ended. Between\n+// the pods of a restart the node is exited, then created.\n+func nodeContainerState(stopRequested bool, pod *corev1.Pod) string {\n+\tswitch {\n+\tcase pod == nil && stopRequested:\n+\t\treturn clablabruntime.ContainerStateExited\n+\tcase pod == nil:\n+\t\treturn clablabruntime.ContainerStateCreated\n+\tcase stopRequested || pod.DeletionTimestamp != nil:\n+\t\treturn clablabruntime.ContainerStateExited\n+\t}\n+\n+\tswitch pod.Status.Phase {\n+\tcase corev1.PodRunning:\n+\t\treturn clablabruntime.ContainerStateRunning\n+\tcase corev1.PodSucceeded, corev1.PodFailed:\n+\t\treturn clablabruntime.ContainerStateExited\n+\tdefault:\n+\t\treturn clablabruntime.ContainerStateCreated\n+\t}\n+}\n+\n+// nodeHealth is the health of a running node: healthy once the Node is ready or its device\n+// containers are, starting before. Device containers are the analogue of a container\n+// healthcheck: a node whose links wait for a stopped peer is not ready, but its device is.\n+func nodeHealth(node clablabruntime.NodeState, resource *unstructured.Unstructured) string {\n+\tif node.Ready {\n+\t\treturn clablabruntime.ContainerHealthHealthy\n+\t}\n+\tif resource != nil {\n+\t\tif condition := nodeCondition(resource, nodeConditionContainersReady); condition != nil &&\n+\t\t\tcondition.status == string(metav1.ConditionTrue) {\n+\t\t\treturn clablabruntime.ContainerHealthHealthy\n+\t\t}\n+\t}\n+\n+\treturn clablabruntime.ContainerHealthStarting\n+}\ndiff --git a/labruntime/clabernetes/topology.go b/labruntime/clabernetes/topology.go\nindex e401ecf..db3715a 100644\n--- a/labruntime/clabernetes/topology.go\n+++ b/labruntime/clabernetes/topology.go\n@@ -12,10 +12,56 @@ import (\n \t\"k8s.io/apimachinery/pkg/util/validation\"\n )\n \n type topologyObjectOption func(map[string]any)\n \n+// annotationTopologyFile records the absolute path of the topology file a lab was deployed from,\n+// on the machine that deployed it. Inspect reports it as the lab's topology path and events as\n+// clab-topo-file, as the local runtimes do, so clients match the running lab to its file. A lab\n+// created by other means than a containerlab deploy has no annotation and reports where its\n+// definition lives in the cluster (k8s://<namespace>/topologies/<lab>).\n+const annotationTopologyFile = \"containerlab.dev/topo-file\"\n+\n+// setTopologySourceFile records the topology file a deploy reads on the Topology. An empty path\n+// (a definition that came from no file) records nothing.\n+func setTopologySourceFile(topology *unstructured.Unstructured, path string) {\n+\tif path == \"\" {\n+\t\treturn\n+\t}\n+\n+\tannotations := topology.GetAnnotations()\n+\tif annotations == nil {\n+\t\tannotations = map[string]string{}\n+\t}\n+\tannotations[annotationTopologyFile] = path\n+\ttopology.SetAnnotations(annotations)\n+}\n+\n+// removeTopologySourceFile drops the deploying machine's file path from an object.\n+func removeTopologySourceFile(obj *unstructured.Unstructured) {\n+\tannotations := obj.GetAnnotations()\n+\tif _, ok := annotations[annotationTopologyFile]; !ok {\n+\t\treturn\n+\t}\n+\n+\tdelete(annotations, annotationTopologyFile)\n+\tif len(annotations) == 0 {\n+\t\tannotations = nil\n+\t}\n+\tobj.SetAnnotations(annotations)\n+}\n+\n+// labTopologyPath is the topology path a lab reports: the file it was deployed from when the\n+// deploy recorded one, otherwise the place given.\n+func labTopologyPath(annotations map[string]string, fallback string) string {\n+\tif path := annotations[annotationTopologyFile]; path != \"\" {\n+\t\treturn path\n+\t}\n+\n+\treturn fallback\n+}\n+\n func topologyWithNaming(naming string) topologyObjectOption {\n \treturn func(spec map[string]any) {\n \t\tif naming != \"\" {\n \t\t\tspec[\"naming\"] = naming\n \t\t}\n@@ -137,10 +183,14 @@ func stateFromTopology(obj *unstructured.Unstructured, namespace string) *clabla\n \towner := obj.GetLabels()[clabconstants.Owner]\n \tif owner == \"\" {\n \t\towner = obj.GetAnnotations()[clabconstants.Owner]\n \t}\n \tnodeSpecs := nodeSpecsFromTopology(obj)\n+\ttopologyPath := labTopologyPath(\n+\t\tobj.GetAnnotations(),\n+\t\tfmt.Sprintf(\"k8s://%s/topologies/%s\", namespace, obj.GetName()),\n+\t)\n \n \tnodeNames := make([]string, 0, len(nodeSpecs))\n \tfor nodeName := range nodeSpecs {\n \t\tnodeNames = append(nodeNames, nodeName)\n \t}\n@@ -158,11 +208,11 @@ func stateFromTopology(obj *unstructured.Unstructured, namespace string) *clabla\n \n \treturn &clablabruntime.LabState{\n \t\tName:         obj.GetName(),\n \t\tNamespace:    namespace,\n \t\tOwner:        owner,\n-\t\tTopologyPath: fmt.Sprintf(\"k8s://%s/topologies/%s\", namespace, obj.GetName()),\n+\t\tTopologyPath: topologyPath,\n \t\tState:        state,\n \t\tReady:        ready,\n \t\tNodes:        nodes,\n \t}\n }\ndiff --git a/labruntime/runtime.go b/labruntime/runtime.go\nindex 367565d..0f2433a 100644\n--- a/labruntime/runtime.go\n+++ b/labruntime/runtime.go\n@@ -191,16 +191,42 @@ type SavedFile struct {\n \n type SaveResult struct {\n \tFiles []SavedFile\n }\n \n+// Container states and health in the vocabulary of container runtimes (Docker), which inspect\n+// and events report for lab runtime nodes too.\n+const (\n+\tContainerStateCreated = \"created\"\n+\tContainerStateRunning = \"running\"\n+\tContainerStateExited  = \"exited\"\n+\n+\tContainerHealthHealthy   = \"healthy\"\n+\tContainerHealthStarting  = \"starting\"\n+\tContainerHealthUnhealthy = \"unhealthy\"\n+)\n+\n type NodeState struct {\n-\tName  string\n-\tKind  string\n-\tImage string\n+\tName string\n+\t// TopologyName is the node name as the topology file spells it, when the runtime had to\n+\t// carry the node under another name (Name). Empty means Name.\n+\tTopologyName string\n+\tKind         string\n+\tImage        string\n+\t// Type and Group are the node's type and group when the topology set them.\n+\tType  string\n+\tGroup string\n+\t// State is the runtime's own view of the node, such as the clabernetes Node readiness, or\n+\t// stopped.\n \tState string\n \tReady bool\n+\t// ContainerState is the node's state in container runtime terms: created, running or\n+\t// exited (the ContainerState* constants). Empty when the runtime does not report one.\n+\tContainerState string\n+\t// Health is the device health of a running node in container runtime terms: healthy or\n+\t// starting. Empty when the node does not run.\n+\tHealth string\n \t// MgmtIPv4Address and MgmtIPv6Address are the node's allocated management addresses in\n \t// CIDR notation, when the runtime reports them.\n \tMgmtIPv4Address     string\n \tMgmtIPv6Address     string\n \tLoadBalancerAddress string\n@@ -216,13 +242,16 @@ type NodeState struct {\n \n // ExposedPort is a node port a lab runtime publishes through a Service.\n type ExposedPort = clabtypes.ExposedPort\n \n type LabState struct {\n-\tName         string\n-\tNamespace    string\n-\tOwner        string\n+\tName      string\n+\tNamespace string\n+\tOwner     string\n+\t// TopologyPath is the absolute path of the topology file the lab was deployed from, on the\n+\t// machine that deployed it. A lab the runtime did not deploy from a file reports where the\n+\t// runtime keeps its definition instead (for c9s k8s://<namespace>/topologies/<lab>).\n \tTopologyPath string\n \tState        string\n \tReady        bool\n \tNodes        []NodeState\n }\n@@ -258,11 +287,61 @@ type Event struct {\n \tType        string\n \tAction      string\n \tActorID     string\n \tActorName   string\n \tActorFullID string\n-\tAttributes  map[string]string\n+\t// Attributes are the runtime's own attributes. Event consumers add the attributes the\n+\t// container runtimes report from Lab, Node and Interface.\n+\tAttributes map[string]string\n+\t// Lab and Node are the lab node a container or interface event is about, as Inspect\n+\t// reports it. containerlab's events command describes the node from them the same way\n+\t// inspect does, so both agree and match what the container runtimes report.\n+\tLab  *LabState\n+\tNode *NodeState\n+\t// Interface is the interface an interface event reports.\n+\tInterface *InterfaceEventData\n+}\n+\n+// Event types and the origin attribute of lab runtime events.\n+const (\n+\tEventTypeContainer = \"container\"\n+\tEventTypeInterface = \"interface\"\n+\t// EventOriginSnapshot marks the events of --initial-state, in the origin attribute.\n+\tEventOriginSnapshot = \"snapshot\"\n+)\n+\n+// InterfaceEventData describes an interface of a node the way the container runtimes' interface\n+// events do (netlink).\n+type InterfaceEventData struct {\n+\t// Name is the interface name inside the node.\n+\tName string\n+\t// Alias is the name the topology gave the interface when the node kind maps it (for\n+\t// example ethernet-1/1 for SR Linux e1-1).\n+\tAlias string\n+\tIndex int\n+\tMTU   int\n+\tMAC   string\n+\t// OperState is the operational state in netlink's vocabulary: up, down, lower-layer-down,\n+\t// dormant, testing, not-present or unknown.\n+\tOperState string\n+\t// Type is the link type in netlink's vocabulary, such as veth or device (loopback).\n+\tType string\n+\t// Stats are set on stats events.\n+\tStats *InterfaceStats\n+}\n+\n+// InterfaceStats are the counters and rates of an interface stats event.\n+type InterfaceStats struct {\n+\tRxBytes   uint64\n+\tTxBytes   uint64\n+\tRxPackets uint64\n+\tTxPackets uint64\n+\tRxBps     float64\n+\tTxBps     float64\n+\tRxPps     float64\n+\tTxPps     float64\n+\tInterval  time.Duration\n }\n \n // NodeLocation is the workload that runs a lab node.\n type NodeLocation struct {\n \t// NodeName is the node name the runtime carries (the sanitized name).\ndiff --git a/tests/14-clabernetes/01-linux-lifecycle.robot b/tests/14-clabernetes/01-linux-lifecycle.robot\nindex f45a3ff..bc27828 100644\n--- a/tests/14-clabernetes/01-linux-lifecycle.robot\n+++ b/tests/14-clabernetes/01-linux-lifecycle.robot\n@@ -27,10 +27,15 @@ ${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+${lifecycle-log}        /tmp/clab-c9s-lifecycle-events.log\n+${lifecycle-err}        /tmp/clab-c9s-lifecycle-events.err\n+${redeploy-log}         /tmp/clab-c9s-redeploy-events.log\n+${redeploy-err}         /tmp/clab-c9s-redeploy-events.err\n+${node-image}           ghcr.io/srl-labs/network-multitool\n \n \n *** Test Cases ***\n Deploy c9s linux lab\n     ${output} =    Run Clab Command    deploy -t ${topo}\n@@ -103,10 +108,47 @@ Inspect all is scoped by the namespace override\n \n     ${other} =    Run Clab Command    --namespace default inspect --all --format json\n     Should Be Equal As Integers    ${other.rc}    0\n     Should Not Contain    ${other.stdout}    ${lab-name}\n \n+Inspect reports the topology file the lab was deployed from\n+    # the deploy recorded this machine's file on the Topology; inspect without the file reports it\n+    ${annotation} =    Process.Run Process\n+    ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} -o jsonpath\\='{.metadata.annotations.containerlab\\\\.dev/topo-file}'\n+    ...    shell=True\n+    Should Be Equal As Integers    ${annotation.rc}    0\n+    Should Be Equal    ${annotation.stdout}    ${topo}\n+\n+    ${output} =    Run Clab Command    inspect --all --format json\n+    Should Be Equal As Integers    ${output.rc}    0\n+    ${labs} =    Evaluate    json.loads($output.stdout)    modules=json\n+    FOR    ${node}    IN    @{labs}[${lab-name}]\n+        Should Be Equal    ${node}[absLabPath]    ${topo}\n+        Should Not Start With    ${node}[labPath]    k8s://\n+        Should Be Equal    ${node}[state]    running\n+        Should Be Equal    ${node}[status]    healthy\n+    END\n+\n+    # manifests are applied by other means; they do not carry this machine's path\n+    ${emit} =    Run Offline Clab Command    deploy -t ${topo} --emit-crs\n+    Should Be Equal As Integers    ${emit.rc}    0\n+    Should Not Contain    ${emit.stdout}    containerlab.dev/topo-file\n+\n+Events carry the attributes of Docker events\n+    ${events} =    Collect Events    --name ${lab-name} events --format json --initial-state\n+    FOR    ${node}    IN    client    server\n+        Container Event Should Carry Docker Attributes    ${events}    ${node}    running    running\n+        # the interfaces a Docker container of the node has: the lab link, eth0 and lo, named\n+        # as in the topology, the link up\n+        ${ifaces} =    Interface States    ${events}    ${node}\n+        Should Be Equal    ${{sorted($ifaces)}}    ${{[\"eth0\", \"eth1\", \"lo\"]}}\n+        Should Be Equal    ${ifaces}[eth1]    up\n+        Should Be Equal    ${ifaces}[eth0]    up\n+        Should Be Equal    ${ifaces}[lo]    unknown\n+    END\n+    Should Not Contain    ${events}    \"ifname\":\"c9s\n+\n Validate and emit-crs work without a kubeconfig\n     ${validate} =    Run Offline Clab Command    validate -t ${topo}\n     Should Be Equal As Integers    ${validate.rc}    0\n     Should Contain    ${validate.stderr}    Topology is valid for lab runtime\n \n@@ -141,17 +183,23 @@ Inspect interfaces lists the link interfaces with their state\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+        # what a Docker container of the node lists: eth0, the lab link and loopback\n+        ${names} =    Evaluate    [i[\"name\"] for i in $container[\"interfaces\"]]\n+        Should Be Equal    ${names}    ${{[\"eth0\", \"eth1\", \"lo\"]}}\n+        ${iface} =    Set Variable    ${container}[interfaces][1]\n         Should Be Equal    ${iface}[name]    eth1\n+        Should Be Equal    ${iface}[alias]    ${EMPTY}\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+        ${lo} =    Set Variable    ${container}[interfaces][2]\n+        Should Be Equal    ${lo}[type]    device\n+        Should Be Equal    ${lo}[state]    unknown\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@@ -338,10 +386,19 @@ Library attaches, port-forwards, streams logs and samples stats as an impersonat\n     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/stats\n     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/forbidden_identity\n     Should Not Contain    ${result.stdout}    SKIP\n \n Stop server and verify dataplane interruption\n+    # the events of the stop and the following start are checked as they happen\n+    Remove File If Exists    ${lifecycle-log}\n+    Start Process    ${CLAB_BIN} --runtime ${runtime} --name ${lab-name} events --format json\n+    ...    shell=True\n+    ...    alias=c9s_lifecycle\n+    ...    stdout=${lifecycle-log}\n+    ...    stderr=${lifecycle-err}\n+    Sleep    5s\n+\n     ${output} =    Run Clab Command    stop -t ${topo} --node server\n     Should Be Equal As Integers    ${output.rc}    0\n \n     # stop is a run state patch on the Node; the controller removes the Pod\n     ${run_state} =    Node Field    server    {.spec.runState}\n@@ -351,14 +408,32 @@ Stop server and verify dataplane interruption\n     ${pods} =    Process.Run Process\n     ...    kubectl -n ${lab-namespace} get pods -l c9s.run/topologyNode\\=server -o name\n     ...    shell=True\n     Should Be Empty    ${pods.stdout}\n     ${inspect} =    Run Clab Command    inspect -t ${topo} --format json\n-    Should Contain    ${inspect.stdout}    \"state\": \"stopped\"\n+    ${states} =    Evaluate\n+    ...    {n[\"name\"]: (n[\"state\"], n[\"status\"]) for n in json.loads($inspect.stdout)[\"${lab-name}\"]}\n+    ...    modules=json\n+    Should Be Equal    ${states}[${lab-name}-server]    ${{(\"exited\", \"Exited\")}}\n \n     Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Fail\n \n+Stopping a node reports the events Docker reports for containerlab stop\n+    # Docker: kill, stop, die; the node's interfaces go with it, its peer loses carrier\n+    Wait Until Keyword Succeeds    30s    1s\n+    ...    Container Actions Should Include In Order    ${lifecycle-log}    server\n+    ...    kill    stop    die\n+    ${events} =    Get File    ${lifecycle-log}\n+    Container Event Should Carry Docker Attributes    ${events}    server    die    exited\n+    Wait Until Keyword Succeeds    30s    1s\n+    ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    delete\n+    Wait Until Keyword Succeeds    30s    1s\n+    ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update\n+    ...    lower-layer-down    down\n+    ${client} =    Container Actions    ${lifecycle-log}    client\n+    Should Not Contain    ${client}    die\n+\n Apply while server is stopped keeps it stopped\n     ${output} =    Run Clab Command    deploy -t ${applied-topo}\n     Should Be Equal As Integers    ${output.rc}    0\n     # the wait settles on the stopped node instead of waiting for it\n     Should Contain    ${output.stderr}    C9s lab is ready apart from stopped nodes\n@@ -385,10 +460,33 @@ Start server by lab name and verify dataplane restore\n     Should Be Equal As Integers    ${mark.rc}    0\n     Should Contain    ${mark_output}    applied-while-stopped\n \n     Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n \n+Starting a node reports the events Docker reports for containerlab start\n+    TRY\n+        # Docker: start; the device's readiness as a container health check\n+        Wait Until Keyword Succeeds    60s    1s\n+        ...    Container Actions Should Include In Order    ${lifecycle-log}    server\n+        ...    kill    stop    die    start    health_status: healthy\n+        ${events} =    Get File    ${lifecycle-log}\n+        # the lab was last deployed from the applied file, which the Topology now records\n+        Container Event Should Carry Docker Attributes\n+        ...    ${events}    server    start    running    ${applied-topo}\n+        Container Event Should Carry Docker Attributes\n+        ...    ${events}    server    health_status: healthy    running    ${applied-topo}\n+        Wait Until Keyword Succeeds    60s    1s\n+        ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    create\n+        Wait Until Keyword Succeeds    60s    1s\n+        ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update    up\n+        Validate JSON Lines    ${lifecycle-log}\n+    FINALLY\n+        Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True\n+        Remove File If Exists    ${lifecycle-log}\n+        Remove File If Exists    ${lifecycle-err}\n+    END\n+\n Restart server and keep dataplane working\n     ${before} =    Server Pod Name\n     ${output} =    Run Clab Command    restart -t ${topo} --node server\n     Should Be Equal As Integers    ${output.rc}    0\n \n@@ -445,26 +543,36 @@ Events report interface up and down\n         ...    stdout=${iface-events-log}\n         ...    stderr=${iface-events-err}\n         Sleep    5s\n         Set Client Eth1    down\n         Wait Until Keyword Succeeds    30s    1s\n-        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    down\n+        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    down\n         # the peer loses carrier\n         Wait Until Keyword Succeeds    30s    1s\n-        ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    down\n+        ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    update\n+        ...    lower-layer-down    down\n         Set Client Eth1    up\n         Wait Until Keyword Succeeds    30s    1s\n-        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    up\n+        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    up\n         Validate JSON Lines    ${iface-events-log}\n     FINALLY\n         Stop Events Process\n         Set Client Eth1    up\n         Remove File If Exists    ${iface-events-log}\n         Remove File If Exists    ${iface-events-err}\n     END\n \n Destroy without cleanup keeps the persistent claims\n+    # the events of the destroy and the following deploy are checked after the deploy\n+    Remove File If Exists    ${redeploy-log}\n+    Start Process    ${CLAB_BIN} --runtime ${runtime} --namespace ${lab-namespace} events --format json\n+    ...    shell=True\n+    ...    alias=c9s_redeploy\n+    ...    stdout=${redeploy-log}\n+    ...    stderr=${redeploy-err}\n+    Sleep    5s\n+\n     ${before} =    Persistent Claim Volumes\n     Should Not Be Empty    ${before}\n \n     ${output} =    Run Clab Command    destroy -t ${topo}\n     Should Be Equal As Integers    ${output.rc}    0\n@@ -479,10 +587,36 @@ Deploy reuses the retained persistent claims\n     Should Be Equal As Integers    ${output.rc}    0\n \n     ${volumes} =    Persistent Claim Volumes\n     Should Be Equal    ${volumes}    ${retained-volumes}\n \n+Destroy and deploy report the events Docker reports\n+    TRY\n+        FOR    ${node}    IN    client    server\n+            # Docker: kill, die, destroy; then create, start (and the health check)\n+            Wait Until Keyword Succeeds    60s    1s\n+            ...    Container Actions Should Include In Order    ${redeploy-log}    ${node}\n+            ...    kill    die    destroy    create    start    health_status: healthy\n+            ${events} =    Get File    ${redeploy-log}\n+            # the destroyed lab was last deployed from the applied file, the new one from ${topo}\n+            Container Event Should Carry Docker Attributes\n+            ...    ${events}    ${node}    destroy    exited    ${applied-topo}\n+            Container Event Should Carry Docker Attributes    ${events}    ${node}    create    created\n+            Container Event Should Carry Docker Attributes    ${events}    ${node}    start    running\n+            # like Docker, the link may be created down and come up after\n+            Wait Until Keyword Succeeds    60s    1s\n+            ...    Interface Event Should Be Logged    ${redeploy-log}    ${node}    eth1    create\n+            Wait Until Keyword Succeeds    60s    1s\n+            ...    Last Interface State Should Be    ${redeploy-log}    ${node}    eth1    up\n+        END\n+        Validate JSON Lines    ${redeploy-log}\n+    FINALLY\n+        Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True\n+        Remove File If Exists    ${redeploy-log}\n+        Remove File If Exists    ${redeploy-err}\n+    END\n+\n Destroy c9s linux lab\n     ${output} =    Run Clab Command    destroy -t ${topo} --cleanup\n     Should Be Equal As Integers    ${output.rc}    0\n \n     ${inspect_all} =    Run Clab Command    inspect --all\n@@ -509,10 +643,18 @@ Deploy c9s linux lab without a Topology resource\n     ...    shell=True\n     Should Be Equal As Integers    ${nodes.rc}    0\n     Should Contain    ${nodes.stdout}    node.c9s.run/client\n     Should Contain    ${nodes.stdout}    node.c9s.run/server\n \n+    # without a Topology the Nodes record the file; inspect without the file reports it\n+    ${annotation} =    Node Field    client    {.metadata.annotations.containerlab\\\\.dev/topo-file}\n+    Should Be Equal    ${annotation}    ${topo}\n+    ${output} =    Run Clab Command    inspect --name ${lab-name} --format json\n+    ${paths} =    Evaluate    {n[\"absLabPath\"] for n in json.loads($output.stdout)[\"${lab-name}\"]}\n+    ...    modules=json\n+    Should Be Equal    ${paths}    ${{{\"${topo}\"}}}\n+\n Apply without a Topology resource keeps a stopped node stopped\n     ${output} =    Run Clab Command    stop -t ${topo} --node client\n     Should Be Equal As Integers    ${output.rc}    0\n \n     ${plan} =    Run Clab Command    deploy -t ${applied-topo} --no-topology-cr --dry-run --format json\n@@ -549,10 +691,12 @@ Setup\n     ${output} =    Run Clab Command    destroy -t ${topo} --cleanup\n     Log    Cleanup return code: ${output.rc}\n \n Teardown\n     Stop Events Process\n+    Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True\n+    Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True\n     Run Clab Command    destroy -t ${topo} --cleanup\n     Remove File If Exists    ${events-log}\n     Remove File If Exists    ${events-err}\n \n Run Clab Command\n@@ -639,17 +783,80 @@ Collect Events\n Set Client Eth1\n     [Arguments]    ${state}\n     Run Clab Command    exec -t ${topo} --label ${client-label} --cmd 'ip link set dev eth1 ${state}'\n \n Interface Event Should Be Logged\n-    [Arguments]    ${path}    ${node}    ${ifname}    ${action}\n+    [Documentation]    An interface event with the action and, when given, one of the states.\n+    [Arguments]    ${path}    ${node}    ${ifname}    ${action}    @{states}\n     ${contents} =    Get File    ${path}\n     ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n     ${found} =    Evaluate\n-    ...    ($action, $actor, $ifname) in [(e.get(\"action\"), e.get(\"actor_id\"), e.get(\"attributes\", {}).get(\"ifname\")) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"interface\"]\n+    ...    any([e.get(\"action\") == $action and e.get(\"actor_id\") == $actor and e.get(\"attributes\", {}).get(\"ifname\") == $ifname and (not $states or e.get(\"attributes\", {}).get(\"state\") in $states) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"interface\"])\n+    ...    modules=json\n+    Should Be True    ${found}    no interface ${action} event ${states} for ${node}:${ifname}\n+\n+Last Interface State Should Be\n+    [Arguments]    ${path}    ${node}    ${ifname}    ${state}\n+    ${contents} =    Get File    ${path}\n+    ${states} =    Interface States    ${contents}    ${node}\n+    Should Be Equal    ${states}[${ifname}]    ${state}\n+\n+Container Actions\n+    [Arguments]    ${path}    ${node}\n+    ${contents} =    Get File    ${path}\n+    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n+    ${actions} =    Evaluate\n+    ...    [e[\"action\"] for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"container\" and e.get(\"actor_id\") == $actor]\n+    ...    modules=json\n+    RETURN    ${actions}\n+\n+Container Actions Should Include In Order\n+    [Arguments]    ${path}    ${node}    @{expected}\n+    ${actions} =    Container Actions    ${path}    ${node}\n+    # the expected actions appear in this order, other actions may come between them\n+    ${in_order} =    Evaluate\n+    ...    re.search(\"\\\\n\" + \"\\\\n(?:.*\\\\n)*?\".join([re.escape(a) for a in $expected]) + \"\\\\n\", \"\\\\n\" + \"\\\\n\".join($actions) + \"\\\\n\") is not None\n+    ...    modules=re\n+    Should Be True    ${in_order}    ${node} reported ${actions}, not ${expected} in this order\n+\n+Container Event Should Carry Docker Attributes\n+    [Documentation]    The last container event of a node with the action carries the attributes\n+    ...    a Docker container event of the node has, and the container state.\n+    [Arguments]    ${events}    ${node}    ${action}    ${state}    ${topo-file}=${topo}\n+    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n+    ${matching} =    Evaluate\n+    ...    [e for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get(\"type\") == \"container\" and e.get(\"actor_id\") == $actor and e.get(\"action\") == $action]\n+    ...    modules=json\n+    Should Not Be Empty    ${matching}    no container ${action} event for ${node}\n+    ${event} =    Set Variable    ${matching}[-1]\n+    ${attributes} =    Set Variable    ${event}[attributes]\n+    Log    ${attributes}\n+    Should Be Equal    ${attributes}[containerlab]    ${lab-name}\n+    Should Be Equal    ${attributes}[clab-node-name]    ${node}\n+    Should Be Equal    ${attributes}[clab-node-longname]    ${lab-name}-${node}\n+    Should Be Equal    ${attributes}[clab-node-kind]    linux\n+    Should Be Equal    ${attributes}[clab-topo-file]    ${topo-file}\n+    Should Not Be Empty    ${attributes}[clab-owner]\n+    Should Be Equal    ${attributes}[image]    ${node-image}\n+    Should Be Equal    ${attributes}[name]    ${lab-name}-${node}\n+    Should Be Equal    ${attributes}[id]    ${actor}\n+    Should Be Equal    ${event}[actor_full_id]    ${actor}\n+    # a node is created before the controller allocates its management address and Service\n+    IF    $state != \"created\"\n+        Should Match Regexp    ${attributes}[mgmt_ipv4]    ^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+/\\\\d+$\n+        Should Contain    ${attributes}[ports]    22/tcp\n+    END\n+    Should Be Equal    ${attributes}[state]    ${state}\n+\n+Interface States\n+    [Documentation]    The interfaces the events report for a node, with their last state.\n+    [Arguments]    ${events}    ${node}\n+    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n+    ${states} =    Evaluate\n+    ...    {e[\"attributes\"][\"ifname\"]: e[\"attributes\"].get(\"state\", \"\") for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get(\"type\") == \"interface\" and e.get(\"actor_id\") == $actor}\n     ...    modules=json\n-    Should Be True    ${found}    no interface ${action} event for ${node}:${ifname}\n+    RETURN    ${states}\n \n Log File Should Contain\n     [Arguments]    ${path}    ${text}\n     ${contents} =    Get File    ${path}\n     Should Contain    ${contents}    ${text}",
        "lineStart": 4396,
        "lineEnd": 5138,
        "totalLines": 5138,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525609112,
      "end": 1793525609124
    }
  }
}
read · completed

Input

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

Output

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

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

1. core/events/netlink.go — head
2. core/events/stream.go — head
3. core/events/parity_test.go — head
4. core/labruntime.go — head
5. core/events (mergedEventAttributes, containerAttributes, aggregatedEventFromContainerSnapshot, exposedPortsAttributeValue, cloneStringMap)
6. labruntime/clabernetes/container_events.go
7. labruntime/clabernetes/events.go
8. labruntime/clabernetes/iface_stats.go
9. labruntime/clabernetes/capture_interfaces.go
10. labruntime/clabernetes/capture.go
11. labruntime/clabernetes/state.go
12. labruntime/clabernetes/topology.go
13. labruntime/clabernetes/manifests.go
14. labruntime/clabernetes/plan.go
15. labruntime/clabernetes/primitives.go
16. labruntime/clabernetes/reconcile.go
17. labruntime/runtime.go
18. labruntime/clabernetes/clabernetes.go
19. docs files
20. tests robot

Let me look for potential issues in the diff:

Issue candidates I've noticed while reading the diff:

1. **core/events/netlink.go `labRuntimeInterfaceAttributes`**: `lab` is set from `ev.Attributes["lab"]` or `ev.Lab.Name`. Then `labRuntimeInterfaceAttributes(lab, ev.ActorName, ev.Interface)` sets `attributes["name"] = name` — but wait, in the c9s interface event path, `aggregatedEventFromLabRuntimeEvent` case for interface: `attributes = labRuntimeInterfaceAttributes(lab, ev.ActorName, ev.Interface)`. But the parity test c9sInterfaceEvent passes `ev.ActorName: state.Name + "-" + node.Name`. Then the runtime's own attributes get merged on top: "namespace", "lab", "node", "pod", "origin". But there's a subtlety: `labRuntimeInterfaceAttributes` sets `attributes["lab"] = lab` (if lab != "") and `attributes["name"] = name`. Then the ev.Attributes merge sets "lab" to ev.Attributes["lab"] — which is the same lab. In parity test, the runtime Attributes contain "lab": state.Name. OK.

Hmm — but in stream.go, `lab := ev.Attributes["lab"]; if ev.Lab != nil { lab = ev.Lab.Name }`. Fine.

2. **containerTracker lock/timer logic in trackContainers**: the `arm` function: `if !armed { timer.Reset(delay); armed = true }`. And in the `case <-timer.C:` they set `armed = false`, then process. But note: the timer was created and stopped; timer.C initially is empty. Wait — there's a subtle bug: timer was created with time.Hour, then timer.Stop() is called immediately. Since the timer is initially armed at 1 hour and Stop() is called right away, does timer.C contain anything? Stop returns false only if already expired... Actually since timer was just created, the 1-hour timer hasn't expired; Stop() removes it from firing. So timer.C is empty. Good.

But there's a real subtlety with `timer.Reset`: "Reset should be invoked only on stopped or expired timers with drained channels." Here they call Reset on a stopped timer whose channel was drained? Actually the timer was stopped before the loop; the channel was never written. When the timer fires after Reset(delay), it writes to timer.C, and the select consumes it. Then armed=false, and the next Reset happens on a stopped timer with drained channel (the value was consumed by select). Wait, after select consumed timer.C, the timer has fired. Reset is allowed on expired timer with drained channel. OK.

But there is a potential issue: when they Reset while the timer is pending? `arm` is guarded by `armed` so Reset only when !armed. When timer fires, armed=false. So they never Reset a running timer. OK.

However, a real concern: `case ref := <-changed:` — pending[ref] = true; arm(200ms). If events keep coming in continuously for >200ms, the timer never fires because armed stays true? No — arm only sets when !armed; armed remains true until timer fires. So the batch will fire 200ms after first change. Good design.

3. **`refresh` returns false when the lab couldn't be read, and returns `ctx.Err() != nil`** — if ctx is done, returns true (stop retrying); otherwise false → re-queued. But note: `if ctx.Err() == nil { log.Debug } return ctx.Err() != nil` — returns false if ctx not done. But wait, when the lab read fails with a non-NotFound error and the context is not done, returns false and refresh is re-armed. OK.

Actually there's a subtle issue: `refresh` returns false → `pending[ref] = true` and the timer re-armed with `containerRefreshRetryDelay` = pollInterval. And if ctx.Err() != nil (done), refresh returns true but the loop's select will exit at ctx.Done(). Fine.

4. **`labStates` reads all labs in scope and reads the lab again whenever its Topology/Nodes/pods change**. Potential issue: In trackContainers, the initial `r.labStates(ctx, scope)` reads all labs and reports a snapshot only when `includeInitialState`. But `observeLab(ctx, labRef{...}, state, &observeSeed{snapshot: includeInitialState})` — if includeInitialState is false, it records nodes without reporting. Good.

5. **Potential race: `changed` channel buffer 256, `sendChangedLab` blocks on `select { case changed <- ref; case <-ctx.Done() }`** — if the tracker dies (e.g., errSink got an error from labStates... actually trackContainers returns only when labStates fails initially or ctx done). If labStates fails at startup, trackContainers returns; then watchNodes/watchTopologies/watchPods goroutines keep calling sendChangedLab, blocking until ctx.Done or until the buffer fills and blocks. Buffer 256 fills fast in a busy cluster; then all three watch goroutines block forever holding watcher.Stop() deferred, until ctx is done. If ctx is never done (StreamEvents ctx is passed by caller), then the watch goroutines block holding the `changed` channel; the error `errs` channel is fine. But the events channel keeps being fed by pollInterfaces. Hmm — if trackContainers dies early (labStates error), the container events stop being reported, but pollInterfaces keeps going. Watchers block. Not a leak per se since they are unblocked when ctx done. It's a degraded mode. The old code similarly had goroutines failing. Acceptable.

But there's a worse aspect: `sendEventError(ctx, errSink, err)` reports the error to errs; the events command streams errs? Let me check core/events/stream.go to see whether runtimeErrs fatal or just logged. Let me read the head file.

6. **`forwardTopologyWatch` reports Topology changes as topology events and the lab to the tracker.** The topology events have ActorID `fmt.Sprintf("%s/%s", namespace, labName)`? Let me check the current code.

7. **Potential deadlock: `labStates` inside trackContainers vs pollInterfaces reading labStates too; no shared lock, both fine.

8. **iface_stats `processStates` bug candidate**: 

```go
switch {
case seen && previous == data:
case !seen && p.firstRound:
    if p.opts.includeInitialState {
        p.emit(ctx, tracked, interfaceActionSnapshot, data, sample.timestamp)
    }
case !seen:
    p.emit(ctx, tracked, interfaceActionCreate, data, sample.timestamp)
default:
    p.emit(ctx, tracked, interfaceActionUpdate, data, sample.timestamp)
}
```

Wait, there's a subtle bug: `case seen && previous == data:` — `previous == data` compares structs (InterfaceEventData). But data.Stats is a pointer! For the same interface, `previous` came from the last sample's `interfaceEventData(iface, alias)` — a fresh struct without Stats. `data` also fresh, no Stats. So equality holds if all fields equal. OK.

But actually: is `previous == data` valid when data contains a pointer? InterfaceEventData comparison with a pointer field: comparable only if pointer; `previous == data` compares the pointer fields (both nil or both non-nil pointers). It compiles since structs with pointer fields are comparable. In processStates, `data` is fresh from interfaceEventData, so Stats is nil. OK.

Also note: the `case seen && previous == data:` — this also covers when the state changed but everything else equal? If OperState changed, previous != data → default → update. Good.

Hmm, but what about alias changes? Alias from clabwire listing. If alias changes, update is emitted. Fine.

One issue: when `!seen && p.firstRound && !p.opts.includeInitialState` — the original code `continue`d (did not report) but it still recorded `tracked.ifaces[iface.Name] = data` before the switch. In the new code, tracked.ifaces[name] = data is set before the switch too. Same behavior. But note: in the original code, when `!seen && p.firstRound && !includeInitialState`, the code continued, and the recorded iface stays in tracked.ifaces. Same as new. Good.

9. **`retireStoppedNodes` emits `delete` for all tracked ifaces and forgets them; then `processStates` re-adds them when the node runs again.** Wait — when a node stops and then starts again: retireStoppedNodes emits delete for all interfaces and deletes p.nodes[key]. Next sample when running: `known := p.nodes[key]` is false → tracked is fresh with empty ifaces; firstRound is false (already had a round); so `case !seen && p.firstRound:` doesn't match; `case !seen:` → emits create. Good.

But wait: what about the case where the node is not sampled but still tracked? retireStoppedNodes handles it. OK.

10. **Stats for no-shell nodes**: processSample — `if sample.hasStates { processStates(...) }`. For a no-shell node, hasStates is false, so processStates is skipped and `tracked.ifaces` stays empty. Then stats loop: `alias, ok := reported[stat.Name]; if !ok { continue }`. reported = reportedInterfaces(sample.links) — but sample.links comes from nodeLinks which lists pod interfaces via clabwire. For a no-shell node, clabwire --list-interfaces may fail? nodeLinks returns error → sample.err set → in sampleAll, sample has err. Let's check how errors are handled in the sample loop. In `sampleAll`, for each target, `samples[i] = p.sample(...)`; then in round: for each sample, `if sample.err != nil { log? }` Let me check the actual head code — the diff shows `p.processSample(ctx, sample)` in a loop; let me read the head to see the err handling.

Actually from the diff (lines 3604-3620 region), after sampleAll:

```go
	for i := range samples {
		if samples[i].err != nil {
			log.Debug(...)  ?
		}
		p.processSample(ctx, samples[i])
	}
```

I need to read the head file to be sure. Also there's a question: for a no-shell node, will nodeLinks error (clabwire exec fails)? In the old code, no-shell nodes reported stats without interface state, and no clabwire listing was made (old processSample handled stats for all sample.stats). In the new code, `sample.links, sample.err = p.nodeLinks(...)` — for a no-shell node, clabwire manager might not even be running? clabwireContainer is the sidecar container, which is part of the pod, so exec into it works. But `r.listPodInterfaces` runs `clabwireManager node-runtime packet-capture --list-interfaces` in the clabwire sidecar container. Would this fail for a no-shell node? The clabwire sidecar should respond regardless of the device container's shell. Hmm — but if it fails, sample.err set and the stats for that node would be dropped silently? That would be a behavior regression for no-shell nodes: previously stats events were emitted for no-shell nodes ("Device containers without a shell report statistics only, no interface state" — the docs still say this). New code: nodeLinks failing sets sample.err. Let me check the error handling in round — if sample.err is logged as debug and processSample is called anyway? Actually in the diff:

```go
	if sample.err != nil {
		return sample
	}

	sample.links, sample.err = p.nodeLinks(ctx, target, sampledInterfaceNames(sample))
```

then processSample(ctx, sample). If sample.err != nil after nodeLinks, processSample is still called with hasStates=false, includeStats... wait processSample would still process stats since it checks p.opts.includeStats and iterates sample.stats — but sample.stats were parsed. Hmm, wait: processSample does not check sample.err! Let me check the head. In the diff, processSample:

```go
func (p *interfacePoller) processSample(ctx context.Context, sample interfaceSample) {
	state := sample.target.state
	...
	if sample.hasStates {
		p.processStates(ctx, tracked, reported, sample)
	}
	...
}
```

No sample.err check. So if nodeLinks errored (sample.err set), the stats are still processed using `reported` from sample.links (nil) → only eth0 and lo get stats... Actually reported would be {eth0: "", lo: ""} since links is nil. So a no-shell node's stats would only cover eth0 and lo, dropping stats for the link interfaces if the clabwire listing failed. But more importantly, is there an err-handling in `round` that skips samples with err? Let me read the head file to confirm.

Also, a concern: if the clabwire listing fails, sample.err set, and the old behavior of "stats only" for no-shell nodes covering ALL interfaces (sample.stats includes pod's own interfaces like c9s0, c9ss*) — in new code stats are filtered to reported (eth0, lo, links). For a no-shell node, does clabwire listing succeed? The clabwire sidecar should work. But what if the exec into clabwireContainer fails because the pod is running but clabwire not ready? Then sample.err → processSample still emits stats for eth0/lo only. And the interface listing error is logged? Let me check.

Actually wait — there's a bigger issue: for a no-shell node, would clabwire --list-interfaces work? clabwire is the sidecar that manages packet capture; it knows about the topology. Probably works. But the docs say no-shell devices report stats only. The new code path requires the clabwire listing for the link stats to appear (alias lookup). If listing fails → sample.err set → stats loop uses reported={eth0, lo}. Silent partial loss. Need to check how errors are handled.

Let me now check `round`'s error handling in head.

11. **`aggregatedEventFromLabRuntimeEvent` — when `clab == nil` for a container event, attributes = nil → ev.Attributes merged. In parity test c9sInterfaceEvent passes clab=nil for interface events — fine. But for container events with clab==nil in production? streamLabRuntimeEvents passes `clab` which is non-nil in the events command. OK.

12. **`labRuntimeInterfaceAttributes` deletes "index" if Index <= 0 and "mtu" if MTU <= 0 — matches the old c9sIfaceStateEvent behavior (index>0, mtu>0). But the parity test `assertAttributeParity` compares docker vs c9s — docker has index and mtu. `TestInterfaceEventOmitsUnknownValues` checks omitted. But there's a question: docker events also include "state" and "alias" — in labRuntimeInterfaceAttributes, `attributes` from interfaceSnapshotAttributes always includes "state": snapshot.OperState and "type": snapshot.Type even when empty. interfaceSnapshotAttributes sets state and type unconditionally (from the netlink path). For c9s stats events without state (data.OperState="")... In `TestInterfaceEventOmitsUnknownValues`, the test checks that "state" is not reported when there's no value — got["state"] not in map? The test checks `for _, key := range []string{"index", "mtu", "state", "mac", "alias"}` — but labRuntimeInterfaceAttributes always sets "state" from iface.OperState! The test's event: InterfaceEventData{Name: "eth1", Type: "veth", Stats: {...}} — OperState is empty → attributes["state"] = "". So `got["state"]` would exist (with empty value) and the test would fail! Let me re-check:

```go
func TestInterfaceEventOmitsUnknownValues(t *testing.T) {
	...
	ev := c9sInterfaceEvent(state, clablabruntime.NodeState{Name: "client"}, "stats",
		clablabruntime.InterfaceEventData{
			Name: "eth1", Type: "veth",
			Stats: &clablabruntime.InterfaceStats{RxBytes: 1, Interval: time.Second},
		})
	got := mergedEventAttributes(ev)
	for _, key := range []string{"index", "mtu", "state", "mac", "alias"} {
		if _, ok := got[key]; ok {
			t.Fatalf("%s reported without a value: %v", key, got)
		}
	}
```

But `labRuntimeInterfaceAttributes` calls `interfaceSnapshotAttributes(ifaceSnapshot{... OperState: iface.OperState ...})` which sets `attributes["state"] = snapshot.OperState` unconditionally. iface.OperState is "" → attributes["state"] = "" exists. So the test would FAIL. Unless mergedEventAttributes drops empty values? Let me check mergedEventAttributes in core/events — probably it merges the event Attributes and the enrichment (e.g., id/name from actor). Does it drop empty attributes? The docker netlink path: interfaceAttributes sets state from snapshot.OperState unconditionally. For netlink snapshot, OperState is never empty. Hmm.

Wait, maybe the parity test intent: the c9s poller produces InterfaceEventData with empty OperState only in stats path `data.OperState = ""` (processSample stats loop: `data, ok := tracked.ifaces[stat.Name]; if !ok { data = interfaceEventData(...); data.OperState = "" }`). And labRuntimeInterfaceAttributes doesn't delete empty state. So the c9s stats event would report "state": ""? While docker stats events report state (from netlink). The parity test asserts c9s carries every docker attribute; docker has "state" so c9s having "state": "" passes parity. But `TestInterfaceEventOmitsUnknownValues` expects "state" to be absent. If attributes["state"] = "" always set, the test fails. So either the test is wrong, or there's something in the head code I haven't seen — maybe labRuntimeInterfaceAttributes deletes empty values. Let me read the head netlink.go to verify the actual code. From the diff, the new function:

```go
func labRuntimeInterfaceAttributes(
	lab, name string,
	iface *clablabruntime.InterfaceEventData,
) map[string]string {
	attributes := interfaceSnapshotAttributes(ifaceSnapshot{
		Index:     iface.Index,
		Name:      iface.Name,
		Alias:     iface.Alias,
		MTU:       iface.MTU,
		MAC:       iface.MAC,
		OperState: iface.OperState,
		Type:      iface.Type,
	})
	if iface.Index <= 0 {
		delete(attributes, "index")
	}
	if iface.MTU <= 0 {
		delete(attributes, "mtu")
	}
	...
```

interfaceSnapshotAttributes sets:
```go
	attributes := map[string]string{
		"ifname": snapshot.Name,
		"index":  strconv.Itoa(snapshot.Index),
		"mtu":    strconv.Itoa(snapshot.MTU),
		"state":  snapshot.OperState,
		"type":   snapshot.Type,
	}
	if snapshot.Alias != "" { attributes["alias"] = snapshot.Alias }
	if snapshot.MAC != "" { attributes["mac"] = snapshot.MAC }
```

So "state": "" exists. Test expects state absent → test failure. Unless mergedEventAttributes drops empty values. I must check mergedEventAttributes.

Let me look at core/events head files. Also "type": "veth" is set (Type: "veth" in test) — not in the omitted list. OK.

So this is a candidate: either the test fails (source-only review can spot compile-level/test-level contradictions) — need to verify mergedEventAttributes.

13. **`containerActionState` for `create`**: returns "created" but the docker action "create" in docker events → c9s state attribute "created". In the parity test, tt.state "created" for action create. OK.

For snapshot actions: `c9sContainerEvent(..., action, extra)`: `containerActionState(action, node.ContainerState)`. In `TestContainerSnapshotParity`, action is "running" (not a docker action) → falls through to snapshotState = node.ContainerState ("running"). OK.

14. **`containerTracker.observeNode` for `previous != nil && previous.pod == next.pod && previous.state == next.state`** — when a node's Health is unhealthy... containerTransitionActions handles health. In observeNode, `next.health = containerHealth(previous, next, node.Health)` — for non-running, health="". Then containerTransitionActions emits actions. Note: for the transition `previousState == created && next.state == exited` → "stop" — matches Docker. And health emit condition:

```go
	if next.state != running {
		return actions
	}
	started := len(actions) != 0 && actions[len(actions)-1] == containerActionStart
	if !started && previous != nil && previous.health == next.health {
		return actions
	}
	if next.health == starting && !started {
		return actions
	}
	return append(actions, healthPrefix+next.health)
```

Case: previous=running/healthy, next=running/starting (device boots? no — device went from ready to not ready in the same pod? containerHealth returns unhealthy if previous healthy and health==""). Hmm, next.health computed by containerHealth: health=="" → starting; if previous healthy and same pod → unhealthy. So next.health=unhealthy → emits "health_status: unhealthy". OK.

Case: previous=nil (new node) running/starting → actions=["create","start"], started → append health_status: starting. But wait: `if next.health == starting && !started { return }` — started is true, so falls to append. OK.

Case: previous running/starting, next running/starting → actions=[] (no change) → started=false → `!started && previous.health == next.health` → return []. Good.

Case: new node created, actions=["create"], next.state != running → return ["create"]. OK.

15. **`containerHealth` with previous==nil and health=="" → starting. But observeNode when node.ContainerState=="" → set to created. OK.

16. **Tracked node health for a stopped node: health="" and state exited. When the node starts again: previous.state=exited → containerHealth: next.state=running, health from node (may be "healthy" if Ready) → returns healthy → actions=["start"] → started → append health_status: healthy. Matches test.

17. **`labRuntimeContainerState`**: When node.ContainerState=="" (a lab runtime that reports no container state, like other lab runtimes? only c9s exists). `if node.State == "" { return state.State, "" }` — for node.State="notready" → return "notready","notready". Hmm, and `if node.Ready { return running, healthy }`. But what if node.Ready is true and node.ContainerState==""? Then returns running/healthy. But wait — the first switch: if node.ContainerState is a non-empty unknown value (e.g., "notready")? falls through to node.Ready check. Fine.

Actually there's an inconsistency: for a node with ContainerState=="" but node.State="ready" (a lab runtime reporting only readiness) and Ready=true → running/healthy. OK.

18. **`containerFromLabNode`**: `nodeType, group := node.Type, node.Group; if topologyNodeConfig, ok := c.Nodes[topologyNode]; ok { nodeType, group = cfg.NodeType, cfg.Group } else if c.Config.Topology != nil && group == "" { group = c.Config.Topology.GetNodeGroup(topologyNode) }`. Hmm — but what about nodeType when the topology node config doesn't exist (read by --name) and the kind's default type? The docs say "with `-t` also a kind's default type; read by `--name` alone, a default type such as SR Linux's `ixr-d2l` is not known." But the code prefers node.Type over the topology config? No wait: `if topologyNodeConfig, ok := c.Nodes[topologyNode]; ok { nodeType, group = ...cfg... }` — this overrides node.Type with the local config's NodeType. If the local config node has NodeType=="" (linux), nodeType becomes "" → label not set. But node.Type (from the runtime) was set (c9s reports spec.type). So a node with spec.type set in the cluster AND loaded topology config with empty NodeType → type label dropped. Hmm: c9s sets spec.type only when the topology sets it, and the local config would have the same NodeType when loaded. When loaded by --name, c.Nodes is empty... wait `c.Nodes[topologyNode]` — how does c.Nodes get populated when read by --name? Let me check how the byName lab works: `NewContainerLab(WithLabNameOnly("parity"))` — probably c.Nodes is empty and c.Config.Topology is nil. So `c.Nodes[topologyNode]` fails → else branch: `c.Config.Topology != nil && group == ""` → Topology nil → nothing. So labels have kind from node.Kind, type from node.Type. Good.

But consider a real scenario: read by -t (topology loaded): c.Nodes has the topology node with cfg.NodeType possibly "" and cfg.Group possibly "". If c9s node.Type is set (spec.type from the topology) and the local config's NodeType is also set (same) → equal. But if c9s spec.type is set and the local config's NodeType is "" → type dropped (overridden by the config's empty). Can spec.type be set while local NodeType is ""? c9s sets spec.type from the topology's type; local cfg.NodeType is also from the same topology → both set or both empty... unless the local topology was changed after deploy (redeploy from another file). Edge case; the topo file label helps. Minor.

Also: `else if c.Config.Topology != nil && group == "" { group = c.Config.Topology.GetNodeGroup(topologyNode) }` — but nodeType from config overrides the runtime's node.Type even when the config type is empty. That drops node.Type when the config exists. Wait no: `if topologyNodeConfig, ok := c.Nodes[topologyNode]; ok { nodeType, group = cfg.NodeType, cfg.Group }` — unconditional override. Consider a node whose runtime type is set but the local topology config has the node with a different kind mapping... The docs table says type is reported "when the topology sets them". Given the runtime's spec.type only comes from the topology too, this is consistent-ish. But hmm — what about kinds with a default type: the local cfg.NodeType would be set (e.g., ixr-d2l) — reported. Fine.

Wait, actually there's a subtle issue: what if the c9s node.Type is set but the local config node's NodeType is empty AND the runtime Type set? The override drops it. E.g., node kind mapped with no default type, topology sets type: "custom-type" → both set. OK consistent. When would spec.type be set but local empty? If the topology was edited between deploy and events read. Minor.

19. **`topologyNodeName`**: `if c.Config.Topology != nil { topologyNode = c.topologyNodeName(topologyNode) }` — maps the sanitized runtime name back to the topology-spelled name. And `if node.TopologyName != "" { topologyNode = node.TopologyName }` before. Need to check c.topologyNodeName semantics (does it return input if not found?).

20. **`state.go stateFromNodeResources`**: uses the first node's topology-file annotation. If Nodes from different files (redeploy from another file without Topology CR carries over per Node), the first annotation wins arbitrarily. Acceptable.

21. **`newestPod` and the `labelOriginalNodeName`** — `labelOriginalNodeName` referenced in test — is it defined in head? grep needed.

22. **`enrichState`**: `node.ContainerState = nodeContainerState(stopRequested, podsByNode[primary])` — podsByNode[primary] (the primary of the group) — fine.

`if node.ContainerState == running { node.Health = nodeHealth(node, resourcesByName[nodeName]) }`.

23. **Docker parity of state attribute for the `create` action**: state created. In c9sContainerEvent, attributes["state"] = containerActionState(action, node.ContainerState). For action create → "created". In the parity test, tt.state for create is "created". OK.

For "die" → exited. For "kill" → running. For "health_status: healthy" → running. For "start" → running. Matches docker semantics. In the parity test, want["state"] = tt.state. OK.

24. **`c9sContainerEvent` copies node (`nodeCopy := node`) — good, avoids shared pointer mutation. But `Lab: state` shares the state pointer across events. The events command reads ev.Lab synchronously; multiple events share state. If a consumer mutates, race. Probably fine.

25. **iface_stats emit for stats when `tracked.ifaces` has data with stats**: `data.Stats = c9sIfaceStatsData(previous, current); p.emit(...)` — but data is a value copy of tracked.ifaces[stat.Name]; Stats set on the copy — but the tracked map entry is NOT updated with Stats, so subsequent processStates comparisons `previous == data` compare structs including Stats pointer — wait, processStates:

```go
	previous, seen := tracked.ifaces[iface.Name]
	tracked.ifaces[iface.Name] = data
```

data comes fresh from interfaceEventData (Stats nil). previous from tracked.ifaces — set in processStates with Stats nil. So equality fine.

But in the stats loop, `data, ok := tracked.ifaces[stat.Name]; if !ok { data = interfaceEventData(...); data.OperState = "" }` — then `data.Stats = ...` — wait, but this happens AFTER processStates (processStates runs before stats loop). Hmm, but there's a subtle ordering: processStates emits create/update events with data WITHOUT Stats; the stats loop emits stats events. Note: processStates sets tracked.ifaces[stat.Name] = data for present interfaces. For the stats loop, `data, ok := tracked.ifaces[stat.Name]` — if the stat is for an interface present in states, ok. If it's a stats-only interface (no-shell: hasStates false, tracked.ifaces empty) → `!ok` → data = interfaceEventData(c9sIfaceState{Name: stat.Name}, alias); data.OperState = "".

But wait — for stats of an interface where `!ok` (e.g., an interface not present in states because hasStates false), the alias comes from reported[stat.Name]. In the no-shell case reported = links from nodeLinks; OK.

One bug candidate: For an interface with states (hasStates true) but no stats (not in sample.stats)... fine.

Another: For a stats interface that is present in tracked.ifaces from processStates, `data.OperState` non-empty — good.

But consider: hasStates true, sample.stats for an interface present in states → data has OperState — good. For the case where a state interface is missing from tracked.ifaces but hasStates — impossible.

Now, the "state" in stats events for interfaces whose sample lacked states: `data.OperState = ""` → c9s stats event has Interface.OperState="" → labRuntimeInterfaceAttributes sets attributes["state"]="" always. Docker stats events always have state. Parity holds. But TestInterfaceEventOmitsUnknownValues expects state absent → need mergedEventAttributes semantics. Let me check.

26. **`sampledInterfaceNames` + `nodeLinks` caching: the listing cache keyed on the pod and re-listed when interface names change. But the listing can change WITHOUT the interface names changing (e.g., clabwire adds an alias for a link while the device's interface set is unchanged? A pod gets its link interfaces as clabwire wires them — when clabwire wires a new link, the device's sysfs sees a new interface → names change → re-list. When clabwire realizes the alias (clabwire sets ifalias in the device) without adding an interface — can that happen? The alias is set when the interface is created. Probably fine.

But there's a race: two nodes of the same pod (network-mode container) — `listing.byNode[entry.Node]` — clabwire lists per node. OK.

27. **`forgetListings` uses the poller's mutex; listings dropped when pods gone. OK.

28. **`retireStoppedNodes` iterates `p.nodes` and emits delete — then `p.forgetStats(tracked, name)`. It deletes p.nodes entries. But `processSample` for a stopped node in the SAME round: the sample comes only for running nodes. OK.

29. **`nodeLinks` may call listPodInterfaces with the poller's ctx; on error, sample.err set. But `round` processes sample regardless? Check head.

30. **In `processStates`, when `!seen && p.firstRound && p.opts.includeInitialState` → emit snapshot. But for a node that appears later (after firstRound), `!seen` → create. And when the node is not sampled (stopped) → retire → delete. OK.

But consider: firstRound with includeInitialState=false: `case !seen && p.firstRound:` matches → if includeInitialState emit snapshot; else nothing. Then tracked.ifaces records. Good.

But wait — there's a subtle change from the original: originally `case !seen && p.firstRound && !p.opts.includeInitialState: continue` — did NOT record? No — the original recorded `tracked.ifaces[iface.Name] = trackedIface{...}` before the switch. Same.

31. **The delete event for the management interface when a node stops: retireStoppedNodes emits delete for all tracked ifaces including eth0/lo. Docker netlink events for a stopped container — the netlink registry would report the interface removal too. Parity test: TestInterfaceEventParity — retireStoppedNodes emits delete for eth1, eth0, lo. Matches.

32. **capture_interfaces.go InspectInterfaces**:

```go
		sampled, hasStates := states[location.NodeName]
		for name, alias := range reportedInterfaces(listed[location.NodeName]) {
			state, ok := sampled[name]
			if !ok {
				if hasStates || (name == managementInterface || name == loopbackInterface) {
					continue
				}
				state = c9sIfaceState{Name: name}
			}
			data := interfaceEventData(state, alias)
			details := &clabtypes.ContainerInterfaceDetails{
				InterfaceName:  data.Name,
				InterfaceAlias: data.Alias,
				InterfaceType:  data.Type,
				InterfaceMAC:   data.MAC,
				InterfaceIndex: data.Index,
				InterfaceMTU:   data.MTU,
			}
			if ok {
				details.InterfaceState = data.OperState
			}
			container.Interfaces = append(container.Interfaces, details)
		}
```

So: an interface reported in the clabwire listing but not in the sysfs states: if the node HAS states (device container has a shell), skip the interface (not present in the node). If the node has NO states, include the link interfaces without sysfs attributes. eth0/lo without states are skipped. Good.

But `state = c9sIfaceState{Name: name}` → interfaceEventData with OperState "" → netlinkOperState("") = "unknown"! For a no-shell node's link interface, the details have InterfaceState unset (since ok==false) — good, but data.OperState would be "unknown" — only used for InterfaceState which is skipped. OK.

Hmm wait, there's a subtle bug: `if ok { details.InterfaceState = data.OperState }` — for interfaces WITH sysfs state. Good.

But another: for eth0/lo when hasStates but not in states → skip. Good.

Test: `TestInspectInterfacesReportsStateFromSysfs` — clabwire listing gives e1-1 and e1-2; states has lo, c9s0, eth0, c9ss1, e1-1, e1-2. reported = {lo:"", eth0:"", e1-1:"ethernet-1/1", e1-2:""}. 4 interfaces. e1-1 state "up", e1-2 "lower-layer-down" — netlinkOperState("lowerlayerdown") = "lower-layer-down". Good. lo device, mac "" (zeroMAC → ""). Good.

Now, wait: the sysfs sample in the test has "eth0" with alias "c9s:interposition:v1" — reported alias for eth0 is "" → `interfaceEventData(iface, "")`: alias=="" and iface.Alias starts with "c9s:" → alias stays "". MAC "3a:3b:86:d8:73:37". Good.

33. **Docker parity for inspect interfaces**: docker inspect interfaces include alias? ContainerInterfaceDetails fields include ifindex, mtu, mac, state, alias, type. Good.

34. **capture.go listPodInterfaces refactor — same behavior. Fine. Note `capture.go` no longer uses `exec := r.execInPodContainer()`; but execInPodContainer called per-pod inside listPodInterfaces — need to confirm execInPodContainer() creates no heavy state per call. It was called once before; now once per pod. If it constructs a closure over the client, cheap. Check.

35. **events.go: `errs := make(chan error, 4)` — 4 goroutines write errors: trackContainers (sendEventError), pollInterfaces? (does pollInterfaces write errs? It writes log only), watchTopologies, watchNodes, watchPods. Actually watchNodes/watchPods/watchTopologies → 3, plus trackContainers → 4. But forwardTopologyWatch's eventSink is `events`, errSink is errs. pollInterfaces doesn't use errs (log only). OK.

But wait: `watchNodes` — errors forwarded with sendEventError; errs buffer 4. If all watches fail fast repeatedly, sendEventError is non-blocking (buffer). OK.

36. **Potential goroutine leak in StreamEvents**: trackContainers returns when labStates fails → errs gets error. The watch goroutines keep sendChangedLab; blocked when buffer full until ctx done. ctx is the stream's context. Events command cancels ctx when done. Acceptable-ish but note: trackContainers also returns when ctx done. Fine.

But there's a subtle issue: `trackContainers` calls `r.labStates(ctx, scope)` ONCE at startup and then relies on watches for changes. The watches: watchTopologies, watchNodes, watchPods each have reconnect loops with pollInterval. If a watch fails to establish (k8s unavailable), sendEventError → errs. The events command prints errors? Let me check stream.go handling of runtimeErrs — need to read head.

37. **`arm` function subtle bug**: 

```go
	pending := map[labRef]bool{}
	timer := time.NewTimer(time.Hour)
	timer.Stop()
	defer timer.Stop()
	armed := false
	arm := func(delay time.Duration) {
		if !armed {
			timer.Reset(delay)
			armed = true
		}
	}
```

But there's a bug: after the timer fires and is consumed, `armed = false`. But the timer's channel is drained by the select. Next `arm` → Reset on a stopped timer with drained channel — allowed. OK.

Hmm, but there's one more path: `case <-timer.C: armed = false; ...` — then in the same iteration, for refs that failed refresh, pending re-armed. Fine.

Another subtlety: `arm(containerRefreshDelay)` — 200ms debounce. But if a `ref` arrives exactly when the timer is about to fire, the batch may exclude the newest ref — no: pending[ref] set before arm; arm does nothing since armed. The timer fires, consumes pending — all refs included. Good.

38. **`refresh` when `state == nil` (notFound)**: `t.observeLab(ctx, ref, nil, nil)` — removes all nodes of the lab with removal actions, then `delete(t.nodes, key)`. Wait — observeLab: `seen := map[string]bool{}` (state nil → empty); `for key, tracked := range t.nodes { if tracked.ref != ref || seen[key] { continue }; for _, action := range containerRemovalActions(tracked) { t.emit(ctx, tracked.lab, tracked.node, action, nil) }; delete(t.nodes, key) }`. Good.

But note: when a lab is gone but later comes back (redeploy), the watch sends the lab ref → refresh reads it → nodes observed again → previous==nil → create/start. Good.

39. **`c9sNodeKey(state.Namespace, state.Name, state.Nodes[idx].Name)` vs `key := c9sNodeKey(...)` in observeNode — consistent.

40. **In observeLab, `key := c9sNodeKey(state.Namespace, state.Name, state.Nodes[idx].Name)` — fine.

41. **`tracker` uses `t.r.Inspect(ctx, clablabruntime.InspectRequest{Name: ref.lab, Namespace: ref.namespace})` — need Inspect to return labNotFoundError. Check Inspect semantics.

42. **Docker parity for the `stop` action: c9s emits kill, stop, die with state running/exited/exited. Docker: kill (state running), stop (running in Docker? Docker's stop action carries the exit code? Docker events: kill → signal; stop → ?; die → exitCode). The state attribute is a c9s addition on top ("c9s reports it on every container event" per docs). The parity test only checks c9s attrs ⊇ docker attrs (docker attrs don't include "state"). But the test's `want` map checks got["state"]==tt.state for each action: stop → "exited" (from containerActionState). Matches tt.state. OK.

43. **`labRuntimeContainerState` for `ContainerStateCreated` → status "Created"; for running without healthy → "health: starting". The parity test's TestContainerStateUsesDockerVocabulary covers.

44. **`managementAddress(node)`**: sets NetworkSettings from MgmtIPv4Address. Check semantics (CIDR parse).

45. **Docker event parity for `mgmt_ipv4` format**: dockerContainerEvent enrichment produces mgmt_ipv4 from GetContainerIPv4 (e.g., "172.20.20.2/24"). c9s: from MgmtIPv4Address "172.20.20.84/24" → managementAddress parses CIDR? Let me check `managementAddress`. If it stores the address as-is and GetContainerIPv4 returns "172.20.20.84/24" → matches.

46. **In `containerFromLabNode`, `Names: []string{nodeName}` where nodeName = state.Name-node.Name. But `labels[clabconstants.LongName] = nodeName` — c9s LongName "lab1-r1" vs docker LongName "parity-client"? In the parity test, docker lab: `cfg := c.Nodes[node].Config()` → LongName "parity-client". c9s: "parity-" + node. Both match.

47. **`containerFromLabNode` labels: `clabconstants.NodeName: topologyNode` — uses the topology-spelled name. Docker labels have NodeName as the topology spells it. Good.

But `labRuntimeContainerID` — where is the container ID used? `Workload.NodeUID`. The parity test checks got["id"] = "c9s-parity/parity/" + node — that's mergedEventAttributes enrichment from ActorID. OK.

48. **`clab-topo-file` label**: `clabconstants.TopoFile: labRuntimeTopologyPath(c, state)` — check labRuntimeTopologyPath: uses state.TopologyPath when set? The docs say events report `clab-topo-file` as the recorded file. In TestDeployRecordsTheTopologyFile, state.TopologyPath = the file → labRuntimeTopologyPath(c, state) should return it. Check the helper: from the base code, `labRuntimeTopologyPath(c, state)` — need to read.

49. **Manifests: removeTopologySourceFile from all objects and the topology — and `primitiveObject` removes from non-Node kinds. But `compilePrimitiveResources` — the Topology itself is `prepared.topology`, and removeTopologySourceFile(prepared.topology) is called in Manifests. But what about `prepareDesiredDeployment` for the actual Deploy (not Manifests)? setTopologySourceFile(desiredTopology, req.TopologyFile) records it on the Topology; primitiveObject removes it from non-Node kinds. So the actual deploy's Node objects carry the annotation (desired), and the Topology carries it. But wait — for a deploy WITH a Topology CR, do Node objects still carry the annotation? The docs say "with `--no-topology-cr`, on every `Node`" — implying with a Topology CR, only the Topology carries it. But primitiveObject removes the annotation from non-Node kinds regardless — meaning with a Topology CR, the Nodes also carry the annotation (since primitiveObject only removes from non-Node kinds). The docs statement "with `--no-topology-cr`, on every `Node`" describes which records it; but with a Topology CR, the Nodes ALSO get the annotation (they just aren't the authoritative one per docs). Hmm — actually `carryOverNodeTopologyFile` says a Node keeps the file from its creation. With a Topology CR, a Node's annotation would remain stale after a redeploy from another file — the docs say inspect/events use the Topology's file when a Topology exists (stateFromTopology). When the Topology is gone but the Nodes remain (destroyed Topology? No, destroy removes everything). OK.

But there's a subtle bug candidate: `carryOverNodeTopologyFile` carries over from existing; for a Node created before this feature (no annotation), `removeTopologySourceFile(updated)` removes the desired annotation — matching the test. Good.

But: does clabernetes copy the Node annotations into the pod template? That's the doc's claim, not code. Fine.

50. **`setTopologySourceFile` in plan.go: `prepareDesiredDeployment` sets the file on the desired topology; then `Plan` computes changes — would the annotation change count as drift for the Topology when the file changed? `reconciledPrimitiveObject(topology, newTopology)` — mergeDesiredMetadata keeps desired annotations — a Topology change from another file updates the annotation → plan reports the Topology changed. Is that a false positive in plan? The Topology resource would genuinely change (annotation), so plan says the Topology needs an update — but the pod template doesn't include Topology annotations... hmm, actually clabernetes copies the Topology's spec into the pod template, not annotations. So an annotation-only change would trigger a controller update of the Topology only, not pods. Fine.

But TestDeployRecordsTheTopologyFile: "a deploy from another file would change Node and replace its pod" — for the no-topology-cr case, the Node annotation carries over so no change. And for the with-topology case, the Topology always records the latest file (carry-over only guards Nodes). But wait — with a Topology CR, do Nodes also get the desired annotation? Yes (primitiveObject doesn't remove from Node). And carryOverNodeTopologyFile keeps the Node's existing annotation → no pod change. Consistent.

51. **`stateFromTopology` with annotation. `labTopologyPath(obj.GetAnnotations(), fallback)`.

52. **`stateFromNodeResources`: iterates nodeResources for the first non-empty annotation. But `nodeExposedPorts`, `labelOriginalNodeName` (TopologyName). OK.

53. **`nodeStateFromResource`**: `if original := nodeResource.GetLabels()[labelOriginalNodeName]; original != node.Name { node.TopologyName = original }`. Where is labelOriginalNodeName defined? Presumably in head. Check.

54. **`enrichState` pod UID check**: `if uid := pods.Items[idx].Annotations[annotationDirectNodeUID]; uid != ""` — annotationDirectNodeUID = "c9s.run/direct-node-uid". Is this a real clabernetes annotation or made up? It's set in... does the c9s controller set pod annotations with the direct node UID? If the controller doesn't set it, the check is inert (uid==""). But the test sets it via withNodeUID. Is this annotation set by the c9s controller (out of scope of this repo)? The comment in clabernetes.go: "annotationDirectNodeUID names the UID of the Node a c9s pod runs." If the real controller sets a different annotation name or none, the code silently ignores. This is a contract with clabernetes. Hmm — maybe the code SETS this annotation on the pod template in the topology compile. Let me grep for direct-node-uid in the head code. If it's set nowhere, the test is asserting behavior of an external component — worth flagging? Let me grep.

55. **robot tests**: `Container Actions Should Include In Order` uses a regex trick with re.search on joined actions — actions could contain health_status: starting etc. The pattern joins with re.escape of each action and `\\n(?:.*\\n)*?` between. Since actions are joined with "\\n" and the file has "\\n" separators — fine.

56. **`Interface Event Should Be Logged` with @{states} — `e.get("attributes", {}).get("state") in $states` — Robot converts @{states} to list. OK.

57. **The docs parity table: `mgmt_ipv4` regexp in the robot test.

Now let me also check:

58. **core/events/parity_test.go — `parityLab` uses `t.Setenv("USER","alice")` and `t.Setenv("SUDO_USER","")`. Tests not parallel; fine.

`dockerContainerEvent` calls `clabutils.DockerMessageToEventData` — existing util. And `aggregatedEventFromContainerEvent(context.Background(), &fakeDockerRuntime{container: container}, clabruntime.ContainerEvent{...})`. Check `aggregatedEventFromContainerEvent` signature in head — (ctx, runtime, event) where runtime is a ContainerRuntime interface — the fake embeds clabruntime.ContainerRuntime and implements ListContainers. OK.

`byName, err := clabcore.NewContainerLab(clabcore.WithLabNameOnly("parity"))` — check that WithLabNameOnly exists.

59. **`aggregatedEventFromLabRuntimeEvent(clab, ev)` when ev.Type==container but clab==nil → attributes nil → ev.Attributes. In the interface case, `lab := ev.Attributes["lab"]; if ev.Lab != nil { lab = ev.Lab.Name }; attributes = labRuntimeInterfaceAttributes(lab, ev.ActorName, ev.Interface)`. Then merge ev.Attributes on top: namespace, lab, node, pod, origin. Wait — labRuntimeInterfaceAttributes sets attributes["lab"]=lab and attributes["name"]=name (if non-empty). Then merge sets attributes["lab"] = ev.Attributes["lab"] — same. But in the parity test c9sInterfaceEvent: ActorName = state.Name + "-" + node.Name = "lab1-r1"; Attributes lab = state.Name. And the test asserts got["name"] == "parity-"+tt.node, got["lab"] == "parity", got["id"] == "c9s-parity/parity/"+tt.node — where id comes from... mergedEventAttributes adds "id" from ActorID? The test passes ev.ActorID: key = "c9s-parity/parity/" + node. mergedEventAttributes presumably adds id=ActorID when missing? For docker interface events: ActorID = container.ShortID, and mergedEventAttributes... hmm, docker interface event's merged attrs: id? The parity test skips comparing "id", "name", "lab", "origin". OK.

But `mergedEventAttributes(ev)` — need to read to see how "id"/"name" are added. If merged adds "id" from ActorFullID... For c9s interface: ActorFullID=key → id=key. For c9s container: id=key. Test expects id "c9s-parity/parity/"+node. OK.

60. **Now — the question of whether the c9s container event carries `state` while the docker snapshot event (`aggregatedEventFromContainerSnapshot`) also carries state (attributes["state"] = state when != ""). TestContainerSnapshotParity: got["state"]=="running". OK.

And the docker snapshot doesn't have "origin"=="snapshot"? It does (attributes["origin"]="snapshot"). The c9s snapshot event's merged attrs: origin comes from ev.Attributes (EventOriginSnapshot="snapshot") merged last. Test checks got["origin"]=="snapshot". OK.

61. **`containerAttributes` new helper sets image, mgmt_ipv4, mgmt_ipv6, ports, labels — and in the snapshot path, `aggregatedEventFromContainerSnapshot` previously added image/mgmt/ports AFTER labels; now containerAttributes does. But the snapshot path previously did NOT set "state" from... it sets attributes["state"]=state if state != "". The c9s container event via LabRuntimeContainer → containerAttributes merges labels — including `clabconstants.TopoFile` etc. Then ev.Attributes merged last: namespace, lab, node, pod, state, origin, signal.

But hold on — in the non-snapshot path, `attributes = containerAttributes(&container)` — the container's labels include `clabconstants.TopoFile` = labRuntimeTopologyPath(c, state). The docker path's enrichment: for a real Docker event, the labels carry `clab-topo-file`. The parity test's dockerContainer sets labels from cfg.Labels plus NodeMgmtNetBr. cfg.Labels include TopoFile? The docker lab was loaded with the topo file; cfg.Labels include clab-topo-file. Test want checks `clabconstants.TopoFile: path` in c9s. And parity: docker has TopoFile in labels. Good.

62. **TestContainerEventParity byName mode**: `byName, err := clabcore.NewContainerLab(clabcore.WithLabNameOnly("parity"))` — does the byName lab set Owner? c9s state.Owner = "alice" → labels[Owner] = state.Owner. The byName lab's enrichment: `aggregatedEventFromContainerEvent`... wait, for the c9s path, clab=byName. `containerFromLabNode(byNameState, node)` — labels[Owner] = state.Owner = "alice". The test want checks Owner "alice". OK.

But in byName mode, does the c9s event carry `clabconstants.NodeKind`? labels[NodeKind] = node.Kind if != "". nodeState.Kind = cfg.Kind from the docker lab (loaded with topology). Yes, c9sNode passes Kind: cfg.Kind. Good.

In byName mode the want map still checks NodeKind from dockerLab.Nodes[node].Config().Kind — c9s labels have node.Kind. Good.

And `byName`'s topologyNodeName: c.Config.Topology nil → skip. And `c.Nodes[topologyNode]` — the byName lab: are c.Nodes populated? If populated from... WithLabNameOnly doesn't load a topology. But `c.Nodes[topologyNode]` — in byName mode, does the code require Nodes? `if c.Config.Topology != nil { topologyNode = c.topologyNodeName(topologyNode) }` — skip. `if c.Nodes[topologyNode]` — not found → else branch requires Topology. OK.

But `labRuntimeTopologyPath(c, state)` — for byName, need it to return state.TopologyPath (the test's path). Check.

63. **Potential nil map issue in containerFromLabNode: `labels[clabconstants.NodeKind]` etc — fine. But `c.Nodes[topologyNode]` — c.Nodes is `map[string]Node`? If c.Nodes nil (not initialized), indexing a nil map is fine in Go (returns zero). OK.

64. **`labRuntimeContainerState(state, node)` when node.ContainerState=="running" but Health=="" → status "health: starting". Docker running without healthcheck has status "Up 19 seconds" and the events enrichment adds status from container.Status ("Up 19 seconds"). The c9s status "healthy"/"health: starting" differs from Docker's status format — but the parity test only asserts c9s carries docker's attrs. For docker, container.Status = "Up 19 seconds" → status attr. c9s: LabRuntimeContainer sets Status via labRuntimeContainerState ("healthy") → containerAttributes does NOT set status (only snapshot path does). So c9s container events (non-snapshot) lack "status" while docker events have it? Hmm: `aggregatedEventFromLabRuntimeEvent` non-snapshot path: attributes = containerAttributes(&container) — no status. Docker event: status in enrichment? Let me check `aggregatedEventFromContainerEvent` — does it add "status"? Actually Docker events carry the status in... the events command's docker conversion — the Docker event attributes come from Docker's event actor attributes (not Status). Docker events actor attributes don't include "status" (they include image, name, container labels). The enrichment adds... mgmt ips and ports? Let me check aggregatedEventFromContainerEvent in head. If docker events don't carry status, then parity is fine, and the c9s status is c9s-only (docs say c9s reports state on every event; status only for snapshot). The docs table (runtime.md) says status = "healthy once the node is ready..." under the inspect section — inspect's status. For events, only snapshot has status? The docs' container-events example shows attributes without "status". OK consistent.

Hmm wait, but the snapshot event: c9s snapshot action "running" → containerActionState(action="running", snapshotState=node.ContainerState="running") → "running". And attributes from aggregatedEventFromContainerSnapshot include status (container.Status="healthy"). Test checks got["status"]=="healthy". Good.

65. **Docker parity in the snapshot test: docker snapshot's merged attrs include "state" (running) — c9s merged attrs include state (from ev.Attributes). Good. And "status" — docker snapshot has status "Up 19 seconds"; c9s has "healthy". assertAttributeParity only checks keys presence, not values. OK.

66. **Now the big one — `mergedEventAttributes`**: need to read. Let me read core/events files.

Let me read the head files now. Priority reads:
- core/events/stream.go (aggregatedEventFromLabRuntimeEvent, mergedEventAttributes, containerAttributes, aggregatedEventFromContainerSnapshot, aggregatedEventFromContainerEvent, streamLabRuntimeEvents, labRuntimeEventStreamRequest)
- core/events/netlink.go (labRuntimeInterfaceAttributes, interfaceAttributes, emitInterfaceStatsEvent)
- core/labruntime.go (containerFromLabNode, LabRuntimeContainer, labRuntimeContainerState, labRuntimePorts, labRuntimeTopologyPath, topologyNodeName, managementAddress)
- labruntime/clabernetes/events.go (watchPods etc.)
- labruntime/clabernetes/iface_stats.go (round error handling, sample, processSample)
- labruntime/clabernetes/capture_interfaces.go
- labruntime/clabernetes/state.go (enrichState)
- labruntime/clabernetes/topology.go, reconcile.go, manifests.go, plan.go, primitives.go
- labruntime/runtime.go
- core/labruntime_gaps_test.go
- labruntime/clabernetes/container_events.go (head — matches diff)
- labruntime/clabernetes/clabernetes_test.go (head)
- labruntime/clabernetes/event_parity_test.go (head)
- docs
- tests robot

Let me grep/read. First: mergedEventAttributes.
The diff is fully ingested. Now let me read the head files, starting with the core events code that the parity tests exercise.
grep · completed

Input

{
  "pattern": "true",
  "path": "/source/head"
}

Output

Found 100 matches (more matches available)
/source/head/tests/01-smoke/10-internal-ca.clab.yml:
  Line 15:       issue: true

  Line 22:         issue: true

  Line 28:         issue: true


/source/head/tests/01-smoke/31-apply-network-mode.vars.drift-w1.yml:
  Line 1: driftW1: true

  Line 2: addSidecar1: true


/source/head/tests/01-smoke/29-apply.vars.deploy-drift.yml:
  Line 4: deployDrift: true


/source/head/tests/01-smoke/31-apply-network-mode.vars.link-restart.yml:
  Line 1: driftW1: true

  Line 2: addSidecar1: true

  Line 3: addTogether: true

  Line 5: addLink: true


/source/head/tests/01-smoke/30-bridge-reconcile.vars.remap.yml:
  Line 1: remap: true


/source/head/tests/01-smoke/29-apply.vars.add-link.yml:
  Line 1: addLink: true


/source/head/tests/01-smoke/31-apply-network-mode.vars.remove-w2.yml:
  Line 1: driftW1: true

  Line 2: addSidecar1: true

  Line 3: addTogether: true

  Line 4: removeW2: true


/source/head/tests/01-smoke/29-apply.vars.add-special-links.yml:
  Line 2: addSpecialLinks: true


/source/head/tests/01-smoke/29-apply.vars.add-node.yml:
  Line 3: addNode: true


/source/head/tests/01-smoke/31-apply-network-mode.vars.link-recreate.yml:
  Line 1: driftW1: true

  Line 2: addSidecar1: true

  Line 3: addTogether: true

  Line 5: addLink: true


/source/head/tests/01-smoke/09-external-ca.clab.yml:
  Line 18:         issue: true


/source/head/tests/01-smoke/23-tools-gotty.robot:
  Line 67:     ...    ${runtime} ps -a | grep ${gotty_container} || true


/source/head/tests/01-smoke/30-bridge-reconcile.vars.no-bridge.yml:
  Line 1: remap: true

  Line 2: noBridge: true


/source/head/tests/01-smoke/31-apply-network-mode.vars.add-together.yml:
  Line 1: driftW1: true

  Line 2: addSidecar1: true

  Line 3: addTogether: true


/source/head/tests/01-smoke/01-basic-flow.robot:
  Line 227:     Should Contain    ${field_check[1]}    true


/source/head/tests/01-smoke/21-tools-sshx.robot:
  Line 69:     ...    ${runtime} ps -a | grep ${sshx_container} || true


/source/head/tests/01-smoke/22-tools-api-server.robot:
  Line 89:     ...    ${runtime} ps -a | grep ${api_server_name} || true


/source/head/tests/01-smoke/31-apply-network-mode.vars.add-sidecar1.yml:
  Line 2: addSidecar1: true


/source/head/tests/08-vxlan/03-tools-veth-vxlan.robot:
  Line 121:     # CI env var is set to true in Github Actions

  Line 142:     # CI env var is set to true in Github Actions

  Line 157:     ...    sudo ip link add ${vxlan-br} type bridge || true

  Line 161:     ...    sudo ip link set dev ${vxlan-br} up && sleep 2 && sudo ip link set dev ${vxlan-br} mtu 9100 && sudo ip addr add ${vxlan-br-ip} dev ${vxlan-br} || true


/source/head/tests/08-vxlan/01-vxlan.robot:
  Line 47:     # CI env var is set to true in Github Actions

  Line 81:     ...    sudo ip link add ${vxlan-br} type bridge || true

  Line 83:     ...    sudo ip link set dev ${vxlan-br} up && sudo ip link set dev ${vxlan-br} mtu 9100 && sudo ip addr add ${vxlan-br-ip} dev ${vxlan-br} || true


/source/head/tests/08-vxlan/02-vxlan-stitch.robot:
  Line 117:     ...    sudo ip link add ${vxlan-br} type bridge || true

  Line 119:     ...    sudo ip link set dev ${vxlan-br} up && sudo ip link set dev ${vxlan-br} mtu 9100 && sudo ip addr add ${vxlan-br-ip} dev ${vxlan-br} || true


/source/head/tests/14-basic-frr/01-frr.robot:
  Line 80:     Set Environment Variable    FRR_ENFORCE_STARTUP_CONFIG    true


/source/head/tests/15-mgmt/09-multi-mgmt.clab.yml:
  Line 14:     macvlan-aux: true


/source/head/tests/15-mgmt/10-multi-mgmt-apply.vars.dropped.yml:
  Line 3: dropOob: true


/source/head/tests/15-mgmt/14-skip-when-unused.clab.yml:
  Line 9:     skip-when-unused: true


/source/head/tests/15-mgmt/mgmt.resource:
  Line 60:     ...    { sudo iptables-save 2>/dev/null; sudo nft list ruleset 2>/dev/null; } | grep '${bridge}' | grep -ci 'set by containerlab' || true


/source/head/tests/15-mgmt/06-macvlan-mgmt.clab.yml:
  Line 7:   macvlan-aux: true


/source/head/tests/15-mgmt/10-multi-mgmt-apply.vars.added.yml:
  Line 2: addNetwork: true


/source/head/tests/09-download/01-download.robot:
  Line 43:     Run    sudo docker run -d --name=${sshpwservername} -e USER_NAME=user -e PASSWORD_ACCESS=true -e USER_PASSWORD=${ssh_password} --restart unless-stopped lscr.io/linuxserver/openssh-server:latest


/source/head/tests/13-srsim/11-srsim-apply.robot:
  Line 94:     Should Be Equal As Strings    ${output}    true\ntrue


/source/head/tests/13-srsim/07-srsim-mix.clab.yml:
  Line 17:         issue: true

  Line 41:         /configure router "Base" isis 0 advertise-passive-only true

  Line 44:         /configure router "Base" isis 0 interface "system" passive true

  Line 98:         /configure router "Base" isis 0 advertise-passive-only true

  Line 101:         /configure router "Base" isis 0 interface "system" passive true


/source/head/tests/13-srsim/04-srsim-classic.clab.yml:
  Line 17:         issue: true


/source/head/tests/13-srsim/06-srsim-sar.clab.yml:
  Line 10:         issue: true

  Line 22:         issue: true


/source/head/tests/13-srsim/14-srsim-new-chassis.robot:
  Line 7: Suite Setup         Skip If    '${26_10_TESTS}'.lower() != 'true'

  Line 8: ...                 SR-SIM 26.10 is required; enable with --variable 26_10_TESTS:true

  Line 83:     Should Be Equal    ${state}    true


/source/head/tests/16-mikrotik-chr/01-chr.robot:
  Line 167:     Should Be Equal As Strings    ${output.strip()}    true


/source/head/tests/13-srsim/03-srsim-dist.clab.yml:
  Line 24:         issue: true


/source/head/tests/13-srsim/11-srsim-apply.vars.linked.yml:
  Line 1: addLinks: true


/source/head/tests/13-srsim/11-srsim-apply.vars.recreate.yml:
  Line 1: addLinks: true

  Line 2: addNode: true


/source/head/tests/13-srsim/11-srsim-apply.vars.linked-with-node.yml:
  Line 1: addLinks: true

  Line 2: addNode: true


/source/head/tests/13-srsim/09-srsim-pause-container.robot:
  Line 79:     Should Be Equal As Strings    ${output}    true

  Line 126:     Should Be Equal As Strings    ${output}    true


/source/head/tests/14-clabernetes/clabwire-captures.sh:
  Line 35:   done" | grep 'packet-capture' || true


/source/head/.github/workflows/vyosnetworks_vyos-tests.yml:
  Line 7:         required: true

  Line 10:         required: true

  Line 41:           enable-cache: true


/source/head/.github/workflows/cisco_iol-tests.yml:
  Line 7:         required: true

  Line 10:         required: true

  Line 41:           enable-cache: true


/source/head/.github/workflows/download-tests.yml:
  Line 7:         required: true

  Line 10:         required: true

  Line 40:           enable-cache: true


/source/head/.github/workflows/srsim-tests.yml:
  Line 7:         required: true

  Line 10:         required: true

  Line 33:             echo "available=true" >> "$GITHUB_OUTPUT"

  Line 41:     if: needs.check-license.outputs.available == 'true'

  Line 82:           enable-cache: true


/source/head/.github/workflows/vxlan-tests.yml:
  Line 7:         required: true

  Line 10:         required: true

  Line 43:           enable-cache: true


/source/head/.github/workflows/fortigate-tests.yml:
  Line 7:         required: true

  Line 10:         required: true

  Line 43:           enable-cache: true


/source/head/.github/workflows/test-srsim.yml:
  Line 42:                 data.permissions?.admin === true ||

  Line 43:                 data.permissions?.maintain === true;

  Line 70:     if: needs.authorize.outputs.authorized == 'true'

  Line 101:     if: needs.authorize.outputs.authorized == 'true'

  Line 126:     if: needs.authorize.outputs.authorized == 'true'

  Line 151:     if: needs.authorize.outputs.authorized == 'true'


/source/head/.github/workflows/golangci-lint.yml:
  Line 6:         required: true


/source/head/.github/workflows/tofarev.yml:
  Line 20:       trusted_config: '{"repository":"srl-labs/containerlab","repositoryId":290960521,"allowedUsers":["hellt","flosch62","kaelemc","sacckth"],"shareSessions":true}'


(Results truncated. Consider using a more specific path or pattern.)
Tool metadata
{
  "type": "tool",
  "id": "prt_196769e73001fx1dorBDQveg9Z",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674f328001s9pBBzHXNa9A7D",
  "callID": "call_f6c13dea1d9c4adbb54ffde0",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "pattern": "true",
      "path": "/source/head"
    },
    "output": "Found 100 matches (more matches available)\n/source/head/tests/01-smoke/10-internal-ca.clab.yml:\n  Line 15:       issue: true\n\n  Line 22:         issue: true\n\n  Line 28:         issue: true\n\n\n/source/head/tests/01-smoke/31-apply-network-mode.vars.drift-w1.yml:\n  Line 1: driftW1: true\n\n  Line 2: addSidecar1: true\n\n\n/source/head/tests/01-smoke/29-apply.vars.deploy-drift.yml:\n  Line 4: deployDrift: true\n\n\n/source/head/tests/01-smoke/31-apply-network-mode.vars.link-restart.yml:\n  Line 1: driftW1: true\n\n  Line 2: addSidecar1: true\n\n  Line 3: addTogether: true\n\n  Line 5: addLink: true\n\n\n/source/head/tests/01-smoke/30-bridge-reconcile.vars.remap.yml:\n  Line 1: remap: true\n\n\n/source/head/tests/01-smoke/29-apply.vars.add-link.yml:\n  Line 1: addLink: true\n\n\n/source/head/tests/01-smoke/31-apply-network-mode.vars.remove-w2.yml:\n  Line 1: driftW1: true\n\n  Line 2: addSidecar1: true\n\n  Line 3: addTogether: true\n\n  Line 4: removeW2: true\n\n\n/source/head/tests/01-smoke/29-apply.vars.add-special-links.yml:\n  Line 2: addSpecialLinks: true\n\n\n/source/head/tests/01-smoke/29-apply.vars.add-node.yml:\n  Line 3: addNode: true\n\n\n/source/head/tests/01-smoke/31-apply-network-mode.vars.link-recreate.yml:\n  Line 1: driftW1: true\n\n  Line 2: addSidecar1: true\n\n  Line 3: addTogether: true\n\n  Line 5: addLink: true\n\n\n/source/head/tests/01-smoke/09-external-ca.clab.yml:\n  Line 18:         issue: true\n\n\n/source/head/tests/01-smoke/23-tools-gotty.robot:\n  Line 67:     ...    ${runtime} ps -a | grep ${gotty_container} || true\n\n\n/source/head/tests/01-smoke/30-bridge-reconcile.vars.no-bridge.yml:\n  Line 1: remap: true\n\n  Line 2: noBridge: true\n\n\n/source/head/tests/01-smoke/31-apply-network-mode.vars.add-together.yml:\n  Line 1: driftW1: true\n\n  Line 2: addSidecar1: true\n\n  Line 3: addTogether: true\n\n\n/source/head/tests/01-smoke/01-basic-flow.robot:\n  Line 227:     Should Contain    ${field_check[1]}    true\n\n\n/source/head/tests/01-smoke/21-tools-sshx.robot:\n  Line 69:     ...    ${runtime} ps -a | grep ${sshx_container} || true\n\n\n/source/head/tests/01-smoke/22-tools-api-server.robot:\n  Line 89:     ...    ${runtime} ps -a | grep ${api_server_name} || true\n\n\n/source/head/tests/01-smoke/31-apply-network-mode.vars.add-sidecar1.yml:\n  Line 2: addSidecar1: true\n\n\n/source/head/tests/08-vxlan/03-tools-veth-vxlan.robot:\n  Line 121:     # CI env var is set to true in Github Actions\n\n  Line 142:     # CI env var is set to true in Github Actions\n\n  Line 157:     ...    sudo ip link add ${vxlan-br} type bridge || true\n\n  Line 161:     ...    sudo ip link set dev ${vxlan-br} up && sleep 2 && sudo ip link set dev ${vxlan-br} mtu 9100 && sudo ip addr add ${vxlan-br-ip} dev ${vxlan-br} || true\n\n\n/source/head/tests/08-vxlan/01-vxlan.robot:\n  Line 47:     # CI env var is set to true in Github Actions\n\n  Line 81:     ...    sudo ip link add ${vxlan-br} type bridge || true\n\n  Line 83:     ...    sudo ip link set dev ${vxlan-br} up && sudo ip link set dev ${vxlan-br} mtu 9100 && sudo ip addr add ${vxlan-br-ip} dev ${vxlan-br} || true\n\n\n/source/head/tests/08-vxlan/02-vxlan-stitch.robot:\n  Line 117:     ...    sudo ip link add ${vxlan-br} type bridge || true\n\n  Line 119:     ...    sudo ip link set dev ${vxlan-br} up && sudo ip link set dev ${vxlan-br} mtu 9100 && sudo ip addr add ${vxlan-br-ip} dev ${vxlan-br} || true\n\n\n/source/head/tests/14-basic-frr/01-frr.robot:\n  Line 80:     Set Environment Variable    FRR_ENFORCE_STARTUP_CONFIG    true\n\n\n/source/head/tests/15-mgmt/09-multi-mgmt.clab.yml:\n  Line 14:     macvlan-aux: true\n\n\n/source/head/tests/15-mgmt/10-multi-mgmt-apply.vars.dropped.yml:\n  Line 3: dropOob: true\n\n\n/source/head/tests/15-mgmt/14-skip-when-unused.clab.yml:\n  Line 9:     skip-when-unused: true\n\n\n/source/head/tests/15-mgmt/mgmt.resource:\n  Line 60:     ...    { sudo iptables-save 2>/dev/null; sudo nft list ruleset 2>/dev/null; } | grep '${bridge}' | grep -ci 'set by containerlab' || true\n\n\n/source/head/tests/15-mgmt/06-macvlan-mgmt.clab.yml:\n  Line 7:   macvlan-aux: true\n\n\n/source/head/tests/15-mgmt/10-multi-mgmt-apply.vars.added.yml:\n  Line 2: addNetwork: true\n\n\n/source/head/tests/09-download/01-download.robot:\n  Line 43:     Run    sudo docker run -d --name=${sshpwservername} -e USER_NAME=user -e PASSWORD_ACCESS=true -e USER_PASSWORD=${ssh_password} --restart unless-stopped lscr.io/linuxserver/openssh-server:latest\n\n\n/source/head/tests/13-srsim/11-srsim-apply.robot:\n  Line 94:     Should Be Equal As Strings    ${output}    true\\ntrue\n\n\n/source/head/tests/13-srsim/07-srsim-mix.clab.yml:\n  Line 17:         issue: true\n\n  Line 41:         /configure router \"Base\" isis 0 advertise-passive-only true\n\n  Line 44:         /configure router \"Base\" isis 0 interface \"system\" passive true\n\n  Line 98:         /configure router \"Base\" isis 0 advertise-passive-only true\n\n  Line 101:         /configure router \"Base\" isis 0 interface \"system\" passive true\n\n\n/source/head/tests/13-srsim/04-srsim-classic.clab.yml:\n  Line 17:         issue: true\n\n\n/source/head/tests/13-srsim/06-srsim-sar.clab.yml:\n  Line 10:         issue: true\n\n  Line 22:         issue: true\n\n\n/source/head/tests/13-srsim/14-srsim-new-chassis.robot:\n  Line 7: Suite Setup         Skip If    '${26_10_TESTS}'.lower() != 'true'\n\n  Line 8: ...                 SR-SIM 26.10 is required; enable with --variable 26_10_TESTS:true\n\n  Line 83:     Should Be Equal    ${state}    true\n\n\n/source/head/tests/16-mikrotik-chr/01-chr.robot:\n  Line 167:     Should Be Equal As Strings    ${output.strip()}    true\n\n\n/source/head/tests/13-srsim/03-srsim-dist.clab.yml:\n  Line 24:         issue: true\n\n\n/source/head/tests/13-srsim/11-srsim-apply.vars.linked.yml:\n  Line 1: addLinks: true\n\n\n/source/head/tests/13-srsim/11-srsim-apply.vars.recreate.yml:\n  Line 1: addLinks: true\n\n  Line 2: addNode: true\n\n\n/source/head/tests/13-srsim/11-srsim-apply.vars.linked-with-node.yml:\n  Line 1: addLinks: true\n\n  Line 2: addNode: true\n\n\n/source/head/tests/13-srsim/09-srsim-pause-container.robot:\n  Line 79:     Should Be Equal As Strings    ${output}    true\n\n  Line 126:     Should Be Equal As Strings    ${output}    true\n\n\n/source/head/tests/14-clabernetes/clabwire-captures.sh:\n  Line 35:   done\" | grep 'packet-capture' || true\n\n\n/source/head/.github/workflows/vyosnetworks_vyos-tests.yml:\n  Line 7:         required: true\n\n  Line 10:         required: true\n\n  Line 41:           enable-cache: true\n\n\n/source/head/.github/workflows/cisco_iol-tests.yml:\n  Line 7:         required: true\n\n  Line 10:         required: true\n\n  Line 41:           enable-cache: true\n\n\n/source/head/.github/workflows/download-tests.yml:\n  Line 7:         required: true\n\n  Line 10:         required: true\n\n  Line 40:           enable-cache: true\n\n\n/source/head/.github/workflows/srsim-tests.yml:\n  Line 7:         required: true\n\n  Line 10:         required: true\n\n  Line 33:             echo \"available=true\" >> \"$GITHUB_OUTPUT\"\n\n  Line 41:     if: needs.check-license.outputs.available == 'true'\n\n  Line 82:           enable-cache: true\n\n\n/source/head/.github/workflows/vxlan-tests.yml:\n  Line 7:         required: true\n\n  Line 10:         required: true\n\n  Line 43:           enable-cache: true\n\n\n/source/head/.github/workflows/fortigate-tests.yml:\n  Line 7:         required: true\n\n  Line 10:         required: true\n\n  Line 43:           enable-cache: true\n\n\n/source/head/.github/workflows/test-srsim.yml:\n  Line 42:                 data.permissions?.admin === true ||\n\n  Line 43:                 data.permissions?.maintain === true;\n\n  Line 70:     if: needs.authorize.outputs.authorized == 'true'\n\n  Line 101:     if: needs.authorize.outputs.authorized == 'true'\n\n  Line 126:     if: needs.authorize.outputs.authorized == 'true'\n\n  Line 151:     if: needs.authorize.outputs.authorized == 'true'\n\n\n/source/head/.github/workflows/golangci-lint.yml:\n  Line 6:         required: true\n\n\n/source/head/.github/workflows/tofarev.yml:\n  Line 20:       trusted_config: '{\"repository\":\"srl-labs/containerlab\",\"repositoryId\":290960521,\"allowedUsers\":[\"hellt\",\"flosch62\",\"kaelemc\",\"sacckth\"],\"shareSessions\":true}'\n\n\n(Results truncated. Consider using a more specific path or pattern.)",
    "title": "true",
    "metadata": {
      "matches": 100,
      "truncated": true
    },
    "time": {
      "start": 1793525718649,
      "end": 1793525718684
    }
  }
}
grep · completed

Input

{
  "pattern": "mergedEventAttributes|func containerAttributes|func aggregatedEventFromLabRuntimeEvent|func aggregatedEventFromContainerEvent|func exposedPortsAttributeValue|func cloneStringMap",
  "path": "/source/head"
}

Output

Found 16 matches
/source/head/core/events/formatter.go:
  Line 46: 		attrs := mergedEventAttributes(ev)

  Line 83: 		copy.Attributes = mergedEventAttributes(ev)

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


/source/head/core/events/stream.go:
  Line 180: func aggregatedEventFromLabRuntimeEvent(

  Line 228: func containerAttributes(container *clabruntime.GenericContainer) map[string]string {

  Line 302: func aggregatedEventFromContainerEvent(

  Line 545: func cloneStringMap(input map[string]string) map[string]string {

  Line 566: func exposedPortsAttributeValue(ports []*clabtypes.GenericPortBinding) string {


/source/head/core/events/parity_test.go:
  Line 213: 	dockerAttributes := mergedEventAttributes(docker)

  Line 214: 	c9sAttributes := mergedEventAttributes(c9s)

  Line 289: 			got := mergedEventAttributes(c9s)

  Line 311: 			dockerAttributes := mergedEventAttributes(docker)

  Line 347: 		got := mergedEventAttributes(c9s)

  Line 500: 			dockerAttributes := mergedEventAttributes(docker)

  Line 501: 			got := mergedEventAttributes(c9s)

  Line 532: 	got := mergedEventAttributes(ev)
Tool metadata
{
  "type": "tool",
  "id": "prt_196769f410012hl6K2mPo0S1WC",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674f328001s9pBBzHXNa9A7D",
  "callID": "call_40edb7a01d604f1baf87df2a",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "pattern": "mergedEventAttributes|func containerAttributes|func aggregatedEventFromLabRuntimeEvent|func aggregatedEventFromContainerEvent|func exposedPortsAttributeValue|func cloneStringMap",
      "path": "/source/head"
    },
    "output": "Found 16 matches\n/source/head/core/events/formatter.go:\n  Line 46: \t\tattrs := mergedEventAttributes(ev)\n\n  Line 83: \t\tcopy.Attributes = mergedEventAttributes(ev)\n\n  Line 89: func mergedEventAttributes(ev aggregatedEvent) map[string]string {\n\n\n/source/head/core/events/stream.go:\n  Line 180: func aggregatedEventFromLabRuntimeEvent(\n\n  Line 228: func containerAttributes(container *clabruntime.GenericContainer) map[string]string {\n\n  Line 302: func aggregatedEventFromContainerEvent(\n\n  Line 545: func cloneStringMap(input map[string]string) map[string]string {\n\n  Line 566: func exposedPortsAttributeValue(ports []*clabtypes.GenericPortBinding) string {\n\n\n/source/head/core/events/parity_test.go:\n  Line 213: \tdockerAttributes := mergedEventAttributes(docker)\n\n  Line 214: \tc9sAttributes := mergedEventAttributes(c9s)\n\n  Line 289: \t\t\tgot := mergedEventAttributes(c9s)\n\n  Line 311: \t\t\tdockerAttributes := mergedEventAttributes(docker)\n\n  Line 347: \t\tgot := mergedEventAttributes(c9s)\n\n  Line 500: \t\t\tdockerAttributes := mergedEventAttributes(docker)\n\n  Line 501: \t\t\tgot := mergedEventAttributes(c9s)\n\n  Line 532: \tgot := mergedEventAttributes(ev)\n",
    "title": "mergedEventAttributes|func containerAttributes|func aggregatedEventFromLabRuntimeEvent|func aggregatedEventFromContainerEvent|func exposedPortsAttributeValue|func cloneStringMap",
    "metadata": {
      "matches": 16,
      "truncated": false
    },
    "time": {
      "start": 1793525718855,
      "end": 1793525718888
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196769f6a001xt95E1svKMdGId",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19674f328001s9pBBzHXNa9A7D",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 110764,
    "input": 31666,
    "output": 109,
    "reasoning": 13197,
    "cache": {
      "read": 65792,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19674f328001s9pBBzHXNa9A7D",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525609257,
    "completed": 1793525718894
  },
  "parentID": "msg_19674becc001poQpu47cHvtM8V",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 110764,
    "input": 31666,
    "output": 109,
    "reasoning": 13197,
    "cache": {
      "read": 65792,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
User · 8
compaction
{
  "type": "compaction",
  "id": "prt_196769f72001iLoJzQ7VSyB6gH",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196769f6f0011OUGxXLdIv2nUl",
  "auto": true,
  "overflow": false
}
Message metadata
{
  "role": "user",
  "id": "msg_196769f6f0011OUGxXLdIv2nUl",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525718895
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 9
step-start
{
  "type": "step-start",
  "id": "prt_19676aae0001k1cJ6FNRiEgGXx",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196769f85001yUa6CASJ1OEQLO"
}
Reasoning
Create summary with objective, details, work state, next moves, files.
## Objective
- Perform a source-only PR review of the read-only snapshot at `/source` (containerlab repo, srl-labs/containerlab): read `standards.json` and referenced rules, analyze `diff.txt` and head/base files, track all 26 changed paths from `manifest.json`, complete checks for each changed path plus relevant callers/tests/docs/schema, then return a trusted result schema. No test execution allowed — limitation must be disclosed.

## Important Details
- Head: `1566c3b8e3cb58c82d238dedbfa3b319249bab0a`; base: `b4de5d55cf17262e39325a7e125a6d3cb2c89318` (merge base identical). Permalink roots: head=`https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/`, base=`https://github.com/srl-labs/containerlab/blob/b4de5d55cf17262e39325a7e125a6d3cb2c89318/`.
- Snapshot incomplete: false; full inventory in `/source/manifest.json`.
- Standards loaded: `.cursor/rules/karpathy-guidelines.mdc` and `.cursor/rules/ponytail.mdc` (surgical changes, simplicity first, surface assumptions, shortest working diff, root-cause fixes, grep every caller of touched functions).
- 26 changed paths (from manifest.json, all confirmed so far): M `core/events/netlink.go`; A `core/events/parity_test.go`; M `core/events/stream.go`; M `core/labruntime.go`; M `core/labruntime_gaps_test.go`; M `docs/cmd/events.md`; M `docs/cmd/inspect/interfaces.md`; M `docs/manual/clabernetes/runtime.md`; M `labruntime/clabernetes/capture.go`; M `labruntime/clabernetes/capture_interfaces.go`; M `labruntime/clabernetes/capture_test.go`; M `labruntime/clabernetes/clabernetes.go`; M `labruntime/clabernetes/clabernetes_test.go`; A `labruntime/clabernetes/container_events.go`; A `labruntime/clabernetes/event_parity_test.go`; M `labruntime/clabernetes/events.go`; M `labruntime/clabernetes/iface_stats.go`; (remaining manifest paths truncated — need full list). Tests under `tests/01-smoke/` also referenced.
- PR theme: clabernetes (c9s) lab-runtime event parity with Docker runtime — new container event tracker (`container_events.go` with `containerTracker`, debounce timer via `arm`/`time.NewTimer`, `refresh`, `observeLab`, `observeNode`, `containerHealth`, `containerTransitionActions`, `containerActionState`, `labRuntimeContainerState`), interface event parity (`labRuntimeInterfaceAttributes`, `interfaceSnapshotAttributes`, `interfaceStatsAttributes` in netlink.go), poller changes in `iface_stats.go` (`processStates`, `processSample`, `sampleAll`, `round`, `retireStoppedNodes`, `nodeLinks`, `sampledInterfaceNames`, `reportedInterfaces`, listing cache keyed by pod), topology source file annotation recording (`setTopologySourceFile`, `removeTopologySourceFile`, `carryOverNodeTopologyFile`, `labTopologyPath`, `stateFromTopology`, `stateFromNodeResources`, `labRuntimeTopologyPath`), c9s `NodeState` enrichment (`TopoFile`, `Type`, `Group`, `labelOriginalNodeName` → `TopologyName`, `annotationDirectNodeUID` = `c9s.run/direct-node-uid`, `newestPod` now prefers non-deleting pods, `enrichState`).
- Read tool is permission-gated; reads under `source/*` allowed. Read offsets used for truncated output (diff.txt read at offsets 1362, 2845, 4396).
- Candidate issues already identified during reasoning (need verification against head files):
  - `TestInterfaceEventOmitsUnknownValues` may fail: `interfaceSnapshotAttributes` sets `attributes["state"]` unconditionally even when `OperState` is "" — unless `mergedEventAttributes` drops empty values (must verify).
  - `processSample` may not check `sample.err` — if `nodeLinks` (clabwire listing) errors, stats may be silently restricted to eth0/lo only, a behavior regression for no-shell device nodes that docs say "report statistics only".
  - `trackContainers` early-return on `labStates` failure leaves watch goroutines (`watchNodes`/`watchPods`/`watchTopologies`) potentially blocked on `sendChangedLab` (`changed` chan buffer 256) until ctx done.
  - `errs := make(chan error, 4)` sizing vs number of error-writing goroutines (trackContainers + 3 watches) — verify.
  - `containerFromLabNode`: config `NodeType` unconditionally overrides runtime `node.Type` even when config NodeType is empty — could drop type label in edge cases (topology edited between deploy and events read).
  - `annotationDirectNodeUID` — verify it is actually set somewhere in c9s code (grep needed) or the contract is with external clabernetes controller.
  - `managementAddress` CIDR parsing parity with `GetContainerIPv4` format (`172.20.20.x/24`).
  - Verify `WithLabNameOnly`, `DockerMessageToEventData`, `labRuntimeTopologyPath(c, state)`, `c.topologyNodeName` semantics for byName mode (Topology nil, Nodes possibly empty).
  - Verify timer.Reset usage in `containerTracker` (appears safe: Reset only when !armed; select drains timer.C).
- Reasoning about docker/c9s parity cases (create/start/kill/stop/die/health_status/snapshot actions, `state`/`status`/`origin` attribute semantics) largely holds; parity tests only check c9s ⊇ docker attributes plus explicit `want` maps.

## Work State
### Completed
- Read `/source/standards.json` → two referenced rules; read `standards/karpathy-guidelines.mdc` and `standards/ponytail.mdc`.
- Read `/source/manifest.json` (truncated — full 26-path list not yet fully captured; 17 paths confirmed).
- Read `/source/diff.txt` at offsets 1, 1362, 2845, 4396 (still not fully read end-to-end).
- Extensive static analysis of diff: enumerated ~65 reasoning points covering tracker debounce/timer correctness, labState refresh semantics, health/transition actions, iface stats ordering (processStates before stats loop, pointer-field struct comparison validity), inspect-interfaces state mapping (`netlinkOperState("lowerlayerdown")` → "lower-layer-down"), docs/robot test consistency.
- Grep located key symbols: `mergedEventAttributes` in `core/events/formatter.go` (lines 46, 83, 89); `aggregatedEventFromLabRuntimeEvent` (stream.go:180), `containerAttributes` (stream.go:228), `aggregatedEventFromContainerEvent` (stream.go:302), `cloneStringMap` (stream.go:545), `exposedPortsAttributeValue` (stream.go:566); parity test call sites at parity_test.go lines 213/214/289/311/347/500/501/532.

### Active
- Verifying candidate issues against head files, starting with `mergedEventAttributes` (formatter.go:89) to resolve the `TestInterfaceEventOmitsUnknownValues` state-attribute question.

### Blocked
- (none)

## Next Move
1. Read `/source/head/core/events/formatter.go` (esp. `mergedEventAttributes`) and `/source/head/core/events/stream.go` (lines ~180-600) to check empty-attribute handling, containerAttributes, aggregatedEventFromContainerEvent/Snapshot, and errs handling in `streamLabRuntimeEvents`.
2. Then read `/source/head/core/events/netlink.go`, `/source/head/core/labruntime.go`, `labruntime/clabernetes/{container_events.go,events.go,iface_stats.go,state.go,topology.go,manifests.go,plan.go,primitives.go,reconcile.go,capture_interfaces.go,capture.go,clabernetes.go}` heads, `labruntime/runtime.go`, all test files, docs files, and robot tests; re-read full manifest.json for the remaining 9 changed paths; finalize per-path findings and emit the trusted result schema (disclosing the no-test-execution limitation).

## Relevant Files
- `/source/standards.json`, `/source/standards/karpathy-guidelines.mdc`, `/source/standards/ponytail.mdc` — review standards (done).
- `/source/manifest.json` — changed-path inventory (truncated read; re-read for full 26 paths).
- `/source/diff.txt` — full PR diff (partially read: offsets 1–~1362, 1362–2845, 2845–4396, 4396–…; finish reading).
- `/source/head/core/events/formatter.go` — `mergedEventAttributes` at line 89; critical for the state-attribute omission question.
- `/source/head/core/events/stream.go` — `aggregatedEventFromLabRuntimeEvent` (:180), `containerAttributes` (:228), `aggregatedEventFromContainerEvent` (:302), `cloneStringMap` (:545), `exposedPortsAttributeValue` (:566), `streamLabRuntimeEvents` and errs channel handling.
- `/source/head/core/events/netlink.go` — `labRuntimeInterfaceAttributes`, `interfaceSnapshotAttributes`, `interfaceStatsAttributes`, `interfaceAttributes`.
- `/source/head/core/events/parity_test.go` — new parity test; call sites at 213/214/289/311/347/500/501/532; `TestInterfaceEventOmitsUnknownValues`, `TestContainerSnapshotParity`, `TestContainerEventParity`, `TestContainerStateUsesDockerVocabulary`, `TestDeployRecordsTheTopologyFile`, `TestInspectInterfacesReportsStateFromSysfs`.
- `/source/head/core/labruntime.go` — `containerFromLabNode`, `LabRuntimeContainer`, `labRuntimeContainerState`, `labRuntimePorts`, `labRuntimeTopologyPath`, `topologyNodeName`, `managementAddress`.
- `/source/head/labruntime/clabernetes/container_events.go` — new container tracker (A).
- `/source/head/labruntime/clabernetes/iface_stats.go` — poller round/processSample/processStates/sampleAll/retireStoppedNodes/nodeLinks error handling.
- `/source/head/labruntime/clabernetes/events.go` — watch goroutines, errs chan sizing, `sendChangedLab`, `sendEventError`.
- `/source/head/labruntime/clabernetes/state.go` — `enrichState`, `stateFromNodeResources`, `newestPod`, `nodeStateFromResource`.
- `/source/head/labruntime/clabernetes/{topology.go,manifests.go,plan.go,primitives.go,reconcile.go}` — topology source file annotation recording/carry-over.
- `/source/head/labruntime/clabernetes/capture_interfaces.go`, `capture.go`, `clabernetes.go` — inspect interfaces, `listPodInterfaces` refactor, `execInPodContainer` per-pod cost.
- `/source/head/labruntime/runtime.go` — `Inspect`/`InspectRequest` lab-not-found semantics used by tracker.
- `/source/head/core/labruntime_gaps_test.go`, `/source/head/labruntime/clabernetes/{clabernetes_test.go,capture_test.go,event_parity_test.go}` — modified/added tests.
- `/source/head/docs/cmd/events.md`, `/source/head/docs/cmd/inspect/interfaces.md`, `/source/head/docs/manual/clabernetes/runtime.md` — docs parity.
- `/source/head/tests/01-smoke/` — robot tests incl. `Container Actions Should Include In Order`, `Interface Event Should Be Logged` with `@{states}`.
step-finish
{
  "type": "step-finish",
  "id": "prt_19676df8d001tX9iEp7UmXGFgH",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196769f85001yUa6CASJ1OEQLO",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 22479,
    "input": 19892,
    "output": 2571,
    "reasoning": 16,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196769f85001yUa6CASJ1OEQLO",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525718917,
    "completed": 1793525735314
  },
  "parentID": "msg_196769f6f0011OUGxXLdIv2nUl",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "compaction",
  "agent": "compaction",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "summary": true,
  "cost": 0,
  "tokens": {
    "total": 22479,
    "input": 19892,
    "output": 2571,
    "reasoning": 16,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "stop"
}
User · 10
Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.
Message metadata
{
  "role": "user",
  "id": "msg_19676df9500159h7P3dGcuBxjO",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525735317
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 11
step-start
{
  "type": "step-start",
  "id": "prt_19676e436001tPHHHeLz8bp5Dk",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19676dfa0001BY469BQld1pxR4"
}
Reasoning
I need to continue the review. The working directory is /tmp/tofarev-review-aS2Bo2 but the previous session referenced /source. Let me check what exists here. The env says workspace root is /, not a git repo. Let me look at the directory contents first.
read · error

Input

{
  "filePath": "/"
}

Output

The user has specified a rule which prevents you from using this specific tool call. Here are some of the relevant rules [{"permission":"*","action":"allow","pattern":"*"},{"permission":"external_directory","pattern":"*","action":"ask"},{"permission":"external_directory","pattern":"/tmp/tofarev-review-aS2Bo2/data/opencode/tool-output/*","action":"allow"},{"permission":"external_directory","pattern":"/tmp/opencode/*","action":"allow"},{"permission":"*","action":"deny","pattern":"*"},{"permission":"external_directory","pattern":"*","action":"deny"},{"permission":"external_directory","pattern":"/source","action":"allow"},{"permission":"external_directory","pattern":"/source/*","action":"allow"},{"permission":"*","action":"deny","pattern":"*"},{"permission":"external_directory","pattern":"*","action":"deny"},{"permission":"external_directory","pattern":"/source","action":"allow"},{"permission":"external_directory","pattern":"/source/*","action":"allow"},{"permission":"external_directory","pattern":"/tmp/tofarev-review-aS2Bo2/data/opencode/tool-output/*","action":"allow"}]
Tool metadata
{
  "type": "tool",
  "id": "prt_19676e69e001KIAeJ51fykgiIj",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19676dfa0001BY469BQld1pxR4",
  "callID": "call_5a3810e981b545d4bf0b89b5",
  "tool": "read",
  "state": {
    "status": "error",
    "input": {
      "filePath": "/"
    },
    "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\":\"external_directory\",\"pattern\":\"*\",\"action\":\"ask\"},{\"permission\":\"external_directory\",\"pattern\":\"/tmp/tofarev-review-aS2Bo2/data/opencode/tool-output/*\",\"action\":\"allow\"},{\"permission\":\"external_directory\",\"pattern\":\"/tmp/opencode/*\",\"action\":\"allow\"},{\"permission\":\"*\",\"action\":\"deny\",\"pattern\":\"*\"},{\"permission\":\"external_directory\",\"pattern\":\"*\",\"action\":\"deny\"},{\"permission\":\"external_directory\",\"pattern\":\"/source\",\"action\":\"allow\"},{\"permission\":\"external_directory\",\"pattern\":\"/source/*\",\"action\":\"allow\"},{\"permission\":\"*\",\"action\":\"deny\",\"pattern\":\"*\"},{\"permission\":\"external_directory\",\"pattern\":\"*\",\"action\":\"deny\"},{\"permission\":\"external_directory\",\"pattern\":\"/source\",\"action\":\"allow\"},{\"permission\":\"external_directory\",\"pattern\":\"/source/*\",\"action\":\"allow\"},{\"permission\":\"external_directory\",\"pattern\":\"/tmp/tofarev-review-aS2Bo2/data/opencode/tool-output/*\",\"action\":\"allow\"}]",
    "time": {
      "start": 1793525737124,
      "end": 1793525737127
    }
  }
}
read · error

Input

{
  "filePath": "/tmp/tofarev-review-aS2Bo2"
}

Output

The user has specified a rule which prevents you from using this specific tool call. Here are some of the relevant rules [{"permission":"*","action":"allow","pattern":"*"},{"permission":"read","pattern":"*","action":"allow"},{"permission":"read","pattern":"*.env","action":"ask"},{"permission":"read","pattern":"*.env.*","action":"ask"},{"permission":"read","pattern":"*.env.example","action":"allow"},{"permission":"*","action":"deny","pattern":"*"},{"permission":"read","pattern":"*","action":"deny"},{"permission":"read","pattern":"source/*","action":"allow"},{"permission":"*","action":"deny","pattern":"*"},{"permission":"read","pattern":"*","action":"deny"},{"permission":"read","pattern":"source/*","action":"allow"}]
Tool metadata
{
  "type": "tool",
  "id": "prt_19676e6d2001wH19637ObKGCKB",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19676dfa0001BY469BQld1pxR4",
  "callID": "call_862feff0b55147b6bc4722a6",
  "tool": "read",
  "state": {
    "status": "error",
    "input": {
      "filePath": "/tmp/tofarev-review-aS2Bo2"
    },
    "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": 1793525737175,
      "end": 1793525737179
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19676e6dd001QYD5AHPPvdt5ZK",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19676dfa0001BY469BQld1pxR4",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 5671,
    "input": 2703,
    "output": 28,
    "reasoning": 60,
    "cache": {
      "read": 2880,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19676dfa0001BY469BQld1pxR4",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525735328,
    "completed": 1793525737185
  },
  "parentID": "msg_19676df9500159h7P3dGcuBxjO",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 5671,
    "input": 2703,
    "output": 28,
    "reasoning": 60,
    "cache": {
      "read": 2880,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 12
step-start
{
  "type": "step-start",
  "id": "prt_19676ec15001egXFrsJj25B6rJ",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19676e6e7001rhvUV1fKr45xMQ"
}
Reasoning
Only /source paths are readable. Continue with the next steps: read formatter.go and stream.go first.
Only `/source` paths are readable, so I will continue the review there. Next step per the plan: verify the `mergedEventAttributes` empty-attribute handling and the events stream code.
read · completed

Input

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

Output

<path>/source/head/core/events/formatter.go</path>
<type>file</type>
<content>
1: package events
2: 
3: import (
4: 	"encoding/json"
5: 	"fmt"
6: 	"io"
7: 	"sort"
8: 	"strings"
9: 	"time"
10: )
11: 
12: type formatter func(aggregatedEvent) error
13: 
14: func newFormatter(format string, w io.Writer) (formatter, error) {
15: 	normalized := strings.TrimSpace(strings.ToLower(format))
16: 	if normalized == "" {
17: 		normalized = "plain"
18: 	}
19: 
20: 	switch normalized {
21: 	case "plain":
22: 		return plainFormatter(w), nil
23: 	case "json":
24: 		return jsonFormatter(w), nil
25: 	default:
26: 		return nil, fmt.Errorf("output format %q is not supported, use 'plain' or 'json'", format)
27: 	}
28: }
29: 
30: func plainFormatter(w io.Writer) formatter {
31: 	return func(ev aggregatedEvent) error {
32: 		ts := ev.Timestamp
33: 		if ts.IsZero() {
34: 			ts = time.Now()
35: 		}
36: 		ts = ts.UTC()
37: 
38: 		actor := ev.ActorID
39: 		if actor == "" {
40: 			actor = ev.ActorName
41: 		}
42: 		if actor == "" {
43: 			actor = "-"
44: 		}
45: 
46: 		attrs := mergedEventAttributes(ev)
47: 		keys := make([]string, 0, len(attrs))
48: 		for k := range attrs {
49: 			keys = append(keys, k)
50: 		}
51: 		sort.Strings(keys)
52: 
53: 		parts := make([]string, 0, len(keys))
54: 		for _, k := range keys {
55: 			parts = append(parts, fmt.Sprintf("%s=%s", k, attrs[k]))
56: 		}
57: 
58: 		suffix := ""
59: 		if len(parts) > 0 {
60: 			suffix = " (" + strings.Join(parts, ", ") + ")"
61: 		}
62: 
63: 		_, err := fmt.Fprintf(
64: 			w,
65: 			"%s %s %s %s%s\n",
66: 			ts.Format(time.RFC3339Nano),
67: 			ev.Type,
68: 			ev.Action,
69: 			actor,
70: 			suffix,
71: 		)
72: 
73: 		return err
74: 	}
75: }
76: 
77: func jsonFormatter(w io.Writer) formatter {
78: 	encoder := json.NewEncoder(w)
79: 	encoder.SetEscapeHTML(false)
80: 
81: 	return func(ev aggregatedEvent) error {
82: 		copy := ev
83: 		copy.Attributes = mergedEventAttributes(ev)
84: 
85: 		return encoder.Encode(copy)
86: 	}
87: }
88: 
89: func mergedEventAttributes(ev aggregatedEvent) map[string]string {
90: 	if len(ev.Attributes) == 0 && ev.ActorName == "" && ev.ActorFullID == "" {
91: 		return nil
92: 	}
93: 
94: 	attrs := make(map[string]string, len(ev.Attributes)+2)
95: 	for k, v := range ev.Attributes {
96: 		if v == "" {
97: 			continue
98: 		}
99: 
100: 		attrs[k] = v
101: 	}
102: 
103: 	if ev.ActorName != "" {
104: 		attrs["name"] = ev.ActorName
105: 	}
106: 
107: 	if ev.ActorFullID != "" {
108: 		attrs["id"] = ev.ActorFullID
109: 	}
110: 
111: 	if len(attrs) == 0 {
112: 		return nil
113: 	}
114: 
115: 	return attrs
116: }

(End of file - total 116 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19676ed88001d5nQHhHMzvEqnX",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19676e6e7001rhvUV1fKr45xMQ",
  "callID": "call_e15a27554fe14fabba8aec30",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/events/formatter.go"
    },
    "output": "<path>/source/head/core/events/formatter.go</path>\n<type>file</type>\n<content>\n1: package events\n2: \n3: import (\n4: \t\"encoding/json\"\n5: \t\"fmt\"\n6: \t\"io\"\n7: \t\"sort\"\n8: \t\"strings\"\n9: \t\"time\"\n10: )\n11: \n12: type formatter func(aggregatedEvent) error\n13: \n14: func newFormatter(format string, w io.Writer) (formatter, error) {\n15: \tnormalized := strings.TrimSpace(strings.ToLower(format))\n16: \tif normalized == \"\" {\n17: \t\tnormalized = \"plain\"\n18: \t}\n19: \n20: \tswitch normalized {\n21: \tcase \"plain\":\n22: \t\treturn plainFormatter(w), nil\n23: \tcase \"json\":\n24: \t\treturn jsonFormatter(w), nil\n25: \tdefault:\n26: \t\treturn nil, fmt.Errorf(\"output format %q is not supported, use 'plain' or 'json'\", format)\n27: \t}\n28: }\n29: \n30: func plainFormatter(w io.Writer) formatter {\n31: \treturn func(ev aggregatedEvent) error {\n32: \t\tts := ev.Timestamp\n33: \t\tif ts.IsZero() {\n34: \t\t\tts = time.Now()\n35: \t\t}\n36: \t\tts = ts.UTC()\n37: \n38: \t\tactor := ev.ActorID\n39: \t\tif actor == \"\" {\n40: \t\t\tactor = ev.ActorName\n41: \t\t}\n42: \t\tif actor == \"\" {\n43: \t\t\tactor = \"-\"\n44: \t\t}\n45: \n46: \t\tattrs := mergedEventAttributes(ev)\n47: \t\tkeys := make([]string, 0, len(attrs))\n48: \t\tfor k := range attrs {\n49: \t\t\tkeys = append(keys, k)\n50: \t\t}\n51: \t\tsort.Strings(keys)\n52: \n53: \t\tparts := make([]string, 0, len(keys))\n54: \t\tfor _, k := range keys {\n55: \t\t\tparts = append(parts, fmt.Sprintf(\"%s=%s\", k, attrs[k]))\n56: \t\t}\n57: \n58: \t\tsuffix := \"\"\n59: \t\tif len(parts) > 0 {\n60: \t\t\tsuffix = \" (\" + strings.Join(parts, \", \") + \")\"\n61: \t\t}\n62: \n63: \t\t_, err := fmt.Fprintf(\n64: \t\t\tw,\n65: \t\t\t\"%s %s %s %s%s\\n\",\n66: \t\t\tts.Format(time.RFC3339Nano),\n67: \t\t\tev.Type,\n68: \t\t\tev.Action,\n69: \t\t\tactor,\n70: \t\t\tsuffix,\n71: \t\t)\n72: \n73: \t\treturn err\n74: \t}\n75: }\n76: \n77: func jsonFormatter(w io.Writer) formatter {\n78: \tencoder := json.NewEncoder(w)\n79: \tencoder.SetEscapeHTML(false)\n80: \n81: \treturn func(ev aggregatedEvent) error {\n82: \t\tcopy := ev\n83: \t\tcopy.Attributes = mergedEventAttributes(ev)\n84: \n85: \t\treturn encoder.Encode(copy)\n86: \t}\n87: }\n88: \n89: func mergedEventAttributes(ev aggregatedEvent) map[string]string {\n90: \tif len(ev.Attributes) == 0 && ev.ActorName == \"\" && ev.ActorFullID == \"\" {\n91: \t\treturn nil\n92: \t}\n93: \n94: \tattrs := make(map[string]string, len(ev.Attributes)+2)\n95: \tfor k, v := range ev.Attributes {\n96: \t\tif v == \"\" {\n97: \t\t\tcontinue\n98: \t\t}\n99: \n100: \t\tattrs[k] = v\n101: \t}\n102: \n103: \tif ev.ActorName != \"\" {\n104: \t\tattrs[\"name\"] = ev.ActorName\n105: \t}\n106: \n107: \tif ev.ActorFullID != \"\" {\n108: \t\tattrs[\"id\"] = ev.ActorFullID\n109: \t}\n110: \n111: \tif len(attrs) == 0 {\n112: \t\treturn nil\n113: \t}\n114: \n115: \treturn attrs\n116: }\n\n(End of file - total 116 lines)\n</content>",
    "title": "source/head/core/events/formatter.go",
    "metadata": {
      "preview": "package events\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype formatter func(aggregatedEvent) error\n\nfunc newFormatter(format string, w io.Writer) (formatter, error) {\n\tnormalized := strings.TrimSpace(strings.ToLower(format))\n\tif normalized == \"\" {\n\t\tnormalized = \"plain\"\n\t}\n\n\tswitch normalized {",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/events/formatter.go",
        "text": "package events\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype formatter func(aggregatedEvent) error\n\nfunc newFormatter(format string, w io.Writer) (formatter, error) {\n\tnormalized := strings.TrimSpace(strings.ToLower(format))\n\tif normalized == \"\" {\n\t\tnormalized = \"plain\"\n\t}\n\n\tswitch normalized {\n\tcase \"plain\":\n\t\treturn plainFormatter(w), nil\n\tcase \"json\":\n\t\treturn jsonFormatter(w), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"output format %q is not supported, use 'plain' or 'json'\", format)\n\t}\n}\n\nfunc plainFormatter(w io.Writer) formatter {\n\treturn func(ev aggregatedEvent) error {\n\t\tts := ev.Timestamp\n\t\tif ts.IsZero() {\n\t\t\tts = time.Now()\n\t\t}\n\t\tts = ts.UTC()\n\n\t\tactor := ev.ActorID\n\t\tif actor == \"\" {\n\t\t\tactor = ev.ActorName\n\t\t}\n\t\tif actor == \"\" {\n\t\t\tactor = \"-\"\n\t\t}\n\n\t\tattrs := mergedEventAttributes(ev)\n\t\tkeys := make([]string, 0, len(attrs))\n\t\tfor k := range attrs {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Strings(keys)\n\n\t\tparts := make([]string, 0, len(keys))\n\t\tfor _, k := range keys {\n\t\t\tparts = append(parts, fmt.Sprintf(\"%s=%s\", k, attrs[k]))\n\t\t}\n\n\t\tsuffix := \"\"\n\t\tif len(parts) > 0 {\n\t\t\tsuffix = \" (\" + strings.Join(parts, \", \") + \")\"\n\t\t}\n\n\t\t_, err := fmt.Fprintf(\n\t\t\tw,\n\t\t\t\"%s %s %s %s%s\\n\",\n\t\t\tts.Format(time.RFC3339Nano),\n\t\t\tev.Type,\n\t\t\tev.Action,\n\t\t\tactor,\n\t\t\tsuffix,\n\t\t)\n\n\t\treturn err\n\t}\n}\n\nfunc jsonFormatter(w io.Writer) formatter {\n\tencoder := json.NewEncoder(w)\n\tencoder.SetEscapeHTML(false)\n\n\treturn func(ev aggregatedEvent) error {\n\t\tcopy := ev\n\t\tcopy.Attributes = mergedEventAttributes(ev)\n\n\t\treturn encoder.Encode(copy)\n\t}\n}\n\nfunc mergedEventAttributes(ev aggregatedEvent) map[string]string {\n\tif len(ev.Attributes) == 0 && ev.ActorName == \"\" && ev.ActorFullID == \"\" {\n\t\treturn nil\n\t}\n\n\tattrs := make(map[string]string, len(ev.Attributes)+2)\n\tfor k, v := range ev.Attributes {\n\t\tif v == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tattrs[k] = v\n\t}\n\n\tif ev.ActorName != \"\" {\n\t\tattrs[\"name\"] = ev.ActorName\n\t}\n\n\tif ev.ActorFullID != \"\" {\n\t\tattrs[\"id\"] = ev.ActorFullID\n\t}\n\n\tif len(attrs) == 0 {\n\t\treturn nil\n\t}\n\n\treturn attrs\n}",
        "lineStart": 1,
        "lineEnd": 116,
        "totalLines": 116,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525738894,
      "end": 1793525738908
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19676ed9e0011XRztVXtGW37Jc",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19676e6e7001rhvUV1fKr45xMQ",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 6144,
    "input": 3187,
    "output": 55,
    "reasoning": 22,
    "cache": {
      "read": 2880,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19676e6e7001rhvUV1fKr45xMQ",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525737191,
    "completed": 1793525738913
  },
  "parentID": "msg_19676df9500159h7P3dGcuBxjO",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 6144,
    "input": 3187,
    "output": 55,
    "reasoning": 22,
    "cache": {
      "read": 2880,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 13
step-start
{
  "type": "step-start",
  "id": "prt_19676f2e1001GUB4IB5jnOy6ID",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19676eda7001heIxLWb0fV1IsA"
}
Reasoning
Good: `mergedEventAttributes` skips empty values (line 96-98), so the `state` attribute set to "" in `interfaceSnapshotAttributes` would be omitted. The candidate issue about `TestInterfaceEventOmitsUnknownValues` failing is resolved — not an issue.

Next: read stream.go relevant parts (lines 1-620 or so, and the rest).
`mergedEventAttributes` drops empty values (formatter.go:96-98), which resolves the candidate concern about `state=""` in `interfaceSnapshotAttributes` — no issue there. Continuing with `stream.go`.
read · completed

Input

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

Output

<path>/source/head/core/events/stream.go</path>
<type>file</type>
<content>
1: package events
2: 
3: import (
4: 	"context"
5: 	"errors"
6: 	"fmt"
7: 	"sort"
8: 	"strings"
9: 	"time"
10: 
11: 	"github.com/charmbracelet/log"
12: 	clabconstants "github.com/srl-labs/containerlab/constants"
13: 	clabcore "github.com/srl-labs/containerlab/core"
14: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
15: 	clabruntime "github.com/srl-labs/containerlab/runtime"
16: 	clabtypes "github.com/srl-labs/containerlab/types"
17: 	clabutils "github.com/srl-labs/containerlab/utils"
18: )
19: 
20: // Stream subscribes to the selected runtime and netlink sources and forwards
21: // aggregated events to the configured writer.
22: func Stream(ctx context.Context, opts Options) error {
23: 	ctx, cancel := context.WithCancel(ctx)
24: 	defer cancel()
25: 
26: 	clab, err := clabcore.NewContainerLab(opts.ClabOptions...)
27: 	if err != nil {
28: 		return err
29: 	}
30: 
31: 	if clab.LabRuntime != nil {
32: 		return streamLabRuntimeEvents(ctx, clab, opts)
33: 	}
34: 
35: 	runtime, ok := clab.Runtimes[opts.Runtime]
36: 	if !ok {
37: 		return fmt.Errorf("runtime %q is not initialized", opts.Runtime)
38: 	}
39: 
40: 	printer, err := newFormatter(opts.Format, opts.writer())
41: 	if err != nil {
42: 		return err
43: 	}
44: 
45: 	eventCh := make(chan aggregatedEvent, 128)
46: 	registry := newNetlinkRegistry(
47: 		ctx,
48: 		eventCh,
49: 		opts.IncludeInitialState,
50: 		opts.IncludeInterfaceStats,
51: 		opts.StatsInterval,
52: 	)
53: 
54: 	containers, err := clab.ListContainers(ctx, clabcore.WithListclabLabelExists())
55: 	if err != nil {
56: 		return fmt.Errorf("failed to list containers: %w", err)
57: 	}
58: 
59: 	if opts.IncludeInitialState {
60: 		go emitContainerSnapshots(ctx, containers, eventCh)
61: 	}
62: 
63: 	for idx := range containers {
64: 		container := containers[idx]
65: 		if !isRunningContainer(&container) {
66: 			continue
67: 		}
68: 
69: 		registry.Start(&container)
70: 	}
71: 
72: 	streamOpts := clabruntime.EventStreamOptions{
73: 		Labels: map[string]string{
74: 			clabconstants.Containerlab: "",
75: 		},
76: 	}
77: 
78: 	runtimeEvents, runtimeErrs, err := runtime.StreamEvents(ctx, streamOpts)
79: 	if err != nil {
80: 		return fmt.Errorf("failed to stream events for runtime %q: %w", opts.Runtime, err)
81: 	}
82: 
83: 	errCh := make(chan error, 1)
84: 	go forwardRuntimeEvents(ctx, runtime, registry, runtimeEvents, runtimeErrs, eventCh, errCh)
85: 
86: 	runtimeErrors := errCh
87: 
88: 	for {
89: 		select {
90: 		case ev := <-eventCh:
91: 			if err := printer(ev); err != nil {
92: 				log.Debugf("failed to write event: %v", err)
93: 			}
94: 		case err, ok := <-runtimeErrors:
95: 			if !ok {
96: 				runtimeErrors = nil
97: 
98: 				continue
99: 			}
100: 
101: 			if err != nil && !errors.Is(err, context.Canceled) {
102: 				return err
103: 			}
104: 		case <-ctx.Done():
105: 			return nil
106: 		}
107: 	}
108: }
109: 
110: func streamLabRuntimeEvents(ctx context.Context, clab *clabcore.CLab, opts Options) error {
111: 	printer, err := newFormatter(opts.Format, opts.writer())
112: 	if err != nil {
113: 		return err
114: 	}
115: 
116: 	runtimeEvents, runtimeErrs, err := clab.LabRuntime.StreamEvents(
117: 		ctx,
118: 		labRuntimeEventStreamRequest(clab.Config.Name, clab.LabRuntimeIdentity(), opts),
119: 	)
120: 	if err != nil {
121: 		return fmt.Errorf("failed to stream events for lab runtime %q: %w", opts.Runtime, err)
122: 	}
123: 
124: 	for runtimeEvents != nil || runtimeErrs != nil {
125: 		select {
126: 		case ev, ok := <-runtimeEvents:
127: 			if !ok {
128: 				runtimeEvents = nil
129: 
130: 				continue
131: 			}
132: 
133: 			if err := printer(aggregatedEventFromLabRuntimeEvent(clab, ev)); err != nil {
134: 				log.Debugf("failed to write event: %v", err)
135: 			}
136: 		case err, ok := <-runtimeErrs:
137: 			if !ok {
138: 				runtimeErrs = nil
139: 
140: 				continue
141: 			}
142: 
143: 			if err != nil && !errors.Is(err, context.Canceled) {
144: 				return err
145: 			}
146: 		case <-ctx.Done():
147: 			return nil
148: 		}
149: 	}
150: 
151: 	return nil
152: }
153: 
154: // labRuntimeEventStreamRequest scopes a lab runtime event stream. A selected lab (--topo or
155: // --name) limits the stream to that lab in its namespace. Without one the stream covers every
156: // namespace, unless a namespace override (--namespace, CLAB_KUBE_NAMESPACE) limits it to that
157: // namespace; the runtime applies the override.
158: func labRuntimeEventStreamRequest(
159: 	labName string,
160: 	identity clablabruntime.Identity,
161: 	opts Options,
162: ) clablabruntime.EventStreamRequest {
163: 	return clablabruntime.EventStreamRequest{
164: 		Name:                  labName,
165: 		Identity:              identity,
166: 		AllNamespaces:         labName == "",
167: 		IncludeInitialState:   opts.IncludeInitialState,
168: 		IncludeInterfaceStats: opts.IncludeInterfaceStats,
169: 		StatsInterval:         opts.StatsInterval,
170: 	}
171: }
172: 
173: // aggregatedEventFromLabRuntimeEvent reports a lab runtime event with the attributes the
174: // container runtimes' events have. A container event describes its node with the container
175: // record inspect reports for it, the way a Docker event carries the container's labels: as a
176: // snapshot like the snapshots of local containers, otherwise with the labels, image,
177: // management addresses and ports a Docker event and its enrichment carry. An interface event
178: // carries the attributes of the netlink interface events. The runtime's own attributes come on
179: // top.
180: func aggregatedEventFromLabRuntimeEvent(
181: 	clab *clabcore.CLab,
182: 	ev clablabruntime.Event,
183: ) aggregatedEvent {
184: 	ts := ev.Timestamp
185: 	if ts.IsZero() {
186: 		ts = time.Now()
187: 	}
188: 
189: 	var attributes map[string]string
190: 	switch {
191: 	case ev.Type == clablabruntime.EventTypeContainer && ev.Lab != nil && ev.Node != nil &&
192: 		clab != nil:
193: 		container := clab.LabRuntimeContainer(ev.Lab, *ev.Node)
194: 		if ev.Attributes["origin"] == clablabruntime.EventOriginSnapshot {
195: 			attributes = aggregatedEventFromContainerSnapshot(&container).Attributes
196: 		} else {
197: 			attributes = containerAttributes(&container)
198: 		}
199: 	case ev.Type == clablabruntime.EventTypeInterface && ev.Interface != nil:
200: 		lab := ev.Attributes["lab"]
201: 		if ev.Lab != nil {
202: 			lab = ev.Lab.Name
203: 		}
204: 		attributes = labRuntimeInterfaceAttributes(lab, ev.ActorName, ev.Interface)
205: 	}
206: 
207: 	for key, value := range ev.Attributes {
208: 		if attributes == nil {
209: 			attributes = make(map[string]string, len(ev.Attributes))
210: 		}
211: 		attributes[key] = value
212: 	}
213: 
214: 	return aggregatedEvent{
215: 		Timestamp:   ts,
216: 		Type:        ev.Type,
217: 		Action:      ev.Action,
218: 		ActorID:     ev.ActorID,
219: 		ActorName:   ev.ActorName,
220: 		ActorFullID: ev.ActorFullID,
221: 		Attributes:  attributes,
222: 	}
223: }
224: 
225: // containerAttributes are the attributes a container event reports for a container: its labels
226: // and image, which Docker puts on every container event, and the management addresses and
227: // ports the events command adds.
228: func containerAttributes(container *clabruntime.GenericContainer) map[string]string {
229: 	attributes := cloneStringMap(container.Labels)
230: 	if attributes == nil {
231: 		attributes = make(map[string]string)
232: 	}
233: 
234: 	if container.Image != "" {
235: 		attributes["image"] = container.Image
236: 	}
237: 
238: 	if container.NetworkSettings.IPv4addr != "" {
239: 		attributes["mgmt_ipv4"] = container.GetContainerIPv4()
240: 	}
241: 
242: 	if container.NetworkSettings.IPv6addr != "" {
243: 		attributes["mgmt_ipv6"] = container.GetContainerIPv6()
244: 	}
245: 
246: 	if ports := exposedPortsAttributeValue(container.Ports); ports != "" {
247: 		attributes["ports"] = ports
248: 	}
249: 
250: 	return attributes
251: }
252: 
253: func forwardRuntimeEvents(
254: 	ctx context.Context,
255: 	runtime clabruntime.ContainerRuntime,
256: 	registry *netlinkRegistry,
257: 	runtimeEvents <-chan clabruntime.ContainerEvent,
258: 	runtimeErrs <-chan error,
259: 	eventSink chan<- aggregatedEvent,
260: 	errSink chan<- error,
261: ) {
262: 	defer close(errSink)
263: 
264: 	sendErr := func(err error) {
265: 		select {
266: 		case errSink <- err:
267: 		case <-ctx.Done():
268: 		}
269: 	}
270: 
271: 	for {
272: 		select {
273: 		case <-ctx.Done():
274: 			return
275: 		case err, ok := <-runtimeErrs:
276: 			if !ok {
277: 				return
278: 			}
279: 
280: 			if err != nil && !errors.Is(err, context.Canceled) {
281: 				sendErr(err)
282: 
283: 				return
284: 			}
285: 		case ev, ok := <-runtimeEvents:
286: 			if !ok {
287: 				return
288: 			}
289: 
290: 			registry.HandleContainerEvent(runtime, ev)
291: 
292: 			aggregated := aggregatedEventFromContainerEvent(ctx, runtime, ev)
293: 			select {
294: 			case eventSink <- aggregated:
295: 			case <-ctx.Done():
296: 				return
297: 			}
298: 		}
299: 	}
300: }
301: 
302: func aggregatedEventFromContainerEvent(
303: 	ctx context.Context,
304: 	runtime clabruntime.ContainerRuntime,
305: 	ev clabruntime.ContainerEvent,
306: ) aggregatedEvent {
307: 	ts := ev.Timestamp
308: 	if ts.IsZero() {
309: 		ts = time.Now()
310: 	}
311: 
312: 	attributes := cloneStringMap(ev.Attributes)
313: 
314: 	actorFullID := ev.ActorFullID
315: 	if actorFullID == "" {
316: 		actorFullID = ev.ActorID
317: 	}
318: 
319: 	actorName := ev.ActorName
320: 	if actorName == "" && attributes != nil {
321: 		actorName = attributes["name"]
322: 	}
323: 
324: 	attributes = ensureContainerAttributes(ctx, runtime, attributes, actorFullID, actorName)
325: 
326: 	short := ev.ActorID
327: 	if short == "" {
328: 		short = actorFullID
329: 	}
330: 
331: 	action := strings.ToLower(ev.Action)
332: 	if action == "" {
333: 		action = ev.Action
334: 	}
335: 
336: 	eventType := strings.ToLower(ev.Type)
337: 	if eventType == "" {
338: 		eventType = ev.Type
339: 	}
340: 
341: 	return aggregatedEvent{
342: 		Timestamp:   ts,
343: 		Type:        eventType,
344: 		Action:      action,
345: 		ActorID:     clabutils.ShortID(short),
346: 		ActorName:   actorName,
347: 		ActorFullID: actorFullID,
348: 		Attributes:  attributes,
349: 	}
350: }
351: 
352: func ensureContainerAttributes(
353: 	ctx context.Context,
354: 	runtime clabruntime.ContainerRuntime,
355: 	attributes map[string]string,
356: 	actorFullID, actorName string,
357: ) map[string]string {
358: 	if runtime == nil {
359: 		return attributes
360: 	}
361: 
362: 	hasIPv4 := attributes != nil && attributes["mgmt_ipv4"] != ""
363: 	hasIPv6 := attributes != nil && attributes["mgmt_ipv6"] != ""
364: 	hasPorts := attributes != nil && attributes["ports"] != ""
365: 
366: 	if hasIPv4 && hasIPv6 && hasPorts {
367: 		return attributes
368: 	}
369: 
370: 	filters := make([]*clabtypes.GenericFilter, 0, 2)
371: 
372: 	if actorName == "" && attributes != nil {
373: 		actorName = attributes["name"]
374: 	}
375: 
376: 	if actorName != "" {
377: 		filters = append(filters, &clabtypes.GenericFilter{FilterType: "name", Match: actorName})
378: 	}
379: 
380: 	if actorFullID != "" {
381: 		filters = append(filters, &clabtypes.GenericFilter{FilterType: "id", Match: actorFullID})
382: 	}
383: 
384: 	if len(filters) == 0 {
385: 		return attributes
386: 	}
387: 
388: 	containers, err := runtime.ListContainers(ctx, filters)
389: 	if err != nil {
390: 		log.Debugf("failed to resolve container for event: %v", err)
391: 
392: 		return attributes
393: 	}
394: 
395: 	container := selectContainerForEvent(containers, actorFullID, actorName)
396: 	if container == nil {
397: 		return attributes
398: 	}
399: 
400: 	if attributes == nil {
401: 		attributes = make(map[string]string)
402: 	}
403: 
404: 	if !hasIPv4 {
405: 		if ipv4 := container.GetContainerIPv4(); ipv4 != "" && ipv4 != clabconstants.NotApplicable {
406: 			attributes["mgmt_ipv4"] = ipv4
407: 		}
408: 	}
409: 
410: 	if !hasIPv6 {
411: 		if ipv6 := container.GetContainerIPv6(); ipv6 != "" && ipv6 != clabconstants.NotApplicable {
412: 			attributes["mgmt_ipv6"] = ipv6
413: 		}
414: 	}
415: 
416: 	if !hasPorts {
417: 		if ports := exposedPortsAttributeValue(container.Ports); ports != "" {
418: 			attributes["ports"] = ports
419: 		}
420: 	}
421: 
422: 	if len(attributes) == 0 {
423: 		return nil
424: 	}
425: 
426: 	return attributes
427: }
428: 
429: func selectContainerForEvent(
430: 	containers []clabruntime.GenericContainer,
431: 	actorFullID, actorName string,
432: ) *clabruntime.GenericContainer {
433: 	if len(containers) == 0 {
434: 		return nil
435: 	}
436: 
437: 	if actorFullID != "" {
438: 		for idx := range containers {
439: 			container := &containers[idx]
440: 
441: 			switch {
442: 			case container.ID == actorFullID:
443: 				return container
444: 			case strings.HasPrefix(container.ID, actorFullID):
445: 				return container
446: 			case container.ShortID == actorFullID:
447: 				return container
448: 			}
449: 		}
450: 	}
451: 
452: 	if actorName != "" {
453: 		for idx := range containers {
454: 			container := &containers[idx]
455: 
456: 			for _, name := range container.Names {
457: 				if name == actorName {
458: 					return container
459: 				}
460: 			}
461: 		}
462: 	}
463: 
464: 	return &containers[0]
465: }
466: 
467: func emitContainerSnapshots(
468: 	ctx context.Context,
469: 	containers []clabruntime.GenericContainer,
470: 	sink chan<- aggregatedEvent,
471: ) {
472: 	for idx := range containers {
473: 		container := containers[idx]
474: 		if !isRunningContainer(&container) && !strings.EqualFold(container.State, "exited") {
475: 			continue
476: 		}
477: 
478: 		event := aggregatedEventFromContainerSnapshot(&container)
479: 		if event.ActorID == "" && event.ActorName == "" {
480: 			continue
481: 		}
482: 
483: 		select {
484: 		case sink <- event:
485: 		case <-ctx.Done():
486: 			return
487: 		}
488: 	}
489: }
490: 
491: func aggregatedEventFromContainerSnapshot(
492: 	container *clabruntime.GenericContainer,
493: ) aggregatedEvent {
494: 	if container == nil {
495: 		return aggregatedEvent{}
496: 	}
497: 
498: 	state := strings.ToLower(container.State)
499: 
500: 	short := container.ShortID
501: 	if short == "" {
502: 		short = clabutils.ShortID(container.ID)
503: 	}
504: 
505: 	attributes := containerAttributes(container)
506: 
507: 	if _, ok := attributes["origin"]; !ok {
508: 		attributes["origin"] = "snapshot"
509: 	}
510: 
511: 	if container.Status != "" {
512: 		attributes["status"] = container.Status
513: 	}
514: 
515: 	if state != "" {
516: 		attributes["state"] = state
517: 	}
518: 
519: 	if container.NetworkName != "" {
520: 		attributes["network"] = container.NetworkName
521: 	}
522: 
523: 	if len(attributes) == 0 {
524: 		attributes = nil
525: 	}
526: 
527: 	actorName := firstContainerName(container)
528: 
529: 	action := state
530: 	if action == "" {
531: 		action = "snapshot"
532: 	}
533: 
534: 	return aggregatedEvent{
535: 		Timestamp:   time.Now(),
536: 		Type:        "container",
537: 		Action:      action,
538: 		ActorID:     clabutils.ShortID(short),
539: 		ActorName:   actorName,
540: 		ActorFullID: container.ID,
541: 		Attributes:  attributes,
542: 	}
543: }
544: 
545: func cloneStringMap(input map[string]string) map[string]string {
546: 	if len(input) == 0 {
547: 		return nil
548: 	}
549: 
550: 	result := make(map[string]string, len(input))
551: 	for k, v := range input {
552: 		result[k] = v
553: 	}
554: 
555: 	return result
556: }
557: 
558: func isRunningContainer(container *clabruntime.GenericContainer) bool {
559: 	if container == nil {
560: 		return false
561: 	}
562: 
563: 	return strings.EqualFold(container.State, "running")
564: }
565: 
566: func exposedPortsAttributeValue(ports []*clabtypes.GenericPortBinding) string {
567: 	if len(ports) == 0 {
568: 		return ""
569: 	}
570: 
571: 	sortedPorts := make([]*clabtypes.GenericPortBinding, 0, len(ports))
572: 	for idx := range ports {
573: 		if ports[idx] != nil {
574: 			sortedPorts = append(sortedPorts, ports[idx])
575: 		}
576: 	}
577: 
578: 	if len(sortedPorts) == 0 {
579: 		return ""
580: 	}
581: 
582: 	sort.Slice(sortedPorts, func(i, j int) bool {
583: 		left := sortedPorts[i]
584: 		right := sortedPorts[j]
585: 
586: 		switch {
587: 		case left.ContainerPort != right.ContainerPort:
588: 			return left.ContainerPort < right.ContainerPort
589: 		case left.Protocol != right.Protocol:
590: 			return left.Protocol < right.Protocol
591: 		case left.HostPort != right.HostPort:
592: 			return left.HostPort < right.HostPort
593: 		default:
594: 			return left.HostIP < right.HostIP
595: 		}
596: 	})
597: 
598: 	result := make([]string, 0, len(sortedPorts))
599: 	for idx := range sortedPorts {
600: 		formatted := formatExposedPort(sortedPorts[idx])
601: 		if formatted != "" {
602: 			result = append(result, formatted)
603: 		}
604: 	}
605: 
606: 	if len(result) == 0 {
607: 		return ""
608: 	}
609: 
610: 	return strings.Join(result, ";")
611: }
612: 
613: func formatExposedPort(port *clabtypes.GenericPortBinding) string {
614: 	if port == nil {
615: 		return ""
616: 	}
617: 
618: 	proto := strings.TrimSpace(strings.ToLower(port.Protocol))
619: 	protoSuffix := ""
620: 	if proto != "" {
621: 		protoSuffix = "/" + proto
622: 	}
623: 
624: 	if port.HostPort > 0 {
625: 		hostIP := port.HostIP
626: 		if hostIP == "" {
627: 			hostIP = "0.0.0.0"
628: 		}
629: 
630: 		if strings.Contains(hostIP, ":") {
631: 			hostIP = fmt.Sprintf("[%s]", hostIP)
632: 		}
633: 
634: 		if port.ContainerPort > 0 {
635: 			return fmt.Sprintf(
636: 				"%s:%d%s->%d",
637: 				hostIP,
638: 				port.HostPort,
639: 				protoSuffix,
640: 				port.ContainerPort,
641: 			)
642: 		}
643: 
644: 		return fmt.Sprintf("%s:%d%s", hostIP, port.HostPort, protoSuffix)
645: 	}
646: 
647: 	if port.ContainerPort <= 0 {
648: 		return ""
649: 	}
650: 
651: 	return fmt.Sprintf("%d%s", port.ContainerPort, protoSuffix)
652: }

(End of file - total 652 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19676f60e001Y7gOgdO1hOp94z",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19676eda7001heIxLWb0fV1IsA",
  "callID": "call_039dd049c0a74bf68c54db70",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/events/stream.go"
    },
    "output": "<path>/source/head/core/events/stream.go</path>\n<type>file</type>\n<content>\n1: package events\n2: \n3: import (\n4: \t\"context\"\n5: \t\"errors\"\n6: \t\"fmt\"\n7: \t\"sort\"\n8: \t\"strings\"\n9: \t\"time\"\n10: \n11: \t\"github.com/charmbracelet/log\"\n12: \tclabconstants \"github.com/srl-labs/containerlab/constants\"\n13: \tclabcore \"github.com/srl-labs/containerlab/core\"\n14: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n15: \tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n16: \tclabtypes \"github.com/srl-labs/containerlab/types\"\n17: \tclabutils \"github.com/srl-labs/containerlab/utils\"\n18: )\n19: \n20: // Stream subscribes to the selected runtime and netlink sources and forwards\n21: // aggregated events to the configured writer.\n22: func Stream(ctx context.Context, opts Options) error {\n23: \tctx, cancel := context.WithCancel(ctx)\n24: \tdefer cancel()\n25: \n26: \tclab, err := clabcore.NewContainerLab(opts.ClabOptions...)\n27: \tif err != nil {\n28: \t\treturn err\n29: \t}\n30: \n31: \tif clab.LabRuntime != nil {\n32: \t\treturn streamLabRuntimeEvents(ctx, clab, opts)\n33: \t}\n34: \n35: \truntime, ok := clab.Runtimes[opts.Runtime]\n36: \tif !ok {\n37: \t\treturn fmt.Errorf(\"runtime %q is not initialized\", opts.Runtime)\n38: \t}\n39: \n40: \tprinter, err := newFormatter(opts.Format, opts.writer())\n41: \tif err != nil {\n42: \t\treturn err\n43: \t}\n44: \n45: \teventCh := make(chan aggregatedEvent, 128)\n46: \tregistry := newNetlinkRegistry(\n47: \t\tctx,\n48: \t\teventCh,\n49: \t\topts.IncludeInitialState,\n50: \t\topts.IncludeInterfaceStats,\n51: \t\topts.StatsInterval,\n52: \t)\n53: \n54: \tcontainers, err := clab.ListContainers(ctx, clabcore.WithListclabLabelExists())\n55: \tif err != nil {\n56: \t\treturn fmt.Errorf(\"failed to list containers: %w\", err)\n57: \t}\n58: \n59: \tif opts.IncludeInitialState {\n60: \t\tgo emitContainerSnapshots(ctx, containers, eventCh)\n61: \t}\n62: \n63: \tfor idx := range containers {\n64: \t\tcontainer := containers[idx]\n65: \t\tif !isRunningContainer(&container) {\n66: \t\t\tcontinue\n67: \t\t}\n68: \n69: \t\tregistry.Start(&container)\n70: \t}\n71: \n72: \tstreamOpts := clabruntime.EventStreamOptions{\n73: \t\tLabels: map[string]string{\n74: \t\t\tclabconstants.Containerlab: \"\",\n75: \t\t},\n76: \t}\n77: \n78: \truntimeEvents, runtimeErrs, err := runtime.StreamEvents(ctx, streamOpts)\n79: \tif err != nil {\n80: \t\treturn fmt.Errorf(\"failed to stream events for runtime %q: %w\", opts.Runtime, err)\n81: \t}\n82: \n83: \terrCh := make(chan error, 1)\n84: \tgo forwardRuntimeEvents(ctx, runtime, registry, runtimeEvents, runtimeErrs, eventCh, errCh)\n85: \n86: \truntimeErrors := errCh\n87: \n88: \tfor {\n89: \t\tselect {\n90: \t\tcase ev := <-eventCh:\n91: \t\t\tif err := printer(ev); err != nil {\n92: \t\t\t\tlog.Debugf(\"failed to write event: %v\", err)\n93: \t\t\t}\n94: \t\tcase err, ok := <-runtimeErrors:\n95: \t\t\tif !ok {\n96: \t\t\t\truntimeErrors = nil\n97: \n98: \t\t\t\tcontinue\n99: \t\t\t}\n100: \n101: \t\t\tif err != nil && !errors.Is(err, context.Canceled) {\n102: \t\t\t\treturn err\n103: \t\t\t}\n104: \t\tcase <-ctx.Done():\n105: \t\t\treturn nil\n106: \t\t}\n107: \t}\n108: }\n109: \n110: func streamLabRuntimeEvents(ctx context.Context, clab *clabcore.CLab, opts Options) error {\n111: \tprinter, err := newFormatter(opts.Format, opts.writer())\n112: \tif err != nil {\n113: \t\treturn err\n114: \t}\n115: \n116: \truntimeEvents, runtimeErrs, err := clab.LabRuntime.StreamEvents(\n117: \t\tctx,\n118: \t\tlabRuntimeEventStreamRequest(clab.Config.Name, clab.LabRuntimeIdentity(), opts),\n119: \t)\n120: \tif err != nil {\n121: \t\treturn fmt.Errorf(\"failed to stream events for lab runtime %q: %w\", opts.Runtime, err)\n122: \t}\n123: \n124: \tfor runtimeEvents != nil || runtimeErrs != nil {\n125: \t\tselect {\n126: \t\tcase ev, ok := <-runtimeEvents:\n127: \t\t\tif !ok {\n128: \t\t\t\truntimeEvents = nil\n129: \n130: \t\t\t\tcontinue\n131: \t\t\t}\n132: \n133: \t\t\tif err := printer(aggregatedEventFromLabRuntimeEvent(clab, ev)); err != nil {\n134: \t\t\t\tlog.Debugf(\"failed to write event: %v\", err)\n135: \t\t\t}\n136: \t\tcase err, ok := <-runtimeErrs:\n137: \t\t\tif !ok {\n138: \t\t\t\truntimeErrs = nil\n139: \n140: \t\t\t\tcontinue\n141: \t\t\t}\n142: \n143: \t\t\tif err != nil && !errors.Is(err, context.Canceled) {\n144: \t\t\t\treturn err\n145: \t\t\t}\n146: \t\tcase <-ctx.Done():\n147: \t\t\treturn nil\n148: \t\t}\n149: \t}\n150: \n151: \treturn nil\n152: }\n153: \n154: // labRuntimeEventStreamRequest scopes a lab runtime event stream. A selected lab (--topo or\n155: // --name) limits the stream to that lab in its namespace. Without one the stream covers every\n156: // namespace, unless a namespace override (--namespace, CLAB_KUBE_NAMESPACE) limits it to that\n157: // namespace; the runtime applies the override.\n158: func labRuntimeEventStreamRequest(\n159: \tlabName string,\n160: \tidentity clablabruntime.Identity,\n161: \topts Options,\n162: ) clablabruntime.EventStreamRequest {\n163: \treturn clablabruntime.EventStreamRequest{\n164: \t\tName:                  labName,\n165: \t\tIdentity:              identity,\n166: \t\tAllNamespaces:         labName == \"\",\n167: \t\tIncludeInitialState:   opts.IncludeInitialState,\n168: \t\tIncludeInterfaceStats: opts.IncludeInterfaceStats,\n169: \t\tStatsInterval:         opts.StatsInterval,\n170: \t}\n171: }\n172: \n173: // aggregatedEventFromLabRuntimeEvent reports a lab runtime event with the attributes the\n174: // container runtimes' events have. A container event describes its node with the container\n175: // record inspect reports for it, the way a Docker event carries the container's labels: as a\n176: // snapshot like the snapshots of local containers, otherwise with the labels, image,\n177: // management addresses and ports a Docker event and its enrichment carry. An interface event\n178: // carries the attributes of the netlink interface events. The runtime's own attributes come on\n179: // top.\n180: func aggregatedEventFromLabRuntimeEvent(\n181: \tclab *clabcore.CLab,\n182: \tev clablabruntime.Event,\n183: ) aggregatedEvent {\n184: \tts := ev.Timestamp\n185: \tif ts.IsZero() {\n186: \t\tts = time.Now()\n187: \t}\n188: \n189: \tvar attributes map[string]string\n190: \tswitch {\n191: \tcase ev.Type == clablabruntime.EventTypeContainer && ev.Lab != nil && ev.Node != nil &&\n192: \t\tclab != nil:\n193: \t\tcontainer := clab.LabRuntimeContainer(ev.Lab, *ev.Node)\n194: \t\tif ev.Attributes[\"origin\"] == clablabruntime.EventOriginSnapshot {\n195: \t\t\tattributes = aggregatedEventFromContainerSnapshot(&container).Attributes\n196: \t\t} else {\n197: \t\t\tattributes = containerAttributes(&container)\n198: \t\t}\n199: \tcase ev.Type == clablabruntime.EventTypeInterface && ev.Interface != nil:\n200: \t\tlab := ev.Attributes[\"lab\"]\n201: \t\tif ev.Lab != nil {\n202: \t\t\tlab = ev.Lab.Name\n203: \t\t}\n204: \t\tattributes = labRuntimeInterfaceAttributes(lab, ev.ActorName, ev.Interface)\n205: \t}\n206: \n207: \tfor key, value := range ev.Attributes {\n208: \t\tif attributes == nil {\n209: \t\t\tattributes = make(map[string]string, len(ev.Attributes))\n210: \t\t}\n211: \t\tattributes[key] = value\n212: \t}\n213: \n214: \treturn aggregatedEvent{\n215: \t\tTimestamp:   ts,\n216: \t\tType:        ev.Type,\n217: \t\tAction:      ev.Action,\n218: \t\tActorID:     ev.ActorID,\n219: \t\tActorName:   ev.ActorName,\n220: \t\tActorFullID: ev.ActorFullID,\n221: \t\tAttributes:  attributes,\n222: \t}\n223: }\n224: \n225: // containerAttributes are the attributes a container event reports for a container: its labels\n226: // and image, which Docker puts on every container event, and the management addresses and\n227: // ports the events command adds.\n228: func containerAttributes(container *clabruntime.GenericContainer) map[string]string {\n229: \tattributes := cloneStringMap(container.Labels)\n230: \tif attributes == nil {\n231: \t\tattributes = make(map[string]string)\n232: \t}\n233: \n234: \tif container.Image != \"\" {\n235: \t\tattributes[\"image\"] = container.Image\n236: \t}\n237: \n238: \tif container.NetworkSettings.IPv4addr != \"\" {\n239: \t\tattributes[\"mgmt_ipv4\"] = container.GetContainerIPv4()\n240: \t}\n241: \n242: \tif container.NetworkSettings.IPv6addr != \"\" {\n243: \t\tattributes[\"mgmt_ipv6\"] = container.GetContainerIPv6()\n244: \t}\n245: \n246: \tif ports := exposedPortsAttributeValue(container.Ports); ports != \"\" {\n247: \t\tattributes[\"ports\"] = ports\n248: \t}\n249: \n250: \treturn attributes\n251: }\n252: \n253: func forwardRuntimeEvents(\n254: \tctx context.Context,\n255: \truntime clabruntime.ContainerRuntime,\n256: \tregistry *netlinkRegistry,\n257: \truntimeEvents <-chan clabruntime.ContainerEvent,\n258: \truntimeErrs <-chan error,\n259: \teventSink chan<- aggregatedEvent,\n260: \terrSink chan<- error,\n261: ) {\n262: \tdefer close(errSink)\n263: \n264: \tsendErr := func(err error) {\n265: \t\tselect {\n266: \t\tcase errSink <- err:\n267: \t\tcase <-ctx.Done():\n268: \t\t}\n269: \t}\n270: \n271: \tfor {\n272: \t\tselect {\n273: \t\tcase <-ctx.Done():\n274: \t\t\treturn\n275: \t\tcase err, ok := <-runtimeErrs:\n276: \t\t\tif !ok {\n277: \t\t\t\treturn\n278: \t\t\t}\n279: \n280: \t\t\tif err != nil && !errors.Is(err, context.Canceled) {\n281: \t\t\t\tsendErr(err)\n282: \n283: \t\t\t\treturn\n284: \t\t\t}\n285: \t\tcase ev, ok := <-runtimeEvents:\n286: \t\t\tif !ok {\n287: \t\t\t\treturn\n288: \t\t\t}\n289: \n290: \t\t\tregistry.HandleContainerEvent(runtime, ev)\n291: \n292: \t\t\taggregated := aggregatedEventFromContainerEvent(ctx, runtime, ev)\n293: \t\t\tselect {\n294: \t\t\tcase eventSink <- aggregated:\n295: \t\t\tcase <-ctx.Done():\n296: \t\t\t\treturn\n297: \t\t\t}\n298: \t\t}\n299: \t}\n300: }\n301: \n302: func aggregatedEventFromContainerEvent(\n303: \tctx context.Context,\n304: \truntime clabruntime.ContainerRuntime,\n305: \tev clabruntime.ContainerEvent,\n306: ) aggregatedEvent {\n307: \tts := ev.Timestamp\n308: \tif ts.IsZero() {\n309: \t\tts = time.Now()\n310: \t}\n311: \n312: \tattributes := cloneStringMap(ev.Attributes)\n313: \n314: \tactorFullID := ev.ActorFullID\n315: \tif actorFullID == \"\" {\n316: \t\tactorFullID = ev.ActorID\n317: \t}\n318: \n319: \tactorName := ev.ActorName\n320: \tif actorName == \"\" && attributes != nil {\n321: \t\tactorName = attributes[\"name\"]\n322: \t}\n323: \n324: \tattributes = ensureContainerAttributes(ctx, runtime, attributes, actorFullID, actorName)\n325: \n326: \tshort := ev.ActorID\n327: \tif short == \"\" {\n328: \t\tshort = actorFullID\n329: \t}\n330: \n331: \taction := strings.ToLower(ev.Action)\n332: \tif action == \"\" {\n333: \t\taction = ev.Action\n334: \t}\n335: \n336: \teventType := strings.ToLower(ev.Type)\n337: \tif eventType == \"\" {\n338: \t\teventType = ev.Type\n339: \t}\n340: \n341: \treturn aggregatedEvent{\n342: \t\tTimestamp:   ts,\n343: \t\tType:        eventType,\n344: \t\tAction:      action,\n345: \t\tActorID:     clabutils.ShortID(short),\n346: \t\tActorName:   actorName,\n347: \t\tActorFullID: actorFullID,\n348: \t\tAttributes:  attributes,\n349: \t}\n350: }\n351: \n352: func ensureContainerAttributes(\n353: \tctx context.Context,\n354: \truntime clabruntime.ContainerRuntime,\n355: \tattributes map[string]string,\n356: \tactorFullID, actorName string,\n357: ) map[string]string {\n358: \tif runtime == nil {\n359: \t\treturn attributes\n360: \t}\n361: \n362: \thasIPv4 := attributes != nil && attributes[\"mgmt_ipv4\"] != \"\"\n363: \thasIPv6 := attributes != nil && attributes[\"mgmt_ipv6\"] != \"\"\n364: \thasPorts := attributes != nil && attributes[\"ports\"] != \"\"\n365: \n366: \tif hasIPv4 && hasIPv6 && hasPorts {\n367: \t\treturn attributes\n368: \t}\n369: \n370: \tfilters := make([]*clabtypes.GenericFilter, 0, 2)\n371: \n372: \tif actorName == \"\" && attributes != nil {\n373: \t\tactorName = attributes[\"name\"]\n374: \t}\n375: \n376: \tif actorName != \"\" {\n377: \t\tfilters = append(filters, &clabtypes.GenericFilter{FilterType: \"name\", Match: actorName})\n378: \t}\n379: \n380: \tif actorFullID != \"\" {\n381: \t\tfilters = append(filters, &clabtypes.GenericFilter{FilterType: \"id\", Match: actorFullID})\n382: \t}\n383: \n384: \tif len(filters) == 0 {\n385: \t\treturn attributes\n386: \t}\n387: \n388: \tcontainers, err := runtime.ListContainers(ctx, filters)\n389: \tif err != nil {\n390: \t\tlog.Debugf(\"failed to resolve container for event: %v\", err)\n391: \n392: \t\treturn attributes\n393: \t}\n394: \n395: \tcontainer := selectContainerForEvent(containers, actorFullID, actorName)\n396: \tif container == nil {\n397: \t\treturn attributes\n398: \t}\n399: \n400: \tif attributes == nil {\n401: \t\tattributes = make(map[string]string)\n402: \t}\n403: \n404: \tif !hasIPv4 {\n405: \t\tif ipv4 := container.GetContainerIPv4(); ipv4 != \"\" && ipv4 != clabconstants.NotApplicable {\n406: \t\t\tattributes[\"mgmt_ipv4\"] = ipv4\n407: \t\t}\n408: \t}\n409: \n410: \tif !hasIPv6 {\n411: \t\tif ipv6 := container.GetContainerIPv6(); ipv6 != \"\" && ipv6 != clabconstants.NotApplicable {\n412: \t\t\tattributes[\"mgmt_ipv6\"] = ipv6\n413: \t\t}\n414: \t}\n415: \n416: \tif !hasPorts {\n417: \t\tif ports := exposedPortsAttributeValue(container.Ports); ports != \"\" {\n418: \t\t\tattributes[\"ports\"] = ports\n419: \t\t}\n420: \t}\n421: \n422: \tif len(attributes) == 0 {\n423: \t\treturn nil\n424: \t}\n425: \n426: \treturn attributes\n427: }\n428: \n429: func selectContainerForEvent(\n430: \tcontainers []clabruntime.GenericContainer,\n431: \tactorFullID, actorName string,\n432: ) *clabruntime.GenericContainer {\n433: \tif len(containers) == 0 {\n434: \t\treturn nil\n435: \t}\n436: \n437: \tif actorFullID != \"\" {\n438: \t\tfor idx := range containers {\n439: \t\t\tcontainer := &containers[idx]\n440: \n441: \t\t\tswitch {\n442: \t\t\tcase container.ID == actorFullID:\n443: \t\t\t\treturn container\n444: \t\t\tcase strings.HasPrefix(container.ID, actorFullID):\n445: \t\t\t\treturn container\n446: \t\t\tcase container.ShortID == actorFullID:\n447: \t\t\t\treturn container\n448: \t\t\t}\n449: \t\t}\n450: \t}\n451: \n452: \tif actorName != \"\" {\n453: \t\tfor idx := range containers {\n454: \t\t\tcontainer := &containers[idx]\n455: \n456: \t\t\tfor _, name := range container.Names {\n457: \t\t\t\tif name == actorName {\n458: \t\t\t\t\treturn container\n459: \t\t\t\t}\n460: \t\t\t}\n461: \t\t}\n462: \t}\n463: \n464: \treturn &containers[0]\n465: }\n466: \n467: func emitContainerSnapshots(\n468: \tctx context.Context,\n469: \tcontainers []clabruntime.GenericContainer,\n470: \tsink chan<- aggregatedEvent,\n471: ) {\n472: \tfor idx := range containers {\n473: \t\tcontainer := containers[idx]\n474: \t\tif !isRunningContainer(&container) && !strings.EqualFold(container.State, \"exited\") {\n475: \t\t\tcontinue\n476: \t\t}\n477: \n478: \t\tevent := aggregatedEventFromContainerSnapshot(&container)\n479: \t\tif event.ActorID == \"\" && event.ActorName == \"\" {\n480: \t\t\tcontinue\n481: \t\t}\n482: \n483: \t\tselect {\n484: \t\tcase sink <- event:\n485: \t\tcase <-ctx.Done():\n486: \t\t\treturn\n487: \t\t}\n488: \t}\n489: }\n490: \n491: func aggregatedEventFromContainerSnapshot(\n492: \tcontainer *clabruntime.GenericContainer,\n493: ) aggregatedEvent {\n494: \tif container == nil {\n495: \t\treturn aggregatedEvent{}\n496: \t}\n497: \n498: \tstate := strings.ToLower(container.State)\n499: \n500: \tshort := container.ShortID\n501: \tif short == \"\" {\n502: \t\tshort = clabutils.ShortID(container.ID)\n503: \t}\n504: \n505: \tattributes := containerAttributes(container)\n506: \n507: \tif _, ok := attributes[\"origin\"]; !ok {\n508: \t\tattributes[\"origin\"] = \"snapshot\"\n509: \t}\n510: \n511: \tif container.Status != \"\" {\n512: \t\tattributes[\"status\"] = container.Status\n513: \t}\n514: \n515: \tif state != \"\" {\n516: \t\tattributes[\"state\"] = state\n517: \t}\n518: \n519: \tif container.NetworkName != \"\" {\n520: \t\tattributes[\"network\"] = container.NetworkName\n521: \t}\n522: \n523: \tif len(attributes) == 0 {\n524: \t\tattributes = nil\n525: \t}\n526: \n527: \tactorName := firstContainerName(container)\n528: \n529: \taction := state\n530: \tif action == \"\" {\n531: \t\taction = \"snapshot\"\n532: \t}\n533: \n534: \treturn aggregatedEvent{\n535: \t\tTimestamp:   time.Now(),\n536: \t\tType:        \"container\",\n537: \t\tAction:      action,\n538: \t\tActorID:     clabutils.ShortID(short),\n539: \t\tActorName:   actorName,\n540: \t\tActorFullID: container.ID,\n541: \t\tAttributes:  attributes,\n542: \t}\n543: }\n544: \n545: func cloneStringMap(input map[string]string) map[string]string {\n546: \tif len(input) == 0 {\n547: \t\treturn nil\n548: \t}\n549: \n550: \tresult := make(map[string]string, len(input))\n551: \tfor k, v := range input {\n552: \t\tresult[k] = v\n553: \t}\n554: \n555: \treturn result\n556: }\n557: \n558: func isRunningContainer(container *clabruntime.GenericContainer) bool {\n559: \tif container == nil {\n560: \t\treturn false\n561: \t}\n562: \n563: \treturn strings.EqualFold(container.State, \"running\")\n564: }\n565: \n566: func exposedPortsAttributeValue(ports []*clabtypes.GenericPortBinding) string {\n567: \tif len(ports) == 0 {\n568: \t\treturn \"\"\n569: \t}\n570: \n571: \tsortedPorts := make([]*clabtypes.GenericPortBinding, 0, len(ports))\n572: \tfor idx := range ports {\n573: \t\tif ports[idx] != nil {\n574: \t\t\tsortedPorts = append(sortedPorts, ports[idx])\n575: \t\t}\n576: \t}\n577: \n578: \tif len(sortedPorts) == 0 {\n579: \t\treturn \"\"\n580: \t}\n581: \n582: \tsort.Slice(sortedPorts, func(i, j int) bool {\n583: \t\tleft := sortedPorts[i]\n584: \t\tright := sortedPorts[j]\n585: \n586: \t\tswitch {\n587: \t\tcase left.ContainerPort != right.ContainerPort:\n588: \t\t\treturn left.ContainerPort < right.ContainerPort\n589: \t\tcase left.Protocol != right.Protocol:\n590: \t\t\treturn left.Protocol < right.Protocol\n591: \t\tcase left.HostPort != right.HostPort:\n592: \t\t\treturn left.HostPort < right.HostPort\n593: \t\tdefault:\n594: \t\t\treturn left.HostIP < right.HostIP\n595: \t\t}\n596: \t})\n597: \n598: \tresult := make([]string, 0, len(sortedPorts))\n599: \tfor idx := range sortedPorts {\n600: \t\tformatted := formatExposedPort(sortedPorts[idx])\n601: \t\tif formatted != \"\" {\n602: \t\t\tresult = append(result, formatted)\n603: \t\t}\n604: \t}\n605: \n606: \tif len(result) == 0 {\n607: \t\treturn \"\"\n608: \t}\n609: \n610: \treturn strings.Join(result, \";\")\n611: }\n612: \n613: func formatExposedPort(port *clabtypes.GenericPortBinding) string {\n614: \tif port == nil {\n615: \t\treturn \"\"\n616: \t}\n617: \n618: \tproto := strings.TrimSpace(strings.ToLower(port.Protocol))\n619: \tprotoSuffix := \"\"\n620: \tif proto != \"\" {\n621: \t\tprotoSuffix = \"/\" + proto\n622: \t}\n623: \n624: \tif port.HostPort > 0 {\n625: \t\thostIP := port.HostIP\n626: \t\tif hostIP == \"\" {\n627: \t\t\thostIP = \"0.0.0.0\"\n628: \t\t}\n629: \n630: \t\tif strings.Contains(hostIP, \":\") {\n631: \t\t\thostIP = fmt.Sprintf(\"[%s]\", hostIP)\n632: \t\t}\n633: \n634: \t\tif port.ContainerPort > 0 {\n635: \t\t\treturn fmt.Sprintf(\n636: \t\t\t\t\"%s:%d%s->%d\",\n637: \t\t\t\thostIP,\n638: \t\t\t\tport.HostPort,\n639: \t\t\t\tprotoSuffix,\n640: \t\t\t\tport.ContainerPort,\n641: \t\t\t)\n642: \t\t}\n643: \n644: \t\treturn fmt.Sprintf(\"%s:%d%s\", hostIP, port.HostPort, protoSuffix)\n645: \t}\n646: \n647: \tif port.ContainerPort <= 0 {\n648: \t\treturn \"\"\n649: \t}\n650: \n651: \treturn fmt.Sprintf(\"%d%s\", port.ContainerPort, protoSuffix)\n652: }\n\n(End of file - total 652 lines)\n</content>",
    "title": "source/head/core/events/stream.go",
    "metadata": {
      "preview": "package events\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\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\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n\tclabtypes \"github.com/srl-labs/containerlab/types\"\n\tclabutils \"github.com/srl-labs/containerlab/utils\"\n)\n\n// Stream subscribes to the selected runtime and netlink sources and forwards",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/events/stream.go",
        "text": "package events\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\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\tclabruntime \"github.com/srl-labs/containerlab/runtime\"\n\tclabtypes \"github.com/srl-labs/containerlab/types\"\n\tclabutils \"github.com/srl-labs/containerlab/utils\"\n)\n\n// Stream subscribes to the selected runtime and netlink sources and forwards\n// aggregated events to the configured writer.\nfunc Stream(ctx context.Context, opts Options) error {\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\tclab, err := clabcore.NewContainerLab(opts.ClabOptions...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif clab.LabRuntime != nil {\n\t\treturn streamLabRuntimeEvents(ctx, clab, opts)\n\t}\n\n\truntime, ok := clab.Runtimes[opts.Runtime]\n\tif !ok {\n\t\treturn fmt.Errorf(\"runtime %q is not initialized\", opts.Runtime)\n\t}\n\n\tprinter, err := newFormatter(opts.Format, opts.writer())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\teventCh := make(chan aggregatedEvent, 128)\n\tregistry := newNetlinkRegistry(\n\t\tctx,\n\t\teventCh,\n\t\topts.IncludeInitialState,\n\t\topts.IncludeInterfaceStats,\n\t\topts.StatsInterval,\n\t)\n\n\tcontainers, err := clab.ListContainers(ctx, clabcore.WithListclabLabelExists())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to list containers: %w\", err)\n\t}\n\n\tif opts.IncludeInitialState {\n\t\tgo emitContainerSnapshots(ctx, containers, eventCh)\n\t}\n\n\tfor idx := range containers {\n\t\tcontainer := containers[idx]\n\t\tif !isRunningContainer(&container) {\n\t\t\tcontinue\n\t\t}\n\n\t\tregistry.Start(&container)\n\t}\n\n\tstreamOpts := clabruntime.EventStreamOptions{\n\t\tLabels: map[string]string{\n\t\t\tclabconstants.Containerlab: \"\",\n\t\t},\n\t}\n\n\truntimeEvents, runtimeErrs, err := runtime.StreamEvents(ctx, streamOpts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to stream events for runtime %q: %w\", opts.Runtime, err)\n\t}\n\n\terrCh := make(chan error, 1)\n\tgo forwardRuntimeEvents(ctx, runtime, registry, runtimeEvents, runtimeErrs, eventCh, errCh)\n\n\truntimeErrors := errCh\n\n\tfor {\n\t\tselect {\n\t\tcase ev := <-eventCh:\n\t\t\tif err := printer(ev); err != nil {\n\t\t\t\tlog.Debugf(\"failed to write event: %v\", err)\n\t\t\t}\n\t\tcase err, ok := <-runtimeErrors:\n\t\t\tif !ok {\n\t\t\t\truntimeErrors = nil\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err != nil && !errors.Is(err, context.Canceled) {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\nfunc streamLabRuntimeEvents(ctx context.Context, clab *clabcore.CLab, opts Options) error {\n\tprinter, err := newFormatter(opts.Format, opts.writer())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\truntimeEvents, runtimeErrs, err := clab.LabRuntime.StreamEvents(\n\t\tctx,\n\t\tlabRuntimeEventStreamRequest(clab.Config.Name, clab.LabRuntimeIdentity(), opts),\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to stream events for lab runtime %q: %w\", opts.Runtime, err)\n\t}\n\n\tfor runtimeEvents != nil || runtimeErrs != nil {\n\t\tselect {\n\t\tcase ev, ok := <-runtimeEvents:\n\t\t\tif !ok {\n\t\t\t\truntimeEvents = nil\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err := printer(aggregatedEventFromLabRuntimeEvent(clab, ev)); err != nil {\n\t\t\t\tlog.Debugf(\"failed to write event: %v\", err)\n\t\t\t}\n\t\tcase err, ok := <-runtimeErrs:\n\t\t\tif !ok {\n\t\t\t\truntimeErrs = nil\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err != nil && !errors.Is(err, context.Canceled) {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// labRuntimeEventStreamRequest scopes a lab runtime event stream. A selected lab (--topo or\n// --name) limits the stream to that lab in its namespace. Without one the stream covers every\n// namespace, unless a namespace override (--namespace, CLAB_KUBE_NAMESPACE) limits it to that\n// namespace; the runtime applies the override.\nfunc labRuntimeEventStreamRequest(\n\tlabName string,\n\tidentity clablabruntime.Identity,\n\topts Options,\n) clablabruntime.EventStreamRequest {\n\treturn clablabruntime.EventStreamRequest{\n\t\tName:                  labName,\n\t\tIdentity:              identity,\n\t\tAllNamespaces:         labName == \"\",\n\t\tIncludeInitialState:   opts.IncludeInitialState,\n\t\tIncludeInterfaceStats: opts.IncludeInterfaceStats,\n\t\tStatsInterval:         opts.StatsInterval,\n\t}\n}\n\n// aggregatedEventFromLabRuntimeEvent reports a lab runtime event with the attributes the\n// container runtimes' events have. A container event describes its node with the container\n// record inspect reports for it, the way a Docker event carries the container's labels: as a\n// snapshot like the snapshots of local containers, otherwise with the labels, image,\n// management addresses and ports a Docker event and its enrichment carry. An interface event\n// carries the attributes of the netlink interface events. The runtime's own attributes come on\n// top.\nfunc aggregatedEventFromLabRuntimeEvent(\n\tclab *clabcore.CLab,\n\tev clablabruntime.Event,\n) aggregatedEvent {\n\tts := ev.Timestamp\n\tif ts.IsZero() {\n\t\tts = time.Now()\n\t}\n\n\tvar attributes map[string]string\n\tswitch {\n\tcase ev.Type == clablabruntime.EventTypeContainer && ev.Lab != nil && ev.Node != nil &&\n\t\tclab != nil:\n\t\tcontainer := clab.LabRuntimeContainer(ev.Lab, *ev.Node)\n\t\tif ev.Attributes[\"origin\"] == clablabruntime.EventOriginSnapshot {\n\t\t\tattributes = aggregatedEventFromContainerSnapshot(&container).Attributes\n\t\t} else {\n\t\t\tattributes = containerAttributes(&container)\n\t\t}\n\tcase ev.Type == clablabruntime.EventTypeInterface && ev.Interface != nil:\n\t\tlab := ev.Attributes[\"lab\"]\n\t\tif ev.Lab != nil {\n\t\t\tlab = ev.Lab.Name\n\t\t}\n\t\tattributes = labRuntimeInterfaceAttributes(lab, ev.ActorName, ev.Interface)\n\t}\n\n\tfor key, value := range ev.Attributes {\n\t\tif attributes == nil {\n\t\t\tattributes = make(map[string]string, len(ev.Attributes))\n\t\t}\n\t\tattributes[key] = value\n\t}\n\n\treturn aggregatedEvent{\n\t\tTimestamp:   ts,\n\t\tType:        ev.Type,\n\t\tAction:      ev.Action,\n\t\tActorID:     ev.ActorID,\n\t\tActorName:   ev.ActorName,\n\t\tActorFullID: ev.ActorFullID,\n\t\tAttributes:  attributes,\n\t}\n}\n\n// containerAttributes are the attributes a container event reports for a container: its labels\n// and image, which Docker puts on every container event, and the management addresses and\n// ports the events command adds.\nfunc containerAttributes(container *clabruntime.GenericContainer) map[string]string {\n\tattributes := cloneStringMap(container.Labels)\n\tif attributes == nil {\n\t\tattributes = make(map[string]string)\n\t}\n\n\tif container.Image != \"\" {\n\t\tattributes[\"image\"] = container.Image\n\t}\n\n\tif container.NetworkSettings.IPv4addr != \"\" {\n\t\tattributes[\"mgmt_ipv4\"] = container.GetContainerIPv4()\n\t}\n\n\tif container.NetworkSettings.IPv6addr != \"\" {\n\t\tattributes[\"mgmt_ipv6\"] = container.GetContainerIPv6()\n\t}\n\n\tif ports := exposedPortsAttributeValue(container.Ports); ports != \"\" {\n\t\tattributes[\"ports\"] = ports\n\t}\n\n\treturn attributes\n}\n\nfunc forwardRuntimeEvents(\n\tctx context.Context,\n\truntime clabruntime.ContainerRuntime,\n\tregistry *netlinkRegistry,\n\truntimeEvents <-chan clabruntime.ContainerEvent,\n\truntimeErrs <-chan error,\n\teventSink chan<- aggregatedEvent,\n\terrSink chan<- error,\n) {\n\tdefer close(errSink)\n\n\tsendErr := func(err error) {\n\t\tselect {\n\t\tcase errSink <- err:\n\t\tcase <-ctx.Done():\n\t\t}\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase err, ok := <-runtimeErrs:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err != nil && !errors.Is(err, context.Canceled) {\n\t\t\t\tsendErr(err)\n\n\t\t\t\treturn\n\t\t\t}\n\t\tcase ev, ok := <-runtimeEvents:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tregistry.HandleContainerEvent(runtime, ev)\n\n\t\t\taggregated := aggregatedEventFromContainerEvent(ctx, runtime, ev)\n\t\t\tselect {\n\t\t\tcase eventSink <- aggregated:\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc aggregatedEventFromContainerEvent(\n\tctx context.Context,\n\truntime clabruntime.ContainerRuntime,\n\tev clabruntime.ContainerEvent,\n) aggregatedEvent {\n\tts := ev.Timestamp\n\tif ts.IsZero() {\n\t\tts = time.Now()\n\t}\n\n\tattributes := cloneStringMap(ev.Attributes)\n\n\tactorFullID := ev.ActorFullID\n\tif actorFullID == \"\" {\n\t\tactorFullID = ev.ActorID\n\t}\n\n\tactorName := ev.ActorName\n\tif actorName == \"\" && attributes != nil {\n\t\tactorName = attributes[\"name\"]\n\t}\n\n\tattributes = ensureContainerAttributes(ctx, runtime, attributes, actorFullID, actorName)\n\n\tshort := ev.ActorID\n\tif short == \"\" {\n\t\tshort = actorFullID\n\t}\n\n\taction := strings.ToLower(ev.Action)\n\tif action == \"\" {\n\t\taction = ev.Action\n\t}\n\n\teventType := strings.ToLower(ev.Type)\n\tif eventType == \"\" {\n\t\teventType = ev.Type\n\t}\n\n\treturn aggregatedEvent{\n\t\tTimestamp:   ts,\n\t\tType:        eventType,\n\t\tAction:      action,\n\t\tActorID:     clabutils.ShortID(short),\n\t\tActorName:   actorName,\n\t\tActorFullID: actorFullID,\n\t\tAttributes:  attributes,\n\t}\n}\n\nfunc ensureContainerAttributes(\n\tctx context.Context,\n\truntime clabruntime.ContainerRuntime,\n\tattributes map[string]string,\n\tactorFullID, actorName string,\n) map[string]string {\n\tif runtime == nil {\n\t\treturn attributes\n\t}\n\n\thasIPv4 := attributes != nil && attributes[\"mgmt_ipv4\"] != \"\"\n\thasIPv6 := attributes != nil && attributes[\"mgmt_ipv6\"] != \"\"\n\thasPorts := attributes != nil && attributes[\"ports\"] != \"\"\n\n\tif hasIPv4 && hasIPv6 && hasPorts {\n\t\treturn attributes\n\t}\n\n\tfilters := make([]*clabtypes.GenericFilter, 0, 2)\n\n\tif actorName == \"\" && attributes != nil {\n\t\tactorName = attributes[\"name\"]\n\t}\n\n\tif actorName != \"\" {\n\t\tfilters = append(filters, &clabtypes.GenericFilter{FilterType: \"name\", Match: actorName})\n\t}\n\n\tif actorFullID != \"\" {\n\t\tfilters = append(filters, &clabtypes.GenericFilter{FilterType: \"id\", Match: actorFullID})\n\t}\n\n\tif len(filters) == 0 {\n\t\treturn attributes\n\t}\n\n\tcontainers, err := runtime.ListContainers(ctx, filters)\n\tif err != nil {\n\t\tlog.Debugf(\"failed to resolve container for event: %v\", err)\n\n\t\treturn attributes\n\t}\n\n\tcontainer := selectContainerForEvent(containers, actorFullID, actorName)\n\tif container == nil {\n\t\treturn attributes\n\t}\n\n\tif attributes == nil {\n\t\tattributes = make(map[string]string)\n\t}\n\n\tif !hasIPv4 {\n\t\tif ipv4 := container.GetContainerIPv4(); ipv4 != \"\" && ipv4 != clabconstants.NotApplicable {\n\t\t\tattributes[\"mgmt_ipv4\"] = ipv4\n\t\t}\n\t}\n\n\tif !hasIPv6 {\n\t\tif ipv6 := container.GetContainerIPv6(); ipv6 != \"\" && ipv6 != clabconstants.NotApplicable {\n\t\t\tattributes[\"mgmt_ipv6\"] = ipv6\n\t\t}\n\t}\n\n\tif !hasPorts {\n\t\tif ports := exposedPortsAttributeValue(container.Ports); ports != \"\" {\n\t\t\tattributes[\"ports\"] = ports\n\t\t}\n\t}\n\n\tif len(attributes) == 0 {\n\t\treturn nil\n\t}\n\n\treturn attributes\n}\n\nfunc selectContainerForEvent(\n\tcontainers []clabruntime.GenericContainer,\n\tactorFullID, actorName string,\n) *clabruntime.GenericContainer {\n\tif len(containers) == 0 {\n\t\treturn nil\n\t}\n\n\tif actorFullID != \"\" {\n\t\tfor idx := range containers {\n\t\t\tcontainer := &containers[idx]\n\n\t\t\tswitch {\n\t\t\tcase container.ID == actorFullID:\n\t\t\t\treturn container\n\t\t\tcase strings.HasPrefix(container.ID, actorFullID):\n\t\t\t\treturn container\n\t\t\tcase container.ShortID == actorFullID:\n\t\t\t\treturn container\n\t\t\t}\n\t\t}\n\t}\n\n\tif actorName != \"\" {\n\t\tfor idx := range containers {\n\t\t\tcontainer := &containers[idx]\n\n\t\t\tfor _, name := range container.Names {\n\t\t\t\tif name == actorName {\n\t\t\t\t\treturn container\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &containers[0]\n}\n\nfunc emitContainerSnapshots(\n\tctx context.Context,\n\tcontainers []clabruntime.GenericContainer,\n\tsink chan<- aggregatedEvent,\n) {\n\tfor idx := range containers {\n\t\tcontainer := containers[idx]\n\t\tif !isRunningContainer(&container) && !strings.EqualFold(container.State, \"exited\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tevent := aggregatedEventFromContainerSnapshot(&container)\n\t\tif event.ActorID == \"\" && event.ActorName == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tselect {\n\t\tcase sink <- event:\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc aggregatedEventFromContainerSnapshot(\n\tcontainer *clabruntime.GenericContainer,\n) aggregatedEvent {\n\tif container == nil {\n\t\treturn aggregatedEvent{}\n\t}\n\n\tstate := strings.ToLower(container.State)\n\n\tshort := container.ShortID\n\tif short == \"\" {\n\t\tshort = clabutils.ShortID(container.ID)\n\t}\n\n\tattributes := containerAttributes(container)\n\n\tif _, ok := attributes[\"origin\"]; !ok {\n\t\tattributes[\"origin\"] = \"snapshot\"\n\t}\n\n\tif container.Status != \"\" {\n\t\tattributes[\"status\"] = container.Status\n\t}\n\n\tif state != \"\" {\n\t\tattributes[\"state\"] = state\n\t}\n\n\tif container.NetworkName != \"\" {\n\t\tattributes[\"network\"] = container.NetworkName\n\t}\n\n\tif len(attributes) == 0 {\n\t\tattributes = nil\n\t}\n\n\tactorName := firstContainerName(container)\n\n\taction := state\n\tif action == \"\" {\n\t\taction = \"snapshot\"\n\t}\n\n\treturn aggregatedEvent{\n\t\tTimestamp:   time.Now(),\n\t\tType:        \"container\",\n\t\tAction:      action,\n\t\tActorID:     clabutils.ShortID(short),\n\t\tActorName:   actorName,\n\t\tActorFullID: container.ID,\n\t\tAttributes:  attributes,\n\t}\n}\n\nfunc cloneStringMap(input map[string]string) map[string]string {\n\tif len(input) == 0 {\n\t\treturn nil\n\t}\n\n\tresult := make(map[string]string, len(input))\n\tfor k, v := range input {\n\t\tresult[k] = v\n\t}\n\n\treturn result\n}\n\nfunc isRunningContainer(container *clabruntime.GenericContainer) bool {\n\tif container == nil {\n\t\treturn false\n\t}\n\n\treturn strings.EqualFold(container.State, \"running\")\n}\n\nfunc exposedPortsAttributeValue(ports []*clabtypes.GenericPortBinding) string {\n\tif len(ports) == 0 {\n\t\treturn \"\"\n\t}\n\n\tsortedPorts := make([]*clabtypes.GenericPortBinding, 0, len(ports))\n\tfor idx := range ports {\n\t\tif ports[idx] != nil {\n\t\t\tsortedPorts = append(sortedPorts, ports[idx])\n\t\t}\n\t}\n\n\tif len(sortedPorts) == 0 {\n\t\treturn \"\"\n\t}\n\n\tsort.Slice(sortedPorts, func(i, j int) bool {\n\t\tleft := sortedPorts[i]\n\t\tright := sortedPorts[j]\n\n\t\tswitch {\n\t\tcase left.ContainerPort != right.ContainerPort:\n\t\t\treturn left.ContainerPort < right.ContainerPort\n\t\tcase left.Protocol != right.Protocol:\n\t\t\treturn left.Protocol < right.Protocol\n\t\tcase left.HostPort != right.HostPort:\n\t\t\treturn left.HostPort < right.HostPort\n\t\tdefault:\n\t\t\treturn left.HostIP < right.HostIP\n\t\t}\n\t})\n\n\tresult := make([]string, 0, len(sortedPorts))\n\tfor idx := range sortedPorts {\n\t\tformatted := formatExposedPort(sortedPorts[idx])\n\t\tif formatted != \"\" {\n\t\t\tresult = append(result, formatted)\n\t\t}\n\t}\n\n\tif len(result) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn strings.Join(result, \";\")\n}\n\nfunc formatExposedPort(port *clabtypes.GenericPortBinding) string {\n\tif port == nil {\n\t\treturn \"\"\n\t}\n\n\tproto := strings.TrimSpace(strings.ToLower(port.Protocol))\n\tprotoSuffix := \"\"\n\tif proto != \"\" {\n\t\tprotoSuffix = \"/\" + proto\n\t}\n\n\tif port.HostPort > 0 {\n\t\thostIP := port.HostIP\n\t\tif hostIP == \"\" {\n\t\t\thostIP = \"0.0.0.0\"\n\t\t}\n\n\t\tif strings.Contains(hostIP, \":\") {\n\t\t\thostIP = fmt.Sprintf(\"[%s]\", hostIP)\n\t\t}\n\n\t\tif port.ContainerPort > 0 {\n\t\t\treturn fmt.Sprintf(\n\t\t\t\t\"%s:%d%s->%d\",\n\t\t\t\thostIP,\n\t\t\t\tport.HostPort,\n\t\t\t\tprotoSuffix,\n\t\t\t\tport.ContainerPort,\n\t\t\t)\n\t\t}\n\n\t\treturn fmt.Sprintf(\"%s:%d%s\", hostIP, port.HostPort, protoSuffix)\n\t}\n\n\tif port.ContainerPort <= 0 {\n\t\treturn \"\"\n\t}\n\n\treturn fmt.Sprintf(\"%d%s\", port.ContainerPort, protoSuffix)\n}",
        "lineStart": 1,
        "lineEnd": 652,
        "totalLines": 652,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525741074,
      "end": 1793525741092
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19676f627001sQ4N1kZQsn7SE9",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19676eda7001heIxLWb0fV1IsA",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 7197,
    "input": 4116,
    "output": 58,
    "reasoning": 79,
    "cache": {
      "read": 2944,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19676eda7001heIxLWb0fV1IsA",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525738919,
    "completed": 1793525741098
  },
  "parentID": "msg_19676df9500159h7P3dGcuBxjO",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 7197,
    "input": 4116,
    "output": 58,
    "reasoning": 79,
    "cache": {
      "read": 2944,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 14
step-start
{
  "type": "step-start",
  "id": "prt_19676fd2e001qY4j2n11ZVWvma",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19676f630001k5K3RVrcoGt3VU"
}
Reasoning
stream.go looks fine. The errs chan concern I had earlier — in the base stream.go the errs channel comes from runtime.StreamEvents; here `errCh` buffered 1 and forwardRuntimeEvents closes it. Fine.

Note: `streamLabRuntimeEvents` relies on `runtimeErrs` channel semantics; need to check clabernetes `StreamEvents` implementation in `events.go` for errs chan sizing and error-goroutine count.

Next: read netlink.go head (the interface attributes part), labruntime.go (containerFromLabNode etc.), and clabernetes events.go + container_events.go + iface_stats.go. Let me batch reads.
`stream.go` is clean. Now the core clabernetes files: `events.go`, `container_events.go`, `iface_stats.go`, plus `core/labruntime.go`.
read · completed

Input

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

Output

<path>/source/head/labruntime/clabernetes/events.go</path>
<type>file</type>
<content>
1: package clabernetes
2: 
3: import (
4: 	"context"
5: 	"errors"
6: 	"fmt"
7: 	"strings"
8: 	"time"
9: 
10: 	"github.com/charmbracelet/log"
11: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
12: 	corev1 "k8s.io/api/core/v1"
13: 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
14: 	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
15: 	"k8s.io/apimachinery/pkg/fields"
16: 	"k8s.io/apimachinery/pkg/labels"
17: 	"k8s.io/apimachinery/pkg/watch"
18: )
19: 
20: func (r *Runtime) StreamEvents(
21: 	ctx context.Context,
22: 	req clablabruntime.EventStreamRequest,
23: ) (<-chan clablabruntime.Event, <-chan error, error) {
24: 	r, connErr := r.connect(ctx, req.Identity)
25: 	if connErr != nil {
26: 		return nil, nil, connErr
27: 	}
28: 
29: 	scope, err := r.eventScopeFor(req)
30: 	if err != nil {
31: 		return nil, nil, err
32: 	}
33: 
34: 	events := make(chan clablabruntime.Event, 128)
35: 	errs := make(chan error, 4)
36: 	// changed carries the labs whose Topology, Nodes or pods changed; the container tracker
37: 	// reads them again and reports what changed for their nodes.
38: 	changed := make(chan labRef, 256)
39: 
40: 	go r.trackContainers(ctx, scope, req.IncludeInitialState, changed, events, errs)
41: 
42: 	// Interface state events are always reported, like the netlink-backed events of the local
43: 	// runtimes; statistics only on request. Both come from the same exec per node.
44: 	go r.pollInterfaces(ctx, scope, interfacePollOptions{
45: 		interval:            req.StatsInterval,
46: 		includeStats:        req.IncludeInterfaceStats,
47: 		includeInitialState: req.IncludeInitialState,
48: 	}, events)
49: 
50: 	go r.watchTopologies(ctx, scope, changed, events, errs)
51: 	go r.watchNodes(ctx, scope, changed, errs)
52: 	go r.watchPods(ctx, scope, changed, errs)
53: 
54: 	return events, errs, nil
55: }
56: 
57: // labRef names a lab in a namespace.
58: type labRef struct {
59: 	namespace string
60: 	lab       string
61: }
62: 
63: func sendChangedLab(ctx context.Context, changed chan<- labRef, ref labRef) {
64: 	if ref.lab == "" {
65: 		return
66: 	}
67: 
68: 	select {
69: 	case changed <- ref:
70: 	case <-ctx.Done():
71: 	}
72: }
73: 
74: // eventScope is the namespace and, optionally, the single lab an event stream covers.
75: type eventScope struct {
76: 	namespace string
77: 	lab       string
78: }
79: 
80: func (r *Runtime) eventScopeFor(req clablabruntime.EventStreamRequest) (eventScope, error) {
81: 	if req.Name != "" {
82: 		namespace, err := r.namespaceForLab(req.Name, req.Namespace)
83: 		if err != nil {
84: 			return eventScope{}, err
85: 		}
86: 
87: 		return eventScope{namespace: namespace, lab: req.Name}, nil
88: 	}
89: 
90: 	return eventScope{namespace: r.listNamespace(req.Namespace, req.AllNamespaces)}, nil
91: }
92: 
93: // labelSelector selects the lab-owned resources of the scope.
94: func (s eventScope) labelSelector() string {
95: 	if s.lab != "" {
96: 		return labels.Set{labelTopologyOwner: s.lab}.String()
97: 	}
98: 
99: 	return labelTopologyOwner
100: }
101: 
102: // topologyListOptions selects the Topology resources of the scope.
103: func (s eventScope) topologyListOptions() metav1.ListOptions {
104: 	if s.lab != "" {
105: 		return metav1.ListOptions{
106: 			FieldSelector: fields.OneTermEqualSelector("metadata.name", s.lab).String(),
107: 		}
108: 	}
109: 
110: 	return metav1.ListOptions{}
111: }
112: 
113: // labStates lists the labs of the scope.
114: func (r *Runtime) labStates(
115: 	ctx context.Context,
116: 	scope eventScope,
117: ) ([]*clablabruntime.LabState, error) {
118: 	if scope.lab != "" {
119: 		state, err := r.Inspect(ctx, clablabruntime.InspectRequest{
120: 			Name:      scope.lab,
121: 			Namespace: scope.namespace,
122: 		})
123: 		if err != nil {
124: 			// A lab that is not deployed yet has no state; its resources show up through
125: 			// the watches once it is.
126: 			var notFound *labNotFoundError
127: 			if errors.As(err, &notFound) {
128: 				return nil, nil
129: 			}
130: 
131: 			return nil, err
132: 		}
133: 
134: 		return []*clablabruntime.LabState{state}, nil
135: 	}
136: 
137: 	return r.List(ctx, clablabruntime.ListRequest{
138: 		Namespace:     scope.namespace,
139: 		AllNamespaces: scope.namespace == metav1.NamespaceAll,
140: 	})
141: }
142: 
143: func (r *Runtime) watchNodes(
144: 	ctx context.Context,
145: 	scope eventScope,
146: 	changed chan<- labRef,
147: 	errSink chan<- error,
148: ) {
149: 	resource := r.client.Resource(nodeGVR).Namespace(scope.namespace)
150: 
151: 	for {
152: 		watcher, err := resource.Watch(ctx, metav1.ListOptions{
153: 			LabelSelector: scope.labelSelector(),
154: 		})
155: 		if err != nil {
156: 			if ctx.Err() != nil {
157: 				return
158: 			}
159: 
160: 			sendEventError(ctx, errSink, fmt.Errorf("failed to watch c9s nodes: %w", err))
161: 			return
162: 		}
163: 
164: 		if !r.forwardNodeWatch(ctx, watcher, changed, errSink) {
165: 			return
166: 		}
167: 
168: 		if !sleepContext(ctx, pollInterval) {
169: 			return
170: 		}
171: 	}
172: }
173: 
174: // forwardNodeWatch reports the lab of every changed Node to the container tracker.
175: func (r *Runtime) forwardNodeWatch(
176: 	ctx context.Context,
177: 	watcher watch.Interface,
178: 	changed chan<- labRef,
179: 	errSink chan<- error,
180: ) bool {
181: 	defer watcher.Stop()
182: 
183: 	for {
184: 		select {
185: 		case <-ctx.Done():
186: 			return false
187: 		case ev, ok := <-watcher.ResultChan():
188: 			if !ok {
189: 				log.Debug("c9s node watch closed, reconnecting")
190: 				return true
191: 			}
192: 			if ev.Type == watch.Error {
193: 				sendEventError(ctx, errSink, fmt.Errorf("c9s node watch returned an error"))
194: 				return false
195: 			}
196: 
197: 			node, ok := ev.Object.(*unstructured.Unstructured)
198: 			if !ok {
199: 				continue
200: 			}
201: 
202: 			sendChangedLab(ctx, changed, labRef{
203: 				namespace: node.GetNamespace(),
204: 				lab:       node.GetLabels()[labelTopologyOwner],
205: 			})
206: 		}
207: 	}
208: }
209: 
210: func (r *Runtime) watchTopologies(
211: 	ctx context.Context,
212: 	scope eventScope,
213: 	changed chan<- labRef,
214: 	eventSink chan<- clablabruntime.Event,
215: 	errSink chan<- error,
216: ) {
217: 	resource := r.client.Resource(topologyGVR).Namespace(scope.namespace)
218: 
219: 	for {
220: 		watcher, err := resource.Watch(ctx, scope.topologyListOptions())
221: 		if err != nil {
222: 			if ctx.Err() != nil {
223: 				return
224: 			}
225: 
226: 			sendEventError(
227: 				ctx,
228: 				errSink,
229: 				fmt.Errorf("failed to watch clabernetes topologies: %w", err),
230: 			)
231: 			return
232: 		}
233: 
234: 		if !r.forwardTopologyWatch(ctx, scope.namespace, watcher, changed, eventSink, errSink) {
235: 			return
236: 		}
237: 
238: 		if !sleepContext(ctx, pollInterval) {
239: 			return
240: 		}
241: 	}
242: }
243: 
244: // forwardTopologyWatch reports Topology changes as topology events, which only c9s has, and
245: // reports the lab to the container tracker.
246: func (r *Runtime) forwardTopologyWatch(
247: 	ctx context.Context,
248: 	namespace string,
249: 	watcher watch.Interface,
250: 	changed chan<- labRef,
251: 	eventSink chan<- clablabruntime.Event,
252: 	errSink chan<- error,
253: ) bool {
254: 	defer watcher.Stop()
255: 
256: 	for {
257: 		select {
258: 		case <-ctx.Done():
259: 			return false
260: 		case ev, ok := <-watcher.ResultChan():
261: 			if !ok {
262: 				log.Debug("C9s topology watch closed, reconnecting")
263: 				return true
264: 			}
265: 			if ev.Type == watch.Error {
266: 				sendEventError(
267: 					ctx,
268: 					errSink,
269: 					fmt.Errorf("clabernetes topology watch returned an error"),
270: 				)
271: 				return false
272: 			}
273: 
274: 			obj, ok := ev.Object.(*unstructured.Unstructured)
275: 			if !ok {
276: 				continue
277: 			}
278: 
279: 			state := stateFromTopology(obj, namespace)
280: 			r.sendEvent(ctx, eventSink, clablabruntime.Event{
281: 				Timestamp: time.Now(),
282: 				Type:      "topology",
283: 				Action:    strings.ToLower(string(ev.Type)),
284: 				ActorID:   fmt.Sprintf("%s/%s", state.Namespace, state.Name),
285: 				ActorName: state.Name,
286: 				Attributes: map[string]string{
287: 					"namespace": state.Namespace,
288: 					"lab":       state.Name,
289: 					"state":     state.State,
290: 					"ready":     fmt.Sprintf("%t", state.Ready),
291: 				},
292: 			})
293: 			sendChangedLab(ctx, changed, labRef{namespace: state.Namespace, lab: state.Name})
294: 		}
295: 	}
296: }
297: 
298: func (r *Runtime) watchPods(
299: 	ctx context.Context,
300: 	scope eventScope,
301: 	changed chan<- labRef,
302: 	errSink chan<- error,
303: ) {
304: 	for {
305: 		watcher, err := r.kubeClient.CoreV1().Pods(scope.namespace).Watch(ctx, metav1.ListOptions{
306: 			LabelSelector: scope.labelSelector(),
307: 		})
308: 		if err != nil {
309: 			if ctx.Err() != nil {
310: 				return
311: 			}
312: 
313: 			sendEventError(ctx, errSink, fmt.Errorf(
314: 				"failed to watch clabernetes pods: %w", err))
315: 			return
316: 		}
317: 
318: 		if !r.forwardPodWatch(ctx, watcher, changed, errSink) {
319: 			return
320: 		}
321: 
322: 		if !sleepContext(ctx, pollInterval) {
323: 			return
324: 		}
325: 	}
326: }
327: 
328: // forwardPodWatch reports the lab of every changed pod to the container tracker.
329: func (r *Runtime) forwardPodWatch(
330: 	ctx context.Context,
331: 	watcher watch.Interface,
332: 	changed chan<- labRef,
333: 	errSink chan<- error,
334: ) bool {
335: 	defer watcher.Stop()
336: 
337: 	for {
338: 		select {
339: 		case <-ctx.Done():
340: 			return false
341: 		case ev, ok := <-watcher.ResultChan():
342: 			if !ok {
343: 				log.Debug("C9s pod watch closed, reconnecting")
344: 				return true
345: 			}
346: 			if ev.Type == watch.Error {
347: 				sendEventError(ctx, errSink, fmt.Errorf(
348: 					"clabernetes pod watch returned an error"))
349: 				return false
350: 			}
351: 
352: 			pod, ok := ev.Object.(*corev1.Pod)
353: 			if !ok {
354: 				continue
355: 			}
356: 
357: 			sendChangedLab(ctx, changed, labRef{
358: 				namespace: pod.Namespace,
359: 				lab:       pod.Labels[labelTopologyOwner],
360: 			})
361: 		}
362: 	}
363: }
364: 
365: func sleepContext(ctx context.Context, d time.Duration) bool {
366: 	timer := time.NewTimer(d)
367: 	defer timer.Stop()
368: 
369: 	select {
370: 	case <-timer.C:
371: 		return true
372: 	case <-ctx.Done():
373: 		return false
374: 	}
375: }
376: 
377: func (r *Runtime) sendEvent(
378: 	ctx context.Context,
379: 	eventSink chan<- clablabruntime.Event,
380: 	event clablabruntime.Event,
381: ) {
382: 	select {
383: 	case eventSink <- event:
384: 	case <-ctx.Done():
385: 	}
386: }
387: 
388: func sendEventError(ctx context.Context, errSink chan<- error, err error) {
389: 	select {
390: 	case errSink <- err:
391: 	case <-ctx.Done():
392: 	}
393: }

(End of file - total 393 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196770804001yBfUy3CTO78VGC",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19676f630001k5K3RVrcoGt3VU",
  "callID": "call_f3ba3945202d4e1a962cf53b",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/events.go"
    },
    "output": "<path>/source/head/labruntime/clabernetes/events.go</path>\n<type>file</type>\n<content>\n1: package clabernetes\n2: \n3: import (\n4: \t\"context\"\n5: \t\"errors\"\n6: \t\"fmt\"\n7: \t\"strings\"\n8: \t\"time\"\n9: \n10: \t\"github.com/charmbracelet/log\"\n11: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n12: \tcorev1 \"k8s.io/api/core/v1\"\n13: \tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n14: \t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n15: \t\"k8s.io/apimachinery/pkg/fields\"\n16: \t\"k8s.io/apimachinery/pkg/labels\"\n17: \t\"k8s.io/apimachinery/pkg/watch\"\n18: )\n19: \n20: func (r *Runtime) StreamEvents(\n21: \tctx context.Context,\n22: \treq clablabruntime.EventStreamRequest,\n23: ) (<-chan clablabruntime.Event, <-chan error, error) {\n24: \tr, connErr := r.connect(ctx, req.Identity)\n25: \tif connErr != nil {\n26: \t\treturn nil, nil, connErr\n27: \t}\n28: \n29: \tscope, err := r.eventScopeFor(req)\n30: \tif err != nil {\n31: \t\treturn nil, nil, err\n32: \t}\n33: \n34: \tevents := make(chan clablabruntime.Event, 128)\n35: \terrs := make(chan error, 4)\n36: \t// changed carries the labs whose Topology, Nodes or pods changed; the container tracker\n37: \t// reads them again and reports what changed for their nodes.\n38: \tchanged := make(chan labRef, 256)\n39: \n40: \tgo r.trackContainers(ctx, scope, req.IncludeInitialState, changed, events, errs)\n41: \n42: \t// Interface state events are always reported, like the netlink-backed events of the local\n43: \t// runtimes; statistics only on request. Both come from the same exec per node.\n44: \tgo r.pollInterfaces(ctx, scope, interfacePollOptions{\n45: \t\tinterval:            req.StatsInterval,\n46: \t\tincludeStats:        req.IncludeInterfaceStats,\n47: \t\tincludeInitialState: req.IncludeInitialState,\n48: \t}, events)\n49: \n50: \tgo r.watchTopologies(ctx, scope, changed, events, errs)\n51: \tgo r.watchNodes(ctx, scope, changed, errs)\n52: \tgo r.watchPods(ctx, scope, changed, errs)\n53: \n54: \treturn events, errs, nil\n55: }\n56: \n57: // labRef names a lab in a namespace.\n58: type labRef struct {\n59: \tnamespace string\n60: \tlab       string\n61: }\n62: \n63: func sendChangedLab(ctx context.Context, changed chan<- labRef, ref labRef) {\n64: \tif ref.lab == \"\" {\n65: \t\treturn\n66: \t}\n67: \n68: \tselect {\n69: \tcase changed <- ref:\n70: \tcase <-ctx.Done():\n71: \t}\n72: }\n73: \n74: // eventScope is the namespace and, optionally, the single lab an event stream covers.\n75: type eventScope struct {\n76: \tnamespace string\n77: \tlab       string\n78: }\n79: \n80: func (r *Runtime) eventScopeFor(req clablabruntime.EventStreamRequest) (eventScope, error) {\n81: \tif req.Name != \"\" {\n82: \t\tnamespace, err := r.namespaceForLab(req.Name, req.Namespace)\n83: \t\tif err != nil {\n84: \t\t\treturn eventScope{}, err\n85: \t\t}\n86: \n87: \t\treturn eventScope{namespace: namespace, lab: req.Name}, nil\n88: \t}\n89: \n90: \treturn eventScope{namespace: r.listNamespace(req.Namespace, req.AllNamespaces)}, nil\n91: }\n92: \n93: // labelSelector selects the lab-owned resources of the scope.\n94: func (s eventScope) labelSelector() string {\n95: \tif s.lab != \"\" {\n96: \t\treturn labels.Set{labelTopologyOwner: s.lab}.String()\n97: \t}\n98: \n99: \treturn labelTopologyOwner\n100: }\n101: \n102: // topologyListOptions selects the Topology resources of the scope.\n103: func (s eventScope) topologyListOptions() metav1.ListOptions {\n104: \tif s.lab != \"\" {\n105: \t\treturn metav1.ListOptions{\n106: \t\t\tFieldSelector: fields.OneTermEqualSelector(\"metadata.name\", s.lab).String(),\n107: \t\t}\n108: \t}\n109: \n110: \treturn metav1.ListOptions{}\n111: }\n112: \n113: // labStates lists the labs of the scope.\n114: func (r *Runtime) labStates(\n115: \tctx context.Context,\n116: \tscope eventScope,\n117: ) ([]*clablabruntime.LabState, error) {\n118: \tif scope.lab != \"\" {\n119: \t\tstate, err := r.Inspect(ctx, clablabruntime.InspectRequest{\n120: \t\t\tName:      scope.lab,\n121: \t\t\tNamespace: scope.namespace,\n122: \t\t})\n123: \t\tif err != nil {\n124: \t\t\t// A lab that is not deployed yet has no state; its resources show up through\n125: \t\t\t// the watches once it is.\n126: \t\t\tvar notFound *labNotFoundError\n127: \t\t\tif errors.As(err, &notFound) {\n128: \t\t\t\treturn nil, nil\n129: \t\t\t}\n130: \n131: \t\t\treturn nil, err\n132: \t\t}\n133: \n134: \t\treturn []*clablabruntime.LabState{state}, nil\n135: \t}\n136: \n137: \treturn r.List(ctx, clablabruntime.ListRequest{\n138: \t\tNamespace:     scope.namespace,\n139: \t\tAllNamespaces: scope.namespace == metav1.NamespaceAll,\n140: \t})\n141: }\n142: \n143: func (r *Runtime) watchNodes(\n144: \tctx context.Context,\n145: \tscope eventScope,\n146: \tchanged chan<- labRef,\n147: \terrSink chan<- error,\n148: ) {\n149: \tresource := r.client.Resource(nodeGVR).Namespace(scope.namespace)\n150: \n151: \tfor {\n152: \t\twatcher, err := resource.Watch(ctx, metav1.ListOptions{\n153: \t\t\tLabelSelector: scope.labelSelector(),\n154: \t\t})\n155: \t\tif err != nil {\n156: \t\t\tif ctx.Err() != nil {\n157: \t\t\t\treturn\n158: \t\t\t}\n159: \n160: \t\t\tsendEventError(ctx, errSink, fmt.Errorf(\"failed to watch c9s nodes: %w\", err))\n161: \t\t\treturn\n162: \t\t}\n163: \n164: \t\tif !r.forwardNodeWatch(ctx, watcher, changed, errSink) {\n165: \t\t\treturn\n166: \t\t}\n167: \n168: \t\tif !sleepContext(ctx, pollInterval) {\n169: \t\t\treturn\n170: \t\t}\n171: \t}\n172: }\n173: \n174: // forwardNodeWatch reports the lab of every changed Node to the container tracker.\n175: func (r *Runtime) forwardNodeWatch(\n176: \tctx context.Context,\n177: \twatcher watch.Interface,\n178: \tchanged chan<- labRef,\n179: \terrSink chan<- error,\n180: ) bool {\n181: \tdefer watcher.Stop()\n182: \n183: \tfor {\n184: \t\tselect {\n185: \t\tcase <-ctx.Done():\n186: \t\t\treturn false\n187: \t\tcase ev, ok := <-watcher.ResultChan():\n188: \t\t\tif !ok {\n189: \t\t\t\tlog.Debug(\"c9s node watch closed, reconnecting\")\n190: \t\t\t\treturn true\n191: \t\t\t}\n192: \t\t\tif ev.Type == watch.Error {\n193: \t\t\t\tsendEventError(ctx, errSink, fmt.Errorf(\"c9s node watch returned an error\"))\n194: \t\t\t\treturn false\n195: \t\t\t}\n196: \n197: \t\t\tnode, ok := ev.Object.(*unstructured.Unstructured)\n198: \t\t\tif !ok {\n199: \t\t\t\tcontinue\n200: \t\t\t}\n201: \n202: \t\t\tsendChangedLab(ctx, changed, labRef{\n203: \t\t\t\tnamespace: node.GetNamespace(),\n204: \t\t\t\tlab:       node.GetLabels()[labelTopologyOwner],\n205: \t\t\t})\n206: \t\t}\n207: \t}\n208: }\n209: \n210: func (r *Runtime) watchTopologies(\n211: \tctx context.Context,\n212: \tscope eventScope,\n213: \tchanged chan<- labRef,\n214: \teventSink chan<- clablabruntime.Event,\n215: \terrSink chan<- error,\n216: ) {\n217: \tresource := r.client.Resource(topologyGVR).Namespace(scope.namespace)\n218: \n219: \tfor {\n220: \t\twatcher, err := resource.Watch(ctx, scope.topologyListOptions())\n221: \t\tif err != nil {\n222: \t\t\tif ctx.Err() != nil {\n223: \t\t\t\treturn\n224: \t\t\t}\n225: \n226: \t\t\tsendEventError(\n227: \t\t\t\tctx,\n228: \t\t\t\terrSink,\n229: \t\t\t\tfmt.Errorf(\"failed to watch clabernetes topologies: %w\", err),\n230: \t\t\t)\n231: \t\t\treturn\n232: \t\t}\n233: \n234: \t\tif !r.forwardTopologyWatch(ctx, scope.namespace, watcher, changed, eventSink, errSink) {\n235: \t\t\treturn\n236: \t\t}\n237: \n238: \t\tif !sleepContext(ctx, pollInterval) {\n239: \t\t\treturn\n240: \t\t}\n241: \t}\n242: }\n243: \n244: // forwardTopologyWatch reports Topology changes as topology events, which only c9s has, and\n245: // reports the lab to the container tracker.\n246: func (r *Runtime) forwardTopologyWatch(\n247: \tctx context.Context,\n248: \tnamespace string,\n249: \twatcher watch.Interface,\n250: \tchanged chan<- labRef,\n251: \teventSink chan<- clablabruntime.Event,\n252: \terrSink chan<- error,\n253: ) bool {\n254: \tdefer watcher.Stop()\n255: \n256: \tfor {\n257: \t\tselect {\n258: \t\tcase <-ctx.Done():\n259: \t\t\treturn false\n260: \t\tcase ev, ok := <-watcher.ResultChan():\n261: \t\t\tif !ok {\n262: \t\t\t\tlog.Debug(\"C9s topology watch closed, reconnecting\")\n263: \t\t\t\treturn true\n264: \t\t\t}\n265: \t\t\tif ev.Type == watch.Error {\n266: \t\t\t\tsendEventError(\n267: \t\t\t\t\tctx,\n268: \t\t\t\t\terrSink,\n269: \t\t\t\t\tfmt.Errorf(\"clabernetes topology watch returned an error\"),\n270: \t\t\t\t)\n271: \t\t\t\treturn false\n272: \t\t\t}\n273: \n274: \t\t\tobj, ok := ev.Object.(*unstructured.Unstructured)\n275: \t\t\tif !ok {\n276: \t\t\t\tcontinue\n277: \t\t\t}\n278: \n279: \t\t\tstate := stateFromTopology(obj, namespace)\n280: \t\t\tr.sendEvent(ctx, eventSink, clablabruntime.Event{\n281: \t\t\t\tTimestamp: time.Now(),\n282: \t\t\t\tType:      \"topology\",\n283: \t\t\t\tAction:    strings.ToLower(string(ev.Type)),\n284: \t\t\t\tActorID:   fmt.Sprintf(\"%s/%s\", state.Namespace, state.Name),\n285: \t\t\t\tActorName: state.Name,\n286: \t\t\t\tAttributes: map[string]string{\n287: \t\t\t\t\t\"namespace\": state.Namespace,\n288: \t\t\t\t\t\"lab\":       state.Name,\n289: \t\t\t\t\t\"state\":     state.State,\n290: \t\t\t\t\t\"ready\":     fmt.Sprintf(\"%t\", state.Ready),\n291: \t\t\t\t},\n292: \t\t\t})\n293: \t\t\tsendChangedLab(ctx, changed, labRef{namespace: state.Namespace, lab: state.Name})\n294: \t\t}\n295: \t}\n296: }\n297: \n298: func (r *Runtime) watchPods(\n299: \tctx context.Context,\n300: \tscope eventScope,\n301: \tchanged chan<- labRef,\n302: \terrSink chan<- error,\n303: ) {\n304: \tfor {\n305: \t\twatcher, err := r.kubeClient.CoreV1().Pods(scope.namespace).Watch(ctx, metav1.ListOptions{\n306: \t\t\tLabelSelector: scope.labelSelector(),\n307: \t\t})\n308: \t\tif err != nil {\n309: \t\t\tif ctx.Err() != nil {\n310: \t\t\t\treturn\n311: \t\t\t}\n312: \n313: \t\t\tsendEventError(ctx, errSink, fmt.Errorf(\n314: \t\t\t\t\"failed to watch clabernetes pods: %w\", err))\n315: \t\t\treturn\n316: \t\t}\n317: \n318: \t\tif !r.forwardPodWatch(ctx, watcher, changed, errSink) {\n319: \t\t\treturn\n320: \t\t}\n321: \n322: \t\tif !sleepContext(ctx, pollInterval) {\n323: \t\t\treturn\n324: \t\t}\n325: \t}\n326: }\n327: \n328: // forwardPodWatch reports the lab of every changed pod to the container tracker.\n329: func (r *Runtime) forwardPodWatch(\n330: \tctx context.Context,\n331: \twatcher watch.Interface,\n332: \tchanged chan<- labRef,\n333: \terrSink chan<- error,\n334: ) bool {\n335: \tdefer watcher.Stop()\n336: \n337: \tfor {\n338: \t\tselect {\n339: \t\tcase <-ctx.Done():\n340: \t\t\treturn false\n341: \t\tcase ev, ok := <-watcher.ResultChan():\n342: \t\t\tif !ok {\n343: \t\t\t\tlog.Debug(\"C9s pod watch closed, reconnecting\")\n344: \t\t\t\treturn true\n345: \t\t\t}\n346: \t\t\tif ev.Type == watch.Error {\n347: \t\t\t\tsendEventError(ctx, errSink, fmt.Errorf(\n348: \t\t\t\t\t\"clabernetes pod watch returned an error\"))\n349: \t\t\t\treturn false\n350: \t\t\t}\n351: \n352: \t\t\tpod, ok := ev.Object.(*corev1.Pod)\n353: \t\t\tif !ok {\n354: \t\t\t\tcontinue\n355: \t\t\t}\n356: \n357: \t\t\tsendChangedLab(ctx, changed, labRef{\n358: \t\t\t\tnamespace: pod.Namespace,\n359: \t\t\t\tlab:       pod.Labels[labelTopologyOwner],\n360: \t\t\t})\n361: \t\t}\n362: \t}\n363: }\n364: \n365: func sleepContext(ctx context.Context, d time.Duration) bool {\n366: \ttimer := time.NewTimer(d)\n367: \tdefer timer.Stop()\n368: \n369: \tselect {\n370: \tcase <-timer.C:\n371: \t\treturn true\n372: \tcase <-ctx.Done():\n373: \t\treturn false\n374: \t}\n375: }\n376: \n377: func (r *Runtime) sendEvent(\n378: \tctx context.Context,\n379: \teventSink chan<- clablabruntime.Event,\n380: \tevent clablabruntime.Event,\n381: ) {\n382: \tselect {\n383: \tcase eventSink <- event:\n384: \tcase <-ctx.Done():\n385: \t}\n386: }\n387: \n388: func sendEventError(ctx context.Context, errSink chan<- error, err error) {\n389: \tselect {\n390: \tcase errSink <- err:\n391: \tcase <-ctx.Done():\n392: \t}\n393: }\n\n(End of file - total 393 lines)\n</content>",
    "title": "source/head/labruntime/clabernetes/events.go",
    "metadata": {
      "preview": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\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\t\"k8s.io/apimachinery/pkg/fields\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/apimachinery/pkg/watch\"\n)\n\nfunc (r *Runtime) StreamEvents(",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/events.go",
        "text": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\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\t\"k8s.io/apimachinery/pkg/fields\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/apimachinery/pkg/watch\"\n)\n\nfunc (r *Runtime) StreamEvents(\n\tctx context.Context,\n\treq clablabruntime.EventStreamRequest,\n) (<-chan clablabruntime.Event, <-chan error, error) {\n\tr, connErr := r.connect(ctx, req.Identity)\n\tif connErr != nil {\n\t\treturn nil, nil, connErr\n\t}\n\n\tscope, err := r.eventScopeFor(req)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tevents := make(chan clablabruntime.Event, 128)\n\terrs := make(chan error, 4)\n\t// changed carries the labs whose Topology, Nodes or pods changed; the container tracker\n\t// reads them again and reports what changed for their nodes.\n\tchanged := make(chan labRef, 256)\n\n\tgo r.trackContainers(ctx, scope, req.IncludeInitialState, changed, events, errs)\n\n\t// Interface state events are always reported, like the netlink-backed events of the local\n\t// runtimes; statistics only on request. Both come from the same exec per node.\n\tgo r.pollInterfaces(ctx, scope, interfacePollOptions{\n\t\tinterval:            req.StatsInterval,\n\t\tincludeStats:        req.IncludeInterfaceStats,\n\t\tincludeInitialState: req.IncludeInitialState,\n\t}, events)\n\n\tgo r.watchTopologies(ctx, scope, changed, events, errs)\n\tgo r.watchNodes(ctx, scope, changed, errs)\n\tgo r.watchPods(ctx, scope, changed, errs)\n\n\treturn events, errs, nil\n}\n\n// labRef names a lab in a namespace.\ntype labRef struct {\n\tnamespace string\n\tlab       string\n}\n\nfunc sendChangedLab(ctx context.Context, changed chan<- labRef, ref labRef) {\n\tif ref.lab == \"\" {\n\t\treturn\n\t}\n\n\tselect {\n\tcase changed <- ref:\n\tcase <-ctx.Done():\n\t}\n}\n\n// eventScope is the namespace and, optionally, the single lab an event stream covers.\ntype eventScope struct {\n\tnamespace string\n\tlab       string\n}\n\nfunc (r *Runtime) eventScopeFor(req clablabruntime.EventStreamRequest) (eventScope, error) {\n\tif req.Name != \"\" {\n\t\tnamespace, err := r.namespaceForLab(req.Name, req.Namespace)\n\t\tif err != nil {\n\t\t\treturn eventScope{}, err\n\t\t}\n\n\t\treturn eventScope{namespace: namespace, lab: req.Name}, nil\n\t}\n\n\treturn eventScope{namespace: r.listNamespace(req.Namespace, req.AllNamespaces)}, nil\n}\n\n// labelSelector selects the lab-owned resources of the scope.\nfunc (s eventScope) labelSelector() string {\n\tif s.lab != \"\" {\n\t\treturn labels.Set{labelTopologyOwner: s.lab}.String()\n\t}\n\n\treturn labelTopologyOwner\n}\n\n// topologyListOptions selects the Topology resources of the scope.\nfunc (s eventScope) topologyListOptions() metav1.ListOptions {\n\tif s.lab != \"\" {\n\t\treturn metav1.ListOptions{\n\t\t\tFieldSelector: fields.OneTermEqualSelector(\"metadata.name\", s.lab).String(),\n\t\t}\n\t}\n\n\treturn metav1.ListOptions{}\n}\n\n// labStates lists the labs of the scope.\nfunc (r *Runtime) labStates(\n\tctx context.Context,\n\tscope eventScope,\n) ([]*clablabruntime.LabState, error) {\n\tif scope.lab != \"\" {\n\t\tstate, err := r.Inspect(ctx, clablabruntime.InspectRequest{\n\t\t\tName:      scope.lab,\n\t\t\tNamespace: scope.namespace,\n\t\t})\n\t\tif err != nil {\n\t\t\t// A lab that is not deployed yet has no state; its resources show up through\n\t\t\t// the watches once it is.\n\t\t\tvar notFound *labNotFoundError\n\t\t\tif errors.As(err, &notFound) {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn []*clablabruntime.LabState{state}, nil\n\t}\n\n\treturn r.List(ctx, clablabruntime.ListRequest{\n\t\tNamespace:     scope.namespace,\n\t\tAllNamespaces: scope.namespace == metav1.NamespaceAll,\n\t})\n}\n\nfunc (r *Runtime) watchNodes(\n\tctx context.Context,\n\tscope eventScope,\n\tchanged chan<- labRef,\n\terrSink chan<- error,\n) {\n\tresource := r.client.Resource(nodeGVR).Namespace(scope.namespace)\n\n\tfor {\n\t\twatcher, err := resource.Watch(ctx, metav1.ListOptions{\n\t\t\tLabelSelector: scope.labelSelector(),\n\t\t})\n\t\tif err != nil {\n\t\t\tif ctx.Err() != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tsendEventError(ctx, errSink, fmt.Errorf(\"failed to watch c9s nodes: %w\", err))\n\t\t\treturn\n\t\t}\n\n\t\tif !r.forwardNodeWatch(ctx, watcher, changed, errSink) {\n\t\t\treturn\n\t\t}\n\n\t\tif !sleepContext(ctx, pollInterval) {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// forwardNodeWatch reports the lab of every changed Node to the container tracker.\nfunc (r *Runtime) forwardNodeWatch(\n\tctx context.Context,\n\twatcher watch.Interface,\n\tchanged chan<- labRef,\n\terrSink chan<- error,\n) bool {\n\tdefer watcher.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn false\n\t\tcase ev, ok := <-watcher.ResultChan():\n\t\t\tif !ok {\n\t\t\t\tlog.Debug(\"c9s node watch closed, reconnecting\")\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif ev.Type == watch.Error {\n\t\t\t\tsendEventError(ctx, errSink, fmt.Errorf(\"c9s node watch returned an error\"))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tnode, ok := ev.Object.(*unstructured.Unstructured)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsendChangedLab(ctx, changed, labRef{\n\t\t\t\tnamespace: node.GetNamespace(),\n\t\t\t\tlab:       node.GetLabels()[labelTopologyOwner],\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc (r *Runtime) watchTopologies(\n\tctx context.Context,\n\tscope eventScope,\n\tchanged chan<- labRef,\n\teventSink chan<- clablabruntime.Event,\n\terrSink chan<- error,\n) {\n\tresource := r.client.Resource(topologyGVR).Namespace(scope.namespace)\n\n\tfor {\n\t\twatcher, err := resource.Watch(ctx, scope.topologyListOptions())\n\t\tif err != nil {\n\t\t\tif ctx.Err() != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tsendEventError(\n\t\t\t\tctx,\n\t\t\t\terrSink,\n\t\t\t\tfmt.Errorf(\"failed to watch clabernetes topologies: %w\", err),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tif !r.forwardTopologyWatch(ctx, scope.namespace, watcher, changed, eventSink, errSink) {\n\t\t\treturn\n\t\t}\n\n\t\tif !sleepContext(ctx, pollInterval) {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// forwardTopologyWatch reports Topology changes as topology events, which only c9s has, and\n// reports the lab to the container tracker.\nfunc (r *Runtime) forwardTopologyWatch(\n\tctx context.Context,\n\tnamespace string,\n\twatcher watch.Interface,\n\tchanged chan<- labRef,\n\teventSink chan<- clablabruntime.Event,\n\terrSink chan<- error,\n) bool {\n\tdefer watcher.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn false\n\t\tcase ev, ok := <-watcher.ResultChan():\n\t\t\tif !ok {\n\t\t\t\tlog.Debug(\"C9s topology watch closed, reconnecting\")\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif ev.Type == watch.Error {\n\t\t\t\tsendEventError(\n\t\t\t\t\tctx,\n\t\t\t\t\terrSink,\n\t\t\t\t\tfmt.Errorf(\"clabernetes topology watch returned an error\"),\n\t\t\t\t)\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tobj, ok := ev.Object.(*unstructured.Unstructured)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tstate := stateFromTopology(obj, namespace)\n\t\t\tr.sendEvent(ctx, eventSink, clablabruntime.Event{\n\t\t\t\tTimestamp: time.Now(),\n\t\t\t\tType:      \"topology\",\n\t\t\t\tAction:    strings.ToLower(string(ev.Type)),\n\t\t\t\tActorID:   fmt.Sprintf(\"%s/%s\", state.Namespace, state.Name),\n\t\t\t\tActorName: state.Name,\n\t\t\t\tAttributes: map[string]string{\n\t\t\t\t\t\"namespace\": state.Namespace,\n\t\t\t\t\t\"lab\":       state.Name,\n\t\t\t\t\t\"state\":     state.State,\n\t\t\t\t\t\"ready\":     fmt.Sprintf(\"%t\", state.Ready),\n\t\t\t\t},\n\t\t\t})\n\t\t\tsendChangedLab(ctx, changed, labRef{namespace: state.Namespace, lab: state.Name})\n\t\t}\n\t}\n}\n\nfunc (r *Runtime) watchPods(\n\tctx context.Context,\n\tscope eventScope,\n\tchanged chan<- labRef,\n\terrSink chan<- error,\n) {\n\tfor {\n\t\twatcher, err := r.kubeClient.CoreV1().Pods(scope.namespace).Watch(ctx, metav1.ListOptions{\n\t\t\tLabelSelector: scope.labelSelector(),\n\t\t})\n\t\tif err != nil {\n\t\t\tif ctx.Err() != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tsendEventError(ctx, errSink, fmt.Errorf(\n\t\t\t\t\"failed to watch clabernetes pods: %w\", err))\n\t\t\treturn\n\t\t}\n\n\t\tif !r.forwardPodWatch(ctx, watcher, changed, errSink) {\n\t\t\treturn\n\t\t}\n\n\t\tif !sleepContext(ctx, pollInterval) {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// forwardPodWatch reports the lab of every changed pod to the container tracker.\nfunc (r *Runtime) forwardPodWatch(\n\tctx context.Context,\n\twatcher watch.Interface,\n\tchanged chan<- labRef,\n\terrSink chan<- error,\n) bool {\n\tdefer watcher.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn false\n\t\tcase ev, ok := <-watcher.ResultChan():\n\t\t\tif !ok {\n\t\t\t\tlog.Debug(\"C9s pod watch closed, reconnecting\")\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif ev.Type == watch.Error {\n\t\t\t\tsendEventError(ctx, errSink, fmt.Errorf(\n\t\t\t\t\t\"clabernetes pod watch returned an error\"))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tpod, ok := ev.Object.(*corev1.Pod)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsendChangedLab(ctx, changed, labRef{\n\t\t\t\tnamespace: pod.Namespace,\n\t\t\t\tlab:       pod.Labels[labelTopologyOwner],\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc sleepContext(ctx context.Context, d time.Duration) bool {\n\ttimer := time.NewTimer(d)\n\tdefer timer.Stop()\n\n\tselect {\n\tcase <-timer.C:\n\t\treturn true\n\tcase <-ctx.Done():\n\t\treturn false\n\t}\n}\n\nfunc (r *Runtime) sendEvent(\n\tctx context.Context,\n\teventSink chan<- clablabruntime.Event,\n\tevent clablabruntime.Event,\n) {\n\tselect {\n\tcase eventSink <- event:\n\tcase <-ctx.Done():\n\t}\n}\n\nfunc sendEventError(ctx context.Context, errSink chan<- error, err error) {\n\tselect {\n\tcase errSink <- err:\n\tcase <-ctx.Done():\n\t}\n}",
        "lineStart": 1,
        "lineEnd": 393,
        "totalLines": 393,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525745672,
      "end": 1793525745684
    }
  }
}
read · completed

Input

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

Output

<path>/source/head/labruntime/clabernetes/container_events.go</path>
<type>file</type>
<content>
1: package clabernetes
2: 
3: import (
4: 	"context"
5: 	"errors"
6: 	"fmt"
7: 	"strings"
8: 	"time"
9: 
10: 	"github.com/charmbracelet/log"
11: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
12: )
13: 
14: // Container event actions, as the Docker runtime reports them.
15: const (
16: 	containerActionCreate        = "create"
17: 	containerActionStart         = "start"
18: 	containerActionKill          = "kill"
19: 	containerActionStop          = "stop"
20: 	containerActionDie           = "die"
21: 	containerActionDestroy       = "destroy"
22: 	containerActionHealthPrefix  = "health_status: "
23: 	containerEventSignalSIGTERM  = "15"
24: 	containerRefreshDelay        = 200 * time.Millisecond
25: 	containerRefreshRetryDelay   = pollInterval
26: 	containerEventAttributeState = "state"
27: )
28: 
29: // trackedContainer is the last reported container state of a node.
30: type trackedContainer struct {
31: 	ref    labRef
32: 	state  string
33: 	health string
34: 	pod    string
35: 	// lab and node are the last observation, which a removed node is described with.
36: 	lab  *clablabruntime.LabState
37: 	node clablabruntime.NodeState
38: }
39: 
40: // containerTracker turns the node states of the labs in an event scope into the container
41: // events the Docker runtime emits for the same lifecycle: create and start when a node's pod
42: // starts, kill, stop and die when it stops (on request, or between the pods of a restart),
43: // destroy when the node is removed, and health_status as its device becomes ready.
44: type containerTracker struct {
45: 	r     *Runtime
46: 	sink  chan<- clablabruntime.Event
47: 	nodes map[string]*trackedContainer
48: }
49: 
50: // trackContainers reports the container events of a scope. It reads the labs once, reporting
51: // them as a snapshot when the stream includes the initial state, and then reads a lab again
52: // whenever its Topology, Nodes or pods change. Changes that arrive together are read once.
53: func (r *Runtime) trackContainers(
54: 	ctx context.Context,
55: 	scope eventScope,
56: 	includeInitialState bool,
57: 	changed <-chan labRef,
58: 	eventSink chan<- clablabruntime.Event,
59: 	errSink chan<- error,
60: ) {
61: 	tracker := &containerTracker{r: r, sink: eventSink, nodes: map[string]*trackedContainer{}}
62: 
63: 	states, err := r.labStates(ctx, scope)
64: 	if err != nil {
65: 		sendEventError(ctx, errSink, err)
66: 		return
67: 	}
68: 	for _, state := range states {
69: 		tracker.observeLab(ctx, labRef{namespace: state.Namespace, lab: state.Name}, state,
70: 			&observeSeed{snapshot: includeInitialState})
71: 	}
72: 
73: 	pending := map[labRef]bool{}
74: 	timer := time.NewTimer(time.Hour)
75: 	timer.Stop()
76: 	defer timer.Stop()
77: 	armed := false
78: 	arm := func(delay time.Duration) {
79: 		if !armed {
80: 			timer.Reset(delay)
81: 			armed = true
82: 		}
83: 	}
84: 
85: 	for {
86: 		select {
87: 		case <-ctx.Done():
88: 			return
89: 		case ref := <-changed:
90: 			pending[ref] = true
91: 			arm(containerRefreshDelay)
92: 		case <-timer.C:
93: 			armed = false
94: 			refs := pending
95: 			pending = map[labRef]bool{}
96: 			for ref := range refs {
97: 				if !tracker.refresh(ctx, ref) {
98: 					pending[ref] = true
99: 				}
100: 			}
101: 			if len(pending) != 0 {
102: 				arm(containerRefreshRetryDelay)
103: 			}
104: 		}
105: 	}
106: }
107: 
108: // observeSeed marks the first observation of a stream: it records the node states without
109: // reporting changes, and reports them as a snapshot when asked to.
110: type observeSeed struct {
111: 	snapshot bool
112: }
113: 
114: // refresh reads a lab again and reports what changed for its nodes. A lab that is gone reports
115: // its nodes as destroyed. It returns false when the lab could not be read.
116: func (t *containerTracker) refresh(ctx context.Context, ref labRef) bool {
117: 	state, err := t.r.Inspect(ctx, clablabruntime.InspectRequest{
118: 		Name:      ref.lab,
119: 		Namespace: ref.namespace,
120: 	})
121: 	if err != nil {
122: 		var notFound *labNotFoundError
123: 		if !errors.As(err, &notFound) {
124: 			if ctx.Err() == nil {
125: 				log.Debug("Failed to read a C9s lab for container events",
126: 					"namespace", ref.namespace, "lab", ref.lab, "error", err)
127: 			}
128: 
129: 			return ctx.Err() != nil
130: 		}
131: 		state = nil
132: 	}
133: 
134: 	t.observeLab(ctx, ref, state, nil)
135: 
136: 	return true
137: }
138: 
139: // observeLab compares the nodes of a lab with what was reported before and reports the
140: // difference. A nil state removes every node of the lab.
141: func (t *containerTracker) observeLab(
142: 	ctx context.Context,
143: 	ref labRef,
144: 	state *clablabruntime.LabState,
145: 	seed *observeSeed,
146: ) {
147: 	seen := map[string]bool{}
148: 	if state != nil {
149: 		for idx := range state.Nodes {
150: 			key := c9sNodeKey(state.Namespace, state.Name, state.Nodes[idx].Name)
151: 			seen[key] = true
152: 			t.observeNode(ctx, ref, state, state.Nodes[idx], seed)
153: 		}
154: 	}
155: 
156: 	for key, tracked := range t.nodes {
157: 		if tracked.ref != ref || seen[key] {
158: 			continue
159: 		}
160: 
161: 		for _, action := range containerRemovalActions(tracked) {
162: 			t.emit(ctx, tracked.lab, tracked.node, action, nil)
163: 		}
164: 		delete(t.nodes, key)
165: 	}
166: }
167: 
168: func (t *containerTracker) observeNode(
169: 	ctx context.Context,
170: 	ref labRef,
171: 	state *clablabruntime.LabState,
172: 	node clablabruntime.NodeState,
173: 	seed *observeSeed,
174: ) {
175: 	key := c9sNodeKey(state.Namespace, state.Name, node.Name)
176: 	previous := t.nodes[key]
177: 	if node.ContainerState == "" {
178: 		node.ContainerState = clablabruntime.ContainerStateCreated
179: 	}
180: 	next := &trackedContainer{
181: 		ref:   ref,
182: 		state: node.ContainerState,
183: 		pod:   node.Pod,
184: 		lab:   state,
185: 		node:  node,
186: 	}
187: 	next.health = containerHealth(previous, next, node.Health)
188: 	t.nodes[key] = next
189: 
190: 	if seed != nil {
191: 		if seed.snapshot {
192: 			t.emit(ctx, state, node, next.state, map[string]string{
193: 				"origin": clablabruntime.EventOriginSnapshot,
194: 			})
195: 		}
196: 
197: 		return
198: 	}
199: 
200: 	for _, action := range containerTransitionActions(previous, next) {
201: 		t.emit(ctx, state, node, action, nil)
202: 	}
203: }
204: 
205: // containerHealth is the health a running node reports: a node that was healthy and is not
206: // ready anymore in the same pod is unhealthy, as a container whose healthcheck starts failing.
207: func containerHealth(previous, next *trackedContainer, health string) string {
208: 	if next.state != clablabruntime.ContainerStateRunning {
209: 		return ""
210: 	}
211: 	if health == "" {
212: 		health = clablabruntime.ContainerHealthStarting
213: 	}
214: 	if health == clablabruntime.ContainerHealthStarting && previous != nil &&
215: 		previous.state == clablabruntime.ContainerStateRunning && previous.pod == next.pod &&
216: 		(previous.health == clablabruntime.ContainerHealthHealthy ||
217: 			previous.health == clablabruntime.ContainerHealthUnhealthy) {
218: 		return clablabruntime.ContainerHealthUnhealthy
219: 	}
220: 
221: 	return health
222: }
223: 
224: // containerTransitionActions are the container event actions Docker reports when a container
225: // goes from the previous to the next state:
226: //
227: //	new node            create (+ start when it runs, + stop when it is already stopped)
228: //	created -> running  start
229: //	exited  -> running  start
230: //	running -> exited   kill, stop, die (stop, or the old pod of a restart ending)
231: //	running -> created  kill, stop, die (the replacement pod of a restart not running yet)
232: //	running, new pod    kill, stop, die, start (restart)
233: //	created -> exited   stop
234: //
235: // A started node also reports its health (health_status: starting or healthy), and a running
236: // node reports health changes, like a container with a healthcheck.
237: func containerTransitionActions(previous, next *trackedContainer) []string {
238: 	const (
239: 		created = clablabruntime.ContainerStateCreated
240: 		running = clablabruntime.ContainerStateRunning
241: 		exited  = clablabruntime.ContainerStateExited
242: 	)
243: 
244: 	var actions []string
245: 	previousState := ""
246: 	if previous != nil {
247: 		previousState = previous.state
248: 	}
249: 
250: 	switch {
251: 	case previous == nil:
252: 		actions = append(actions, containerActionCreate)
253: 		switch next.state {
254: 		case running:
255: 			actions = append(actions, containerActionStart)
256: 		case exited:
257: 			actions = append(actions, containerActionStop)
258: 		}
259: 	case previousState == running && next.state == running && previous.pod != next.pod:
260: 		actions = append(actions, containerActionKill, containerActionStop, containerActionDie,
261: 			containerActionStart)
262: 	case previousState == running && next.state != running:
263: 		actions = append(actions, containerActionKill, containerActionStop, containerActionDie)
264: 	case previousState != running && next.state == running:
265: 		actions = append(actions, containerActionStart)
266: 	case previousState == created && next.state == exited:
267: 		actions = append(actions, containerActionStop)
268: 	}
269: 
270: 	if next.state != running {
271: 		return actions
272: 	}
273: 
274: 	started := len(actions) != 0 && actions[len(actions)-1] == containerActionStart
275: 	if !started && previous != nil && previous.health == next.health {
276: 		return actions
277: 	}
278: 	if next.health == clablabruntime.ContainerHealthStarting && !started {
279: 		return actions
280: 	}
281: 
282: 	return append(actions, containerActionHealthPrefix+next.health)
283: }
284: 
285: // containerRemovalActions are the actions Docker reports when a container is removed: a running
286: // one is killed and dies first.
287: func containerRemovalActions(previous *trackedContainer) []string {
288: 	if previous.state == clablabruntime.ContainerStateRunning {
289: 		return []string{containerActionKill, containerActionDie, containerActionDestroy}
290: 	}
291: 
292: 	return []string{containerActionDestroy}
293: }
294: 
295: // containerActionState is the container state after an action, which every container event
296: // reports in its state attribute.
297: func containerActionState(action, snapshotState string) string {
298: 	switch action {
299: 	case containerActionCreate:
300: 		return clablabruntime.ContainerStateCreated
301: 	case containerActionStop, containerActionDie, containerActionDestroy:
302: 		return clablabruntime.ContainerStateExited
303: 	case containerActionStart, containerActionKill:
304: 		return clablabruntime.ContainerStateRunning
305: 	}
306: 	if strings.HasPrefix(action, containerActionHealthPrefix) {
307: 		return clablabruntime.ContainerStateRunning
308: 	}
309: 
310: 	return snapshotState
311: }
312: 
313: func (t *containerTracker) emit(
314: 	ctx context.Context,
315: 	state *clablabruntime.LabState,
316: 	node clablabruntime.NodeState,
317: 	action string,
318: 	extra map[string]string,
319: ) {
320: 	t.r.sendEvent(ctx, t.sink, c9sContainerEvent(state, node, action, extra))
321: }
322: 
323: // c9sContainerEvent is a container event of a node. The actor is the node, as for its interface
324: // events; its ID is the container_id inspect reports. Lab and Node let the events command
325: // describe the node with the attributes inspect and the Docker runtime report.
326: func c9sContainerEvent(
327: 	state *clablabruntime.LabState,
328: 	node clablabruntime.NodeState,
329: 	action string,
330: 	extra map[string]string,
331: ) clablabruntime.Event {
332: 	key := c9sNodeKey(state.Namespace, state.Name, node.Name)
333: 	attributes := map[string]string{
334: 		"namespace":                  state.Namespace,
335: 		"lab":                        state.Name,
336: 		"node":                       node.Name,
337: 		containerEventAttributeState: containerActionState(action, node.ContainerState),
338: 	}
339: 	if node.Pod != "" {
340: 		attributes["pod"] = node.Pod
341: 	}
342: 	if action == containerActionKill {
343: 		// Kubernetes stops a pod's containers with SIGTERM.
344: 		attributes["signal"] = containerEventSignalSIGTERM
345: 	}
346: 	for k, v := range extra {
347: 		attributes[k] = v
348: 	}
349: 
350: 	nodeCopy := node
351: 
352: 	return clablabruntime.Event{
353: 		Timestamp:   time.Now(),
354: 		Type:        clablabruntime.EventTypeContainer,
355: 		Action:      action,
356: 		ActorID:     key,
357: 		ActorName:   fmt.Sprintf("%s-%s", state.Name, node.Name),
358: 		ActorFullID: key,
359: 		Attributes:  attributes,
360: 		Lab:         state,
361: 		Node:        &nodeCopy,
362: 	}
363: }

(End of file - total 363 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196770831001RZJFgFLu2PL7l2",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19676f630001k5K3RVrcoGt3VU",
  "callID": "call_e20ec5aa25874924a31cd2b6",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/container_events.go"
    },
    "output": "<path>/source/head/labruntime/clabernetes/container_events.go</path>\n<type>file</type>\n<content>\n1: package clabernetes\n2: \n3: import (\n4: \t\"context\"\n5: \t\"errors\"\n6: \t\"fmt\"\n7: \t\"strings\"\n8: \t\"time\"\n9: \n10: \t\"github.com/charmbracelet/log\"\n11: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n12: )\n13: \n14: // Container event actions, as the Docker runtime reports them.\n15: const (\n16: \tcontainerActionCreate        = \"create\"\n17: \tcontainerActionStart         = \"start\"\n18: \tcontainerActionKill          = \"kill\"\n19: \tcontainerActionStop          = \"stop\"\n20: \tcontainerActionDie           = \"die\"\n21: \tcontainerActionDestroy       = \"destroy\"\n22: \tcontainerActionHealthPrefix  = \"health_status: \"\n23: \tcontainerEventSignalSIGTERM  = \"15\"\n24: \tcontainerRefreshDelay        = 200 * time.Millisecond\n25: \tcontainerRefreshRetryDelay   = pollInterval\n26: \tcontainerEventAttributeState = \"state\"\n27: )\n28: \n29: // trackedContainer is the last reported container state of a node.\n30: type trackedContainer struct {\n31: \tref    labRef\n32: \tstate  string\n33: \thealth string\n34: \tpod    string\n35: \t// lab and node are the last observation, which a removed node is described with.\n36: \tlab  *clablabruntime.LabState\n37: \tnode clablabruntime.NodeState\n38: }\n39: \n40: // containerTracker turns the node states of the labs in an event scope into the container\n41: // events the Docker runtime emits for the same lifecycle: create and start when a node's pod\n42: // starts, kill, stop and die when it stops (on request, or between the pods of a restart),\n43: // destroy when the node is removed, and health_status as its device becomes ready.\n44: type containerTracker struct {\n45: \tr     *Runtime\n46: \tsink  chan<- clablabruntime.Event\n47: \tnodes map[string]*trackedContainer\n48: }\n49: \n50: // trackContainers reports the container events of a scope. It reads the labs once, reporting\n51: // them as a snapshot when the stream includes the initial state, and then reads a lab again\n52: // whenever its Topology, Nodes or pods change. Changes that arrive together are read once.\n53: func (r *Runtime) trackContainers(\n54: \tctx context.Context,\n55: \tscope eventScope,\n56: \tincludeInitialState bool,\n57: \tchanged <-chan labRef,\n58: \teventSink chan<- clablabruntime.Event,\n59: \terrSink chan<- error,\n60: ) {\n61: \ttracker := &containerTracker{r: r, sink: eventSink, nodes: map[string]*trackedContainer{}}\n62: \n63: \tstates, err := r.labStates(ctx, scope)\n64: \tif err != nil {\n65: \t\tsendEventError(ctx, errSink, err)\n66: \t\treturn\n67: \t}\n68: \tfor _, state := range states {\n69: \t\ttracker.observeLab(ctx, labRef{namespace: state.Namespace, lab: state.Name}, state,\n70: \t\t\t&observeSeed{snapshot: includeInitialState})\n71: \t}\n72: \n73: \tpending := map[labRef]bool{}\n74: \ttimer := time.NewTimer(time.Hour)\n75: \ttimer.Stop()\n76: \tdefer timer.Stop()\n77: \tarmed := false\n78: \tarm := func(delay time.Duration) {\n79: \t\tif !armed {\n80: \t\t\ttimer.Reset(delay)\n81: \t\t\tarmed = true\n82: \t\t}\n83: \t}\n84: \n85: \tfor {\n86: \t\tselect {\n87: \t\tcase <-ctx.Done():\n88: \t\t\treturn\n89: \t\tcase ref := <-changed:\n90: \t\t\tpending[ref] = true\n91: \t\t\tarm(containerRefreshDelay)\n92: \t\tcase <-timer.C:\n93: \t\t\tarmed = false\n94: \t\t\trefs := pending\n95: \t\t\tpending = map[labRef]bool{}\n96: \t\t\tfor ref := range refs {\n97: \t\t\t\tif !tracker.refresh(ctx, ref) {\n98: \t\t\t\t\tpending[ref] = true\n99: \t\t\t\t}\n100: \t\t\t}\n101: \t\t\tif len(pending) != 0 {\n102: \t\t\t\tarm(containerRefreshRetryDelay)\n103: \t\t\t}\n104: \t\t}\n105: \t}\n106: }\n107: \n108: // observeSeed marks the first observation of a stream: it records the node states without\n109: // reporting changes, and reports them as a snapshot when asked to.\n110: type observeSeed struct {\n111: \tsnapshot bool\n112: }\n113: \n114: // refresh reads a lab again and reports what changed for its nodes. A lab that is gone reports\n115: // its nodes as destroyed. It returns false when the lab could not be read.\n116: func (t *containerTracker) refresh(ctx context.Context, ref labRef) bool {\n117: \tstate, err := t.r.Inspect(ctx, clablabruntime.InspectRequest{\n118: \t\tName:      ref.lab,\n119: \t\tNamespace: ref.namespace,\n120: \t})\n121: \tif err != nil {\n122: \t\tvar notFound *labNotFoundError\n123: \t\tif !errors.As(err, &notFound) {\n124: \t\t\tif ctx.Err() == nil {\n125: \t\t\t\tlog.Debug(\"Failed to read a C9s lab for container events\",\n126: \t\t\t\t\t\"namespace\", ref.namespace, \"lab\", ref.lab, \"error\", err)\n127: \t\t\t}\n128: \n129: \t\t\treturn ctx.Err() != nil\n130: \t\t}\n131: \t\tstate = nil\n132: \t}\n133: \n134: \tt.observeLab(ctx, ref, state, nil)\n135: \n136: \treturn true\n137: }\n138: \n139: // observeLab compares the nodes of a lab with what was reported before and reports the\n140: // difference. A nil state removes every node of the lab.\n141: func (t *containerTracker) observeLab(\n142: \tctx context.Context,\n143: \tref labRef,\n144: \tstate *clablabruntime.LabState,\n145: \tseed *observeSeed,\n146: ) {\n147: \tseen := map[string]bool{}\n148: \tif state != nil {\n149: \t\tfor idx := range state.Nodes {\n150: \t\t\tkey := c9sNodeKey(state.Namespace, state.Name, state.Nodes[idx].Name)\n151: \t\t\tseen[key] = true\n152: \t\t\tt.observeNode(ctx, ref, state, state.Nodes[idx], seed)\n153: \t\t}\n154: \t}\n155: \n156: \tfor key, tracked := range t.nodes {\n157: \t\tif tracked.ref != ref || seen[key] {\n158: \t\t\tcontinue\n159: \t\t}\n160: \n161: \t\tfor _, action := range containerRemovalActions(tracked) {\n162: \t\t\tt.emit(ctx, tracked.lab, tracked.node, action, nil)\n163: \t\t}\n164: \t\tdelete(t.nodes, key)\n165: \t}\n166: }\n167: \n168: func (t *containerTracker) observeNode(\n169: \tctx context.Context,\n170: \tref labRef,\n171: \tstate *clablabruntime.LabState,\n172: \tnode clablabruntime.NodeState,\n173: \tseed *observeSeed,\n174: ) {\n175: \tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n176: \tprevious := t.nodes[key]\n177: \tif node.ContainerState == \"\" {\n178: \t\tnode.ContainerState = clablabruntime.ContainerStateCreated\n179: \t}\n180: \tnext := &trackedContainer{\n181: \t\tref:   ref,\n182: \t\tstate: node.ContainerState,\n183: \t\tpod:   node.Pod,\n184: \t\tlab:   state,\n185: \t\tnode:  node,\n186: \t}\n187: \tnext.health = containerHealth(previous, next, node.Health)\n188: \tt.nodes[key] = next\n189: \n190: \tif seed != nil {\n191: \t\tif seed.snapshot {\n192: \t\t\tt.emit(ctx, state, node, next.state, map[string]string{\n193: \t\t\t\t\"origin\": clablabruntime.EventOriginSnapshot,\n194: \t\t\t})\n195: \t\t}\n196: \n197: \t\treturn\n198: \t}\n199: \n200: \tfor _, action := range containerTransitionActions(previous, next) {\n201: \t\tt.emit(ctx, state, node, action, nil)\n202: \t}\n203: }\n204: \n205: // containerHealth is the health a running node reports: a node that was healthy and is not\n206: // ready anymore in the same pod is unhealthy, as a container whose healthcheck starts failing.\n207: func containerHealth(previous, next *trackedContainer, health string) string {\n208: \tif next.state != clablabruntime.ContainerStateRunning {\n209: \t\treturn \"\"\n210: \t}\n211: \tif health == \"\" {\n212: \t\thealth = clablabruntime.ContainerHealthStarting\n213: \t}\n214: \tif health == clablabruntime.ContainerHealthStarting && previous != nil &&\n215: \t\tprevious.state == clablabruntime.ContainerStateRunning && previous.pod == next.pod &&\n216: \t\t(previous.health == clablabruntime.ContainerHealthHealthy ||\n217: \t\t\tprevious.health == clablabruntime.ContainerHealthUnhealthy) {\n218: \t\treturn clablabruntime.ContainerHealthUnhealthy\n219: \t}\n220: \n221: \treturn health\n222: }\n223: \n224: // containerTransitionActions are the container event actions Docker reports when a container\n225: // goes from the previous to the next state:\n226: //\n227: //\tnew node            create (+ start when it runs, + stop when it is already stopped)\n228: //\tcreated -> running  start\n229: //\texited  -> running  start\n230: //\trunning -> exited   kill, stop, die (stop, or the old pod of a restart ending)\n231: //\trunning -> created  kill, stop, die (the replacement pod of a restart not running yet)\n232: //\trunning, new pod    kill, stop, die, start (restart)\n233: //\tcreated -> exited   stop\n234: //\n235: // A started node also reports its health (health_status: starting or healthy), and a running\n236: // node reports health changes, like a container with a healthcheck.\n237: func containerTransitionActions(previous, next *trackedContainer) []string {\n238: \tconst (\n239: \t\tcreated = clablabruntime.ContainerStateCreated\n240: \t\trunning = clablabruntime.ContainerStateRunning\n241: \t\texited  = clablabruntime.ContainerStateExited\n242: \t)\n243: \n244: \tvar actions []string\n245: \tpreviousState := \"\"\n246: \tif previous != nil {\n247: \t\tpreviousState = previous.state\n248: \t}\n249: \n250: \tswitch {\n251: \tcase previous == nil:\n252: \t\tactions = append(actions, containerActionCreate)\n253: \t\tswitch next.state {\n254: \t\tcase running:\n255: \t\t\tactions = append(actions, containerActionStart)\n256: \t\tcase exited:\n257: \t\t\tactions = append(actions, containerActionStop)\n258: \t\t}\n259: \tcase previousState == running && next.state == running && previous.pod != next.pod:\n260: \t\tactions = append(actions, containerActionKill, containerActionStop, containerActionDie,\n261: \t\t\tcontainerActionStart)\n262: \tcase previousState == running && next.state != running:\n263: \t\tactions = append(actions, containerActionKill, containerActionStop, containerActionDie)\n264: \tcase previousState != running && next.state == running:\n265: \t\tactions = append(actions, containerActionStart)\n266: \tcase previousState == created && next.state == exited:\n267: \t\tactions = append(actions, containerActionStop)\n268: \t}\n269: \n270: \tif next.state != running {\n271: \t\treturn actions\n272: \t}\n273: \n274: \tstarted := len(actions) != 0 && actions[len(actions)-1] == containerActionStart\n275: \tif !started && previous != nil && previous.health == next.health {\n276: \t\treturn actions\n277: \t}\n278: \tif next.health == clablabruntime.ContainerHealthStarting && !started {\n279: \t\treturn actions\n280: \t}\n281: \n282: \treturn append(actions, containerActionHealthPrefix+next.health)\n283: }\n284: \n285: // containerRemovalActions are the actions Docker reports when a container is removed: a running\n286: // one is killed and dies first.\n287: func containerRemovalActions(previous *trackedContainer) []string {\n288: \tif previous.state == clablabruntime.ContainerStateRunning {\n289: \t\treturn []string{containerActionKill, containerActionDie, containerActionDestroy}\n290: \t}\n291: \n292: \treturn []string{containerActionDestroy}\n293: }\n294: \n295: // containerActionState is the container state after an action, which every container event\n296: // reports in its state attribute.\n297: func containerActionState(action, snapshotState string) string {\n298: \tswitch action {\n299: \tcase containerActionCreate:\n300: \t\treturn clablabruntime.ContainerStateCreated\n301: \tcase containerActionStop, containerActionDie, containerActionDestroy:\n302: \t\treturn clablabruntime.ContainerStateExited\n303: \tcase containerActionStart, containerActionKill:\n304: \t\treturn clablabruntime.ContainerStateRunning\n305: \t}\n306: \tif strings.HasPrefix(action, containerActionHealthPrefix) {\n307: \t\treturn clablabruntime.ContainerStateRunning\n308: \t}\n309: \n310: \treturn snapshotState\n311: }\n312: \n313: func (t *containerTracker) emit(\n314: \tctx context.Context,\n315: \tstate *clablabruntime.LabState,\n316: \tnode clablabruntime.NodeState,\n317: \taction string,\n318: \textra map[string]string,\n319: ) {\n320: \tt.r.sendEvent(ctx, t.sink, c9sContainerEvent(state, node, action, extra))\n321: }\n322: \n323: // c9sContainerEvent is a container event of a node. The actor is the node, as for its interface\n324: // events; its ID is the container_id inspect reports. Lab and Node let the events command\n325: // describe the node with the attributes inspect and the Docker runtime report.\n326: func c9sContainerEvent(\n327: \tstate *clablabruntime.LabState,\n328: \tnode clablabruntime.NodeState,\n329: \taction string,\n330: \textra map[string]string,\n331: ) clablabruntime.Event {\n332: \tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n333: \tattributes := map[string]string{\n334: \t\t\"namespace\":                  state.Namespace,\n335: \t\t\"lab\":                        state.Name,\n336: \t\t\"node\":                       node.Name,\n337: \t\tcontainerEventAttributeState: containerActionState(action, node.ContainerState),\n338: \t}\n339: \tif node.Pod != \"\" {\n340: \t\tattributes[\"pod\"] = node.Pod\n341: \t}\n342: \tif action == containerActionKill {\n343: \t\t// Kubernetes stops a pod's containers with SIGTERM.\n344: \t\tattributes[\"signal\"] = containerEventSignalSIGTERM\n345: \t}\n346: \tfor k, v := range extra {\n347: \t\tattributes[k] = v\n348: \t}\n349: \n350: \tnodeCopy := node\n351: \n352: \treturn clablabruntime.Event{\n353: \t\tTimestamp:   time.Now(),\n354: \t\tType:        clablabruntime.EventTypeContainer,\n355: \t\tAction:      action,\n356: \t\tActorID:     key,\n357: \t\tActorName:   fmt.Sprintf(\"%s-%s\", state.Name, node.Name),\n358: \t\tActorFullID: key,\n359: \t\tAttributes:  attributes,\n360: \t\tLab:         state,\n361: \t\tNode:        &nodeCopy,\n362: \t}\n363: }\n\n(End of file - total 363 lines)\n</content>",
    "title": "source/head/labruntime/clabernetes/container_events.go",
    "metadata": {
      "preview": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\n// Container event actions, as the Docker runtime reports them.\nconst (\n\tcontainerActionCreate        = \"create\"\n\tcontainerActionStart         = \"start\"\n\tcontainerActionKill          = \"kill\"\n\tcontainerActionStop          = \"stop\"\n\tcontainerActionDie           = \"die\"",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/container_events.go",
        "text": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\n// Container event actions, as the Docker runtime reports them.\nconst (\n\tcontainerActionCreate        = \"create\"\n\tcontainerActionStart         = \"start\"\n\tcontainerActionKill          = \"kill\"\n\tcontainerActionStop          = \"stop\"\n\tcontainerActionDie           = \"die\"\n\tcontainerActionDestroy       = \"destroy\"\n\tcontainerActionHealthPrefix  = \"health_status: \"\n\tcontainerEventSignalSIGTERM  = \"15\"\n\tcontainerRefreshDelay        = 200 * time.Millisecond\n\tcontainerRefreshRetryDelay   = pollInterval\n\tcontainerEventAttributeState = \"state\"\n)\n\n// trackedContainer is the last reported container state of a node.\ntype trackedContainer struct {\n\tref    labRef\n\tstate  string\n\thealth string\n\tpod    string\n\t// lab and node are the last observation, which a removed node is described with.\n\tlab  *clablabruntime.LabState\n\tnode clablabruntime.NodeState\n}\n\n// containerTracker turns the node states of the labs in an event scope into the container\n// events the Docker runtime emits for the same lifecycle: create and start when a node's pod\n// starts, kill, stop and die when it stops (on request, or between the pods of a restart),\n// destroy when the node is removed, and health_status as its device becomes ready.\ntype containerTracker struct {\n\tr     *Runtime\n\tsink  chan<- clablabruntime.Event\n\tnodes map[string]*trackedContainer\n}\n\n// trackContainers reports the container events of a scope. It reads the labs once, reporting\n// them as a snapshot when the stream includes the initial state, and then reads a lab again\n// whenever its Topology, Nodes or pods change. Changes that arrive together are read once.\nfunc (r *Runtime) trackContainers(\n\tctx context.Context,\n\tscope eventScope,\n\tincludeInitialState bool,\n\tchanged <-chan labRef,\n\teventSink chan<- clablabruntime.Event,\n\terrSink chan<- error,\n) {\n\ttracker := &containerTracker{r: r, sink: eventSink, nodes: map[string]*trackedContainer{}}\n\n\tstates, err := r.labStates(ctx, scope)\n\tif err != nil {\n\t\tsendEventError(ctx, errSink, err)\n\t\treturn\n\t}\n\tfor _, state := range states {\n\t\ttracker.observeLab(ctx, labRef{namespace: state.Namespace, lab: state.Name}, state,\n\t\t\t&observeSeed{snapshot: includeInitialState})\n\t}\n\n\tpending := map[labRef]bool{}\n\ttimer := time.NewTimer(time.Hour)\n\ttimer.Stop()\n\tdefer timer.Stop()\n\tarmed := false\n\tarm := func(delay time.Duration) {\n\t\tif !armed {\n\t\t\ttimer.Reset(delay)\n\t\t\tarmed = true\n\t\t}\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase ref := <-changed:\n\t\t\tpending[ref] = true\n\t\t\tarm(containerRefreshDelay)\n\t\tcase <-timer.C:\n\t\t\tarmed = false\n\t\t\trefs := pending\n\t\t\tpending = map[labRef]bool{}\n\t\t\tfor ref := range refs {\n\t\t\t\tif !tracker.refresh(ctx, ref) {\n\t\t\t\t\tpending[ref] = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(pending) != 0 {\n\t\t\t\tarm(containerRefreshRetryDelay)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// observeSeed marks the first observation of a stream: it records the node states without\n// reporting changes, and reports them as a snapshot when asked to.\ntype observeSeed struct {\n\tsnapshot bool\n}\n\n// refresh reads a lab again and reports what changed for its nodes. A lab that is gone reports\n// its nodes as destroyed. It returns false when the lab could not be read.\nfunc (t *containerTracker) refresh(ctx context.Context, ref labRef) bool {\n\tstate, err := t.r.Inspect(ctx, clablabruntime.InspectRequest{\n\t\tName:      ref.lab,\n\t\tNamespace: ref.namespace,\n\t})\n\tif err != nil {\n\t\tvar notFound *labNotFoundError\n\t\tif !errors.As(err, &notFound) {\n\t\t\tif ctx.Err() == nil {\n\t\t\t\tlog.Debug(\"Failed to read a C9s lab for container events\",\n\t\t\t\t\t\"namespace\", ref.namespace, \"lab\", ref.lab, \"error\", err)\n\t\t\t}\n\n\t\t\treturn ctx.Err() != nil\n\t\t}\n\t\tstate = nil\n\t}\n\n\tt.observeLab(ctx, ref, state, nil)\n\n\treturn true\n}\n\n// observeLab compares the nodes of a lab with what was reported before and reports the\n// difference. A nil state removes every node of the lab.\nfunc (t *containerTracker) observeLab(\n\tctx context.Context,\n\tref labRef,\n\tstate *clablabruntime.LabState,\n\tseed *observeSeed,\n) {\n\tseen := map[string]bool{}\n\tif state != nil {\n\t\tfor idx := range state.Nodes {\n\t\t\tkey := c9sNodeKey(state.Namespace, state.Name, state.Nodes[idx].Name)\n\t\t\tseen[key] = true\n\t\t\tt.observeNode(ctx, ref, state, state.Nodes[idx], seed)\n\t\t}\n\t}\n\n\tfor key, tracked := range t.nodes {\n\t\tif tracked.ref != ref || seen[key] {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, action := range containerRemovalActions(tracked) {\n\t\t\tt.emit(ctx, tracked.lab, tracked.node, action, nil)\n\t\t}\n\t\tdelete(t.nodes, key)\n\t}\n}\n\nfunc (t *containerTracker) observeNode(\n\tctx context.Context,\n\tref labRef,\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n\tseed *observeSeed,\n) {\n\tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n\tprevious := t.nodes[key]\n\tif node.ContainerState == \"\" {\n\t\tnode.ContainerState = clablabruntime.ContainerStateCreated\n\t}\n\tnext := &trackedContainer{\n\t\tref:   ref,\n\t\tstate: node.ContainerState,\n\t\tpod:   node.Pod,\n\t\tlab:   state,\n\t\tnode:  node,\n\t}\n\tnext.health = containerHealth(previous, next, node.Health)\n\tt.nodes[key] = next\n\n\tif seed != nil {\n\t\tif seed.snapshot {\n\t\t\tt.emit(ctx, state, node, next.state, map[string]string{\n\t\t\t\t\"origin\": clablabruntime.EventOriginSnapshot,\n\t\t\t})\n\t\t}\n\n\t\treturn\n\t}\n\n\tfor _, action := range containerTransitionActions(previous, next) {\n\t\tt.emit(ctx, state, node, action, nil)\n\t}\n}\n\n// containerHealth is the health a running node reports: a node that was healthy and is not\n// ready anymore in the same pod is unhealthy, as a container whose healthcheck starts failing.\nfunc containerHealth(previous, next *trackedContainer, health string) string {\n\tif next.state != clablabruntime.ContainerStateRunning {\n\t\treturn \"\"\n\t}\n\tif health == \"\" {\n\t\thealth = clablabruntime.ContainerHealthStarting\n\t}\n\tif health == clablabruntime.ContainerHealthStarting && previous != nil &&\n\t\tprevious.state == clablabruntime.ContainerStateRunning && previous.pod == next.pod &&\n\t\t(previous.health == clablabruntime.ContainerHealthHealthy ||\n\t\t\tprevious.health == clablabruntime.ContainerHealthUnhealthy) {\n\t\treturn clablabruntime.ContainerHealthUnhealthy\n\t}\n\n\treturn health\n}\n\n// containerTransitionActions are the container event actions Docker reports when a container\n// goes from the previous to the next state:\n//\n//\tnew node            create (+ start when it runs, + stop when it is already stopped)\n//\tcreated -> running  start\n//\texited  -> running  start\n//\trunning -> exited   kill, stop, die (stop, or the old pod of a restart ending)\n//\trunning -> created  kill, stop, die (the replacement pod of a restart not running yet)\n//\trunning, new pod    kill, stop, die, start (restart)\n//\tcreated -> exited   stop\n//\n// A started node also reports its health (health_status: starting or healthy), and a running\n// node reports health changes, like a container with a healthcheck.\nfunc containerTransitionActions(previous, next *trackedContainer) []string {\n\tconst (\n\t\tcreated = clablabruntime.ContainerStateCreated\n\t\trunning = clablabruntime.ContainerStateRunning\n\t\texited  = clablabruntime.ContainerStateExited\n\t)\n\n\tvar actions []string\n\tpreviousState := \"\"\n\tif previous != nil {\n\t\tpreviousState = previous.state\n\t}\n\n\tswitch {\n\tcase previous == nil:\n\t\tactions = append(actions, containerActionCreate)\n\t\tswitch next.state {\n\t\tcase running:\n\t\t\tactions = append(actions, containerActionStart)\n\t\tcase exited:\n\t\t\tactions = append(actions, containerActionStop)\n\t\t}\n\tcase previousState == running && next.state == running && previous.pod != next.pod:\n\t\tactions = append(actions, containerActionKill, containerActionStop, containerActionDie,\n\t\t\tcontainerActionStart)\n\tcase previousState == running && next.state != running:\n\t\tactions = append(actions, containerActionKill, containerActionStop, containerActionDie)\n\tcase previousState != running && next.state == running:\n\t\tactions = append(actions, containerActionStart)\n\tcase previousState == created && next.state == exited:\n\t\tactions = append(actions, containerActionStop)\n\t}\n\n\tif next.state != running {\n\t\treturn actions\n\t}\n\n\tstarted := len(actions) != 0 && actions[len(actions)-1] == containerActionStart\n\tif !started && previous != nil && previous.health == next.health {\n\t\treturn actions\n\t}\n\tif next.health == clablabruntime.ContainerHealthStarting && !started {\n\t\treturn actions\n\t}\n\n\treturn append(actions, containerActionHealthPrefix+next.health)\n}\n\n// containerRemovalActions are the actions Docker reports when a container is removed: a running\n// one is killed and dies first.\nfunc containerRemovalActions(previous *trackedContainer) []string {\n\tif previous.state == clablabruntime.ContainerStateRunning {\n\t\treturn []string{containerActionKill, containerActionDie, containerActionDestroy}\n\t}\n\n\treturn []string{containerActionDestroy}\n}\n\n// containerActionState is the container state after an action, which every container event\n// reports in its state attribute.\nfunc containerActionState(action, snapshotState string) string {\n\tswitch action {\n\tcase containerActionCreate:\n\t\treturn clablabruntime.ContainerStateCreated\n\tcase containerActionStop, containerActionDie, containerActionDestroy:\n\t\treturn clablabruntime.ContainerStateExited\n\tcase containerActionStart, containerActionKill:\n\t\treturn clablabruntime.ContainerStateRunning\n\t}\n\tif strings.HasPrefix(action, containerActionHealthPrefix) {\n\t\treturn clablabruntime.ContainerStateRunning\n\t}\n\n\treturn snapshotState\n}\n\nfunc (t *containerTracker) emit(\n\tctx context.Context,\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n\taction string,\n\textra map[string]string,\n) {\n\tt.r.sendEvent(ctx, t.sink, c9sContainerEvent(state, node, action, extra))\n}\n\n// c9sContainerEvent is a container event of a node. The actor is the node, as for its interface\n// events; its ID is the container_id inspect reports. Lab and Node let the events command\n// describe the node with the attributes inspect and the Docker runtime report.\nfunc c9sContainerEvent(\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n\taction string,\n\textra map[string]string,\n) clablabruntime.Event {\n\tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n\tattributes := map[string]string{\n\t\t\"namespace\":                  state.Namespace,\n\t\t\"lab\":                        state.Name,\n\t\t\"node\":                       node.Name,\n\t\tcontainerEventAttributeState: containerActionState(action, node.ContainerState),\n\t}\n\tif node.Pod != \"\" {\n\t\tattributes[\"pod\"] = node.Pod\n\t}\n\tif action == containerActionKill {\n\t\t// Kubernetes stops a pod's containers with SIGTERM.\n\t\tattributes[\"signal\"] = containerEventSignalSIGTERM\n\t}\n\tfor k, v := range extra {\n\t\tattributes[k] = v\n\t}\n\n\tnodeCopy := node\n\n\treturn clablabruntime.Event{\n\t\tTimestamp:   time.Now(),\n\t\tType:        clablabruntime.EventTypeContainer,\n\t\tAction:      action,\n\t\tActorID:     key,\n\t\tActorName:   fmt.Sprintf(\"%s-%s\", state.Name, node.Name),\n\t\tActorFullID: key,\n\t\tAttributes:  attributes,\n\t\tLab:         state,\n\t\tNode:        &nodeCopy,\n\t}\n}",
        "lineStart": 1,
        "lineEnd": 363,
        "totalLines": 363,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525745716,
      "end": 1793525745721
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19677084f001prejNrUSS4i35Q",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19676f630001k5K3RVrcoGt3VU",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 13286,
    "input": 5913,
    "output": 72,
    "reasoning": 133,
    "cache": {
      "read": 7168,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19676f630001k5K3RVrcoGt3VU",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525741104,
    "completed": 1793525745746
  },
  "parentID": "msg_19676df9500159h7P3dGcuBxjO",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 13286,
    "input": 5913,
    "output": 72,
    "reasoning": 133,
    "cache": {
      "read": 7168,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 15
step-start
{
  "type": "step-start",
  "id": "prt_196770f5b001pFZO4OhaY7RSWd",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196770857001sQDZoRoeELv1VY"
}
Reasoning
Analysis of `container_events.go`:

1. `trackContainers` early return on `labStates` error (line 63-67): if initial listing fails, the tracker goroutine returns, but the watch goroutines still push to `changed` (buffer 256). When buffer fills, watch goroutines block in `sendChangedLab` until ctx done. This is a leaked/stalled goroutine situation until the stream is closed, and container events silently stop. However, `pollInterfaces` also reads events. When StreamEvents consumer receives the error on errs, it typically returns and cancels ctx — in `streamLabRuntimeEvents`, an error from runtimeErrs returns the error and the deferred cancel in Stream cancels ctx. So the watches unblock. That's acceptable. But if the consumer does not cancel... in Stream it does via defer cancel. So minor. Also `pollInterfaces` and watches keep running. Not a big deal; P3/P4 maybe. Actually the watch goroutines would block on sendChangedLab; ctx cancellation unblocks. Fine.

2. `refresh` returns `ctx.Err() != nil` when Inspect fails with non-notFound error: returns false when ctx alive (retry later) and true when ctx done (give up since loop will exit). Reasonable.

But wait: in `refresh`, on a non-notFound error, it returns false → the ref is re-added to pending and `arm(containerRefreshRetryDelay)` re-arms. But the retry loop: when `len(pending) != 0`, it arms retry. That's fine — however there's a subtle issue: if Inspect keeps failing, we keep polling every pollInterval — that's intended retry.

3. `observeLab`: when state != nil, iterates nodes; but nodes removed... `tracked.ref != ref` — labRef is a struct, comparable. OK.

Potential issue: `observeNode` when `previous == nil` and seed==nil (a new node appears mid-stream) emits create (+start). Good.

4. In `containerTransitionActions`, the health logic: for a new node (previous==nil) with actions [create, start], started=true; if next.health == starting, we'd append health_status: starting. OK. But there's a subtle case: previous != nil, same pod, state running->running, no actions (len(actions)==0), and previous.health == next.health → return actions (empty). Good. If health changed from starting→healthy: started=false, previous.health != next.health, next.health == healthy → append health_status: healthy. Good. If next.health == starting and !started → skip (avoids repeat of starting). But what if health goes healthy → starting (unhealthy regression)? containerHealth: next running, health=="starting", previous running same pod, previous.health healthy → returns unhealthy. Good.

Edge: node was running, pod changed (restart) → actions kill,stop,die,start. started=true. next.health: containerHealth computes — previous.pod != next.pod so no unhealthy downgrade; health from node.Health or starting. Appends health_status: starting/healthy. Good.

5. `containerActionState` for `containerActionStop` returns exited... wait Docker: `stop` event — container state after stop is "exited". OK.

Hmm, but for `create` when node is already running: attributes state = created. Docker parity: create event has state created. OK.

6. `c9sContainerEvent` — state could be nil? emit is called with tracked.lab or state from observeLab which is non-nil in observeNode path (observeNode called with state non-nil). In observeLab removal path, tracked.lab is the last observation which was non-nil when tracked. OK. But wait — in observeLab, if state != nil, tracked nodes' lab pointer replaced each refresh. Fine.

7. One issue: `observeNode` sets `t.nodes[key] = next` before emitting events; if emit blocks... fine, ctx select.

8. `emit` uses `state` (the LabState pointer) — removal path uses tracked.lab which is the previous state pointer. OK.

Now `iface_stats.go` and `netlink.go` and `labruntime.go`. Let me read them.
`events.go` and `container_events.go` look largely sound. Now the poller and netlink attribute helpers.
read · completed

Input

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

Output

<path>/source/head/labruntime/clabernetes/iface_stats.go</path>
<type>file</type>
<content>
1: package clabernetes
2: 
3: import (
4: 	"context"
5: 	"fmt"
6: 	"sort"
7: 	"strconv"
8: 	"strings"
9: 	"sync"
10: 	"time"
11: 
12: 	"github.com/charmbracelet/log"
13: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
14: 	corev1 "k8s.io/api/core/v1"
15: 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
16: )
17: 
18: const (
19: 	// interfaceSysfsMarker separates the /proc/net/dev counters from the sysfs interface
20: 	// attributes in the output of interfaceSampleScript.
21: 	interfaceSysfsMarker = "@@clab-sysfs"
22: 	// interfaceSampleScript reads the interface counters and, per interface, the sysfs
23: 	// attributes the interface state events carry, in one exec:
24: 	// name, ifindex, mtu, address, operstate, flags and ifalias, tab separated.
25: 	interfaceSampleScript = `cat /proc/net/dev; echo ` + interfaceSysfsMarker + `; ` +
26: 		`for d in /sys/class/net/*; do [ -e "$d/operstate" ] || continue; ` +
27: 		`printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "${d##*/}" "$(cat "$d/ifindex")" ` +
28: 		`"$(cat "$d/mtu")" "$(cat "$d/address")" "$(cat "$d/operstate")" ` +
29: 		`"$(cat "$d/flags")" "$(cat "$d/ifalias")"; done 2>/dev/null`
30: 
31: 	// interfaceSampleWorkers bounds the concurrent execs of one sampling round.
32: 	interfaceSampleWorkers = 16
33: 
34: 	// managementInterface is a node's management interface in its pod, the interface the
35: 	// clabernetes planner gives the management address by default. It has the name the
36: 	// management interface has in a container of the local runtimes.
37: 	managementInterface = "eth0"
38: 	// loopbackInterface is reported like the local runtimes report it.
39: 	loopbackInterface = "lo"
40: 	// clabernetesAliasPrefix starts the interface aliases clabernetes marks its own interfaces
41: 	// and the lab links it wires with. They are not the topology's names, so they are not
42: 	// reported.
43: 	clabernetesAliasPrefix = "c9s:"
44: 	// zeroMAC is the hardware address sysfs reports for interfaces without one (loopback).
45: 	zeroMAC = "00:00:00:00:00:00"
46: 
47: 	// Interface event actions and link types, as the local runtimes report them.
48: 	interfaceActionSnapshot = "snapshot"
49: 	interfaceActionCreate   = "create"
50: 	interfaceActionUpdate   = "update"
51: 	interfaceActionDelete   = "delete"
52: 	interfaceActionStats    = "stats"
53: 	interfaceTypeVeth       = "veth"
54: 	interfaceTypeDevice     = "device"
55: 
56: 	// shell exit codes of a command that cannot be found or executed.
57: 	exitCommandNotExecutable = 126
58: 	exitCommandNotFound      = 127
59: )
60: 
61: type interfacePollOptions struct {
62: 	interval            time.Duration
63: 	includeStats        bool
64: 	includeInitialState bool
65: }
66: 
67: type c9sIfaceStats struct {
68: 	Name      string
69: 	RxBytes   uint64
70: 	RxPackets uint64
71: 	TxBytes   uint64
72: 	TxPackets uint64
73: }
74: 
75: type c9sIfaceStatsSample struct {
76: 	Stats     c9sIfaceStats
77: 	Timestamp time.Time
78: }
79: 
80: // c9sIfaceState is the sysfs view of one interface in a device container.
81: type c9sIfaceState struct {
82: 	Name      string
83: 	Index     int
84: 	MTU       int
85: 	MAC       string
86: 	OperState string
87: 	Flags     uint64
88: 	Alias     string
89: }
90: 
91: // trackedNode remembers the interfaces last reported for a node, so their changes and their
92: // removal can be reported, also when the node stops running.
93: type trackedNode struct {
94: 	lab    *clablabruntime.LabState
95: 	node   clablabruntime.NodeState
96: 	ifaces map[string]clablabruntime.InterfaceEventData
97: }
98: 
99: type interfaceSampleTarget struct {
100: 	state *clablabruntime.LabState
101: 	node  clablabruntime.NodeState
102: 	pod   *corev1.Pod
103: }
104: 
105: type interfaceSample struct {
106: 	target    interfaceSampleTarget
107: 	stats     []c9sIfaceStats
108: 	ifaces    []c9sIfaceState
109: 	hasStates bool
110: 	// links are the node's lab link interfaces as clabwire lists them.
111: 	links     []clabwireInterface
112: 	timestamp time.Time
113: 	err       error
114: }
115: 
116: // podInterfaceListing is the clabwire interface listing of a pod, per node. It is listed again
117: // when the pod's interfaces change.
118: type podInterfaceListing struct {
119: 	names  string
120: 	byNode map[string][]clabwireInterface
121: }
122: 
123: // interfacePoller samples the interfaces of every running node in an event scope and turns the
124: // samples into interface events. It reports the interfaces a container of the local runtimes
125: // has for the same node: the node's lab link interfaces, with the names and aliases clabwire
126: // lists for them, the management interface and loopback. The pod's own interfaces (the pod
127: // network, clabernetes' interposition and link transport interfaces) are not reported.
128: type interfacePoller struct {
129: 	r     *Runtime
130: 	scope eventScope
131: 	opts  interfacePollOptions
132: 	sink  chan<- clablabruntime.Event
133: 
134: 	statsSamples map[string]c9sIfaceStatsSample
135: 	nodes        map[string]*trackedNode
136: 
137: 	noShellMu sync.Mutex
138: 	// noShell holds the pods whose device container has no shell; they are sampled with a
139: 	// plain cat of /proc/net/dev and report statistics without interface state.
140: 	noShell map[string]bool
141: 
142: 	listingsMu sync.Mutex
143: 	// listings holds the clabwire interface listing per pod (namespace/pod).
144: 	listings map[string]*podInterfaceListing
145: 
146: 	firstRound bool
147: }
148: 
149: func (r *Runtime) pollInterfaces(
150: 	ctx context.Context,
151: 	scope eventScope,
152: 	opts interfacePollOptions,
153: 	eventSink chan<- clablabruntime.Event,
154: ) {
155: 	if opts.interval <= 0 {
156: 		opts.interval = time.Second
157: 	}
158: 
159: 	poller := newInterfacePoller(r, scope, opts, eventSink)
160: 	poller.round(ctx)
161: 
162: 	ticker := time.NewTicker(opts.interval)
163: 	defer ticker.Stop()
164: 
165: 	for {
166: 		select {
167: 		case <-ctx.Done():
168: 			return
169: 		case <-ticker.C:
170: 			poller.round(ctx)
171: 		}
172: 	}
173: }
174: 
175: func newInterfacePoller(
176: 	r *Runtime,
177: 	scope eventScope,
178: 	opts interfacePollOptions,
179: 	eventSink chan<- clablabruntime.Event,
180: ) *interfacePoller {
181: 	return &interfacePoller{
182: 		r:            r,
183: 		scope:        scope,
184: 		opts:         opts,
185: 		sink:         eventSink,
186: 		statsSamples: map[string]c9sIfaceStatsSample{},
187: 		nodes:        map[string]*trackedNode{},
188: 		noShell:      map[string]bool{},
189: 		listings:     map[string]*podInterfaceListing{},
190: 		firstRound:   true,
191: 	}
192: }
193: 
194: func (p *interfacePoller) round(ctx context.Context) {
195: 	defer func() { p.firstRound = false }()
196: 
197: 	states, err := p.r.labStates(ctx, p.scope)
198: 	if err != nil {
199: 		log.Debug("failed to list C9s labs for interface events", "error", err)
200: 		return
201: 	}
202: 
203: 	running := map[string]bool{}
204: 	pods := map[string]bool{}
205: 	var targets []interfaceSampleTarget
206: 	for _, state := range states {
207: 		for _, node := range state.Nodes {
208: 			if node.ContainerState != clablabruntime.ContainerStateRunning || node.Pod == "" ||
209: 				node.Container == "" {
210: 				continue
211: 			}
212: 
213: 			running[c9sNodeKey(state.Namespace, state.Name, node.Name)] = true
214: 			pods[state.Namespace+"/"+node.Pod] = true
215: 			targets = append(targets, interfaceSampleTarget{
216: 				state: state,
217: 				node:  node,
218: 				pod: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{
219: 					Name:      node.Pod,
220: 					Namespace: state.Namespace,
221: 				}},
222: 			})
223: 		}
224: 	}
225: 
226: 	for _, sample := range p.sampleAll(ctx, targets) {
227: 		if ctx.Err() != nil {
228: 			return
229: 		}
230: 		if sample.err != nil {
231: 			log.Debug("failed to sample C9s interfaces",
232: 				"namespace", sample.target.state.Namespace,
233: 				"lab", sample.target.state.Name,
234: 				"node", sample.target.node.Name,
235: 				"error", sample.err,
236: 			)
237: 
238: 			continue
239: 		}
240: 
241: 		p.processSample(ctx, sample)
242: 	}
243: 
244: 	p.retireStoppedNodes(ctx, running)
245: 	p.forgetListings(pods)
246: }
247: 
248: // retireStoppedNodes reports the interfaces of nodes that stopped running, or were removed, as
249: // deleted: they are gone with the node's pod.
250: func (p *interfacePoller) retireStoppedNodes(ctx context.Context, running map[string]bool) {
251: 	for key, tracked := range p.nodes {
252: 		if running[key] {
253: 			continue
254: 		}
255: 
256: 		for _, name := range sortedInterfaceNames(tracked.ifaces) {
257: 			p.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], time.Now())
258: 			p.forgetStats(tracked, name)
259: 		}
260: 		delete(p.nodes, key)
261: 	}
262: }
263: 
264: // forgetListings drops the interface listings of pods that are gone.
265: func (p *interfacePoller) forgetListings(pods map[string]bool) {
266: 	p.listingsMu.Lock()
267: 	defer p.listingsMu.Unlock()
268: 
269: 	for key := range p.listings {
270: 		if !pods[key] {
271: 			delete(p.listings, key)
272: 		}
273: 	}
274: }
275: 
276: func (p *interfacePoller) sampleAll(
277: 	ctx context.Context,
278: 	targets []interfaceSampleTarget,
279: ) []interfaceSample {
280: 	samples := make([]interfaceSample, len(targets))
281: 
282: 	var wg sync.WaitGroup
283: 	sem := make(chan struct{}, interfaceSampleWorkers)
284: 	for idx := range targets {
285: 		wg.Add(1)
286: 		sem <- struct{}{}
287: 		go func(idx int) {
288: 			defer wg.Done()
289: 			defer func() { <-sem }()
290: 
291: 			samples[idx] = p.sample(ctx, targets[idx])
292: 		}(idx)
293: 	}
294: 	wg.Wait()
295: 
296: 	return samples
297: }
298: 
299: func (p *interfacePoller) sample(
300: 	ctx context.Context,
301: 	target interfaceSampleTarget,
302: ) interfaceSample {
303: 	sample := interfaceSample{target: target}
304: 	podName := target.pod.Name
305: 
306: 	p.noShellMu.Lock()
307: 	noShell := p.noShell[podName]
308: 	p.noShellMu.Unlock()
309: 
310: 	command := []string{"sh", "-c", interfaceSampleScript}
311: 	if noShell {
312: 		command = []string{"cat", "/proc/net/dev"}
313: 	}
314: 
315: 	stdout, stderr, rc, err := p.r.execInPod(ctx, target.pod, target.node.Container, command)
316: 	if !noShell && commandNotExecutable(rc, err) {
317: 		p.noShellMu.Lock()
318: 		p.noShell[podName] = true
319: 		p.noShellMu.Unlock()
320: 
321: 		log.Debug("C9s device container has no shell; reporting interface statistics only",
322: 			"namespace", target.state.Namespace,
323: 			"lab", target.state.Name,
324: 			"node", target.node.Name,
325: 		)
326: 
327: 		stdout, stderr, rc, err = p.r.execInPod(ctx, target.pod, target.node.Container,
328: 			[]string{"cat", "/proc/net/dev"})
329: 	}
330: 
331: 	sample.timestamp = time.Now()
332: 	switch {
333: 	case err != nil:
334: 		sample.err = err
335: 	case rc != 0:
336: 		sample.err = fmt.Errorf("exit code %d: %s", rc, strings.TrimSpace(string(stderr)))
337: 	default:
338: 		sample.stats, sample.ifaces, sample.hasStates, sample.err = parseInterfaceSample(stdout)
339: 	}
340: 	if sample.err != nil {
341: 		return sample
342: 	}
343: 
344: 	sample.links, sample.err = p.nodeLinks(ctx, target, sampledInterfaceNames(sample))
345: 
346: 	return sample
347: }
348: 
349: // sampledInterfaceNames lists the interface names a sample saw, sorted and comma-joined.
350: func sampledInterfaceNames(sample interfaceSample) string {
351: 	names := make([]string, 0, len(sample.stats)+len(sample.ifaces))
352: 	seen := map[string]bool{}
353: 	for _, iface := range sample.ifaces {
354: 		if !seen[iface.Name] {
355: 			seen[iface.Name] = true
356: 			names = append(names, iface.Name)
357: 		}
358: 	}
359: 	for _, stat := range sample.stats {
360: 		if !seen[stat.Name] {
361: 			seen[stat.Name] = true
362: 			names = append(names, stat.Name)
363: 		}
364: 	}
365: 	sort.Strings(names)
366: 
367: 	return strings.Join(names, ",")
368: }
369: 
370: // nodeLinks returns the lab link interfaces of a node from its pod's clabwire listing. A pod is
371: // listed once, and again when its interfaces change (a pod gets its link interfaces as clabwire
372: // wires them).
373: func (p *interfacePoller) nodeLinks(
374: 	ctx context.Context,
375: 	target interfaceSampleTarget,
376: 	names string,
377: ) ([]clabwireInterface, error) {
378: 	key := target.pod.Namespace + "/" + target.pod.Name
379: 
380: 	p.listingsMu.Lock()
381: 	listing := p.listings[key]
382: 	p.listingsMu.Unlock()
383: 
384: 	if listing == nil || listing.names != names {
385: 		entries, err := p.r.listPodInterfaces(ctx, target.pod.Namespace, target.pod.Name)
386: 		if err != nil {
387: 			return nil, err
388: 		}
389: 
390: 		listing = &podInterfaceListing{
391: 			names:  names,
392: 			byNode: map[string][]clabwireInterface{},
393: 		}
394: 		for _, entry := range entries {
395: 			listing.byNode[entry.Node] = append(listing.byNode[entry.Node], entry)
396: 		}
397: 
398: 		p.listingsMu.Lock()
399: 		p.listings[key] = listing
400: 		p.listingsMu.Unlock()
401: 	}
402: 
403: 	return listing.byNode[target.node.Name], nil
404: }
405: 
406: // commandNotExecutable reports an exec that failed because the command does not exist in the
407: // container.
408: func commandNotExecutable(rc int, err error) bool {
409: 	if rc == exitCommandNotExecutable || rc == exitCommandNotFound {
410: 		return true
411: 	}
412: 
413: 	return err != nil && strings.Contains(err.Error(), "executable file not found")
414: }
415: 
416: // reportedInterfaces are the interfaces reported for a node, by name, with the alias the
417: // topology gave them: its lab link interfaces, the management interface and loopback.
418: func reportedInterfaces(links []clabwireInterface) map[string]string {
419: 	reported := map[string]string{
420: 		loopbackInterface:   "",
421: 		managementInterface: "",
422: 	}
423: 	for _, link := range links {
424: 		reported[link.Interface] = link.Alias
425: 	}
426: 
427: 	return reported
428: }
429: 
430: // interfaceEventData describes an interface the way the local runtimes' netlink events do: the
431: // alias is the topology's name for the interface (an alias clabernetes set for its own use is
432: // not reported), the operational state uses netlink's names, lab link and management
433: // interfaces are veth pairs, loopback a device, and loopback has no hardware address.
434: func interfaceEventData(iface c9sIfaceState, alias string) clablabruntime.InterfaceEventData {
435: 	if alias == "" && !strings.HasPrefix(iface.Alias, clabernetesAliasPrefix) {
436: 		alias = iface.Alias
437: 	}
438: 
439: 	mac := iface.MAC
440: 	if mac == zeroMAC {
441: 		mac = ""
442: 	}
443: 
444: 	linkType := interfaceTypeVeth
445: 	if iface.Name == loopbackInterface {
446: 		linkType = interfaceTypeDevice
447: 	}
448: 
449: 	return clablabruntime.InterfaceEventData{
450: 		Name:      iface.Name,
451: 		Alias:     alias,
452: 		Index:     iface.Index,
453: 		MTU:       iface.MTU,
454: 		MAC:       mac,
455: 		OperState: netlinkOperState(iface.OperState),
456: 		Type:      linkType,
457: 	}
458: }
459: 
460: // netlinkOperState names an operational state from sysfs (RFC 2863, as in
461: // /sys/class/net/<if>/operstate) the way netlink, and so the local runtimes' events, name it.
462: func netlinkOperState(operState string) string {
463: 	switch operState {
464: 	case "notpresent":
465: 		return "not-present"
466: 	case "lowerlayerdown":
467: 		return "lower-layer-down"
468: 	case "":
469: 		return "unknown"
470: 	default:
471: 		return operState
472: 	}
473: }
474: 
475: func (p *interfacePoller) processSample(ctx context.Context, sample interfaceSample) {
476: 	state := sample.target.state
477: 	node := sample.target.node
478: 	key := c9sNodeKey(state.Namespace, state.Name, node.Name)
479: 
480: 	tracked, known := p.nodes[key]
481: 	if !known {
482: 		tracked = &trackedNode{ifaces: map[string]clablabruntime.InterfaceEventData{}}
483: 		p.nodes[key] = tracked
484: 	}
485: 	tracked.lab = state
486: 	tracked.node = node
487: 
488: 	reported := reportedInterfaces(sample.links)
489: 
490: 	if sample.hasStates {
491: 		p.processStates(ctx, tracked, reported, sample)
492: 	}
493: 
494: 	if !p.opts.includeStats {
495: 		return
496: 	}
497: 	for _, stat := range sample.stats {
498: 		alias, ok := reported[stat.Name]
499: 		if !ok {
500: 			continue
501: 		}
502: 
503: 		statsKey := c9sIfaceStatsKey(state.Namespace, state.Name, node.Name, stat.Name)
504: 		current := c9sIfaceStatsSample{Stats: stat, Timestamp: sample.timestamp}
505: 		if previous, ok := p.statsSamples[statsKey]; ok {
506: 			data, ok := tracked.ifaces[stat.Name]
507: 			if !ok {
508: 				data = interfaceEventData(c9sIfaceState{Name: stat.Name}, alias)
509: 				data.OperState = ""
510: 			}
511: 			data.Stats = c9sIfaceStatsData(previous, current)
512: 			p.emit(ctx, tracked, interfaceActionStats, data, current.Timestamp)
513: 		}
514: 
515: 		p.statsSamples[statsKey] = current
516: 	}
517: }
518: 
519: // processStates reports the interfaces that appeared (snapshot in the first round with
520: // --initial-state, create later), changed (update) or disappeared (delete) since the last
521: // sample, like the netlink events of the local runtimes.
522: func (p *interfacePoller) processStates(
523: 	ctx context.Context,
524: 	tracked *trackedNode,
525: 	reported map[string]string,
526: 	sample interfaceSample,
527: ) {
528: 	present := map[string]bool{}
529: 	for _, iface := range sample.ifaces {
530: 		alias, ok := reported[iface.Name]
531: 		if !ok {
532: 			continue
533: 		}
534: 
535: 		data := interfaceEventData(iface, alias)
536: 		present[iface.Name] = true
537: 		previous, seen := tracked.ifaces[iface.Name]
538: 		tracked.ifaces[iface.Name] = data
539: 
540: 		switch {
541: 		case seen && previous == data:
542: 		case !seen && p.firstRound:
543: 			// Interfaces that exist when the stream starts are only reported with
544: 			// --initial-state; later changes are always reported.
545: 			if p.opts.includeInitialState {
546: 				p.emit(ctx, tracked, interfaceActionSnapshot, data, sample.timestamp)
547: 			}
548: 		case !seen:
549: 			p.emit(ctx, tracked, interfaceActionCreate, data, sample.timestamp)
550: 		default:
551: 			p.emit(ctx, tracked, interfaceActionUpdate, data, sample.timestamp)
552: 		}
553: 	}
554: 
555: 	for _, name := range sortedInterfaceNames(tracked.ifaces) {
556: 		if present[name] {
557: 			continue
558: 		}
559: 
560: 		p.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], sample.timestamp)
561: 		p.forgetStats(tracked, name)
562: 		delete(tracked.ifaces, name)
563: 	}
564: }
565: 
566: func sortedInterfaceNames(ifaces map[string]clablabruntime.InterfaceEventData) []string {
567: 	names := make([]string, 0, len(ifaces))
568: 	for name := range ifaces {
569: 		names = append(names, name)
570: 	}
571: 	sort.Strings(names)
572: 
573: 	return names
574: }
575: 
576: func (p *interfacePoller) forgetStats(tracked *trackedNode, ifName string) {
577: 	delete(p.statsSamples,
578: 		c9sIfaceStatsKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name, ifName))
579: }
580: 
581: func (p *interfacePoller) emit(
582: 	ctx context.Context,
583: 	tracked *trackedNode,
584: 	action string,
585: 	data clablabruntime.InterfaceEventData,
586: 	timestamp time.Time,
587: ) {
588: 	p.r.sendEvent(ctx, p.sink, c9sInterfaceEvent(tracked, action, data, timestamp))
589: }
590: 
591: // c9sInterfaceEvent is an interface event of a node. The actor is the node, as for its container
592: // events. The interface itself is in Interface; the events command reports it with the
593: // attributes of the local runtimes' interface events.
594: func c9sInterfaceEvent(
595: 	tracked *trackedNode,
596: 	action string,
597: 	data clablabruntime.InterfaceEventData,
598: 	timestamp time.Time,
599: ) clablabruntime.Event {
600: 	key := c9sNodeKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name)
601: 
602: 	attributes := map[string]string{
603: 		"namespace": tracked.lab.Namespace,
604: 		"lab":       tracked.lab.Name,
605: 		"node":      tracked.node.Name,
606: 		"origin":    clabernetesAppValue,
607: 	}
608: 	if tracked.node.Pod != "" {
609: 		attributes["pod"] = tracked.node.Pod
610: 	}
611: 
612: 	node := tracked.node
613: 
614: 	return clablabruntime.Event{
615: 		Timestamp:   timestamp,
616: 		Type:        clablabruntime.EventTypeInterface,
617: 		Action:      action,
618: 		ActorID:     key,
619: 		ActorName:   fmt.Sprintf("%s-%s", tracked.lab.Name, tracked.node.Name),
620: 		ActorFullID: key,
621: 		Attributes:  attributes,
622: 		Lab:         tracked.lab,
623: 		Node:        &node,
624: 		Interface:   &data,
625: 	}
626: }
627: 
628: // c9sIfaceStatsData computes the counters and rates of a stats event from two samples.
629: func c9sIfaceStatsData(previous, current c9sIfaceStatsSample) *clablabruntime.InterfaceStats {
630: 	interval := current.Timestamp.Sub(previous.Timestamp)
631: 	if interval <= 0 {
632: 		interval = time.Second
633: 	}
634: 
635: 	seconds := interval.Seconds()
636: 	stat := current.Stats
637: 
638: 	return &clablabruntime.InterfaceStats{
639: 		RxBytes:   stat.RxBytes,
640: 		TxBytes:   stat.TxBytes,
641: 		RxPackets: stat.RxPackets,
642: 		TxPackets: stat.TxPackets,
643: 		RxBps:     float64(counterDelta(stat.RxBytes, previous.Stats.RxBytes)*8) / seconds,
644: 		TxBps:     float64(counterDelta(stat.TxBytes, previous.Stats.TxBytes)*8) / seconds,
645: 		RxPps:     float64(counterDelta(stat.RxPackets, previous.Stats.RxPackets)) / seconds,
646: 		TxPps:     float64(counterDelta(stat.TxPackets, previous.Stats.TxPackets)) / seconds,
647: 		Interval:  interval,
648: 	}
649: }
650: 
651: // parseInterfaceSample splits the output of interfaceSampleScript into the /proc/net/dev
652: // counters and the sysfs interface states. hasStates is false for output without the sysfs
653: // section, such as a plain cat of /proc/net/dev.
654: func parseInterfaceSample(data []byte) ([]c9sIfaceStats, []c9sIfaceState, bool, error) {
655: 	text := string(data)
656: 
657: 	procPart, sysfsPart, hasStates := strings.Cut(text, interfaceSysfsMarker+"\n")
658: 	if !hasStates {
659: 		procPart, _, hasStates = strings.Cut(text, interfaceSysfsMarker)
660: 	}
661: 
662: 	stats, err := parseProcNetDev([]byte(procPart))
663: 	if err != nil {
664: 		return nil, nil, false, err
665: 	}
666: 	if !hasStates {
667: 		return stats, nil, false, nil
668: 	}
669: 
670: 	return stats, parseSysfsInterfaces(sysfsPart), true, nil
671: }
672: 
673: func parseSysfsInterfaces(data string) []c9sIfaceState {
674: 	lines := strings.Split(data, "\n")
675: 	states := make([]c9sIfaceState, 0, len(lines))
676: 
677: 	for _, line := range lines {
678: 		fields := strings.SplitN(line, "\t", 7) //nolint:mnd
679: 		if len(fields) < 5 || strings.TrimSpace(fields[0]) == "" {
680: 			continue
681: 		}
682: 
683: 		state := c9sIfaceState{
684: 			Name:      strings.TrimSpace(fields[0]),
685: 			MAC:       strings.TrimSpace(fields[3]),
686: 			OperState: strings.ToLower(strings.TrimSpace(fields[4])),
687: 		}
688: 		state.Index, _ = strconv.Atoi(strings.TrimSpace(fields[1]))
689: 		state.MTU, _ = strconv.Atoi(strings.TrimSpace(fields[2]))
690: 		if len(fields) > 5 {
691: 			state.Flags, _ = strconv.ParseUint(
692: 				strings.TrimPrefix(strings.TrimSpace(fields[5]), "0x"), 16, 64)
693: 		}
694: 		if len(fields) > 6 {
695: 			state.Alias = strings.TrimSpace(fields[6])
696: 		}
697: 		if state.OperState == "" {
698: 			state.OperState = "unknown"
699: 		}
700: 
701: 		states = append(states, state)
702: 	}
703: 
704: 	return states
705: }
706: 
707: func parseProcNetDev(data []byte) ([]c9sIfaceStats, error) {
708: 	lines := strings.Split(string(data), "\n")
709: 	stats := make([]c9sIfaceStats, 0, len(lines))
710: 
711: 	for _, line := range lines {
712: 		line = strings.TrimSpace(line)
713: 		if line == "" || !strings.Contains(line, ":") {
714: 			continue
715: 		}
716: 
717: 		parts := strings.SplitN(line, ":", 2)
718: 		if len(parts) != 2 {
719: 			continue
720: 		}
721: 
722: 		ifName := strings.TrimSpace(parts[0])
723: 		fields := strings.Fields(parts[1])
724: 		if len(fields) < 16 {
725: 			return nil, fmt.Errorf("unexpected /proc/net/dev line for %q: %q", ifName, line)
726: 		}
727: 
728: 		rxBytes, err := strconv.ParseUint(fields[0], 10, 64)
729: 		if err != nil {
730: 			return nil, fmt.Errorf("failed to parse rx bytes for %q: %w", ifName, err)
731: 		}
732: 		rxPackets, err := strconv.ParseUint(fields[1], 10, 64)
733: 		if err != nil {
734: 			return nil, fmt.Errorf("failed to parse rx packets for %q: %w", ifName, err)
735: 		}
736: 		txBytes, err := strconv.ParseUint(fields[8], 10, 64)
737: 		if err != nil {
738: 			return nil, fmt.Errorf("failed to parse tx bytes for %q: %w", ifName, err)
739: 		}
740: 		txPackets, err := strconv.ParseUint(fields[9], 10, 64)
741: 		if err != nil {
742: 			return nil, fmt.Errorf("failed to parse tx packets for %q: %w", ifName, err)
743: 		}
744: 
745: 		stats = append(stats, c9sIfaceStats{
746: 			Name:      ifName,
747: 			RxBytes:   rxBytes,
748: 			RxPackets: rxPackets,
749: 			TxBytes:   txBytes,
750: 			TxPackets: txPackets,
751: 		})
752: 	}
753: 
754: 	return stats, nil
755: }
756: 
757: // c9sNodeKey is the actor ID of a node: <namespace>/<lab>/<node>, the same value inspect
758: // reports as container_id.
759: func c9sNodeKey(namespace, lab, node string) string {
760: 	return namespace + "/" + lab + "/" + node
761: }
762: 
763: func c9sIfaceStatsKey(namespace, lab, node, ifName string) string {
764: 	return c9sNodeKey(namespace, lab, node) + "/" + ifName
765: }
766: 
767: func counterDelta(current, previous uint64) uint64 {
768: 	if current < previous {
769: 		return 0
770: 	}
771: 
772: 	return current - previous
773: }

(End of file - total 773 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19677307c001k1bvjc6Q2DWnqM",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196770857001sQDZoRoeELv1VY",
  "callID": "call_85e214f781334f7da8b8149f",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/iface_stats.go"
    },
    "output": "<path>/source/head/labruntime/clabernetes/iface_stats.go</path>\n<type>file</type>\n<content>\n1: package clabernetes\n2: \n3: import (\n4: \t\"context\"\n5: \t\"fmt\"\n6: \t\"sort\"\n7: \t\"strconv\"\n8: \t\"strings\"\n9: \t\"sync\"\n10: \t\"time\"\n11: \n12: \t\"github.com/charmbracelet/log\"\n13: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n14: \tcorev1 \"k8s.io/api/core/v1\"\n15: \tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n16: )\n17: \n18: const (\n19: \t// interfaceSysfsMarker separates the /proc/net/dev counters from the sysfs interface\n20: \t// attributes in the output of interfaceSampleScript.\n21: \tinterfaceSysfsMarker = \"@@clab-sysfs\"\n22: \t// interfaceSampleScript reads the interface counters and, per interface, the sysfs\n23: \t// attributes the interface state events carry, in one exec:\n24: \t// name, ifindex, mtu, address, operstate, flags and ifalias, tab separated.\n25: \tinterfaceSampleScript = `cat /proc/net/dev; echo ` + interfaceSysfsMarker + `; ` +\n26: \t\t`for d in /sys/class/net/*; do [ -e \"$d/operstate\" ] || continue; ` +\n27: \t\t`printf '%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n' \"${d##*/}\" \"$(cat \"$d/ifindex\")\" ` +\n28: \t\t`\"$(cat \"$d/mtu\")\" \"$(cat \"$d/address\")\" \"$(cat \"$d/operstate\")\" ` +\n29: \t\t`\"$(cat \"$d/flags\")\" \"$(cat \"$d/ifalias\")\"; done 2>/dev/null`\n30: \n31: \t// interfaceSampleWorkers bounds the concurrent execs of one sampling round.\n32: \tinterfaceSampleWorkers = 16\n33: \n34: \t// managementInterface is a node's management interface in its pod, the interface the\n35: \t// clabernetes planner gives the management address by default. It has the name the\n36: \t// management interface has in a container of the local runtimes.\n37: \tmanagementInterface = \"eth0\"\n38: \t// loopbackInterface is reported like the local runtimes report it.\n39: \tloopbackInterface = \"lo\"\n40: \t// clabernetesAliasPrefix starts the interface aliases clabernetes marks its own interfaces\n41: \t// and the lab links it wires with. They are not the topology's names, so they are not\n42: \t// reported.\n43: \tclabernetesAliasPrefix = \"c9s:\"\n44: \t// zeroMAC is the hardware address sysfs reports for interfaces without one (loopback).\n45: \tzeroMAC = \"00:00:00:00:00:00\"\n46: \n47: \t// Interface event actions and link types, as the local runtimes report them.\n48: \tinterfaceActionSnapshot = \"snapshot\"\n49: \tinterfaceActionCreate   = \"create\"\n50: \tinterfaceActionUpdate   = \"update\"\n51: \tinterfaceActionDelete   = \"delete\"\n52: \tinterfaceActionStats    = \"stats\"\n53: \tinterfaceTypeVeth       = \"veth\"\n54: \tinterfaceTypeDevice     = \"device\"\n55: \n56: \t// shell exit codes of a command that cannot be found or executed.\n57: \texitCommandNotExecutable = 126\n58: \texitCommandNotFound      = 127\n59: )\n60: \n61: type interfacePollOptions struct {\n62: \tinterval            time.Duration\n63: \tincludeStats        bool\n64: \tincludeInitialState bool\n65: }\n66: \n67: type c9sIfaceStats struct {\n68: \tName      string\n69: \tRxBytes   uint64\n70: \tRxPackets uint64\n71: \tTxBytes   uint64\n72: \tTxPackets uint64\n73: }\n74: \n75: type c9sIfaceStatsSample struct {\n76: \tStats     c9sIfaceStats\n77: \tTimestamp time.Time\n78: }\n79: \n80: // c9sIfaceState is the sysfs view of one interface in a device container.\n81: type c9sIfaceState struct {\n82: \tName      string\n83: \tIndex     int\n84: \tMTU       int\n85: \tMAC       string\n86: \tOperState string\n87: \tFlags     uint64\n88: \tAlias     string\n89: }\n90: \n91: // trackedNode remembers the interfaces last reported for a node, so their changes and their\n92: // removal can be reported, also when the node stops running.\n93: type trackedNode struct {\n94: \tlab    *clablabruntime.LabState\n95: \tnode   clablabruntime.NodeState\n96: \tifaces map[string]clablabruntime.InterfaceEventData\n97: }\n98: \n99: type interfaceSampleTarget struct {\n100: \tstate *clablabruntime.LabState\n101: \tnode  clablabruntime.NodeState\n102: \tpod   *corev1.Pod\n103: }\n104: \n105: type interfaceSample struct {\n106: \ttarget    interfaceSampleTarget\n107: \tstats     []c9sIfaceStats\n108: \tifaces    []c9sIfaceState\n109: \thasStates bool\n110: \t// links are the node's lab link interfaces as clabwire lists them.\n111: \tlinks     []clabwireInterface\n112: \ttimestamp time.Time\n113: \terr       error\n114: }\n115: \n116: // podInterfaceListing is the clabwire interface listing of a pod, per node. It is listed again\n117: // when the pod's interfaces change.\n118: type podInterfaceListing struct {\n119: \tnames  string\n120: \tbyNode map[string][]clabwireInterface\n121: }\n122: \n123: // interfacePoller samples the interfaces of every running node in an event scope and turns the\n124: // samples into interface events. It reports the interfaces a container of the local runtimes\n125: // has for the same node: the node's lab link interfaces, with the names and aliases clabwire\n126: // lists for them, the management interface and loopback. The pod's own interfaces (the pod\n127: // network, clabernetes' interposition and link transport interfaces) are not reported.\n128: type interfacePoller struct {\n129: \tr     *Runtime\n130: \tscope eventScope\n131: \topts  interfacePollOptions\n132: \tsink  chan<- clablabruntime.Event\n133: \n134: \tstatsSamples map[string]c9sIfaceStatsSample\n135: \tnodes        map[string]*trackedNode\n136: \n137: \tnoShellMu sync.Mutex\n138: \t// noShell holds the pods whose device container has no shell; they are sampled with a\n139: \t// plain cat of /proc/net/dev and report statistics without interface state.\n140: \tnoShell map[string]bool\n141: \n142: \tlistingsMu sync.Mutex\n143: \t// listings holds the clabwire interface listing per pod (namespace/pod).\n144: \tlistings map[string]*podInterfaceListing\n145: \n146: \tfirstRound bool\n147: }\n148: \n149: func (r *Runtime) pollInterfaces(\n150: \tctx context.Context,\n151: \tscope eventScope,\n152: \topts interfacePollOptions,\n153: \teventSink chan<- clablabruntime.Event,\n154: ) {\n155: \tif opts.interval <= 0 {\n156: \t\topts.interval = time.Second\n157: \t}\n158: \n159: \tpoller := newInterfacePoller(r, scope, opts, eventSink)\n160: \tpoller.round(ctx)\n161: \n162: \tticker := time.NewTicker(opts.interval)\n163: \tdefer ticker.Stop()\n164: \n165: \tfor {\n166: \t\tselect {\n167: \t\tcase <-ctx.Done():\n168: \t\t\treturn\n169: \t\tcase <-ticker.C:\n170: \t\t\tpoller.round(ctx)\n171: \t\t}\n172: \t}\n173: }\n174: \n175: func newInterfacePoller(\n176: \tr *Runtime,\n177: \tscope eventScope,\n178: \topts interfacePollOptions,\n179: \teventSink chan<- clablabruntime.Event,\n180: ) *interfacePoller {\n181: \treturn &interfacePoller{\n182: \t\tr:            r,\n183: \t\tscope:        scope,\n184: \t\topts:         opts,\n185: \t\tsink:         eventSink,\n186: \t\tstatsSamples: map[string]c9sIfaceStatsSample{},\n187: \t\tnodes:        map[string]*trackedNode{},\n188: \t\tnoShell:      map[string]bool{},\n189: \t\tlistings:     map[string]*podInterfaceListing{},\n190: \t\tfirstRound:   true,\n191: \t}\n192: }\n193: \n194: func (p *interfacePoller) round(ctx context.Context) {\n195: \tdefer func() { p.firstRound = false }()\n196: \n197: \tstates, err := p.r.labStates(ctx, p.scope)\n198: \tif err != nil {\n199: \t\tlog.Debug(\"failed to list C9s labs for interface events\", \"error\", err)\n200: \t\treturn\n201: \t}\n202: \n203: \trunning := map[string]bool{}\n204: \tpods := map[string]bool{}\n205: \tvar targets []interfaceSampleTarget\n206: \tfor _, state := range states {\n207: \t\tfor _, node := range state.Nodes {\n208: \t\t\tif node.ContainerState != clablabruntime.ContainerStateRunning || node.Pod == \"\" ||\n209: \t\t\t\tnode.Container == \"\" {\n210: \t\t\t\tcontinue\n211: \t\t\t}\n212: \n213: \t\t\trunning[c9sNodeKey(state.Namespace, state.Name, node.Name)] = true\n214: \t\t\tpods[state.Namespace+\"/\"+node.Pod] = true\n215: \t\t\ttargets = append(targets, interfaceSampleTarget{\n216: \t\t\t\tstate: state,\n217: \t\t\t\tnode:  node,\n218: \t\t\t\tpod: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{\n219: \t\t\t\t\tName:      node.Pod,\n220: \t\t\t\t\tNamespace: state.Namespace,\n221: \t\t\t\t}},\n222: \t\t\t})\n223: \t\t}\n224: \t}\n225: \n226: \tfor _, sample := range p.sampleAll(ctx, targets) {\n227: \t\tif ctx.Err() != nil {\n228: \t\t\treturn\n229: \t\t}\n230: \t\tif sample.err != nil {\n231: \t\t\tlog.Debug(\"failed to sample C9s interfaces\",\n232: \t\t\t\t\"namespace\", sample.target.state.Namespace,\n233: \t\t\t\t\"lab\", sample.target.state.Name,\n234: \t\t\t\t\"node\", sample.target.node.Name,\n235: \t\t\t\t\"error\", sample.err,\n236: \t\t\t)\n237: \n238: \t\t\tcontinue\n239: \t\t}\n240: \n241: \t\tp.processSample(ctx, sample)\n242: \t}\n243: \n244: \tp.retireStoppedNodes(ctx, running)\n245: \tp.forgetListings(pods)\n246: }\n247: \n248: // retireStoppedNodes reports the interfaces of nodes that stopped running, or were removed, as\n249: // deleted: they are gone with the node's pod.\n250: func (p *interfacePoller) retireStoppedNodes(ctx context.Context, running map[string]bool) {\n251: \tfor key, tracked := range p.nodes {\n252: \t\tif running[key] {\n253: \t\t\tcontinue\n254: \t\t}\n255: \n256: \t\tfor _, name := range sortedInterfaceNames(tracked.ifaces) {\n257: \t\t\tp.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], time.Now())\n258: \t\t\tp.forgetStats(tracked, name)\n259: \t\t}\n260: \t\tdelete(p.nodes, key)\n261: \t}\n262: }\n263: \n264: // forgetListings drops the interface listings of pods that are gone.\n265: func (p *interfacePoller) forgetListings(pods map[string]bool) {\n266: \tp.listingsMu.Lock()\n267: \tdefer p.listingsMu.Unlock()\n268: \n269: \tfor key := range p.listings {\n270: \t\tif !pods[key] {\n271: \t\t\tdelete(p.listings, key)\n272: \t\t}\n273: \t}\n274: }\n275: \n276: func (p *interfacePoller) sampleAll(\n277: \tctx context.Context,\n278: \ttargets []interfaceSampleTarget,\n279: ) []interfaceSample {\n280: \tsamples := make([]interfaceSample, len(targets))\n281: \n282: \tvar wg sync.WaitGroup\n283: \tsem := make(chan struct{}, interfaceSampleWorkers)\n284: \tfor idx := range targets {\n285: \t\twg.Add(1)\n286: \t\tsem <- struct{}{}\n287: \t\tgo func(idx int) {\n288: \t\t\tdefer wg.Done()\n289: \t\t\tdefer func() { <-sem }()\n290: \n291: \t\t\tsamples[idx] = p.sample(ctx, targets[idx])\n292: \t\t}(idx)\n293: \t}\n294: \twg.Wait()\n295: \n296: \treturn samples\n297: }\n298: \n299: func (p *interfacePoller) sample(\n300: \tctx context.Context,\n301: \ttarget interfaceSampleTarget,\n302: ) interfaceSample {\n303: \tsample := interfaceSample{target: target}\n304: \tpodName := target.pod.Name\n305: \n306: \tp.noShellMu.Lock()\n307: \tnoShell := p.noShell[podName]\n308: \tp.noShellMu.Unlock()\n309: \n310: \tcommand := []string{\"sh\", \"-c\", interfaceSampleScript}\n311: \tif noShell {\n312: \t\tcommand = []string{\"cat\", \"/proc/net/dev\"}\n313: \t}\n314: \n315: \tstdout, stderr, rc, err := p.r.execInPod(ctx, target.pod, target.node.Container, command)\n316: \tif !noShell && commandNotExecutable(rc, err) {\n317: \t\tp.noShellMu.Lock()\n318: \t\tp.noShell[podName] = true\n319: \t\tp.noShellMu.Unlock()\n320: \n321: \t\tlog.Debug(\"C9s device container has no shell; reporting interface statistics only\",\n322: \t\t\t\"namespace\", target.state.Namespace,\n323: \t\t\t\"lab\", target.state.Name,\n324: \t\t\t\"node\", target.node.Name,\n325: \t\t)\n326: \n327: \t\tstdout, stderr, rc, err = p.r.execInPod(ctx, target.pod, target.node.Container,\n328: \t\t\t[]string{\"cat\", \"/proc/net/dev\"})\n329: \t}\n330: \n331: \tsample.timestamp = time.Now()\n332: \tswitch {\n333: \tcase err != nil:\n334: \t\tsample.err = err\n335: \tcase rc != 0:\n336: \t\tsample.err = fmt.Errorf(\"exit code %d: %s\", rc, strings.TrimSpace(string(stderr)))\n337: \tdefault:\n338: \t\tsample.stats, sample.ifaces, sample.hasStates, sample.err = parseInterfaceSample(stdout)\n339: \t}\n340: \tif sample.err != nil {\n341: \t\treturn sample\n342: \t}\n343: \n344: \tsample.links, sample.err = p.nodeLinks(ctx, target, sampledInterfaceNames(sample))\n345: \n346: \treturn sample\n347: }\n348: \n349: // sampledInterfaceNames lists the interface names a sample saw, sorted and comma-joined.\n350: func sampledInterfaceNames(sample interfaceSample) string {\n351: \tnames := make([]string, 0, len(sample.stats)+len(sample.ifaces))\n352: \tseen := map[string]bool{}\n353: \tfor _, iface := range sample.ifaces {\n354: \t\tif !seen[iface.Name] {\n355: \t\t\tseen[iface.Name] = true\n356: \t\t\tnames = append(names, iface.Name)\n357: \t\t}\n358: \t}\n359: \tfor _, stat := range sample.stats {\n360: \t\tif !seen[stat.Name] {\n361: \t\t\tseen[stat.Name] = true\n362: \t\t\tnames = append(names, stat.Name)\n363: \t\t}\n364: \t}\n365: \tsort.Strings(names)\n366: \n367: \treturn strings.Join(names, \",\")\n368: }\n369: \n370: // nodeLinks returns the lab link interfaces of a node from its pod's clabwire listing. A pod is\n371: // listed once, and again when its interfaces change (a pod gets its link interfaces as clabwire\n372: // wires them).\n373: func (p *interfacePoller) nodeLinks(\n374: \tctx context.Context,\n375: \ttarget interfaceSampleTarget,\n376: \tnames string,\n377: ) ([]clabwireInterface, error) {\n378: \tkey := target.pod.Namespace + \"/\" + target.pod.Name\n379: \n380: \tp.listingsMu.Lock()\n381: \tlisting := p.listings[key]\n382: \tp.listingsMu.Unlock()\n383: \n384: \tif listing == nil || listing.names != names {\n385: \t\tentries, err := p.r.listPodInterfaces(ctx, target.pod.Namespace, target.pod.Name)\n386: \t\tif err != nil {\n387: \t\t\treturn nil, err\n388: \t\t}\n389: \n390: \t\tlisting = &podInterfaceListing{\n391: \t\t\tnames:  names,\n392: \t\t\tbyNode: map[string][]clabwireInterface{},\n393: \t\t}\n394: \t\tfor _, entry := range entries {\n395: \t\t\tlisting.byNode[entry.Node] = append(listing.byNode[entry.Node], entry)\n396: \t\t}\n397: \n398: \t\tp.listingsMu.Lock()\n399: \t\tp.listings[key] = listing\n400: \t\tp.listingsMu.Unlock()\n401: \t}\n402: \n403: \treturn listing.byNode[target.node.Name], nil\n404: }\n405: \n406: // commandNotExecutable reports an exec that failed because the command does not exist in the\n407: // container.\n408: func commandNotExecutable(rc int, err error) bool {\n409: \tif rc == exitCommandNotExecutable || rc == exitCommandNotFound {\n410: \t\treturn true\n411: \t}\n412: \n413: \treturn err != nil && strings.Contains(err.Error(), \"executable file not found\")\n414: }\n415: \n416: // reportedInterfaces are the interfaces reported for a node, by name, with the alias the\n417: // topology gave them: its lab link interfaces, the management interface and loopback.\n418: func reportedInterfaces(links []clabwireInterface) map[string]string {\n419: \treported := map[string]string{\n420: \t\tloopbackInterface:   \"\",\n421: \t\tmanagementInterface: \"\",\n422: \t}\n423: \tfor _, link := range links {\n424: \t\treported[link.Interface] = link.Alias\n425: \t}\n426: \n427: \treturn reported\n428: }\n429: \n430: // interfaceEventData describes an interface the way the local runtimes' netlink events do: the\n431: // alias is the topology's name for the interface (an alias clabernetes set for its own use is\n432: // not reported), the operational state uses netlink's names, lab link and management\n433: // interfaces are veth pairs, loopback a device, and loopback has no hardware address.\n434: func interfaceEventData(iface c9sIfaceState, alias string) clablabruntime.InterfaceEventData {\n435: \tif alias == \"\" && !strings.HasPrefix(iface.Alias, clabernetesAliasPrefix) {\n436: \t\talias = iface.Alias\n437: \t}\n438: \n439: \tmac := iface.MAC\n440: \tif mac == zeroMAC {\n441: \t\tmac = \"\"\n442: \t}\n443: \n444: \tlinkType := interfaceTypeVeth\n445: \tif iface.Name == loopbackInterface {\n446: \t\tlinkType = interfaceTypeDevice\n447: \t}\n448: \n449: \treturn clablabruntime.InterfaceEventData{\n450: \t\tName:      iface.Name,\n451: \t\tAlias:     alias,\n452: \t\tIndex:     iface.Index,\n453: \t\tMTU:       iface.MTU,\n454: \t\tMAC:       mac,\n455: \t\tOperState: netlinkOperState(iface.OperState),\n456: \t\tType:      linkType,\n457: \t}\n458: }\n459: \n460: // netlinkOperState names an operational state from sysfs (RFC 2863, as in\n461: // /sys/class/net/<if>/operstate) the way netlink, and so the local runtimes' events, name it.\n462: func netlinkOperState(operState string) string {\n463: \tswitch operState {\n464: \tcase \"notpresent\":\n465: \t\treturn \"not-present\"\n466: \tcase \"lowerlayerdown\":\n467: \t\treturn \"lower-layer-down\"\n468: \tcase \"\":\n469: \t\treturn \"unknown\"\n470: \tdefault:\n471: \t\treturn operState\n472: \t}\n473: }\n474: \n475: func (p *interfacePoller) processSample(ctx context.Context, sample interfaceSample) {\n476: \tstate := sample.target.state\n477: \tnode := sample.target.node\n478: \tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n479: \n480: \ttracked, known := p.nodes[key]\n481: \tif !known {\n482: \t\ttracked = &trackedNode{ifaces: map[string]clablabruntime.InterfaceEventData{}}\n483: \t\tp.nodes[key] = tracked\n484: \t}\n485: \ttracked.lab = state\n486: \ttracked.node = node\n487: \n488: \treported := reportedInterfaces(sample.links)\n489: \n490: \tif sample.hasStates {\n491: \t\tp.processStates(ctx, tracked, reported, sample)\n492: \t}\n493: \n494: \tif !p.opts.includeStats {\n495: \t\treturn\n496: \t}\n497: \tfor _, stat := range sample.stats {\n498: \t\talias, ok := reported[stat.Name]\n499: \t\tif !ok {\n500: \t\t\tcontinue\n501: \t\t}\n502: \n503: \t\tstatsKey := c9sIfaceStatsKey(state.Namespace, state.Name, node.Name, stat.Name)\n504: \t\tcurrent := c9sIfaceStatsSample{Stats: stat, Timestamp: sample.timestamp}\n505: \t\tif previous, ok := p.statsSamples[statsKey]; ok {\n506: \t\t\tdata, ok := tracked.ifaces[stat.Name]\n507: \t\t\tif !ok {\n508: \t\t\t\tdata = interfaceEventData(c9sIfaceState{Name: stat.Name}, alias)\n509: \t\t\t\tdata.OperState = \"\"\n510: \t\t\t}\n511: \t\t\tdata.Stats = c9sIfaceStatsData(previous, current)\n512: \t\t\tp.emit(ctx, tracked, interfaceActionStats, data, current.Timestamp)\n513: \t\t}\n514: \n515: \t\tp.statsSamples[statsKey] = current\n516: \t}\n517: }\n518: \n519: // processStates reports the interfaces that appeared (snapshot in the first round with\n520: // --initial-state, create later), changed (update) or disappeared (delete) since the last\n521: // sample, like the netlink events of the local runtimes.\n522: func (p *interfacePoller) processStates(\n523: \tctx context.Context,\n524: \ttracked *trackedNode,\n525: \treported map[string]string,\n526: \tsample interfaceSample,\n527: ) {\n528: \tpresent := map[string]bool{}\n529: \tfor _, iface := range sample.ifaces {\n530: \t\talias, ok := reported[iface.Name]\n531: \t\tif !ok {\n532: \t\t\tcontinue\n533: \t\t}\n534: \n535: \t\tdata := interfaceEventData(iface, alias)\n536: \t\tpresent[iface.Name] = true\n537: \t\tprevious, seen := tracked.ifaces[iface.Name]\n538: \t\ttracked.ifaces[iface.Name] = data\n539: \n540: \t\tswitch {\n541: \t\tcase seen && previous == data:\n542: \t\tcase !seen && p.firstRound:\n543: \t\t\t// Interfaces that exist when the stream starts are only reported with\n544: \t\t\t// --initial-state; later changes are always reported.\n545: \t\t\tif p.opts.includeInitialState {\n546: \t\t\t\tp.emit(ctx, tracked, interfaceActionSnapshot, data, sample.timestamp)\n547: \t\t\t}\n548: \t\tcase !seen:\n549: \t\t\tp.emit(ctx, tracked, interfaceActionCreate, data, sample.timestamp)\n550: \t\tdefault:\n551: \t\t\tp.emit(ctx, tracked, interfaceActionUpdate, data, sample.timestamp)\n552: \t\t}\n553: \t}\n554: \n555: \tfor _, name := range sortedInterfaceNames(tracked.ifaces) {\n556: \t\tif present[name] {\n557: \t\t\tcontinue\n558: \t\t}\n559: \n560: \t\tp.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], sample.timestamp)\n561: \t\tp.forgetStats(tracked, name)\n562: \t\tdelete(tracked.ifaces, name)\n563: \t}\n564: }\n565: \n566: func sortedInterfaceNames(ifaces map[string]clablabruntime.InterfaceEventData) []string {\n567: \tnames := make([]string, 0, len(ifaces))\n568: \tfor name := range ifaces {\n569: \t\tnames = append(names, name)\n570: \t}\n571: \tsort.Strings(names)\n572: \n573: \treturn names\n574: }\n575: \n576: func (p *interfacePoller) forgetStats(tracked *trackedNode, ifName string) {\n577: \tdelete(p.statsSamples,\n578: \t\tc9sIfaceStatsKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name, ifName))\n579: }\n580: \n581: func (p *interfacePoller) emit(\n582: \tctx context.Context,\n583: \ttracked *trackedNode,\n584: \taction string,\n585: \tdata clablabruntime.InterfaceEventData,\n586: \ttimestamp time.Time,\n587: ) {\n588: \tp.r.sendEvent(ctx, p.sink, c9sInterfaceEvent(tracked, action, data, timestamp))\n589: }\n590: \n591: // c9sInterfaceEvent is an interface event of a node. The actor is the node, as for its container\n592: // events. The interface itself is in Interface; the events command reports it with the\n593: // attributes of the local runtimes' interface events.\n594: func c9sInterfaceEvent(\n595: \ttracked *trackedNode,\n596: \taction string,\n597: \tdata clablabruntime.InterfaceEventData,\n598: \ttimestamp time.Time,\n599: ) clablabruntime.Event {\n600: \tkey := c9sNodeKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name)\n601: \n602: \tattributes := map[string]string{\n603: \t\t\"namespace\": tracked.lab.Namespace,\n604: \t\t\"lab\":       tracked.lab.Name,\n605: \t\t\"node\":      tracked.node.Name,\n606: \t\t\"origin\":    clabernetesAppValue,\n607: \t}\n608: \tif tracked.node.Pod != \"\" {\n609: \t\tattributes[\"pod\"] = tracked.node.Pod\n610: \t}\n611: \n612: \tnode := tracked.node\n613: \n614: \treturn clablabruntime.Event{\n615: \t\tTimestamp:   timestamp,\n616: \t\tType:        clablabruntime.EventTypeInterface,\n617: \t\tAction:      action,\n618: \t\tActorID:     key,\n619: \t\tActorName:   fmt.Sprintf(\"%s-%s\", tracked.lab.Name, tracked.node.Name),\n620: \t\tActorFullID: key,\n621: \t\tAttributes:  attributes,\n622: \t\tLab:         tracked.lab,\n623: \t\tNode:        &node,\n624: \t\tInterface:   &data,\n625: \t}\n626: }\n627: \n628: // c9sIfaceStatsData computes the counters and rates of a stats event from two samples.\n629: func c9sIfaceStatsData(previous, current c9sIfaceStatsSample) *clablabruntime.InterfaceStats {\n630: \tinterval := current.Timestamp.Sub(previous.Timestamp)\n631: \tif interval <= 0 {\n632: \t\tinterval = time.Second\n633: \t}\n634: \n635: \tseconds := interval.Seconds()\n636: \tstat := current.Stats\n637: \n638: \treturn &clablabruntime.InterfaceStats{\n639: \t\tRxBytes:   stat.RxBytes,\n640: \t\tTxBytes:   stat.TxBytes,\n641: \t\tRxPackets: stat.RxPackets,\n642: \t\tTxPackets: stat.TxPackets,\n643: \t\tRxBps:     float64(counterDelta(stat.RxBytes, previous.Stats.RxBytes)*8) / seconds,\n644: \t\tTxBps:     float64(counterDelta(stat.TxBytes, previous.Stats.TxBytes)*8) / seconds,\n645: \t\tRxPps:     float64(counterDelta(stat.RxPackets, previous.Stats.RxPackets)) / seconds,\n646: \t\tTxPps:     float64(counterDelta(stat.TxPackets, previous.Stats.TxPackets)) / seconds,\n647: \t\tInterval:  interval,\n648: \t}\n649: }\n650: \n651: // parseInterfaceSample splits the output of interfaceSampleScript into the /proc/net/dev\n652: // counters and the sysfs interface states. hasStates is false for output without the sysfs\n653: // section, such as a plain cat of /proc/net/dev.\n654: func parseInterfaceSample(data []byte) ([]c9sIfaceStats, []c9sIfaceState, bool, error) {\n655: \ttext := string(data)\n656: \n657: \tprocPart, sysfsPart, hasStates := strings.Cut(text, interfaceSysfsMarker+\"\\n\")\n658: \tif !hasStates {\n659: \t\tprocPart, _, hasStates = strings.Cut(text, interfaceSysfsMarker)\n660: \t}\n661: \n662: \tstats, err := parseProcNetDev([]byte(procPart))\n663: \tif err != nil {\n664: \t\treturn nil, nil, false, err\n665: \t}\n666: \tif !hasStates {\n667: \t\treturn stats, nil, false, nil\n668: \t}\n669: \n670: \treturn stats, parseSysfsInterfaces(sysfsPart), true, nil\n671: }\n672: \n673: func parseSysfsInterfaces(data string) []c9sIfaceState {\n674: \tlines := strings.Split(data, \"\\n\")\n675: \tstates := make([]c9sIfaceState, 0, len(lines))\n676: \n677: \tfor _, line := range lines {\n678: \t\tfields := strings.SplitN(line, \"\\t\", 7) //nolint:mnd\n679: \t\tif len(fields) < 5 || strings.TrimSpace(fields[0]) == \"\" {\n680: \t\t\tcontinue\n681: \t\t}\n682: \n683: \t\tstate := c9sIfaceState{\n684: \t\t\tName:      strings.TrimSpace(fields[0]),\n685: \t\t\tMAC:       strings.TrimSpace(fields[3]),\n686: \t\t\tOperState: strings.ToLower(strings.TrimSpace(fields[4])),\n687: \t\t}\n688: \t\tstate.Index, _ = strconv.Atoi(strings.TrimSpace(fields[1]))\n689: \t\tstate.MTU, _ = strconv.Atoi(strings.TrimSpace(fields[2]))\n690: \t\tif len(fields) > 5 {\n691: \t\t\tstate.Flags, _ = strconv.ParseUint(\n692: \t\t\t\tstrings.TrimPrefix(strings.TrimSpace(fields[5]), \"0x\"), 16, 64)\n693: \t\t}\n694: \t\tif len(fields) > 6 {\n695: \t\t\tstate.Alias = strings.TrimSpace(fields[6])\n696: \t\t}\n697: \t\tif state.OperState == \"\" {\n698: \t\t\tstate.OperState = \"unknown\"\n699: \t\t}\n700: \n701: \t\tstates = append(states, state)\n702: \t}\n703: \n704: \treturn states\n705: }\n706: \n707: func parseProcNetDev(data []byte) ([]c9sIfaceStats, error) {\n708: \tlines := strings.Split(string(data), \"\\n\")\n709: \tstats := make([]c9sIfaceStats, 0, len(lines))\n710: \n711: \tfor _, line := range lines {\n712: \t\tline = strings.TrimSpace(line)\n713: \t\tif line == \"\" || !strings.Contains(line, \":\") {\n714: \t\t\tcontinue\n715: \t\t}\n716: \n717: \t\tparts := strings.SplitN(line, \":\", 2)\n718: \t\tif len(parts) != 2 {\n719: \t\t\tcontinue\n720: \t\t}\n721: \n722: \t\tifName := strings.TrimSpace(parts[0])\n723: \t\tfields := strings.Fields(parts[1])\n724: \t\tif len(fields) < 16 {\n725: \t\t\treturn nil, fmt.Errorf(\"unexpected /proc/net/dev line for %q: %q\", ifName, line)\n726: \t\t}\n727: \n728: \t\trxBytes, err := strconv.ParseUint(fields[0], 10, 64)\n729: \t\tif err != nil {\n730: \t\t\treturn nil, fmt.Errorf(\"failed to parse rx bytes for %q: %w\", ifName, err)\n731: \t\t}\n732: \t\trxPackets, err := strconv.ParseUint(fields[1], 10, 64)\n733: \t\tif err != nil {\n734: \t\t\treturn nil, fmt.Errorf(\"failed to parse rx packets for %q: %w\", ifName, err)\n735: \t\t}\n736: \t\ttxBytes, err := strconv.ParseUint(fields[8], 10, 64)\n737: \t\tif err != nil {\n738: \t\t\treturn nil, fmt.Errorf(\"failed to parse tx bytes for %q: %w\", ifName, err)\n739: \t\t}\n740: \t\ttxPackets, err := strconv.ParseUint(fields[9], 10, 64)\n741: \t\tif err != nil {\n742: \t\t\treturn nil, fmt.Errorf(\"failed to parse tx packets for %q: %w\", ifName, err)\n743: \t\t}\n744: \n745: \t\tstats = append(stats, c9sIfaceStats{\n746: \t\t\tName:      ifName,\n747: \t\t\tRxBytes:   rxBytes,\n748: \t\t\tRxPackets: rxPackets,\n749: \t\t\tTxBytes:   txBytes,\n750: \t\t\tTxPackets: txPackets,\n751: \t\t})\n752: \t}\n753: \n754: \treturn stats, nil\n755: }\n756: \n757: // c9sNodeKey is the actor ID of a node: <namespace>/<lab>/<node>, the same value inspect\n758: // reports as container_id.\n759: func c9sNodeKey(namespace, lab, node string) string {\n760: \treturn namespace + \"/\" + lab + \"/\" + node\n761: }\n762: \n763: func c9sIfaceStatsKey(namespace, lab, node, ifName string) string {\n764: \treturn c9sNodeKey(namespace, lab, node) + \"/\" + ifName\n765: }\n766: \n767: func counterDelta(current, previous uint64) uint64 {\n768: \tif current < previous {\n769: \t\treturn 0\n770: \t}\n771: \n772: \treturn current - previous\n773: }\n\n(End of file - total 773 lines)\n</content>",
    "title": "source/head/labruntime/clabernetes/iface_stats.go",
    "metadata": {
      "preview": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\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)\n\nconst (\n\t// interfaceSysfsMarker separates the /proc/net/dev counters from the sysfs interface\n\t// attributes in the output of interfaceSampleScript.",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/iface_stats.go",
        "text": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\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)\n\nconst (\n\t// interfaceSysfsMarker separates the /proc/net/dev counters from the sysfs interface\n\t// attributes in the output of interfaceSampleScript.\n\tinterfaceSysfsMarker = \"@@clab-sysfs\"\n\t// interfaceSampleScript reads the interface counters and, per interface, the sysfs\n\t// attributes the interface state events carry, in one exec:\n\t// name, ifindex, mtu, address, operstate, flags and ifalias, tab separated.\n\tinterfaceSampleScript = `cat /proc/net/dev; echo ` + interfaceSysfsMarker + `; ` +\n\t\t`for d in /sys/class/net/*; do [ -e \"$d/operstate\" ] || continue; ` +\n\t\t`printf '%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n' \"${d##*/}\" \"$(cat \"$d/ifindex\")\" ` +\n\t\t`\"$(cat \"$d/mtu\")\" \"$(cat \"$d/address\")\" \"$(cat \"$d/operstate\")\" ` +\n\t\t`\"$(cat \"$d/flags\")\" \"$(cat \"$d/ifalias\")\"; done 2>/dev/null`\n\n\t// interfaceSampleWorkers bounds the concurrent execs of one sampling round.\n\tinterfaceSampleWorkers = 16\n\n\t// managementInterface is a node's management interface in its pod, the interface the\n\t// clabernetes planner gives the management address by default. It has the name the\n\t// management interface has in a container of the local runtimes.\n\tmanagementInterface = \"eth0\"\n\t// loopbackInterface is reported like the local runtimes report it.\n\tloopbackInterface = \"lo\"\n\t// clabernetesAliasPrefix starts the interface aliases clabernetes marks its own interfaces\n\t// and the lab links it wires with. They are not the topology's names, so they are not\n\t// reported.\n\tclabernetesAliasPrefix = \"c9s:\"\n\t// zeroMAC is the hardware address sysfs reports for interfaces without one (loopback).\n\tzeroMAC = \"00:00:00:00:00:00\"\n\n\t// Interface event actions and link types, as the local runtimes report them.\n\tinterfaceActionSnapshot = \"snapshot\"\n\tinterfaceActionCreate   = \"create\"\n\tinterfaceActionUpdate   = \"update\"\n\tinterfaceActionDelete   = \"delete\"\n\tinterfaceActionStats    = \"stats\"\n\tinterfaceTypeVeth       = \"veth\"\n\tinterfaceTypeDevice     = \"device\"\n\n\t// shell exit codes of a command that cannot be found or executed.\n\texitCommandNotExecutable = 126\n\texitCommandNotFound      = 127\n)\n\ntype interfacePollOptions struct {\n\tinterval            time.Duration\n\tincludeStats        bool\n\tincludeInitialState bool\n}\n\ntype c9sIfaceStats struct {\n\tName      string\n\tRxBytes   uint64\n\tRxPackets uint64\n\tTxBytes   uint64\n\tTxPackets uint64\n}\n\ntype c9sIfaceStatsSample struct {\n\tStats     c9sIfaceStats\n\tTimestamp time.Time\n}\n\n// c9sIfaceState is the sysfs view of one interface in a device container.\ntype c9sIfaceState struct {\n\tName      string\n\tIndex     int\n\tMTU       int\n\tMAC       string\n\tOperState string\n\tFlags     uint64\n\tAlias     string\n}\n\n// trackedNode remembers the interfaces last reported for a node, so their changes and their\n// removal can be reported, also when the node stops running.\ntype trackedNode struct {\n\tlab    *clablabruntime.LabState\n\tnode   clablabruntime.NodeState\n\tifaces map[string]clablabruntime.InterfaceEventData\n}\n\ntype interfaceSampleTarget struct {\n\tstate *clablabruntime.LabState\n\tnode  clablabruntime.NodeState\n\tpod   *corev1.Pod\n}\n\ntype interfaceSample struct {\n\ttarget    interfaceSampleTarget\n\tstats     []c9sIfaceStats\n\tifaces    []c9sIfaceState\n\thasStates bool\n\t// links are the node's lab link interfaces as clabwire lists them.\n\tlinks     []clabwireInterface\n\ttimestamp time.Time\n\terr       error\n}\n\n// podInterfaceListing is the clabwire interface listing of a pod, per node. It is listed again\n// when the pod's interfaces change.\ntype podInterfaceListing struct {\n\tnames  string\n\tbyNode map[string][]clabwireInterface\n}\n\n// interfacePoller samples the interfaces of every running node in an event scope and turns the\n// samples into interface events. It reports the interfaces a container of the local runtimes\n// has for the same node: the node's lab link interfaces, with the names and aliases clabwire\n// lists for them, the management interface and loopback. The pod's own interfaces (the pod\n// network, clabernetes' interposition and link transport interfaces) are not reported.\ntype interfacePoller struct {\n\tr     *Runtime\n\tscope eventScope\n\topts  interfacePollOptions\n\tsink  chan<- clablabruntime.Event\n\n\tstatsSamples map[string]c9sIfaceStatsSample\n\tnodes        map[string]*trackedNode\n\n\tnoShellMu sync.Mutex\n\t// noShell holds the pods whose device container has no shell; they are sampled with a\n\t// plain cat of /proc/net/dev and report statistics without interface state.\n\tnoShell map[string]bool\n\n\tlistingsMu sync.Mutex\n\t// listings holds the clabwire interface listing per pod (namespace/pod).\n\tlistings map[string]*podInterfaceListing\n\n\tfirstRound bool\n}\n\nfunc (r *Runtime) pollInterfaces(\n\tctx context.Context,\n\tscope eventScope,\n\topts interfacePollOptions,\n\teventSink chan<- clablabruntime.Event,\n) {\n\tif opts.interval <= 0 {\n\t\topts.interval = time.Second\n\t}\n\n\tpoller := newInterfacePoller(r, scope, opts, eventSink)\n\tpoller.round(ctx)\n\n\tticker := time.NewTicker(opts.interval)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tpoller.round(ctx)\n\t\t}\n\t}\n}\n\nfunc newInterfacePoller(\n\tr *Runtime,\n\tscope eventScope,\n\topts interfacePollOptions,\n\teventSink chan<- clablabruntime.Event,\n) *interfacePoller {\n\treturn &interfacePoller{\n\t\tr:            r,\n\t\tscope:        scope,\n\t\topts:         opts,\n\t\tsink:         eventSink,\n\t\tstatsSamples: map[string]c9sIfaceStatsSample{},\n\t\tnodes:        map[string]*trackedNode{},\n\t\tnoShell:      map[string]bool{},\n\t\tlistings:     map[string]*podInterfaceListing{},\n\t\tfirstRound:   true,\n\t}\n}\n\nfunc (p *interfacePoller) round(ctx context.Context) {\n\tdefer func() { p.firstRound = false }()\n\n\tstates, err := p.r.labStates(ctx, p.scope)\n\tif err != nil {\n\t\tlog.Debug(\"failed to list C9s labs for interface events\", \"error\", err)\n\t\treturn\n\t}\n\n\trunning := map[string]bool{}\n\tpods := map[string]bool{}\n\tvar targets []interfaceSampleTarget\n\tfor _, state := range states {\n\t\tfor _, node := range state.Nodes {\n\t\t\tif node.ContainerState != clablabruntime.ContainerStateRunning || node.Pod == \"\" ||\n\t\t\t\tnode.Container == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trunning[c9sNodeKey(state.Namespace, state.Name, node.Name)] = true\n\t\t\tpods[state.Namespace+\"/\"+node.Pod] = true\n\t\t\ttargets = append(targets, interfaceSampleTarget{\n\t\t\t\tstate: state,\n\t\t\t\tnode:  node,\n\t\t\t\tpod: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName:      node.Pod,\n\t\t\t\t\tNamespace: state.Namespace,\n\t\t\t\t}},\n\t\t\t})\n\t\t}\n\t}\n\n\tfor _, sample := range p.sampleAll(ctx, targets) {\n\t\tif ctx.Err() != nil {\n\t\t\treturn\n\t\t}\n\t\tif sample.err != nil {\n\t\t\tlog.Debug(\"failed to sample C9s interfaces\",\n\t\t\t\t\"namespace\", sample.target.state.Namespace,\n\t\t\t\t\"lab\", sample.target.state.Name,\n\t\t\t\t\"node\", sample.target.node.Name,\n\t\t\t\t\"error\", sample.err,\n\t\t\t)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tp.processSample(ctx, sample)\n\t}\n\n\tp.retireStoppedNodes(ctx, running)\n\tp.forgetListings(pods)\n}\n\n// retireStoppedNodes reports the interfaces of nodes that stopped running, or were removed, as\n// deleted: they are gone with the node's pod.\nfunc (p *interfacePoller) retireStoppedNodes(ctx context.Context, running map[string]bool) {\n\tfor key, tracked := range p.nodes {\n\t\tif running[key] {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, name := range sortedInterfaceNames(tracked.ifaces) {\n\t\t\tp.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], time.Now())\n\t\t\tp.forgetStats(tracked, name)\n\t\t}\n\t\tdelete(p.nodes, key)\n\t}\n}\n\n// forgetListings drops the interface listings of pods that are gone.\nfunc (p *interfacePoller) forgetListings(pods map[string]bool) {\n\tp.listingsMu.Lock()\n\tdefer p.listingsMu.Unlock()\n\n\tfor key := range p.listings {\n\t\tif !pods[key] {\n\t\t\tdelete(p.listings, key)\n\t\t}\n\t}\n}\n\nfunc (p *interfacePoller) sampleAll(\n\tctx context.Context,\n\ttargets []interfaceSampleTarget,\n) []interfaceSample {\n\tsamples := make([]interfaceSample, len(targets))\n\n\tvar wg sync.WaitGroup\n\tsem := make(chan struct{}, interfaceSampleWorkers)\n\tfor idx := range targets {\n\t\twg.Add(1)\n\t\tsem <- struct{}{}\n\t\tgo func(idx int) {\n\t\t\tdefer wg.Done()\n\t\t\tdefer func() { <-sem }()\n\n\t\t\tsamples[idx] = p.sample(ctx, targets[idx])\n\t\t}(idx)\n\t}\n\twg.Wait()\n\n\treturn samples\n}\n\nfunc (p *interfacePoller) sample(\n\tctx context.Context,\n\ttarget interfaceSampleTarget,\n) interfaceSample {\n\tsample := interfaceSample{target: target}\n\tpodName := target.pod.Name\n\n\tp.noShellMu.Lock()\n\tnoShell := p.noShell[podName]\n\tp.noShellMu.Unlock()\n\n\tcommand := []string{\"sh\", \"-c\", interfaceSampleScript}\n\tif noShell {\n\t\tcommand = []string{\"cat\", \"/proc/net/dev\"}\n\t}\n\n\tstdout, stderr, rc, err := p.r.execInPod(ctx, target.pod, target.node.Container, command)\n\tif !noShell && commandNotExecutable(rc, err) {\n\t\tp.noShellMu.Lock()\n\t\tp.noShell[podName] = true\n\t\tp.noShellMu.Unlock()\n\n\t\tlog.Debug(\"C9s device container has no shell; reporting interface statistics only\",\n\t\t\t\"namespace\", target.state.Namespace,\n\t\t\t\"lab\", target.state.Name,\n\t\t\t\"node\", target.node.Name,\n\t\t)\n\n\t\tstdout, stderr, rc, err = p.r.execInPod(ctx, target.pod, target.node.Container,\n\t\t\t[]string{\"cat\", \"/proc/net/dev\"})\n\t}\n\n\tsample.timestamp = time.Now()\n\tswitch {\n\tcase err != nil:\n\t\tsample.err = err\n\tcase rc != 0:\n\t\tsample.err = fmt.Errorf(\"exit code %d: %s\", rc, strings.TrimSpace(string(stderr)))\n\tdefault:\n\t\tsample.stats, sample.ifaces, sample.hasStates, sample.err = parseInterfaceSample(stdout)\n\t}\n\tif sample.err != nil {\n\t\treturn sample\n\t}\n\n\tsample.links, sample.err = p.nodeLinks(ctx, target, sampledInterfaceNames(sample))\n\n\treturn sample\n}\n\n// sampledInterfaceNames lists the interface names a sample saw, sorted and comma-joined.\nfunc sampledInterfaceNames(sample interfaceSample) string {\n\tnames := make([]string, 0, len(sample.stats)+len(sample.ifaces))\n\tseen := map[string]bool{}\n\tfor _, iface := range sample.ifaces {\n\t\tif !seen[iface.Name] {\n\t\t\tseen[iface.Name] = true\n\t\t\tnames = append(names, iface.Name)\n\t\t}\n\t}\n\tfor _, stat := range sample.stats {\n\t\tif !seen[stat.Name] {\n\t\t\tseen[stat.Name] = true\n\t\t\tnames = append(names, stat.Name)\n\t\t}\n\t}\n\tsort.Strings(names)\n\n\treturn strings.Join(names, \",\")\n}\n\n// nodeLinks returns the lab link interfaces of a node from its pod's clabwire listing. A pod is\n// listed once, and again when its interfaces change (a pod gets its link interfaces as clabwire\n// wires them).\nfunc (p *interfacePoller) nodeLinks(\n\tctx context.Context,\n\ttarget interfaceSampleTarget,\n\tnames string,\n) ([]clabwireInterface, error) {\n\tkey := target.pod.Namespace + \"/\" + target.pod.Name\n\n\tp.listingsMu.Lock()\n\tlisting := p.listings[key]\n\tp.listingsMu.Unlock()\n\n\tif listing == nil || listing.names != names {\n\t\tentries, err := p.r.listPodInterfaces(ctx, target.pod.Namespace, target.pod.Name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlisting = &podInterfaceListing{\n\t\t\tnames:  names,\n\t\t\tbyNode: map[string][]clabwireInterface{},\n\t\t}\n\t\tfor _, entry := range entries {\n\t\t\tlisting.byNode[entry.Node] = append(listing.byNode[entry.Node], entry)\n\t\t}\n\n\t\tp.listingsMu.Lock()\n\t\tp.listings[key] = listing\n\t\tp.listingsMu.Unlock()\n\t}\n\n\treturn listing.byNode[target.node.Name], nil\n}\n\n// commandNotExecutable reports an exec that failed because the command does not exist in the\n// container.\nfunc commandNotExecutable(rc int, err error) bool {\n\tif rc == exitCommandNotExecutable || rc == exitCommandNotFound {\n\t\treturn true\n\t}\n\n\treturn err != nil && strings.Contains(err.Error(), \"executable file not found\")\n}\n\n// reportedInterfaces are the interfaces reported for a node, by name, with the alias the\n// topology gave them: its lab link interfaces, the management interface and loopback.\nfunc reportedInterfaces(links []clabwireInterface) map[string]string {\n\treported := map[string]string{\n\t\tloopbackInterface:   \"\",\n\t\tmanagementInterface: \"\",\n\t}\n\tfor _, link := range links {\n\t\treported[link.Interface] = link.Alias\n\t}\n\n\treturn reported\n}\n\n// interfaceEventData describes an interface the way the local runtimes' netlink events do: the\n// alias is the topology's name for the interface (an alias clabernetes set for its own use is\n// not reported), the operational state uses netlink's names, lab link and management\n// interfaces are veth pairs, loopback a device, and loopback has no hardware address.\nfunc interfaceEventData(iface c9sIfaceState, alias string) clablabruntime.InterfaceEventData {\n\tif alias == \"\" && !strings.HasPrefix(iface.Alias, clabernetesAliasPrefix) {\n\t\talias = iface.Alias\n\t}\n\n\tmac := iface.MAC\n\tif mac == zeroMAC {\n\t\tmac = \"\"\n\t}\n\n\tlinkType := interfaceTypeVeth\n\tif iface.Name == loopbackInterface {\n\t\tlinkType = interfaceTypeDevice\n\t}\n\n\treturn clablabruntime.InterfaceEventData{\n\t\tName:      iface.Name,\n\t\tAlias:     alias,\n\t\tIndex:     iface.Index,\n\t\tMTU:       iface.MTU,\n\t\tMAC:       mac,\n\t\tOperState: netlinkOperState(iface.OperState),\n\t\tType:      linkType,\n\t}\n}\n\n// netlinkOperState names an operational state from sysfs (RFC 2863, as in\n// /sys/class/net/<if>/operstate) the way netlink, and so the local runtimes' events, name it.\nfunc netlinkOperState(operState string) string {\n\tswitch operState {\n\tcase \"notpresent\":\n\t\treturn \"not-present\"\n\tcase \"lowerlayerdown\":\n\t\treturn \"lower-layer-down\"\n\tcase \"\":\n\t\treturn \"unknown\"\n\tdefault:\n\t\treturn operState\n\t}\n}\n\nfunc (p *interfacePoller) processSample(ctx context.Context, sample interfaceSample) {\n\tstate := sample.target.state\n\tnode := sample.target.node\n\tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n\n\ttracked, known := p.nodes[key]\n\tif !known {\n\t\ttracked = &trackedNode{ifaces: map[string]clablabruntime.InterfaceEventData{}}\n\t\tp.nodes[key] = tracked\n\t}\n\ttracked.lab = state\n\ttracked.node = node\n\n\treported := reportedInterfaces(sample.links)\n\n\tif sample.hasStates {\n\t\tp.processStates(ctx, tracked, reported, sample)\n\t}\n\n\tif !p.opts.includeStats {\n\t\treturn\n\t}\n\tfor _, stat := range sample.stats {\n\t\talias, ok := reported[stat.Name]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tstatsKey := c9sIfaceStatsKey(state.Namespace, state.Name, node.Name, stat.Name)\n\t\tcurrent := c9sIfaceStatsSample{Stats: stat, Timestamp: sample.timestamp}\n\t\tif previous, ok := p.statsSamples[statsKey]; ok {\n\t\t\tdata, ok := tracked.ifaces[stat.Name]\n\t\t\tif !ok {\n\t\t\t\tdata = interfaceEventData(c9sIfaceState{Name: stat.Name}, alias)\n\t\t\t\tdata.OperState = \"\"\n\t\t\t}\n\t\t\tdata.Stats = c9sIfaceStatsData(previous, current)\n\t\t\tp.emit(ctx, tracked, interfaceActionStats, data, current.Timestamp)\n\t\t}\n\n\t\tp.statsSamples[statsKey] = current\n\t}\n}\n\n// processStates reports the interfaces that appeared (snapshot in the first round with\n// --initial-state, create later), changed (update) or disappeared (delete) since the last\n// sample, like the netlink events of the local runtimes.\nfunc (p *interfacePoller) processStates(\n\tctx context.Context,\n\ttracked *trackedNode,\n\treported map[string]string,\n\tsample interfaceSample,\n) {\n\tpresent := map[string]bool{}\n\tfor _, iface := range sample.ifaces {\n\t\talias, ok := reported[iface.Name]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tdata := interfaceEventData(iface, alias)\n\t\tpresent[iface.Name] = true\n\t\tprevious, seen := tracked.ifaces[iface.Name]\n\t\ttracked.ifaces[iface.Name] = data\n\n\t\tswitch {\n\t\tcase seen && previous == data:\n\t\tcase !seen && p.firstRound:\n\t\t\t// Interfaces that exist when the stream starts are only reported with\n\t\t\t// --initial-state; later changes are always reported.\n\t\t\tif p.opts.includeInitialState {\n\t\t\t\tp.emit(ctx, tracked, interfaceActionSnapshot, data, sample.timestamp)\n\t\t\t}\n\t\tcase !seen:\n\t\t\tp.emit(ctx, tracked, interfaceActionCreate, data, sample.timestamp)\n\t\tdefault:\n\t\t\tp.emit(ctx, tracked, interfaceActionUpdate, data, sample.timestamp)\n\t\t}\n\t}\n\n\tfor _, name := range sortedInterfaceNames(tracked.ifaces) {\n\t\tif present[name] {\n\t\t\tcontinue\n\t\t}\n\n\t\tp.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], sample.timestamp)\n\t\tp.forgetStats(tracked, name)\n\t\tdelete(tracked.ifaces, name)\n\t}\n}\n\nfunc sortedInterfaceNames(ifaces map[string]clablabruntime.InterfaceEventData) []string {\n\tnames := make([]string, 0, len(ifaces))\n\tfor name := range ifaces {\n\t\tnames = append(names, name)\n\t}\n\tsort.Strings(names)\n\n\treturn names\n}\n\nfunc (p *interfacePoller) forgetStats(tracked *trackedNode, ifName string) {\n\tdelete(p.statsSamples,\n\t\tc9sIfaceStatsKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name, ifName))\n}\n\nfunc (p *interfacePoller) emit(\n\tctx context.Context,\n\ttracked *trackedNode,\n\taction string,\n\tdata clablabruntime.InterfaceEventData,\n\ttimestamp time.Time,\n) {\n\tp.r.sendEvent(ctx, p.sink, c9sInterfaceEvent(tracked, action, data, timestamp))\n}\n\n// c9sInterfaceEvent is an interface event of a node. The actor is the node, as for its container\n// events. The interface itself is in Interface; the events command reports it with the\n// attributes of the local runtimes' interface events.\nfunc c9sInterfaceEvent(\n\ttracked *trackedNode,\n\taction string,\n\tdata clablabruntime.InterfaceEventData,\n\ttimestamp time.Time,\n) clablabruntime.Event {\n\tkey := c9sNodeKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name)\n\n\tattributes := map[string]string{\n\t\t\"namespace\": tracked.lab.Namespace,\n\t\t\"lab\":       tracked.lab.Name,\n\t\t\"node\":      tracked.node.Name,\n\t\t\"origin\":    clabernetesAppValue,\n\t}\n\tif tracked.node.Pod != \"\" {\n\t\tattributes[\"pod\"] = tracked.node.Pod\n\t}\n\n\tnode := tracked.node\n\n\treturn clablabruntime.Event{\n\t\tTimestamp:   timestamp,\n\t\tType:        clablabruntime.EventTypeInterface,\n\t\tAction:      action,\n\t\tActorID:     key,\n\t\tActorName:   fmt.Sprintf(\"%s-%s\", tracked.lab.Name, tracked.node.Name),\n\t\tActorFullID: key,\n\t\tAttributes:  attributes,\n\t\tLab:         tracked.lab,\n\t\tNode:        &node,\n\t\tInterface:   &data,\n\t}\n}\n\n// c9sIfaceStatsData computes the counters and rates of a stats event from two samples.\nfunc c9sIfaceStatsData(previous, current c9sIfaceStatsSample) *clablabruntime.InterfaceStats {\n\tinterval := current.Timestamp.Sub(previous.Timestamp)\n\tif interval <= 0 {\n\t\tinterval = time.Second\n\t}\n\n\tseconds := interval.Seconds()\n\tstat := current.Stats\n\n\treturn &clablabruntime.InterfaceStats{\n\t\tRxBytes:   stat.RxBytes,\n\t\tTxBytes:   stat.TxBytes,\n\t\tRxPackets: stat.RxPackets,\n\t\tTxPackets: stat.TxPackets,\n\t\tRxBps:     float64(counterDelta(stat.RxBytes, previous.Stats.RxBytes)*8) / seconds,\n\t\tTxBps:     float64(counterDelta(stat.TxBytes, previous.Stats.TxBytes)*8) / seconds,\n\t\tRxPps:     float64(counterDelta(stat.RxPackets, previous.Stats.RxPackets)) / seconds,\n\t\tTxPps:     float64(counterDelta(stat.TxPackets, previous.Stats.TxPackets)) / seconds,\n\t\tInterval:  interval,\n\t}\n}\n\n// parseInterfaceSample splits the output of interfaceSampleScript into the /proc/net/dev\n// counters and the sysfs interface states. hasStates is false for output without the sysfs\n// section, such as a plain cat of /proc/net/dev.\nfunc parseInterfaceSample(data []byte) ([]c9sIfaceStats, []c9sIfaceState, bool, error) {\n\ttext := string(data)\n\n\tprocPart, sysfsPart, hasStates := strings.Cut(text, interfaceSysfsMarker+\"\\n\")\n\tif !hasStates {\n\t\tprocPart, _, hasStates = strings.Cut(text, interfaceSysfsMarker)\n\t}\n\n\tstats, err := parseProcNetDev([]byte(procPart))\n\tif err != nil {\n\t\treturn nil, nil, false, err\n\t}\n\tif !hasStates {\n\t\treturn stats, nil, false, nil\n\t}\n\n\treturn stats, parseSysfsInterfaces(sysfsPart), true, nil\n}\n\nfunc parseSysfsInterfaces(data string) []c9sIfaceState {\n\tlines := strings.Split(data, \"\\n\")\n\tstates := make([]c9sIfaceState, 0, len(lines))\n\n\tfor _, line := range lines {\n\t\tfields := strings.SplitN(line, \"\\t\", 7) //nolint:mnd\n\t\tif len(fields) < 5 || strings.TrimSpace(fields[0]) == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tstate := c9sIfaceState{\n\t\t\tName:      strings.TrimSpace(fields[0]),\n\t\t\tMAC:       strings.TrimSpace(fields[3]),\n\t\t\tOperState: strings.ToLower(strings.TrimSpace(fields[4])),\n\t\t}\n\t\tstate.Index, _ = strconv.Atoi(strings.TrimSpace(fields[1]))\n\t\tstate.MTU, _ = strconv.Atoi(strings.TrimSpace(fields[2]))\n\t\tif len(fields) > 5 {\n\t\t\tstate.Flags, _ = strconv.ParseUint(\n\t\t\t\tstrings.TrimPrefix(strings.TrimSpace(fields[5]), \"0x\"), 16, 64)\n\t\t}\n\t\tif len(fields) > 6 {\n\t\t\tstate.Alias = strings.TrimSpace(fields[6])\n\t\t}\n\t\tif state.OperState == \"\" {\n\t\t\tstate.OperState = \"unknown\"\n\t\t}\n\n\t\tstates = append(states, state)\n\t}\n\n\treturn states\n}\n\nfunc parseProcNetDev(data []byte) ([]c9sIfaceStats, error) {\n\tlines := strings.Split(string(data), \"\\n\")\n\tstats := make([]c9sIfaceStats, 0, len(lines))\n\n\tfor _, line := range lines {\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" || !strings.Contains(line, \":\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tparts := strings.SplitN(line, \":\", 2)\n\t\tif len(parts) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tifName := strings.TrimSpace(parts[0])\n\t\tfields := strings.Fields(parts[1])\n\t\tif len(fields) < 16 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected /proc/net/dev line for %q: %q\", ifName, line)\n\t\t}\n\n\t\trxBytes, err := strconv.ParseUint(fields[0], 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse rx bytes for %q: %w\", ifName, err)\n\t\t}\n\t\trxPackets, err := strconv.ParseUint(fields[1], 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse rx packets for %q: %w\", ifName, err)\n\t\t}\n\t\ttxBytes, err := strconv.ParseUint(fields[8], 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse tx bytes for %q: %w\", ifName, err)\n\t\t}\n\t\ttxPackets, err := strconv.ParseUint(fields[9], 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse tx packets for %q: %w\", ifName, err)\n\t\t}\n\n\t\tstats = append(stats, c9sIfaceStats{\n\t\t\tName:      ifName,\n\t\t\tRxBytes:   rxBytes,\n\t\t\tRxPackets: rxPackets,\n\t\t\tTxBytes:   txBytes,\n\t\t\tTxPackets: txPackets,\n\t\t})\n\t}\n\n\treturn stats, nil\n}\n\n// c9sNodeKey is the actor ID of a node: <namespace>/<lab>/<node>, the same value inspect\n// reports as container_id.\nfunc c9sNodeKey(namespace, lab, node string) string {\n\treturn namespace + \"/\" + lab + \"/\" + node\n}\n\nfunc c9sIfaceStatsKey(namespace, lab, node, ifName string) string {\n\treturn c9sNodeKey(namespace, lab, node) + \"/\" + ifName\n}\n\nfunc counterDelta(current, previous uint64) uint64 {\n\tif current < previous {\n\t\treturn 0\n\t}\n\n\treturn current - previous\n}",
        "lineStart": 1,
        "lineEnd": 773,
        "totalLines": 773,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525756033,
      "end": 1793525756048
    }
  }
}
read · completed

Input

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

Output

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

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

1. `netlink.go` — `labRuntimeInterfaceAttributes` sets `attributes["state"]` unconditionally (via `interfaceSnapshotAttributes`), but `mergedEventAttributes` drops empty values, so the parity test should pass. Resolved.

2. `iface_stats.go` — `sample()` when `nodeLinks` fails: `sample.err` set; `processSample` skipped in `round()` since sample.err != nil. So on a clabwire listing error, the node's stats are not emitted for that round. That means with `--include-stats`, if `listPodInterfaces` fails transiently, stats events are dropped for that round. Is that a bug or acceptable? The docs say no-shell devices "report statistics only". For no-shell nodes, `sample.stats` will include all interfaces from /proc/net/dev, and `reportedInterfaces(sample.links)` — links come from clabwire listing. If listing errors, no stats at all that round. It's a graceful degradation; probably acceptable behavior. But there's a subtle thing: in `processSample`, when `sample.hasStates` is false (no-shell), stats for interfaces not in `reported` are skipped — consistent.

Wait, one potential real issue in `processSample`: when a node transitions from having states (has shell) to... not relevant.

Another potential issue: `processSample` stats loop: when `tracked.ifaces` has the interface but `sample.hasStates` was false this round (transient?), fine.

Actually there's a subtle bug candidate: in `processSample`, `data.OperState = ""` for stats when not in tracked.ifaces. Then `interfaceEventData`... no wait, they construct `interfaceEventData(c9sIfaceState{Name: stat.Name}, alias)` then override OperState = "". `interfaceEventData` sets `OperState: netlinkOperState("")` = "unknown", then overwritten to "". Then `labRuntimeInterfaceAttributes` sets attributes["state"] = "" → dropped by mergedEventAttributes. OK.

3. `retireStoppedNodes` emits delete for tracked.ifaces and forgetStats. Fine.

4. `c9sInterfaceEvent` uses `tracked.lab` — set in processSample. In `retireStoppedNodes`, tracked.lab non-nil. Fine.

5. Race concern: `p.nodes`, `p.statsSamples`, `p.firstRound` accessed only from pollInterfaces goroutine (round → processSample). `noShell` and `listings` guarded by mutexes because `sample()` runs in worker goroutines. OK.

6. In `sampleAll`, `sem <- struct{}{}` before launching goroutine — bounds concurrency. OK.

Now `core/labruntime.go` — `containerFromLabNode`, `LabRuntimeContainer`, `labRuntimeContainerState`, `labRuntimePorts`, `labRuntimeTopologyPath`, `topologyNodeName`, `managementAddress`. Read it. It's probably big; read relevant portions via grep first.
Now `core/labruntime.go` — the key conversion functions. Let me locate the relevant sections first.
grep · completed

Input

{
  "pattern": "func (c \\*CLab) LabRuntimeContainer|func containerFromLabNode|func labRuntimeContainerState|func labRuntimePorts|func labRuntimeTopologyPath|func topologyNodeName|func managementAddress|func setTopologySourceFile|func removeTopologySourceFile|func carryOverNodeTopologyFile",
  "path": "/source/head/core",
  "include": "*.go"
}

Output

Found 4 matches
/source/head/core/labruntime.go:
  Line 547: func labRuntimeContainerState(

  Line 577: func labRuntimePorts(ports []clablabruntime.ExposedPort) []*clabtypes.GenericPortBinding {

  Line 620: func managementAddress(node clablabruntime.NodeState) clabruntime.GenericMgmtIPs {

  Line 662: func labRuntimeTopologyPath(c *CLab, state *clablabruntime.LabState) string {
Tool metadata
{
  "type": "tool",
  "id": "prt_196774b75001mKmaU3XOGMwgJT",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967730d0001Td0HIMqZtNrE1R",
  "callID": "call_1a555b1bd0e64fbc93471b96",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "pattern": "func (c \\*CLab) LabRuntimeContainer|func containerFromLabNode|func labRuntimeContainerState|func labRuntimePorts|func labRuntimeTopologyPath|func topologyNodeName|func managementAddress|func setTopologySourceFile|func removeTopologySourceFile|func carryOverNodeTopologyFile",
      "path": "/source/head/core",
      "include": "*.go"
    },
    "output": "Found 4 matches\n/source/head/core/labruntime.go:\n  Line 547: func labRuntimeContainerState(\n\n  Line 577: func labRuntimePorts(ports []clablabruntime.ExposedPort) []*clabtypes.GenericPortBinding {\n\n  Line 620: func managementAddress(node clablabruntime.NodeState) clabruntime.GenericMgmtIPs {\n\n  Line 662: func labRuntimeTopologyPath(c *CLab, state *clablabruntime.LabState) string {\n",
    "title": "func (c \\*CLab) LabRuntimeContainer|func containerFromLabNode|func labRuntimeContainerState|func labRuntimePorts|func labRuntimeTopologyPath|func topologyNodeName|func managementAddress|func setTopologySourceFile|func removeTopologySourceFile|func carryOverNodeTopologyFile",
    "metadata": {
      "matches": 4,
      "truncated": false
    },
    "time": {
      "start": 1793525762939,
      "end": 1793525762952
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196774b92001PlfIgNTbBK4eBR",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967730d0001Td0HIMqZtNrE1R",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 43167,
    "input": 20938,
    "output": 107,
    "reasoning": 618,
    "cache": {
      "read": 21504,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1967730d0001Td0HIMqZtNrE1R",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525756112,
    "completed": 1793525762968
  },
  "parentID": "msg_19676df9500159h7P3dGcuBxjO",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 43167,
    "input": 20938,
    "output": 107,
    "reasoning": 618,
    "cache": {
      "read": 21504,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 17
step-start
{
  "type": "step-start",
  "id": "prt_1967758dd0018edIfRlsNmkC0B",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196774b9f001rQ0Klo3mQ42lYs"
}
read · completed

Input

{
  "filePath": "/source/head/core/labruntime.go",
  "offset": 440,
  "limit": 280
}

Output

<path>/source/head/core/labruntime.go</path>
<type>file</type>
<content>
440: 				Ready: state.Ready,
441: 			})
442: 		}
443: 	}
444: 
445: 	containers := make([]clabruntime.GenericContainer, 0, len(nodes))
446: 	for _, node := range nodes {
447: 		containers = append(containers, c.containerFromLabNode(state, node))
448: 	}
449: 
450: 	return containers
451: }
452: 
453: // LabRuntimeContainer describes a lab runtime node as a container record, the way inspect
454: // reports it. The events command describes lab runtime nodes with it too.
455: func (c *CLab) LabRuntimeContainer(
456: 	state *clablabruntime.LabState,
457: 	node clablabruntime.NodeState,
458: ) clabruntime.GenericContainer {
459: 	return c.containerFromLabNode(state, node)
460: }
461: 
462: func (c *CLab) containerFromLabNode(
463: 	state *clablabruntime.LabState,
464: 	node clablabruntime.NodeState,
465: ) clabruntime.GenericContainer {
466: 	nodeName := fmt.Sprintf("%s-%s", state.Name, node.Name)
467: 	containerState, containerStatus := labRuntimeContainerState(state, node)
468: 
469: 	topologyNode := node.Name
470: 	if node.TopologyName != "" {
471: 		topologyNode = node.TopologyName
472: 	}
473: 	if c.Config.Topology != nil {
474: 		topologyNode = c.topologyNodeName(topologyNode)
475: 	}
476: 
477: 	labels := map[string]string{
478: 		clabconstants.Containerlab: state.Name,
479: 		clabconstants.NodeName:     topologyNode,
480: 		clabconstants.LongName:     nodeName,
481: 		clabconstants.TopoFile:     labRuntimeTopologyPath(c, state),
482: 	}
483: 
484: 	var image string
485: 	if c.Config.Topology != nil {
486: 		labels[clabconstants.NodeKind] = c.Config.Topology.GetNodeKind(topologyNode)
487: 		image = c.Config.Topology.GetNodeImage(topologyNode)
488: 	}
489: 	if node.Kind != "" {
490: 		labels[clabconstants.NodeKind] = node.Kind
491: 	}
492: 	if node.Image != "" {
493: 		image = node.Image
494: 	}
495: 
496: 	// The node's type and group: from the loaded topology's node, with the kind's defaults the
497: 	// local runtimes report too, otherwise as the topology set them on the runtime's node.
498: 	nodeType, group := node.Type, node.Group
499: 	if topologyNodeConfig, ok := c.Nodes[topologyNode]; ok {
500: 		nodeType, group = topologyNodeConfig.Config().NodeType, topologyNodeConfig.Config().Group
501: 	} else if c.Config.Topology != nil && group == "" {
502: 		group = c.Config.Topology.GetNodeGroup(topologyNode)
503: 	}
504: 	if nodeType != "" {
505: 		labels[clabconstants.NodeType] = nodeType
506: 	}
507: 	if group != "" {
508: 		labels[clabconstants.NodeGroup] = group
509: 	}
510: 
511: 	if state.Owner != "" {
512: 		labels[clabconstants.Owner] = state.Owner
513: 	} else if c.customOwner != "" {
514: 		labels[clabconstants.Owner] = c.customOwner
515: 	}
516: 
517: 	// The ID names the node uniquely across namespaces and labs. It is also the short ID, so
518: 	// inspect reports it as container_id and it matches the events actor ID.
519: 	id := labRuntimeContainerID(state.Namespace, state.Name, node.Name)
520: 
521: 	return clabruntime.GenericContainer{
522: 		Names:           []string{nodeName},
523: 		ID:              id,
524: 		ShortID:         id,
525: 		Image:           image,
526: 		State:           containerState,
527: 		Status:          containerStatus,
528: 		Labels:          labels,
529: 		NetworkName:     state.Namespace,
530: 		NetworkSettings: managementAddress(node),
531: 		Ports:           labRuntimePorts(node.ExposedPorts),
532: 		Workload: &clabtypes.LabRuntimeWorkload{
533: 			Namespace:           state.Namespace,
534: 			Pod:                 node.Pod,
535: 			Container:           node.Container,
536: 			NodeUID:             node.NodeUID,
537: 			ExposedPorts:        node.ExposedPorts,
538: 			LoadBalancerAddress: node.LoadBalancerAddress,
539: 		},
540: 	}
541: }
542: 
543: // labRuntimeContainerState is a lab runtime node's state and status in the vocabulary of the
544: // container runtimes: state created, running or exited; status healthy or "health: starting"
545: // for a running node, as inspect shortens a Docker status line with a healthcheck, Created or
546: // Exited otherwise. A runtime that reports no container state keeps its own state.
547: func labRuntimeContainerState(
548: 	state *clablabruntime.LabState,
549: 	node clablabruntime.NodeState,
550: ) (string, string) {
551: 	switch node.ContainerState {
552: 	case clablabruntime.ContainerStateRunning:
553: 		if node.Health == clablabruntime.ContainerHealthHealthy {
554: 			return node.ContainerState, "healthy"
555: 		}
556: 
557: 		return node.ContainerState, "health: starting"
558: 	case clablabruntime.ContainerStateCreated:
559: 		return node.ContainerState, "Created"
560: 	case clablabruntime.ContainerStateExited:
561: 		return node.ContainerState, "Exited"
562: 	}
563: 
564: 	if node.Ready {
565: 		return clablabruntime.ContainerStateRunning, "healthy"
566: 	}
567: 	if node.State == "" {
568: 		return state.State, ""
569: 	}
570: 
571: 	return node.State, node.State
572: }
573: 
574: // labRuntimePorts reports the ports a lab runtime exposes for a node as the ports a container
575: // exposes without publishing them on the host: the node is reached through the runtime (a
576: // Service, a port-forward), never on a port of this machine.
577: func labRuntimePorts(ports []clablabruntime.ExposedPort) []*clabtypes.GenericPortBinding {
578: 	if len(ports) == 0 {
579: 		return nil
580: 	}
581: 
582: 	bindings := make([]*clabtypes.GenericPortBinding, 0, len(ports))
583: 	for _, port := range ports {
584: 		bindings = append(bindings, &clabtypes.GenericPortBinding{
585: 			ContainerPort: port.Port,
586: 			Protocol:      port.Protocol,
587: 		})
588: 	}
589: 
590: 	return bindings
591: }
592: 
593: // labRuntimeContainerID is the ID of a lab runtime node: <namespace>/<lab>/<node>.
594: func labRuntimeContainerID(namespace, lab, node string) string {
595: 	return fmt.Sprintf("%s/%s/%s", namespace, lab, node)
596: }
597: 
598: // topologyNodeName maps a node name a lab runtime reports back onto the topology node it belongs
599: // to. The runtime renames the nodes Kubernetes cannot carry, so the state it reports does not
600: // always use the name the topology file wrote.
601: func (c *CLab) topologyNodeName(name string) string {
602: 	if c.Config.Topology == nil {
603: 		return name
604: 	}
605: 	if _, ok := c.Config.Topology.Nodes[name]; ok {
606: 		return name
607: 	}
608: 
609: 	for nodeName := range c.Config.Topology.Nodes {
610: 		if clabnames.SanitizeName(nodeName) == name {
611: 			return nodeName
612: 		}
613: 	}
614: 
615: 	return name
616: }
617: 
618: // managementAddress reports the address a user reaches the node at: the LoadBalancer address
619: // when the node is exposed, otherwise the allocated management address.
620: func managementAddress(node clablabruntime.NodeState) clabruntime.GenericMgmtIPs {
621: 	settings := clabruntime.GenericMgmtIPs{}
622: 
623: 	if ip := net.ParseIP(node.LoadBalancerAddress); ip != nil {
624: 		if ip.To4() != nil {
625: 			settings.IPv4addr = node.LoadBalancerAddress
626: 			settings.IPv4pLen = 32
627: 		} else {
628: 			settings.IPv6addr = node.LoadBalancerAddress
629: 			settings.IPv6pLen = 128
630: 		}
631: 	}
632: 
633: 	if settings.IPv4addr == "" {
634: 		settings.IPv4addr, settings.IPv4pLen = splitManagementCIDR(node.MgmtIPv4Address)
635: 	}
636: 	if settings.IPv6addr == "" {
637: 		settings.IPv6addr, settings.IPv6pLen = splitManagementCIDR(node.MgmtIPv6Address)
638: 	}
639: 
640: 	return settings
641: }
642: 
643: func splitManagementCIDR(cidr string) (string, int) {
644: 	if cidr == "" {
645: 		return "", 0
646: 	}
647: 
648: 	ip, network, err := net.ParseCIDR(cidr)
649: 	if err != nil {
650: 		if net.ParseIP(cidr) != nil {
651: 			return cidr, 0
652: 		}
653: 
654: 		return "", 0
655: 	}
656: 
657: 	prefixLen, _ := network.Mask.Size()
658: 
659: 	return ip.String(), prefixLen
660: }
661: 
662: func labRuntimeTopologyPath(c *CLab, state *clablabruntime.LabState) string {
663: 	if c.TopoPaths.TopologyFileIsSet() {
664: 		return c.TopoPaths.TopologyFilenameAbsPath()
665: 	}
666: 
667: 	if state.TopologyPath != "" {
668: 		return state.TopologyPath
669: 	}
670: 
671: 	return fmt.Sprintf("k8s://%s/topologies/%s", state.Namespace, state.Name)
672: }
673: 
674: func labRuntimeContainerParts(c clabruntime.GenericContainer) (string, string, string, error) {
675: 	parts := strings.Split(c.ID, "/")
676: 	if len(parts) != 3 {
677: 		return "", "", "", fmt.Errorf("expected namespace/lab/node id, got %q", c.ID)
678: 	}
679: 
680: 	return parts[0], parts[1], parts[2], nil
681: }
682: 
683: func filterLabRuntimeContainers(
684: 	containers []clabruntime.GenericContainer,
685: 	filters []*clabtypes.GenericFilter,
686: ) []clabruntime.GenericContainer {
687: 	if len(filters) == 0 {
688: 		return containers
689: 	}
690: 
691: 	filtered := make([]clabruntime.GenericContainer, 0, len(containers))
692: 	for _, container := range containers {
693: 		if labRuntimeContainerMatches(container, filters) {
694: 			filtered = append(filtered, container)
695: 		}
696: 	}
697: 
698: 	return filtered
699: }
700: 
701: func labRuntimeContainerMatches(
702: 	container clabruntime.GenericContainer,
703: 	filters []*clabtypes.GenericFilter,
704: ) bool {
705: 	for _, filter := range filters {
706: 		switch filter.FilterType {
707: 		case "name":
708: 			if !labRuntimeNameMatches(container.Names, filter.Match) {
709: 				return false
710: 			}
711: 		case "id":
712: 			if container.ID != filter.Match && !strings.HasPrefix(container.ID, filter.Match) {
713: 				return false
714: 			}
715: 		case "label":
716: 			if !labRuntimeLabelMatches(container.Labels, filter) {
717: 				return false
718: 			}
719: 		}

(Showing lines 440-719 of 827. Use offset=720 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19677593c001pQ8w2FiCZgQ5v7",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196774b9f001rQ0Klo3mQ42lYs",
  "callID": "call_4e0e7d33fa0e4487aeba8815",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/labruntime.go",
      "offset": 440,
      "limit": 280
    },
    "output": "<path>/source/head/core/labruntime.go</path>\n<type>file</type>\n<content>\n440: \t\t\t\tReady: state.Ready,\n441: \t\t\t})\n442: \t\t}\n443: \t}\n444: \n445: \tcontainers := make([]clabruntime.GenericContainer, 0, len(nodes))\n446: \tfor _, node := range nodes {\n447: \t\tcontainers = append(containers, c.containerFromLabNode(state, node))\n448: \t}\n449: \n450: \treturn containers\n451: }\n452: \n453: // LabRuntimeContainer describes a lab runtime node as a container record, the way inspect\n454: // reports it. The events command describes lab runtime nodes with it too.\n455: func (c *CLab) LabRuntimeContainer(\n456: \tstate *clablabruntime.LabState,\n457: \tnode clablabruntime.NodeState,\n458: ) clabruntime.GenericContainer {\n459: \treturn c.containerFromLabNode(state, node)\n460: }\n461: \n462: func (c *CLab) containerFromLabNode(\n463: \tstate *clablabruntime.LabState,\n464: \tnode clablabruntime.NodeState,\n465: ) clabruntime.GenericContainer {\n466: \tnodeName := fmt.Sprintf(\"%s-%s\", state.Name, node.Name)\n467: \tcontainerState, containerStatus := labRuntimeContainerState(state, node)\n468: \n469: \ttopologyNode := node.Name\n470: \tif node.TopologyName != \"\" {\n471: \t\ttopologyNode = node.TopologyName\n472: \t}\n473: \tif c.Config.Topology != nil {\n474: \t\ttopologyNode = c.topologyNodeName(topologyNode)\n475: \t}\n476: \n477: \tlabels := map[string]string{\n478: \t\tclabconstants.Containerlab: state.Name,\n479: \t\tclabconstants.NodeName:     topologyNode,\n480: \t\tclabconstants.LongName:     nodeName,\n481: \t\tclabconstants.TopoFile:     labRuntimeTopologyPath(c, state),\n482: \t}\n483: \n484: \tvar image string\n485: \tif c.Config.Topology != nil {\n486: \t\tlabels[clabconstants.NodeKind] = c.Config.Topology.GetNodeKind(topologyNode)\n487: \t\timage = c.Config.Topology.GetNodeImage(topologyNode)\n488: \t}\n489: \tif node.Kind != \"\" {\n490: \t\tlabels[clabconstants.NodeKind] = node.Kind\n491: \t}\n492: \tif node.Image != \"\" {\n493: \t\timage = node.Image\n494: \t}\n495: \n496: \t// The node's type and group: from the loaded topology's node, with the kind's defaults the\n497: \t// local runtimes report too, otherwise as the topology set them on the runtime's node.\n498: \tnodeType, group := node.Type, node.Group\n499: \tif topologyNodeConfig, ok := c.Nodes[topologyNode]; ok {\n500: \t\tnodeType, group = topologyNodeConfig.Config().NodeType, topologyNodeConfig.Config().Group\n501: \t} else if c.Config.Topology != nil && group == \"\" {\n502: \t\tgroup = c.Config.Topology.GetNodeGroup(topologyNode)\n503: \t}\n504: \tif nodeType != \"\" {\n505: \t\tlabels[clabconstants.NodeType] = nodeType\n506: \t}\n507: \tif group != \"\" {\n508: \t\tlabels[clabconstants.NodeGroup] = group\n509: \t}\n510: \n511: \tif state.Owner != \"\" {\n512: \t\tlabels[clabconstants.Owner] = state.Owner\n513: \t} else if c.customOwner != \"\" {\n514: \t\tlabels[clabconstants.Owner] = c.customOwner\n515: \t}\n516: \n517: \t// The ID names the node uniquely across namespaces and labs. It is also the short ID, so\n518: \t// inspect reports it as container_id and it matches the events actor ID.\n519: \tid := labRuntimeContainerID(state.Namespace, state.Name, node.Name)\n520: \n521: \treturn clabruntime.GenericContainer{\n522: \t\tNames:           []string{nodeName},\n523: \t\tID:              id,\n524: \t\tShortID:         id,\n525: \t\tImage:           image,\n526: \t\tState:           containerState,\n527: \t\tStatus:          containerStatus,\n528: \t\tLabels:          labels,\n529: \t\tNetworkName:     state.Namespace,\n530: \t\tNetworkSettings: managementAddress(node),\n531: \t\tPorts:           labRuntimePorts(node.ExposedPorts),\n532: \t\tWorkload: &clabtypes.LabRuntimeWorkload{\n533: \t\t\tNamespace:           state.Namespace,\n534: \t\t\tPod:                 node.Pod,\n535: \t\t\tContainer:           node.Container,\n536: \t\t\tNodeUID:             node.NodeUID,\n537: \t\t\tExposedPorts:        node.ExposedPorts,\n538: \t\t\tLoadBalancerAddress: node.LoadBalancerAddress,\n539: \t\t},\n540: \t}\n541: }\n542: \n543: // labRuntimeContainerState is a lab runtime node's state and status in the vocabulary of the\n544: // container runtimes: state created, running or exited; status healthy or \"health: starting\"\n545: // for a running node, as inspect shortens a Docker status line with a healthcheck, Created or\n546: // Exited otherwise. A runtime that reports no container state keeps its own state.\n547: func labRuntimeContainerState(\n548: \tstate *clablabruntime.LabState,\n549: \tnode clablabruntime.NodeState,\n550: ) (string, string) {\n551: \tswitch node.ContainerState {\n552: \tcase clablabruntime.ContainerStateRunning:\n553: \t\tif node.Health == clablabruntime.ContainerHealthHealthy {\n554: \t\t\treturn node.ContainerState, \"healthy\"\n555: \t\t}\n556: \n557: \t\treturn node.ContainerState, \"health: starting\"\n558: \tcase clablabruntime.ContainerStateCreated:\n559: \t\treturn node.ContainerState, \"Created\"\n560: \tcase clablabruntime.ContainerStateExited:\n561: \t\treturn node.ContainerState, \"Exited\"\n562: \t}\n563: \n564: \tif node.Ready {\n565: \t\treturn clablabruntime.ContainerStateRunning, \"healthy\"\n566: \t}\n567: \tif node.State == \"\" {\n568: \t\treturn state.State, \"\"\n569: \t}\n570: \n571: \treturn node.State, node.State\n572: }\n573: \n574: // labRuntimePorts reports the ports a lab runtime exposes for a node as the ports a container\n575: // exposes without publishing them on the host: the node is reached through the runtime (a\n576: // Service, a port-forward), never on a port of this machine.\n577: func labRuntimePorts(ports []clablabruntime.ExposedPort) []*clabtypes.GenericPortBinding {\n578: \tif len(ports) == 0 {\n579: \t\treturn nil\n580: \t}\n581: \n582: \tbindings := make([]*clabtypes.GenericPortBinding, 0, len(ports))\n583: \tfor _, port := range ports {\n584: \t\tbindings = append(bindings, &clabtypes.GenericPortBinding{\n585: \t\t\tContainerPort: port.Port,\n586: \t\t\tProtocol:      port.Protocol,\n587: \t\t})\n588: \t}\n589: \n590: \treturn bindings\n591: }\n592: \n593: // labRuntimeContainerID is the ID of a lab runtime node: <namespace>/<lab>/<node>.\n594: func labRuntimeContainerID(namespace, lab, node string) string {\n595: \treturn fmt.Sprintf(\"%s/%s/%s\", namespace, lab, node)\n596: }\n597: \n598: // topologyNodeName maps a node name a lab runtime reports back onto the topology node it belongs\n599: // to. The runtime renames the nodes Kubernetes cannot carry, so the state it reports does not\n600: // always use the name the topology file wrote.\n601: func (c *CLab) topologyNodeName(name string) string {\n602: \tif c.Config.Topology == nil {\n603: \t\treturn name\n604: \t}\n605: \tif _, ok := c.Config.Topology.Nodes[name]; ok {\n606: \t\treturn name\n607: \t}\n608: \n609: \tfor nodeName := range c.Config.Topology.Nodes {\n610: \t\tif clabnames.SanitizeName(nodeName) == name {\n611: \t\t\treturn nodeName\n612: \t\t}\n613: \t}\n614: \n615: \treturn name\n616: }\n617: \n618: // managementAddress reports the address a user reaches the node at: the LoadBalancer address\n619: // when the node is exposed, otherwise the allocated management address.\n620: func managementAddress(node clablabruntime.NodeState) clabruntime.GenericMgmtIPs {\n621: \tsettings := clabruntime.GenericMgmtIPs{}\n622: \n623: \tif ip := net.ParseIP(node.LoadBalancerAddress); ip != nil {\n624: \t\tif ip.To4() != nil {\n625: \t\t\tsettings.IPv4addr = node.LoadBalancerAddress\n626: \t\t\tsettings.IPv4pLen = 32\n627: \t\t} else {\n628: \t\t\tsettings.IPv6addr = node.LoadBalancerAddress\n629: \t\t\tsettings.IPv6pLen = 128\n630: \t\t}\n631: \t}\n632: \n633: \tif settings.IPv4addr == \"\" {\n634: \t\tsettings.IPv4addr, settings.IPv4pLen = splitManagementCIDR(node.MgmtIPv4Address)\n635: \t}\n636: \tif settings.IPv6addr == \"\" {\n637: \t\tsettings.IPv6addr, settings.IPv6pLen = splitManagementCIDR(node.MgmtIPv6Address)\n638: \t}\n639: \n640: \treturn settings\n641: }\n642: \n643: func splitManagementCIDR(cidr string) (string, int) {\n644: \tif cidr == \"\" {\n645: \t\treturn \"\", 0\n646: \t}\n647: \n648: \tip, network, err := net.ParseCIDR(cidr)\n649: \tif err != nil {\n650: \t\tif net.ParseIP(cidr) != nil {\n651: \t\t\treturn cidr, 0\n652: \t\t}\n653: \n654: \t\treturn \"\", 0\n655: \t}\n656: \n657: \tprefixLen, _ := network.Mask.Size()\n658: \n659: \treturn ip.String(), prefixLen\n660: }\n661: \n662: func labRuntimeTopologyPath(c *CLab, state *clablabruntime.LabState) string {\n663: \tif c.TopoPaths.TopologyFileIsSet() {\n664: \t\treturn c.TopoPaths.TopologyFilenameAbsPath()\n665: \t}\n666: \n667: \tif state.TopologyPath != \"\" {\n668: \t\treturn state.TopologyPath\n669: \t}\n670: \n671: \treturn fmt.Sprintf(\"k8s://%s/topologies/%s\", state.Namespace, state.Name)\n672: }\n673: \n674: func labRuntimeContainerParts(c clabruntime.GenericContainer) (string, string, string, error) {\n675: \tparts := strings.Split(c.ID, \"/\")\n676: \tif len(parts) != 3 {\n677: \t\treturn \"\", \"\", \"\", fmt.Errorf(\"expected namespace/lab/node id, got %q\", c.ID)\n678: \t}\n679: \n680: \treturn parts[0], parts[1], parts[2], nil\n681: }\n682: \n683: func filterLabRuntimeContainers(\n684: \tcontainers []clabruntime.GenericContainer,\n685: \tfilters []*clabtypes.GenericFilter,\n686: ) []clabruntime.GenericContainer {\n687: \tif len(filters) == 0 {\n688: \t\treturn containers\n689: \t}\n690: \n691: \tfiltered := make([]clabruntime.GenericContainer, 0, len(containers))\n692: \tfor _, container := range containers {\n693: \t\tif labRuntimeContainerMatches(container, filters) {\n694: \t\t\tfiltered = append(filtered, container)\n695: \t\t}\n696: \t}\n697: \n698: \treturn filtered\n699: }\n700: \n701: func labRuntimeContainerMatches(\n702: \tcontainer clabruntime.GenericContainer,\n703: \tfilters []*clabtypes.GenericFilter,\n704: ) bool {\n705: \tfor _, filter := range filters {\n706: \t\tswitch filter.FilterType {\n707: \t\tcase \"name\":\n708: \t\t\tif !labRuntimeNameMatches(container.Names, filter.Match) {\n709: \t\t\t\treturn false\n710: \t\t\t}\n711: \t\tcase \"id\":\n712: \t\t\tif container.ID != filter.Match && !strings.HasPrefix(container.ID, filter.Match) {\n713: \t\t\t\treturn false\n714: \t\t\t}\n715: \t\tcase \"label\":\n716: \t\t\tif !labRuntimeLabelMatches(container.Labels, filter) {\n717: \t\t\t\treturn false\n718: \t\t\t}\n719: \t\t}\n\n(Showing lines 440-719 of 827. Use offset=720 to continue.)\n</content>",
    "title": "source/head/core/labruntime.go",
    "metadata": {
      "preview": "\t\t\t\tReady: state.Ready,\n\t\t\t})\n\t\t}\n\t}\n\n\tcontainers := make([]clabruntime.GenericContainer, 0, len(nodes))\n\tfor _, node := range nodes {\n\t\tcontainers = append(containers, c.containerFromLabNode(state, node))\n\t}\n\n\treturn containers\n}\n\n// LabRuntimeContainer describes a lab runtime node as a container record, the way inspect\n// reports it. The events command describes lab runtime nodes with it too.\nfunc (c *CLab) LabRuntimeContainer(\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n) clabruntime.GenericContainer {\n\treturn c.containerFromLabNode(state, node)",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/labruntime.go",
        "text": "\t\t\t\tReady: state.Ready,\n\t\t\t})\n\t\t}\n\t}\n\n\tcontainers := make([]clabruntime.GenericContainer, 0, len(nodes))\n\tfor _, node := range nodes {\n\t\tcontainers = append(containers, c.containerFromLabNode(state, node))\n\t}\n\n\treturn containers\n}\n\n// LabRuntimeContainer describes a lab runtime node as a container record, the way inspect\n// reports it. The events command describes lab runtime nodes with it too.\nfunc (c *CLab) LabRuntimeContainer(\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n) clabruntime.GenericContainer {\n\treturn c.containerFromLabNode(state, node)\n}\n\nfunc (c *CLab) containerFromLabNode(\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n) clabruntime.GenericContainer {\n\tnodeName := fmt.Sprintf(\"%s-%s\", state.Name, node.Name)\n\tcontainerState, containerStatus := labRuntimeContainerState(state, node)\n\n\ttopologyNode := node.Name\n\tif node.TopologyName != \"\" {\n\t\ttopologyNode = node.TopologyName\n\t}\n\tif c.Config.Topology != nil {\n\t\ttopologyNode = c.topologyNodeName(topologyNode)\n\t}\n\n\tlabels := map[string]string{\n\t\tclabconstants.Containerlab: state.Name,\n\t\tclabconstants.NodeName:     topologyNode,\n\t\tclabconstants.LongName:     nodeName,\n\t\tclabconstants.TopoFile:     labRuntimeTopologyPath(c, state),\n\t}\n\n\tvar image string\n\tif c.Config.Topology != nil {\n\t\tlabels[clabconstants.NodeKind] = c.Config.Topology.GetNodeKind(topologyNode)\n\t\timage = c.Config.Topology.GetNodeImage(topologyNode)\n\t}\n\tif node.Kind != \"\" {\n\t\tlabels[clabconstants.NodeKind] = node.Kind\n\t}\n\tif node.Image != \"\" {\n\t\timage = node.Image\n\t}\n\n\t// The node's type and group: from the loaded topology's node, with the kind's defaults the\n\t// local runtimes report too, otherwise as the topology set them on the runtime's node.\n\tnodeType, group := node.Type, node.Group\n\tif topologyNodeConfig, ok := c.Nodes[topologyNode]; ok {\n\t\tnodeType, group = topologyNodeConfig.Config().NodeType, topologyNodeConfig.Config().Group\n\t} else if c.Config.Topology != nil && group == \"\" {\n\t\tgroup = c.Config.Topology.GetNodeGroup(topologyNode)\n\t}\n\tif nodeType != \"\" {\n\t\tlabels[clabconstants.NodeType] = nodeType\n\t}\n\tif group != \"\" {\n\t\tlabels[clabconstants.NodeGroup] = group\n\t}\n\n\tif state.Owner != \"\" {\n\t\tlabels[clabconstants.Owner] = state.Owner\n\t} else if c.customOwner != \"\" {\n\t\tlabels[clabconstants.Owner] = c.customOwner\n\t}\n\n\t// The ID names the node uniquely across namespaces and labs. It is also the short ID, so\n\t// inspect reports it as container_id and it matches the events actor ID.\n\tid := labRuntimeContainerID(state.Namespace, state.Name, node.Name)\n\n\treturn clabruntime.GenericContainer{\n\t\tNames:           []string{nodeName},\n\t\tID:              id,\n\t\tShortID:         id,\n\t\tImage:           image,\n\t\tState:           containerState,\n\t\tStatus:          containerStatus,\n\t\tLabels:          labels,\n\t\tNetworkName:     state.Namespace,\n\t\tNetworkSettings: managementAddress(node),\n\t\tPorts:           labRuntimePorts(node.ExposedPorts),\n\t\tWorkload: &clabtypes.LabRuntimeWorkload{\n\t\t\tNamespace:           state.Namespace,\n\t\t\tPod:                 node.Pod,\n\t\t\tContainer:           node.Container,\n\t\t\tNodeUID:             node.NodeUID,\n\t\t\tExposedPorts:        node.ExposedPorts,\n\t\t\tLoadBalancerAddress: node.LoadBalancerAddress,\n\t\t},\n\t}\n}\n\n// labRuntimeContainerState is a lab runtime node's state and status in the vocabulary of the\n// container runtimes: state created, running or exited; status healthy or \"health: starting\"\n// for a running node, as inspect shortens a Docker status line with a healthcheck, Created or\n// Exited otherwise. A runtime that reports no container state keeps its own state.\nfunc labRuntimeContainerState(\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n) (string, string) {\n\tswitch node.ContainerState {\n\tcase clablabruntime.ContainerStateRunning:\n\t\tif node.Health == clablabruntime.ContainerHealthHealthy {\n\t\t\treturn node.ContainerState, \"healthy\"\n\t\t}\n\n\t\treturn node.ContainerState, \"health: starting\"\n\tcase clablabruntime.ContainerStateCreated:\n\t\treturn node.ContainerState, \"Created\"\n\tcase clablabruntime.ContainerStateExited:\n\t\treturn node.ContainerState, \"Exited\"\n\t}\n\n\tif node.Ready {\n\t\treturn clablabruntime.ContainerStateRunning, \"healthy\"\n\t}\n\tif node.State == \"\" {\n\t\treturn state.State, \"\"\n\t}\n\n\treturn node.State, node.State\n}\n\n// labRuntimePorts reports the ports a lab runtime exposes for a node as the ports a container\n// exposes without publishing them on the host: the node is reached through the runtime (a\n// Service, a port-forward), never on a port of this machine.\nfunc labRuntimePorts(ports []clablabruntime.ExposedPort) []*clabtypes.GenericPortBinding {\n\tif len(ports) == 0 {\n\t\treturn nil\n\t}\n\n\tbindings := make([]*clabtypes.GenericPortBinding, 0, len(ports))\n\tfor _, port := range ports {\n\t\tbindings = append(bindings, &clabtypes.GenericPortBinding{\n\t\t\tContainerPort: port.Port,\n\t\t\tProtocol:      port.Protocol,\n\t\t})\n\t}\n\n\treturn bindings\n}\n\n// labRuntimeContainerID is the ID of a lab runtime node: <namespace>/<lab>/<node>.\nfunc labRuntimeContainerID(namespace, lab, node string) string {\n\treturn fmt.Sprintf(\"%s/%s/%s\", namespace, lab, node)\n}\n\n// topologyNodeName maps a node name a lab runtime reports back onto the topology node it belongs\n// to. The runtime renames the nodes Kubernetes cannot carry, so the state it reports does not\n// always use the name the topology file wrote.\nfunc (c *CLab) topologyNodeName(name string) string {\n\tif c.Config.Topology == nil {\n\t\treturn name\n\t}\n\tif _, ok := c.Config.Topology.Nodes[name]; ok {\n\t\treturn name\n\t}\n\n\tfor nodeName := range c.Config.Topology.Nodes {\n\t\tif clabnames.SanitizeName(nodeName) == name {\n\t\t\treturn nodeName\n\t\t}\n\t}\n\n\treturn name\n}\n\n// managementAddress reports the address a user reaches the node at: the LoadBalancer address\n// when the node is exposed, otherwise the allocated management address.\nfunc managementAddress(node clablabruntime.NodeState) clabruntime.GenericMgmtIPs {\n\tsettings := clabruntime.GenericMgmtIPs{}\n\n\tif ip := net.ParseIP(node.LoadBalancerAddress); ip != nil {\n\t\tif ip.To4() != nil {\n\t\t\tsettings.IPv4addr = node.LoadBalancerAddress\n\t\t\tsettings.IPv4pLen = 32\n\t\t} else {\n\t\t\tsettings.IPv6addr = node.LoadBalancerAddress\n\t\t\tsettings.IPv6pLen = 128\n\t\t}\n\t}\n\n\tif settings.IPv4addr == \"\" {\n\t\tsettings.IPv4addr, settings.IPv4pLen = splitManagementCIDR(node.MgmtIPv4Address)\n\t}\n\tif settings.IPv6addr == \"\" {\n\t\tsettings.IPv6addr, settings.IPv6pLen = splitManagementCIDR(node.MgmtIPv6Address)\n\t}\n\n\treturn settings\n}\n\nfunc splitManagementCIDR(cidr string) (string, int) {\n\tif cidr == \"\" {\n\t\treturn \"\", 0\n\t}\n\n\tip, network, err := net.ParseCIDR(cidr)\n\tif err != nil {\n\t\tif net.ParseIP(cidr) != nil {\n\t\t\treturn cidr, 0\n\t\t}\n\n\t\treturn \"\", 0\n\t}\n\n\tprefixLen, _ := network.Mask.Size()\n\n\treturn ip.String(), prefixLen\n}\n\nfunc labRuntimeTopologyPath(c *CLab, state *clablabruntime.LabState) string {\n\tif c.TopoPaths.TopologyFileIsSet() {\n\t\treturn c.TopoPaths.TopologyFilenameAbsPath()\n\t}\n\n\tif state.TopologyPath != \"\" {\n\t\treturn state.TopologyPath\n\t}\n\n\treturn fmt.Sprintf(\"k8s://%s/topologies/%s\", state.Namespace, state.Name)\n}\n\nfunc labRuntimeContainerParts(c clabruntime.GenericContainer) (string, string, string, error) {\n\tparts := strings.Split(c.ID, \"/\")\n\tif len(parts) != 3 {\n\t\treturn \"\", \"\", \"\", fmt.Errorf(\"expected namespace/lab/node id, got %q\", c.ID)\n\t}\n\n\treturn parts[0], parts[1], parts[2], nil\n}\n\nfunc filterLabRuntimeContainers(\n\tcontainers []clabruntime.GenericContainer,\n\tfilters []*clabtypes.GenericFilter,\n) []clabruntime.GenericContainer {\n\tif len(filters) == 0 {\n\t\treturn containers\n\t}\n\n\tfiltered := make([]clabruntime.GenericContainer, 0, len(containers))\n\tfor _, container := range containers {\n\t\tif labRuntimeContainerMatches(container, filters) {\n\t\t\tfiltered = append(filtered, container)\n\t\t}\n\t}\n\n\treturn filtered\n}\n\nfunc labRuntimeContainerMatches(\n\tcontainer clabruntime.GenericContainer,\n\tfilters []*clabtypes.GenericFilter,\n) bool {\n\tfor _, filter := range filters {\n\t\tswitch filter.FilterType {\n\t\tcase \"name\":\n\t\t\tif !labRuntimeNameMatches(container.Names, filter.Match) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase \"id\":\n\t\t\tif container.ID != filter.Match && !strings.HasPrefix(container.ID, filter.Match) {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase \"label\":\n\t\t\tif !labRuntimeLabelMatches(container.Labels, filter) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}",
        "lineStart": 440,
        "lineEnd": 719,
        "totalLines": 827,
        "truncated": true
      }
    },
    "time": {
      "start": 1793525766465,
      "end": 1793525766472
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19677594b001A1qytVwlhaCrmf",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196774b9f001rQ0Klo3mQ42lYs",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 43307,
    "input": 40398,
    "output": 28,
    "reasoning": 1,
    "cache": {
      "read": 2880,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196774b9f001rQ0Klo3mQ42lYs",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525762975,
    "completed": 1793525766479
  },
  "parentID": "msg_19676df9500159h7P3dGcuBxjO",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 43307,
    "input": 40398,
    "output": 28,
    "reasoning": 1,
    "cache": {
      "read": 2880,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 18
step-start
{
  "type": "step-start",
  "id": "prt_1967760bc001rRjsdWRBzw2B2p",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196775955001eS3UIf8cY8YWd1"
}
Reasoning
Noted: `containerFromLabNode` nodeType: `if topologyNodeConfig, ok := c.Nodes[topologyNode]; ok { nodeType, group = topologyNodeConfig.Config().NodeType, ... }` — this unconditionally overrides node.Type even when the topology config's NodeType is empty. That's my earlier candidate: if the local loaded topology differs (edited between deploy and event read) or the topology doesn't include the node, we override with "" — wait no: `nodeType, group = cfg.NodeType, cfg.Group` — if the loaded topology has the node but NodeType is empty (auto-derived kinds? For local runtimes, NodeType gets set from kind defaults during deploy; but here reading from the loaded config, NodeType may be empty if the node's kind was specified but type defaults are applied at deploy time, not parse time). Hmm — in the local topology parse, `NodeType` defaults are set per kind via `kindDefaults`? Let me check: in `core/config.go`, node config `NodeType` is set to `nodeDef.GetShortName()` or similar during topology load. Actually for the local events path (containerAttributes), labels come from real Docker containers, which have the real NodeType label set at deploy. Here for c9s nodes, when the user runs `clab events --topo file.yaml` against a c9s lab, c.Nodes is populated from the parsed topology, so NodeType should be set by the loader (kinds set NodeTypes). But if the user runs `clab events` without --topo (byName mode), c.Config.Topology == nil, and c.Nodes is empty, so node.Type/group from the runtime state are used — good fallback.

The risk: when the loaded topology has the node but `Config().NodeType` is empty while node.Type (from runtime state) is set. Does the topology loader always set NodeType? In containerlab, `types.NodeConfig.NodeType` is set during `ParseTopoConfig` for each node — yes, typically `nodeType` from kind defaults. But for a node with a kind whose type is the kind name, it's set. Let me not overstate; but if the user edits the topology after deploy (renaming/changes), labels would reflect the edited topology rather than the deployed one. That's arguably intentional (docs might say local enrichment is best-effort). I'll check how the diff justifies this. This could be a P4 note at most.

Also `c.Nodes[topologyNode]` — c.Nodes is only populated when a topology is loaded. With `--name` mode, Nodes is empty. OK.

Now check the earlier part of labruntime.go (0-440) for context: `ListContainers` with lab runtime etc. Also check the diff for what was added. Actually, I've been reading head files; the diff is the authority on what changed. I read diff partially. Let me finish reading diff.txt to see all changes. It's likely ~6000 lines. Let me read the remaining parts.
`containerFromLabNode` and helpers look coherent. Now let me finish reading the full diff to catalog all changes.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 1300,
  "offset": 4396
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
4396:  func nodeStateFromResource(nodeResource *unstructured.Unstructured) clablabruntime.NodeState {
4397:  	node := clablabruntime.NodeState{
4398:  		Name:    nodeResource.GetName(),
4399:  		NodeUID: string(nodeResource.GetUID()),
4400:  	}
4401: +	if original := nodeResource.GetLabels()[labelOriginalNodeName]; original != node.Name {
4402: +		node.TopologyName = original
4403: +	}
4404:  	node.ExposedPorts = nodeExposedPorts(nodeResource)
4405:  	// The same container exec targets: the observed primary device container.
4406:  	node.Container, _ = preferredDeviceContainerName(nodeResource, node.Name)
4407:  	node.Kind, _, _ = unstructured.NestedString(nodeResource.Object, "spec", "kind")
4408:  	node.Image, _, _ = unstructured.NestedString(nodeResource.Object, "spec", "image")
4409: +	node.Type, _, _ = unstructured.NestedString(nodeResource.Object, "spec", "type")
4410: +	node.Group, _, _ = unstructured.NestedString(nodeResource.Object, "spec", "group")
4411:  	node.State, _, _ = unstructured.NestedString(nodeResource.Object, "status", "readiness")
4412:  	node.Ready = node.State == "ready"
4413:  	node.LoadBalancerAddress, _, _ = unstructured.NestedString(
4414:  		nodeResource.Object,
4415:  		"status",
4416: @@ -132,17 +144,28 @@ func intField(value any) int {
4417:  	default:
4418:  		return 0
4419:  	}
4420:  }
4421:  
4422: -// newestPod prefers a running pod and, among equals, the newest one: several pods can match a
4423: -// node during a rolling update.
4424: +// newestPod prefers a pod that is not being deleted, then a running pod and, among equals, the
4425: +// newest one: several pods can match a node during a rolling update or a restart, when the old
4426: +// pod terminates while its replacement starts.
4427:  func newestPod(current, candidate *corev1.Pod) *corev1.Pod {
4428:  	if current == nil {
4429:  		return candidate
4430:  	}
4431:  
4432: +	currentDeleting := current.DeletionTimestamp != nil
4433: +	candidateDeleting := candidate.DeletionTimestamp != nil
4434: +	if currentDeleting != candidateDeleting {
4435: +		if candidateDeleting {
4436: +			return current
4437: +		}
4438: +
4439: +		return candidate
4440: +	}
4441: +
4442:  	currentRunning := current.Status.Phase == corev1.PodRunning
4443:  	candidateRunning := candidate.Status.Phase == corev1.PodRunning
4444:  	if currentRunning != candidateRunning {
4445:  		if candidateRunning {
4446:  			return candidate
4447: @@ -197,20 +220,30 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat
4448:  	for idx := range pods.Items {
4449:  		nodeName := pods.Items[idx].Labels[labelTopologyNode]
4450:  		if nodeName == "" {
4451:  			continue
4452:  		}
4453: +		// A pod of an earlier Node of the same name (a redeploy while the old pod still
4454: +		// terminates) is not this node's pod.
4455: +		if uid := pods.Items[idx].Annotations[annotationDirectNodeUID]; uid != "" {
4456: +			if resource := resourcesByName[nodeName]; resource != nil &&
4457: +				string(resource.GetUID()) != uid {
4458: +				continue
4459: +			}
4460: +		}
4461:  		podsByNode[nodeName] = newestPod(podsByNode[nodeName], &pods.Items[idx])
4462:  	}
4463:  
4464:  	// The Node's status.readiness is the authoritative device signal. The primary Node's run
4465:  	// state governs the pod a group of nodes shares: a stopped primary stops the whole group.
4466:  	// Nodes without readiness yet report their pod phase.
4467:  	for nodeName, node := range nodesByName {
4468:  		primary := resolvePrimaryNode(nodeName, networkModes)
4469: -		if primaryResource := resourcesByName[primary]; primaryResource != nil &&
4470: -			nodeRunState(primaryResource) == nodeRunStateStopped {
4471: +		primaryResource := resourcesByName[primary]
4472: +		stopRequested := primaryResource != nil &&
4473: +			nodeRunState(primaryResource) == nodeRunStateStopped
4474: +		if stopRequested {
4475:  			node.State = "stopping"
4476:  			if condition := nodeCondition(
4477:  				primaryResource,
4478:  				nodeConditionStopped,
4479:  			); condition != nil &&
4480: @@ -220,10 +253,14 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat
4481:  			node.Ready = false
4482:  		} else if pod := podsByNode[primary]; node.State == "" && pod != nil &&
4483:  			pod.Status.Phase != "" {
4484:  			node.State = strings.ToLower(string(pod.Status.Phase))
4485:  		}
4486: +		node.ContainerState = nodeContainerState(stopRequested, podsByNode[primary])
4487: +		if node.ContainerState == clablabruntime.ContainerStateRunning {
4488: +			node.Health = nodeHealth(node, resourcesByName[nodeName])
4489: +		}
4490:  		nodesByName[nodeName] = node
4491:  	}
4492:  
4493:  	// Nodes grouped through network-mode container: share the pod of the group's primary
4494:  	// node. Before the controller observed the device containers, the pod's default-container
4495: @@ -270,5 +307,46 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat
4496:  		state.Ready = false
4497:  	}
4498:  
4499:  	return nil
4500:  }
4501: +
4502: +// nodeContainerState is the state of a node in container runtime terms, from its pod: created
4503: +// while the pod is scheduled and prepared (init containers), running once the device containers
4504: +// run, and exited once the node was stopped, its pod is being deleted, or the pod ended. Between
4505: +// the pods of a restart the node is exited, then created.
4506: +func nodeContainerState(stopRequested bool, pod *corev1.Pod) string {
4507: +	switch {
4508: +	case pod == nil && stopRequested:
4509: +		return clablabruntime.ContainerStateExited
4510: +	case pod == nil:
4511: +		return clablabruntime.ContainerStateCreated
4512: +	case stopRequested || pod.DeletionTimestamp != nil:
4513: +		return clablabruntime.ContainerStateExited
4514: +	}
4515: +
4516: +	switch pod.Status.Phase {
4517: +	case corev1.PodRunning:
4518: +		return clablabruntime.ContainerStateRunning
4519: +	case corev1.PodSucceeded, corev1.PodFailed:
4520: +		return clablabruntime.ContainerStateExited
4521: +	default:
4522: +		return clablabruntime.ContainerStateCreated
4523: +	}
4524: +}
4525: +
4526: +// nodeHealth is the health of a running node: healthy once the Node is ready or its device
4527: +// containers are, starting before. Device containers are the analogue of a container
4528: +// healthcheck: a node whose links wait for a stopped peer is not ready, but its device is.
4529: +func nodeHealth(node clablabruntime.NodeState, resource *unstructured.Unstructured) string {
4530: +	if node.Ready {
4531: +		return clablabruntime.ContainerHealthHealthy
4532: +	}
4533: +	if resource != nil {
4534: +		if condition := nodeCondition(resource, nodeConditionContainersReady); condition != nil &&
4535: +			condition.status == string(metav1.ConditionTrue) {
4536: +			return clablabruntime.ContainerHealthHealthy
4537: +		}
4538: +	}
4539: +
4540: +	return clablabruntime.ContainerHealthStarting
4541: +}
4542: diff --git a/labruntime/clabernetes/topology.go b/labruntime/clabernetes/topology.go
4543: index e401ecf..db3715a 100644
4544: --- a/labruntime/clabernetes/topology.go
4545: +++ b/labruntime/clabernetes/topology.go
4546: @@ -12,10 +12,56 @@ import (
4547:  	"k8s.io/apimachinery/pkg/util/validation"
4548:  )
4549:  
4550:  type topologyObjectOption func(map[string]any)
4551:  
4552: +// annotationTopologyFile records the absolute path of the topology file a lab was deployed from,
4553: +// on the machine that deployed it. Inspect reports it as the lab's topology path and events as
4554: +// clab-topo-file, as the local runtimes do, so clients match the running lab to its file. A lab
4555: +// created by other means than a containerlab deploy has no annotation and reports where its
4556: +// definition lives in the cluster (k8s://<namespace>/topologies/<lab>).
4557: +const annotationTopologyFile = "containerlab.dev/topo-file"
4558: +
4559: +// setTopologySourceFile records the topology file a deploy reads on the Topology. An empty path
4560: +// (a definition that came from no file) records nothing.
4561: +func setTopologySourceFile(topology *unstructured.Unstructured, path string) {
4562: +	if path == "" {
4563: +		return
4564: +	}
4565: +
4566: +	annotations := topology.GetAnnotations()
4567: +	if annotations == nil {
4568: +		annotations = map[string]string{}
4569: +	}
4570: +	annotations[annotationTopologyFile] = path
4571: +	topology.SetAnnotations(annotations)
4572: +}
4573: +
4574: +// removeTopologySourceFile drops the deploying machine's file path from an object.
4575: +func removeTopologySourceFile(obj *unstructured.Unstructured) {
4576: +	annotations := obj.GetAnnotations()
4577: +	if _, ok := annotations[annotationTopologyFile]; !ok {
4578: +		return
4579: +	}
4580: +
4581: +	delete(annotations, annotationTopologyFile)
4582: +	if len(annotations) == 0 {
4583: +		annotations = nil
4584: +	}
4585: +	obj.SetAnnotations(annotations)
4586: +}
4587: +
4588: +// labTopologyPath is the topology path a lab reports: the file it was deployed from when the
4589: +// deploy recorded one, otherwise the place given.
4590: +func labTopologyPath(annotations map[string]string, fallback string) string {
4591: +	if path := annotations[annotationTopologyFile]; path != "" {
4592: +		return path
4593: +	}
4594: +
4595: +	return fallback
4596: +}
4597: +
4598:  func topologyWithNaming(naming string) topologyObjectOption {
4599:  	return func(spec map[string]any) {
4600:  		if naming != "" {
4601:  			spec["naming"] = naming
4602:  		}
4603: @@ -137,10 +183,14 @@ func stateFromTopology(obj *unstructured.Unstructured, namespace string) *clabla
4604:  	owner := obj.GetLabels()[clabconstants.Owner]
4605:  	if owner == "" {
4606:  		owner = obj.GetAnnotations()[clabconstants.Owner]
4607:  	}
4608:  	nodeSpecs := nodeSpecsFromTopology(obj)
4609: +	topologyPath := labTopologyPath(
4610: +		obj.GetAnnotations(),
4611: +		fmt.Sprintf("k8s://%s/topologies/%s", namespace, obj.GetName()),
4612: +	)
4613:  
4614:  	nodeNames := make([]string, 0, len(nodeSpecs))
4615:  	for nodeName := range nodeSpecs {
4616:  		nodeNames = append(nodeNames, nodeName)
4617:  	}
4618: @@ -158,11 +208,11 @@ func stateFromTopology(obj *unstructured.Unstructured, namespace string) *clabla
4619:  
4620:  	return &clablabruntime.LabState{
4621:  		Name:         obj.GetName(),
4622:  		Namespace:    namespace,
4623:  		Owner:        owner,
4624: -		TopologyPath: fmt.Sprintf("k8s://%s/topologies/%s", namespace, obj.GetName()),
4625: +		TopologyPath: topologyPath,
4626:  		State:        state,
4627:  		Ready:        ready,
4628:  		Nodes:        nodes,
4629:  	}
4630:  }
4631: diff --git a/labruntime/runtime.go b/labruntime/runtime.go
4632: index 367565d..0f2433a 100644
4633: --- a/labruntime/runtime.go
4634: +++ b/labruntime/runtime.go
4635: @@ -191,16 +191,42 @@ type SavedFile struct {
4636:  
4637:  type SaveResult struct {
4638:  	Files []SavedFile
4639:  }
4640:  
4641: +// Container states and health in the vocabulary of container runtimes (Docker), which inspect
4642: +// and events report for lab runtime nodes too.
4643: +const (
4644: +	ContainerStateCreated = "created"
4645: +	ContainerStateRunning = "running"
4646: +	ContainerStateExited  = "exited"
4647: +
4648: +	ContainerHealthHealthy   = "healthy"
4649: +	ContainerHealthStarting  = "starting"
4650: +	ContainerHealthUnhealthy = "unhealthy"
4651: +)
4652: +
4653:  type NodeState struct {
4654: -	Name  string
4655: -	Kind  string
4656: -	Image string
4657: +	Name string
4658: +	// TopologyName is the node name as the topology file spells it, when the runtime had to
4659: +	// carry the node under another name (Name). Empty means Name.
4660: +	TopologyName string
4661: +	Kind         string
4662: +	Image        string
4663: +	// Type and Group are the node's type and group when the topology set them.
4664: +	Type  string
4665: +	Group string
4666: +	// State is the runtime's own view of the node, such as the clabernetes Node readiness, or
4667: +	// stopped.
4668:  	State string
4669:  	Ready bool
4670: +	// ContainerState is the node's state in container runtime terms: created, running or
4671: +	// exited (the ContainerState* constants). Empty when the runtime does not report one.
4672: +	ContainerState string
4673: +	// Health is the device health of a running node in container runtime terms: healthy or
4674: +	// starting. Empty when the node does not run.
4675: +	Health string
4676:  	// MgmtIPv4Address and MgmtIPv6Address are the node's allocated management addresses in
4677:  	// CIDR notation, when the runtime reports them.
4678:  	MgmtIPv4Address     string
4679:  	MgmtIPv6Address     string
4680:  	LoadBalancerAddress string
4681: @@ -216,13 +242,16 @@ type NodeState struct {
4682:  
4683:  // ExposedPort is a node port a lab runtime publishes through a Service.
4684:  type ExposedPort = clabtypes.ExposedPort
4685:  
4686:  type LabState struct {
4687: -	Name         string
4688: -	Namespace    string
4689: -	Owner        string
4690: +	Name      string
4691: +	Namespace string
4692: +	Owner     string
4693: +	// TopologyPath is the absolute path of the topology file the lab was deployed from, on the
4694: +	// machine that deployed it. A lab the runtime did not deploy from a file reports where the
4695: +	// runtime keeps its definition instead (for c9s k8s://<namespace>/topologies/<lab>).
4696:  	TopologyPath string
4697:  	State        string
4698:  	Ready        bool
4699:  	Nodes        []NodeState
4700:  }
4701: @@ -258,11 +287,61 @@ type Event struct {
4702:  	Type        string
4703:  	Action      string
4704:  	ActorID     string
4705:  	ActorName   string
4706:  	ActorFullID string
4707: -	Attributes  map[string]string
4708: +	// Attributes are the runtime's own attributes. Event consumers add the attributes the
4709: +	// container runtimes report from Lab, Node and Interface.
4710: +	Attributes map[string]string
4711: +	// Lab and Node are the lab node a container or interface event is about, as Inspect
4712: +	// reports it. containerlab's events command describes the node from them the same way
4713: +	// inspect does, so both agree and match what the container runtimes report.
4714: +	Lab  *LabState
4715: +	Node *NodeState
4716: +	// Interface is the interface an interface event reports.
4717: +	Interface *InterfaceEventData
4718: +}
4719: +
4720: +// Event types and the origin attribute of lab runtime events.
4721: +const (
4722: +	EventTypeContainer = "container"
4723: +	EventTypeInterface = "interface"
4724: +	// EventOriginSnapshot marks the events of --initial-state, in the origin attribute.
4725: +	EventOriginSnapshot = "snapshot"
4726: +)
4727: +
4728: +// InterfaceEventData describes an interface of a node the way the container runtimes' interface
4729: +// events do (netlink).
4730: +type InterfaceEventData struct {
4731: +	// Name is the interface name inside the node.
4732: +	Name string
4733: +	// Alias is the name the topology gave the interface when the node kind maps it (for
4734: +	// example ethernet-1/1 for SR Linux e1-1).
4735: +	Alias string
4736: +	Index int
4737: +	MTU   int
4738: +	MAC   string
4739: +	// OperState is the operational state in netlink's vocabulary: up, down, lower-layer-down,
4740: +	// dormant, testing, not-present or unknown.
4741: +	OperState string
4742: +	// Type is the link type in netlink's vocabulary, such as veth or device (loopback).
4743: +	Type string
4744: +	// Stats are set on stats events.
4745: +	Stats *InterfaceStats
4746: +}
4747: +
4748: +// InterfaceStats are the counters and rates of an interface stats event.
4749: +type InterfaceStats struct {
4750: +	RxBytes   uint64
4751: +	TxBytes   uint64
4752: +	RxPackets uint64
4753: +	TxPackets uint64
4754: +	RxBps     float64
4755: +	TxBps     float64
4756: +	RxPps     float64
4757: +	TxPps     float64
4758: +	Interval  time.Duration
4759:  }
4760:  
4761:  // NodeLocation is the workload that runs a lab node.
4762:  type NodeLocation struct {
4763:  	// NodeName is the node name the runtime carries (the sanitized name).
4764: diff --git a/tests/14-clabernetes/01-linux-lifecycle.robot b/tests/14-clabernetes/01-linux-lifecycle.robot
4765: index f45a3ff..bc27828 100644
4766: --- a/tests/14-clabernetes/01-linux-lifecycle.robot
4767: +++ b/tests/14-clabernetes/01-linux-lifecycle.robot
4768: @@ -27,10 +27,15 @@ ${recovery-timeout}     180s
4769:  ${retry-interval}       5s
4770:  ${capture-file}         /tmp/clab-c9s-capture.pcapng
4771:  ${chain-file}           /tmp/clab-c9s-capture-chain.pcapng
4772:  ${stop-file}            /tmp/clab-c9s-capture-stop.pcapng
4773:  ${stop-err}             /tmp/clab-c9s-capture-stop.err
4774: +${lifecycle-log}        /tmp/clab-c9s-lifecycle-events.log
4775: +${lifecycle-err}        /tmp/clab-c9s-lifecycle-events.err
4776: +${redeploy-log}         /tmp/clab-c9s-redeploy-events.log
4777: +${redeploy-err}         /tmp/clab-c9s-redeploy-events.err
4778: +${node-image}           ghcr.io/srl-labs/network-multitool
4779:  
4780:  
4781:  *** Test Cases ***
4782:  Deploy c9s linux lab
4783:      ${output} =    Run Clab Command    deploy -t ${topo}
4784: @@ -103,10 +108,47 @@ Inspect all is scoped by the namespace override
4785:  
4786:      ${other} =    Run Clab Command    --namespace default inspect --all --format json
4787:      Should Be Equal As Integers    ${other.rc}    0
4788:      Should Not Contain    ${other.stdout}    ${lab-name}
4789:  
4790: +Inspect reports the topology file the lab was deployed from
4791: +    # the deploy recorded this machine's file on the Topology; inspect without the file reports it
4792: +    ${annotation} =    Process.Run Process
4793: +    ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} -o jsonpath\='{.metadata.annotations.containerlab\\.dev/topo-file}'
4794: +    ...    shell=True
4795: +    Should Be Equal As Integers    ${annotation.rc}    0
4796: +    Should Be Equal    ${annotation.stdout}    ${topo}
4797: +
4798: +    ${output} =    Run Clab Command    inspect --all --format json
4799: +    Should Be Equal As Integers    ${output.rc}    0
4800: +    ${labs} =    Evaluate    json.loads($output.stdout)    modules=json
4801: +    FOR    ${node}    IN    @{labs}[${lab-name}]
4802: +        Should Be Equal    ${node}[absLabPath]    ${topo}
4803: +        Should Not Start With    ${node}[labPath]    k8s://
4804: +        Should Be Equal    ${node}[state]    running
4805: +        Should Be Equal    ${node}[status]    healthy
4806: +    END
4807: +
4808: +    # manifests are applied by other means; they do not carry this machine's path
4809: +    ${emit} =    Run Offline Clab Command    deploy -t ${topo} --emit-crs
4810: +    Should Be Equal As Integers    ${emit.rc}    0
4811: +    Should Not Contain    ${emit.stdout}    containerlab.dev/topo-file
4812: +
4813: +Events carry the attributes of Docker events
4814: +    ${events} =    Collect Events    --name ${lab-name} events --format json --initial-state
4815: +    FOR    ${node}    IN    client    server
4816: +        Container Event Should Carry Docker Attributes    ${events}    ${node}    running    running
4817: +        # the interfaces a Docker container of the node has: the lab link, eth0 and lo, named
4818: +        # as in the topology, the link up
4819: +        ${ifaces} =    Interface States    ${events}    ${node}
4820: +        Should Be Equal    ${{sorted($ifaces)}}    ${{["eth0", "eth1", "lo"]}}
4821: +        Should Be Equal    ${ifaces}[eth1]    up
4822: +        Should Be Equal    ${ifaces}[eth0]    up
4823: +        Should Be Equal    ${ifaces}[lo]    unknown
4824: +    END
4825: +    Should Not Contain    ${events}    "ifname":"c9s
4826: +
4827:  Validate and emit-crs work without a kubeconfig
4828:      ${validate} =    Run Offline Clab Command    validate -t ${topo}
4829:      Should Be Equal As Integers    ${validate.rc}    0
4830:      Should Contain    ${validate.stderr}    Topology is valid for lab runtime
4831:  
4832: @@ -141,17 +183,23 @@ Inspect interfaces lists the link interfaces with their state
4833:      Should Be Equal As Integers    ${output.rc}    0
4834:      ${containers} =    Evaluate    json.loads($output.stdout)    modules=json
4835:      Length Should Be    ${containers}    2
4836:      FOR    ${container}    IN    @{containers}
4837:          Should Match Regexp    ${container}[name]    ^${lab-name}-(client|server)$
4838: -        Length Should Be    ${container}[interfaces]    1
4839: -        ${iface} =    Set Variable    ${container}[interfaces][0]
4840: +        # what a Docker container of the node lists: eth0, the lab link and loopback
4841: +        ${names} =    Evaluate    [i["name"] for i in $container["interfaces"]]
4842: +        Should Be Equal    ${names}    ${{["eth0", "eth1", "lo"]}}
4843: +        ${iface} =    Set Variable    ${container}[interfaces][1]
4844:          Should Be Equal    ${iface}[name]    eth1
4845: +        Should Be Equal    ${iface}[alias]    ${EMPTY}
4846:          Should Be Equal    ${iface}[type]    veth
4847:          Should Be Equal    ${iface}[state]    up
4848:          Should Match Regexp    ${iface}[mac]    ^([0-9a-f]{2}:){5}[0-9a-f]{2}$
4849:          Should Be True    ${iface}[ifindex] > 0 and ${iface}[mtu] > 0
4850: +        ${lo} =    Set Variable    ${container}[interfaces][2]
4851: +        Should Be Equal    ${lo}[type]    device
4852: +        Should Be Equal    ${lo}[state]    unknown
4853:      END
4854:  
4855:      ${one} =    Run Clab Command    inspect interfaces --name ${lab-name} -n client -f json
4856:      Should Be Equal As Integers    ${one.rc}    0
4857:      ${only} =    Evaluate    [c["name"] for c in json.loads($one.stdout)]    modules=json
4858: @@ -338,10 +386,19 @@ Library attaches, port-forwards, streams logs and samples stats as an impersonat
4859:      Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/stats
4860:      Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/forbidden_identity
4861:      Should Not Contain    ${result.stdout}    SKIP
4862:  
4863:  Stop server and verify dataplane interruption
4864: +    # the events of the stop and the following start are checked as they happen
4865: +    Remove File If Exists    ${lifecycle-log}
4866: +    Start Process    ${CLAB_BIN} --runtime ${runtime} --name ${lab-name} events --format json
4867: +    ...    shell=True
4868: +    ...    alias=c9s_lifecycle
4869: +    ...    stdout=${lifecycle-log}
4870: +    ...    stderr=${lifecycle-err}
4871: +    Sleep    5s
4872: +
4873:      ${output} =    Run Clab Command    stop -t ${topo} --node server
4874:      Should Be Equal As Integers    ${output.rc}    0
4875:  
4876:      # stop is a run state patch on the Node; the controller removes the Pod
4877:      ${run_state} =    Node Field    server    {.spec.runState}
4878: @@ -351,14 +408,32 @@ Stop server and verify dataplane interruption
4879:      ${pods} =    Process.Run Process
4880:      ...    kubectl -n ${lab-namespace} get pods -l c9s.run/topologyNode\=server -o name
4881:      ...    shell=True
4882:      Should Be Empty    ${pods.stdout}
4883:      ${inspect} =    Run Clab Command    inspect -t ${topo} --format json
4884: -    Should Contain    ${inspect.stdout}    "state": "stopped"
4885: +    ${states} =    Evaluate
4886: +    ...    {n["name"]: (n["state"], n["status"]) for n in json.loads($inspect.stdout)["${lab-name}"]}
4887: +    ...    modules=json
4888: +    Should Be Equal    ${states}[${lab-name}-server]    ${{("exited", "Exited")}}
4889:  
4890:      Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Fail
4891:  
4892: +Stopping a node reports the events Docker reports for containerlab stop
4893: +    # Docker: kill, stop, die; the node's interfaces go with it, its peer loses carrier
4894: +    Wait Until Keyword Succeeds    30s    1s
4895: +    ...    Container Actions Should Include In Order    ${lifecycle-log}    server
4896: +    ...    kill    stop    die
4897: +    ${events} =    Get File    ${lifecycle-log}
4898: +    Container Event Should Carry Docker Attributes    ${events}    server    die    exited
4899: +    Wait Until Keyword Succeeds    30s    1s
4900: +    ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    delete
4901: +    Wait Until Keyword Succeeds    30s    1s
4902: +    ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update
4903: +    ...    lower-layer-down    down
4904: +    ${client} =    Container Actions    ${lifecycle-log}    client
4905: +    Should Not Contain    ${client}    die
4906: +
4907:  Apply while server is stopped keeps it stopped
4908:      ${output} =    Run Clab Command    deploy -t ${applied-topo}
4909:      Should Be Equal As Integers    ${output.rc}    0
4910:      # the wait settles on the stopped node instead of waiting for it
4911:      Should Contain    ${output.stderr}    C9s lab is ready apart from stopped nodes
4912: @@ -385,10 +460,33 @@ Start server by lab name and verify dataplane restore
4913:      Should Be Equal As Integers    ${mark.rc}    0
4914:      Should Contain    ${mark_output}    applied-while-stopped
4915:  
4916:      Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed
4917:  
4918: +Starting a node reports the events Docker reports for containerlab start
4919: +    TRY
4920: +        # Docker: start; the device's readiness as a container health check
4921: +        Wait Until Keyword Succeeds    60s    1s
4922: +        ...    Container Actions Should Include In Order    ${lifecycle-log}    server
4923: +        ...    kill    stop    die    start    health_status: healthy
4924: +        ${events} =    Get File    ${lifecycle-log}
4925: +        # the lab was last deployed from the applied file, which the Topology now records
4926: +        Container Event Should Carry Docker Attributes
4927: +        ...    ${events}    server    start    running    ${applied-topo}
4928: +        Container Event Should Carry Docker Attributes
4929: +        ...    ${events}    server    health_status: healthy    running    ${applied-topo}
4930: +        Wait Until Keyword Succeeds    60s    1s
4931: +        ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    create
4932: +        Wait Until Keyword Succeeds    60s    1s
4933: +        ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update    up
4934: +        Validate JSON Lines    ${lifecycle-log}
4935: +    FINALLY
4936: +        Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True
4937: +        Remove File If Exists    ${lifecycle-log}
4938: +        Remove File If Exists    ${lifecycle-err}
4939: +    END
4940: +
4941:  Restart server and keep dataplane working
4942:      ${before} =    Server Pod Name
4943:      ${output} =    Run Clab Command    restart -t ${topo} --node server
4944:      Should Be Equal As Integers    ${output.rc}    0
4945:  
4946: @@ -445,26 +543,36 @@ Events report interface up and down
4947:          ...    stdout=${iface-events-log}
4948:          ...    stderr=${iface-events-err}
4949:          Sleep    5s
4950:          Set Client Eth1    down
4951:          Wait Until Keyword Succeeds    30s    1s
4952: -        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    down
4953: +        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    down
4954:          # the peer loses carrier
4955:          Wait Until Keyword Succeeds    30s    1s
4956: -        ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    down
4957: +        ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    update
4958: +        ...    lower-layer-down    down
4959:          Set Client Eth1    up
4960:          Wait Until Keyword Succeeds    30s    1s
4961: -        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    up
4962: +        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    up
4963:          Validate JSON Lines    ${iface-events-log}
4964:      FINALLY
4965:          Stop Events Process
4966:          Set Client Eth1    up
4967:          Remove File If Exists    ${iface-events-log}
4968:          Remove File If Exists    ${iface-events-err}
4969:      END
4970:  
4971:  Destroy without cleanup keeps the persistent claims
4972: +    # the events of the destroy and the following deploy are checked after the deploy
4973: +    Remove File If Exists    ${redeploy-log}
4974: +    Start Process    ${CLAB_BIN} --runtime ${runtime} --namespace ${lab-namespace} events --format json
4975: +    ...    shell=True
4976: +    ...    alias=c9s_redeploy
4977: +    ...    stdout=${redeploy-log}
4978: +    ...    stderr=${redeploy-err}
4979: +    Sleep    5s
4980: +
4981:      ${before} =    Persistent Claim Volumes
4982:      Should Not Be Empty    ${before}
4983:  
4984:      ${output} =    Run Clab Command    destroy -t ${topo}
4985:      Should Be Equal As Integers    ${output.rc}    0
4986: @@ -479,10 +587,36 @@ Deploy reuses the retained persistent claims
4987:      Should Be Equal As Integers    ${output.rc}    0
4988:  
4989:      ${volumes} =    Persistent Claim Volumes
4990:      Should Be Equal    ${volumes}    ${retained-volumes}
4991:  
4992: +Destroy and deploy report the events Docker reports
4993: +    TRY
4994: +        FOR    ${node}    IN    client    server
4995: +            # Docker: kill, die, destroy; then create, start (and the health check)
4996: +            Wait Until Keyword Succeeds    60s    1s
4997: +            ...    Container Actions Should Include In Order    ${redeploy-log}    ${node}
4998: +            ...    kill    die    destroy    create    start    health_status: healthy
4999: +            ${events} =    Get File    ${redeploy-log}
5000: +            # the destroyed lab was last deployed from the applied file, the new one from ${topo}
5001: +            Container Event Should Carry Docker Attributes
5002: +            ...    ${events}    ${node}    destroy    exited    ${applied-topo}
5003: +            Container Event Should Carry Docker Attributes    ${events}    ${node}    create    created
5004: +            Container Event Should Carry Docker Attributes    ${events}    ${node}    start    running
5005: +            # like Docker, the link may be created down and come up after
5006: +            Wait Until Keyword Succeeds    60s    1s
5007: +            ...    Interface Event Should Be Logged    ${redeploy-log}    ${node}    eth1    create
5008: +            Wait Until Keyword Succeeds    60s    1s
5009: +            ...    Last Interface State Should Be    ${redeploy-log}    ${node}    eth1    up
5010: +        END
5011: +        Validate JSON Lines    ${redeploy-log}
5012: +    FINALLY
5013: +        Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True
5014: +        Remove File If Exists    ${redeploy-log}
5015: +        Remove File If Exists    ${redeploy-err}
5016: +    END
5017: +
5018:  Destroy c9s linux lab
5019:      ${output} =    Run Clab Command    destroy -t ${topo} --cleanup
5020:      Should Be Equal As Integers    ${output.rc}    0
5021:  
5022:      ${inspect_all} =    Run Clab Command    inspect --all
5023: @@ -509,10 +643,18 @@ Deploy c9s linux lab without a Topology resource
5024:      ...    shell=True
5025:      Should Be Equal As Integers    ${nodes.rc}    0
5026:      Should Contain    ${nodes.stdout}    node.c9s.run/client
5027:      Should Contain    ${nodes.stdout}    node.c9s.run/server
5028:  
5029: +    # without a Topology the Nodes record the file; inspect without the file reports it
5030: +    ${annotation} =    Node Field    client    {.metadata.annotations.containerlab\\.dev/topo-file}
5031: +    Should Be Equal    ${annotation}    ${topo}
5032: +    ${output} =    Run Clab Command    inspect --name ${lab-name} --format json
5033: +    ${paths} =    Evaluate    {n["absLabPath"] for n in json.loads($output.stdout)["${lab-name}"]}
5034: +    ...    modules=json
5035: +    Should Be Equal    ${paths}    ${{{"${topo}"}}}
5036: +
5037:  Apply without a Topology resource keeps a stopped node stopped
5038:      ${output} =    Run Clab Command    stop -t ${topo} --node client
5039:      Should Be Equal As Integers    ${output.rc}    0
5040:  
5041:      ${plan} =    Run Clab Command    deploy -t ${applied-topo} --no-topology-cr --dry-run --format json
5042: @@ -549,10 +691,12 @@ Setup
5043:      ${output} =    Run Clab Command    destroy -t ${topo} --cleanup
5044:      Log    Cleanup return code: ${output.rc}
5045:  
5046:  Teardown
5047:      Stop Events Process
5048: +    Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True
5049: +    Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True
5050:      Run Clab Command    destroy -t ${topo} --cleanup
5051:      Remove File If Exists    ${events-log}
5052:      Remove File If Exists    ${events-err}
5053:  
5054:  Run Clab Command
5055: @@ -639,17 +783,80 @@ Collect Events
5056:  Set Client Eth1
5057:      [Arguments]    ${state}
5058:      Run Clab Command    exec -t ${topo} --label ${client-label} --cmd 'ip link set dev eth1 ${state}'
5059:  
5060:  Interface Event Should Be Logged
5061: -    [Arguments]    ${path}    ${node}    ${ifname}    ${action}
5062: +    [Documentation]    An interface event with the action and, when given, one of the states.
5063: +    [Arguments]    ${path}    ${node}    ${ifname}    ${action}    @{states}
5064:      ${contents} =    Get File    ${path}
5065:      ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}
5066:      ${found} =    Evaluate
5067: -    ...    ($action, $actor, $ifname) in [(e.get("action"), e.get("actor_id"), e.get("attributes", {}).get("ifname")) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get("type") == "interface"]
5068: +    ...    any([e.get("action") == $action and e.get("actor_id") == $actor and e.get("attributes", {}).get("ifname") == $ifname and (not $states or e.get("attributes", {}).get("state") in $states) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get("type") == "interface"])
5069: +    ...    modules=json
5070: +    Should Be True    ${found}    no interface ${action} event ${states} for ${node}:${ifname}
5071: +
5072: +Last Interface State Should Be
5073: +    [Arguments]    ${path}    ${node}    ${ifname}    ${state}
5074: +    ${contents} =    Get File    ${path}
5075: +    ${states} =    Interface States    ${contents}    ${node}
5076: +    Should Be Equal    ${states}[${ifname}]    ${state}
5077: +
5078: +Container Actions
5079: +    [Arguments]    ${path}    ${node}
5080: +    ${contents} =    Get File    ${path}
5081: +    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}
5082: +    ${actions} =    Evaluate
5083: +    ...    [e["action"] for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get("type") == "container" and e.get("actor_id") == $actor]
5084: +    ...    modules=json
5085: +    RETURN    ${actions}
5086: +
5087: +Container Actions Should Include In Order
5088: +    [Arguments]    ${path}    ${node}    @{expected}
5089: +    ${actions} =    Container Actions    ${path}    ${node}
5090: +    # the expected actions appear in this order, other actions may come between them
5091: +    ${in_order} =    Evaluate
5092: +    ...    re.search("\\n" + "\\n(?:.*\\n)*?".join([re.escape(a) for a in $expected]) + "\\n", "\\n" + "\\n".join($actions) + "\\n") is not None
5093: +    ...    modules=re
5094: +    Should Be True    ${in_order}    ${node} reported ${actions}, not ${expected} in this order
5095: +
5096: +Container Event Should Carry Docker Attributes
5097: +    [Documentation]    The last container event of a node with the action carries the attributes
5098: +    ...    a Docker container event of the node has, and the container state.
5099: +    [Arguments]    ${events}    ${node}    ${action}    ${state}    ${topo-file}=${topo}
5100: +    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}
5101: +    ${matching} =    Evaluate
5102: +    ...    [e for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get("type") == "container" and e.get("actor_id") == $actor and e.get("action") == $action]
5103: +    ...    modules=json
5104: +    Should Not Be Empty    ${matching}    no container ${action} event for ${node}
5105: +    ${event} =    Set Variable    ${matching}[-1]
5106: +    ${attributes} =    Set Variable    ${event}[attributes]
5107: +    Log    ${attributes}
5108: +    Should Be Equal    ${attributes}[containerlab]    ${lab-name}
5109: +    Should Be Equal    ${attributes}[clab-node-name]    ${node}
5110: +    Should Be Equal    ${attributes}[clab-node-longname]    ${lab-name}-${node}
5111: +    Should Be Equal    ${attributes}[clab-node-kind]    linux
5112: +    Should Be Equal    ${attributes}[clab-topo-file]    ${topo-file}
5113: +    Should Not Be Empty    ${attributes}[clab-owner]
5114: +    Should Be Equal    ${attributes}[image]    ${node-image}
5115: +    Should Be Equal    ${attributes}[name]    ${lab-name}-${node}
5116: +    Should Be Equal    ${attributes}[id]    ${actor}
5117: +    Should Be Equal    ${event}[actor_full_id]    ${actor}
5118: +    # a node is created before the controller allocates its management address and Service
5119: +    IF    $state != "created"
5120: +        Should Match Regexp    ${attributes}[mgmt_ipv4]    ^\\d+\\.\\d+\\.\\d+\\.\\d+/\\d+$
5121: +        Should Contain    ${attributes}[ports]    22/tcp
5122: +    END
5123: +    Should Be Equal    ${attributes}[state]    ${state}
5124: +
5125: +Interface States
5126: +    [Documentation]    The interfaces the events report for a node, with their last state.
5127: +    [Arguments]    ${events}    ${node}
5128: +    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}
5129: +    ${states} =    Evaluate
5130: +    ...    {e["attributes"]["ifname"]: e["attributes"].get("state", "") for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get("type") == "interface" and e.get("actor_id") == $actor}
5131:      ...    modules=json
5132: -    Should Be True    ${found}    no interface ${action} event for ${node}:${ifname}
5133: +    RETURN    ${states}
5134:  
5135:  Log File Should Contain
5136:      [Arguments]    ${path}    ${text}
5137:      ${contents} =    Get File    ${path}
5138:      Should Contain    ${contents}    ${text}

(End of file - total 5138 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1967774c30014H2zajD6csxixu",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196775955001eS3UIf8cY8YWd1",
  "callID": "call_3b769ce17b2e460a8b3407a1",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 1300,
      "offset": 4396
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n4396:  func nodeStateFromResource(nodeResource *unstructured.Unstructured) clablabruntime.NodeState {\n4397:  \tnode := clablabruntime.NodeState{\n4398:  \t\tName:    nodeResource.GetName(),\n4399:  \t\tNodeUID: string(nodeResource.GetUID()),\n4400:  \t}\n4401: +\tif original := nodeResource.GetLabels()[labelOriginalNodeName]; original != node.Name {\n4402: +\t\tnode.TopologyName = original\n4403: +\t}\n4404:  \tnode.ExposedPorts = nodeExposedPorts(nodeResource)\n4405:  \t// The same container exec targets: the observed primary device container.\n4406:  \tnode.Container, _ = preferredDeviceContainerName(nodeResource, node.Name)\n4407:  \tnode.Kind, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"kind\")\n4408:  \tnode.Image, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"image\")\n4409: +\tnode.Type, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"type\")\n4410: +\tnode.Group, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"group\")\n4411:  \tnode.State, _, _ = unstructured.NestedString(nodeResource.Object, \"status\", \"readiness\")\n4412:  \tnode.Ready = node.State == \"ready\"\n4413:  \tnode.LoadBalancerAddress, _, _ = unstructured.NestedString(\n4414:  \t\tnodeResource.Object,\n4415:  \t\t\"status\",\n4416: @@ -132,17 +144,28 @@ func intField(value any) int {\n4417:  \tdefault:\n4418:  \t\treturn 0\n4419:  \t}\n4420:  }\n4421:  \n4422: -// newestPod prefers a running pod and, among equals, the newest one: several pods can match a\n4423: -// node during a rolling update.\n4424: +// newestPod prefers a pod that is not being deleted, then a running pod and, among equals, the\n4425: +// newest one: several pods can match a node during a rolling update or a restart, when the old\n4426: +// pod terminates while its replacement starts.\n4427:  func newestPod(current, candidate *corev1.Pod) *corev1.Pod {\n4428:  \tif current == nil {\n4429:  \t\treturn candidate\n4430:  \t}\n4431:  \n4432: +\tcurrentDeleting := current.DeletionTimestamp != nil\n4433: +\tcandidateDeleting := candidate.DeletionTimestamp != nil\n4434: +\tif currentDeleting != candidateDeleting {\n4435: +\t\tif candidateDeleting {\n4436: +\t\t\treturn current\n4437: +\t\t}\n4438: +\n4439: +\t\treturn candidate\n4440: +\t}\n4441: +\n4442:  \tcurrentRunning := current.Status.Phase == corev1.PodRunning\n4443:  \tcandidateRunning := candidate.Status.Phase == corev1.PodRunning\n4444:  \tif currentRunning != candidateRunning {\n4445:  \t\tif candidateRunning {\n4446:  \t\t\treturn candidate\n4447: @@ -197,20 +220,30 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat\n4448:  \tfor idx := range pods.Items {\n4449:  \t\tnodeName := pods.Items[idx].Labels[labelTopologyNode]\n4450:  \t\tif nodeName == \"\" {\n4451:  \t\t\tcontinue\n4452:  \t\t}\n4453: +\t\t// A pod of an earlier Node of the same name (a redeploy while the old pod still\n4454: +\t\t// terminates) is not this node's pod.\n4455: +\t\tif uid := pods.Items[idx].Annotations[annotationDirectNodeUID]; uid != \"\" {\n4456: +\t\t\tif resource := resourcesByName[nodeName]; resource != nil &&\n4457: +\t\t\t\tstring(resource.GetUID()) != uid {\n4458: +\t\t\t\tcontinue\n4459: +\t\t\t}\n4460: +\t\t}\n4461:  \t\tpodsByNode[nodeName] = newestPod(podsByNode[nodeName], &pods.Items[idx])\n4462:  \t}\n4463:  \n4464:  \t// The Node's status.readiness is the authoritative device signal. The primary Node's run\n4465:  \t// state governs the pod a group of nodes shares: a stopped primary stops the whole group.\n4466:  \t// Nodes without readiness yet report their pod phase.\n4467:  \tfor nodeName, node := range nodesByName {\n4468:  \t\tprimary := resolvePrimaryNode(nodeName, networkModes)\n4469: -\t\tif primaryResource := resourcesByName[primary]; primaryResource != nil &&\n4470: -\t\t\tnodeRunState(primaryResource) == nodeRunStateStopped {\n4471: +\t\tprimaryResource := resourcesByName[primary]\n4472: +\t\tstopRequested := primaryResource != nil &&\n4473: +\t\t\tnodeRunState(primaryResource) == nodeRunStateStopped\n4474: +\t\tif stopRequested {\n4475:  \t\t\tnode.State = \"stopping\"\n4476:  \t\t\tif condition := nodeCondition(\n4477:  \t\t\t\tprimaryResource,\n4478:  \t\t\t\tnodeConditionStopped,\n4479:  \t\t\t); condition != nil &&\n4480: @@ -220,10 +253,14 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat\n4481:  \t\t\tnode.Ready = false\n4482:  \t\t} else if pod := podsByNode[primary]; node.State == \"\" && pod != nil &&\n4483:  \t\t\tpod.Status.Phase != \"\" {\n4484:  \t\t\tnode.State = strings.ToLower(string(pod.Status.Phase))\n4485:  \t\t}\n4486: +\t\tnode.ContainerState = nodeContainerState(stopRequested, podsByNode[primary])\n4487: +\t\tif node.ContainerState == clablabruntime.ContainerStateRunning {\n4488: +\t\t\tnode.Health = nodeHealth(node, resourcesByName[nodeName])\n4489: +\t\t}\n4490:  \t\tnodesByName[nodeName] = node\n4491:  \t}\n4492:  \n4493:  \t// Nodes grouped through network-mode container: share the pod of the group's primary\n4494:  \t// node. Before the controller observed the device containers, the pod's default-container\n4495: @@ -270,5 +307,46 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat\n4496:  \t\tstate.Ready = false\n4497:  \t}\n4498:  \n4499:  \treturn nil\n4500:  }\n4501: +\n4502: +// nodeContainerState is the state of a node in container runtime terms, from its pod: created\n4503: +// while the pod is scheduled and prepared (init containers), running once the device containers\n4504: +// run, and exited once the node was stopped, its pod is being deleted, or the pod ended. Between\n4505: +// the pods of a restart the node is exited, then created.\n4506: +func nodeContainerState(stopRequested bool, pod *corev1.Pod) string {\n4507: +\tswitch {\n4508: +\tcase pod == nil && stopRequested:\n4509: +\t\treturn clablabruntime.ContainerStateExited\n4510: +\tcase pod == nil:\n4511: +\t\treturn clablabruntime.ContainerStateCreated\n4512: +\tcase stopRequested || pod.DeletionTimestamp != nil:\n4513: +\t\treturn clablabruntime.ContainerStateExited\n4514: +\t}\n4515: +\n4516: +\tswitch pod.Status.Phase {\n4517: +\tcase corev1.PodRunning:\n4518: +\t\treturn clablabruntime.ContainerStateRunning\n4519: +\tcase corev1.PodSucceeded, corev1.PodFailed:\n4520: +\t\treturn clablabruntime.ContainerStateExited\n4521: +\tdefault:\n4522: +\t\treturn clablabruntime.ContainerStateCreated\n4523: +\t}\n4524: +}\n4525: +\n4526: +// nodeHealth is the health of a running node: healthy once the Node is ready or its device\n4527: +// containers are, starting before. Device containers are the analogue of a container\n4528: +// healthcheck: a node whose links wait for a stopped peer is not ready, but its device is.\n4529: +func nodeHealth(node clablabruntime.NodeState, resource *unstructured.Unstructured) string {\n4530: +\tif node.Ready {\n4531: +\t\treturn clablabruntime.ContainerHealthHealthy\n4532: +\t}\n4533: +\tif resource != nil {\n4534: +\t\tif condition := nodeCondition(resource, nodeConditionContainersReady); condition != nil &&\n4535: +\t\t\tcondition.status == string(metav1.ConditionTrue) {\n4536: +\t\t\treturn clablabruntime.ContainerHealthHealthy\n4537: +\t\t}\n4538: +\t}\n4539: +\n4540: +\treturn clablabruntime.ContainerHealthStarting\n4541: +}\n4542: diff --git a/labruntime/clabernetes/topology.go b/labruntime/clabernetes/topology.go\n4543: index e401ecf..db3715a 100644\n4544: --- a/labruntime/clabernetes/topology.go\n4545: +++ b/labruntime/clabernetes/topology.go\n4546: @@ -12,10 +12,56 @@ import (\n4547:  \t\"k8s.io/apimachinery/pkg/util/validation\"\n4548:  )\n4549:  \n4550:  type topologyObjectOption func(map[string]any)\n4551:  \n4552: +// annotationTopologyFile records the absolute path of the topology file a lab was deployed from,\n4553: +// on the machine that deployed it. Inspect reports it as the lab's topology path and events as\n4554: +// clab-topo-file, as the local runtimes do, so clients match the running lab to its file. A lab\n4555: +// created by other means than a containerlab deploy has no annotation and reports where its\n4556: +// definition lives in the cluster (k8s://<namespace>/topologies/<lab>).\n4557: +const annotationTopologyFile = \"containerlab.dev/topo-file\"\n4558: +\n4559: +// setTopologySourceFile records the topology file a deploy reads on the Topology. An empty path\n4560: +// (a definition that came from no file) records nothing.\n4561: +func setTopologySourceFile(topology *unstructured.Unstructured, path string) {\n4562: +\tif path == \"\" {\n4563: +\t\treturn\n4564: +\t}\n4565: +\n4566: +\tannotations := topology.GetAnnotations()\n4567: +\tif annotations == nil {\n4568: +\t\tannotations = map[string]string{}\n4569: +\t}\n4570: +\tannotations[annotationTopologyFile] = path\n4571: +\ttopology.SetAnnotations(annotations)\n4572: +}\n4573: +\n4574: +// removeTopologySourceFile drops the deploying machine's file path from an object.\n4575: +func removeTopologySourceFile(obj *unstructured.Unstructured) {\n4576: +\tannotations := obj.GetAnnotations()\n4577: +\tif _, ok := annotations[annotationTopologyFile]; !ok {\n4578: +\t\treturn\n4579: +\t}\n4580: +\n4581: +\tdelete(annotations, annotationTopologyFile)\n4582: +\tif len(annotations) == 0 {\n4583: +\t\tannotations = nil\n4584: +\t}\n4585: +\tobj.SetAnnotations(annotations)\n4586: +}\n4587: +\n4588: +// labTopologyPath is the topology path a lab reports: the file it was deployed from when the\n4589: +// deploy recorded one, otherwise the place given.\n4590: +func labTopologyPath(annotations map[string]string, fallback string) string {\n4591: +\tif path := annotations[annotationTopologyFile]; path != \"\" {\n4592: +\t\treturn path\n4593: +\t}\n4594: +\n4595: +\treturn fallback\n4596: +}\n4597: +\n4598:  func topologyWithNaming(naming string) topologyObjectOption {\n4599:  \treturn func(spec map[string]any) {\n4600:  \t\tif naming != \"\" {\n4601:  \t\t\tspec[\"naming\"] = naming\n4602:  \t\t}\n4603: @@ -137,10 +183,14 @@ func stateFromTopology(obj *unstructured.Unstructured, namespace string) *clabla\n4604:  \towner := obj.GetLabels()[clabconstants.Owner]\n4605:  \tif owner == \"\" {\n4606:  \t\towner = obj.GetAnnotations()[clabconstants.Owner]\n4607:  \t}\n4608:  \tnodeSpecs := nodeSpecsFromTopology(obj)\n4609: +\ttopologyPath := labTopologyPath(\n4610: +\t\tobj.GetAnnotations(),\n4611: +\t\tfmt.Sprintf(\"k8s://%s/topologies/%s\", namespace, obj.GetName()),\n4612: +\t)\n4613:  \n4614:  \tnodeNames := make([]string, 0, len(nodeSpecs))\n4615:  \tfor nodeName := range nodeSpecs {\n4616:  \t\tnodeNames = append(nodeNames, nodeName)\n4617:  \t}\n4618: @@ -158,11 +208,11 @@ func stateFromTopology(obj *unstructured.Unstructured, namespace string) *clabla\n4619:  \n4620:  \treturn &clablabruntime.LabState{\n4621:  \t\tName:         obj.GetName(),\n4622:  \t\tNamespace:    namespace,\n4623:  \t\tOwner:        owner,\n4624: -\t\tTopologyPath: fmt.Sprintf(\"k8s://%s/topologies/%s\", namespace, obj.GetName()),\n4625: +\t\tTopologyPath: topologyPath,\n4626:  \t\tState:        state,\n4627:  \t\tReady:        ready,\n4628:  \t\tNodes:        nodes,\n4629:  \t}\n4630:  }\n4631: diff --git a/labruntime/runtime.go b/labruntime/runtime.go\n4632: index 367565d..0f2433a 100644\n4633: --- a/labruntime/runtime.go\n4634: +++ b/labruntime/runtime.go\n4635: @@ -191,16 +191,42 @@ type SavedFile struct {\n4636:  \n4637:  type SaveResult struct {\n4638:  \tFiles []SavedFile\n4639:  }\n4640:  \n4641: +// Container states and health in the vocabulary of container runtimes (Docker), which inspect\n4642: +// and events report for lab runtime nodes too.\n4643: +const (\n4644: +\tContainerStateCreated = \"created\"\n4645: +\tContainerStateRunning = \"running\"\n4646: +\tContainerStateExited  = \"exited\"\n4647: +\n4648: +\tContainerHealthHealthy   = \"healthy\"\n4649: +\tContainerHealthStarting  = \"starting\"\n4650: +\tContainerHealthUnhealthy = \"unhealthy\"\n4651: +)\n4652: +\n4653:  type NodeState struct {\n4654: -\tName  string\n4655: -\tKind  string\n4656: -\tImage string\n4657: +\tName string\n4658: +\t// TopologyName is the node name as the topology file spells it, when the runtime had to\n4659: +\t// carry the node under another name (Name). Empty means Name.\n4660: +\tTopologyName string\n4661: +\tKind         string\n4662: +\tImage        string\n4663: +\t// Type and Group are the node's type and group when the topology set them.\n4664: +\tType  string\n4665: +\tGroup string\n4666: +\t// State is the runtime's own view of the node, such as the clabernetes Node readiness, or\n4667: +\t// stopped.\n4668:  \tState string\n4669:  \tReady bool\n4670: +\t// ContainerState is the node's state in container runtime terms: created, running or\n4671: +\t// exited (the ContainerState* constants). Empty when the runtime does not report one.\n4672: +\tContainerState string\n4673: +\t// Health is the device health of a running node in container runtime terms: healthy or\n4674: +\t// starting. Empty when the node does not run.\n4675: +\tHealth string\n4676:  \t// MgmtIPv4Address and MgmtIPv6Address are the node's allocated management addresses in\n4677:  \t// CIDR notation, when the runtime reports them.\n4678:  \tMgmtIPv4Address     string\n4679:  \tMgmtIPv6Address     string\n4680:  \tLoadBalancerAddress string\n4681: @@ -216,13 +242,16 @@ type NodeState struct {\n4682:  \n4683:  // ExposedPort is a node port a lab runtime publishes through a Service.\n4684:  type ExposedPort = clabtypes.ExposedPort\n4685:  \n4686:  type LabState struct {\n4687: -\tName         string\n4688: -\tNamespace    string\n4689: -\tOwner        string\n4690: +\tName      string\n4691: +\tNamespace string\n4692: +\tOwner     string\n4693: +\t// TopologyPath is the absolute path of the topology file the lab was deployed from, on the\n4694: +\t// machine that deployed it. A lab the runtime did not deploy from a file reports where the\n4695: +\t// runtime keeps its definition instead (for c9s k8s://<namespace>/topologies/<lab>).\n4696:  \tTopologyPath string\n4697:  \tState        string\n4698:  \tReady        bool\n4699:  \tNodes        []NodeState\n4700:  }\n4701: @@ -258,11 +287,61 @@ type Event struct {\n4702:  \tType        string\n4703:  \tAction      string\n4704:  \tActorID     string\n4705:  \tActorName   string\n4706:  \tActorFullID string\n4707: -\tAttributes  map[string]string\n4708: +\t// Attributes are the runtime's own attributes. Event consumers add the attributes the\n4709: +\t// container runtimes report from Lab, Node and Interface.\n4710: +\tAttributes map[string]string\n4711: +\t// Lab and Node are the lab node a container or interface event is about, as Inspect\n4712: +\t// reports it. containerlab's events command describes the node from them the same way\n4713: +\t// inspect does, so both agree and match what the container runtimes report.\n4714: +\tLab  *LabState\n4715: +\tNode *NodeState\n4716: +\t// Interface is the interface an interface event reports.\n4717: +\tInterface *InterfaceEventData\n4718: +}\n4719: +\n4720: +// Event types and the origin attribute of lab runtime events.\n4721: +const (\n4722: +\tEventTypeContainer = \"container\"\n4723: +\tEventTypeInterface = \"interface\"\n4724: +\t// EventOriginSnapshot marks the events of --initial-state, in the origin attribute.\n4725: +\tEventOriginSnapshot = \"snapshot\"\n4726: +)\n4727: +\n4728: +// InterfaceEventData describes an interface of a node the way the container runtimes' interface\n4729: +// events do (netlink).\n4730: +type InterfaceEventData struct {\n4731: +\t// Name is the interface name inside the node.\n4732: +\tName string\n4733: +\t// Alias is the name the topology gave the interface when the node kind maps it (for\n4734: +\t// example ethernet-1/1 for SR Linux e1-1).\n4735: +\tAlias string\n4736: +\tIndex int\n4737: +\tMTU   int\n4738: +\tMAC   string\n4739: +\t// OperState is the operational state in netlink's vocabulary: up, down, lower-layer-down,\n4740: +\t// dormant, testing, not-present or unknown.\n4741: +\tOperState string\n4742: +\t// Type is the link type in netlink's vocabulary, such as veth or device (loopback).\n4743: +\tType string\n4744: +\t// Stats are set on stats events.\n4745: +\tStats *InterfaceStats\n4746: +}\n4747: +\n4748: +// InterfaceStats are the counters and rates of an interface stats event.\n4749: +type InterfaceStats struct {\n4750: +\tRxBytes   uint64\n4751: +\tTxBytes   uint64\n4752: +\tRxPackets uint64\n4753: +\tTxPackets uint64\n4754: +\tRxBps     float64\n4755: +\tTxBps     float64\n4756: +\tRxPps     float64\n4757: +\tTxPps     float64\n4758: +\tInterval  time.Duration\n4759:  }\n4760:  \n4761:  // NodeLocation is the workload that runs a lab node.\n4762:  type NodeLocation struct {\n4763:  \t// NodeName is the node name the runtime carries (the sanitized name).\n4764: diff --git a/tests/14-clabernetes/01-linux-lifecycle.robot b/tests/14-clabernetes/01-linux-lifecycle.robot\n4765: index f45a3ff..bc27828 100644\n4766: --- a/tests/14-clabernetes/01-linux-lifecycle.robot\n4767: +++ b/tests/14-clabernetes/01-linux-lifecycle.robot\n4768: @@ -27,10 +27,15 @@ ${recovery-timeout}     180s\n4769:  ${retry-interval}       5s\n4770:  ${capture-file}         /tmp/clab-c9s-capture.pcapng\n4771:  ${chain-file}           /tmp/clab-c9s-capture-chain.pcapng\n4772:  ${stop-file}            /tmp/clab-c9s-capture-stop.pcapng\n4773:  ${stop-err}             /tmp/clab-c9s-capture-stop.err\n4774: +${lifecycle-log}        /tmp/clab-c9s-lifecycle-events.log\n4775: +${lifecycle-err}        /tmp/clab-c9s-lifecycle-events.err\n4776: +${redeploy-log}         /tmp/clab-c9s-redeploy-events.log\n4777: +${redeploy-err}         /tmp/clab-c9s-redeploy-events.err\n4778: +${node-image}           ghcr.io/srl-labs/network-multitool\n4779:  \n4780:  \n4781:  *** Test Cases ***\n4782:  Deploy c9s linux lab\n4783:      ${output} =    Run Clab Command    deploy -t ${topo}\n4784: @@ -103,10 +108,47 @@ Inspect all is scoped by the namespace override\n4785:  \n4786:      ${other} =    Run Clab Command    --namespace default inspect --all --format json\n4787:      Should Be Equal As Integers    ${other.rc}    0\n4788:      Should Not Contain    ${other.stdout}    ${lab-name}\n4789:  \n4790: +Inspect reports the topology file the lab was deployed from\n4791: +    # the deploy recorded this machine's file on the Topology; inspect without the file reports it\n4792: +    ${annotation} =    Process.Run Process\n4793: +    ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} -o jsonpath\\='{.metadata.annotations.containerlab\\\\.dev/topo-file}'\n4794: +    ...    shell=True\n4795: +    Should Be Equal As Integers    ${annotation.rc}    0\n4796: +    Should Be Equal    ${annotation.stdout}    ${topo}\n4797: +\n4798: +    ${output} =    Run Clab Command    inspect --all --format json\n4799: +    Should Be Equal As Integers    ${output.rc}    0\n4800: +    ${labs} =    Evaluate    json.loads($output.stdout)    modules=json\n4801: +    FOR    ${node}    IN    @{labs}[${lab-name}]\n4802: +        Should Be Equal    ${node}[absLabPath]    ${topo}\n4803: +        Should Not Start With    ${node}[labPath]    k8s://\n4804: +        Should Be Equal    ${node}[state]    running\n4805: +        Should Be Equal    ${node}[status]    healthy\n4806: +    END\n4807: +\n4808: +    # manifests are applied by other means; they do not carry this machine's path\n4809: +    ${emit} =    Run Offline Clab Command    deploy -t ${topo} --emit-crs\n4810: +    Should Be Equal As Integers    ${emit.rc}    0\n4811: +    Should Not Contain    ${emit.stdout}    containerlab.dev/topo-file\n4812: +\n4813: +Events carry the attributes of Docker events\n4814: +    ${events} =    Collect Events    --name ${lab-name} events --format json --initial-state\n4815: +    FOR    ${node}    IN    client    server\n4816: +        Container Event Should Carry Docker Attributes    ${events}    ${node}    running    running\n4817: +        # the interfaces a Docker container of the node has: the lab link, eth0 and lo, named\n4818: +        # as in the topology, the link up\n4819: +        ${ifaces} =    Interface States    ${events}    ${node}\n4820: +        Should Be Equal    ${{sorted($ifaces)}}    ${{[\"eth0\", \"eth1\", \"lo\"]}}\n4821: +        Should Be Equal    ${ifaces}[eth1]    up\n4822: +        Should Be Equal    ${ifaces}[eth0]    up\n4823: +        Should Be Equal    ${ifaces}[lo]    unknown\n4824: +    END\n4825: +    Should Not Contain    ${events}    \"ifname\":\"c9s\n4826: +\n4827:  Validate and emit-crs work without a kubeconfig\n4828:      ${validate} =    Run Offline Clab Command    validate -t ${topo}\n4829:      Should Be Equal As Integers    ${validate.rc}    0\n4830:      Should Contain    ${validate.stderr}    Topology is valid for lab runtime\n4831:  \n4832: @@ -141,17 +183,23 @@ Inspect interfaces lists the link interfaces with their state\n4833:      Should Be Equal As Integers    ${output.rc}    0\n4834:      ${containers} =    Evaluate    json.loads($output.stdout)    modules=json\n4835:      Length Should Be    ${containers}    2\n4836:      FOR    ${container}    IN    @{containers}\n4837:          Should Match Regexp    ${container}[name]    ^${lab-name}-(client|server)$\n4838: -        Length Should Be    ${container}[interfaces]    1\n4839: -        ${iface} =    Set Variable    ${container}[interfaces][0]\n4840: +        # what a Docker container of the node lists: eth0, the lab link and loopback\n4841: +        ${names} =    Evaluate    [i[\"name\"] for i in $container[\"interfaces\"]]\n4842: +        Should Be Equal    ${names}    ${{[\"eth0\", \"eth1\", \"lo\"]}}\n4843: +        ${iface} =    Set Variable    ${container}[interfaces][1]\n4844:          Should Be Equal    ${iface}[name]    eth1\n4845: +        Should Be Equal    ${iface}[alias]    ${EMPTY}\n4846:          Should Be Equal    ${iface}[type]    veth\n4847:          Should Be Equal    ${iface}[state]    up\n4848:          Should Match Regexp    ${iface}[mac]    ^([0-9a-f]{2}:){5}[0-9a-f]{2}$\n4849:          Should Be True    ${iface}[ifindex] > 0 and ${iface}[mtu] > 0\n4850: +        ${lo} =    Set Variable    ${container}[interfaces][2]\n4851: +        Should Be Equal    ${lo}[type]    device\n4852: +        Should Be Equal    ${lo}[state]    unknown\n4853:      END\n4854:  \n4855:      ${one} =    Run Clab Command    inspect interfaces --name ${lab-name} -n client -f json\n4856:      Should Be Equal As Integers    ${one.rc}    0\n4857:      ${only} =    Evaluate    [c[\"name\"] for c in json.loads($one.stdout)]    modules=json\n4858: @@ -338,10 +386,19 @@ Library attaches, port-forwards, streams logs and samples stats as an impersonat\n4859:      Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/stats\n4860:      Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/forbidden_identity\n4861:      Should Not Contain    ${result.stdout}    SKIP\n4862:  \n4863:  Stop server and verify dataplane interruption\n4864: +    # the events of the stop and the following start are checked as they happen\n4865: +    Remove File If Exists    ${lifecycle-log}\n4866: +    Start Process    ${CLAB_BIN} --runtime ${runtime} --name ${lab-name} events --format json\n4867: +    ...    shell=True\n4868: +    ...    alias=c9s_lifecycle\n4869: +    ...    stdout=${lifecycle-log}\n4870: +    ...    stderr=${lifecycle-err}\n4871: +    Sleep    5s\n4872: +\n4873:      ${output} =    Run Clab Command    stop -t ${topo} --node server\n4874:      Should Be Equal As Integers    ${output.rc}    0\n4875:  \n4876:      # stop is a run state patch on the Node; the controller removes the Pod\n4877:      ${run_state} =    Node Field    server    {.spec.runState}\n4878: @@ -351,14 +408,32 @@ Stop server and verify dataplane interruption\n4879:      ${pods} =    Process.Run Process\n4880:      ...    kubectl -n ${lab-namespace} get pods -l c9s.run/topologyNode\\=server -o name\n4881:      ...    shell=True\n4882:      Should Be Empty    ${pods.stdout}\n4883:      ${inspect} =    Run Clab Command    inspect -t ${topo} --format json\n4884: -    Should Contain    ${inspect.stdout}    \"state\": \"stopped\"\n4885: +    ${states} =    Evaluate\n4886: +    ...    {n[\"name\"]: (n[\"state\"], n[\"status\"]) for n in json.loads($inspect.stdout)[\"${lab-name}\"]}\n4887: +    ...    modules=json\n4888: +    Should Be Equal    ${states}[${lab-name}-server]    ${{(\"exited\", \"Exited\")}}\n4889:  \n4890:      Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Fail\n4891:  \n4892: +Stopping a node reports the events Docker reports for containerlab stop\n4893: +    # Docker: kill, stop, die; the node's interfaces go with it, its peer loses carrier\n4894: +    Wait Until Keyword Succeeds    30s    1s\n4895: +    ...    Container Actions Should Include In Order    ${lifecycle-log}    server\n4896: +    ...    kill    stop    die\n4897: +    ${events} =    Get File    ${lifecycle-log}\n4898: +    Container Event Should Carry Docker Attributes    ${events}    server    die    exited\n4899: +    Wait Until Keyword Succeeds    30s    1s\n4900: +    ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    delete\n4901: +    Wait Until Keyword Succeeds    30s    1s\n4902: +    ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update\n4903: +    ...    lower-layer-down    down\n4904: +    ${client} =    Container Actions    ${lifecycle-log}    client\n4905: +    Should Not Contain    ${client}    die\n4906: +\n4907:  Apply while server is stopped keeps it stopped\n4908:      ${output} =    Run Clab Command    deploy -t ${applied-topo}\n4909:      Should Be Equal As Integers    ${output.rc}    0\n4910:      # the wait settles on the stopped node instead of waiting for it\n4911:      Should Contain    ${output.stderr}    C9s lab is ready apart from stopped nodes\n4912: @@ -385,10 +460,33 @@ Start server by lab name and verify dataplane restore\n4913:      Should Be Equal As Integers    ${mark.rc}    0\n4914:      Should Contain    ${mark_output}    applied-while-stopped\n4915:  \n4916:      Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n4917:  \n4918: +Starting a node reports the events Docker reports for containerlab start\n4919: +    TRY\n4920: +        # Docker: start; the device's readiness as a container health check\n4921: +        Wait Until Keyword Succeeds    60s    1s\n4922: +        ...    Container Actions Should Include In Order    ${lifecycle-log}    server\n4923: +        ...    kill    stop    die    start    health_status: healthy\n4924: +        ${events} =    Get File    ${lifecycle-log}\n4925: +        # the lab was last deployed from the applied file, which the Topology now records\n4926: +        Container Event Should Carry Docker Attributes\n4927: +        ...    ${events}    server    start    running    ${applied-topo}\n4928: +        Container Event Should Carry Docker Attributes\n4929: +        ...    ${events}    server    health_status: healthy    running    ${applied-topo}\n4930: +        Wait Until Keyword Succeeds    60s    1s\n4931: +        ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    create\n4932: +        Wait Until Keyword Succeeds    60s    1s\n4933: +        ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update    up\n4934: +        Validate JSON Lines    ${lifecycle-log}\n4935: +    FINALLY\n4936: +        Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True\n4937: +        Remove File If Exists    ${lifecycle-log}\n4938: +        Remove File If Exists    ${lifecycle-err}\n4939: +    END\n4940: +\n4941:  Restart server and keep dataplane working\n4942:      ${before} =    Server Pod Name\n4943:      ${output} =    Run Clab Command    restart -t ${topo} --node server\n4944:      Should Be Equal As Integers    ${output.rc}    0\n4945:  \n4946: @@ -445,26 +543,36 @@ Events report interface up and down\n4947:          ...    stdout=${iface-events-log}\n4948:          ...    stderr=${iface-events-err}\n4949:          Sleep    5s\n4950:          Set Client Eth1    down\n4951:          Wait Until Keyword Succeeds    30s    1s\n4952: -        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    down\n4953: +        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    down\n4954:          # the peer loses carrier\n4955:          Wait Until Keyword Succeeds    30s    1s\n4956: -        ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    down\n4957: +        ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    update\n4958: +        ...    lower-layer-down    down\n4959:          Set Client Eth1    up\n4960:          Wait Until Keyword Succeeds    30s    1s\n4961: -        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    up\n4962: +        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    up\n4963:          Validate JSON Lines    ${iface-events-log}\n4964:      FINALLY\n4965:          Stop Events Process\n4966:          Set Client Eth1    up\n4967:          Remove File If Exists    ${iface-events-log}\n4968:          Remove File If Exists    ${iface-events-err}\n4969:      END\n4970:  \n4971:  Destroy without cleanup keeps the persistent claims\n4972: +    # the events of the destroy and the following deploy are checked after the deploy\n4973: +    Remove File If Exists    ${redeploy-log}\n4974: +    Start Process    ${CLAB_BIN} --runtime ${runtime} --namespace ${lab-namespace} events --format json\n4975: +    ...    shell=True\n4976: +    ...    alias=c9s_redeploy\n4977: +    ...    stdout=${redeploy-log}\n4978: +    ...    stderr=${redeploy-err}\n4979: +    Sleep    5s\n4980: +\n4981:      ${before} =    Persistent Claim Volumes\n4982:      Should Not Be Empty    ${before}\n4983:  \n4984:      ${output} =    Run Clab Command    destroy -t ${topo}\n4985:      Should Be Equal As Integers    ${output.rc}    0\n4986: @@ -479,10 +587,36 @@ Deploy reuses the retained persistent claims\n4987:      Should Be Equal As Integers    ${output.rc}    0\n4988:  \n4989:      ${volumes} =    Persistent Claim Volumes\n4990:      Should Be Equal    ${volumes}    ${retained-volumes}\n4991:  \n4992: +Destroy and deploy report the events Docker reports\n4993: +    TRY\n4994: +        FOR    ${node}    IN    client    server\n4995: +            # Docker: kill, die, destroy; then create, start (and the health check)\n4996: +            Wait Until Keyword Succeeds    60s    1s\n4997: +            ...    Container Actions Should Include In Order    ${redeploy-log}    ${node}\n4998: +            ...    kill    die    destroy    create    start    health_status: healthy\n4999: +            ${events} =    Get File    ${redeploy-log}\n5000: +            # the destroyed lab was last deployed from the applied file, the new one from ${topo}\n5001: +            Container Event Should Carry Docker Attributes\n5002: +            ...    ${events}    ${node}    destroy    exited    ${applied-topo}\n5003: +            Container Event Should Carry Docker Attributes    ${events}    ${node}    create    created\n5004: +            Container Event Should Carry Docker Attributes    ${events}    ${node}    start    running\n5005: +            # like Docker, the link may be created down and come up after\n5006: +            Wait Until Keyword Succeeds    60s    1s\n5007: +            ...    Interface Event Should Be Logged    ${redeploy-log}    ${node}    eth1    create\n5008: +            Wait Until Keyword Succeeds    60s    1s\n5009: +            ...    Last Interface State Should Be    ${redeploy-log}    ${node}    eth1    up\n5010: +        END\n5011: +        Validate JSON Lines    ${redeploy-log}\n5012: +    FINALLY\n5013: +        Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True\n5014: +        Remove File If Exists    ${redeploy-log}\n5015: +        Remove File If Exists    ${redeploy-err}\n5016: +    END\n5017: +\n5018:  Destroy c9s linux lab\n5019:      ${output} =    Run Clab Command    destroy -t ${topo} --cleanup\n5020:      Should Be Equal As Integers    ${output.rc}    0\n5021:  \n5022:      ${inspect_all} =    Run Clab Command    inspect --all\n5023: @@ -509,10 +643,18 @@ Deploy c9s linux lab without a Topology resource\n5024:      ...    shell=True\n5025:      Should Be Equal As Integers    ${nodes.rc}    0\n5026:      Should Contain    ${nodes.stdout}    node.c9s.run/client\n5027:      Should Contain    ${nodes.stdout}    node.c9s.run/server\n5028:  \n5029: +    # without a Topology the Nodes record the file; inspect without the file reports it\n5030: +    ${annotation} =    Node Field    client    {.metadata.annotations.containerlab\\\\.dev/topo-file}\n5031: +    Should Be Equal    ${annotation}    ${topo}\n5032: +    ${output} =    Run Clab Command    inspect --name ${lab-name} --format json\n5033: +    ${paths} =    Evaluate    {n[\"absLabPath\"] for n in json.loads($output.stdout)[\"${lab-name}\"]}\n5034: +    ...    modules=json\n5035: +    Should Be Equal    ${paths}    ${{{\"${topo}\"}}}\n5036: +\n5037:  Apply without a Topology resource keeps a stopped node stopped\n5038:      ${output} =    Run Clab Command    stop -t ${topo} --node client\n5039:      Should Be Equal As Integers    ${output.rc}    0\n5040:  \n5041:      ${plan} =    Run Clab Command    deploy -t ${applied-topo} --no-topology-cr --dry-run --format json\n5042: @@ -549,10 +691,12 @@ Setup\n5043:      ${output} =    Run Clab Command    destroy -t ${topo} --cleanup\n5044:      Log    Cleanup return code: ${output.rc}\n5045:  \n5046:  Teardown\n5047:      Stop Events Process\n5048: +    Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True\n5049: +    Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True\n5050:      Run Clab Command    destroy -t ${topo} --cleanup\n5051:      Remove File If Exists    ${events-log}\n5052:      Remove File If Exists    ${events-err}\n5053:  \n5054:  Run Clab Command\n5055: @@ -639,17 +783,80 @@ Collect Events\n5056:  Set Client Eth1\n5057:      [Arguments]    ${state}\n5058:      Run Clab Command    exec -t ${topo} --label ${client-label} --cmd 'ip link set dev eth1 ${state}'\n5059:  \n5060:  Interface Event Should Be Logged\n5061: -    [Arguments]    ${path}    ${node}    ${ifname}    ${action}\n5062: +    [Documentation]    An interface event with the action and, when given, one of the states.\n5063: +    [Arguments]    ${path}    ${node}    ${ifname}    ${action}    @{states}\n5064:      ${contents} =    Get File    ${path}\n5065:      ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n5066:      ${found} =    Evaluate\n5067: -    ...    ($action, $actor, $ifname) in [(e.get(\"action\"), e.get(\"actor_id\"), e.get(\"attributes\", {}).get(\"ifname\")) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"interface\"]\n5068: +    ...    any([e.get(\"action\") == $action and e.get(\"actor_id\") == $actor and e.get(\"attributes\", {}).get(\"ifname\") == $ifname and (not $states or e.get(\"attributes\", {}).get(\"state\") in $states) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"interface\"])\n5069: +    ...    modules=json\n5070: +    Should Be True    ${found}    no interface ${action} event ${states} for ${node}:${ifname}\n5071: +\n5072: +Last Interface State Should Be\n5073: +    [Arguments]    ${path}    ${node}    ${ifname}    ${state}\n5074: +    ${contents} =    Get File    ${path}\n5075: +    ${states} =    Interface States    ${contents}    ${node}\n5076: +    Should Be Equal    ${states}[${ifname}]    ${state}\n5077: +\n5078: +Container Actions\n5079: +    [Arguments]    ${path}    ${node}\n5080: +    ${contents} =    Get File    ${path}\n5081: +    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n5082: +    ${actions} =    Evaluate\n5083: +    ...    [e[\"action\"] for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"container\" and e.get(\"actor_id\") == $actor]\n5084: +    ...    modules=json\n5085: +    RETURN    ${actions}\n5086: +\n5087: +Container Actions Should Include In Order\n5088: +    [Arguments]    ${path}    ${node}    @{expected}\n5089: +    ${actions} =    Container Actions    ${path}    ${node}\n5090: +    # the expected actions appear in this order, other actions may come between them\n5091: +    ${in_order} =    Evaluate\n5092: +    ...    re.search(\"\\\\n\" + \"\\\\n(?:.*\\\\n)*?\".join([re.escape(a) for a in $expected]) + \"\\\\n\", \"\\\\n\" + \"\\\\n\".join($actions) + \"\\\\n\") is not None\n5093: +    ...    modules=re\n5094: +    Should Be True    ${in_order}    ${node} reported ${actions}, not ${expected} in this order\n5095: +\n5096: +Container Event Should Carry Docker Attributes\n5097: +    [Documentation]    The last container event of a node with the action carries the attributes\n5098: +    ...    a Docker container event of the node has, and the container state.\n5099: +    [Arguments]    ${events}    ${node}    ${action}    ${state}    ${topo-file}=${topo}\n5100: +    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n5101: +    ${matching} =    Evaluate\n5102: +    ...    [e for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get(\"type\") == \"container\" and e.get(\"actor_id\") == $actor and e.get(\"action\") == $action]\n5103: +    ...    modules=json\n5104: +    Should Not Be Empty    ${matching}    no container ${action} event for ${node}\n5105: +    ${event} =    Set Variable    ${matching}[-1]\n5106: +    ${attributes} =    Set Variable    ${event}[attributes]\n5107: +    Log    ${attributes}\n5108: +    Should Be Equal    ${attributes}[containerlab]    ${lab-name}\n5109: +    Should Be Equal    ${attributes}[clab-node-name]    ${node}\n5110: +    Should Be Equal    ${attributes}[clab-node-longname]    ${lab-name}-${node}\n5111: +    Should Be Equal    ${attributes}[clab-node-kind]    linux\n5112: +    Should Be Equal    ${attributes}[clab-topo-file]    ${topo-file}\n5113: +    Should Not Be Empty    ${attributes}[clab-owner]\n5114: +    Should Be Equal    ${attributes}[image]    ${node-image}\n5115: +    Should Be Equal    ${attributes}[name]    ${lab-name}-${node}\n5116: +    Should Be Equal    ${attributes}[id]    ${actor}\n5117: +    Should Be Equal    ${event}[actor_full_id]    ${actor}\n5118: +    # a node is created before the controller allocates its management address and Service\n5119: +    IF    $state != \"created\"\n5120: +        Should Match Regexp    ${attributes}[mgmt_ipv4]    ^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+/\\\\d+$\n5121: +        Should Contain    ${attributes}[ports]    22/tcp\n5122: +    END\n5123: +    Should Be Equal    ${attributes}[state]    ${state}\n5124: +\n5125: +Interface States\n5126: +    [Documentation]    The interfaces the events report for a node, with their last state.\n5127: +    [Arguments]    ${events}    ${node}\n5128: +    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n5129: +    ${states} =    Evaluate\n5130: +    ...    {e[\"attributes\"][\"ifname\"]: e[\"attributes\"].get(\"state\", \"\") for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get(\"type\") == \"interface\" and e.get(\"actor_id\") == $actor}\n5131:      ...    modules=json\n5132: -    Should Be True    ${found}    no interface ${action} event for ${node}:${ifname}\n5133: +    RETURN    ${states}\n5134:  \n5135:  Log File Should Contain\n5136:      [Arguments]    ${path}    ${text}\n5137:      ${contents} =    Get File    ${path}\n5138:      Should Contain    ${contents}    ${text}\n\n(End of file - total 5138 lines)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": " func nodeStateFromResource(nodeResource *unstructured.Unstructured) clablabruntime.NodeState {\n \tnode := clablabruntime.NodeState{\n \t\tName:    nodeResource.GetName(),\n \t\tNodeUID: string(nodeResource.GetUID()),\n \t}\n+\tif original := nodeResource.GetLabels()[labelOriginalNodeName]; original != node.Name {\n+\t\tnode.TopologyName = original\n+\t}\n \tnode.ExposedPorts = nodeExposedPorts(nodeResource)\n \t// The same container exec targets: the observed primary device container.\n \tnode.Container, _ = preferredDeviceContainerName(nodeResource, node.Name)\n \tnode.Kind, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"kind\")\n \tnode.Image, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"image\")\n+\tnode.Type, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"type\")\n+\tnode.Group, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"group\")\n \tnode.State, _, _ = unstructured.NestedString(nodeResource.Object, \"status\", \"readiness\")\n \tnode.Ready = node.State == \"ready\"\n \tnode.LoadBalancerAddress, _, _ = unstructured.NestedString(\n \t\tnodeResource.Object,\n \t\t\"status\",",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": " func nodeStateFromResource(nodeResource *unstructured.Unstructured) clablabruntime.NodeState {\n \tnode := clablabruntime.NodeState{\n \t\tName:    nodeResource.GetName(),\n \t\tNodeUID: string(nodeResource.GetUID()),\n \t}\n+\tif original := nodeResource.GetLabels()[labelOriginalNodeName]; original != node.Name {\n+\t\tnode.TopologyName = original\n+\t}\n \tnode.ExposedPorts = nodeExposedPorts(nodeResource)\n \t// The same container exec targets: the observed primary device container.\n \tnode.Container, _ = preferredDeviceContainerName(nodeResource, node.Name)\n \tnode.Kind, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"kind\")\n \tnode.Image, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"image\")\n+\tnode.Type, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"type\")\n+\tnode.Group, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"group\")\n \tnode.State, _, _ = unstructured.NestedString(nodeResource.Object, \"status\", \"readiness\")\n \tnode.Ready = node.State == \"ready\"\n \tnode.LoadBalancerAddress, _, _ = unstructured.NestedString(\n \t\tnodeResource.Object,\n \t\t\"status\",\n@@ -132,17 +144,28 @@ func intField(value any) int {\n \tdefault:\n \t\treturn 0\n \t}\n }\n \n-// newestPod prefers a running pod and, among equals, the newest one: several pods can match a\n-// node during a rolling update.\n+// newestPod prefers a pod that is not being deleted, then a running pod and, among equals, the\n+// newest one: several pods can match a node during a rolling update or a restart, when the old\n+// pod terminates while its replacement starts.\n func newestPod(current, candidate *corev1.Pod) *corev1.Pod {\n \tif current == nil {\n \t\treturn candidate\n \t}\n \n+\tcurrentDeleting := current.DeletionTimestamp != nil\n+\tcandidateDeleting := candidate.DeletionTimestamp != nil\n+\tif currentDeleting != candidateDeleting {\n+\t\tif candidateDeleting {\n+\t\t\treturn current\n+\t\t}\n+\n+\t\treturn candidate\n+\t}\n+\n \tcurrentRunning := current.Status.Phase == corev1.PodRunning\n \tcandidateRunning := candidate.Status.Phase == corev1.PodRunning\n \tif currentRunning != candidateRunning {\n \t\tif candidateRunning {\n \t\t\treturn candidate\n@@ -197,20 +220,30 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat\n \tfor idx := range pods.Items {\n \t\tnodeName := pods.Items[idx].Labels[labelTopologyNode]\n \t\tif nodeName == \"\" {\n \t\t\tcontinue\n \t\t}\n+\t\t// A pod of an earlier Node of the same name (a redeploy while the old pod still\n+\t\t// terminates) is not this node's pod.\n+\t\tif uid := pods.Items[idx].Annotations[annotationDirectNodeUID]; uid != \"\" {\n+\t\t\tif resource := resourcesByName[nodeName]; resource != nil &&\n+\t\t\t\tstring(resource.GetUID()) != uid {\n+\t\t\t\tcontinue\n+\t\t\t}\n+\t\t}\n \t\tpodsByNode[nodeName] = newestPod(podsByNode[nodeName], &pods.Items[idx])\n \t}\n \n \t// The Node's status.readiness is the authoritative device signal. The primary Node's run\n \t// state governs the pod a group of nodes shares: a stopped primary stops the whole group.\n \t// Nodes without readiness yet report their pod phase.\n \tfor nodeName, node := range nodesByName {\n \t\tprimary := resolvePrimaryNode(nodeName, networkModes)\n-\t\tif primaryResource := resourcesByName[primary]; primaryResource != nil &&\n-\t\t\tnodeRunState(primaryResource) == nodeRunStateStopped {\n+\t\tprimaryResource := resourcesByName[primary]\n+\t\tstopRequested := primaryResource != nil &&\n+\t\t\tnodeRunState(primaryResource) == nodeRunStateStopped\n+\t\tif stopRequested {\n \t\t\tnode.State = \"stopping\"\n \t\t\tif condition := nodeCondition(\n \t\t\t\tprimaryResource,\n \t\t\t\tnodeConditionStopped,\n \t\t\t); condition != nil &&\n@@ -220,10 +253,14 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat\n \t\t\tnode.Ready = false\n \t\t} else if pod := podsByNode[primary]; node.State == \"\" && pod != nil &&\n \t\t\tpod.Status.Phase != \"\" {\n \t\t\tnode.State = strings.ToLower(string(pod.Status.Phase))\n \t\t}\n+\t\tnode.ContainerState = nodeContainerState(stopRequested, podsByNode[primary])\n+\t\tif node.ContainerState == clablabruntime.ContainerStateRunning {\n+\t\t\tnode.Health = nodeHealth(node, resourcesByName[nodeName])\n+\t\t}\n \t\tnodesByName[nodeName] = node\n \t}\n \n \t// Nodes grouped through network-mode container: share the pod of the group's primary\n \t// node. Before the controller observed the device containers, the pod's default-container\n@@ -270,5 +307,46 @@ func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabStat\n \t\tstate.Ready = false\n \t}\n \n \treturn nil\n }\n+\n+// nodeContainerState is the state of a node in container runtime terms, from its pod: created\n+// while the pod is scheduled and prepared (init containers), running once the device containers\n+// run, and exited once the node was stopped, its pod is being deleted, or the pod ended. Between\n+// the pods of a restart the node is exited, then created.\n+func nodeContainerState(stopRequested bool, pod *corev1.Pod) string {\n+\tswitch {\n+\tcase pod == nil && stopRequested:\n+\t\treturn clablabruntime.ContainerStateExited\n+\tcase pod == nil:\n+\t\treturn clablabruntime.ContainerStateCreated\n+\tcase stopRequested || pod.DeletionTimestamp != nil:\n+\t\treturn clablabruntime.ContainerStateExited\n+\t}\n+\n+\tswitch pod.Status.Phase {\n+\tcase corev1.PodRunning:\n+\t\treturn clablabruntime.ContainerStateRunning\n+\tcase corev1.PodSucceeded, corev1.PodFailed:\n+\t\treturn clablabruntime.ContainerStateExited\n+\tdefault:\n+\t\treturn clablabruntime.ContainerStateCreated\n+\t}\n+}\n+\n+// nodeHealth is the health of a running node: healthy once the Node is ready or its device\n+// containers are, starting before. Device containers are the analogue of a container\n+// healthcheck: a node whose links wait for a stopped peer is not ready, but its device is.\n+func nodeHealth(node clablabruntime.NodeState, resource *unstructured.Unstructured) string {\n+\tif node.Ready {\n+\t\treturn clablabruntime.ContainerHealthHealthy\n+\t}\n+\tif resource != nil {\n+\t\tif condition := nodeCondition(resource, nodeConditionContainersReady); condition != nil &&\n+\t\t\tcondition.status == string(metav1.ConditionTrue) {\n+\t\t\treturn clablabruntime.ContainerHealthHealthy\n+\t\t}\n+\t}\n+\n+\treturn clablabruntime.ContainerHealthStarting\n+}\ndiff --git a/labruntime/clabernetes/topology.go b/labruntime/clabernetes/topology.go\nindex e401ecf..db3715a 100644\n--- a/labruntime/clabernetes/topology.go\n+++ b/labruntime/clabernetes/topology.go\n@@ -12,10 +12,56 @@ import (\n \t\"k8s.io/apimachinery/pkg/util/validation\"\n )\n \n type topologyObjectOption func(map[string]any)\n \n+// annotationTopologyFile records the absolute path of the topology file a lab was deployed from,\n+// on the machine that deployed it. Inspect reports it as the lab's topology path and events as\n+// clab-topo-file, as the local runtimes do, so clients match the running lab to its file. A lab\n+// created by other means than a containerlab deploy has no annotation and reports where its\n+// definition lives in the cluster (k8s://<namespace>/topologies/<lab>).\n+const annotationTopologyFile = \"containerlab.dev/topo-file\"\n+\n+// setTopologySourceFile records the topology file a deploy reads on the Topology. An empty path\n+// (a definition that came from no file) records nothing.\n+func setTopologySourceFile(topology *unstructured.Unstructured, path string) {\n+\tif path == \"\" {\n+\t\treturn\n+\t}\n+\n+\tannotations := topology.GetAnnotations()\n+\tif annotations == nil {\n+\t\tannotations = map[string]string{}\n+\t}\n+\tannotations[annotationTopologyFile] = path\n+\ttopology.SetAnnotations(annotations)\n+}\n+\n+// removeTopologySourceFile drops the deploying machine's file path from an object.\n+func removeTopologySourceFile(obj *unstructured.Unstructured) {\n+\tannotations := obj.GetAnnotations()\n+\tif _, ok := annotations[annotationTopologyFile]; !ok {\n+\t\treturn\n+\t}\n+\n+\tdelete(annotations, annotationTopologyFile)\n+\tif len(annotations) == 0 {\n+\t\tannotations = nil\n+\t}\n+\tobj.SetAnnotations(annotations)\n+}\n+\n+// labTopologyPath is the topology path a lab reports: the file it was deployed from when the\n+// deploy recorded one, otherwise the place given.\n+func labTopologyPath(annotations map[string]string, fallback string) string {\n+\tif path := annotations[annotationTopologyFile]; path != \"\" {\n+\t\treturn path\n+\t}\n+\n+\treturn fallback\n+}\n+\n func topologyWithNaming(naming string) topologyObjectOption {\n \treturn func(spec map[string]any) {\n \t\tif naming != \"\" {\n \t\t\tspec[\"naming\"] = naming\n \t\t}\n@@ -137,10 +183,14 @@ func stateFromTopology(obj *unstructured.Unstructured, namespace string) *clabla\n \towner := obj.GetLabels()[clabconstants.Owner]\n \tif owner == \"\" {\n \t\towner = obj.GetAnnotations()[clabconstants.Owner]\n \t}\n \tnodeSpecs := nodeSpecsFromTopology(obj)\n+\ttopologyPath := labTopologyPath(\n+\t\tobj.GetAnnotations(),\n+\t\tfmt.Sprintf(\"k8s://%s/topologies/%s\", namespace, obj.GetName()),\n+\t)\n \n \tnodeNames := make([]string, 0, len(nodeSpecs))\n \tfor nodeName := range nodeSpecs {\n \t\tnodeNames = append(nodeNames, nodeName)\n \t}\n@@ -158,11 +208,11 @@ func stateFromTopology(obj *unstructured.Unstructured, namespace string) *clabla\n \n \treturn &clablabruntime.LabState{\n \t\tName:         obj.GetName(),\n \t\tNamespace:    namespace,\n \t\tOwner:        owner,\n-\t\tTopologyPath: fmt.Sprintf(\"k8s://%s/topologies/%s\", namespace, obj.GetName()),\n+\t\tTopologyPath: topologyPath,\n \t\tState:        state,\n \t\tReady:        ready,\n \t\tNodes:        nodes,\n \t}\n }\ndiff --git a/labruntime/runtime.go b/labruntime/runtime.go\nindex 367565d..0f2433a 100644\n--- a/labruntime/runtime.go\n+++ b/labruntime/runtime.go\n@@ -191,16 +191,42 @@ type SavedFile struct {\n \n type SaveResult struct {\n \tFiles []SavedFile\n }\n \n+// Container states and health in the vocabulary of container runtimes (Docker), which inspect\n+// and events report for lab runtime nodes too.\n+const (\n+\tContainerStateCreated = \"created\"\n+\tContainerStateRunning = \"running\"\n+\tContainerStateExited  = \"exited\"\n+\n+\tContainerHealthHealthy   = \"healthy\"\n+\tContainerHealthStarting  = \"starting\"\n+\tContainerHealthUnhealthy = \"unhealthy\"\n+)\n+\n type NodeState struct {\n-\tName  string\n-\tKind  string\n-\tImage string\n+\tName string\n+\t// TopologyName is the node name as the topology file spells it, when the runtime had to\n+\t// carry the node under another name (Name). Empty means Name.\n+\tTopologyName string\n+\tKind         string\n+\tImage        string\n+\t// Type and Group are the node's type and group when the topology set them.\n+\tType  string\n+\tGroup string\n+\t// State is the runtime's own view of the node, such as the clabernetes Node readiness, or\n+\t// stopped.\n \tState string\n \tReady bool\n+\t// ContainerState is the node's state in container runtime terms: created, running or\n+\t// exited (the ContainerState* constants). Empty when the runtime does not report one.\n+\tContainerState string\n+\t// Health is the device health of a running node in container runtime terms: healthy or\n+\t// starting. Empty when the node does not run.\n+\tHealth string\n \t// MgmtIPv4Address and MgmtIPv6Address are the node's allocated management addresses in\n \t// CIDR notation, when the runtime reports them.\n \tMgmtIPv4Address     string\n \tMgmtIPv6Address     string\n \tLoadBalancerAddress string\n@@ -216,13 +242,16 @@ type NodeState struct {\n \n // ExposedPort is a node port a lab runtime publishes through a Service.\n type ExposedPort = clabtypes.ExposedPort\n \n type LabState struct {\n-\tName         string\n-\tNamespace    string\n-\tOwner        string\n+\tName      string\n+\tNamespace string\n+\tOwner     string\n+\t// TopologyPath is the absolute path of the topology file the lab was deployed from, on the\n+\t// machine that deployed it. A lab the runtime did not deploy from a file reports where the\n+\t// runtime keeps its definition instead (for c9s k8s://<namespace>/topologies/<lab>).\n \tTopologyPath string\n \tState        string\n \tReady        bool\n \tNodes        []NodeState\n }\n@@ -258,11 +287,61 @@ type Event struct {\n \tType        string\n \tAction      string\n \tActorID     string\n \tActorName   string\n \tActorFullID string\n-\tAttributes  map[string]string\n+\t// Attributes are the runtime's own attributes. Event consumers add the attributes the\n+\t// container runtimes report from Lab, Node and Interface.\n+\tAttributes map[string]string\n+\t// Lab and Node are the lab node a container or interface event is about, as Inspect\n+\t// reports it. containerlab's events command describes the node from them the same way\n+\t// inspect does, so both agree and match what the container runtimes report.\n+\tLab  *LabState\n+\tNode *NodeState\n+\t// Interface is the interface an interface event reports.\n+\tInterface *InterfaceEventData\n+}\n+\n+// Event types and the origin attribute of lab runtime events.\n+const (\n+\tEventTypeContainer = \"container\"\n+\tEventTypeInterface = \"interface\"\n+\t// EventOriginSnapshot marks the events of --initial-state, in the origin attribute.\n+\tEventOriginSnapshot = \"snapshot\"\n+)\n+\n+// InterfaceEventData describes an interface of a node the way the container runtimes' interface\n+// events do (netlink).\n+type InterfaceEventData struct {\n+\t// Name is the interface name inside the node.\n+\tName string\n+\t// Alias is the name the topology gave the interface when the node kind maps it (for\n+\t// example ethernet-1/1 for SR Linux e1-1).\n+\tAlias string\n+\tIndex int\n+\tMTU   int\n+\tMAC   string\n+\t// OperState is the operational state in netlink's vocabulary: up, down, lower-layer-down,\n+\t// dormant, testing, not-present or unknown.\n+\tOperState string\n+\t// Type is the link type in netlink's vocabulary, such as veth or device (loopback).\n+\tType string\n+\t// Stats are set on stats events.\n+\tStats *InterfaceStats\n+}\n+\n+// InterfaceStats are the counters and rates of an interface stats event.\n+type InterfaceStats struct {\n+\tRxBytes   uint64\n+\tTxBytes   uint64\n+\tRxPackets uint64\n+\tTxPackets uint64\n+\tRxBps     float64\n+\tTxBps     float64\n+\tRxPps     float64\n+\tTxPps     float64\n+\tInterval  time.Duration\n }\n \n // NodeLocation is the workload that runs a lab node.\n type NodeLocation struct {\n \t// NodeName is the node name the runtime carries (the sanitized name).\ndiff --git a/tests/14-clabernetes/01-linux-lifecycle.robot b/tests/14-clabernetes/01-linux-lifecycle.robot\nindex f45a3ff..bc27828 100644\n--- a/tests/14-clabernetes/01-linux-lifecycle.robot\n+++ b/tests/14-clabernetes/01-linux-lifecycle.robot\n@@ -27,10 +27,15 @@ ${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+${lifecycle-log}        /tmp/clab-c9s-lifecycle-events.log\n+${lifecycle-err}        /tmp/clab-c9s-lifecycle-events.err\n+${redeploy-log}         /tmp/clab-c9s-redeploy-events.log\n+${redeploy-err}         /tmp/clab-c9s-redeploy-events.err\n+${node-image}           ghcr.io/srl-labs/network-multitool\n \n \n *** Test Cases ***\n Deploy c9s linux lab\n     ${output} =    Run Clab Command    deploy -t ${topo}\n@@ -103,10 +108,47 @@ Inspect all is scoped by the namespace override\n \n     ${other} =    Run Clab Command    --namespace default inspect --all --format json\n     Should Be Equal As Integers    ${other.rc}    0\n     Should Not Contain    ${other.stdout}    ${lab-name}\n \n+Inspect reports the topology file the lab was deployed from\n+    # the deploy recorded this machine's file on the Topology; inspect without the file reports it\n+    ${annotation} =    Process.Run Process\n+    ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} -o jsonpath\\='{.metadata.annotations.containerlab\\\\.dev/topo-file}'\n+    ...    shell=True\n+    Should Be Equal As Integers    ${annotation.rc}    0\n+    Should Be Equal    ${annotation.stdout}    ${topo}\n+\n+    ${output} =    Run Clab Command    inspect --all --format json\n+    Should Be Equal As Integers    ${output.rc}    0\n+    ${labs} =    Evaluate    json.loads($output.stdout)    modules=json\n+    FOR    ${node}    IN    @{labs}[${lab-name}]\n+        Should Be Equal    ${node}[absLabPath]    ${topo}\n+        Should Not Start With    ${node}[labPath]    k8s://\n+        Should Be Equal    ${node}[state]    running\n+        Should Be Equal    ${node}[status]    healthy\n+    END\n+\n+    # manifests are applied by other means; they do not carry this machine's path\n+    ${emit} =    Run Offline Clab Command    deploy -t ${topo} --emit-crs\n+    Should Be Equal As Integers    ${emit.rc}    0\n+    Should Not Contain    ${emit.stdout}    containerlab.dev/topo-file\n+\n+Events carry the attributes of Docker events\n+    ${events} =    Collect Events    --name ${lab-name} events --format json --initial-state\n+    FOR    ${node}    IN    client    server\n+        Container Event Should Carry Docker Attributes    ${events}    ${node}    running    running\n+        # the interfaces a Docker container of the node has: the lab link, eth0 and lo, named\n+        # as in the topology, the link up\n+        ${ifaces} =    Interface States    ${events}    ${node}\n+        Should Be Equal    ${{sorted($ifaces)}}    ${{[\"eth0\", \"eth1\", \"lo\"]}}\n+        Should Be Equal    ${ifaces}[eth1]    up\n+        Should Be Equal    ${ifaces}[eth0]    up\n+        Should Be Equal    ${ifaces}[lo]    unknown\n+    END\n+    Should Not Contain    ${events}    \"ifname\":\"c9s\n+\n Validate and emit-crs work without a kubeconfig\n     ${validate} =    Run Offline Clab Command    validate -t ${topo}\n     Should Be Equal As Integers    ${validate.rc}    0\n     Should Contain    ${validate.stderr}    Topology is valid for lab runtime\n \n@@ -141,17 +183,23 @@ Inspect interfaces lists the link interfaces with their state\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+        # what a Docker container of the node lists: eth0, the lab link and loopback\n+        ${names} =    Evaluate    [i[\"name\"] for i in $container[\"interfaces\"]]\n+        Should Be Equal    ${names}    ${{[\"eth0\", \"eth1\", \"lo\"]}}\n+        ${iface} =    Set Variable    ${container}[interfaces][1]\n         Should Be Equal    ${iface}[name]    eth1\n+        Should Be Equal    ${iface}[alias]    ${EMPTY}\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+        ${lo} =    Set Variable    ${container}[interfaces][2]\n+        Should Be Equal    ${lo}[type]    device\n+        Should Be Equal    ${lo}[state]    unknown\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@@ -338,10 +386,19 @@ Library attaches, port-forwards, streams logs and samples stats as an impersonat\n     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/stats\n     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/forbidden_identity\n     Should Not Contain    ${result.stdout}    SKIP\n \n Stop server and verify dataplane interruption\n+    # the events of the stop and the following start are checked as they happen\n+    Remove File If Exists    ${lifecycle-log}\n+    Start Process    ${CLAB_BIN} --runtime ${runtime} --name ${lab-name} events --format json\n+    ...    shell=True\n+    ...    alias=c9s_lifecycle\n+    ...    stdout=${lifecycle-log}\n+    ...    stderr=${lifecycle-err}\n+    Sleep    5s\n+\n     ${output} =    Run Clab Command    stop -t ${topo} --node server\n     Should Be Equal As Integers    ${output.rc}    0\n \n     # stop is a run state patch on the Node; the controller removes the Pod\n     ${run_state} =    Node Field    server    {.spec.runState}\n@@ -351,14 +408,32 @@ Stop server and verify dataplane interruption\n     ${pods} =    Process.Run Process\n     ...    kubectl -n ${lab-namespace} get pods -l c9s.run/topologyNode\\=server -o name\n     ...    shell=True\n     Should Be Empty    ${pods.stdout}\n     ${inspect} =    Run Clab Command    inspect -t ${topo} --format json\n-    Should Contain    ${inspect.stdout}    \"state\": \"stopped\"\n+    ${states} =    Evaluate\n+    ...    {n[\"name\"]: (n[\"state\"], n[\"status\"]) for n in json.loads($inspect.stdout)[\"${lab-name}\"]}\n+    ...    modules=json\n+    Should Be Equal    ${states}[${lab-name}-server]    ${{(\"exited\", \"Exited\")}}\n \n     Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Fail\n \n+Stopping a node reports the events Docker reports for containerlab stop\n+    # Docker: kill, stop, die; the node's interfaces go with it, its peer loses carrier\n+    Wait Until Keyword Succeeds    30s    1s\n+    ...    Container Actions Should Include In Order    ${lifecycle-log}    server\n+    ...    kill    stop    die\n+    ${events} =    Get File    ${lifecycle-log}\n+    Container Event Should Carry Docker Attributes    ${events}    server    die    exited\n+    Wait Until Keyword Succeeds    30s    1s\n+    ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    delete\n+    Wait Until Keyword Succeeds    30s    1s\n+    ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update\n+    ...    lower-layer-down    down\n+    ${client} =    Container Actions    ${lifecycle-log}    client\n+    Should Not Contain    ${client}    die\n+\n Apply while server is stopped keeps it stopped\n     ${output} =    Run Clab Command    deploy -t ${applied-topo}\n     Should Be Equal As Integers    ${output.rc}    0\n     # the wait settles on the stopped node instead of waiting for it\n     Should Contain    ${output.stderr}    C9s lab is ready apart from stopped nodes\n@@ -385,10 +460,33 @@ Start server by lab name and verify dataplane restore\n     Should Be Equal As Integers    ${mark.rc}    0\n     Should Contain    ${mark_output}    applied-while-stopped\n \n     Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n \n+Starting a node reports the events Docker reports for containerlab start\n+    TRY\n+        # Docker: start; the device's readiness as a container health check\n+        Wait Until Keyword Succeeds    60s    1s\n+        ...    Container Actions Should Include In Order    ${lifecycle-log}    server\n+        ...    kill    stop    die    start    health_status: healthy\n+        ${events} =    Get File    ${lifecycle-log}\n+        # the lab was last deployed from the applied file, which the Topology now records\n+        Container Event Should Carry Docker Attributes\n+        ...    ${events}    server    start    running    ${applied-topo}\n+        Container Event Should Carry Docker Attributes\n+        ...    ${events}    server    health_status: healthy    running    ${applied-topo}\n+        Wait Until Keyword Succeeds    60s    1s\n+        ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    create\n+        Wait Until Keyword Succeeds    60s    1s\n+        ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update    up\n+        Validate JSON Lines    ${lifecycle-log}\n+    FINALLY\n+        Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True\n+        Remove File If Exists    ${lifecycle-log}\n+        Remove File If Exists    ${lifecycle-err}\n+    END\n+\n Restart server and keep dataplane working\n     ${before} =    Server Pod Name\n     ${output} =    Run Clab Command    restart -t ${topo} --node server\n     Should Be Equal As Integers    ${output.rc}    0\n \n@@ -445,26 +543,36 @@ Events report interface up and down\n         ...    stdout=${iface-events-log}\n         ...    stderr=${iface-events-err}\n         Sleep    5s\n         Set Client Eth1    down\n         Wait Until Keyword Succeeds    30s    1s\n-        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    down\n+        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    down\n         # the peer loses carrier\n         Wait Until Keyword Succeeds    30s    1s\n-        ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    down\n+        ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    update\n+        ...    lower-layer-down    down\n         Set Client Eth1    up\n         Wait Until Keyword Succeeds    30s    1s\n-        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    up\n+        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    up\n         Validate JSON Lines    ${iface-events-log}\n     FINALLY\n         Stop Events Process\n         Set Client Eth1    up\n         Remove File If Exists    ${iface-events-log}\n         Remove File If Exists    ${iface-events-err}\n     END\n \n Destroy without cleanup keeps the persistent claims\n+    # the events of the destroy and the following deploy are checked after the deploy\n+    Remove File If Exists    ${redeploy-log}\n+    Start Process    ${CLAB_BIN} --runtime ${runtime} --namespace ${lab-namespace} events --format json\n+    ...    shell=True\n+    ...    alias=c9s_redeploy\n+    ...    stdout=${redeploy-log}\n+    ...    stderr=${redeploy-err}\n+    Sleep    5s\n+\n     ${before} =    Persistent Claim Volumes\n     Should Not Be Empty    ${before}\n \n     ${output} =    Run Clab Command    destroy -t ${topo}\n     Should Be Equal As Integers    ${output.rc}    0\n@@ -479,10 +587,36 @@ Deploy reuses the retained persistent claims\n     Should Be Equal As Integers    ${output.rc}    0\n \n     ${volumes} =    Persistent Claim Volumes\n     Should Be Equal    ${volumes}    ${retained-volumes}\n \n+Destroy and deploy report the events Docker reports\n+    TRY\n+        FOR    ${node}    IN    client    server\n+            # Docker: kill, die, destroy; then create, start (and the health check)\n+            Wait Until Keyword Succeeds    60s    1s\n+            ...    Container Actions Should Include In Order    ${redeploy-log}    ${node}\n+            ...    kill    die    destroy    create    start    health_status: healthy\n+            ${events} =    Get File    ${redeploy-log}\n+            # the destroyed lab was last deployed from the applied file, the new one from ${topo}\n+            Container Event Should Carry Docker Attributes\n+            ...    ${events}    ${node}    destroy    exited    ${applied-topo}\n+            Container Event Should Carry Docker Attributes    ${events}    ${node}    create    created\n+            Container Event Should Carry Docker Attributes    ${events}    ${node}    start    running\n+            # like Docker, the link may be created down and come up after\n+            Wait Until Keyword Succeeds    60s    1s\n+            ...    Interface Event Should Be Logged    ${redeploy-log}    ${node}    eth1    create\n+            Wait Until Keyword Succeeds    60s    1s\n+            ...    Last Interface State Should Be    ${redeploy-log}    ${node}    eth1    up\n+        END\n+        Validate JSON Lines    ${redeploy-log}\n+    FINALLY\n+        Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True\n+        Remove File If Exists    ${redeploy-log}\n+        Remove File If Exists    ${redeploy-err}\n+    END\n+\n Destroy c9s linux lab\n     ${output} =    Run Clab Command    destroy -t ${topo} --cleanup\n     Should Be Equal As Integers    ${output.rc}    0\n \n     ${inspect_all} =    Run Clab Command    inspect --all\n@@ -509,10 +643,18 @@ Deploy c9s linux lab without a Topology resource\n     ...    shell=True\n     Should Be Equal As Integers    ${nodes.rc}    0\n     Should Contain    ${nodes.stdout}    node.c9s.run/client\n     Should Contain    ${nodes.stdout}    node.c9s.run/server\n \n+    # without a Topology the Nodes record the file; inspect without the file reports it\n+    ${annotation} =    Node Field    client    {.metadata.annotations.containerlab\\\\.dev/topo-file}\n+    Should Be Equal    ${annotation}    ${topo}\n+    ${output} =    Run Clab Command    inspect --name ${lab-name} --format json\n+    ${paths} =    Evaluate    {n[\"absLabPath\"] for n in json.loads($output.stdout)[\"${lab-name}\"]}\n+    ...    modules=json\n+    Should Be Equal    ${paths}    ${{{\"${topo}\"}}}\n+\n Apply without a Topology resource keeps a stopped node stopped\n     ${output} =    Run Clab Command    stop -t ${topo} --node client\n     Should Be Equal As Integers    ${output.rc}    0\n \n     ${plan} =    Run Clab Command    deploy -t ${applied-topo} --no-topology-cr --dry-run --format json\n@@ -549,10 +691,12 @@ Setup\n     ${output} =    Run Clab Command    destroy -t ${topo} --cleanup\n     Log    Cleanup return code: ${output.rc}\n \n Teardown\n     Stop Events Process\n+    Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True\n+    Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True\n     Run Clab Command    destroy -t ${topo} --cleanup\n     Remove File If Exists    ${events-log}\n     Remove File If Exists    ${events-err}\n \n Run Clab Command\n@@ -639,17 +783,80 @@ Collect Events\n Set Client Eth1\n     [Arguments]    ${state}\n     Run Clab Command    exec -t ${topo} --label ${client-label} --cmd 'ip link set dev eth1 ${state}'\n \n Interface Event Should Be Logged\n-    [Arguments]    ${path}    ${node}    ${ifname}    ${action}\n+    [Documentation]    An interface event with the action and, when given, one of the states.\n+    [Arguments]    ${path}    ${node}    ${ifname}    ${action}    @{states}\n     ${contents} =    Get File    ${path}\n     ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n     ${found} =    Evaluate\n-    ...    ($action, $actor, $ifname) in [(e.get(\"action\"), e.get(\"actor_id\"), e.get(\"attributes\", {}).get(\"ifname\")) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"interface\"]\n+    ...    any([e.get(\"action\") == $action and e.get(\"actor_id\") == $actor and e.get(\"attributes\", {}).get(\"ifname\") == $ifname and (not $states or e.get(\"attributes\", {}).get(\"state\") in $states) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"interface\"])\n+    ...    modules=json\n+    Should Be True    ${found}    no interface ${action} event ${states} for ${node}:${ifname}\n+\n+Last Interface State Should Be\n+    [Arguments]    ${path}    ${node}    ${ifname}    ${state}\n+    ${contents} =    Get File    ${path}\n+    ${states} =    Interface States    ${contents}    ${node}\n+    Should Be Equal    ${states}[${ifname}]    ${state}\n+\n+Container Actions\n+    [Arguments]    ${path}    ${node}\n+    ${contents} =    Get File    ${path}\n+    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n+    ${actions} =    Evaluate\n+    ...    [e[\"action\"] for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"container\" and e.get(\"actor_id\") == $actor]\n+    ...    modules=json\n+    RETURN    ${actions}\n+\n+Container Actions Should Include In Order\n+    [Arguments]    ${path}    ${node}    @{expected}\n+    ${actions} =    Container Actions    ${path}    ${node}\n+    # the expected actions appear in this order, other actions may come between them\n+    ${in_order} =    Evaluate\n+    ...    re.search(\"\\\\n\" + \"\\\\n(?:.*\\\\n)*?\".join([re.escape(a) for a in $expected]) + \"\\\\n\", \"\\\\n\" + \"\\\\n\".join($actions) + \"\\\\n\") is not None\n+    ...    modules=re\n+    Should Be True    ${in_order}    ${node} reported ${actions}, not ${expected} in this order\n+\n+Container Event Should Carry Docker Attributes\n+    [Documentation]    The last container event of a node with the action carries the attributes\n+    ...    a Docker container event of the node has, and the container state.\n+    [Arguments]    ${events}    ${node}    ${action}    ${state}    ${topo-file}=${topo}\n+    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n+    ${matching} =    Evaluate\n+    ...    [e for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get(\"type\") == \"container\" and e.get(\"actor_id\") == $actor and e.get(\"action\") == $action]\n+    ...    modules=json\n+    Should Not Be Empty    ${matching}    no container ${action} event for ${node}\n+    ${event} =    Set Variable    ${matching}[-1]\n+    ${attributes} =    Set Variable    ${event}[attributes]\n+    Log    ${attributes}\n+    Should Be Equal    ${attributes}[containerlab]    ${lab-name}\n+    Should Be Equal    ${attributes}[clab-node-name]    ${node}\n+    Should Be Equal    ${attributes}[clab-node-longname]    ${lab-name}-${node}\n+    Should Be Equal    ${attributes}[clab-node-kind]    linux\n+    Should Be Equal    ${attributes}[clab-topo-file]    ${topo-file}\n+    Should Not Be Empty    ${attributes}[clab-owner]\n+    Should Be Equal    ${attributes}[image]    ${node-image}\n+    Should Be Equal    ${attributes}[name]    ${lab-name}-${node}\n+    Should Be Equal    ${attributes}[id]    ${actor}\n+    Should Be Equal    ${event}[actor_full_id]    ${actor}\n+    # a node is created before the controller allocates its management address and Service\n+    IF    $state != \"created\"\n+        Should Match Regexp    ${attributes}[mgmt_ipv4]    ^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+/\\\\d+$\n+        Should Contain    ${attributes}[ports]    22/tcp\n+    END\n+    Should Be Equal    ${attributes}[state]    ${state}\n+\n+Interface States\n+    [Documentation]    The interfaces the events report for a node, with their last state.\n+    [Arguments]    ${events}    ${node}\n+    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n+    ${states} =    Evaluate\n+    ...    {e[\"attributes\"][\"ifname\"]: e[\"attributes\"].get(\"state\", \"\") for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get(\"type\") == \"interface\" and e.get(\"actor_id\") == $actor}\n     ...    modules=json\n-    Should Be True    ${found}    no interface ${action} event for ${node}:${ifname}\n+    RETURN    ${states}\n \n Log File Should Contain\n     [Arguments]    ${path}    ${text}\n     ${contents} =    Get File    ${path}\n     Should Contain    ${contents}    ${text}",
        "lineStart": 4396,
        "lineEnd": 5138,
        "totalLines": 5138,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525773512,
      "end": 1793525773529
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1967774dc001qonglLxVJ2lMYp",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196775955001eS3UIf8cY8YWd1",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 47123,
    "input": 3178,
    "output": 52,
    "reasoning": 629,
    "cache": {
      "read": 43264,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196775955001eS3UIf8cY8YWd1",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525766485,
    "completed": 1793525773537
  },
  "parentID": "msg_19676df9500159h7P3dGcuBxjO",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 47123,
    "input": 3178,
    "output": 52,
    "reasoning": 629,
    "cache": {
      "read": 43264,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 19
step-start
{
  "type": "step-start",
  "id": "prt_196777f29001YJNo70ghszrRcr",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967774e8001BGGnQCqx3hEnno"
}
Reasoning
Good, I've now read to the end of the diff. Interesting robot test detail: `Container Event Should Carry Docker Attributes` expects `attributes[clab-node-kind]` = `linux` and `clab-node-name` = node (not sanitized). The topology uses client/server names, fine.

Note the robot test expects `Container Event Should Carry Docker Attributes ... create created` — no mgmt_ipv4 check for created. Good.

Also `Container Actions Should Include In Order ... kill die destroy create start health_status: healthy` for destroy+deploy. Note: for the destroy side, `containerRemovalActions` for running → kill, die, destroy (no stop). Matches the test's `kill die destroy`. And for `stop` (node stop), running → kill, stop, die. Matches test `kill stop die`.

Wait — in the stop flow, the node is stopped via run-state patch → pod deleted → tracker refresh sees lab with node... Let me think about how the stop is detected. `stop -t topo --node server` patches Node runState=stopped → controller deletes pod. Watchers: watchPods sees pod deletion → sendChangedLab(server lab) → tracker.refresh → Inspect → enrichState: nodeContainerState(stopRequested=true, pod=nil) → exited. containerTransitionActions: previous running → next exited → kill, stop, die. Matches.

But there's a subtlety: enrichState requires podsByNode — with the pod gone, stopRequested comes from primaryResource runState stopped. OK.

But wait — in `enrichState`, `node.ContainerState = nodeContainerState(stopRequested, podsByNode[primary])`. Hmm, podsByNode[primary] — for a group, the pod of the primary. For a standalone node, primary == nodeName. OK.

Now, one thing I noticed in the diff at line 4455: `if uid := pods.Items[idx].Annotations[annotationDirectNodeUID]; uid != ""` — need to verify `annotationDirectNodeUID` is set somewhere (in c9s controller code, maybe not in this repo). Let me grep for it.

Also `labelOriginalNodeName` — grep.

Let me also check remaining changed paths from manifest: I need to re-read manifest.json fully. And read remaining head files: state.go, topology.go (annotations usage in manifests/plan/primitives/reconcile), capture_interfaces.go, capture.go, clabernetes.go, runtime.go changes, core/labruntime.go earlier parts, labruntime_gaps_test.go, tests, docs.

Let me batch greps and reads.
The diff is fully read. Now verifying cross-references: `annotationDirectNodeUID`, `labelOriginalNodeName`, and the remaining manifest paths.
read · completed

Input

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

Output

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

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

Input

{
  "include": "*.go",
  "path": "/source/head",
  "pattern": "annotationDirectNodeUID|labelOriginalNodeName"
}

Output

Found 17 matches
/source/head/labruntime/clabernetes/names.go:
  Line 51: 		if nodeDefinition.Labels[labelOriginalNodeName] != originalLabel {

  Line 55: 			nodeDefinition.Labels[labelOriginalNodeName] = originalLabel


/source/head/labruntime/clabernetes/capture.go:
  Line 328: 		if original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != "" {


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

  Line 40: 	// annotationDirectNodeUID names the UID of the Node a c9s pod runs.

  Line 41: 	annotationDirectNodeUID = "c9s.run/direct-node-uid"


/source/head/labruntime/clabernetes/event_parity_test.go:
  Line 484: 				labelTopologyOwner: "lab1", labelOriginalNodeName: strings.ToUpper(name),

  Line 999: 	pod.Annotations[annotationDirectNodeUID] = uid


/source/head/labruntime/clabernetes/state.go:
  Line 54: 	if original := nodeResource.GetLabels()[labelOriginalNodeName]; original != node.Name {

  Line 227: 		if uid := pods.Items[idx].Annotations[annotationDirectNodeUID]; uid != "" {


/source/head/labruntime/clabernetes/nodes_test.go:
  Line 800: 				if obj.GetLabels()[labelOriginalNodeName] == "" {

  Line 801: 					t.Errorf("Node %s lost its %s label", obj.GetName(), labelOriginalNodeName)


/source/head/labruntime/clabernetes/capture_test.go:
  Line 29: 		labels[labelOriginalNodeName] = original


/source/head/labruntime/clabernetes/clabernetes_test.go:
  Line 2360: 		if got := labels[labelOriginalNodeName]; got != originalName {

  Line 2364: 				labelOriginalNodeName,

  Line 2464: 		if got := node.GetLabels()[labelOriginalNodeName]; got != originalName {

  Line 2468: 				labelOriginalNodeName,
Tool metadata
{
  "type": "tool",
  "id": "prt_196778d56001NmA7PSptz2ObBT",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967774e8001BGGnQCqx3hEnno",
  "callID": "call_b95546c3d78941e1b41d2357",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "include": "*.go",
      "path": "/source/head",
      "pattern": "annotationDirectNodeUID|labelOriginalNodeName"
    },
    "output": "Found 17 matches\n/source/head/labruntime/clabernetes/names.go:\n  Line 51: \t\tif nodeDefinition.Labels[labelOriginalNodeName] != originalLabel {\n\n  Line 55: \t\t\tnodeDefinition.Labels[labelOriginalNodeName] = originalLabel\n\n\n/source/head/labruntime/clabernetes/capture.go:\n  Line 328: \t\tif original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != \"\" {\n\n\n/source/head/labruntime/clabernetes/clabernetes.go:\n  Line 34: \tlabelOriginalNodeName = \"c9s.run/originalNodeName\"\n\n  Line 40: \t// annotationDirectNodeUID names the UID of the Node a c9s pod runs.\n\n  Line 41: \tannotationDirectNodeUID = \"c9s.run/direct-node-uid\"\n\n\n/source/head/labruntime/clabernetes/event_parity_test.go:\n  Line 484: \t\t\t\tlabelTopologyOwner: \"lab1\", labelOriginalNodeName: strings.ToUpper(name),\n\n  Line 999: \tpod.Annotations[annotationDirectNodeUID] = uid\n\n\n/source/head/labruntime/clabernetes/state.go:\n  Line 54: \tif original := nodeResource.GetLabels()[labelOriginalNodeName]; original != node.Name {\n\n  Line 227: \t\tif uid := pods.Items[idx].Annotations[annotationDirectNodeUID]; uid != \"\" {\n\n\n/source/head/labruntime/clabernetes/nodes_test.go:\n  Line 800: \t\t\t\tif obj.GetLabels()[labelOriginalNodeName] == \"\" {\n\n  Line 801: \t\t\t\t\tt.Errorf(\"Node %s lost its %s label\", obj.GetName(), labelOriginalNodeName)\n\n\n/source/head/labruntime/clabernetes/capture_test.go:\n  Line 29: \t\tlabels[labelOriginalNodeName] = original\n\n\n/source/head/labruntime/clabernetes/clabernetes_test.go:\n  Line 2360: \t\tif got := labels[labelOriginalNodeName]; got != originalName {\n\n  Line 2364: \t\t\t\tlabelOriginalNodeName,\n\n  Line 2464: \t\tif got := node.GetLabels()[labelOriginalNodeName]; got != originalName {\n\n  Line 2468: \t\t\t\tlabelOriginalNodeName,\n",
    "title": "annotationDirectNodeUID|labelOriginalNodeName",
    "metadata": {
      "matches": 17,
      "truncated": false
    },
    "time": {
      "start": 1793525779803,
      "end": 1793525779824
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196778d73001JdkUaZawYEklCY",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967774e8001BGGnQCqx3hEnno",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 59957,
    "input": 12241,
    "output": 74,
    "reasoning": 538,
    "cache": {
      "read": 47104,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1967774e8001BGGnQCqx3hEnno",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525773544,
    "completed": 1793525779831
  },
  "parentID": "msg_19676df9500159h7P3dGcuBxjO",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 59957,
    "input": 12241,
    "output": 74,
    "reasoning": 538,
    "cache": {
      "read": 47104,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 20
step-start
{
  "type": "step-start",
  "id": "prt_1967799140013s9zkU7b3z50VL",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196778d7e001SINK9sXOPv8V7M"
}
Reasoning
`annotationDirectNodeUID` = "c9s.run/direct-node-uid" — it's defined in this repo's clabernetes.go as a constant that names a c9s controller annotation. It's set by the c9s controller (external), consumed here. Fine.

Note the manifest's "changed" list has 26 entries; the "files" list includes the whole repo (extra files listed under head files, e.g. docs and schemas, but those aren't changed). The changed list I now have complete:
1. core/events/netlink.go M
2. core/events/parity_test.go A
3. core/events/stream.go M
4. core/labruntime.go M
5. core/labruntime_gaps_test.go M
6. docs/cmd/events.md M
7. docs/cmd/inspect/interfaces.md M
8. docs/manual/clabernetes/runtime.md M
9. labruntime/clabernetes/capture.go M
10. capture_interfaces.go M
11. capture_test.go M
12. clabernetes.go M
13. clabernetes_test.go M
14. container_events.go A
15. event_parity_test.go A
16. events.go M
17. iface_stats.go M
18. manifests.go M
19. plan.go M
20. primitives.go M
21. reconcile.go M
22. runtime_gaps_test.go M
23. state.go M
24. topology.go M
25. labruntime/runtime.go M
26. tests/14-clabernetes/01-linux-lifecycle.robot M

I need to see the diff for the parts I haven't seen in diff.txt: the diff is 5138 lines total and I've read 1-1300 (first session), 1362-2845, 2845-4396, 4396-5138. I may have missed 1300-1362. Let me read that gap.

Then remaining head files to inspect:
- state.go (full)
- clabernetes.go (constants)
- manifests.go, plan.go, primitives.go, reconcile.go (topo file annotation changes)
- capture.go / capture_interfaces.go (listPodInterfaces refactor)
- core/labruntime.go lines 1-440 (context, TopoFile label etc.)
- runtime.go full? We saw diff parts.
- Tests: parity_test.go, event_parity_test.go, labruntime_gaps_test.go, runtime_gaps_test.go, clabernetes_test.go (big), capture_test.go.
- Docs: events.md, interfaces.md, runtime.md.

Let me read diff gap first, plus state.go.
The manifest confirms26 changed paths. Let me fill the diff gap (lines ~1300-1362) and read `state.go`.
read · completed

Input

{
  "filePath": "/source/diff.txt",
  "limit": 80,
  "offset": 1284
}

Output

<path>/source/diff.txt</path>
<type>file</type>
<content>
1284: +    "name": "clos-srl1",
1285: +    "lab": "clos",
1286: +    "node": "srl1",
1287: +    "namespace": "c9s-clos",
1288: +    "pod": "srl1-7d9c6b5f4-x2k8p"
1289: +  }
1290: +}
1291: +```
1292: +
1293: +- The actor ID is the node's `<namespace>/<lab>/<node>` ID, the `container_id`
1294: +  inspect reports, and `actor_name` and `name` are the inspect `name`.
1295: +- `clab-node-name` is the node name as the topology spells it.
1296: +- `clab-topo-file` is the file the lab was deployed from (see
1297: +  [Topology file](#topology-file)).
1298: +- `state` is the container state after the event: `created`, `running` or
1299: +  `exited`. Docker leaves it to the client to derive it from the action; c9s
1300: +  reports it on every container event.
1301: +- `ports` lists the node's exposed ports without a host binding: they are
1302: +  reached through the node's Service or a port-forward, not on a port of the
1303: +  local machine.
1304: +- `kill` carries `signal` `15`; Kubernetes stops containers with SIGTERM.
1305: +- `create` can come before the controller has allocated the node's management
1306: +  address and Service, so it may lack `mgmt_ipv4`, `mgmt_ipv6` and `ports`;
1307: +  the following events carry them.
1308: +- `namespace`, `lab`, `node` and `pod` are c9s attributes on top.
1309: +
1310: +Docker attributes c9s does not report: `scope`, `clab-mgmt-net-bridge` (no
1311: +Docker bridge), `clab-node-lab-dir` (a c9s lab has no lab directory on the
1312: +deploying machine; node state lives in the cluster), and `exitCode` and
1313: +`execDuration` on `die`. `clab-node-type` and `clab-node-group` are reported
1314: +when the topology sets them, and with `-t` also a kind's default type; read by
1315: +`--name` alone, a default type such as SR Linux's `ixr-d2l` is not known.
1316:  
1317:  ### Interface events
1318:  
1319:  Containerlab samples the interfaces of every running node by exec into its
1320:  device container. One exec per node and interval reads `/proc/net/dev` and
1321:  `/sys/class/net/*/operstate` (with index, MTU, MAC address, flags and alias).
1322: -All containers of a device pod share one network namespace, so the samples
1323: -cover the node's pod interfaces.
1324:  
1325: -Interface state events are always streamed. They use the same schema as the
1326: -interface events of the local runtimes, with the operational state as action:
1327: +It reports the interfaces a Docker container of the same node kind has, named
1328: +as in that container:
1329: +
1330: +- the node's lab link interfaces, with the names and aliases clabwire lists for
1331: +  them (`containerlab capture --list`): `eth1` for a linux node, `e1-1` with
1332: +  alias `ethernet-1/1` for SR Linux, so a client finds a link's interface by
1333: +  the endpoint name in the topology or its alias
1334: +- the management interface `eth0`
1335: +- the loopback `lo`
1336: +
1337: +The pod's own interfaces (the pod network interface `c9s0`, clabernetes'
1338: +interposition interfaces `c9sr0` and `c9sm0`, and the link transport interfaces
1339: +`c9ss*`) are not reported, and neither are the aliases clabernetes sets for its
1340: +own use (`c9s:…`).
1341: +
1342: +Interface state events are always streamed, with the actions and attributes of
1343: +the local runtimes' netlink events:
1344:  
1345:  ```json
1346:  {
1347:    "timestamp": "2026-10-27T10:15:02.123456789Z",
1348:    "type": "interface",
1349: -  "action": "down",
1350: +  "action": "update",
1351:    "actor_id": "c9s-clos/clos/srl1",
1352:    "actor_name": "clos-srl1",
1353: -  "actor_full_id": "srl1-7d9c6b5f4-x2k8p",
1354: +  "actor_full_id": "c9s-clos/clos/srl1",
1355:    "attributes": {
1356:      "ifname": "e1-1",
1357: -    "state": "lowerlayerdown",
1358: +    "alias": "ethernet-1/1",
1359: +    "state": "lower-layer-down",
1360: +    "type": "veth",
1361:      "index": "7",
1362:      "mtu": "9232",
1363:      "mac": "aa:c1:ab:5e:2f:01",

(Showing lines 1284-1363 of 5138. Use offset=1364 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19677a5c6001lKtV5ApZ6UxF7Q",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196778d7e001SINK9sXOPv8V7M",
  "callID": "call_e37ddf5a77db4bd482f5e138",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/diff.txt",
      "limit": 80,
      "offset": 1284
    },
    "output": "<path>/source/diff.txt</path>\n<type>file</type>\n<content>\n1284: +    \"name\": \"clos-srl1\",\n1285: +    \"lab\": \"clos\",\n1286: +    \"node\": \"srl1\",\n1287: +    \"namespace\": \"c9s-clos\",\n1288: +    \"pod\": \"srl1-7d9c6b5f4-x2k8p\"\n1289: +  }\n1290: +}\n1291: +```\n1292: +\n1293: +- The actor ID is the node's `<namespace>/<lab>/<node>` ID, the `container_id`\n1294: +  inspect reports, and `actor_name` and `name` are the inspect `name`.\n1295: +- `clab-node-name` is the node name as the topology spells it.\n1296: +- `clab-topo-file` is the file the lab was deployed from (see\n1297: +  [Topology file](#topology-file)).\n1298: +- `state` is the container state after the event: `created`, `running` or\n1299: +  `exited`. Docker leaves it to the client to derive it from the action; c9s\n1300: +  reports it on every container event.\n1301: +- `ports` lists the node's exposed ports without a host binding: they are\n1302: +  reached through the node's Service or a port-forward, not on a port of the\n1303: +  local machine.\n1304: +- `kill` carries `signal` `15`; Kubernetes stops containers with SIGTERM.\n1305: +- `create` can come before the controller has allocated the node's management\n1306: +  address and Service, so it may lack `mgmt_ipv4`, `mgmt_ipv6` and `ports`;\n1307: +  the following events carry them.\n1308: +- `namespace`, `lab`, `node` and `pod` are c9s attributes on top.\n1309: +\n1310: +Docker attributes c9s does not report: `scope`, `clab-mgmt-net-bridge` (no\n1311: +Docker bridge), `clab-node-lab-dir` (a c9s lab has no lab directory on the\n1312: +deploying machine; node state lives in the cluster), and `exitCode` and\n1313: +`execDuration` on `die`. `clab-node-type` and `clab-node-group` are reported\n1314: +when the topology sets them, and with `-t` also a kind's default type; read by\n1315: +`--name` alone, a default type such as SR Linux's `ixr-d2l` is not known.\n1316:  \n1317:  ### Interface events\n1318:  \n1319:  Containerlab samples the interfaces of every running node by exec into its\n1320:  device container. One exec per node and interval reads `/proc/net/dev` and\n1321:  `/sys/class/net/*/operstate` (with index, MTU, MAC address, flags and alias).\n1322: -All containers of a device pod share one network namespace, so the samples\n1323: -cover the node's pod interfaces.\n1324:  \n1325: -Interface state events are always streamed. They use the same schema as the\n1326: -interface events of the local runtimes, with the operational state as action:\n1327: +It reports the interfaces a Docker container of the same node kind has, named\n1328: +as in that container:\n1329: +\n1330: +- the node's lab link interfaces, with the names and aliases clabwire lists for\n1331: +  them (`containerlab capture --list`): `eth1` for a linux node, `e1-1` with\n1332: +  alias `ethernet-1/1` for SR Linux, so a client finds a link's interface by\n1333: +  the endpoint name in the topology or its alias\n1334: +- the management interface `eth0`\n1335: +- the loopback `lo`\n1336: +\n1337: +The pod's own interfaces (the pod network interface `c9s0`, clabernetes'\n1338: +interposition interfaces `c9sr0` and `c9sm0`, and the link transport interfaces\n1339: +`c9ss*`) are not reported, and neither are the aliases clabernetes sets for its\n1340: +own use (`c9s:…`).\n1341: +\n1342: +Interface state events are always streamed, with the actions and attributes of\n1343: +the local runtimes' netlink events:\n1344:  \n1345:  ```json\n1346:  {\n1347:    \"timestamp\": \"2026-10-27T10:15:02.123456789Z\",\n1348:    \"type\": \"interface\",\n1349: -  \"action\": \"down\",\n1350: +  \"action\": \"update\",\n1351:    \"actor_id\": \"c9s-clos/clos/srl1\",\n1352:    \"actor_name\": \"clos-srl1\",\n1353: -  \"actor_full_id\": \"srl1-7d9c6b5f4-x2k8p\",\n1354: +  \"actor_full_id\": \"c9s-clos/clos/srl1\",\n1355:    \"attributes\": {\n1356:      \"ifname\": \"e1-1\",\n1357: -    \"state\": \"lowerlayerdown\",\n1358: +    \"alias\": \"ethernet-1/1\",\n1359: +    \"state\": \"lower-layer-down\",\n1360: +    \"type\": \"veth\",\n1361:      \"index\": \"7\",\n1362:      \"mtu\": \"9232\",\n1363:      \"mac\": \"aa:c1:ab:5e:2f:01\",\n\n(Showing lines 1284-1363 of 5138. Use offset=1364 to continue.)\n</content>",
    "title": "source/diff.txt",
    "metadata": {
      "preview": "+    \"name\": \"clos-srl1\",\n+    \"lab\": \"clos\",\n+    \"node\": \"srl1\",\n+    \"namespace\": \"c9s-clos\",\n+    \"pod\": \"srl1-7d9c6b5f4-x2k8p\"\n+  }\n+}\n+```\n+\n+- The actor ID is the node's `<namespace>/<lab>/<node>` ID, the `container_id`\n+  inspect reports, and `actor_name` and `name` are the inspect `name`.\n+- `clab-node-name` is the node name as the topology spells it.\n+- `clab-topo-file` is the file the lab was deployed from (see\n+  [Topology file](#topology-file)).\n+- `state` is the container state after the event: `created`, `running` or\n+  `exited`. Docker leaves it to the client to derive it from the action; c9s\n+  reports it on every container event.\n+- `ports` lists the node's exposed ports without a host binding: they are\n+  reached through the node's Service or a port-forward, not on a port of the\n+  local machine.",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/diff.txt",
        "text": "+    \"name\": \"clos-srl1\",\n+    \"lab\": \"clos\",\n+    \"node\": \"srl1\",\n+    \"namespace\": \"c9s-clos\",\n+    \"pod\": \"srl1-7d9c6b5f4-x2k8p\"\n+  }\n+}\n+```\n+\n+- The actor ID is the node's `<namespace>/<lab>/<node>` ID, the `container_id`\n+  inspect reports, and `actor_name` and `name` are the inspect `name`.\n+- `clab-node-name` is the node name as the topology spells it.\n+- `clab-topo-file` is the file the lab was deployed from (see\n+  [Topology file](#topology-file)).\n+- `state` is the container state after the event: `created`, `running` or\n+  `exited`. Docker leaves it to the client to derive it from the action; c9s\n+  reports it on every container event.\n+- `ports` lists the node's exposed ports without a host binding: they are\n+  reached through the node's Service or a port-forward, not on a port of the\n+  local machine.\n+- `kill` carries `signal` `15`; Kubernetes stops containers with SIGTERM.\n+- `create` can come before the controller has allocated the node's management\n+  address and Service, so it may lack `mgmt_ipv4`, `mgmt_ipv6` and `ports`;\n+  the following events carry them.\n+- `namespace`, `lab`, `node` and `pod` are c9s attributes on top.\n+\n+Docker attributes c9s does not report: `scope`, `clab-mgmt-net-bridge` (no\n+Docker bridge), `clab-node-lab-dir` (a c9s lab has no lab directory on the\n+deploying machine; node state lives in the cluster), and `exitCode` and\n+`execDuration` on `die`. `clab-node-type` and `clab-node-group` are reported\n+when the topology sets them, and with `-t` also a kind's default type; read by\n+`--name` alone, a default type such as SR Linux's `ixr-d2l` is not known.\n \n ### Interface events\n \n Containerlab samples the interfaces of every running node by exec into its\n device container. One exec per node and interval reads `/proc/net/dev` and\n `/sys/class/net/*/operstate` (with index, MTU, MAC address, flags and alias).\n-All containers of a device pod share one network namespace, so the samples\n-cover the node's pod interfaces.\n \n-Interface state events are always streamed. They use the same schema as the\n-interface events of the local runtimes, with the operational state as action:\n+It reports the interfaces a Docker container of the same node kind has, named\n+as in that container:\n+\n+- the node's lab link interfaces, with the names and aliases clabwire lists for\n+  them (`containerlab capture --list`): `eth1` for a linux node, `e1-1` with\n+  alias `ethernet-1/1` for SR Linux, so a client finds a link's interface by\n+  the endpoint name in the topology or its alias\n+- the management interface `eth0`\n+- the loopback `lo`\n+\n+The pod's own interfaces (the pod network interface `c9s0`, clabernetes'\n+interposition interfaces `c9sr0` and `c9sm0`, and the link transport interfaces\n+`c9ss*`) are not reported, and neither are the aliases clabernetes sets for its\n+own use (`c9s:…`).\n+\n+Interface state events are always streamed, with the actions and attributes of\n+the local runtimes' netlink events:\n \n ```json\n {\n   \"timestamp\": \"2026-10-27T10:15:02.123456789Z\",\n   \"type\": \"interface\",\n-  \"action\": \"down\",\n+  \"action\": \"update\",\n   \"actor_id\": \"c9s-clos/clos/srl1\",\n   \"actor_name\": \"clos-srl1\",\n-  \"actor_full_id\": \"srl1-7d9c6b5f4-x2k8p\",\n+  \"actor_full_id\": \"c9s-clos/clos/srl1\",\n   \"attributes\": {\n     \"ifname\": \"e1-1\",\n-    \"state\": \"lowerlayerdown\",\n+    \"alias\": \"ethernet-1/1\",\n+    \"state\": \"lower-layer-down\",\n+    \"type\": \"veth\",\n     \"index\": \"7\",\n     \"mtu\": \"9232\",\n     \"mac\": \"aa:c1:ab:5e:2f:01\",",
        "lineStart": 1284,
        "lineEnd": 1363,
        "totalLines": 5138,
        "truncated": true
      }
    },
    "time": {
      "start": 1793525786059,
      "end": 1793525786074
    }
  }
}
read · completed

Input

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

Output

<path>/source/head/labruntime/clabernetes/state.go</path>
<type>file</type>
<content>
1: package clabernetes
2: 
3: import (
4: 	"context"
5: 	"fmt"
6: 	"sort"
7: 	"strings"
8: 
9: 	clabconstants "github.com/srl-labs/containerlab/constants"
10: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
11: 	corev1 "k8s.io/api/core/v1"
12: 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
13: 	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
14: 	"k8s.io/apimachinery/pkg/labels"
15: )
16: 
17: func stateFromNodeResources(
18: 	name,
19: 	namespace string,
20: 	nodeResources []unstructured.Unstructured,
21: ) *clablabruntime.LabState {
22: 	state := &clablabruntime.LabState{
23: 		Name:         name,
24: 		Namespace:    namespace,
25: 		TopologyPath: fmt.Sprintf("k8s://%s/labs/%s", namespace, name),
26: 	}
27: 	// Without a Topology resource the Nodes record the file the lab was deployed from.
28: 	for idx := range nodeResources {
29: 		if path := nodeResources[idx].GetAnnotations()[annotationTopologyFile]; path != "" {
30: 			state.TopologyPath = path
31: 			break
32: 		}
33: 	}
34: 	if len(nodeResources) != 0 {
35: 		state.Owner = nodeResources[0].GetLabels()[clabconstants.Owner]
36: 		if state.Owner == "" {
37: 			state.Owner = nodeResources[0].GetAnnotations()[clabconstants.Owner]
38: 		}
39: 	}
40: 
41: 	state.Nodes = make([]clablabruntime.NodeState, 0, len(nodeResources))
42: 	for idx := range nodeResources {
43: 		state.Nodes = append(state.Nodes, nodeStateFromResource(&nodeResources[idx]))
44: 	}
45: 
46: 	return state
47: }
48: 
49: func nodeStateFromResource(nodeResource *unstructured.Unstructured) clablabruntime.NodeState {
50: 	node := clablabruntime.NodeState{
51: 		Name:    nodeResource.GetName(),
52: 		NodeUID: string(nodeResource.GetUID()),
53: 	}
54: 	if original := nodeResource.GetLabels()[labelOriginalNodeName]; original != node.Name {
55: 		node.TopologyName = original
56: 	}
57: 	node.ExposedPorts = nodeExposedPorts(nodeResource)
58: 	// The same container exec targets: the observed primary device container.
59: 	node.Container, _ = preferredDeviceContainerName(nodeResource, node.Name)
60: 	node.Kind, _, _ = unstructured.NestedString(nodeResource.Object, "spec", "kind")
61: 	node.Image, _, _ = unstructured.NestedString(nodeResource.Object, "spec", "image")
62: 	node.Type, _, _ = unstructured.NestedString(nodeResource.Object, "spec", "type")
63: 	node.Group, _, _ = unstructured.NestedString(nodeResource.Object, "spec", "group")
64: 	node.State, _, _ = unstructured.NestedString(nodeResource.Object, "status", "readiness")
65: 	node.Ready = node.State == "ready"
66: 	node.LoadBalancerAddress, _, _ = unstructured.NestedString(
67: 		nodeResource.Object,
68: 		"status",
69: 		"exposedPorts",
70: 		"loadBalancerAddress",
71: 	)
72: 	node.MgmtIPv4Address, _, _ = unstructured.NestedString(
73: 		nodeResource.Object,
74: 		"status",
75: 		"directManagement",
76: 		"ipv4",
77: 	)
78: 	node.MgmtIPv6Address, _, _ = unstructured.NestedString(
79: 		nodeResource.Object,
80: 		"status",
81: 		"directManagement",
82: 		"ipv6",
83: 	)
84: 
85: 	return node
86: }
87: 
88: // nodeExposedPorts reads the expose-port allocations the controller published on the Node.
89: func nodeExposedPorts(nodeResource *unstructured.Unstructured) []clablabruntime.ExposedPort {
90: 	rawPorts, _, _ := unstructured.NestedSlice(
91: 		nodeResource.Object,
92: 		"status",
93: 		"exposedPorts",
94: 		"ports",
95: 	)
96: 
97: 	ports := make([]clablabruntime.ExposedPort, 0, len(rawPorts))
98: 	for _, raw := range rawPorts {
99: 		entry, ok := raw.(map[string]any)
100: 		if !ok {
101: 			continue
102: 		}
103: 
104: 		port := clablabruntime.ExposedPort{
105: 			Port:       intField(entry["destinationPort"]),
106: 			ExposePort: intField(entry["exposePort"]),
107: 			Protocol:   strings.ToLower(fmt.Sprint(entry["protocol"])),
108: 		}
109: 		if port.Port == 0 {
110: 			continue
111: 		}
112: 		if port.Protocol == "" || port.Protocol == "<nil>" {
113: 			port.Protocol = "tcp"
114: 		}
115: 
116: 		ports = append(ports, port)
117: 	}
118: 
119: 	if len(ports) == 0 {
120: 		return nil
121: 	}
122: 
123: 	sort.Slice(ports, func(i, j int) bool {
124: 		if ports[i].Port == ports[j].Port {
125: 			return ports[i].Protocol < ports[j].Protocol
126: 		}
127: 
128: 		return ports[i].Port < ports[j].Port
129: 	})
130: 
131: 	return ports
132: }
133: 
134: func intField(value any) int {
135: 	switch v := value.(type) {
136: 	case int64:
137: 		return int(v)
138: 	case int:
139: 		return v
140: 	case int32:
141: 		return int(v)
142: 	case float64:
143: 		return int(v)
144: 	default:
145: 		return 0
146: 	}
147: }
148: 
149: // newestPod prefers a pod that is not being deleted, then a running pod and, among equals, the
150: // newest one: several pods can match a node during a rolling update or a restart, when the old
151: // pod terminates while its replacement starts.
152: func newestPod(current, candidate *corev1.Pod) *corev1.Pod {
153: 	if current == nil {
154: 		return candidate
155: 	}
156: 
157: 	currentDeleting := current.DeletionTimestamp != nil
158: 	candidateDeleting := candidate.DeletionTimestamp != nil
159: 	if currentDeleting != candidateDeleting {
160: 		if candidateDeleting {
161: 			return current
162: 		}
163: 
164: 		return candidate
165: 	}
166: 
167: 	currentRunning := current.Status.Phase == corev1.PodRunning
168: 	candidateRunning := candidate.Status.Phase == corev1.PodRunning
169: 	if currentRunning != candidateRunning {
170: 		if candidateRunning {
171: 			return candidate
172: 		}
173: 
174: 		return current
175: 	}
176: 
177: 	if candidate.CreationTimestamp.After(current.CreationTimestamp.Time) {
178: 		return candidate
179: 	}
180: 
181: 	return current
182: }
183: 
184: func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabState) error {
185: 	if state == nil || state.Name == "" {
186: 		return nil
187: 	}
188: 
189: 	nodeResources, err := r.nodesForTopology(ctx, state.Name, state.Namespace)
190: 	if err != nil {
191: 		return err
192: 	}
193: 
194: 	nodesByName := map[string]clablabruntime.NodeState{}
195: 	for _, node := range state.Nodes {
196: 		nodesByName[node.Name] = node
197: 	}
198: 
199: 	networkModes := make(map[string]string, len(nodeResources.Items))
200: 	resourcesByName := make(map[string]*unstructured.Unstructured, len(nodeResources.Items))
201: 	for idx := range nodeResources.Items {
202: 		nodeResource := &nodeResources.Items[idx]
203: 		nodesByName[nodeResource.GetName()] = nodeStateFromResource(nodeResource)
204: 		networkModes[nodeResource.GetName()] = nodeNetworkMode(nodeResource)
205: 		resourcesByName[nodeResource.GetName()] = nodeResource
206: 	}
207: 
208: 	pods, err := r.kubeClient.CoreV1().Pods(state.Namespace).List(ctx, metav1.ListOptions{
209: 		LabelSelector: labels.Set{
210: 			labelApp:           clabernetesAppValue,
211: 			labelTopologyOwner: state.Name,
212: 		}.String(),
213: 	})
214: 	if err != nil {
215: 		return fmt.Errorf("failed to list clabernetes pods for topology %s/%s: %w",
216: 			state.Namespace, state.Name, err)
217: 	}
218: 
219: 	podsByNode := map[string]*corev1.Pod{}
220: 	for idx := range pods.Items {
221: 		nodeName := pods.Items[idx].Labels[labelTopologyNode]
222: 		if nodeName == "" {
223: 			continue
224: 		}
225: 		// A pod of an earlier Node of the same name (a redeploy while the old pod still
226: 		// terminates) is not this node's pod.
227: 		if uid := pods.Items[idx].Annotations[annotationDirectNodeUID]; uid != "" {
228: 			if resource := resourcesByName[nodeName]; resource != nil &&
229: 				string(resource.GetUID()) != uid {
230: 				continue
231: 			}
232: 		}
233: 		podsByNode[nodeName] = newestPod(podsByNode[nodeName], &pods.Items[idx])
234: 	}
235: 
236: 	// The Node's status.readiness is the authoritative device signal. The primary Node's run
237: 	// state governs the pod a group of nodes shares: a stopped primary stops the whole group.
238: 	// Nodes without readiness yet report their pod phase.
239: 	for nodeName, node := range nodesByName {
240: 		primary := resolvePrimaryNode(nodeName, networkModes)
241: 		primaryResource := resourcesByName[primary]
242: 		stopRequested := primaryResource != nil &&
243: 			nodeRunState(primaryResource) == nodeRunStateStopped
244: 		if stopRequested {
245: 			node.State = "stopping"
246: 			if condition := nodeCondition(
247: 				primaryResource,
248: 				nodeConditionStopped,
249: 			); condition != nil &&
250: 				condition.status == string(metav1.ConditionTrue) {
251: 				node.State = "stopped"
252: 			}
253: 			node.Ready = false
254: 		} else if pod := podsByNode[primary]; node.State == "" && pod != nil &&
255: 			pod.Status.Phase != "" {
256: 			node.State = strings.ToLower(string(pod.Status.Phase))
257: 		}
258: 		node.ContainerState = nodeContainerState(stopRequested, podsByNode[primary])
259: 		if node.ContainerState == clablabruntime.ContainerStateRunning {
260: 			node.Health = nodeHealth(node, resourcesByName[nodeName])
261: 		}
262: 		nodesByName[nodeName] = node
263: 	}
264: 
265: 	// Nodes grouped through network-mode container: share the pod of the group's primary
266: 	// node. Before the controller observed the device containers, the pod's default-container
267: 	// annotation names the primary node's container.
268: 	for nodeName, node := range nodesByName {
269: 		primary := resolvePrimaryNode(nodeName, networkModes)
270: 		pod := podsByNode[primary]
271: 		if pod == nil {
272: 			continue
273: 		}
274: 
275: 		node.Pod = pod.Name
276: 		if node.Container == "" && primary == nodeName {
277: 			node.Container = pod.Annotations[defaultContainerAnnotation]
278: 		}
279: 		nodesByName[nodeName] = node
280: 	}
281: 
282: 	nodeNames := make([]string, 0, len(nodesByName))
283: 	for nodeName := range nodesByName {
284: 		nodeNames = append(nodeNames, nodeName)
285: 	}
286: 	sort.Strings(nodeNames)
287: 
288: 	state.Nodes = make([]clablabruntime.NodeState, 0, len(nodeNames))
289: 	allReady := len(nodeNames) > 0 // codespell:ignore allready
290: 	allStopped := len(nodeNames) > 0
291: 	for _, nodeName := range nodeNames {
292: 		node := nodesByName[nodeName]
293: 		state.Nodes = append(state.Nodes, node)
294: 		allReady = allReady && node.Ready // codespell:ignore allready
295: 		allStopped = allStopped && node.State == "stopped"
296: 	}
297: 
298: 	switch {
299: 	case allReady: // codespell:ignore allready
300: 		state.State = "running"
301: 		state.Ready = true
302: 	case allStopped:
303: 		state.State = "stopped"
304: 		state.Ready = false
305: 	case len(nodeNames) != 0:
306: 		state.State = "partial"
307: 		state.Ready = false
308: 	}
309: 
310: 	return nil
311: }
312: 
313: // nodeContainerState is the state of a node in container runtime terms, from its pod: created
314: // while the pod is scheduled and prepared (init containers), running once the device containers
315: // run, and exited once the node was stopped, its pod is being deleted, or the pod ended. Between
316: // the pods of a restart the node is exited, then created.
317: func nodeContainerState(stopRequested bool, pod *corev1.Pod) string {
318: 	switch {
319: 	case pod == nil && stopRequested:
320: 		return clablabruntime.ContainerStateExited
321: 	case pod == nil:
322: 		return clablabruntime.ContainerStateCreated
323: 	case stopRequested || pod.DeletionTimestamp != nil:
324: 		return clablabruntime.ContainerStateExited
325: 	}
326: 
327: 	switch pod.Status.Phase {
328: 	case corev1.PodRunning:
329: 		return clablabruntime.ContainerStateRunning
330: 	case corev1.PodSucceeded, corev1.PodFailed:
331: 		return clablabruntime.ContainerStateExited
332: 	default:
333: 		return clablabruntime.ContainerStateCreated
334: 	}
335: }
336: 
337: // nodeHealth is the health of a running node: healthy once the Node is ready or its device
338: // containers are, starting before. Device containers are the analogue of a container
339: // healthcheck: a node whose links wait for a stopped peer is not ready, but its device is.
340: func nodeHealth(node clablabruntime.NodeState, resource *unstructured.Unstructured) string {
341: 	if node.Ready {
342: 		return clablabruntime.ContainerHealthHealthy
343: 	}
344: 	if resource != nil {
345: 		if condition := nodeCondition(resource, nodeConditionContainersReady); condition != nil &&
346: 			condition.status == string(metav1.ConditionTrue) {
347: 			return clablabruntime.ContainerHealthHealthy
348: 		}
349: 	}
350: 
351: 	return clablabruntime.ContainerHealthStarting
352: }

(End of file - total 352 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19677a5e9001OFjm6PPLX17VdV",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196778d7e001SINK9sXOPv8V7M",
  "callID": "call_e5f6bd199bb343ad8e5427ec",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/state.go"
    },
    "output": "<path>/source/head/labruntime/clabernetes/state.go</path>\n<type>file</type>\n<content>\n1: package clabernetes\n2: \n3: import (\n4: \t\"context\"\n5: \t\"fmt\"\n6: \t\"sort\"\n7: \t\"strings\"\n8: \n9: \tclabconstants \"github.com/srl-labs/containerlab/constants\"\n10: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n11: \tcorev1 \"k8s.io/api/core/v1\"\n12: \tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n13: \t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n14: \t\"k8s.io/apimachinery/pkg/labels\"\n15: )\n16: \n17: func stateFromNodeResources(\n18: \tname,\n19: \tnamespace string,\n20: \tnodeResources []unstructured.Unstructured,\n21: ) *clablabruntime.LabState {\n22: \tstate := &clablabruntime.LabState{\n23: \t\tName:         name,\n24: \t\tNamespace:    namespace,\n25: \t\tTopologyPath: fmt.Sprintf(\"k8s://%s/labs/%s\", namespace, name),\n26: \t}\n27: \t// Without a Topology resource the Nodes record the file the lab was deployed from.\n28: \tfor idx := range nodeResources {\n29: \t\tif path := nodeResources[idx].GetAnnotations()[annotationTopologyFile]; path != \"\" {\n30: \t\t\tstate.TopologyPath = path\n31: \t\t\tbreak\n32: \t\t}\n33: \t}\n34: \tif len(nodeResources) != 0 {\n35: \t\tstate.Owner = nodeResources[0].GetLabels()[clabconstants.Owner]\n36: \t\tif state.Owner == \"\" {\n37: \t\t\tstate.Owner = nodeResources[0].GetAnnotations()[clabconstants.Owner]\n38: \t\t}\n39: \t}\n40: \n41: \tstate.Nodes = make([]clablabruntime.NodeState, 0, len(nodeResources))\n42: \tfor idx := range nodeResources {\n43: \t\tstate.Nodes = append(state.Nodes, nodeStateFromResource(&nodeResources[idx]))\n44: \t}\n45: \n46: \treturn state\n47: }\n48: \n49: func nodeStateFromResource(nodeResource *unstructured.Unstructured) clablabruntime.NodeState {\n50: \tnode := clablabruntime.NodeState{\n51: \t\tName:    nodeResource.GetName(),\n52: \t\tNodeUID: string(nodeResource.GetUID()),\n53: \t}\n54: \tif original := nodeResource.GetLabels()[labelOriginalNodeName]; original != node.Name {\n55: \t\tnode.TopologyName = original\n56: \t}\n57: \tnode.ExposedPorts = nodeExposedPorts(nodeResource)\n58: \t// The same container exec targets: the observed primary device container.\n59: \tnode.Container, _ = preferredDeviceContainerName(nodeResource, node.Name)\n60: \tnode.Kind, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"kind\")\n61: \tnode.Image, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"image\")\n62: \tnode.Type, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"type\")\n63: \tnode.Group, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"group\")\n64: \tnode.State, _, _ = unstructured.NestedString(nodeResource.Object, \"status\", \"readiness\")\n65: \tnode.Ready = node.State == \"ready\"\n66: \tnode.LoadBalancerAddress, _, _ = unstructured.NestedString(\n67: \t\tnodeResource.Object,\n68: \t\t\"status\",\n69: \t\t\"exposedPorts\",\n70: \t\t\"loadBalancerAddress\",\n71: \t)\n72: \tnode.MgmtIPv4Address, _, _ = unstructured.NestedString(\n73: \t\tnodeResource.Object,\n74: \t\t\"status\",\n75: \t\t\"directManagement\",\n76: \t\t\"ipv4\",\n77: \t)\n78: \tnode.MgmtIPv6Address, _, _ = unstructured.NestedString(\n79: \t\tnodeResource.Object,\n80: \t\t\"status\",\n81: \t\t\"directManagement\",\n82: \t\t\"ipv6\",\n83: \t)\n84: \n85: \treturn node\n86: }\n87: \n88: // nodeExposedPorts reads the expose-port allocations the controller published on the Node.\n89: func nodeExposedPorts(nodeResource *unstructured.Unstructured) []clablabruntime.ExposedPort {\n90: \trawPorts, _, _ := unstructured.NestedSlice(\n91: \t\tnodeResource.Object,\n92: \t\t\"status\",\n93: \t\t\"exposedPorts\",\n94: \t\t\"ports\",\n95: \t)\n96: \n97: \tports := make([]clablabruntime.ExposedPort, 0, len(rawPorts))\n98: \tfor _, raw := range rawPorts {\n99: \t\tentry, ok := raw.(map[string]any)\n100: \t\tif !ok {\n101: \t\t\tcontinue\n102: \t\t}\n103: \n104: \t\tport := clablabruntime.ExposedPort{\n105: \t\t\tPort:       intField(entry[\"destinationPort\"]),\n106: \t\t\tExposePort: intField(entry[\"exposePort\"]),\n107: \t\t\tProtocol:   strings.ToLower(fmt.Sprint(entry[\"protocol\"])),\n108: \t\t}\n109: \t\tif port.Port == 0 {\n110: \t\t\tcontinue\n111: \t\t}\n112: \t\tif port.Protocol == \"\" || port.Protocol == \"<nil>\" {\n113: \t\t\tport.Protocol = \"tcp\"\n114: \t\t}\n115: \n116: \t\tports = append(ports, port)\n117: \t}\n118: \n119: \tif len(ports) == 0 {\n120: \t\treturn nil\n121: \t}\n122: \n123: \tsort.Slice(ports, func(i, j int) bool {\n124: \t\tif ports[i].Port == ports[j].Port {\n125: \t\t\treturn ports[i].Protocol < ports[j].Protocol\n126: \t\t}\n127: \n128: \t\treturn ports[i].Port < ports[j].Port\n129: \t})\n130: \n131: \treturn ports\n132: }\n133: \n134: func intField(value any) int {\n135: \tswitch v := value.(type) {\n136: \tcase int64:\n137: \t\treturn int(v)\n138: \tcase int:\n139: \t\treturn v\n140: \tcase int32:\n141: \t\treturn int(v)\n142: \tcase float64:\n143: \t\treturn int(v)\n144: \tdefault:\n145: \t\treturn 0\n146: \t}\n147: }\n148: \n149: // newestPod prefers a pod that is not being deleted, then a running pod and, among equals, the\n150: // newest one: several pods can match a node during a rolling update or a restart, when the old\n151: // pod terminates while its replacement starts.\n152: func newestPod(current, candidate *corev1.Pod) *corev1.Pod {\n153: \tif current == nil {\n154: \t\treturn candidate\n155: \t}\n156: \n157: \tcurrentDeleting := current.DeletionTimestamp != nil\n158: \tcandidateDeleting := candidate.DeletionTimestamp != nil\n159: \tif currentDeleting != candidateDeleting {\n160: \t\tif candidateDeleting {\n161: \t\t\treturn current\n162: \t\t}\n163: \n164: \t\treturn candidate\n165: \t}\n166: \n167: \tcurrentRunning := current.Status.Phase == corev1.PodRunning\n168: \tcandidateRunning := candidate.Status.Phase == corev1.PodRunning\n169: \tif currentRunning != candidateRunning {\n170: \t\tif candidateRunning {\n171: \t\t\treturn candidate\n172: \t\t}\n173: \n174: \t\treturn current\n175: \t}\n176: \n177: \tif candidate.CreationTimestamp.After(current.CreationTimestamp.Time) {\n178: \t\treturn candidate\n179: \t}\n180: \n181: \treturn current\n182: }\n183: \n184: func (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabState) error {\n185: \tif state == nil || state.Name == \"\" {\n186: \t\treturn nil\n187: \t}\n188: \n189: \tnodeResources, err := r.nodesForTopology(ctx, state.Name, state.Namespace)\n190: \tif err != nil {\n191: \t\treturn err\n192: \t}\n193: \n194: \tnodesByName := map[string]clablabruntime.NodeState{}\n195: \tfor _, node := range state.Nodes {\n196: \t\tnodesByName[node.Name] = node\n197: \t}\n198: \n199: \tnetworkModes := make(map[string]string, len(nodeResources.Items))\n200: \tresourcesByName := make(map[string]*unstructured.Unstructured, len(nodeResources.Items))\n201: \tfor idx := range nodeResources.Items {\n202: \t\tnodeResource := &nodeResources.Items[idx]\n203: \t\tnodesByName[nodeResource.GetName()] = nodeStateFromResource(nodeResource)\n204: \t\tnetworkModes[nodeResource.GetName()] = nodeNetworkMode(nodeResource)\n205: \t\tresourcesByName[nodeResource.GetName()] = nodeResource\n206: \t}\n207: \n208: \tpods, err := r.kubeClient.CoreV1().Pods(state.Namespace).List(ctx, metav1.ListOptions{\n209: \t\tLabelSelector: labels.Set{\n210: \t\t\tlabelApp:           clabernetesAppValue,\n211: \t\t\tlabelTopologyOwner: state.Name,\n212: \t\t}.String(),\n213: \t})\n214: \tif err != nil {\n215: \t\treturn fmt.Errorf(\"failed to list clabernetes pods for topology %s/%s: %w\",\n216: \t\t\tstate.Namespace, state.Name, err)\n217: \t}\n218: \n219: \tpodsByNode := map[string]*corev1.Pod{}\n220: \tfor idx := range pods.Items {\n221: \t\tnodeName := pods.Items[idx].Labels[labelTopologyNode]\n222: \t\tif nodeName == \"\" {\n223: \t\t\tcontinue\n224: \t\t}\n225: \t\t// A pod of an earlier Node of the same name (a redeploy while the old pod still\n226: \t\t// terminates) is not this node's pod.\n227: \t\tif uid := pods.Items[idx].Annotations[annotationDirectNodeUID]; uid != \"\" {\n228: \t\t\tif resource := resourcesByName[nodeName]; resource != nil &&\n229: \t\t\t\tstring(resource.GetUID()) != uid {\n230: \t\t\t\tcontinue\n231: \t\t\t}\n232: \t\t}\n233: \t\tpodsByNode[nodeName] = newestPod(podsByNode[nodeName], &pods.Items[idx])\n234: \t}\n235: \n236: \t// The Node's status.readiness is the authoritative device signal. The primary Node's run\n237: \t// state governs the pod a group of nodes shares: a stopped primary stops the whole group.\n238: \t// Nodes without readiness yet report their pod phase.\n239: \tfor nodeName, node := range nodesByName {\n240: \t\tprimary := resolvePrimaryNode(nodeName, networkModes)\n241: \t\tprimaryResource := resourcesByName[primary]\n242: \t\tstopRequested := primaryResource != nil &&\n243: \t\t\tnodeRunState(primaryResource) == nodeRunStateStopped\n244: \t\tif stopRequested {\n245: \t\t\tnode.State = \"stopping\"\n246: \t\t\tif condition := nodeCondition(\n247: \t\t\t\tprimaryResource,\n248: \t\t\t\tnodeConditionStopped,\n249: \t\t\t); condition != nil &&\n250: \t\t\t\tcondition.status == string(metav1.ConditionTrue) {\n251: \t\t\t\tnode.State = \"stopped\"\n252: \t\t\t}\n253: \t\t\tnode.Ready = false\n254: \t\t} else if pod := podsByNode[primary]; node.State == \"\" && pod != nil &&\n255: \t\t\tpod.Status.Phase != \"\" {\n256: \t\t\tnode.State = strings.ToLower(string(pod.Status.Phase))\n257: \t\t}\n258: \t\tnode.ContainerState = nodeContainerState(stopRequested, podsByNode[primary])\n259: \t\tif node.ContainerState == clablabruntime.ContainerStateRunning {\n260: \t\t\tnode.Health = nodeHealth(node, resourcesByName[nodeName])\n261: \t\t}\n262: \t\tnodesByName[nodeName] = node\n263: \t}\n264: \n265: \t// Nodes grouped through network-mode container: share the pod of the group's primary\n266: \t// node. Before the controller observed the device containers, the pod's default-container\n267: \t// annotation names the primary node's container.\n268: \tfor nodeName, node := range nodesByName {\n269: \t\tprimary := resolvePrimaryNode(nodeName, networkModes)\n270: \t\tpod := podsByNode[primary]\n271: \t\tif pod == nil {\n272: \t\t\tcontinue\n273: \t\t}\n274: \n275: \t\tnode.Pod = pod.Name\n276: \t\tif node.Container == \"\" && primary == nodeName {\n277: \t\t\tnode.Container = pod.Annotations[defaultContainerAnnotation]\n278: \t\t}\n279: \t\tnodesByName[nodeName] = node\n280: \t}\n281: \n282: \tnodeNames := make([]string, 0, len(nodesByName))\n283: \tfor nodeName := range nodesByName {\n284: \t\tnodeNames = append(nodeNames, nodeName)\n285: \t}\n286: \tsort.Strings(nodeNames)\n287: \n288: \tstate.Nodes = make([]clablabruntime.NodeState, 0, len(nodeNames))\n289: \tallReady := len(nodeNames) > 0 // codespell:ignore allready\n290: \tallStopped := len(nodeNames) > 0\n291: \tfor _, nodeName := range nodeNames {\n292: \t\tnode := nodesByName[nodeName]\n293: \t\tstate.Nodes = append(state.Nodes, node)\n294: \t\tallReady = allReady && node.Ready // codespell:ignore allready\n295: \t\tallStopped = allStopped && node.State == \"stopped\"\n296: \t}\n297: \n298: \tswitch {\n299: \tcase allReady: // codespell:ignore allready\n300: \t\tstate.State = \"running\"\n301: \t\tstate.Ready = true\n302: \tcase allStopped:\n303: \t\tstate.State = \"stopped\"\n304: \t\tstate.Ready = false\n305: \tcase len(nodeNames) != 0:\n306: \t\tstate.State = \"partial\"\n307: \t\tstate.Ready = false\n308: \t}\n309: \n310: \treturn nil\n311: }\n312: \n313: // nodeContainerState is the state of a node in container runtime terms, from its pod: created\n314: // while the pod is scheduled and prepared (init containers), running once the device containers\n315: // run, and exited once the node was stopped, its pod is being deleted, or the pod ended. Between\n316: // the pods of a restart the node is exited, then created.\n317: func nodeContainerState(stopRequested bool, pod *corev1.Pod) string {\n318: \tswitch {\n319: \tcase pod == nil && stopRequested:\n320: \t\treturn clablabruntime.ContainerStateExited\n321: \tcase pod == nil:\n322: \t\treturn clablabruntime.ContainerStateCreated\n323: \tcase stopRequested || pod.DeletionTimestamp != nil:\n324: \t\treturn clablabruntime.ContainerStateExited\n325: \t}\n326: \n327: \tswitch pod.Status.Phase {\n328: \tcase corev1.PodRunning:\n329: \t\treturn clablabruntime.ContainerStateRunning\n330: \tcase corev1.PodSucceeded, corev1.PodFailed:\n331: \t\treturn clablabruntime.ContainerStateExited\n332: \tdefault:\n333: \t\treturn clablabruntime.ContainerStateCreated\n334: \t}\n335: }\n336: \n337: // nodeHealth is the health of a running node: healthy once the Node is ready or its device\n338: // containers are, starting before. Device containers are the analogue of a container\n339: // healthcheck: a node whose links wait for a stopped peer is not ready, but its device is.\n340: func nodeHealth(node clablabruntime.NodeState, resource *unstructured.Unstructured) string {\n341: \tif node.Ready {\n342: \t\treturn clablabruntime.ContainerHealthHealthy\n343: \t}\n344: \tif resource != nil {\n345: \t\tif condition := nodeCondition(resource, nodeConditionContainersReady); condition != nil &&\n346: \t\t\tcondition.status == string(metav1.ConditionTrue) {\n347: \t\t\treturn clablabruntime.ContainerHealthHealthy\n348: \t\t}\n349: \t}\n350: \n351: \treturn clablabruntime.ContainerHealthStarting\n352: }\n\n(End of file - total 352 lines)\n</content>",
    "title": "source/head/labruntime/clabernetes/state.go",
    "metadata": {
      "preview": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\tclabconstants \"github.com/srl-labs/containerlab/constants\"\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\t\"k8s.io/apimachinery/pkg/labels\"\n)\n\nfunc stateFromNodeResources(\n\tname,\n\tnamespace string,\n\tnodeResources []unstructured.Unstructured,",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/state.go",
        "text": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\tclabconstants \"github.com/srl-labs/containerlab/constants\"\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\t\"k8s.io/apimachinery/pkg/labels\"\n)\n\nfunc stateFromNodeResources(\n\tname,\n\tnamespace string,\n\tnodeResources []unstructured.Unstructured,\n) *clablabruntime.LabState {\n\tstate := &clablabruntime.LabState{\n\t\tName:         name,\n\t\tNamespace:    namespace,\n\t\tTopologyPath: fmt.Sprintf(\"k8s://%s/labs/%s\", namespace, name),\n\t}\n\t// Without a Topology resource the Nodes record the file the lab was deployed from.\n\tfor idx := range nodeResources {\n\t\tif path := nodeResources[idx].GetAnnotations()[annotationTopologyFile]; path != \"\" {\n\t\t\tstate.TopologyPath = path\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(nodeResources) != 0 {\n\t\tstate.Owner = nodeResources[0].GetLabels()[clabconstants.Owner]\n\t\tif state.Owner == \"\" {\n\t\t\tstate.Owner = nodeResources[0].GetAnnotations()[clabconstants.Owner]\n\t\t}\n\t}\n\n\tstate.Nodes = make([]clablabruntime.NodeState, 0, len(nodeResources))\n\tfor idx := range nodeResources {\n\t\tstate.Nodes = append(state.Nodes, nodeStateFromResource(&nodeResources[idx]))\n\t}\n\n\treturn state\n}\n\nfunc nodeStateFromResource(nodeResource *unstructured.Unstructured) clablabruntime.NodeState {\n\tnode := clablabruntime.NodeState{\n\t\tName:    nodeResource.GetName(),\n\t\tNodeUID: string(nodeResource.GetUID()),\n\t}\n\tif original := nodeResource.GetLabels()[labelOriginalNodeName]; original != node.Name {\n\t\tnode.TopologyName = original\n\t}\n\tnode.ExposedPorts = nodeExposedPorts(nodeResource)\n\t// The same container exec targets: the observed primary device container.\n\tnode.Container, _ = preferredDeviceContainerName(nodeResource, node.Name)\n\tnode.Kind, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"kind\")\n\tnode.Image, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"image\")\n\tnode.Type, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"type\")\n\tnode.Group, _, _ = unstructured.NestedString(nodeResource.Object, \"spec\", \"group\")\n\tnode.State, _, _ = unstructured.NestedString(nodeResource.Object, \"status\", \"readiness\")\n\tnode.Ready = node.State == \"ready\"\n\tnode.LoadBalancerAddress, _, _ = unstructured.NestedString(\n\t\tnodeResource.Object,\n\t\t\"status\",\n\t\t\"exposedPorts\",\n\t\t\"loadBalancerAddress\",\n\t)\n\tnode.MgmtIPv4Address, _, _ = unstructured.NestedString(\n\t\tnodeResource.Object,\n\t\t\"status\",\n\t\t\"directManagement\",\n\t\t\"ipv4\",\n\t)\n\tnode.MgmtIPv6Address, _, _ = unstructured.NestedString(\n\t\tnodeResource.Object,\n\t\t\"status\",\n\t\t\"directManagement\",\n\t\t\"ipv6\",\n\t)\n\n\treturn node\n}\n\n// nodeExposedPorts reads the expose-port allocations the controller published on the Node.\nfunc nodeExposedPorts(nodeResource *unstructured.Unstructured) []clablabruntime.ExposedPort {\n\trawPorts, _, _ := unstructured.NestedSlice(\n\t\tnodeResource.Object,\n\t\t\"status\",\n\t\t\"exposedPorts\",\n\t\t\"ports\",\n\t)\n\n\tports := make([]clablabruntime.ExposedPort, 0, len(rawPorts))\n\tfor _, raw := range rawPorts {\n\t\tentry, ok := raw.(map[string]any)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tport := clablabruntime.ExposedPort{\n\t\t\tPort:       intField(entry[\"destinationPort\"]),\n\t\t\tExposePort: intField(entry[\"exposePort\"]),\n\t\t\tProtocol:   strings.ToLower(fmt.Sprint(entry[\"protocol\"])),\n\t\t}\n\t\tif port.Port == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif port.Protocol == \"\" || port.Protocol == \"<nil>\" {\n\t\t\tport.Protocol = \"tcp\"\n\t\t}\n\n\t\tports = append(ports, port)\n\t}\n\n\tif len(ports) == 0 {\n\t\treturn nil\n\t}\n\n\tsort.Slice(ports, func(i, j int) bool {\n\t\tif ports[i].Port == ports[j].Port {\n\t\t\treturn ports[i].Protocol < ports[j].Protocol\n\t\t}\n\n\t\treturn ports[i].Port < ports[j].Port\n\t})\n\n\treturn ports\n}\n\nfunc intField(value any) int {\n\tswitch v := value.(type) {\n\tcase int64:\n\t\treturn int(v)\n\tcase int:\n\t\treturn v\n\tcase int32:\n\t\treturn int(v)\n\tcase float64:\n\t\treturn int(v)\n\tdefault:\n\t\treturn 0\n\t}\n}\n\n// newestPod prefers a pod that is not being deleted, then a running pod and, among equals, the\n// newest one: several pods can match a node during a rolling update or a restart, when the old\n// pod terminates while its replacement starts.\nfunc newestPod(current, candidate *corev1.Pod) *corev1.Pod {\n\tif current == nil {\n\t\treturn candidate\n\t}\n\n\tcurrentDeleting := current.DeletionTimestamp != nil\n\tcandidateDeleting := candidate.DeletionTimestamp != nil\n\tif currentDeleting != candidateDeleting {\n\t\tif candidateDeleting {\n\t\t\treturn current\n\t\t}\n\n\t\treturn candidate\n\t}\n\n\tcurrentRunning := current.Status.Phase == corev1.PodRunning\n\tcandidateRunning := candidate.Status.Phase == corev1.PodRunning\n\tif currentRunning != candidateRunning {\n\t\tif candidateRunning {\n\t\t\treturn candidate\n\t\t}\n\n\t\treturn current\n\t}\n\n\tif candidate.CreationTimestamp.After(current.CreationTimestamp.Time) {\n\t\treturn candidate\n\t}\n\n\treturn current\n}\n\nfunc (r *Runtime) enrichState(ctx context.Context, state *clablabruntime.LabState) error {\n\tif state == nil || state.Name == \"\" {\n\t\treturn nil\n\t}\n\n\tnodeResources, err := r.nodesForTopology(ctx, state.Name, state.Namespace)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnodesByName := map[string]clablabruntime.NodeState{}\n\tfor _, node := range state.Nodes {\n\t\tnodesByName[node.Name] = node\n\t}\n\n\tnetworkModes := make(map[string]string, len(nodeResources.Items))\n\tresourcesByName := make(map[string]*unstructured.Unstructured, len(nodeResources.Items))\n\tfor idx := range nodeResources.Items {\n\t\tnodeResource := &nodeResources.Items[idx]\n\t\tnodesByName[nodeResource.GetName()] = nodeStateFromResource(nodeResource)\n\t\tnetworkModes[nodeResource.GetName()] = nodeNetworkMode(nodeResource)\n\t\tresourcesByName[nodeResource.GetName()] = nodeResource\n\t}\n\n\tpods, err := r.kubeClient.CoreV1().Pods(state.Namespace).List(ctx, metav1.ListOptions{\n\t\tLabelSelector: labels.Set{\n\t\t\tlabelApp:           clabernetesAppValue,\n\t\t\tlabelTopologyOwner: state.Name,\n\t\t}.String(),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to list clabernetes pods for topology %s/%s: %w\",\n\t\t\tstate.Namespace, state.Name, err)\n\t}\n\n\tpodsByNode := map[string]*corev1.Pod{}\n\tfor idx := range pods.Items {\n\t\tnodeName := pods.Items[idx].Labels[labelTopologyNode]\n\t\tif nodeName == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\t// A pod of an earlier Node of the same name (a redeploy while the old pod still\n\t\t// terminates) is not this node's pod.\n\t\tif uid := pods.Items[idx].Annotations[annotationDirectNodeUID]; uid != \"\" {\n\t\t\tif resource := resourcesByName[nodeName]; resource != nil &&\n\t\t\t\tstring(resource.GetUID()) != uid {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tpodsByNode[nodeName] = newestPod(podsByNode[nodeName], &pods.Items[idx])\n\t}\n\n\t// The Node's status.readiness is the authoritative device signal. The primary Node's run\n\t// state governs the pod a group of nodes shares: a stopped primary stops the whole group.\n\t// Nodes without readiness yet report their pod phase.\n\tfor nodeName, node := range nodesByName {\n\t\tprimary := resolvePrimaryNode(nodeName, networkModes)\n\t\tprimaryResource := resourcesByName[primary]\n\t\tstopRequested := primaryResource != nil &&\n\t\t\tnodeRunState(primaryResource) == nodeRunStateStopped\n\t\tif stopRequested {\n\t\t\tnode.State = \"stopping\"\n\t\t\tif condition := nodeCondition(\n\t\t\t\tprimaryResource,\n\t\t\t\tnodeConditionStopped,\n\t\t\t); condition != nil &&\n\t\t\t\tcondition.status == string(metav1.ConditionTrue) {\n\t\t\t\tnode.State = \"stopped\"\n\t\t\t}\n\t\t\tnode.Ready = false\n\t\t} else if pod := podsByNode[primary]; node.State == \"\" && pod != nil &&\n\t\t\tpod.Status.Phase != \"\" {\n\t\t\tnode.State = strings.ToLower(string(pod.Status.Phase))\n\t\t}\n\t\tnode.ContainerState = nodeContainerState(stopRequested, podsByNode[primary])\n\t\tif node.ContainerState == clablabruntime.ContainerStateRunning {\n\t\t\tnode.Health = nodeHealth(node, resourcesByName[nodeName])\n\t\t}\n\t\tnodesByName[nodeName] = node\n\t}\n\n\t// Nodes grouped through network-mode container: share the pod of the group's primary\n\t// node. Before the controller observed the device containers, the pod's default-container\n\t// annotation names the primary node's container.\n\tfor nodeName, node := range nodesByName {\n\t\tprimary := resolvePrimaryNode(nodeName, networkModes)\n\t\tpod := podsByNode[primary]\n\t\tif pod == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tnode.Pod = pod.Name\n\t\tif node.Container == \"\" && primary == nodeName {\n\t\t\tnode.Container = pod.Annotations[defaultContainerAnnotation]\n\t\t}\n\t\tnodesByName[nodeName] = node\n\t}\n\n\tnodeNames := make([]string, 0, len(nodesByName))\n\tfor nodeName := range nodesByName {\n\t\tnodeNames = append(nodeNames, nodeName)\n\t}\n\tsort.Strings(nodeNames)\n\n\tstate.Nodes = make([]clablabruntime.NodeState, 0, len(nodeNames))\n\tallReady := len(nodeNames) > 0 // codespell:ignore allready\n\tallStopped := len(nodeNames) > 0\n\tfor _, nodeName := range nodeNames {\n\t\tnode := nodesByName[nodeName]\n\t\tstate.Nodes = append(state.Nodes, node)\n\t\tallReady = allReady && node.Ready // codespell:ignore allready\n\t\tallStopped = allStopped && node.State == \"stopped\"\n\t}\n\n\tswitch {\n\tcase allReady: // codespell:ignore allready\n\t\tstate.State = \"running\"\n\t\tstate.Ready = true\n\tcase allStopped:\n\t\tstate.State = \"stopped\"\n\t\tstate.Ready = false\n\tcase len(nodeNames) != 0:\n\t\tstate.State = \"partial\"\n\t\tstate.Ready = false\n\t}\n\n\treturn nil\n}\n\n// nodeContainerState is the state of a node in container runtime terms, from its pod: created\n// while the pod is scheduled and prepared (init containers), running once the device containers\n// run, and exited once the node was stopped, its pod is being deleted, or the pod ended. Between\n// the pods of a restart the node is exited, then created.\nfunc nodeContainerState(stopRequested bool, pod *corev1.Pod) string {\n\tswitch {\n\tcase pod == nil && stopRequested:\n\t\treturn clablabruntime.ContainerStateExited\n\tcase pod == nil:\n\t\treturn clablabruntime.ContainerStateCreated\n\tcase stopRequested || pod.DeletionTimestamp != nil:\n\t\treturn clablabruntime.ContainerStateExited\n\t}\n\n\tswitch pod.Status.Phase {\n\tcase corev1.PodRunning:\n\t\treturn clablabruntime.ContainerStateRunning\n\tcase corev1.PodSucceeded, corev1.PodFailed:\n\t\treturn clablabruntime.ContainerStateExited\n\tdefault:\n\t\treturn clablabruntime.ContainerStateCreated\n\t}\n}\n\n// nodeHealth is the health of a running node: healthy once the Node is ready or its device\n// containers are, starting before. Device containers are the analogue of a container\n// healthcheck: a node whose links wait for a stopped peer is not ready, but its device is.\nfunc nodeHealth(node clablabruntime.NodeState, resource *unstructured.Unstructured) string {\n\tif node.Ready {\n\t\treturn clablabruntime.ContainerHealthHealthy\n\t}\n\tif resource != nil {\n\t\tif condition := nodeCondition(resource, nodeConditionContainersReady); condition != nil &&\n\t\t\tcondition.status == string(metav1.ConditionTrue) {\n\t\t\treturn clablabruntime.ContainerHealthHealthy\n\t\t}\n\t}\n\n\treturn clablabruntime.ContainerHealthStarting\n}",
        "lineStart": 1,
        "lineEnd": 352,
        "totalLines": 352,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525786093,
      "end": 1793525786106
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19677a5fd001UbeXLZ7VoE8wzx",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196778d7e001SINK9sXOPv8V7M",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 80417,
    "input": 19888,
    "output": 72,
    "reasoning": 553,
    "cache": {
      "read": 59904,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196778d7e001SINK9sXOPv8V7M",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525779839,
    "completed": 1793525786112
  },
  "parentID": "msg_19676df9500159h7P3dGcuBxjO",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 80417,
    "input": 19888,
    "output": 72,
    "reasoning": 553,
    "cache": {
      "read": 59904,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 21
step-start
{
  "type": "step-start",
  "id": "prt_19677af490017DtVitUeiFiNhX",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19677a608001SBsSyT2IalSaYg"
}
Reasoning
state.go looks fine. One subtle thing in `enrichState`: podsByNode built only from pods whose annotationDirectNodeUID matches or is absent; then `podsByNode[primary]` is used for `node.Pod = pod.Name` in the second loop — for grouped nodes with network-mode container, primary's pod assigned to all group members. OK.

A subtle issue: `nodeContainerState(stopRequested, podsByNode[primary])` — for a node in a group whose primary is running, all members report running. OK.

Now I still need to check:
1. Where `annotationTopologyFile` is set during deploy (manifests.go / plan.go / primitives.go / reconcile.go changes).
2. capture_interfaces.go `listPodInterfaces` refactor.
3. clabernetes.go constants and any changes (annotationDirectNodeUID addition).
4. core/labruntime.go lines 1-440 (how Inspect builds TopoFile etc.).
5. Docs and tests.

Let me read the diff sections for manifests/plan/primitives/reconcile/clabernetes/capture/capture_interfaces. These are at various offsets in diff.txt. I read diff 1-1300 partially in the first session (details lost except what was recorded). Let me just read head files directly for the annotation-related changes, and also grep diff for specific hunks.

Actually more efficient: read the head files for these small files.
`state.go` is coherent. Now the deploy-side annotation recording and the capture refactor.
read · completed

Input

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

Output

<path>/source/head/labruntime/clabernetes/manifests.go</path>
<type>file</type>
<content>
1: // Copyright 2020 Nokia
2: // Licensed under the BSD 3-Clause License.
3: // SPDX-License-Identifier: BSD-3-Clause
4: 
5: package clabernetes
6: 
7: import (
8: 	"context"
9: 	"fmt"
10: 
11: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
12: 	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
13: 	k8sruntime "k8s.io/apimachinery/pkg/runtime"
14: )
15: 
16: // Manifests renders the resources a deploy would create for the topology, in the order the
17: // runtime applies them, without contacting the cluster. The bundle is the managed lab
18: // Namespace when containerlab would create one, the staged ConfigMaps every node file mounts
19: // from, and then either the Topology resource or, for a lab deployed without one, the
20: // NodeProfile, Link, and Node resources compiled client-side. Every object carries the labels
21: // the runtime relies on to discover the lab later, so a bundle applied by hand stays
22: // manageable with inspect, destroy, and the node lifecycle commands.
23: func (r *Runtime) Manifests(
24: 	ctx context.Context,
25: 	req clablabruntime.DeployRequest,
26: ) ([]clablabruntime.Manifest, error) {
27: 	if req.Name == "" {
28: 		return nil, fmt.Errorf("topology name is required")
29: 	}
30: 	if len(req.TopologyDefinition) == 0 {
31: 		return nil, fmt.Errorf("rendered containerlab topology is required")
32: 	}
33: 
34: 	namespace, err := r.namespaceForLab(req.Name, req.Namespace)
35: 	if err != nil {
36: 		return nil, err
37: 	}
38: 	prepared, err := prepareDesiredDeployment(ctx, req, namespace)
39: 	if err != nil {
40: 		return nil, err
41: 	}
42: 
43: 	// The manifests are applied by other means than this deploy, so they do not carry the path
44: 	// of the topology file on this machine; such a lab reports where its definition lives.
45: 	removeTopologySourceFile(prepared.topology)
46: 	for _, group := range prepared.primitives.groups() {
47: 		for _, obj := range group.objects {
48: 			removeTopologySourceFile(obj)
49: 		}
50: 	}
51: 
52: 	manifests := []clablabruntime.Manifest{}
53: 
54: 	// A namespace override must already exist, matching the deploy contract; only the
55: 	// canonical per-lab namespace is created by containerlab and therefore emitted.
56: 	if req.Namespace == "" && r.labNamespaceOverride == "" {
57: 		manifest, err := typedManifest(labNamespaceObject(req.Name, namespace))
58: 		if err != nil {
59: 			return nil, err
60: 		}
61: 		manifests = append(manifests, manifest)
62: 	}
63: 
64: 	for _, staged := range prepared.configMaps {
65: 		manifest, err := typedManifest(stagedConfigMapObject(namespace, req.Name, staged, nil))
66: 		if err != nil {
67: 			return nil, err
68: 		}
69: 		manifests = append(manifests, manifest)
70: 	}
71: 
72: 	if !req.NoTopologyCR {
73: 		return append(manifests, unstructuredManifest(prepared.topology)), nil
74: 	}
75: 
76: 	for _, group := range prepared.primitives.groups() {
77: 		for _, obj := range group.objects {
78: 			manifests = append(manifests, unstructuredManifest(obj))
79: 		}
80: 	}
81: 
82: 	return manifests, nil
83: }
84: 
85: func typedManifest(obj k8sruntime.Object) (clablabruntime.Manifest, error) {
86: 	object, err := k8sruntime.DefaultUnstructuredConverter.ToUnstructured(obj)
87: 	if err != nil {
88: 		return clablabruntime.Manifest{}, fmt.Errorf("failed to render manifest: %w", err)
89: 	}
90: 
91: 	return unstructuredManifest(&unstructured.Unstructured{Object: object}), nil
92: }
93: 
94: // unstructuredManifest copies the object and strips the server-populated fields that typed
95: // conversion materializes as empty values, so the emitted document is a clean input for apply.
96: func unstructuredManifest(obj *unstructured.Unstructured) clablabruntime.Manifest {
97: 	object := obj.DeepCopy().Object
98: 
99: 	unstructured.RemoveNestedField(object, "status")
100: 	if timestamp, found, _ := unstructured.NestedFieldNoCopy(
101: 		object, "metadata", "creationTimestamp",
102: 	); found && timestamp == nil {
103: 		unstructured.RemoveNestedField(object, "metadata", "creationTimestamp")
104: 	}
105: 	if spec, found, _ := unstructured.NestedMap(object, "spec"); found && len(spec) == 0 {
106: 		unstructured.RemoveNestedField(object, "spec")
107: 	}
108: 
109: 	copied := &unstructured.Unstructured{Object: object}
110: 
111: 	return clablabruntime.Manifest{
112: 		APIVersion: copied.GetAPIVersion(),
113: 		Kind:       copied.GetKind(),
114: 		Namespace:  copied.GetNamespace(),
115: 		Name:       copied.GetName(),
116: 		Object:     object,
117: 	}
118: }

(End of file - total 118 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19677b8b1001Htbg8SvSYH32U7",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19677a608001SBsSyT2IalSaYg",
  "callID": "call_01f93a18a5304bba80bba092",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/manifests.go"
    },
    "output": "<path>/source/head/labruntime/clabernetes/manifests.go</path>\n<type>file</type>\n<content>\n1: // Copyright 2020 Nokia\n2: // Licensed under the BSD 3-Clause License.\n3: // SPDX-License-Identifier: BSD-3-Clause\n4: \n5: package clabernetes\n6: \n7: import (\n8: \t\"context\"\n9: \t\"fmt\"\n10: \n11: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n12: \t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n13: \tk8sruntime \"k8s.io/apimachinery/pkg/runtime\"\n14: )\n15: \n16: // Manifests renders the resources a deploy would create for the topology, in the order the\n17: // runtime applies them, without contacting the cluster. The bundle is the managed lab\n18: // Namespace when containerlab would create one, the staged ConfigMaps every node file mounts\n19: // from, and then either the Topology resource or, for a lab deployed without one, the\n20: // NodeProfile, Link, and Node resources compiled client-side. Every object carries the labels\n21: // the runtime relies on to discover the lab later, so a bundle applied by hand stays\n22: // manageable with inspect, destroy, and the node lifecycle commands.\n23: func (r *Runtime) Manifests(\n24: \tctx context.Context,\n25: \treq clablabruntime.DeployRequest,\n26: ) ([]clablabruntime.Manifest, error) {\n27: \tif req.Name == \"\" {\n28: \t\treturn nil, fmt.Errorf(\"topology name is required\")\n29: \t}\n30: \tif len(req.TopologyDefinition) == 0 {\n31: \t\treturn nil, fmt.Errorf(\"rendered containerlab topology is required\")\n32: \t}\n33: \n34: \tnamespace, err := r.namespaceForLab(req.Name, req.Namespace)\n35: \tif err != nil {\n36: \t\treturn nil, err\n37: \t}\n38: \tprepared, err := prepareDesiredDeployment(ctx, req, namespace)\n39: \tif err != nil {\n40: \t\treturn nil, err\n41: \t}\n42: \n43: \t// The manifests are applied by other means than this deploy, so they do not carry the path\n44: \t// of the topology file on this machine; such a lab reports where its definition lives.\n45: \tremoveTopologySourceFile(prepared.topology)\n46: \tfor _, group := range prepared.primitives.groups() {\n47: \t\tfor _, obj := range group.objects {\n48: \t\t\tremoveTopologySourceFile(obj)\n49: \t\t}\n50: \t}\n51: \n52: \tmanifests := []clablabruntime.Manifest{}\n53: \n54: \t// A namespace override must already exist, matching the deploy contract; only the\n55: \t// canonical per-lab namespace is created by containerlab and therefore emitted.\n56: \tif req.Namespace == \"\" && r.labNamespaceOverride == \"\" {\n57: \t\tmanifest, err := typedManifest(labNamespaceObject(req.Name, namespace))\n58: \t\tif err != nil {\n59: \t\t\treturn nil, err\n60: \t\t}\n61: \t\tmanifests = append(manifests, manifest)\n62: \t}\n63: \n64: \tfor _, staged := range prepared.configMaps {\n65: \t\tmanifest, err := typedManifest(stagedConfigMapObject(namespace, req.Name, staged, nil))\n66: \t\tif err != nil {\n67: \t\t\treturn nil, err\n68: \t\t}\n69: \t\tmanifests = append(manifests, manifest)\n70: \t}\n71: \n72: \tif !req.NoTopologyCR {\n73: \t\treturn append(manifests, unstructuredManifest(prepared.topology)), nil\n74: \t}\n75: \n76: \tfor _, group := range prepared.primitives.groups() {\n77: \t\tfor _, obj := range group.objects {\n78: \t\t\tmanifests = append(manifests, unstructuredManifest(obj))\n79: \t\t}\n80: \t}\n81: \n82: \treturn manifests, nil\n83: }\n84: \n85: func typedManifest(obj k8sruntime.Object) (clablabruntime.Manifest, error) {\n86: \tobject, err := k8sruntime.DefaultUnstructuredConverter.ToUnstructured(obj)\n87: \tif err != nil {\n88: \t\treturn clablabruntime.Manifest{}, fmt.Errorf(\"failed to render manifest: %w\", err)\n89: \t}\n90: \n91: \treturn unstructuredManifest(&unstructured.Unstructured{Object: object}), nil\n92: }\n93: \n94: // unstructuredManifest copies the object and strips the server-populated fields that typed\n95: // conversion materializes as empty values, so the emitted document is a clean input for apply.\n96: func unstructuredManifest(obj *unstructured.Unstructured) clablabruntime.Manifest {\n97: \tobject := obj.DeepCopy().Object\n98: \n99: \tunstructured.RemoveNestedField(object, \"status\")\n100: \tif timestamp, found, _ := unstructured.NestedFieldNoCopy(\n101: \t\tobject, \"metadata\", \"creationTimestamp\",\n102: \t); found && timestamp == nil {\n103: \t\tunstructured.RemoveNestedField(object, \"metadata\", \"creationTimestamp\")\n104: \t}\n105: \tif spec, found, _ := unstructured.NestedMap(object, \"spec\"); found && len(spec) == 0 {\n106: \t\tunstructured.RemoveNestedField(object, \"spec\")\n107: \t}\n108: \n109: \tcopied := &unstructured.Unstructured{Object: object}\n110: \n111: \treturn clablabruntime.Manifest{\n112: \t\tAPIVersion: copied.GetAPIVersion(),\n113: \t\tKind:       copied.GetKind(),\n114: \t\tNamespace:  copied.GetNamespace(),\n115: \t\tName:       copied.GetName(),\n116: \t\tObject:     object,\n117: \t}\n118: }\n\n(End of file - total 118 lines)\n</content>",
    "title": "source/head/labruntime/clabernetes/manifests.go",
    "metadata": {
      "preview": "// Copyright 2020 Nokia\n// Licensed under the BSD 3-Clause License.\n// SPDX-License-Identifier: BSD-3-Clause\n\npackage clabernetes\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n\tk8sruntime \"k8s.io/apimachinery/pkg/runtime\"\n)\n\n// Manifests renders the resources a deploy would create for the topology, in the order the\n// runtime applies them, without contacting the cluster. The bundle is the managed lab\n// Namespace when containerlab would create one, the staged ConfigMaps every node file mounts\n// from, and then either the Topology resource or, for a lab deployed without one, the\n// NodeProfile, Link, and Node resources compiled client-side. Every object carries the labels",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/manifests.go",
        "text": "// Copyright 2020 Nokia\n// Licensed under the BSD 3-Clause License.\n// SPDX-License-Identifier: BSD-3-Clause\n\npackage clabernetes\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n\tk8sruntime \"k8s.io/apimachinery/pkg/runtime\"\n)\n\n// Manifests renders the resources a deploy would create for the topology, in the order the\n// runtime applies them, without contacting the cluster. The bundle is the managed lab\n// Namespace when containerlab would create one, the staged ConfigMaps every node file mounts\n// from, and then either the Topology resource or, for a lab deployed without one, the\n// NodeProfile, Link, and Node resources compiled client-side. Every object carries the labels\n// the runtime relies on to discover the lab later, so a bundle applied by hand stays\n// manageable with inspect, destroy, and the node lifecycle commands.\nfunc (r *Runtime) Manifests(\n\tctx context.Context,\n\treq clablabruntime.DeployRequest,\n) ([]clablabruntime.Manifest, error) {\n\tif req.Name == \"\" {\n\t\treturn nil, fmt.Errorf(\"topology name is required\")\n\t}\n\tif len(req.TopologyDefinition) == 0 {\n\t\treturn nil, fmt.Errorf(\"rendered containerlab topology is required\")\n\t}\n\n\tnamespace, err := r.namespaceForLab(req.Name, req.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprepared, err := prepareDesiredDeployment(ctx, req, namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// The manifests are applied by other means than this deploy, so they do not carry the path\n\t// of the topology file on this machine; such a lab reports where its definition lives.\n\tremoveTopologySourceFile(prepared.topology)\n\tfor _, group := range prepared.primitives.groups() {\n\t\tfor _, obj := range group.objects {\n\t\t\tremoveTopologySourceFile(obj)\n\t\t}\n\t}\n\n\tmanifests := []clablabruntime.Manifest{}\n\n\t// A namespace override must already exist, matching the deploy contract; only the\n\t// canonical per-lab namespace is created by containerlab and therefore emitted.\n\tif req.Namespace == \"\" && r.labNamespaceOverride == \"\" {\n\t\tmanifest, err := typedManifest(labNamespaceObject(req.Name, namespace))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmanifests = append(manifests, manifest)\n\t}\n\n\tfor _, staged := range prepared.configMaps {\n\t\tmanifest, err := typedManifest(stagedConfigMapObject(namespace, req.Name, staged, nil))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmanifests = append(manifests, manifest)\n\t}\n\n\tif !req.NoTopologyCR {\n\t\treturn append(manifests, unstructuredManifest(prepared.topology)), nil\n\t}\n\n\tfor _, group := range prepared.primitives.groups() {\n\t\tfor _, obj := range group.objects {\n\t\t\tmanifests = append(manifests, unstructuredManifest(obj))\n\t\t}\n\t}\n\n\treturn manifests, nil\n}\n\nfunc typedManifest(obj k8sruntime.Object) (clablabruntime.Manifest, error) {\n\tobject, err := k8sruntime.DefaultUnstructuredConverter.ToUnstructured(obj)\n\tif err != nil {\n\t\treturn clablabruntime.Manifest{}, fmt.Errorf(\"failed to render manifest: %w\", err)\n\t}\n\n\treturn unstructuredManifest(&unstructured.Unstructured{Object: object}), nil\n}\n\n// unstructuredManifest copies the object and strips the server-populated fields that typed\n// conversion materializes as empty values, so the emitted document is a clean input for apply.\nfunc unstructuredManifest(obj *unstructured.Unstructured) clablabruntime.Manifest {\n\tobject := obj.DeepCopy().Object\n\n\tunstructured.RemoveNestedField(object, \"status\")\n\tif timestamp, found, _ := unstructured.NestedFieldNoCopy(\n\t\tobject, \"metadata\", \"creationTimestamp\",\n\t); found && timestamp == nil {\n\t\tunstructured.RemoveNestedField(object, \"metadata\", \"creationTimestamp\")\n\t}\n\tif spec, found, _ := unstructured.NestedMap(object, \"spec\"); found && len(spec) == 0 {\n\t\tunstructured.RemoveNestedField(object, \"spec\")\n\t}\n\n\tcopied := &unstructured.Unstructured{Object: object}\n\n\treturn clablabruntime.Manifest{\n\t\tAPIVersion: copied.GetAPIVersion(),\n\t\tKind:       copied.GetKind(),\n\t\tNamespace:  copied.GetNamespace(),\n\t\tName:       copied.GetName(),\n\t\tObject:     object,\n\t}\n}",
        "lineStart": 1,
        "lineEnd": 118,
        "totalLines": 118,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525790902,
      "end": 1793525790914
    }
  }
}
read · completed

Input

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

Output

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

(End of file - total 198 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19677b8e8001Buml1o2wOq4AgB",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19677a608001SBsSyT2IalSaYg",
  "callID": "call_381d4a996f3b4167982cbe94",
  "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 interfaces of the requested nodes, or of every running node, in\n72: // the shape of `inspect interfaces`, with the interfaces the interface events report: the lab\n73: // link interfaces and their aliases as clabwire lists them, the management interface and\n74: // loopback. Per node (named <lab>-<node> like in inspect) it reports the MAC address, index,\n75: // MTU and operational state read from sysfs in the device container. A node whose device\n76: // container has no shell reports its link interfaces without these attributes.\n77: func (r *Runtime) InspectInterfaces(\n78: \tctx context.Context,\n79: \treq clablabruntime.NodeRequest,\n80: ) ([]*clabtypes.ContainerInterfaces, error) {\n81: \tr, err := r.connect(ctx, req.Identity)\n82: \tif err != nil {\n83: \t\treturn nil, err\n84: \t}\n85: \n86: \tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n87: \t\tName: req.Name, Namespace: req.Namespace, Nodes: req.Nodes, Identity: req.Identity,\n88: \t})\n89: \tif err != nil {\n90: \t\treturn nil, err\n91: \t}\n92: \n93: \trunning := make([]clablabruntime.NodeLocation, 0, len(locations))\n94: \tfor _, location := range locations {\n95: \t\tif location.Pod == \"\" {\n96: \t\t\tlog.Warn(\"Skipping interface detection of a node that does not run\",\n97: \t\t\t\t\"node\", location.NodeName)\n98: \t\t\tcontinue\n99: \t\t}\n100: \t\trunning = append(running, location)\n101: \t}\n102: \n103: \tlisted, err := r.listCaptureInterfaces(ctx, req.Name, running)\n104: \tif err != nil {\n105: \t\treturn nil, err\n106: \t}\n107: \tstates := r.sampleInterfaceStates(ctx, running)\n108: \n109: \tresult := make([]*clabtypes.ContainerInterfaces, 0, len(running))\n110: \tfor _, location := range running {\n111: \t\tcontainer := &clabtypes.ContainerInterfaces{\n112: \t\t\tContainerName: req.Name + \"-\" + location.NodeName,\n113: \t\t\tInterfaces:    []*clabtypes.ContainerInterfaceDetails{},\n114: \t\t}\n115: \t\tsampled, hasStates := states[location.NodeName]\n116: \t\tfor name, alias := range reportedInterfaces(listed[location.NodeName]) {\n117: \t\t\tstate, ok := sampled[name]\n118: \t\t\tif !ok {\n119: \t\t\t\tif hasStates || (name == managementInterface || name == loopbackInterface) {\n120: \t\t\t\t\t// not present in the node (yet), or not known without its states\n121: \t\t\t\t\tcontinue\n122: \t\t\t\t}\n123: \t\t\t\tstate = c9sIfaceState{Name: name}\n124: \t\t\t}\n125: \n126: \t\t\tdata := interfaceEventData(state, alias)\n127: \t\t\tdetails := &clabtypes.ContainerInterfaceDetails{\n128: \t\t\t\tInterfaceName:  data.Name,\n129: \t\t\t\tInterfaceAlias: data.Alias,\n130: \t\t\t\tInterfaceType:  data.Type,\n131: \t\t\t\tInterfaceMAC:   data.MAC,\n132: \t\t\t\tInterfaceIndex: data.Index,\n133: \t\t\t\tInterfaceMTU:   data.MTU,\n134: \t\t\t}\n135: \t\t\tif ok {\n136: \t\t\t\tdetails.InterfaceState = data.OperState\n137: \t\t\t}\n138: \t\t\tcontainer.Interfaces = append(container.Interfaces, details)\n139: \t\t}\n140: \t\tsort.Slice(container.Interfaces, func(i, j int) bool {\n141: \t\t\treturn container.Interfaces[i].InterfaceName < container.Interfaces[j].InterfaceName\n142: \t\t})\n143: \t\tresult = append(result, container)\n144: \t}\n145: \tsort.Slice(result, func(i, j int) bool {\n146: \t\treturn result[i].ContainerName < result[j].ContainerName\n147: \t})\n148: \n149: \treturn result, nil\n150: }\n151: \n152: // sampleInterfaceStates reads the sysfs interface attributes of every node's device container,\n153: // one exec per node, with the script the interface events use.\n154: func (r *Runtime) sampleInterfaceStates(\n155: \tctx context.Context,\n156: \tlocations []clablabruntime.NodeLocation,\n157: ) map[string]map[string]c9sIfaceState {\n158: \tvar mu sync.Mutex\n159: \tresult := map[string]map[string]c9sIfaceState{}\n160: \n161: \tvar wg sync.WaitGroup\n162: \tworkers := make(chan struct{}, interfaceSampleWorkers)\n163: \texec := r.execInPodContainer()\n164: \tfor _, location := range locations {\n165: \t\twg.Add(1)\n166: \t\tgo func() {\n167: \t\t\tdefer wg.Done()\n168: \t\t\tworkers <- struct{}{}\n169: \t\t\tdefer func() { <-workers }()\n170: \n171: \t\t\tvar stdout, stderr bytes.Buffer\n172: \t\t\terr := exec(ctx, location.Namespace, location.Pod, location.Container,\n173: \t\t\t\t[]string{\"sh\", \"-c\", interfaceSampleScript}, nil, &stdout, &stderr)\n174: \t\t\tif err != nil {\n175: \t\t\t\tlog.Debug(\"Cannot read the interface state of a c9s node\",\n176: \t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n177: \t\t\t\treturn\n178: \t\t\t}\n179: \t\t\t_, ifaces, _, err := parseInterfaceSample(stdout.Bytes())\n180: \t\t\tif err != nil {\n181: \t\t\t\tlog.Debug(\"Cannot parse the interface state of a c9s node\",\n182: \t\t\t\t\t\"node\", location.NodeName, \"error\", err)\n183: \t\t\t\treturn\n184: \t\t\t}\n185: \n186: \t\t\tbyName := make(map[string]c9sIfaceState, len(ifaces))\n187: \t\t\tfor _, iface := range ifaces {\n188: \t\t\t\tbyName[iface.Name] = iface\n189: \t\t\t}\n190: \t\t\tmu.Lock()\n191: \t\t\tresult[location.NodeName] = byName\n192: \t\t\tmu.Unlock()\n193: \t\t}()\n194: \t}\n195: \twg.Wait()\n196: \n197: \treturn result\n198: }\n\n(End of file - total 198 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 interfaces of the requested nodes, or of every running node, in\n// the shape of `inspect interfaces`, with the interfaces the interface events report: the lab\n// link interfaces and their aliases as clabwire lists them, the management interface and\n// loopback. Per node (named <lab>-<node> like in inspect) it reports 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 link 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\tsampled, hasStates := states[location.NodeName]\n\t\tfor name, alias := range reportedInterfaces(listed[location.NodeName]) {\n\t\t\tstate, ok := sampled[name]\n\t\t\tif !ok {\n\t\t\t\tif hasStates || (name == managementInterface || name == loopbackInterface) {\n\t\t\t\t\t// not present in the node (yet), or not known without its states\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tstate = c9sIfaceState{Name: name}\n\t\t\t}\n\n\t\t\tdata := interfaceEventData(state, alias)\n\t\t\tdetails := &clabtypes.ContainerInterfaceDetails{\n\t\t\t\tInterfaceName:  data.Name,\n\t\t\t\tInterfaceAlias: data.Alias,\n\t\t\t\tInterfaceType:  data.Type,\n\t\t\t\tInterfaceMAC:   data.MAC,\n\t\t\t\tInterfaceIndex: data.Index,\n\t\t\t\tInterfaceMTU:   data.MTU,\n\t\t\t}\n\t\t\tif ok {\n\t\t\t\tdetails.InterfaceState = data.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": 198,
        "totalLines": 198,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525790957,
      "end": 1793525790972
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19677b8ff001QE7XsG3sI7B37y",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19677a608001SBsSyT2IalSaYg",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 85860,
    "input": 5765,
    "output": 57,
    "reasoning": 294,
    "cache": {
      "read": 79744,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19677a608001SBsSyT2IalSaYg",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525786120,
    "completed": 1793525790978
  },
  "parentID": "msg_19676df9500159h7P3dGcuBxjO",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 85860,
    "input": 5765,
    "output": 57,
    "reasoning": 294,
    "cache": {
      "read": 79744,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
User · 22
compaction
{
  "type": "compaction",
  "id": "prt_19677b9040013ES7o0NOBvOKj0",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19677b903001XpuPfKo7EVPMOc",
  "auto": true,
  "overflow": false,
  "tail_start_id": "msg_196778d7e001SINK9sXOPv8V7M"
}
Message metadata
{
  "role": "user",
  "id": "msg_19677b903001XpuPfKo7EVPMOc",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525790979
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 23
step-start
{
  "type": "step-start",
  "id": "prt_19677e660001uL7N1Ea73fkmmu",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19677b91b001mP8GZDrQEPcoat"
}
Reasoning
Combine prior summary with new conversation progress. Key new findings:

- Read permission: only `/source` paths readable (rule gated).
- Read formatter.go: `mergedEventAttributes` drops empty values (lines 96-98 per assistant reasoning; formatter.go is only 87 lines shown but truncated note said truncated — reasoning references lines 96-98 of mergedEventAttributes). Resolved candidate issue: `state=""` omitted — `TestInterfaceEventOmitsUnknownValues` not an issue.
- Read stream.go (first ~70 lines): Stream looks fine; errs channel concern resolved (errCh buffered 1, forwardRuntimeEvents closes it).
- Read events.go: StreamEvents spawns 4 goroutines (trackContainers, pollInterfaces, watchTopologies, watchNodes, watchPods — actually 5 goroutines: trackContainers, pollInterfaces, watchTopologies, watchNodes, watchPods; errs chan buffer 4). pollInterfaces doesn't write to errs. So 4 error-writing goroutines → buffer 4 OK.
- Read container_events.go (partial): analyzed; mostly sound; minor note about early return on labStates error leaving watch goroutines stalled until ctx done — deemed acceptable (P3/P4).
- Read iface_stats.go (partial, truncated): analysis of sample()/processSample; candidate issue about sample.err considered graceful degradation, acceptable.
- Read netlink.go (partial): confirms labRuntimeInterfaceAttributes sets attributes["state"] unconditionally; mergedEventAttributes drops empties → resolved.
- Read core/labruntime.go lines 440-720: containerFromLabNode — candidate issue about NodeType override; deemed P4 at most; needs check whether topology loader always sets NodeType.
- Read diff.txt offset 4396 (final chunk): diff fully read now. Noted: nodeStateFromResource adds TopologyName from labelOriginalNodeName, Type/Group from spec; newestPod prefers non-deleting pods; robot tests expectations match implementation (kill die destroy for destroy; kill stop die for stop; health_status: healthy).
- Read manifest.json again (truncated at path 17).
- Grep for annotationDirectNodeUID and labelOriginalNodeName: both defined in clabernetes.go (lines 34-41); used in state.go:54,227; set in tests; labelOriginalNodeName set in names.go:51-55. So annotationDirectNodeUID contract is with c9s controller (set via annotations) — it's read in state.go:227.

Next steps: read remaining head files (state.go, topology.go, manifests.go, plan.go, primitives.go, reconcile.go, capture_interfaces.go, capture.go, clabernetes.go full, runtime.go, remaining test files, docs, robot tests), re-read manifest.json for remaining changed paths (after path 17: likely state.go, topology.go, etc. — 9 remaining), finalize findings, emit trusted result schema with no-test-execution disclosure.

Keep prior summary's unresolved items:
- errs chan sizing: resolved (buffer 4, 4 error-writing goroutines: trackContainers, watchTopologies, watchNodes, watchPods; pollInterfaces doesn't write errs). Actually need to double check pollInterfaces signature: `go r.pollInterfaces(ctx, scope, interfacePollOptions{...}, events)` — no errs. So OK.
- containerFromLabNode NodeType override: still open P4 candidate.
- managementAddress CIDR parity: still open.
- WithLabNameOnly / byName mode semantics: partially reasoned; c.Config.Topology nil → fallback to runtime state values; still worth confirming.
- ProcessSample sample.err: analyzed, deemed graceful degradation/acceptable.

Work state: mostly reading phase done for core events + c9s events/container_events/iface_stats/labruntime portions; diff fully read.

Next move: read remaining manifest paths, state.go, topology files, capture files, runtime.go, tests, docs, robot tests; verify NodeType in topology loader; then finalize schema.
## Objective
- Perform a source-only PR review of the read-only snapshot at `/source` (containerlab repo, srl-labs/containerlab): read `standards.json` and referenced rules, analyze `diff.txt` and head/base files, track all 26 changed paths from `manifest.json`, complete checks for each changed path plus relevant callers/tests/docs/schema, then return a trusted result schema. No test execution allowed — limitation must be disclosed in the final result.

## Important Details
- Head: `1566c3b8e3cb58c82d238dedbfa3b319249bab0a`; base: `b4de5d55cf17262e39325a7e125a6d3cb2c89318` (merge base identical). Permalink roots: head=`https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/`, base=`https://github.com/srl-labs/containerlab/blob/b4de5d55cf17262e39325a7e125a6d3cb2c89318/`.
- Snapshot incomplete: false; full inventory in `/source/manifest.json`.
- Standards loaded: `.cursor/rules/karpathy-guidelines.mdc` and `.cursor/rules/ponytail.mdc` (surgical changes, simplicity first, surface assumptions, shortest working diff, root-cause fixes, grep every caller of touched functions).
- 26 changed paths; confirmed so far (17): M `core/events/netlink.go`; A `core/events/parity_test.go`; M `core/events/stream.go`; M `core/labruntime.go`; M `core/labruntime_gaps_test.go`; M `docs/cmd/events.md`; M `docs/cmd/inspect/interfaces.md`; M `docs/manual/clabernetes/runtime.md`; M `labruntime/clabernetes/capture.go`; M `labruntime/clabernetes/capture_interfaces.go`; M `labruntime/clabernetes/capture_test.go`; M `labruntime/clabernetes/clabernetes.go`; M `labruntime/clabernetes/clabernetes_test.go`; A `labruntime/clabernetes/container_events.go`; A `labruntime/clabernetes/event_parity_test.go`; M `labruntime/clabernetes/events.go`; M `labruntime/clabernetes/iface_stats.go` (+9 remaining paths to read from manifest.json, likely incl. `state.go`, `topology.go`, robot tests).
- Tool permission constraint: only `/source` paths are readable (read tool is permission-gated; `/source` and `/source/*` allowed, `/` and `/tmp/...` denied).
- PR theme: clabernetes (c9s) lab-runtime event parity with Docker runtime — new container event tracker (`container_events.go`), interface event parity (`netlink.go` attributes), poller changes (`iface_stats.go`), topology source file annotation recording/carry-over, c9s `NodeState` enrichment (`TopoFile`, `Type`, `Group`, `TopologyName` from `labelOriginalNodeName` = `c9s.run/originalNodeName`, `annotationDirectNodeUID` = `c9s.run/direct-node-uid`, `newestPod` now prefers non-deleting pods).
- Status of candidate issues:
  - RESOLVED: `mergedEventAttributes` (formatter.go) drops empty attribute values — the `state=""` set by `interfaceSnapshotAttributes` is omitted, so `TestInterfaceEventOmitsUnknownValues` is not an issue.
  - RESOLVED: `stream.go` errs handling is fine — `errCh` buffered 1, `forwardRuntimeEvents` closes it.
  - RESOLVED: errs chan sizing in c9s `StreamEvents` — buffer 4 matches the 4 error-writing goroutines (`trackContainers`, `watchTopologies`, `watchNodes`, `watchPods`); `pollInterfaces` does not write errs.
  - ANALYZED/acceptable: `trackContainers` early-return on `labStates` error leaves watch goroutines blocked on `sendChangedLab` (buffer 256) until ctx done; mitigated by `Stream`'s deferred cancel on error — P3/P4 at most.
  - ANALYZED/acceptable: `processSample` skipped when `sample.err != nil` (nodeLinks/clabwire listing failure) drops that round's stats — graceful degradation, likely acceptable.
  - OPEN (P4 candidate): `containerFromLabNode` unconditionally overrides `node.Type`/group from loaded topology config (`c.Nodes[topologyNode].Config()`) even when the config's NodeType is empty; if user runs `clab events` with `--topo` of an edited topology, labels reflect the edit; with byName mode (`c.Config.Topology == nil`) fallback to runtime state values works. Need to verify topology loader always sets `NodeType`.
  - OPEN: `managementAddress` CIDR parsing parity with `GetContainerIPv4` format (`172.20.20.x/24`).
  - OPEN: `WithLabNameOnly`, `labRuntimeTopologyPath(c, state)`, `c.topologyNodeName` semantics for byName mode.
  - RESOLVED: `annotationDirectNodeUID`/`labelOriginalNodeName` — defined in `clabernetes.go:34-41`; `labelOriginalNodeName` is set by the controller (`names.go:51-55`) and read in `state.go:54`, `capture.go:328`; `annotationDirectNodeUID` is read in `state.go:227` (set on pods by the c9s controller; contract with external controller, covered in tests).
  - RESOLVED: timer.Reset usage in `containerTracker` is safe (Reset only when !armed; select drains timer.C).
- Robot test parity confirmed: destroy of running node → `kill die destroy` (no stop); node stop → `kill stop die`; health_status events (`starting`→skip when new, `healthy` appended); `state`/`status`/`origin` attribute semantics consistent.

## Work State
### Completed
- Read `/source/standards.json` → two referenced rules; read both standards files.
- Read `/source/diff.txt` fully (offsets 1, 1362, 2845, 4396 — complete).
- Read `/source/manifest.json` (truncated at path 17 of 26; re-read needed for remaining paths).
- Read `/source/head/core/events/formatter.go` — confirmed `mergedEventAttributes` drops empty values (empty-attribute candidate resolved).
- Read `/source/head/core/events/stream.go` (beginning; Stream setup, netlinkRegistry wiring, snapshot emission, per-container `registry.Start`) — clean.
- Read `/source/head/labruntime/clabernetes/events.go` — `StreamEvents` spawns trackContainers, pollInterfaces, watchTopologies, watchNodes, watchPods; errs buffer 4 matches error writers.
- Read `/source/head/labruntime/clabernetes/container_events.go` (partial) — analyzed tracker: `refresh` retry semantics OK, `observeLab`/`observeNode`/`containerTransitionActions`/`containerHealth` parity logic sound, removal path uses `tracked.lab` (non-nil).
- Read `/source/head/labruntime/clabernetes/iface_stats.go` (partial) — `interfaceSampleScript` (one exec reads /proc/net/dev + sysfs), `interfaceSampleWorkers = 16`, `managementInterface = "eth0"`, `clabernetesAliasPrefix` filtering; analyzed sample/processSample error paths.
- Read `/source/head/core/events/netlink.go` (partial) — netlinkRegistry structure confirmed.
- Read `/source/head/core/labruntime.go` lines 440-720 — `containerFromLabNode`, `LabRuntimeContainer`, `labRuntimeContainerState`, `labRuntimePorts`, `managementAddress`, `labRuntimeTopologyPath`; analyzed NodeType override concern.
- Grepped `annotationDirectNodeUID|labelOriginalNodeName` — all 17 uses located and verified.
- Extensive static parity analysis: docker/c9s event action/attribute vocabulary, health transitions, pod restart flows, robot test expectations.

### Active
- Reading remaining head files not yet covered: `state.go`, `topology.go`, `manifests.go`, `plan.go`, `primitives.go`, `reconcile.go`, `capture_interfaces.go`, `capture.go` (full), `clabernetes.go` (full), `runtime.go`, all test files, docs files, robot tests.

### Blocked
- (none)

## Next Move
1. Re-read `/source/manifest.json` to capture the remaining 9 changed paths; then read `/source/head/labruntime/clabernetes/state.go`, `topology.go`, `manifests.go`, `plan.go`, `primitives.go`, `reconcile.go` (topology source file annotation recording/carry-over), `capture_interfaces.go`, `capture.go`, `clabernetes.go`, `labruntime/runtime.go` (Inspect/InspectRequest lab-not-found semantics).
2. Verify whether the topology loader always sets `NodeConfig.NodeType` (resolves the `containerFromLabNode` override candidate); check `managementAddress` CIDR parity and byName-mode semantics; read tests (`core/labruntime_gaps_test.go`, `event_parity_test.go`, `clabernetes_test.go`, `capture_test.go`), docs (`docs/cmd/events.md`, `docs/cmd/inspect/interfaces.md`, `docs/manual/clabernetes/runtime.md`), robot tests under `tests/01-smoke/`; finalize per-path findings and emit the trusted result schema (disclosing the no-test-execution limitation).

## Relevant Files
- `/source/standards.json`, `/source/standards/karpathy-guidelines.mdc`, `/source/standards/ponytail.mdc` — review standards (done).
- `/source/manifest.json` — changed-path inventory (truncated read; re-read for remaining ~9 paths).
- `/source/diff.txt` — full PR diff (fully read).
- `/source/head/core/events/formatter.go` — `mergedEventAttributes` drops empty attrs (verified; resolves state-attr candidate).
- `/source/head/core/events/stream.go` — Stream wiring, `streamLabRuntimeEvents` errs handling (verified fine); lines ~180-600 not yet re-read in detail.
- `/source/head/core/events/netlink.go` — `labRuntimeInterfaceAttributes`, `interfaceSnapshotAttributes`, `interfaceStatsAttributes`; partially read.
- `/source/head/core/events/parity_test.go` — new parity test; call sites 213/214/289/311/347/500/501/532.
- `/source/head/core/labruntime.go` — `containerFromLabNode` (lines 462-510 read), `labRuntimeContainerState` (:547), `labRuntimePorts` (:577), `managementAddress` (:620), `labRuntimeTopologyPath` (:662); lines 1-440 not yet read.
- `/source/head/labruntime/clabernetes/events.go` — `StreamEvents` goroutine/errs wiring (read).
- `/source/head/labruntime/clabernetes/container_events.go` — new tracker (partially read; rest of file to skim).
- `/source/head/labruntime/clabernetes/iface_stats.go` — poller (partially read; `processStates`, `processSample`, `round`, `retireStoppedNodes` bodies to verify).
- `/source/head/labruntime/clabernetes/state.go` — `enrichState`, `stateFromNodeResources`, `newestPod`, `nodeStateFromResource` (grep-verified lines 54, 227); full read pending.
- `/source/head/labruntime/clabernetes/{topology.go,manifests.go,plan.go,primitives.go,reconcile.go}` — topology source file annotation recording/carry-over; unread.
- `/source/head/labruntime/clabernetes/{capture_interfaces.go,capture.go,clabernetes.go,names.go}` — inspect interfaces, label definitions; partial reads only.
- `/source/head/labruntime/runtime.go` — Inspect/InspectRequest lab-not-found semantics; unread.
- `/source/head/core/labruntime_gaps_test.go`, `/source/head/labruntime/clabernetes/{clabernetes_test.go,capture_test.go,event_parity_test.go}` — modified/added tests; unread.
- `/source/head/docs/cmd/events.md`, `/source/head/docs/cmd/inspect/interfaces.md`, `/source/head/docs/manual/clabernetes/runtime.md` — docs parity; unread.
- `/source/head/tests/01-smoke/` — robot tests (`Container Actions Should Include In Order`, `Container Event Should Carry Docker Attributes`, `Interface Event Should Be Logged` with `@{states}`); expectations already cross-checked against diff, files not directly read.
step-finish
{
  "type": "step-finish",
  "id": "prt_196785f94001ztrzXvwjpjA5yD",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19677b91b001mP8GZDrQEPcoat",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 17032,
    "input": 13475,
    "output": 2737,
    "reasoning": 820,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19677b91b001mP8GZDrQEPcoat",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525791003,
    "completed": 1793525833625
  },
  "parentID": "msg_19677b903001XpuPfKo7EVPMOc",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "compaction",
  "agent": "compaction",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "summary": true,
  "cost": 0,
  "tokens": {
    "total": 17032,
    "input": 13475,
    "output": 2737,
    "reasoning": 820,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "stop"
}
User · 24
Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.
Message metadata
{
  "role": "user",
  "id": "msg_196785f9c001RzWg2gr7EYUdBK",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525833628
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 25
step-start
{
  "type": "step-start",
  "id": "prt_196786ae6001wVyJ4SAsEpTYut",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196785fa8001hEk0acQLRaHhES"
}
Reasoning
Continue. Remaining to read:

1. topology.go, plan.go, primitives.go, reconcile.go — topology source file annotation recording/carry-over.
2. capture.go (full, esp. listCaptureInterfaces, reportedInterfaces, c9sIfaceState, interfaceEventData usage).
3. clabernetes.go (constants: annotationDirectNodeUID, labelOriginalNodeName, managementInterface, loopbackInterface, clabernetesAliasPrefix).
4. core/labruntime.go lines 1-440 (context: TopoFile, Inspect semantics).
5. labruntime/runtime.go (Inspect / InspectInterfaces for lab-not-found).
6. Tests: parity_test.go, event_parity_test.go, labruntime_gaps_test.go, runtime_gaps_test.go, clabernetes_test.go, capture_test.go.
7. Docs: events.md, interfaces.md, runtime.md.
8. Robot tests.

Let me batch reads.
Continuing. Next: the topology-source-file annotation changes and the constants file.
read · completed

Input

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

Output

<path>/source/head/labruntime/clabernetes/topology.go</path>
<type>file</type>
<content>
1: package clabernetes
2: 
3: import (
4: 	"fmt"
5: 	"sort"
6: 
7: 	"github.com/charmbracelet/log"
8: 	clabconstants "github.com/srl-labs/containerlab/constants"
9: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
10: 	"gopkg.in/yaml.v2"
11: 	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
12: 	"k8s.io/apimachinery/pkg/util/validation"
13: )
14: 
15: type topologyObjectOption func(map[string]any)
16: 
17: // annotationTopologyFile records the absolute path of the topology file a lab was deployed from,
18: // on the machine that deployed it. Inspect reports it as the lab's topology path and events as
19: // clab-topo-file, as the local runtimes do, so clients match the running lab to its file. A lab
20: // created by other means than a containerlab deploy has no annotation and reports where its
21: // definition lives in the cluster (k8s://<namespace>/topologies/<lab>).
22: const annotationTopologyFile = "containerlab.dev/topo-file"
23: 
24: // setTopologySourceFile records the topology file a deploy reads on the Topology. An empty path
25: // (a definition that came from no file) records nothing.
26: func setTopologySourceFile(topology *unstructured.Unstructured, path string) {
27: 	if path == "" {
28: 		return
29: 	}
30: 
31: 	annotations := topology.GetAnnotations()
32: 	if annotations == nil {
33: 		annotations = map[string]string{}
34: 	}
35: 	annotations[annotationTopologyFile] = path
36: 	topology.SetAnnotations(annotations)
37: }
38: 
39: // removeTopologySourceFile drops the deploying machine's file path from an object.
40: func removeTopologySourceFile(obj *unstructured.Unstructured) {
41: 	annotations := obj.GetAnnotations()
42: 	if _, ok := annotations[annotationTopologyFile]; !ok {
43: 		return
44: 	}
45: 
46: 	delete(annotations, annotationTopologyFile)
47: 	if len(annotations) == 0 {
48: 		annotations = nil
49: 	}
50: 	obj.SetAnnotations(annotations)
51: }
52: 
53: // labTopologyPath is the topology path a lab reports: the file it was deployed from when the
54: // deploy recorded one, otherwise the place given.
55: func labTopologyPath(annotations map[string]string, fallback string) string {
56: 	if path := annotations[annotationTopologyFile]; path != "" {
57: 		return path
58: 	}
59: 
60: 	return fallback
61: }
62: 
63: func topologyWithNaming(naming string) topologyObjectOption {
64: 	return func(spec map[string]any) {
65: 		if naming != "" {
66: 			spec["naming"] = naming
67: 		}
68: 	}
69: }
70: 
71: // topologyWithImagePullSecret sets the image pull secret the kubelet uses when pulling device
72: // images. An empty name leaves imagePull unset entirely: the controller fails closed on a named
73: // Secret that does not exist, so a Topology must only reference one the deploy actually asked
74: // for.
75: func topologyWithImagePullSecret(secret string) topologyObjectOption {
76: 	return func(spec map[string]any) {
77: 		if secret == "" {
78: 			return
79: 		}
80: 		spec["imagePull"] = map[string]any{
81: 			"pullSecrets": []any{secret},
82: 		}
83: 	}
84: }
85: 
86: func topologyWithExposeType(exposeType string) topologyObjectOption {
87: 	return func(spec map[string]any) {
88: 		if exposeType == "" {
89: 			return
90: 		}
91: 		spec["expose"] = map[string]any{
92: 			"exposeType": exposeType,
93: 		}
94: 	}
95: }
96: 
97: // topologyWithPersistence backs each node's artifact volume with a persistent claim so saved
98: // device configuration survives Pod replacement, the same contract a local runtime provides
99: // through the lab directory. The claims are retained when their Node is deleted, so a plain
100: // destroy keeps the saved configuration like the local lab directory, and a redeploy boots from
101: // it; destroy --cleanup deletes them. Disabled leaves persistence unset entirely: ephemeral
102: // storage is the CRD default.
103: func topologyWithPersistence(enabled bool) topologyObjectOption {
104: 	return func(spec map[string]any) {
105: 		if !enabled {
106: 			return
107: 		}
108: 		deployment, ok := spec["deployment"].(map[string]any)
109: 		if !ok {
110: 			deployment = map[string]any{}
111: 			spec["deployment"] = deployment
112: 		}
113: 		deployment["persistence"] = map[string]any{
114: 			"enabled": true,
115: 			"reclaim": persistenceReclaimRetain,
116: 		}
117: 	}
118: }
119: 
120: func topologyObject(
121: 	name,
122: 	namespace,
123: 	owner,
124: 	definition string,
125: 	opts ...topologyObjectOption,
126: ) *unstructured.Unstructured {
127: 	topologyLabels := map[string]any{
128: 		"containerlab.dev/runtime": clablabruntime.ClabernetesRuntimeName,
129: 	}
130: 	topologyAnnotations := map[string]any{}
131: 	if owner != "" {
132: 		topologyAnnotations[clabconstants.Owner] = owner
133: 		if len(validation.IsValidLabelValue(owner)) == 0 {
134: 			topologyLabels[clabconstants.Owner] = owner
135: 		}
136: 	}
137: 
138: 	metadata := map[string]any{
139: 		"name":      name,
140: 		"namespace": namespace,
141: 		"labels":    topologyLabels,
142: 	}
143: 	if len(topologyAnnotations) != 0 {
144: 		metadata["annotations"] = topologyAnnotations
145: 	}
146: 
147: 	spec := map[string]any{
148: 		"definition": map[string]any{
149: 			"containerlab": definition,
150: 		},
151: 		// The runtime's readiness contract requires c9s status probes. Persist the setting
152: 		// explicitly: CRD defaulting cannot materialize it in an absent statusProbes object, and
153: 		// the controller's typed writes would then pin the zero value (disabled) instead. This
154: 		// mirrors configurePrimitiveReadiness on the client-side compile.
155: 		"statusProbes": map[string]any{
156: 			"enabled": true,
157: 		},
158: 	}
159: 	for _, opt := range opts {
160: 		opt(spec)
161: 	}
162: 
163: 	return &unstructured.Unstructured{
164: 		Object: map[string]any{
165: 			"apiVersion": c9sAPIVersion,
166: 			"kind":       "Topology",
167: 			"metadata":   metadata,
168: 			"spec":       spec,
169: 		},
170: 	}
171: }
172: 
173: // stateFromTopology builds the lab-state skeleton from a Topology CR. The direct-runtime
174: // Topology status intentionally carries only aggregate readiness -- per-node detail is always
175: // filled in from the Node objects and workloads by enrichState.
176: func stateFromTopology(obj *unstructured.Unstructured, namespace string) *clablabruntime.LabState {
177: 	if obj.GetNamespace() != "" {
178: 		namespace = obj.GetNamespace()
179: 	}
180: 
181: 	ready, _, _ := unstructured.NestedBool(obj.Object, "status", "topologyReady")
182: 	state, _, _ := unstructured.NestedString(obj.Object, "status", "topologyState")
183: 	owner := obj.GetLabels()[clabconstants.Owner]
184: 	if owner == "" {
185: 		owner = obj.GetAnnotations()[clabconstants.Owner]
186: 	}
187: 	nodeSpecs := nodeSpecsFromTopology(obj)
188: 	topologyPath := labTopologyPath(
189: 		obj.GetAnnotations(),
190: 		fmt.Sprintf("k8s://%s/topologies/%s", namespace, obj.GetName()),
191: 	)
192: 
193: 	nodeNames := make([]string, 0, len(nodeSpecs))
194: 	for nodeName := range nodeSpecs {
195: 		nodeNames = append(nodeNames, nodeName)
196: 	}
197: 	sort.Strings(nodeNames)
198: 
199: 	nodes := make([]clablabruntime.NodeState, 0, len(nodeNames))
200: 	for _, nodeName := range nodeNames {
201: 		spec := nodeSpecs[nodeName]
202: 		nodes = append(nodes, clablabruntime.NodeState{
203: 			Name:  nodeName,
204: 			Kind:  spec.Kind,
205: 			Image: spec.Image,
206: 		})
207: 	}
208: 
209: 	return &clablabruntime.LabState{
210: 		Name:         obj.GetName(),
211: 		Namespace:    namespace,
212: 		Owner:        owner,
213: 		TopologyPath: topologyPath,
214: 		State:        state,
215: 		Ready:        ready,
216: 		Nodes:        nodes,
217: 	}
218: }
219: 
220: type nodeSpec struct {
221: 	Kind  string `yaml:"kind"`
222: 	Image string `yaml:"image"`
223: }
224: 
225: type containerlabDefinition struct {
226: 	Topology struct {
227: 		Nodes map[string]nodeSpec `yaml:"nodes"`
228: 	} `yaml:"topology"`
229: }
230: 
231: func nodeSpecsFromTopology(obj *unstructured.Unstructured) map[string]nodeSpec {
232: 	specs := map[string]nodeSpec{}
233: 
234: 	definition, _, _ := unstructured.NestedString(
235: 		obj.Object,
236: 		"spec",
237: 		"definition",
238: 		"containerlab",
239: 	)
240: 	mergeNodeSpecs(specs, definition)
241: 
242: 	return specs
243: }
244: 
245: func mergeNodeSpecs(specs map[string]nodeSpec, definition string) {
246: 	if definition == "" {
247: 		return
248: 	}
249: 
250: 	var parsed containerlabDefinition
251: 	if err := yaml.Unmarshal([]byte(definition), &parsed); err != nil {
252: 		log.Debug("failed to parse C9s topology definition", "error", err)
253: 		return
254: 	}
255: 
256: 	for nodeName, spec := range parsed.Topology.Nodes {
257: 		specs[nodeName] = spec
258: 	}
259: }

(End of file - total 259 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196789af9001ua9JiLwHlDlxnD",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196785fa8001hEk0acQLRaHhES",
  "callID": "call_fd2dce9da5e54630bc4cc7c1",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/topology.go"
    },
    "output": "<path>/source/head/labruntime/clabernetes/topology.go</path>\n<type>file</type>\n<content>\n1: package clabernetes\n2: \n3: import (\n4: \t\"fmt\"\n5: \t\"sort\"\n6: \n7: \t\"github.com/charmbracelet/log\"\n8: \tclabconstants \"github.com/srl-labs/containerlab/constants\"\n9: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n10: \t\"gopkg.in/yaml.v2\"\n11: \t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n12: \t\"k8s.io/apimachinery/pkg/util/validation\"\n13: )\n14: \n15: type topologyObjectOption func(map[string]any)\n16: \n17: // annotationTopologyFile records the absolute path of the topology file a lab was deployed from,\n18: // on the machine that deployed it. Inspect reports it as the lab's topology path and events as\n19: // clab-topo-file, as the local runtimes do, so clients match the running lab to its file. A lab\n20: // created by other means than a containerlab deploy has no annotation and reports where its\n21: // definition lives in the cluster (k8s://<namespace>/topologies/<lab>).\n22: const annotationTopologyFile = \"containerlab.dev/topo-file\"\n23: \n24: // setTopologySourceFile records the topology file a deploy reads on the Topology. An empty path\n25: // (a definition that came from no file) records nothing.\n26: func setTopologySourceFile(topology *unstructured.Unstructured, path string) {\n27: \tif path == \"\" {\n28: \t\treturn\n29: \t}\n30: \n31: \tannotations := topology.GetAnnotations()\n32: \tif annotations == nil {\n33: \t\tannotations = map[string]string{}\n34: \t}\n35: \tannotations[annotationTopologyFile] = path\n36: \ttopology.SetAnnotations(annotations)\n37: }\n38: \n39: // removeTopologySourceFile drops the deploying machine's file path from an object.\n40: func removeTopologySourceFile(obj *unstructured.Unstructured) {\n41: \tannotations := obj.GetAnnotations()\n42: \tif _, ok := annotations[annotationTopologyFile]; !ok {\n43: \t\treturn\n44: \t}\n45: \n46: \tdelete(annotations, annotationTopologyFile)\n47: \tif len(annotations) == 0 {\n48: \t\tannotations = nil\n49: \t}\n50: \tobj.SetAnnotations(annotations)\n51: }\n52: \n53: // labTopologyPath is the topology path a lab reports: the file it was deployed from when the\n54: // deploy recorded one, otherwise the place given.\n55: func labTopologyPath(annotations map[string]string, fallback string) string {\n56: \tif path := annotations[annotationTopologyFile]; path != \"\" {\n57: \t\treturn path\n58: \t}\n59: \n60: \treturn fallback\n61: }\n62: \n63: func topologyWithNaming(naming string) topologyObjectOption {\n64: \treturn func(spec map[string]any) {\n65: \t\tif naming != \"\" {\n66: \t\t\tspec[\"naming\"] = naming\n67: \t\t}\n68: \t}\n69: }\n70: \n71: // topologyWithImagePullSecret sets the image pull secret the kubelet uses when pulling device\n72: // images. An empty name leaves imagePull unset entirely: the controller fails closed on a named\n73: // Secret that does not exist, so a Topology must only reference one the deploy actually asked\n74: // for.\n75: func topologyWithImagePullSecret(secret string) topologyObjectOption {\n76: \treturn func(spec map[string]any) {\n77: \t\tif secret == \"\" {\n78: \t\t\treturn\n79: \t\t}\n80: \t\tspec[\"imagePull\"] = map[string]any{\n81: \t\t\t\"pullSecrets\": []any{secret},\n82: \t\t}\n83: \t}\n84: }\n85: \n86: func topologyWithExposeType(exposeType string) topologyObjectOption {\n87: \treturn func(spec map[string]any) {\n88: \t\tif exposeType == \"\" {\n89: \t\t\treturn\n90: \t\t}\n91: \t\tspec[\"expose\"] = map[string]any{\n92: \t\t\t\"exposeType\": exposeType,\n93: \t\t}\n94: \t}\n95: }\n96: \n97: // topologyWithPersistence backs each node's artifact volume with a persistent claim so saved\n98: // device configuration survives Pod replacement, the same contract a local runtime provides\n99: // through the lab directory. The claims are retained when their Node is deleted, so a plain\n100: // destroy keeps the saved configuration like the local lab directory, and a redeploy boots from\n101: // it; destroy --cleanup deletes them. Disabled leaves persistence unset entirely: ephemeral\n102: // storage is the CRD default.\n103: func topologyWithPersistence(enabled bool) topologyObjectOption {\n104: \treturn func(spec map[string]any) {\n105: \t\tif !enabled {\n106: \t\t\treturn\n107: \t\t}\n108: \t\tdeployment, ok := spec[\"deployment\"].(map[string]any)\n109: \t\tif !ok {\n110: \t\t\tdeployment = map[string]any{}\n111: \t\t\tspec[\"deployment\"] = deployment\n112: \t\t}\n113: \t\tdeployment[\"persistence\"] = map[string]any{\n114: \t\t\t\"enabled\": true,\n115: \t\t\t\"reclaim\": persistenceReclaimRetain,\n116: \t\t}\n117: \t}\n118: }\n119: \n120: func topologyObject(\n121: \tname,\n122: \tnamespace,\n123: \towner,\n124: \tdefinition string,\n125: \topts ...topologyObjectOption,\n126: ) *unstructured.Unstructured {\n127: \ttopologyLabels := map[string]any{\n128: \t\t\"containerlab.dev/runtime\": clablabruntime.ClabernetesRuntimeName,\n129: \t}\n130: \ttopologyAnnotations := map[string]any{}\n131: \tif owner != \"\" {\n132: \t\ttopologyAnnotations[clabconstants.Owner] = owner\n133: \t\tif len(validation.IsValidLabelValue(owner)) == 0 {\n134: \t\t\ttopologyLabels[clabconstants.Owner] = owner\n135: \t\t}\n136: \t}\n137: \n138: \tmetadata := map[string]any{\n139: \t\t\"name\":      name,\n140: \t\t\"namespace\": namespace,\n141: \t\t\"labels\":    topologyLabels,\n142: \t}\n143: \tif len(topologyAnnotations) != 0 {\n144: \t\tmetadata[\"annotations\"] = topologyAnnotations\n145: \t}\n146: \n147: \tspec := map[string]any{\n148: \t\t\"definition\": map[string]any{\n149: \t\t\t\"containerlab\": definition,\n150: \t\t},\n151: \t\t// The runtime's readiness contract requires c9s status probes. Persist the setting\n152: \t\t// explicitly: CRD defaulting cannot materialize it in an absent statusProbes object, and\n153: \t\t// the controller's typed writes would then pin the zero value (disabled) instead. This\n154: \t\t// mirrors configurePrimitiveReadiness on the client-side compile.\n155: \t\t\"statusProbes\": map[string]any{\n156: \t\t\t\"enabled\": true,\n157: \t\t},\n158: \t}\n159: \tfor _, opt := range opts {\n160: \t\topt(spec)\n161: \t}\n162: \n163: \treturn &unstructured.Unstructured{\n164: \t\tObject: map[string]any{\n165: \t\t\t\"apiVersion\": c9sAPIVersion,\n166: \t\t\t\"kind\":       \"Topology\",\n167: \t\t\t\"metadata\":   metadata,\n168: \t\t\t\"spec\":       spec,\n169: \t\t},\n170: \t}\n171: }\n172: \n173: // stateFromTopology builds the lab-state skeleton from a Topology CR. The direct-runtime\n174: // Topology status intentionally carries only aggregate readiness -- per-node detail is always\n175: // filled in from the Node objects and workloads by enrichState.\n176: func stateFromTopology(obj *unstructured.Unstructured, namespace string) *clablabruntime.LabState {\n177: \tif obj.GetNamespace() != \"\" {\n178: \t\tnamespace = obj.GetNamespace()\n179: \t}\n180: \n181: \tready, _, _ := unstructured.NestedBool(obj.Object, \"status\", \"topologyReady\")\n182: \tstate, _, _ := unstructured.NestedString(obj.Object, \"status\", \"topologyState\")\n183: \towner := obj.GetLabels()[clabconstants.Owner]\n184: \tif owner == \"\" {\n185: \t\towner = obj.GetAnnotations()[clabconstants.Owner]\n186: \t}\n187: \tnodeSpecs := nodeSpecsFromTopology(obj)\n188: \ttopologyPath := labTopologyPath(\n189: \t\tobj.GetAnnotations(),\n190: \t\tfmt.Sprintf(\"k8s://%s/topologies/%s\", namespace, obj.GetName()),\n191: \t)\n192: \n193: \tnodeNames := make([]string, 0, len(nodeSpecs))\n194: \tfor nodeName := range nodeSpecs {\n195: \t\tnodeNames = append(nodeNames, nodeName)\n196: \t}\n197: \tsort.Strings(nodeNames)\n198: \n199: \tnodes := make([]clablabruntime.NodeState, 0, len(nodeNames))\n200: \tfor _, nodeName := range nodeNames {\n201: \t\tspec := nodeSpecs[nodeName]\n202: \t\tnodes = append(nodes, clablabruntime.NodeState{\n203: \t\t\tName:  nodeName,\n204: \t\t\tKind:  spec.Kind,\n205: \t\t\tImage: spec.Image,\n206: \t\t})\n207: \t}\n208: \n209: \treturn &clablabruntime.LabState{\n210: \t\tName:         obj.GetName(),\n211: \t\tNamespace:    namespace,\n212: \t\tOwner:        owner,\n213: \t\tTopologyPath: topologyPath,\n214: \t\tState:        state,\n215: \t\tReady:        ready,\n216: \t\tNodes:        nodes,\n217: \t}\n218: }\n219: \n220: type nodeSpec struct {\n221: \tKind  string `yaml:\"kind\"`\n222: \tImage string `yaml:\"image\"`\n223: }\n224: \n225: type containerlabDefinition struct {\n226: \tTopology struct {\n227: \t\tNodes map[string]nodeSpec `yaml:\"nodes\"`\n228: \t} `yaml:\"topology\"`\n229: }\n230: \n231: func nodeSpecsFromTopology(obj *unstructured.Unstructured) map[string]nodeSpec {\n232: \tspecs := map[string]nodeSpec{}\n233: \n234: \tdefinition, _, _ := unstructured.NestedString(\n235: \t\tobj.Object,\n236: \t\t\"spec\",\n237: \t\t\"definition\",\n238: \t\t\"containerlab\",\n239: \t)\n240: \tmergeNodeSpecs(specs, definition)\n241: \n242: \treturn specs\n243: }\n244: \n245: func mergeNodeSpecs(specs map[string]nodeSpec, definition string) {\n246: \tif definition == \"\" {\n247: \t\treturn\n248: \t}\n249: \n250: \tvar parsed containerlabDefinition\n251: \tif err := yaml.Unmarshal([]byte(definition), &parsed); err != nil {\n252: \t\tlog.Debug(\"failed to parse C9s topology definition\", \"error\", err)\n253: \t\treturn\n254: \t}\n255: \n256: \tfor nodeName, spec := range parsed.Topology.Nodes {\n257: \t\tspecs[nodeName] = spec\n258: \t}\n259: }\n\n(End of file - total 259 lines)\n</content>",
    "title": "source/head/labruntime/clabernetes/topology.go",
    "metadata": {
      "preview": "package clabernetes\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t\"github.com/charmbracelet/log\"\n\tclabconstants \"github.com/srl-labs/containerlab/constants\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\t\"gopkg.in/yaml.v2\"\n\t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n\t\"k8s.io/apimachinery/pkg/util/validation\"\n)\n\ntype topologyObjectOption func(map[string]any)\n\n// annotationTopologyFile records the absolute path of the topology file a lab was deployed from,\n// on the machine that deployed it. Inspect reports it as the lab's topology path and events as\n// clab-topo-file, as the local runtimes do, so clients match the running lab to its file. A lab\n// created by other means than a containerlab deploy has no annotation and reports where its",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/topology.go",
        "text": "package clabernetes\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t\"github.com/charmbracelet/log\"\n\tclabconstants \"github.com/srl-labs/containerlab/constants\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\t\"gopkg.in/yaml.v2\"\n\t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n\t\"k8s.io/apimachinery/pkg/util/validation\"\n)\n\ntype topologyObjectOption func(map[string]any)\n\n// annotationTopologyFile records the absolute path of the topology file a lab was deployed from,\n// on the machine that deployed it. Inspect reports it as the lab's topology path and events as\n// clab-topo-file, as the local runtimes do, so clients match the running lab to its file. A lab\n// created by other means than a containerlab deploy has no annotation and reports where its\n// definition lives in the cluster (k8s://<namespace>/topologies/<lab>).\nconst annotationTopologyFile = \"containerlab.dev/topo-file\"\n\n// setTopologySourceFile records the topology file a deploy reads on the Topology. An empty path\n// (a definition that came from no file) records nothing.\nfunc setTopologySourceFile(topology *unstructured.Unstructured, path string) {\n\tif path == \"\" {\n\t\treturn\n\t}\n\n\tannotations := topology.GetAnnotations()\n\tif annotations == nil {\n\t\tannotations = map[string]string{}\n\t}\n\tannotations[annotationTopologyFile] = path\n\ttopology.SetAnnotations(annotations)\n}\n\n// removeTopologySourceFile drops the deploying machine's file path from an object.\nfunc removeTopologySourceFile(obj *unstructured.Unstructured) {\n\tannotations := obj.GetAnnotations()\n\tif _, ok := annotations[annotationTopologyFile]; !ok {\n\t\treturn\n\t}\n\n\tdelete(annotations, annotationTopologyFile)\n\tif len(annotations) == 0 {\n\t\tannotations = nil\n\t}\n\tobj.SetAnnotations(annotations)\n}\n\n// labTopologyPath is the topology path a lab reports: the file it was deployed from when the\n// deploy recorded one, otherwise the place given.\nfunc labTopologyPath(annotations map[string]string, fallback string) string {\n\tif path := annotations[annotationTopologyFile]; path != \"\" {\n\t\treturn path\n\t}\n\n\treturn fallback\n}\n\nfunc topologyWithNaming(naming string) topologyObjectOption {\n\treturn func(spec map[string]any) {\n\t\tif naming != \"\" {\n\t\t\tspec[\"naming\"] = naming\n\t\t}\n\t}\n}\n\n// topologyWithImagePullSecret sets the image pull secret the kubelet uses when pulling device\n// images. An empty name leaves imagePull unset entirely: the controller fails closed on a named\n// Secret that does not exist, so a Topology must only reference one the deploy actually asked\n// for.\nfunc topologyWithImagePullSecret(secret string) topologyObjectOption {\n\treturn func(spec map[string]any) {\n\t\tif secret == \"\" {\n\t\t\treturn\n\t\t}\n\t\tspec[\"imagePull\"] = map[string]any{\n\t\t\t\"pullSecrets\": []any{secret},\n\t\t}\n\t}\n}\n\nfunc topologyWithExposeType(exposeType string) topologyObjectOption {\n\treturn func(spec map[string]any) {\n\t\tif exposeType == \"\" {\n\t\t\treturn\n\t\t}\n\t\tspec[\"expose\"] = map[string]any{\n\t\t\t\"exposeType\": exposeType,\n\t\t}\n\t}\n}\n\n// topologyWithPersistence backs each node's artifact volume with a persistent claim so saved\n// device configuration survives Pod replacement, the same contract a local runtime provides\n// through the lab directory. The claims are retained when their Node is deleted, so a plain\n// destroy keeps the saved configuration like the local lab directory, and a redeploy boots from\n// it; destroy --cleanup deletes them. Disabled leaves persistence unset entirely: ephemeral\n// storage is the CRD default.\nfunc topologyWithPersistence(enabled bool) topologyObjectOption {\n\treturn func(spec map[string]any) {\n\t\tif !enabled {\n\t\t\treturn\n\t\t}\n\t\tdeployment, ok := spec[\"deployment\"].(map[string]any)\n\t\tif !ok {\n\t\t\tdeployment = map[string]any{}\n\t\t\tspec[\"deployment\"] = deployment\n\t\t}\n\t\tdeployment[\"persistence\"] = map[string]any{\n\t\t\t\"enabled\": true,\n\t\t\t\"reclaim\": persistenceReclaimRetain,\n\t\t}\n\t}\n}\n\nfunc topologyObject(\n\tname,\n\tnamespace,\n\towner,\n\tdefinition string,\n\topts ...topologyObjectOption,\n) *unstructured.Unstructured {\n\ttopologyLabels := map[string]any{\n\t\t\"containerlab.dev/runtime\": clablabruntime.ClabernetesRuntimeName,\n\t}\n\ttopologyAnnotations := map[string]any{}\n\tif owner != \"\" {\n\t\ttopologyAnnotations[clabconstants.Owner] = owner\n\t\tif len(validation.IsValidLabelValue(owner)) == 0 {\n\t\t\ttopologyLabels[clabconstants.Owner] = owner\n\t\t}\n\t}\n\n\tmetadata := map[string]any{\n\t\t\"name\":      name,\n\t\t\"namespace\": namespace,\n\t\t\"labels\":    topologyLabels,\n\t}\n\tif len(topologyAnnotations) != 0 {\n\t\tmetadata[\"annotations\"] = topologyAnnotations\n\t}\n\n\tspec := map[string]any{\n\t\t\"definition\": map[string]any{\n\t\t\t\"containerlab\": definition,\n\t\t},\n\t\t// The runtime's readiness contract requires c9s status probes. Persist the setting\n\t\t// explicitly: CRD defaulting cannot materialize it in an absent statusProbes object, and\n\t\t// the controller's typed writes would then pin the zero value (disabled) instead. This\n\t\t// mirrors configurePrimitiveReadiness on the client-side compile.\n\t\t\"statusProbes\": map[string]any{\n\t\t\t\"enabled\": true,\n\t\t},\n\t}\n\tfor _, opt := range opts {\n\t\topt(spec)\n\t}\n\n\treturn &unstructured.Unstructured{\n\t\tObject: map[string]any{\n\t\t\t\"apiVersion\": c9sAPIVersion,\n\t\t\t\"kind\":       \"Topology\",\n\t\t\t\"metadata\":   metadata,\n\t\t\t\"spec\":       spec,\n\t\t},\n\t}\n}\n\n// stateFromTopology builds the lab-state skeleton from a Topology CR. The direct-runtime\n// Topology status intentionally carries only aggregate readiness -- per-node detail is always\n// filled in from the Node objects and workloads by enrichState.\nfunc stateFromTopology(obj *unstructured.Unstructured, namespace string) *clablabruntime.LabState {\n\tif obj.GetNamespace() != \"\" {\n\t\tnamespace = obj.GetNamespace()\n\t}\n\n\tready, _, _ := unstructured.NestedBool(obj.Object, \"status\", \"topologyReady\")\n\tstate, _, _ := unstructured.NestedString(obj.Object, \"status\", \"topologyState\")\n\towner := obj.GetLabels()[clabconstants.Owner]\n\tif owner == \"\" {\n\t\towner = obj.GetAnnotations()[clabconstants.Owner]\n\t}\n\tnodeSpecs := nodeSpecsFromTopology(obj)\n\ttopologyPath := labTopologyPath(\n\t\tobj.GetAnnotations(),\n\t\tfmt.Sprintf(\"k8s://%s/topologies/%s\", namespace, obj.GetName()),\n\t)\n\n\tnodeNames := make([]string, 0, len(nodeSpecs))\n\tfor nodeName := range nodeSpecs {\n\t\tnodeNames = append(nodeNames, nodeName)\n\t}\n\tsort.Strings(nodeNames)\n\n\tnodes := make([]clablabruntime.NodeState, 0, len(nodeNames))\n\tfor _, nodeName := range nodeNames {\n\t\tspec := nodeSpecs[nodeName]\n\t\tnodes = append(nodes, clablabruntime.NodeState{\n\t\t\tName:  nodeName,\n\t\t\tKind:  spec.Kind,\n\t\t\tImage: spec.Image,\n\t\t})\n\t}\n\n\treturn &clablabruntime.LabState{\n\t\tName:         obj.GetName(),\n\t\tNamespace:    namespace,\n\t\tOwner:        owner,\n\t\tTopologyPath: topologyPath,\n\t\tState:        state,\n\t\tReady:        ready,\n\t\tNodes:        nodes,\n\t}\n}\n\ntype nodeSpec struct {\n\tKind  string `yaml:\"kind\"`\n\tImage string `yaml:\"image\"`\n}\n\ntype containerlabDefinition struct {\n\tTopology struct {\n\t\tNodes map[string]nodeSpec `yaml:\"nodes\"`\n\t} `yaml:\"topology\"`\n}\n\nfunc nodeSpecsFromTopology(obj *unstructured.Unstructured) map[string]nodeSpec {\n\tspecs := map[string]nodeSpec{}\n\n\tdefinition, _, _ := unstructured.NestedString(\n\t\tobj.Object,\n\t\t\"spec\",\n\t\t\"definition\",\n\t\t\"containerlab\",\n\t)\n\tmergeNodeSpecs(specs, definition)\n\n\treturn specs\n}\n\nfunc mergeNodeSpecs(specs map[string]nodeSpec, definition string) {\n\tif definition == \"\" {\n\t\treturn\n\t}\n\n\tvar parsed containerlabDefinition\n\tif err := yaml.Unmarshal([]byte(definition), &parsed); err != nil {\n\t\tlog.Debug(\"failed to parse C9s topology definition\", \"error\", err)\n\t\treturn\n\t}\n\n\tfor nodeName, spec := range parsed.Topology.Nodes {\n\t\tspecs[nodeName] = spec\n\t}\n}",
        "lineStart": 1,
        "lineEnd": 259,
        "totalLines": 259,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525848830,
      "end": 1793525848836
    }
  }
}
read · completed

Input

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

Output

<path>/source/head/labruntime/clabernetes/clabernetes.go</path>
<type>file</type>
<content>
1: package clabernetes
2: 
3: import (
4: 	"context"
5: 	"fmt"
6: 	"slices"
7: 	"strings"
8: 	"sync"
9: 	"time"
10: 
11: 	"github.com/charmbracelet/log"
12: 	"github.com/go-logr/logr/funcr"
13: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
14: 	"k8s.io/apimachinery/pkg/runtime/schema"
15: 	"k8s.io/client-go/dynamic"
16: 	"k8s.io/client-go/kubernetes"
17: 	"k8s.io/client-go/rest"
18: 	"k8s.io/klog/v2"
19: )
20: 
21: const (
22: 	defaultNamespace = "default"
23: 	pollInterval     = 2 * time.Second
24: 
25: 	envKubeconfig = "CLAB_KUBECONFIG"
26: 	envContext    = "CLAB_KUBE_CONTEXT"
27: 	envNamespace  = "CLAB_KUBE_NAMESPACE"
28: 
29: 	c9sAPIVersion         = "c9s.run/v1alpha1"
30: 	labelRuntime          = "containerlab.dev/runtime"
31: 	labelApp              = "c9s.run/app"
32: 	labelTopologyOwner    = "c9s.run/topologyOwner"
33: 	labelTopologyNode     = "c9s.run/topologyNode"
34: 	labelOriginalNodeName = "c9s.run/originalNodeName"
35: 	clabernetesAppValue   = "clabernetes"
36: 	// persistenceReclaimRetain keeps a node's persistent claim when its Node is deleted.
37: 	persistenceReclaimRetain = "Retain"
38: 	// defaultContainerAnnotation names the primary device container of a c9s pod.
39: 	defaultContainerAnnotation = "kubectl.kubernetes.io/default-container"
40: 	// annotationDirectNodeUID names the UID of the Node a c9s pod runs.
41: 	annotationDirectNodeUID = "c9s.run/direct-node-uid"
42: )
43: 
44: var topologyGVR = schema.GroupVersionResource{
45: 	Group:    "c9s.run",
46: 	Version:  "v1alpha1",
47: 	Resource: "topologies",
48: }
49: 
50: var nodeGVR = schema.GroupVersionResource{
51: 	Group:    "c9s.run",
52: 	Version:  "v1alpha1",
53: 	Resource: "nodes",
54: }
55: 
56: var linkGVR = schema.GroupVersionResource{
57: 	Group:    "c9s.run",
58: 	Version:  "v1alpha1",
59: 	Resource: "links",
60: }
61: 
62: var nodeProfileGVR = schema.GroupVersionResource{
63: 	Group:    "c9s.run",
64: 	Version:  "v1alpha1",
65: 	Resource: "nodeprofiles",
66: }
67: 
68: type Runtime struct {
69: 	client     dynamic.Interface
70: 	kubeClient kubernetes.Interface
71: 	restConfig *rest.Config
72: 	namespace  string
73: 	// labNamespaceOverride is set by --namespace or CLAB_KUBE_NAMESPACE. When
74: 	// empty, lab-scoped operations derive their namespace from the lab name.
75: 	labNamespaceOverride string
76: 	timeout              time.Duration
77: 	// kindLinkApplyMode resolves the default link apply mode a node kind declares.
78: 	// The plan uses it to predict the pod lifecycle impact of link changes.
79: 	kindLinkApplyMode func(kind string) string
80: 	// clients loads the Kubernetes clients on first use. Commands that only compile the
81: 	// topology (validate, deploy --emit-crs) never call it, so they work without a
82: 	// kubeconfig that loads. It is nil when the clients were injected (tests).
83: 	clients *clientLoader
84: 	// connected marks a runtime view whose client fields are populated.
85: 	connected bool
86: 	// identity is the configured identity of calls without one; in a connected view it is the
87: 	// identity the clients impersonate.
88: 	identity clablabruntime.Identity
89: 	// pollInterval overrides how often waits poll the cluster (tests).
90: 	pollInterval time.Duration
91: 	// podExec overrides how commands run in pod containers (tests).
92: 	podExec podExecFunc
93: 	// captureSegment is the length of one chained packet capture; zero uses the clabwire
94: 	// maximum of one hour.
95: 	captureSegment time.Duration
96: 	// captureReorderWindow is how long the merged capture stream holds packets back to write
97: 	// them in timestamp order: zero uses the default, a negative value disables reordering.
98: 	captureReorderWindow time.Duration
99: 	// support checks once per runtime instance, before the first cluster call, that the
100: 	// cluster runs a clabernetes release with the contract this runtime needs. Every view
101: 	// shares it. It is nil when the clients were injected (tests).
102: 	support *supportCheck
103: }
104: 
105: // kubeClients is the set of Kubernetes clients a runtime view operates with.
106: type kubeClients struct {
107: 	dynamic    dynamic.Interface
108: 	kube       kubernetes.Interface
109: 	restConfig *rest.Config
110: }
111: 
112: // clientLoader loads the kubeconfig once and builds, and caches, the Kubernetes clients of
113: // every identity from it.
114: type clientLoader struct {
115: 	loadConfig func() (*rest.Config, string, error)
116: 	newClients func(*rest.Config) (*kubeClients, error)
117: 
118: 	once      sync.Once
119: 	base      *rest.Config
120: 	namespace string
121: 	err       error
122: 
123: 	mu         sync.Mutex
124: 	byIdentity map[string]*kubeClients
125: }
126: 
127: func newClientLoader() *clientLoader {
128: 	return &clientLoader{
129: 		loadConfig: kubeClientConfig,
130: 		newClients: newKubeClients,
131: 	}
132: }
133: 
134: func newKubeClients(restConfig *rest.Config) (*kubeClients, error) {
135: 	client, err := dynamic.NewForConfig(restConfig)
136: 	if err != nil {
137: 		return nil, fmt.Errorf("failed to create Kubernetes dynamic client: %w", err)
138: 	}
139: 
140: 	kubeClient, err := kubernetes.NewForConfig(restConfig)
141: 	if err != nil {
142: 		return nil, fmt.Errorf("failed to create Kubernetes client: %w", err)
143: 	}
144: 
145: 	return &kubeClients{dynamic: client, kube: kubeClient, restConfig: restConfig}, nil
146: }
147: 
148: // load returns the clients of an identity. The impersonation is part of the rest config, so it
149: // applies to every transport built from it: REST calls, watches, log streams, and the SPDY and
150: // websocket upgrades of exec, attach and port-forward.
151: func (l *clientLoader) load(
152: 	identity clablabruntime.Identity,
153: ) (*kubeClients, string, error) {
154: 	l.once.Do(func() {
155: 		l.base, l.namespace, l.err = l.loadConfig()
156: 		if l.namespace == "" {
157: 			l.namespace = defaultNamespace
158: 		}
159: 	})
160: 	if l.err != nil {
161: 		return nil, "", l.err
162: 	}
163: 
164: 	key := identityKey(identity)
165: 
166: 	l.mu.Lock()
167: 	defer l.mu.Unlock()
168: 
169: 	if clients, ok := l.byIdentity[key]; ok {
170: 		return clients, l.namespace, nil
171: 	}
172: 
173: 	restConfig := rest.CopyConfig(l.base)
174: 	if !identity.IsZero() {
175: 		restConfig.Impersonate = rest.ImpersonationConfig{
176: 			UserName: identity.User,
177: 			Groups:   slices.Clone(identity.Groups),
178: 		}
179: 	}
180: 
181: 	clients, err := l.newClients(restConfig)
182: 	if err != nil {
183: 		return nil, "", err
184: 	}
185: 	if l.byIdentity == nil {
186: 		l.byIdentity = map[string]*kubeClients{}
187: 	}
188: 	l.byIdentity[key] = clients
189: 
190: 	return clients, l.namespace, nil
191: }
192: 
193: func identityKey(identity clablabruntime.Identity) string {
194: 	return identity.User + "\x00" + strings.Join(identity.Groups, "\x00")
195: }
196: 
197: // connect returns a view of the runtime with the Kubernetes clients of an identity populated,
198: // loading the kubeconfig on first use. A zero identity uses the runtime's configured identity.
199: // Every operation that reads or changes cluster state calls it first, so it also runs the
200: // clabernetes version check once per runtime instance, before the first cluster call.
201: func (r *Runtime) connect(
202: 	ctx context.Context,
203: 	identity clablabruntime.Identity,
204: ) (*Runtime, error) {
205: 	if identity.IsZero() {
206: 		identity = r.identity
207: 	}
208: 	if r.connected && identity.Equal(r.identity) {
209: 		return r, nil
210: 	}
211: 	if r.clients == nil {
212: 		// clients were injected (tests); they act as the identity they were built with
213: 		if err := r.support.ensure(ctx, r); err != nil {
214: 			return nil, err
215: 		}
216: 
217: 		return r, nil
218: 	}
219: 
220: 	clients, namespace, err := r.clients.load(identity)
221: 	if err != nil {
222: 		return nil, err
223: 	}
224: 
225: 	view := *r
226: 	view.client = clients.dynamic
227: 	view.kubeClient = clients.kube
228: 	view.restConfig = clients.restConfig
229: 	if view.namespace == "" {
230: 		view.namespace = namespace
231: 	}
232: 	view.identity = identity
233: 	view.connected = true
234: 
235: 	if err := r.support.ensure(ctx, &view); err != nil {
236: 		return nil, err
237: 	}
238: 
239: 	return &view, nil
240: }
241: 
242: func withKubernetesClientDebugLogs(ctx context.Context) context.Context {
243: 	verbosity := -1
244: 	if log.GetLevel() <= log.DebugLevel {
245: 		verbosity = 3
246: 	}
247: 	logger := funcr.New(func(prefix, args string) {
248: 		log.Debug("Kubernetes client", "log", strings.TrimSpace(prefix+" "+args))
249: 	}, funcr.Options{Verbosity: verbosity})
250: 
251: 	return klog.NewContext(ctx, logger)
252: }
253: 
254: func init() {
255: 	clablabruntime.Register(clablabruntime.ClabernetesRuntimeName, New)
256: }
257: 
258: // New returns the c9s lab runtime. It does not load the kubeconfig: the Kubernetes clients
259: // are created on the first operation that needs the cluster.
260: func New(cfg clablabruntime.Config) (clablabruntime.LabRuntime, error) {
261: 	return &Runtime{
262: 		labNamespaceOverride: configuredLabNamespace(cfg.Namespace),
263: 		timeout:              cfg.Timeout,
264: 		kindLinkApplyMode:    cfg.KindLinkApplyMode,
265: 		identity:             cfg.Identity,
266: 		clients:              newClientLoader(),
267: 		support:              &supportCheck{},
268: 		captureSegment:       captureSegmentFromEnv(),
269: 		captureReorderWindow: captureReorderWindowFromEnv(),
270: 	}, nil
271: }

(End of file - total 271 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196789b4e0010Cy2sqhKVNXtoa",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196785fa8001hEk0acQLRaHhES",
  "callID": "call_ff047c0f89c24a26810f7685",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/clabernetes.go"
    },
    "output": "<path>/source/head/labruntime/clabernetes/clabernetes.go</path>\n<type>file</type>\n<content>\n1: package clabernetes\n2: \n3: import (\n4: \t\"context\"\n5: \t\"fmt\"\n6: \t\"slices\"\n7: \t\"strings\"\n8: \t\"sync\"\n9: \t\"time\"\n10: \n11: \t\"github.com/charmbracelet/log\"\n12: \t\"github.com/go-logr/logr/funcr\"\n13: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n14: \t\"k8s.io/apimachinery/pkg/runtime/schema\"\n15: \t\"k8s.io/client-go/dynamic\"\n16: \t\"k8s.io/client-go/kubernetes\"\n17: \t\"k8s.io/client-go/rest\"\n18: \t\"k8s.io/klog/v2\"\n19: )\n20: \n21: const (\n22: \tdefaultNamespace = \"default\"\n23: \tpollInterval     = 2 * time.Second\n24: \n25: \tenvKubeconfig = \"CLAB_KUBECONFIG\"\n26: \tenvContext    = \"CLAB_KUBE_CONTEXT\"\n27: \tenvNamespace  = \"CLAB_KUBE_NAMESPACE\"\n28: \n29: \tc9sAPIVersion         = \"c9s.run/v1alpha1\"\n30: \tlabelRuntime          = \"containerlab.dev/runtime\"\n31: \tlabelApp              = \"c9s.run/app\"\n32: \tlabelTopologyOwner    = \"c9s.run/topologyOwner\"\n33: \tlabelTopologyNode     = \"c9s.run/topologyNode\"\n34: \tlabelOriginalNodeName = \"c9s.run/originalNodeName\"\n35: \tclabernetesAppValue   = \"clabernetes\"\n36: \t// persistenceReclaimRetain keeps a node's persistent claim when its Node is deleted.\n37: \tpersistenceReclaimRetain = \"Retain\"\n38: \t// defaultContainerAnnotation names the primary device container of a c9s pod.\n39: \tdefaultContainerAnnotation = \"kubectl.kubernetes.io/default-container\"\n40: \t// annotationDirectNodeUID names the UID of the Node a c9s pod runs.\n41: \tannotationDirectNodeUID = \"c9s.run/direct-node-uid\"\n42: )\n43: \n44: var topologyGVR = schema.GroupVersionResource{\n45: \tGroup:    \"c9s.run\",\n46: \tVersion:  \"v1alpha1\",\n47: \tResource: \"topologies\",\n48: }\n49: \n50: var nodeGVR = schema.GroupVersionResource{\n51: \tGroup:    \"c9s.run\",\n52: \tVersion:  \"v1alpha1\",\n53: \tResource: \"nodes\",\n54: }\n55: \n56: var linkGVR = schema.GroupVersionResource{\n57: \tGroup:    \"c9s.run\",\n58: \tVersion:  \"v1alpha1\",\n59: \tResource: \"links\",\n60: }\n61: \n62: var nodeProfileGVR = schema.GroupVersionResource{\n63: \tGroup:    \"c9s.run\",\n64: \tVersion:  \"v1alpha1\",\n65: \tResource: \"nodeprofiles\",\n66: }\n67: \n68: type Runtime struct {\n69: \tclient     dynamic.Interface\n70: \tkubeClient kubernetes.Interface\n71: \trestConfig *rest.Config\n72: \tnamespace  string\n73: \t// labNamespaceOverride is set by --namespace or CLAB_KUBE_NAMESPACE. When\n74: \t// empty, lab-scoped operations derive their namespace from the lab name.\n75: \tlabNamespaceOverride string\n76: \ttimeout              time.Duration\n77: \t// kindLinkApplyMode resolves the default link apply mode a node kind declares.\n78: \t// The plan uses it to predict the pod lifecycle impact of link changes.\n79: \tkindLinkApplyMode func(kind string) string\n80: \t// clients loads the Kubernetes clients on first use. Commands that only compile the\n81: \t// topology (validate, deploy --emit-crs) never call it, so they work without a\n82: \t// kubeconfig that loads. It is nil when the clients were injected (tests).\n83: \tclients *clientLoader\n84: \t// connected marks a runtime view whose client fields are populated.\n85: \tconnected bool\n86: \t// identity is the configured identity of calls without one; in a connected view it is the\n87: \t// identity the clients impersonate.\n88: \tidentity clablabruntime.Identity\n89: \t// pollInterval overrides how often waits poll the cluster (tests).\n90: \tpollInterval time.Duration\n91: \t// podExec overrides how commands run in pod containers (tests).\n92: \tpodExec podExecFunc\n93: \t// captureSegment is the length of one chained packet capture; zero uses the clabwire\n94: \t// maximum of one hour.\n95: \tcaptureSegment time.Duration\n96: \t// captureReorderWindow is how long the merged capture stream holds packets back to write\n97: \t// them in timestamp order: zero uses the default, a negative value disables reordering.\n98: \tcaptureReorderWindow time.Duration\n99: \t// support checks once per runtime instance, before the first cluster call, that the\n100: \t// cluster runs a clabernetes release with the contract this runtime needs. Every view\n101: \t// shares it. It is nil when the clients were injected (tests).\n102: \tsupport *supportCheck\n103: }\n104: \n105: // kubeClients is the set of Kubernetes clients a runtime view operates with.\n106: type kubeClients struct {\n107: \tdynamic    dynamic.Interface\n108: \tkube       kubernetes.Interface\n109: \trestConfig *rest.Config\n110: }\n111: \n112: // clientLoader loads the kubeconfig once and builds, and caches, the Kubernetes clients of\n113: // every identity from it.\n114: type clientLoader struct {\n115: \tloadConfig func() (*rest.Config, string, error)\n116: \tnewClients func(*rest.Config) (*kubeClients, error)\n117: \n118: \tonce      sync.Once\n119: \tbase      *rest.Config\n120: \tnamespace string\n121: \terr       error\n122: \n123: \tmu         sync.Mutex\n124: \tbyIdentity map[string]*kubeClients\n125: }\n126: \n127: func newClientLoader() *clientLoader {\n128: \treturn &clientLoader{\n129: \t\tloadConfig: kubeClientConfig,\n130: \t\tnewClients: newKubeClients,\n131: \t}\n132: }\n133: \n134: func newKubeClients(restConfig *rest.Config) (*kubeClients, error) {\n135: \tclient, err := dynamic.NewForConfig(restConfig)\n136: \tif err != nil {\n137: \t\treturn nil, fmt.Errorf(\"failed to create Kubernetes dynamic client: %w\", err)\n138: \t}\n139: \n140: \tkubeClient, err := kubernetes.NewForConfig(restConfig)\n141: \tif err != nil {\n142: \t\treturn nil, fmt.Errorf(\"failed to create Kubernetes client: %w\", err)\n143: \t}\n144: \n145: \treturn &kubeClients{dynamic: client, kube: kubeClient, restConfig: restConfig}, nil\n146: }\n147: \n148: // load returns the clients of an identity. The impersonation is part of the rest config, so it\n149: // applies to every transport built from it: REST calls, watches, log streams, and the SPDY and\n150: // websocket upgrades of exec, attach and port-forward.\n151: func (l *clientLoader) load(\n152: \tidentity clablabruntime.Identity,\n153: ) (*kubeClients, string, error) {\n154: \tl.once.Do(func() {\n155: \t\tl.base, l.namespace, l.err = l.loadConfig()\n156: \t\tif l.namespace == \"\" {\n157: \t\t\tl.namespace = defaultNamespace\n158: \t\t}\n159: \t})\n160: \tif l.err != nil {\n161: \t\treturn nil, \"\", l.err\n162: \t}\n163: \n164: \tkey := identityKey(identity)\n165: \n166: \tl.mu.Lock()\n167: \tdefer l.mu.Unlock()\n168: \n169: \tif clients, ok := l.byIdentity[key]; ok {\n170: \t\treturn clients, l.namespace, nil\n171: \t}\n172: \n173: \trestConfig := rest.CopyConfig(l.base)\n174: \tif !identity.IsZero() {\n175: \t\trestConfig.Impersonate = rest.ImpersonationConfig{\n176: \t\t\tUserName: identity.User,\n177: \t\t\tGroups:   slices.Clone(identity.Groups),\n178: \t\t}\n179: \t}\n180: \n181: \tclients, err := l.newClients(restConfig)\n182: \tif err != nil {\n183: \t\treturn nil, \"\", err\n184: \t}\n185: \tif l.byIdentity == nil {\n186: \t\tl.byIdentity = map[string]*kubeClients{}\n187: \t}\n188: \tl.byIdentity[key] = clients\n189: \n190: \treturn clients, l.namespace, nil\n191: }\n192: \n193: func identityKey(identity clablabruntime.Identity) string {\n194: \treturn identity.User + \"\\x00\" + strings.Join(identity.Groups, \"\\x00\")\n195: }\n196: \n197: // connect returns a view of the runtime with the Kubernetes clients of an identity populated,\n198: // loading the kubeconfig on first use. A zero identity uses the runtime's configured identity.\n199: // Every operation that reads or changes cluster state calls it first, so it also runs the\n200: // clabernetes version check once per runtime instance, before the first cluster call.\n201: func (r *Runtime) connect(\n202: \tctx context.Context,\n203: \tidentity clablabruntime.Identity,\n204: ) (*Runtime, error) {\n205: \tif identity.IsZero() {\n206: \t\tidentity = r.identity\n207: \t}\n208: \tif r.connected && identity.Equal(r.identity) {\n209: \t\treturn r, nil\n210: \t}\n211: \tif r.clients == nil {\n212: \t\t// clients were injected (tests); they act as the identity they were built with\n213: \t\tif err := r.support.ensure(ctx, r); err != nil {\n214: \t\t\treturn nil, err\n215: \t\t}\n216: \n217: \t\treturn r, nil\n218: \t}\n219: \n220: \tclients, namespace, err := r.clients.load(identity)\n221: \tif err != nil {\n222: \t\treturn nil, err\n223: \t}\n224: \n225: \tview := *r\n226: \tview.client = clients.dynamic\n227: \tview.kubeClient = clients.kube\n228: \tview.restConfig = clients.restConfig\n229: \tif view.namespace == \"\" {\n230: \t\tview.namespace = namespace\n231: \t}\n232: \tview.identity = identity\n233: \tview.connected = true\n234: \n235: \tif err := r.support.ensure(ctx, &view); err != nil {\n236: \t\treturn nil, err\n237: \t}\n238: \n239: \treturn &view, nil\n240: }\n241: \n242: func withKubernetesClientDebugLogs(ctx context.Context) context.Context {\n243: \tverbosity := -1\n244: \tif log.GetLevel() <= log.DebugLevel {\n245: \t\tverbosity = 3\n246: \t}\n247: \tlogger := funcr.New(func(prefix, args string) {\n248: \t\tlog.Debug(\"Kubernetes client\", \"log\", strings.TrimSpace(prefix+\" \"+args))\n249: \t}, funcr.Options{Verbosity: verbosity})\n250: \n251: \treturn klog.NewContext(ctx, logger)\n252: }\n253: \n254: func init() {\n255: \tclablabruntime.Register(clablabruntime.ClabernetesRuntimeName, New)\n256: }\n257: \n258: // New returns the c9s lab runtime. It does not load the kubeconfig: the Kubernetes clients\n259: // are created on the first operation that needs the cluster.\n260: func New(cfg clablabruntime.Config) (clablabruntime.LabRuntime, error) {\n261: \treturn &Runtime{\n262: \t\tlabNamespaceOverride: configuredLabNamespace(cfg.Namespace),\n263: \t\ttimeout:              cfg.Timeout,\n264: \t\tkindLinkApplyMode:    cfg.KindLinkApplyMode,\n265: \t\tidentity:             cfg.Identity,\n266: \t\tclients:              newClientLoader(),\n267: \t\tsupport:              &supportCheck{},\n268: \t\tcaptureSegment:       captureSegmentFromEnv(),\n269: \t\tcaptureReorderWindow: captureReorderWindowFromEnv(),\n270: \t}, nil\n271: }\n\n(End of file - total 271 lines)\n</content>",
    "title": "source/head/labruntime/clabernetes/clabernetes.go",
    "metadata": {
      "preview": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\t\"github.com/go-logr/logr/funcr\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"k8s.io/client-go/dynamic\"\n\t\"k8s.io/client-go/kubernetes\"\n\t\"k8s.io/client-go/rest\"\n\t\"k8s.io/klog/v2\"\n)\n",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/clabernetes.go",
        "text": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\t\"github.com/go-logr/logr/funcr\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n\t\"k8s.io/client-go/dynamic\"\n\t\"k8s.io/client-go/kubernetes\"\n\t\"k8s.io/client-go/rest\"\n\t\"k8s.io/klog/v2\"\n)\n\nconst (\n\tdefaultNamespace = \"default\"\n\tpollInterval     = 2 * time.Second\n\n\tenvKubeconfig = \"CLAB_KUBECONFIG\"\n\tenvContext    = \"CLAB_KUBE_CONTEXT\"\n\tenvNamespace  = \"CLAB_KUBE_NAMESPACE\"\n\n\tc9sAPIVersion         = \"c9s.run/v1alpha1\"\n\tlabelRuntime          = \"containerlab.dev/runtime\"\n\tlabelApp              = \"c9s.run/app\"\n\tlabelTopologyOwner    = \"c9s.run/topologyOwner\"\n\tlabelTopologyNode     = \"c9s.run/topologyNode\"\n\tlabelOriginalNodeName = \"c9s.run/originalNodeName\"\n\tclabernetesAppValue   = \"clabernetes\"\n\t// persistenceReclaimRetain keeps a node's persistent claim when its Node is deleted.\n\tpersistenceReclaimRetain = \"Retain\"\n\t// defaultContainerAnnotation names the primary device container of a c9s pod.\n\tdefaultContainerAnnotation = \"kubectl.kubernetes.io/default-container\"\n\t// annotationDirectNodeUID names the UID of the Node a c9s pod runs.\n\tannotationDirectNodeUID = \"c9s.run/direct-node-uid\"\n)\n\nvar topologyGVR = schema.GroupVersionResource{\n\tGroup:    \"c9s.run\",\n\tVersion:  \"v1alpha1\",\n\tResource: \"topologies\",\n}\n\nvar nodeGVR = schema.GroupVersionResource{\n\tGroup:    \"c9s.run\",\n\tVersion:  \"v1alpha1\",\n\tResource: \"nodes\",\n}\n\nvar linkGVR = schema.GroupVersionResource{\n\tGroup:    \"c9s.run\",\n\tVersion:  \"v1alpha1\",\n\tResource: \"links\",\n}\n\nvar nodeProfileGVR = schema.GroupVersionResource{\n\tGroup:    \"c9s.run\",\n\tVersion:  \"v1alpha1\",\n\tResource: \"nodeprofiles\",\n}\n\ntype Runtime struct {\n\tclient     dynamic.Interface\n\tkubeClient kubernetes.Interface\n\trestConfig *rest.Config\n\tnamespace  string\n\t// labNamespaceOverride is set by --namespace or CLAB_KUBE_NAMESPACE. When\n\t// empty, lab-scoped operations derive their namespace from the lab name.\n\tlabNamespaceOverride string\n\ttimeout              time.Duration\n\t// kindLinkApplyMode resolves the default link apply mode a node kind declares.\n\t// The plan uses it to predict the pod lifecycle impact of link changes.\n\tkindLinkApplyMode func(kind string) string\n\t// clients loads the Kubernetes clients on first use. Commands that only compile the\n\t// topology (validate, deploy --emit-crs) never call it, so they work without a\n\t// kubeconfig that loads. It is nil when the clients were injected (tests).\n\tclients *clientLoader\n\t// connected marks a runtime view whose client fields are populated.\n\tconnected bool\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\n// kubeClients is the set of Kubernetes clients a runtime view operates with.\ntype kubeClients struct {\n\tdynamic    dynamic.Interface\n\tkube       kubernetes.Interface\n\trestConfig *rest.Config\n}\n\n// clientLoader loads the kubeconfig once and builds, and caches, the Kubernetes clients of\n// every identity from it.\ntype clientLoader struct {\n\tloadConfig func() (*rest.Config, string, error)\n\tnewClients func(*rest.Config) (*kubeClients, error)\n\n\tonce      sync.Once\n\tbase      *rest.Config\n\tnamespace string\n\terr       error\n\n\tmu         sync.Mutex\n\tbyIdentity map[string]*kubeClients\n}\n\nfunc newClientLoader() *clientLoader {\n\treturn &clientLoader{\n\t\tloadConfig: kubeClientConfig,\n\t\tnewClients: newKubeClients,\n\t}\n}\n\nfunc newKubeClients(restConfig *rest.Config) (*kubeClients, error) {\n\tclient, err := dynamic.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create Kubernetes dynamic client: %w\", err)\n\t}\n\n\tkubeClient, err := kubernetes.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create Kubernetes client: %w\", err)\n\t}\n\n\treturn &kubeClients{dynamic: client, kube: kubeClient, restConfig: restConfig}, nil\n}\n\n// load returns the clients of an identity. The impersonation is part of the rest config, so it\n// applies to every transport built from it: REST calls, watches, log streams, and the SPDY and\n// websocket upgrades of exec, attach and port-forward.\nfunc (l *clientLoader) load(\n\tidentity clablabruntime.Identity,\n) (*kubeClients, string, error) {\n\tl.once.Do(func() {\n\t\tl.base, l.namespace, l.err = l.loadConfig()\n\t\tif l.namespace == \"\" {\n\t\t\tl.namespace = defaultNamespace\n\t\t}\n\t})\n\tif l.err != nil {\n\t\treturn nil, \"\", l.err\n\t}\n\n\tkey := identityKey(identity)\n\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\tif clients, ok := l.byIdentity[key]; ok {\n\t\treturn clients, l.namespace, nil\n\t}\n\n\trestConfig := rest.CopyConfig(l.base)\n\tif !identity.IsZero() {\n\t\trestConfig.Impersonate = rest.ImpersonationConfig{\n\t\t\tUserName: identity.User,\n\t\t\tGroups:   slices.Clone(identity.Groups),\n\t\t}\n\t}\n\n\tclients, err := l.newClients(restConfig)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tif l.byIdentity == nil {\n\t\tl.byIdentity = map[string]*kubeClients{}\n\t}\n\tl.byIdentity[key] = clients\n\n\treturn clients, l.namespace, nil\n}\n\nfunc identityKey(identity clablabruntime.Identity) string {\n\treturn identity.User + \"\\x00\" + strings.Join(identity.Groups, \"\\x00\")\n}\n\n// connect returns a view of the runtime with the Kubernetes clients of an identity populated,\n// loading the kubeconfig on first use. A zero identity uses the runtime's configured identity.\n// Every operation that reads or changes cluster state calls it first, so it also runs the\n// clabernetes version check once per runtime instance, before the first cluster call.\nfunc (r *Runtime) connect(\n\tctx context.Context,\n\tidentity clablabruntime.Identity,\n) (*Runtime, error) {\n\tif identity.IsZero() {\n\t\tidentity = r.identity\n\t}\n\tif r.connected && identity.Equal(r.identity) {\n\t\treturn r, nil\n\t}\n\tif r.clients == nil {\n\t\t// clients were injected (tests); they act as the identity they were built with\n\t\tif err := r.support.ensure(ctx, r); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn r, nil\n\t}\n\n\tclients, namespace, err := r.clients.load(identity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tview := *r\n\tview.client = clients.dynamic\n\tview.kubeClient = clients.kube\n\tview.restConfig = clients.restConfig\n\tif view.namespace == \"\" {\n\t\tview.namespace = namespace\n\t}\n\tview.identity = identity\n\tview.connected = true\n\n\tif err := r.support.ensure(ctx, &view); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &view, nil\n}\n\nfunc withKubernetesClientDebugLogs(ctx context.Context) context.Context {\n\tverbosity := -1\n\tif log.GetLevel() <= log.DebugLevel {\n\t\tverbosity = 3\n\t}\n\tlogger := funcr.New(func(prefix, args string) {\n\t\tlog.Debug(\"Kubernetes client\", \"log\", strings.TrimSpace(prefix+\" \"+args))\n\t}, funcr.Options{Verbosity: verbosity})\n\n\treturn klog.NewContext(ctx, logger)\n}\n\nfunc init() {\n\tclablabruntime.Register(clablabruntime.ClabernetesRuntimeName, New)\n}\n\n// New returns the c9s lab runtime. It does not load the kubeconfig: the Kubernetes clients\n// are created on the first operation that needs the cluster.\nfunc New(cfg clablabruntime.Config) (clablabruntime.LabRuntime, error) {\n\treturn &Runtime{\n\t\tlabNamespaceOverride: configuredLabNamespace(cfg.Namespace),\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}",
        "lineStart": 1,
        "lineEnd": 271,
        "totalLines": 271,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525848917,
      "end": 1793525848925
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196789b60001fQC4sEIKXq43He",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196785fa8001hEk0acQLRaHhES",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 16287,
    "input": 16044,
    "output": 54,
    "reasoning": 189,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196785fa8001hEk0acQLRaHhES",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525833640,
    "completed": 1793525848931
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 16287,
    "input": 16044,
    "output": 54,
    "reasoning": 189,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 26
step-start
{
  "type": "step-start",
  "id": "prt_19678a2af001dccEN1uBKUnDLC",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196789b6c001KnZ5BdzG974Jav"
}
Reasoning
Both fine. Now the remaining unviewed parts:

1. Where `setTopologySourceFile` is called during deploy — grep.
2. `capture.go` — `listCaptureInterfaces`, `reportedInterfaces`, `c9sIfaceState`, `interfaceEventData`.
3. `core/labruntime.go` lines 1-440 — how events wire to `streamLabRuntimeEvents`, and `containerFromLabNode` context.
4. `labruntime/runtime.go` — diff said lab-not-found semantics changed; read relevant part.
5. Tests and docs.

Let me grep for setTopologySourceFile callers and read capture.go.
Now find the callers of `setTopologySourceFile`/`labTopologyPath`, and read `capture.go`.
grep · completed

Input

{
  "pattern": "setTopologySourceFile|labTopologyPath|removeTopologySourceFile",
  "path": "/source/head"
}

Output

Found 16 matches
/source/head/labruntime/clabernetes/event_parity_test.go:
  Line 937: 	setTopologySourceFile(topology, "/old.clab.yml")

  Line 939: 	setTopologySourceFile(newTopology, "/new.clab.yml")

  Line 975: 	setTopologySourceFile(topology, "/home/alice/lab1.clab.yml")


/source/head/labruntime/clabernetes/plan.go:
  Line 56: 	setTopologySourceFile(desiredTopology, req.TopologyFile)


/source/head/labruntime/clabernetes/manifests.go:
  Line 45: 	removeTopologySourceFile(prepared.topology)

  Line 48: 			removeTopologySourceFile(obj)


/source/head/labruntime/clabernetes/primitives.go:
  Line 225: 		removeTopologySourceFile(obj)


/source/head/labruntime/clabernetes/reconcile.go:
  Line 217: 		removeTopologySourceFile(updated)

  Line 221: 	setTopologySourceFile(updated, path)


/source/head/labruntime/clabernetes/topology.go:
  Line 24: // setTopologySourceFile records the topology file a deploy reads on the Topology. An empty path

  Line 26: func setTopologySourceFile(topology *unstructured.Unstructured, path string) {

  Line 39: // removeTopologySourceFile drops the deploying machine's file path from an object.

  Line 40: func removeTopologySourceFile(obj *unstructured.Unstructured) {

  Line 53: // labTopologyPath is the topology path a lab reports: the file it was deployed from when the

  Line 55: func labTopologyPath(annotations map[string]string, fallback string) string {

  Line 188: 	topologyPath := labTopologyPath(
Tool metadata
{
  "type": "tool",
  "id": "prt_19678a7b0001tUUEbUDQueutID",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196789b6c001KnZ5BdzG974Jav",
  "callID": "call_6d4c12d2fdb644bf86e6ef1e",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "pattern": "setTopologySourceFile|labTopologyPath|removeTopologySourceFile",
      "path": "/source/head"
    },
    "output": "Found 16 matches\n/source/head/labruntime/clabernetes/event_parity_test.go:\n  Line 937: \tsetTopologySourceFile(topology, \"/old.clab.yml\")\n\n  Line 939: \tsetTopologySourceFile(newTopology, \"/new.clab.yml\")\n\n  Line 975: \tsetTopologySourceFile(topology, \"/home/alice/lab1.clab.yml\")\n\n\n/source/head/labruntime/clabernetes/plan.go:\n  Line 56: \tsetTopologySourceFile(desiredTopology, req.TopologyFile)\n\n\n/source/head/labruntime/clabernetes/manifests.go:\n  Line 45: \tremoveTopologySourceFile(prepared.topology)\n\n  Line 48: \t\t\tremoveTopologySourceFile(obj)\n\n\n/source/head/labruntime/clabernetes/primitives.go:\n  Line 225: \t\tremoveTopologySourceFile(obj)\n\n\n/source/head/labruntime/clabernetes/reconcile.go:\n  Line 217: \t\tremoveTopologySourceFile(updated)\n\n  Line 221: \tsetTopologySourceFile(updated, path)\n\n\n/source/head/labruntime/clabernetes/topology.go:\n  Line 24: // setTopologySourceFile records the topology file a deploy reads on the Topology. An empty path\n\n  Line 26: func setTopologySourceFile(topology *unstructured.Unstructured, path string) {\n\n  Line 39: // removeTopologySourceFile drops the deploying machine's file path from an object.\n\n  Line 40: func removeTopologySourceFile(obj *unstructured.Unstructured) {\n\n  Line 53: // labTopologyPath is the topology path a lab reports: the file it was deployed from when the\n\n  Line 55: func labTopologyPath(annotations map[string]string, fallback string) string {\n\n  Line 188: \ttopologyPath := labTopologyPath(\n",
    "title": "setTopologySourceFile|labTopologyPath|removeTopologySourceFile",
    "metadata": {
      "matches": 16,
      "truncated": false
    },
    "time": {
      "start": 1793525852085,
      "end": 1793525852130
    }
  }
}
read · completed

Input

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

Output

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

(End of file - total 1215 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19678a7d5001iLDOjV78oB79Hd",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196789b6c001KnZ5BdzG974Jav",
  "callID": "call_5e28099405d4426da66f141a",
  "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: \tfor _, location := range pods {\n243: \t\tgroup.Go(func() error {\n244: \t\t\tentries, err := r.listPodInterfaces(groupCtx, location.Namespace, location.Pod)\n245: \t\t\tif err != nil {\n246: \t\t\t\treturn err\n247: \t\t\t}\n248: \n249: \t\t\tmu.Lock()\n250: \t\t\tdefer mu.Unlock()\n251: \t\t\tfor _, entry := range entries {\n252: \t\t\t\tif wanted[entry.Node] {\n253: \t\t\t\t\tresult[entry.Node] = append(result[entry.Node], entry)\n254: \t\t\t\t}\n255: \t\t\t}\n256: \n257: \t\t\treturn nil\n258: \t\t})\n259: \t}\n260: \tif err := group.Wait(); err != nil {\n261: \t\treturn nil, err\n262: \t}\n263: \n264: \treturn result, nil\n265: }\n266: \n267: // listPodInterfaces runs clabwire's --list-interfaces in a pod: the lab link interfaces of the\n268: // pod's nodes, with their aliases and peers.\n269: func (r *Runtime) listPodInterfaces(\n270: \tctx context.Context,\n271: \tnamespace, pod string,\n272: ) ([]clabwireInterface, error) {\n273: \tvar stdout, stderr bytes.Buffer\n274: \terr := r.execInPodContainer()(ctx, namespace, pod, clabwireContainer,\n275: \t\t[]string{clabwireManager, \"node-runtime\", \"packet-capture\", \"--list-interfaces\"},\n276: \t\tnil, &stdout, &stderr)\n277: \tif err != nil {\n278: \t\treturn nil, fmt.Errorf(\"failed to list the capturable interfaces of pod %s/%s: %w%s\",\n279: \t\t\tnamespace, pod, err, stderrSuffix(stderr.Bytes()))\n280: \t}\n281: \n282: \tvar entries []clabwireInterface\n283: \tif err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {\n284: \t\treturn nil, fmt.Errorf(\"failed to parse the capturable interfaces of pod %s/%s: %w\",\n285: \t\t\tnamespace, pod, err)\n286: \t}\n287: \n288: \treturn entries, nil\n289: }\n290: \n291: func stderrSuffix(stderr []byte) string {\n292: \ttext := strings.TrimSpace(string(stderr))\n293: \tif text == \"\" {\n294: \t\treturn \"\"\n295: \t}\n296: \n297: \treturn \": \" + text\n298: }\n299: \n300: // nodeNames maps the node names the cluster carries to the names the topology file uses.\n301: type nodeNames map[string]string\n302: \n303: func (n nodeNames) display(name string) string {\n304: \tif original := n[name]; original != \"\" {\n305: \t\treturn original\n306: \t}\n307: \n308: \treturn name\n309: }\n310: \n311: // nodeDisplayNames reads the original node names from the c9s.run/originalNodeName label of the\n312: // lab's Nodes.\n313: func (r *Runtime) nodeDisplayNames(\n314: \tctx context.Context,\n315: \tlab string,\n316: \tlocations []clablabruntime.NodeLocation,\n317: ) (nodeNames, error) {\n318: \tnames := nodeNames{}\n319: \tif len(locations) == 0 {\n320: \t\treturn names, nil\n321: \t}\n322: \n323: \tnodes, err := r.nodesForTopology(ctx, lab, locations[0].Namespace)\n324: \tif err != nil {\n325: \t\treturn nil, err\n326: \t}\n327: \tfor idx := range nodes.Items {\n328: \t\tif original := nodes.Items[idx].GetLabels()[labelOriginalNodeName]; original != \"\" {\n329: \t\t\tnames[nodes.Items[idx].GetName()] = original\n330: \t\t}\n331: \t}\n332: \n333: \treturn names, nil\n334: }\n335: \n336: // captureGroup is the part of a capture one clabwire process serves: the requested interfaces of\n337: // one node, in one pod.\n338: type captureGroup struct {\n339: \tlocation clablabruntime.NodeLocation\n340: \tdisplay  string\n341: \t// interfaces are the planned interface names, in the order the merged stream lists them.\n342: \tinterfaces []string\n343: \t// ids are the merged interface IDs of interfaces.\n344: \tids []uint32\n345: }\n346: \n347: // resolvedCapture is a validated capture request.\n348: type resolvedCapture struct {\n349: \tgroups []*captureGroup\n350: \t// names are the merged interface names (<node>:<interface>), indexed by merged ID.\n351: \tnames []string\n352: }\n353: \n354: // resolveCaptureTargets locates every target node, checks every interface against the\n355: // interfaces clabwire allows, and groups the targets per node.\n356: func (r *Runtime) resolveCaptureTargets(\n357: \tctx context.Context,\n358: \treq clablabruntime.CaptureRequest,\n359: ) (*resolvedCapture, error) {\n360: \tnodeOrder := make([]string, 0, len(req.Targets))\n361: \tseenNodes := map[string]bool{}\n362: \tfor _, target := range req.Targets {\n363: \t\tif !seenNodes[target.Node] {\n364: \t\t\tseenNodes[target.Node] = true\n365: \t\t\tnodeOrder = append(nodeOrder, target.Node)\n366: \t\t}\n367: \t}\n368: \n369: \tlocations, err := r.LocateNode(ctx, clablabruntime.NodeRequest{\n370: \t\tName: req.Name, Namespace: req.Namespace, Nodes: nodeOrder, Identity: req.Identity,\n371: \t})\n372: \tif err != nil {\n373: \t\treturn nil, err\n374: \t}\n375: \tbyRequest := make(map[string]clablabruntime.NodeLocation, len(nodeOrder))\n376: \tfor idx, name := range nodeOrder {\n377: \t\tbyRequest[name] = locations[idx]\n378: \t}\n379: \n380: \tlisted, err := r.listCaptureInterfaces(ctx, req.Name, locations)\n381: \tif err != nil {\n382: \t\treturn nil, err\n383: \t}\n384: \tnames, err := r.nodeDisplayNames(ctx, req.Name, locations)\n385: \tif err != nil {\n386: \t\treturn nil, err\n387: \t}\n388: \n389: \tresolved := &resolvedCapture{}\n390: \tgroups := map[string]*captureGroup{}\n391: \tseen := map[string]bool{}\n392: \tfor _, target := range req.Targets {\n393: \t\tlocation := byRequest[target.Node]\n394: \t\tentry, ok := findCaptureInterface(listed[location.NodeName], target.Interface)\n395: \t\tif !ok {\n396: \t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is not a capturable link \"+\n397: \t\t\t\t\"interface; capturable: %s\", target.Interface, target.Node,\n398: \t\t\t\tdescribeCaptureInterfaces(listed[location.NodeName]))\n399: \t\t}\n400: \n401: \t\tkey := location.NodeName + \"\\x00\" + entry.Interface\n402: \t\tif seen[key] {\n403: \t\t\treturn nil, fmt.Errorf(\"interface %q of node %q is requested more than once\",\n404: \t\t\t\tentry.Interface, target.Node)\n405: \t\t}\n406: \t\tseen[key] = true\n407: \n408: \t\tgroup := groups[location.NodeName]\n409: \t\tif group == nil {\n410: \t\t\tgroup = &captureGroup{\n411: \t\t\t\tlocation: location,\n412: \t\t\t\tdisplay:  names.display(location.NodeName),\n413: \t\t\t}\n414: \t\t\tgroups[location.NodeName] = group\n415: \t\t\tresolved.groups = append(resolved.groups, group)\n416: \t\t}\n417: \n418: \t\tid := uint32(len(resolved.names)) //nolint:gosec // bounded by the targets\n419: \t\tgroup.interfaces = append(group.interfaces, entry.Interface)\n420: \t\tgroup.ids = append(group.ids, id)\n421: \t\tresolved.names = append(resolved.names, group.display+\":\"+entry.Interface)\n422: \t}\n423: \n424: \treturn resolved, nil\n425: }\n426: \n427: // findCaptureInterface matches a requested interface by its planned name or its alias.\n428: func findCaptureInterface(entries []clabwireInterface, name string) (clabwireInterface, bool) {\n429: \tfor _, entry := range entries {\n430: \t\tif entry.Interface == name {\n431: \t\t\treturn entry, true\n432: \t\t}\n433: \t}\n434: \tfor _, entry := range entries {\n435: \t\tif entry.Alias != \"\" && entry.Alias == name {\n436: \t\t\treturn entry, true\n437: \t\t}\n438: \t}\n439: \n440: \treturn clabwireInterface{}, false\n441: }\n442: \n443: func describeCaptureInterfaces(entries []clabwireInterface) string {\n444: \tif len(entries) == 0 {\n445: \t\treturn \"none\"\n446: \t}\n447: \n448: \tnames := make([]string, 0, len(entries))\n449: \tfor _, entry := range entries {\n450: \t\tname := entry.Interface\n451: \t\tif entry.Alias != \"\" {\n452: \t\t\tname += \" (\" + entry.Alias + \")\"\n453: \t\t}\n454: \t\tnames = append(names, name)\n455: \t}\n456: \n457: \treturn strings.Join(names, \", \")\n458: }\n459: \n460: // Capture streams pcapng from lab link interfaces to w: one section, one Interface Description\n461: // Block per target in request order named <node>:<interface>, then the packets of every target.\n462: //\n463: // Each node's interfaces are captured by one clabwire process in the node's pod. clabwire limits\n464: // a capture to one hour, so a longer capture (or one without Duration) chains captures: the next\n465: // one starts before the current one ends, and the stream switches at a cut in the overlap. See\n466: // captureChain for how packets of the overlap are kept once.\n467: //\n468: // Packets go out in timestamp order across nodes, through a reorder buffer (captureReorder).\n469: //\n470: // Every clabwire process runs with stdin attached and --stop-on-stdin-close: a Kubernetes exec\n471: // does not stop its process when the stream closes, so containerlab closes stdin whenever a\n472: // segment ends (the capture ends, fails, its output fails, or a newer segment took over) and\n473: // clabwire ends the capture itself.\n474: //\n475: // Capture returns when Duration has passed, PacketLimit packets were written, or ctx ends; an\n476: // ended ctx is not an error. Every block reaches w in one write, so the stream is a valid capture\n477: // whenever it stops. A clabwire Denied or Failed audit record is returned as an error.\n478: func (r *Runtime) Capture(\n479: \tctx context.Context,\n480: \treq clablabruntime.CaptureRequest,\n481: \tw io.Writer,\n482: ) error {\n483: \tif err := clabcapture.ValidateRequest(&req); err != nil {\n484: \t\treturn err\n485: \t}\n486: \n487: \tr, err := r.connect(ctx, req.Identity)\n488: \tif err != nil {\n489: \t\treturn err\n490: \t}\n491: \n492: \tresolved, err := r.resolveCaptureTargets(ctx, req)\n493: \tif err != nil {\n494: \t\treturn err\n495: \t}\n496: \n497: \tcaptureCtx, stop := context.WithCancel(ctx)\n498: \tdefer stop()\n499: \n500: \tout, err := clabcapture.NewOutput(w, resolved.names, req.SnapLength, req.PacketLimit,\n501: \t\tr.captureReorderWindowLength(), stop)\n502: \tif err != nil {\n503: \t\treturn err\n504: \t}\n505: \n506: \trun := &captureRun{\n507: \t\tr:       r,\n508: \t\treq:     req,\n509: \t\tout:     out,\n510: \t\tsegment: r.captureSegmentLength(),\n511: \t}\n512: \tif req.Duration > 0 {\n513: \t\trun.deadline = time.Now().Add(req.Duration)\n514: \t}\n515: \trun.overlap = min(maxCaptureOverlap, run.segment/3)\n516: \trun.window = min(maxCaptureCutWindow, run.overlap/4)\n517: \n518: \tif req.Duration > 0 {\n519: \t\t// a clabwire process that does not end on its own does not hold the capture open\n520: \t\tvar cancelTimeout context.CancelFunc\n521: \t\tcaptureCtx, cancelTimeout = context.WithTimeout(captureCtx,\n522: \t\t\treq.Duration+run.overlap+captureEndGrace)\n523: \t\tdefer cancelTimeout()\n524: \t}\n525: \n526: \tgroup, groupCtx := errgroup.WithContext(captureCtx)\n527: \tfor _, captureGroup := range resolved.groups {\n528: \t\tchain := &captureChain{capture: run, group: captureGroup}\n529: \t\tgroup.Go(func() error {\n530: \t\t\treturn chain.run(groupCtx)\n531: \t\t})\n532: \t}\n533: \n534: \terr = group.Wait()\n535: \tif writeErr := out.Close(); writeErr != nil {\n536: \t\treturn writeErr\n537: \t}\n538: \tif err != nil && !(errors.Is(err, context.Canceled) && captureCtx.Err() != nil) {\n539: \t\treturn err\n540: \t}\n541: \n542: \treturn nil\n543: }\n544: \n545: // captureRun is the state a capture's chains share.\n546: type captureRun struct {\n547: \tr   *Runtime\n548: \treq clablabruntime.CaptureRequest\n549: \t// out is the merged stream; it writes the packets of every chain in timestamp order and\n550: \t// stops every chain once the packet limit is reached.\n551: \tout *clabcapture.Output\n552: \n553: \tsegment  time.Duration\n554: \toverlap  time.Duration\n555: \twindow   time.Duration\n556: \tdeadline time.Time\n557: }\n558: \n559: // emit writes a packet under its merged interface ID. It reports false once the packet limit is\n560: // reached and the capture stops.\n561: func (run *captureRun) emit(id uint32, packet *clabcapture.Packet) (bool, error) {\n562: \treturn run.out.Emit(id, packet)\n563: }\n564: \n565: func (run *captureRun) reportGap(gap clablabruntime.CaptureGap) {\n566: \tclabcapture.ReportGap(run.req.OnGap, gap)\n567: }\n568: \n569: // captureSegment is one clabwire capture process of a chain.\n570: type captureSegment struct {\n571: \tindex      int\n572: \tlocalStart time.Time\n573: \tduration   time.Duration\n574: \tcancel     context.CancelFunc\n575: \t// closeStdin closes the stdin of the segment's clabwire process, which ends it; it may be\n576: \t// called any number of times.\n577: \tcloseStdin func()\n578: \t// stopTimer closes stdin once the segment is no longer needed after a switch-over.\n579: \tstopTimer *time.Timer\n580: \t// started and ended are the pod-clock times of the Started and Succeeded audit records.\n581: \tstarted time.Time\n582: \tended   time.Time\n583: \tdone    bool\n584: }\n585: \n586: func (s *captureSegment) plannedEnd() time.Time {\n587: \treturn s.started.Add(s.duration)\n588: }\n589: \n590: // segmentEvent is something a segment reported: a packet, an audit record, or its end.\n591: type segmentEvent struct {\n592: \tsegment *captureSegment\n593: \tpacket  *clabcapture.Packet\n594: \taudit   *captureAudit\n595: \tdone    bool\n596: \terr     error\n597: }\n598: \n599: // captureChain runs the chained clabwire captures of one group.\n600: //\n601: // Chaining and the cut: segment k+1 starts `overlap` before segment k is due to end, so both\n602: // capture the same packets for a while. clabwire stamps packets when it reads them, so two\n603: // processes give the same packet timestamps a few microseconds apart, and timestamps alone\n604: // cannot pair them. The chain therefore cuts in the middle of the overlap and matches packets by\n605: // content close to the cut:\n606: //\n607: //  1. When segment k+1 reports Started (pod clock, from its audit record), the cut is\n608: //     T = midpoint of [Started(k+1), Started(k) + duration(k)]: both segments run then.\n609: //  2. Segment k keeps streaming live, but only packets stamped before T; it remembers the\n610: //     content of what it wrote since segment k+1 started.\n611: //  3. Segment k+1's packets are held back until segment k has ended. Then the ones stamped\n612: //     before T-W are dropped (segment k had them), the ones stamped within W of T are dropped\n613: //     when segment k wrote the same bytes on the same interface, and every other one is written.\n614: //     From then on segment k+1 streams live.\n615: //\n616: // Once the pod clock passed T+W, segment k's stdin is closed so it ends without running to its\n617: // planned end. While packets are held back, the chain holds the reorder buffer at T-W, so other\n618: // nodes' later packets do not overtake them in the merged stream.\n619: //\n620: // W (500 ms, less for short test segments) covers the stamping difference. Identical frames on\n621: // the same interface within W of the cut can be paired with each other, which can drop a true\n622: // repeat; nothing else is lost or doubled. A follow-up segment that does not start in time leaves\n623: // a gap, which is reported through CaptureRequest.OnGap (or logged), never silently ignored.\n624: type captureChain struct {\n625: \tcapture *captureRun\n626: \tgroup   *captureGroup\n627: \n628: \tevents chan segmentEvent\n629: \twg     sync.WaitGroup\n630: \n631: \tactive *captureSegment\n632: \tnext   *captureSegment\n633: \t// cut is the switch time between active and next, in nanoseconds; zero until known.\n634: \tcut int64\n635: \t// emitted remembers the content of the packets active wrote while next runs.\n636: \temitted map[uint64]int\n637: \t// held are the packets of next until active ends.\n638: \theld     []*clabcapture.Packet\n639: \tsegments int\n640: \tretries  int\n641: \t// final is set once no further segment is due.\n642: \tfinal bool\n643: \t// stopping is set once ctx ended: the segments are asked to end and what they still\n644: \t// deliver is written.\n645: \tstopping bool\n646: }\n647: \n648: // run runs the chain until its last segment ended. When ctx ends, it stops the segments and\n649: // keeps writing the packets they read until then; a segment that does not end within\n650: // captureStdinCloseGrace is cut.\n651: func (c *captureChain) run(ctx context.Context) error {\n652: \tc.events = make(chan segmentEvent, 256)\n653: \t// the segments outlive ctx so they can deliver their last packets; segmentsCtx cuts them\n654: \tsegmentsCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))\n655: \tvar abort *time.Timer\n656: \tdefer func() {\n657: \t\tif abort != nil {\n658: \t\t\tabort.Stop()\n659: \t\t}\n660: \t\tcancel()\n661: \t\tc.drain()\n662: \t\tc.capture.out.Release(c)\n663: \t}()\n664: \n665: \tc.active = c.start(segmentsCtx, c.segmentDuration(time.Now()))\n666: \ttimer := time.NewTimer(c.nextStartIn())\n667: \tdefer timer.Stop()\n668: \n669: \tdone := ctx.Done()\n670: \tfor {\n671: \t\tselect {\n672: \t\tcase <-done:\n673: \t\t\tdone = nil\n674: \t\t\tc.stop(timer)\n675: \t\t\tabort = time.AfterFunc(captureStdinCloseGrace, cancel)\n676: \t\tcase <-segmentsCtx.Done():\n677: \t\t\treturn nil\n678: \t\tcase <-timer.C:\n679: \t\t\tif c.next == nil && !c.final {\n680: \t\t\t\tc.startNext(segmentsCtx)\n681: \t\t\t}\n682: \t\tcase event := <-c.events:\n683: \t\t\tstop, err := c.handle(segmentsCtx, event, timer)\n684: \t\t\tif err != nil || stop {\n685: \t\t\t\treturn err\n686: \t\t\t}\n687: \t\t}\n688: \t}\n689: }\n690: \n691: // stop ends the chain early, like a deadline would: no further segment starts and the running\n692: // ones are asked to end. The chain then writes what they deliver until they ended.\n693: func (c *captureChain) stop(timer *time.Timer) {\n694: \tc.stopping = true\n695: \tc.final = true\n696: \ttimer.Stop()\n697: \tc.active.closeStdin()\n698: \tif c.next != nil {\n699: \t\tc.next.closeStdin()\n700: \t}\n701: }\n702: \n703: // drain waits for the segment goroutines after the chain ended.\n704: func (c *captureChain) drain() {\n705: \tdone := make(chan struct{})\n706: \tgo func() {\n707: \t\tc.wg.Wait()\n708: \t\tclose(done)\n709: \t}()\n710: \tfor {\n711: \t\tselect {\n712: \t\tcase <-done:\n713: \t\t\treturn\n714: \t\tcase <-c.events:\n715: \t\t}\n716: \t}\n717: }\n718: \n719: // segmentDuration is the requested duration of a segment starting now.\n720: func (c *captureChain) segmentDuration(now time.Time) time.Duration {\n721: \tduration := c.capture.segment\n722: \tif !c.capture.deadline.IsZero() {\n723: \t\tduration = min(duration, c.capture.deadline.Sub(now))\n724: \t}\n725: \n726: \treturn max(duration, minCaptureSegment)\n727: }\n728: \n729: // nextStartIn is the time until the follow-up of the active segment is due. It marks the chain\n730: // final when none is due.\n731: func (c *captureChain) nextStartIn() time.Duration {\n732: \tif c.stopping {\n733: \t\tc.final = true\n734: \t\treturn maxCaptureSegment\n735: \t}\n736: \tactiveEnd := c.active.localStart.Add(c.active.duration)\n737: \tif !c.capture.deadline.IsZero() &&\n738: \t\t!activeEnd.Before(c.capture.deadline.Add(-c.capture.window)) {\n739: \t\tc.final = true\n740: \t\treturn maxCaptureSegment\n741: \t}\n742: \tc.final = false\n743: \n744: \treturn max(time.Until(activeEnd.Add(-c.capture.overlap)), 0)\n745: }\n746: \n747: func (c *captureChain) startNext(ctx context.Context) {\n748: \tc.next = c.start(ctx, c.segmentDuration(time.Now()))\n749: \tc.emitted = map[uint64]int{}\n750: \tc.held = nil\n751: \tc.cut = 0\n752: }\n753: \n754: func (c *captureChain) handle(\n755: \tctx context.Context,\n756: \tevent segmentEvent,\n757: \ttimer *time.Timer,\n758: ) (bool, error) {\n759: \tsegment := event.segment\n760: \n761: \tswitch {\n762: \tcase event.audit != nil:\n763: \t\treturn false, c.handleAudit(segment, event.audit)\n764: \tcase event.packet != nil:\n765: \t\treturn c.handlePacket(segment, event.packet)\n766: \tcase event.done:\n767: \t\tsegment.done = true\n768: \t\tif segment.stopTimer != nil {\n769: \t\t\tsegment.stopTimer.Stop()\n770: \t\t}\n771: \t\tif event.err != nil && !c.stopping {\n772: \t\t\tif segment == c.next && segment.started.IsZero() && c.retries < captureStartRetries {\n773: \t\t\t\t// the follow-up did not start; try again while the active one still runs\n774: \t\t\t\tc.retries++\n775: \t\t\t\tlog.Warn(\"Capture follow-up segment failed to start, retrying\",\n776: \t\t\t\t\t\"node\", c.group.display, \"error\", event.err)\n777: \t\t\t\tc.next = nil\n778: \t\t\t\tresetTimer(timer, time.Second)\n779: \n780: \t\t\t\treturn false, nil\n781: \t\t\t}\n782: \n783: \t\t\treturn true, fmt.Errorf(\"capture on c9s node %s/%s/%s failed: %w\",\n784: \t\t\t\tc.group.location.Namespace, c.capture.req.Name, c.group.display, event.err)\n785: \t\t}\n786: \t\tif segment != c.active {\n787: \t\t\treturn false, nil\n788: \t\t}\n789: \n790: \t\treturn c.switchSegments(ctx, timer)\n791: \t}\n792: \n793: \treturn false, nil\n794: }\n795: \n796: func (c *captureChain) handleAudit(segment *captureSegment, audit *captureAudit) error {\n797: \tswitch audit.Status {\n798: \tcase captureAuditStarted:\n799: \t\tsegment.started = audit.Time\n800: \t\tlog.Debug(\"Capture segment started\", \"node\", c.group.display, \"segment\", segment.index,\n801: \t\t\t\"interfaces\", strings.Join(c.group.interfaces, \",\"), \"duration\", segment.duration)\n802: \t\tif segment == c.next && !c.active.started.IsZero() {\n803: \t\t\tc.setCut()\n804: \t\t}\n805: \t\tif segment == c.next {\n806: \t\t\tc.retries = 0\n807: \t\t}\n808: \tcase captureAuditSucceeded:\n809: \t\tsegment.ended = audit.Time\n810: \t\tlog.Debug(\"Capture segment succeeded\", \"node\", c.group.display,\n811: \t\t\t\"segment\", segment.index, \"packets\", audit.Packets)\n812: \tcase captureAuditDenied, captureAuditFailed:\n813: \t\treturn captureAuditError(c.group.display, audit)\n814: \t}\n815: \n816: \treturn nil\n817: }\n818: \n819: // captureAuditError turns a Denied or Failed clabwire audit record into an error.\n820: func captureAuditError(node string, audit *captureAudit) error {\n821: \tverb := \"failed\"\n822: \tif audit.Status == captureAuditDenied {\n823: \t\tverb = \"was denied\"\n824: \t}\n825: \tinterfaces := make([]string, 0, len(audit.Interfaces))\n826: \tfor _, intf := range audit.Interfaces {\n827: \t\tinterfaces = append(interfaces, intf.Name)\n828: \t}\n829: \n830: \treturn fmt.Errorf(\"capture of %s on node %s %s by clabwire: %s\",\n831: \t\tstrings.Join(interfaces, \",\"), node, verb, audit.Reason)\n832: }\n833: \n834: // setCut places the cut in the middle of the overlap of the active and the next segment, both\n835: // measured on the pod clock.\n836: func (c *captureChain) setCut() {\n837: \toverlapStart := c.next.started\n838: \toverlapEnd := c.active.plannedEnd()\n839: \tif overlapEnd.Sub(overlapStart) < 2*c.capture.window {\n840: \t\t// the overlap is too short to match packets around a cut: the switch is reported as a\n841: \t\t// gap once the active segment ended\n842: \t\tc.cut = 0\n843: \t\treturn\n844: \t}\n845: \tc.cut = overlapStart.Add(overlapEnd.Sub(overlapStart) / 2).UnixNano()\n846: \n847: \twindow := c.capture.window.Nanoseconds()\n848: \t// Packets the next segment holds back are stamped from T-W on: other chains' packets after\n849: \t// that wait in the reorder buffer until the switch, so the merged stream stays in order.\n850: \tc.capture.out.Hold(c, c.cut-window)\n851: \n852: \t// The active segment only matters for packets stamped before T. Once the pod clock passed\n853: \t// T+W, it is closed: packets it read until then are still delivered, and the ones it reads\n854: \t// later are stamped after T and dropped anyway. The next segment's Started record was\n855: \t// written on the pod clock no later than now, so the pod clock passes T+W no later than\n856: \t// (T - Started + W) from now.\n857: \tactive := c.active\n858: \tactive.stopTimer = time.AfterFunc(\n859: \t\ttime.Duration(c.cut-c.next.started.UnixNano()+window), active.closeStdin)\n860: }\n861: \n862: func (c *captureChain) handlePacket(\n863: \tsegment *captureSegment,\n864: \tpacket *clabcapture.Packet,\n865: ) (bool, error) {\n866: \tswitch segment {\n867: \tcase c.active:\n868: \t\tif c.cut != 0 && packet.Timestamp >= c.cut {\n869: \t\t\treturn false, nil\n870: \t\t}\n871: \t\tif c.next != nil {\n872: \t\t\tc.emitted[packetKey(packet)]++\n873: \t\t}\n874: \n875: \t\treturn c.emit(packet)\n876: \tcase c.next:\n877: \t\tc.held = append(c.held, packet)\n878: \t}\n879: \n880: \treturn false, nil\n881: }\n882: \n883: func (c *captureChain) emit(packet *clabcapture.Packet) (bool, error) {\n884: \tif int(packet.InterfaceID) >= len(c.group.ids) {\n885: \t\treturn true, fmt.Errorf(\"clabwire wrote a packet for interface %d of %d\",\n886: \t\t\tpacket.InterfaceID, len(c.group.ids))\n887: \t}\n888: \tmore, err := c.capture.emit(c.group.ids[packet.InterfaceID], packet)\n889: \n890: \treturn !more, err\n891: }\n892: \n893: // switchSegments makes the next segment the active one after the active one ended, writing the\n894: // held packets of the next one that the active one did not write.\n895: func (c *captureChain) switchSegments(ctx context.Context, timer *time.Timer) (bool, error) {\n896: \t// the held packets are in the reorder buffer once this returns\n897: \tdefer c.capture.out.Release(c)\n898: \n899: \tended := c.active\n900: \tif c.stopping && c.next != nil && c.next.started.IsZero() {\n901: \t\t// the chain is stopping: a follow-up that has not started takes nothing over\n902: \t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n903: \t}\n904: \tif c.final && c.next == nil {\n905: \t\treturn true, nil\n906: \t}\n907: \n908: \tif c.next == nil || c.next.started.IsZero() || c.cut == 0 {\n909: \t\tfrom := ended.ended\n910: \t\tif from.IsZero() {\n911: \t\t\tfrom = ended.plannedEnd()\n912: \t\t}\n913: \t\tgap := clablabruntime.CaptureGap{\n914: \t\t\tNode: c.group.display, Interfaces: c.group.interfaces, From: from,\n915: \t\t\tReason: \"the follow-up capture did not overlap the previous one\",\n916: \t\t}\n917: \t\tif c.next != nil && !c.next.started.IsZero() {\n918: \t\t\tgap.To = c.next.started\n919: \t\t}\n920: \t\tc.capture.reportGap(gap)\n921: \t}\n922: \n923: \tif c.next != nil && c.next.done && !c.stopping {\n924: \t\t// the follow-up already ended (it started too late to take over): keep what it\n925: \t\t// captured and continue with a fresh segment\n926: \t\tfor _, packet := range c.held {\n927: \t\t\tif stop, err := c.emit(packet); stop || err != nil {\n928: \t\t\t\treturn true, err\n929: \t\t\t}\n930: \t\t}\n931: \t\tc.next, c.held, c.emitted, c.cut = nil, nil, nil, 0\n932: \t}\n933: \n934: \tif c.next == nil {\n935: \t\tif !c.capture.deadline.IsZero() &&\n936: \t\t\t!time.Now().Before(c.capture.deadline.Add(-c.capture.window)) {\n937: \t\t\treturn true, nil\n938: \t\t}\n939: \t\tc.active = c.start(ctx, c.segmentDuration(time.Now()))\n940: \t\tresetTimer(timer, c.nextStartIn())\n941: \n942: \t\treturn false, nil\n943: \t}\n944: \n945: \twindow := c.capture.window.Nanoseconds()\n946: \tfor _, packet := range c.held {\n947: \t\tif c.cut != 0 {\n948: \t\t\tif packet.Timestamp < c.cut-window {\n949: \t\t\t\tcontinue\n950: \t\t\t}\n951: \t\t\tif packet.Timestamp < c.cut+window {\n952: \t\t\t\tkey := packetKey(packet)\n953: \t\t\t\tif c.emitted[key] > 0 {\n954: \t\t\t\t\tc.emitted[key]--\n955: \t\t\t\t\tcontinue\n956: \t\t\t\t}\n957: \t\t\t}\n958: \t\t}\n959: \t\tif stop, err := c.emit(packet); stop || err != nil {\n960: \t\t\treturn true, err\n961: \t\t}\n962: \t}\n963: \n964: \tc.active, c.next = c.next, nil\n965: \tc.held, c.emitted, c.cut = nil, nil, 0\n966: \tif c.active.done {\n967: \t\t// the chain is stopping and the follow-up ended before the active one\n968: \t\treturn true, nil\n969: \t}\n970: \tresetTimer(timer, c.nextStartIn())\n971: \n972: \treturn false, nil\n973: }\n974: \n975: func resetTimer(timer *time.Timer, d time.Duration) {\n976: \tif !timer.Stop() {\n977: \t\tselect {\n978: \t\tcase <-timer.C:\n979: \t\tdefault:\n980: \t\t}\n981: \t}\n982: \ttimer.Reset(d)\n983: }\n984: \n985: // packetKey identifies a packet by its interface and content.\n986: func packetKey(packet *clabcapture.Packet) uint64 {\n987: \thash := fnv.New64a()\n988: \tvar id [4]byte\n989: \tid[0] = byte(packet.InterfaceID)\n990: \tid[1] = byte(packet.InterfaceID >> 8)\n991: \t_, _ = hash.Write(id[:])\n992: \t_, _ = hash.Write(packet.Data)\n993: \n994: \treturn hash.Sum64()\n995: }\n996: \n997: // start runs one clabwire capture and reports its packets, audit records and end as events.\n998: func (c *captureChain) start(ctx context.Context, duration time.Duration) *captureSegment {\n999: \tsegmentCtx, cancel := context.WithCancel(ctx)\n1000: \tstdinReader, stdinWriter := io.Pipe()\n1001: \tsegment := &captureSegment{\n1002: \t\tindex: c.segments, localStart: time.Now(), duration: duration, cancel: cancel,\n1003: \t\tcloseStdin: func() { _ = stdinWriter.Close() },\n1004: \t}\n1005: \tc.segments++\n1006: \n1007: \tcommand := []string{\n1008: \t\tclabwireManager, \"node-runtime\", \"packet-capture\",\n1009: \t\t\"--nodeName\", c.group.location.NodeName,\n1010: \t\t\"--format\", \"pcapng\",\n1011: \t\t\"--snapLength\", strconv.Itoa(c.capture.req.SnapLength),\n1012: \t\t\"--duration\", duration.String(),\n1013: \t\tclabwireStopOnStdinClose,\n1014: \t}\n1015: \tfor _, name := range c.group.interfaces {\n1016: \t\tcommand = append(command, \"--interface\", name)\n1017: \t}\n1018: \tif c.capture.req.PacketLimit > 0 {\n1019: \t\tremaining := int64(c.capture.req.PacketLimit) - c.capture.out.Written()\n1020: \t\tcommand = append(command, \"--packetLimit\",\n1021: \t\t\tstrconv.FormatInt(min(max(remaining, 1), maxClabwirePackets), 10))\n1022: \t}\n1023: \n1024: \tsend := func(event segmentEvent) {\n1025: \t\tevent.segment = segment\n1026: \t\tselect {\n1027: \t\tcase c.events <- event:\n1028: \t\tcase <-segmentCtx.Done():\n1029: \t\t}\n1030: \t}\n1031: \n1032: \tstdoutReader, stdoutWriter := io.Pipe()\n1033: \tstderr := &auditLineWriter{send: func(audit *captureAudit) { send(segmentEvent{audit: audit}) }}\n1034: \n1035: \t// The exec outlives the segment's context by up to captureStdinCloseGrace: when the segment\n1036: \t// ends for any reason (the capture is cancelled or failed, the output failed, or a newer\n1037: \t// segment took over), its stdin is closed first so clabwire ends on its own, and the stream\n1038: \t// is cut only if it does not.\n1039: \texecCtx, cancelExec := context.WithCancel(context.WithoutCancel(segmentCtx))\n1040: \texecDone := make(chan struct{})\n1041: \n1042: \tc.wg.Add(3)\n1043: \treadDone := make(chan error, 1)\n1044: \tgo func() {\n1045: \t\tdefer c.wg.Done()\n1046: \t\treadDone <- c.readSegment(stdoutReader, func(packet *clabcapture.Packet) {\n1047: \t\t\tsend(segmentEvent{packet: packet})\n1048: \t\t})\n1049: \t\t_, _ = io.Copy(io.Discard, stdoutReader)\n1050: \t}()\n1051: \tgo func() {\n1052: \t\tdefer c.wg.Done()\n1053: \t\tselect {\n1054: \t\tcase <-execDone:\n1055: \t\t\treturn\n1056: \t\tcase <-segmentCtx.Done():\n1057: \t\t}\n1058: \t\tsegment.closeStdin()\n1059: \t\tgrace := time.NewTimer(captureStdinCloseGrace)\n1060: \t\tdefer grace.Stop()\n1061: \t\tselect {\n1062: \t\tcase <-execDone:\n1063: \t\tcase <-grace.C:\n1064: \t\t\tlog.Debug(\"Capture segment did not end after its stdin closed, cutting the stream\",\n1065: \t\t\t\t\"node\", c.group.display, \"segment\", segment.index)\n1066: \t\t\tcancelExec()\n1067: \t\t}\n1068: \t}()\n1069: \tgo func() {\n1070: \t\tdefer c.wg.Done()\n1071: \t\tdefer cancel()\n1072: \t\tdefer cancelExec()\n1073: \n1074: \t\terr := c.capture.r.execInPodContainer()(execCtx, c.group.location.Namespace,\n1075: \t\t\tc.group.location.Pod, clabwireContainer, command, stdinReader, stdoutWriter, stderr)\n1076: \t\tclose(execDone)\n1077: \t\t// the process ended: release the stdin copy of the exec stream\n1078: \t\tsegment.closeStdin()\n1079: \t\t_ = stdoutWriter.Close()\n1080: \t\treadErr := <-readDone\n1081: \t\tstderr.flush()\n1082: \t\tif err == nil && readErr != nil {\n1083: \t\t\terr = readErr\n1084: \t\t}\n1085: \t\tif err != nil && stderr.text() != \"\" {\n1086: \t\t\tif unsupported := unsupportedClabwire(\n1087: \t\t\t\tc.group.location,\n1088: \t\t\t\tstderr.text(),\n1089: \t\t\t); unsupported != nil {\n1090: \t\t\t\terr = unsupported\n1091: \t\t\t} else {\n1092: \t\t\t\terr = fmt.Errorf(\"%w: %s\", err, stderr.text())\n1093: \t\t\t}\n1094: \t\t}\n1095: \t\tsend(segmentEvent{done: true, err: err})\n1096: \t}()\n1097: \n1098: \treturn segment\n1099: }\n1100: \n1101: // unsupportedClabwire recognizes a clabwire that rejects --stop-on-stdin-close, which every\n1102: // capture passes: its release predates the capture contract the runtime needs.\n1103: func unsupportedClabwire(location clablabruntime.NodeLocation, stderr string) error {\n1104: \tif !strings.Contains(stderr, \"flag provided but not defined\") ||\n1105: \t\t!strings.Contains(stderr, strings.TrimPrefix(clabwireStopOnStdinClose, \"-\")) {\n1106: \t\treturn nil\n1107: \t}\n1108: \n1109: \treturn &unsupportedClabernetesError{reason: fmt.Sprintf(\n1110: \t\t\"clabwire in pod %s/%s does not accept packet-capture %s\",\n1111: \t\tlocation.Namespace, location.Pod, clabwireStopOnStdinClose)}\n1112: }\n1113: \n1114: // readSegment checks that a segment's interfaces are the requested ones and passes its packets\n1115: // on with the segment's interface index.\n1116: func (c *captureChain) readSegment(stdout io.Reader, packet func(*clabcapture.Packet)) error {\n1117: \treader := clabcapture.NewReader(stdout)\n1118: \tinterfaces := 0\n1119: \tfor {\n1120: \t\tevent, err := reader.Next()\n1121: \t\tif errors.Is(err, io.EOF) {\n1122: \t\t\treturn nil\n1123: \t\t}\n1124: \t\tif errors.Is(err, io.ErrUnexpectedEOF) {\n1125: \t\t\t// the process was stopped inside a block\n1126: \t\t\treturn nil\n1127: \t\t}\n1128: \t\tif err != nil {\n1129: \t\t\treturn fmt.Errorf(\"failed to read the clabwire capture: %w\", err)\n1130: \t\t}\n1131: \t\tif event.Interface != nil {\n1132: \t\t\tif interfaces >= len(c.group.interfaces) ||\n1133: \t\t\t\tevent.Interface.Name != c.group.interfaces[interfaces] {\n1134: \t\t\t\treturn fmt.Errorf(\"clabwire described interface %q, want %s in order\",\n1135: \t\t\t\t\tevent.Interface.Name, strings.Join(c.group.interfaces, \", \"))\n1136: \t\t\t}\n1137: \t\t\tinterfaces++\n1138: \t\t\tcontinue\n1139: \t\t}\n1140: \t\tif event.Packet != nil {\n1141: \t\t\tpacket(event.Packet)\n1142: \t\t}\n1143: \t}\n1144: }\n1145: \n1146: // auditLineWriter parses clabwire's stderr: audit records go to send, other lines are kept for\n1147: // error messages.\n1148: type auditLineWriter struct {\n1149: \tsend func(*captureAudit)\n1150: \n1151: \tmu      sync.Mutex\n1152: \tpartial []byte\n1153: \tother   []string\n1154: }\n1155: \n1156: func (w *auditLineWriter) Write(data []byte) (int, error) {\n1157: \tw.mu.Lock()\n1158: \tw.partial = append(w.partial, data...)\n1159: \tvar lines [][]byte\n1160: \tfor {\n1161: \t\tidx := bytes.IndexByte(w.partial, '\\n')\n1162: \t\tif idx < 0 {\n1163: \t\t\tbreak\n1164: \t\t}\n1165: \t\tlines = append(lines, append([]byte(nil), w.partial[:idx]...))\n1166: \t\tw.partial = w.partial[idx+1:]\n1167: \t}\n1168: \tw.mu.Unlock()\n1169: \n1170: \tfor _, line := range lines {\n1171: \t\tw.line(line)\n1172: \t}\n1173: \n1174: \treturn len(data), nil\n1175: }\n1176: \n1177: func (w *auditLineWriter) flush() {\n1178: \tw.mu.Lock()\n1179: \tline := w.partial\n1180: \tw.partial = nil\n1181: \tw.mu.Unlock()\n1182: \tif len(bytes.TrimSpace(line)) != 0 {\n1183: \t\tw.line(line)\n1184: \t}\n1185: }\n1186: \n1187: func (w *auditLineWriter) line(line []byte) {\n1188: \tline = bytes.TrimSpace(line)\n1189: \tif len(line) == 0 {\n1190: \t\treturn\n1191: \t}\n1192: \n1193: \tvar audit captureAudit\n1194: \tif err := json.Unmarshal(\n1195: \t\tline,\n1196: \t\t&audit,\n1197: \t); err == nil &&\n1198: \t\taudit.SchemaVersion == captureAuditSchema {\n1199: \t\tw.send(&audit)\n1200: \t\treturn\n1201: \t}\n1202: \n1203: \tw.mu.Lock()\n1204: \tdefer w.mu.Unlock()\n1205: \tif len(w.other) < 20 {\n1206: \t\tw.other = append(w.other, string(line))\n1207: \t}\n1208: }\n1209: \n1210: func (w *auditLineWriter) text() string {\n1211: \tw.mu.Lock()\n1212: \tdefer w.mu.Unlock()\n1213: \n1214: \treturn strings.Join(w.other, \"; \")\n1215: }\n\n(End of file - total 1215 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\tfor _, location := range pods {\n\t\tgroup.Go(func() error {\n\t\t\tentries, err := r.listPodInterfaces(groupCtx, location.Namespace, location.Pod)\n\t\t\tif err != nil {\n\t\t\t\treturn 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// listPodInterfaces runs clabwire's --list-interfaces in a pod: the lab link interfaces of the\n// pod's nodes, with their aliases and peers.\nfunc (r *Runtime) listPodInterfaces(\n\tctx context.Context,\n\tnamespace, pod string,\n) ([]clabwireInterface, error) {\n\tvar stdout, stderr bytes.Buffer\n\terr := r.execInPodContainer()(ctx, namespace, pod, clabwireContainer,\n\t\t[]string{clabwireManager, \"node-runtime\", \"packet-capture\", \"--list-interfaces\"},\n\t\tnil, &stdout, &stderr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list the capturable interfaces of pod %s/%s: %w%s\",\n\t\t\tnamespace, pod, err, stderrSuffix(stderr.Bytes()))\n\t}\n\n\tvar entries []clabwireInterface\n\tif err := json.Unmarshal(stdout.Bytes(), &entries); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse the capturable interfaces of pod %s/%s: %w\",\n\t\t\tnamespace, pod, err)\n\t}\n\n\treturn entries, 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": 1215,
        "totalLines": 1215,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525852122,
      "end": 1793525852148
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19678a7f9001bRgWeEgo2jmA89",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196789b6c001KnZ5BdzG974Jav",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 21972,
    "input": 5643,
    "output": 70,
    "reasoning": 131,
    "cache": {
      "read": 16128,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196789b6c001KnZ5BdzG974Jav",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525848940,
    "completed": 1793525852157
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 21972,
    "input": 5643,
    "output": 70,
    "reasoning": 131,
    "cache": {
      "read": 16128,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 27
step-start
{
  "type": "step-start",
  "id": "prt_19678b046001PMSSVBHWwiSPXM",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19678a805001A3Xi9IrNVARfXH"
}
Reasoning
capture.go is large but mostly unchanged from before; the diff said capture.go M — changes likely: `listPodInterfaces` extraction, `nodeDisplayNames`, `findCaptureInterface`, `describeCaptureInterfaces`. I should compare with base to see what changed. But the diff for capture.go I saw in diff.txt earlier (details lost). The key review targets are the changed behaviors. Since the summary is long, I should focus.

Remaining to verify:
1. `reportedInterfaces`, `c9sIfaceState`, `interfaceEventData` in events.go or iface_stats.go — need to read the rest of events.go/iface_stats.go. Actually `reportedInterfaces` and `interfaceEventData` are probably in events.go. I read events.go partially before (lost details). Let me read iface_stats.go and events.go fully now.

2. reconcile.go lines around 217-221 (setTopologySourceFile on update).

3. plan.go line 56 context.

4. primitives.go line 225 context.

5. core/labruntime.go remaining parts (1-440, 720-end).

6. labruntime/runtime.go — Inspect lab-not-found.

7. Tests + docs + robot tests.

Let me batch: reconcile.go (partial around 180-260), plan.go (partial around 1-120), primitives.go (partial around 190-260), events.go, iface_stats.go full.
`capture.go` internals are coherent. Now the remaining poller/events bodies and the reconcile/plan/primitives hunks.
read · completed

Input

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

Output

<path>/source/head/labruntime/clabernetes/iface_stats.go</path>
<type>file</type>
<content>
1: package clabernetes
2: 
3: import (
4: 	"context"
5: 	"fmt"
6: 	"sort"
7: 	"strconv"
8: 	"strings"
9: 	"sync"
10: 	"time"
11: 
12: 	"github.com/charmbracelet/log"
13: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
14: 	corev1 "k8s.io/api/core/v1"
15: 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
16: )
17: 
18: const (
19: 	// interfaceSysfsMarker separates the /proc/net/dev counters from the sysfs interface
20: 	// attributes in the output of interfaceSampleScript.
21: 	interfaceSysfsMarker = "@@clab-sysfs"
22: 	// interfaceSampleScript reads the interface counters and, per interface, the sysfs
23: 	// attributes the interface state events carry, in one exec:
24: 	// name, ifindex, mtu, address, operstate, flags and ifalias, tab separated.
25: 	interfaceSampleScript = `cat /proc/net/dev; echo ` + interfaceSysfsMarker + `; ` +
26: 		`for d in /sys/class/net/*; do [ -e "$d/operstate" ] || continue; ` +
27: 		`printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "${d##*/}" "$(cat "$d/ifindex")" ` +
28: 		`"$(cat "$d/mtu")" "$(cat "$d/address")" "$(cat "$d/operstate")" ` +
29: 		`"$(cat "$d/flags")" "$(cat "$d/ifalias")"; done 2>/dev/null`
30: 
31: 	// interfaceSampleWorkers bounds the concurrent execs of one sampling round.
32: 	interfaceSampleWorkers = 16
33: 
34: 	// managementInterface is a node's management interface in its pod, the interface the
35: 	// clabernetes planner gives the management address by default. It has the name the
36: 	// management interface has in a container of the local runtimes.
37: 	managementInterface = "eth0"
38: 	// loopbackInterface is reported like the local runtimes report it.
39: 	loopbackInterface = "lo"
40: 	// clabernetesAliasPrefix starts the interface aliases clabernetes marks its own interfaces
41: 	// and the lab links it wires with. They are not the topology's names, so they are not
42: 	// reported.
43: 	clabernetesAliasPrefix = "c9s:"
44: 	// zeroMAC is the hardware address sysfs reports for interfaces without one (loopback).
45: 	zeroMAC = "00:00:00:00:00:00"
46: 
47: 	// Interface event actions and link types, as the local runtimes report them.
48: 	interfaceActionSnapshot = "snapshot"
49: 	interfaceActionCreate   = "create"
50: 	interfaceActionUpdate   = "update"
51: 	interfaceActionDelete   = "delete"
52: 	interfaceActionStats    = "stats"
53: 	interfaceTypeVeth       = "veth"
54: 	interfaceTypeDevice     = "device"
55: 
56: 	// shell exit codes of a command that cannot be found or executed.
57: 	exitCommandNotExecutable = 126
58: 	exitCommandNotFound      = 127
59: )
60: 
61: type interfacePollOptions struct {
62: 	interval            time.Duration
63: 	includeStats        bool
64: 	includeInitialState bool
65: }
66: 
67: type c9sIfaceStats struct {
68: 	Name      string
69: 	RxBytes   uint64
70: 	RxPackets uint64
71: 	TxBytes   uint64
72: 	TxPackets uint64
73: }
74: 
75: type c9sIfaceStatsSample struct {
76: 	Stats     c9sIfaceStats
77: 	Timestamp time.Time
78: }
79: 
80: // c9sIfaceState is the sysfs view of one interface in a device container.
81: type c9sIfaceState struct {
82: 	Name      string
83: 	Index     int
84: 	MTU       int
85: 	MAC       string
86: 	OperState string
87: 	Flags     uint64
88: 	Alias     string
89: }
90: 
91: // trackedNode remembers the interfaces last reported for a node, so their changes and their
92: // removal can be reported, also when the node stops running.
93: type trackedNode struct {
94: 	lab    *clablabruntime.LabState
95: 	node   clablabruntime.NodeState
96: 	ifaces map[string]clablabruntime.InterfaceEventData
97: }
98: 
99: type interfaceSampleTarget struct {
100: 	state *clablabruntime.LabState
101: 	node  clablabruntime.NodeState
102: 	pod   *corev1.Pod
103: }
104: 
105: type interfaceSample struct {
106: 	target    interfaceSampleTarget
107: 	stats     []c9sIfaceStats
108: 	ifaces    []c9sIfaceState
109: 	hasStates bool
110: 	// links are the node's lab link interfaces as clabwire lists them.
111: 	links     []clabwireInterface
112: 	timestamp time.Time
113: 	err       error
114: }
115: 
116: // podInterfaceListing is the clabwire interface listing of a pod, per node. It is listed again
117: // when the pod's interfaces change.
118: type podInterfaceListing struct {
119: 	names  string
120: 	byNode map[string][]clabwireInterface
121: }
122: 
123: // interfacePoller samples the interfaces of every running node in an event scope and turns the
124: // samples into interface events. It reports the interfaces a container of the local runtimes
125: // has for the same node: the node's lab link interfaces, with the names and aliases clabwire
126: // lists for them, the management interface and loopback. The pod's own interfaces (the pod
127: // network, clabernetes' interposition and link transport interfaces) are not reported.
128: type interfacePoller struct {
129: 	r     *Runtime
130: 	scope eventScope
131: 	opts  interfacePollOptions
132: 	sink  chan<- clablabruntime.Event
133: 
134: 	statsSamples map[string]c9sIfaceStatsSample
135: 	nodes        map[string]*trackedNode
136: 
137: 	noShellMu sync.Mutex
138: 	// noShell holds the pods whose device container has no shell; they are sampled with a
139: 	// plain cat of /proc/net/dev and report statistics without interface state.
140: 	noShell map[string]bool
141: 
142: 	listingsMu sync.Mutex
143: 	// listings holds the clabwire interface listing per pod (namespace/pod).
144: 	listings map[string]*podInterfaceListing
145: 
146: 	firstRound bool
147: }
148: 
149: func (r *Runtime) pollInterfaces(
150: 	ctx context.Context,
151: 	scope eventScope,
152: 	opts interfacePollOptions,
153: 	eventSink chan<- clablabruntime.Event,
154: ) {
155: 	if opts.interval <= 0 {
156: 		opts.interval = time.Second
157: 	}
158: 
159: 	poller := newInterfacePoller(r, scope, opts, eventSink)
160: 	poller.round(ctx)
161: 
162: 	ticker := time.NewTicker(opts.interval)
163: 	defer ticker.Stop()
164: 
165: 	for {
166: 		select {
167: 		case <-ctx.Done():
168: 			return
169: 		case <-ticker.C:
170: 			poller.round(ctx)
171: 		}
172: 	}
173: }
174: 
175: func newInterfacePoller(
176: 	r *Runtime,
177: 	scope eventScope,
178: 	opts interfacePollOptions,
179: 	eventSink chan<- clablabruntime.Event,
180: ) *interfacePoller {
181: 	return &interfacePoller{
182: 		r:            r,
183: 		scope:        scope,
184: 		opts:         opts,
185: 		sink:         eventSink,
186: 		statsSamples: map[string]c9sIfaceStatsSample{},
187: 		nodes:        map[string]*trackedNode{},
188: 		noShell:      map[string]bool{},
189: 		listings:     map[string]*podInterfaceListing{},
190: 		firstRound:   true,
191: 	}
192: }
193: 
194: func (p *interfacePoller) round(ctx context.Context) {
195: 	defer func() { p.firstRound = false }()
196: 
197: 	states, err := p.r.labStates(ctx, p.scope)
198: 	if err != nil {
199: 		log.Debug("failed to list C9s labs for interface events", "error", err)
200: 		return
201: 	}
202: 
203: 	running := map[string]bool{}
204: 	pods := map[string]bool{}
205: 	var targets []interfaceSampleTarget
206: 	for _, state := range states {
207: 		for _, node := range state.Nodes {
208: 			if node.ContainerState != clablabruntime.ContainerStateRunning || node.Pod == "" ||
209: 				node.Container == "" {
210: 				continue
211: 			}
212: 
213: 			running[c9sNodeKey(state.Namespace, state.Name, node.Name)] = true
214: 			pods[state.Namespace+"/"+node.Pod] = true
215: 			targets = append(targets, interfaceSampleTarget{
216: 				state: state,
217: 				node:  node,
218: 				pod: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{
219: 					Name:      node.Pod,
220: 					Namespace: state.Namespace,
221: 				}},
222: 			})
223: 		}
224: 	}
225: 
226: 	for _, sample := range p.sampleAll(ctx, targets) {
227: 		if ctx.Err() != nil {
228: 			return
229: 		}
230: 		if sample.err != nil {
231: 			log.Debug("failed to sample C9s interfaces",
232: 				"namespace", sample.target.state.Namespace,
233: 				"lab", sample.target.state.Name,
234: 				"node", sample.target.node.Name,
235: 				"error", sample.err,
236: 			)
237: 
238: 			continue
239: 		}
240: 
241: 		p.processSample(ctx, sample)
242: 	}
243: 
244: 	p.retireStoppedNodes(ctx, running)
245: 	p.forgetListings(pods)
246: }
247: 
248: // retireStoppedNodes reports the interfaces of nodes that stopped running, or were removed, as
249: // deleted: they are gone with the node's pod.
250: func (p *interfacePoller) retireStoppedNodes(ctx context.Context, running map[string]bool) {
251: 	for key, tracked := range p.nodes {
252: 		if running[key] {
253: 			continue
254: 		}
255: 
256: 		for _, name := range sortedInterfaceNames(tracked.ifaces) {
257: 			p.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], time.Now())
258: 			p.forgetStats(tracked, name)
259: 		}
260: 		delete(p.nodes, key)
261: 	}
262: }
263: 
264: // forgetListings drops the interface listings of pods that are gone.
265: func (p *interfacePoller) forgetListings(pods map[string]bool) {
266: 	p.listingsMu.Lock()
267: 	defer p.listingsMu.Unlock()
268: 
269: 	for key := range p.listings {
270: 		if !pods[key] {
271: 			delete(p.listings, key)
272: 		}
273: 	}
274: }
275: 
276: func (p *interfacePoller) sampleAll(
277: 	ctx context.Context,
278: 	targets []interfaceSampleTarget,
279: ) []interfaceSample {
280: 	samples := make([]interfaceSample, len(targets))
281: 
282: 	var wg sync.WaitGroup
283: 	sem := make(chan struct{}, interfaceSampleWorkers)
284: 	for idx := range targets {
285: 		wg.Add(1)
286: 		sem <- struct{}{}
287: 		go func(idx int) {
288: 			defer wg.Done()
289: 			defer func() { <-sem }()
290: 
291: 			samples[idx] = p.sample(ctx, targets[idx])
292: 		}(idx)
293: 	}
294: 	wg.Wait()
295: 
296: 	return samples
297: }
298: 
299: func (p *interfacePoller) sample(
300: 	ctx context.Context,
301: 	target interfaceSampleTarget,
302: ) interfaceSample {
303: 	sample := interfaceSample{target: target}
304: 	podName := target.pod.Name
305: 
306: 	p.noShellMu.Lock()
307: 	noShell := p.noShell[podName]
308: 	p.noShellMu.Unlock()
309: 
310: 	command := []string{"sh", "-c", interfaceSampleScript}
311: 	if noShell {
312: 		command = []string{"cat", "/proc/net/dev"}
313: 	}
314: 
315: 	stdout, stderr, rc, err := p.r.execInPod(ctx, target.pod, target.node.Container, command)
316: 	if !noShell && commandNotExecutable(rc, err) {
317: 		p.noShellMu.Lock()
318: 		p.noShell[podName] = true
319: 		p.noShellMu.Unlock()
320: 
321: 		log.Debug("C9s device container has no shell; reporting interface statistics only",
322: 			"namespace", target.state.Namespace,
323: 			"lab", target.state.Name,
324: 			"node", target.node.Name,
325: 		)
326: 
327: 		stdout, stderr, rc, err = p.r.execInPod(ctx, target.pod, target.node.Container,
328: 			[]string{"cat", "/proc/net/dev"})
329: 	}
330: 
331: 	sample.timestamp = time.Now()
332: 	switch {
333: 	case err != nil:
334: 		sample.err = err
335: 	case rc != 0:
336: 		sample.err = fmt.Errorf("exit code %d: %s", rc, strings.TrimSpace(string(stderr)))
337: 	default:
338: 		sample.stats, sample.ifaces, sample.hasStates, sample.err = parseInterfaceSample(stdout)
339: 	}
340: 	if sample.err != nil {
341: 		return sample
342: 	}
343: 
344: 	sample.links, sample.err = p.nodeLinks(ctx, target, sampledInterfaceNames(sample))
345: 
346: 	return sample
347: }
348: 
349: // sampledInterfaceNames lists the interface names a sample saw, sorted and comma-joined.
350: func sampledInterfaceNames(sample interfaceSample) string {
351: 	names := make([]string, 0, len(sample.stats)+len(sample.ifaces))
352: 	seen := map[string]bool{}
353: 	for _, iface := range sample.ifaces {
354: 		if !seen[iface.Name] {
355: 			seen[iface.Name] = true
356: 			names = append(names, iface.Name)
357: 		}
358: 	}
359: 	for _, stat := range sample.stats {
360: 		if !seen[stat.Name] {
361: 			seen[stat.Name] = true
362: 			names = append(names, stat.Name)
363: 		}
364: 	}
365: 	sort.Strings(names)
366: 
367: 	return strings.Join(names, ",")
368: }
369: 
370: // nodeLinks returns the lab link interfaces of a node from its pod's clabwire listing. A pod is
371: // listed once, and again when its interfaces change (a pod gets its link interfaces as clabwire
372: // wires them).
373: func (p *interfacePoller) nodeLinks(
374: 	ctx context.Context,
375: 	target interfaceSampleTarget,
376: 	names string,
377: ) ([]clabwireInterface, error) {
378: 	key := target.pod.Namespace + "/" + target.pod.Name
379: 
380: 	p.listingsMu.Lock()
381: 	listing := p.listings[key]
382: 	p.listingsMu.Unlock()
383: 
384: 	if listing == nil || listing.names != names {
385: 		entries, err := p.r.listPodInterfaces(ctx, target.pod.Namespace, target.pod.Name)
386: 		if err != nil {
387: 			return nil, err
388: 		}
389: 
390: 		listing = &podInterfaceListing{
391: 			names:  names,
392: 			byNode: map[string][]clabwireInterface{},
393: 		}
394: 		for _, entry := range entries {
395: 			listing.byNode[entry.Node] = append(listing.byNode[entry.Node], entry)
396: 		}
397: 
398: 		p.listingsMu.Lock()
399: 		p.listings[key] = listing
400: 		p.listingsMu.Unlock()
401: 	}
402: 
403: 	return listing.byNode[target.node.Name], nil
404: }
405: 
406: // commandNotExecutable reports an exec that failed because the command does not exist in the
407: // container.
408: func commandNotExecutable(rc int, err error) bool {
409: 	if rc == exitCommandNotExecutable || rc == exitCommandNotFound {
410: 		return true
411: 	}
412: 
413: 	return err != nil && strings.Contains(err.Error(), "executable file not found")
414: }
415: 
416: // reportedInterfaces are the interfaces reported for a node, by name, with the alias the
417: // topology gave them: its lab link interfaces, the management interface and loopback.
418: func reportedInterfaces(links []clabwireInterface) map[string]string {
419: 	reported := map[string]string{
420: 		loopbackInterface:   "",
421: 		managementInterface: "",
422: 	}
423: 	for _, link := range links {
424: 		reported[link.Interface] = link.Alias
425: 	}
426: 
427: 	return reported
428: }
429: 
430: // interfaceEventData describes an interface the way the local runtimes' netlink events do: the
431: // alias is the topology's name for the interface (an alias clabernetes set for its own use is
432: // not reported), the operational state uses netlink's names, lab link and management
433: // interfaces are veth pairs, loopback a device, and loopback has no hardware address.
434: func interfaceEventData(iface c9sIfaceState, alias string) clablabruntime.InterfaceEventData {
435: 	if alias == "" && !strings.HasPrefix(iface.Alias, clabernetesAliasPrefix) {
436: 		alias = iface.Alias
437: 	}
438: 
439: 	mac := iface.MAC
440: 	if mac == zeroMAC {
441: 		mac = ""
442: 	}
443: 
444: 	linkType := interfaceTypeVeth
445: 	if iface.Name == loopbackInterface {
446: 		linkType = interfaceTypeDevice
447: 	}
448: 
449: 	return clablabruntime.InterfaceEventData{
450: 		Name:      iface.Name,
451: 		Alias:     alias,
452: 		Index:     iface.Index,
453: 		MTU:       iface.MTU,
454: 		MAC:       mac,
455: 		OperState: netlinkOperState(iface.OperState),
456: 		Type:      linkType,
457: 	}
458: }
459: 
460: // netlinkOperState names an operational state from sysfs (RFC 2863, as in
461: // /sys/class/net/<if>/operstate) the way netlink, and so the local runtimes' events, name it.
462: func netlinkOperState(operState string) string {
463: 	switch operState {
464: 	case "notpresent":
465: 		return "not-present"
466: 	case "lowerlayerdown":
467: 		return "lower-layer-down"
468: 	case "":
469: 		return "unknown"
470: 	default:
471: 		return operState
472: 	}
473: }
474: 
475: func (p *interfacePoller) processSample(ctx context.Context, sample interfaceSample) {
476: 	state := sample.target.state
477: 	node := sample.target.node
478: 	key := c9sNodeKey(state.Namespace, state.Name, node.Name)
479: 
480: 	tracked, known := p.nodes[key]
481: 	if !known {
482: 		tracked = &trackedNode{ifaces: map[string]clablabruntime.InterfaceEventData{}}
483: 		p.nodes[key] = tracked
484: 	}
485: 	tracked.lab = state
486: 	tracked.node = node
487: 
488: 	reported := reportedInterfaces(sample.links)
489: 
490: 	if sample.hasStates {
491: 		p.processStates(ctx, tracked, reported, sample)
492: 	}
493: 
494: 	if !p.opts.includeStats {
495: 		return
496: 	}
497: 	for _, stat := range sample.stats {
498: 		alias, ok := reported[stat.Name]
499: 		if !ok {
500: 			continue
501: 		}
502: 
503: 		statsKey := c9sIfaceStatsKey(state.Namespace, state.Name, node.Name, stat.Name)
504: 		current := c9sIfaceStatsSample{Stats: stat, Timestamp: sample.timestamp}
505: 		if previous, ok := p.statsSamples[statsKey]; ok {
506: 			data, ok := tracked.ifaces[stat.Name]
507: 			if !ok {
508: 				data = interfaceEventData(c9sIfaceState{Name: stat.Name}, alias)
509: 				data.OperState = ""
510: 			}
511: 			data.Stats = c9sIfaceStatsData(previous, current)
512: 			p.emit(ctx, tracked, interfaceActionStats, data, current.Timestamp)
513: 		}
514: 
515: 		p.statsSamples[statsKey] = current
516: 	}
517: }
518: 
519: // processStates reports the interfaces that appeared (snapshot in the first round with
520: // --initial-state, create later), changed (update) or disappeared (delete) since the last
521: // sample, like the netlink events of the local runtimes.
522: func (p *interfacePoller) processStates(
523: 	ctx context.Context,
524: 	tracked *trackedNode,
525: 	reported map[string]string,
526: 	sample interfaceSample,
527: ) {
528: 	present := map[string]bool{}
529: 	for _, iface := range sample.ifaces {
530: 		alias, ok := reported[iface.Name]
531: 		if !ok {
532: 			continue
533: 		}
534: 
535: 		data := interfaceEventData(iface, alias)
536: 		present[iface.Name] = true
537: 		previous, seen := tracked.ifaces[iface.Name]
538: 		tracked.ifaces[iface.Name] = data
539: 
540: 		switch {
541: 		case seen && previous == data:
542: 		case !seen && p.firstRound:
543: 			// Interfaces that exist when the stream starts are only reported with
544: 			// --initial-state; later changes are always reported.
545: 			if p.opts.includeInitialState {
546: 				p.emit(ctx, tracked, interfaceActionSnapshot, data, sample.timestamp)
547: 			}
548: 		case !seen:
549: 			p.emit(ctx, tracked, interfaceActionCreate, data, sample.timestamp)
550: 		default:
551: 			p.emit(ctx, tracked, interfaceActionUpdate, data, sample.timestamp)
552: 		}
553: 	}
554: 
555: 	for _, name := range sortedInterfaceNames(tracked.ifaces) {
556: 		if present[name] {
557: 			continue
558: 		}
559: 
560: 		p.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], sample.timestamp)
561: 		p.forgetStats(tracked, name)
562: 		delete(tracked.ifaces, name)
563: 	}
564: }
565: 
566: func sortedInterfaceNames(ifaces map[string]clablabruntime.InterfaceEventData) []string {
567: 	names := make([]string, 0, len(ifaces))
568: 	for name := range ifaces {
569: 		names = append(names, name)
570: 	}
571: 	sort.Strings(names)
572: 
573: 	return names
574: }
575: 
576: func (p *interfacePoller) forgetStats(tracked *trackedNode, ifName string) {
577: 	delete(p.statsSamples,
578: 		c9sIfaceStatsKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name, ifName))
579: }
580: 
581: func (p *interfacePoller) emit(
582: 	ctx context.Context,
583: 	tracked *trackedNode,
584: 	action string,
585: 	data clablabruntime.InterfaceEventData,
586: 	timestamp time.Time,
587: ) {
588: 	p.r.sendEvent(ctx, p.sink, c9sInterfaceEvent(tracked, action, data, timestamp))
589: }
590: 
591: // c9sInterfaceEvent is an interface event of a node. The actor is the node, as for its container
592: // events. The interface itself is in Interface; the events command reports it with the
593: // attributes of the local runtimes' interface events.
594: func c9sInterfaceEvent(
595: 	tracked *trackedNode,
596: 	action string,
597: 	data clablabruntime.InterfaceEventData,
598: 	timestamp time.Time,
599: ) clablabruntime.Event {
600: 	key := c9sNodeKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name)
601: 
602: 	attributes := map[string]string{
603: 		"namespace": tracked.lab.Namespace,
604: 		"lab":       tracked.lab.Name,
605: 		"node":      tracked.node.Name,
606: 		"origin":    clabernetesAppValue,
607: 	}
608: 	if tracked.node.Pod != "" {
609: 		attributes["pod"] = tracked.node.Pod
610: 	}
611: 
612: 	node := tracked.node
613: 
614: 	return clablabruntime.Event{
615: 		Timestamp:   timestamp,
616: 		Type:        clablabruntime.EventTypeInterface,
617: 		Action:      action,
618: 		ActorID:     key,
619: 		ActorName:   fmt.Sprintf("%s-%s", tracked.lab.Name, tracked.node.Name),
620: 		ActorFullID: key,
621: 		Attributes:  attributes,
622: 		Lab:         tracked.lab,
623: 		Node:        &node,
624: 		Interface:   &data,
625: 	}
626: }
627: 
628: // c9sIfaceStatsData computes the counters and rates of a stats event from two samples.
629: func c9sIfaceStatsData(previous, current c9sIfaceStatsSample) *clablabruntime.InterfaceStats {
630: 	interval := current.Timestamp.Sub(previous.Timestamp)
631: 	if interval <= 0 {
632: 		interval = time.Second
633: 	}
634: 
635: 	seconds := interval.Seconds()
636: 	stat := current.Stats
637: 
638: 	return &clablabruntime.InterfaceStats{
639: 		RxBytes:   stat.RxBytes,
640: 		TxBytes:   stat.TxBytes,
641: 		RxPackets: stat.RxPackets,
642: 		TxPackets: stat.TxPackets,
643: 		RxBps:     float64(counterDelta(stat.RxBytes, previous.Stats.RxBytes)*8) / seconds,
644: 		TxBps:     float64(counterDelta(stat.TxBytes, previous.Stats.TxBytes)*8) / seconds,
645: 		RxPps:     float64(counterDelta(stat.RxPackets, previous.Stats.RxPackets)) / seconds,
646: 		TxPps:     float64(counterDelta(stat.TxPackets, previous.Stats.TxPackets)) / seconds,
647: 		Interval:  interval,
648: 	}
649: }
650: 
651: // parseInterfaceSample splits the output of interfaceSampleScript into the /proc/net/dev
652: // counters and the sysfs interface states. hasStates is false for output without the sysfs
653: // section, such as a plain cat of /proc/net/dev.
654: func parseInterfaceSample(data []byte) ([]c9sIfaceStats, []c9sIfaceState, bool, error) {
655: 	text := string(data)
656: 
657: 	procPart, sysfsPart, hasStates := strings.Cut(text, interfaceSysfsMarker+"\n")
658: 	if !hasStates {
659: 		procPart, _, hasStates = strings.Cut(text, interfaceSysfsMarker)
660: 	}
661: 
662: 	stats, err := parseProcNetDev([]byte(procPart))
663: 	if err != nil {
664: 		return nil, nil, false, err
665: 	}
666: 	if !hasStates {
667: 		return stats, nil, false, nil
668: 	}
669: 
670: 	return stats, parseSysfsInterfaces(sysfsPart), true, nil
671: }
672: 
673: func parseSysfsInterfaces(data string) []c9sIfaceState {
674: 	lines := strings.Split(data, "\n")
675: 	states := make([]c9sIfaceState, 0, len(lines))
676: 
677: 	for _, line := range lines {
678: 		fields := strings.SplitN(line, "\t", 7) //nolint:mnd
679: 		if len(fields) < 5 || strings.TrimSpace(fields[0]) == "" {
680: 			continue
681: 		}
682: 
683: 		state := c9sIfaceState{
684: 			Name:      strings.TrimSpace(fields[0]),
685: 			MAC:       strings.TrimSpace(fields[3]),
686: 			OperState: strings.ToLower(strings.TrimSpace(fields[4])),
687: 		}
688: 		state.Index, _ = strconv.Atoi(strings.TrimSpace(fields[1]))
689: 		state.MTU, _ = strconv.Atoi(strings.TrimSpace(fields[2]))
690: 		if len(fields) > 5 {
691: 			state.Flags, _ = strconv.ParseUint(
692: 				strings.TrimPrefix(strings.TrimSpace(fields[5]), "0x"), 16, 64)
693: 		}
694: 		if len(fields) > 6 {
695: 			state.Alias = strings.TrimSpace(fields[6])
696: 		}
697: 		if state.OperState == "" {
698: 			state.OperState = "unknown"
699: 		}
700: 
701: 		states = append(states, state)
702: 	}
703: 
704: 	return states
705: }
706: 
707: func parseProcNetDev(data []byte) ([]c9sIfaceStats, error) {
708: 	lines := strings.Split(string(data), "\n")
709: 	stats := make([]c9sIfaceStats, 0, len(lines))
710: 
711: 	for _, line := range lines {
712: 		line = strings.TrimSpace(line)
713: 		if line == "" || !strings.Contains(line, ":") {
714: 			continue
715: 		}
716: 
717: 		parts := strings.SplitN(line, ":", 2)
718: 		if len(parts) != 2 {
719: 			continue
720: 		}
721: 
722: 		ifName := strings.TrimSpace(parts[0])
723: 		fields := strings.Fields(parts[1])
724: 		if len(fields) < 16 {
725: 			return nil, fmt.Errorf("unexpected /proc/net/dev line for %q: %q", ifName, line)
726: 		}
727: 
728: 		rxBytes, err := strconv.ParseUint(fields[0], 10, 64)
729: 		if err != nil {
730: 			return nil, fmt.Errorf("failed to parse rx bytes for %q: %w", ifName, err)
731: 		}
732: 		rxPackets, err := strconv.ParseUint(fields[1], 10, 64)
733: 		if err != nil {
734: 			return nil, fmt.Errorf("failed to parse rx packets for %q: %w", ifName, err)
735: 		}
736: 		txBytes, err := strconv.ParseUint(fields[8], 10, 64)
737: 		if err != nil {
738: 			return nil, fmt.Errorf("failed to parse tx bytes for %q: %w", ifName, err)
739: 		}
740: 		txPackets, err := strconv.ParseUint(fields[9], 10, 64)
741: 		if err != nil {
742: 			return nil, fmt.Errorf("failed to parse tx packets for %q: %w", ifName, err)
743: 		}
744: 
745: 		stats = append(stats, c9sIfaceStats{
746: 			Name:      ifName,
747: 			RxBytes:   rxBytes,
748: 			RxPackets: rxPackets,
749: 			TxBytes:   txBytes,
750: 			TxPackets: txPackets,
751: 		})
752: 	}
753: 
754: 	return stats, nil
755: }
756: 
757: // c9sNodeKey is the actor ID of a node: <namespace>/<lab>/<node>, the same value inspect
758: // reports as container_id.
759: func c9sNodeKey(namespace, lab, node string) string {
760: 	return namespace + "/" + lab + "/" + node
761: }
762: 
763: func c9sIfaceStatsKey(namespace, lab, node, ifName string) string {
764: 	return c9sNodeKey(namespace, lab, node) + "/" + ifName
765: }
766: 
767: func counterDelta(current, previous uint64) uint64 {
768: 	if current < previous {
769: 		return 0
770: 	}
771: 
772: 	return current - previous
773: }

(End of file - total 773 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19678bb5e001ec7n3NpxiRvcVu",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19678a805001A3Xi9IrNVARfXH",
  "callID": "call_c8bfec99bc984d63adb2732a",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/iface_stats.go"
    },
    "output": "<path>/source/head/labruntime/clabernetes/iface_stats.go</path>\n<type>file</type>\n<content>\n1: package clabernetes\n2: \n3: import (\n4: \t\"context\"\n5: \t\"fmt\"\n6: \t\"sort\"\n7: \t\"strconv\"\n8: \t\"strings\"\n9: \t\"sync\"\n10: \t\"time\"\n11: \n12: \t\"github.com/charmbracelet/log\"\n13: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n14: \tcorev1 \"k8s.io/api/core/v1\"\n15: \tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n16: )\n17: \n18: const (\n19: \t// interfaceSysfsMarker separates the /proc/net/dev counters from the sysfs interface\n20: \t// attributes in the output of interfaceSampleScript.\n21: \tinterfaceSysfsMarker = \"@@clab-sysfs\"\n22: \t// interfaceSampleScript reads the interface counters and, per interface, the sysfs\n23: \t// attributes the interface state events carry, in one exec:\n24: \t// name, ifindex, mtu, address, operstate, flags and ifalias, tab separated.\n25: \tinterfaceSampleScript = `cat /proc/net/dev; echo ` + interfaceSysfsMarker + `; ` +\n26: \t\t`for d in /sys/class/net/*; do [ -e \"$d/operstate\" ] || continue; ` +\n27: \t\t`printf '%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n' \"${d##*/}\" \"$(cat \"$d/ifindex\")\" ` +\n28: \t\t`\"$(cat \"$d/mtu\")\" \"$(cat \"$d/address\")\" \"$(cat \"$d/operstate\")\" ` +\n29: \t\t`\"$(cat \"$d/flags\")\" \"$(cat \"$d/ifalias\")\"; done 2>/dev/null`\n30: \n31: \t// interfaceSampleWorkers bounds the concurrent execs of one sampling round.\n32: \tinterfaceSampleWorkers = 16\n33: \n34: \t// managementInterface is a node's management interface in its pod, the interface the\n35: \t// clabernetes planner gives the management address by default. It has the name the\n36: \t// management interface has in a container of the local runtimes.\n37: \tmanagementInterface = \"eth0\"\n38: \t// loopbackInterface is reported like the local runtimes report it.\n39: \tloopbackInterface = \"lo\"\n40: \t// clabernetesAliasPrefix starts the interface aliases clabernetes marks its own interfaces\n41: \t// and the lab links it wires with. They are not the topology's names, so they are not\n42: \t// reported.\n43: \tclabernetesAliasPrefix = \"c9s:\"\n44: \t// zeroMAC is the hardware address sysfs reports for interfaces without one (loopback).\n45: \tzeroMAC = \"00:00:00:00:00:00\"\n46: \n47: \t// Interface event actions and link types, as the local runtimes report them.\n48: \tinterfaceActionSnapshot = \"snapshot\"\n49: \tinterfaceActionCreate   = \"create\"\n50: \tinterfaceActionUpdate   = \"update\"\n51: \tinterfaceActionDelete   = \"delete\"\n52: \tinterfaceActionStats    = \"stats\"\n53: \tinterfaceTypeVeth       = \"veth\"\n54: \tinterfaceTypeDevice     = \"device\"\n55: \n56: \t// shell exit codes of a command that cannot be found or executed.\n57: \texitCommandNotExecutable = 126\n58: \texitCommandNotFound      = 127\n59: )\n60: \n61: type interfacePollOptions struct {\n62: \tinterval            time.Duration\n63: \tincludeStats        bool\n64: \tincludeInitialState bool\n65: }\n66: \n67: type c9sIfaceStats struct {\n68: \tName      string\n69: \tRxBytes   uint64\n70: \tRxPackets uint64\n71: \tTxBytes   uint64\n72: \tTxPackets uint64\n73: }\n74: \n75: type c9sIfaceStatsSample struct {\n76: \tStats     c9sIfaceStats\n77: \tTimestamp time.Time\n78: }\n79: \n80: // c9sIfaceState is the sysfs view of one interface in a device container.\n81: type c9sIfaceState struct {\n82: \tName      string\n83: \tIndex     int\n84: \tMTU       int\n85: \tMAC       string\n86: \tOperState string\n87: \tFlags     uint64\n88: \tAlias     string\n89: }\n90: \n91: // trackedNode remembers the interfaces last reported for a node, so their changes and their\n92: // removal can be reported, also when the node stops running.\n93: type trackedNode struct {\n94: \tlab    *clablabruntime.LabState\n95: \tnode   clablabruntime.NodeState\n96: \tifaces map[string]clablabruntime.InterfaceEventData\n97: }\n98: \n99: type interfaceSampleTarget struct {\n100: \tstate *clablabruntime.LabState\n101: \tnode  clablabruntime.NodeState\n102: \tpod   *corev1.Pod\n103: }\n104: \n105: type interfaceSample struct {\n106: \ttarget    interfaceSampleTarget\n107: \tstats     []c9sIfaceStats\n108: \tifaces    []c9sIfaceState\n109: \thasStates bool\n110: \t// links are the node's lab link interfaces as clabwire lists them.\n111: \tlinks     []clabwireInterface\n112: \ttimestamp time.Time\n113: \terr       error\n114: }\n115: \n116: // podInterfaceListing is the clabwire interface listing of a pod, per node. It is listed again\n117: // when the pod's interfaces change.\n118: type podInterfaceListing struct {\n119: \tnames  string\n120: \tbyNode map[string][]clabwireInterface\n121: }\n122: \n123: // interfacePoller samples the interfaces of every running node in an event scope and turns the\n124: // samples into interface events. It reports the interfaces a container of the local runtimes\n125: // has for the same node: the node's lab link interfaces, with the names and aliases clabwire\n126: // lists for them, the management interface and loopback. The pod's own interfaces (the pod\n127: // network, clabernetes' interposition and link transport interfaces) are not reported.\n128: type interfacePoller struct {\n129: \tr     *Runtime\n130: \tscope eventScope\n131: \topts  interfacePollOptions\n132: \tsink  chan<- clablabruntime.Event\n133: \n134: \tstatsSamples map[string]c9sIfaceStatsSample\n135: \tnodes        map[string]*trackedNode\n136: \n137: \tnoShellMu sync.Mutex\n138: \t// noShell holds the pods whose device container has no shell; they are sampled with a\n139: \t// plain cat of /proc/net/dev and report statistics without interface state.\n140: \tnoShell map[string]bool\n141: \n142: \tlistingsMu sync.Mutex\n143: \t// listings holds the clabwire interface listing per pod (namespace/pod).\n144: \tlistings map[string]*podInterfaceListing\n145: \n146: \tfirstRound bool\n147: }\n148: \n149: func (r *Runtime) pollInterfaces(\n150: \tctx context.Context,\n151: \tscope eventScope,\n152: \topts interfacePollOptions,\n153: \teventSink chan<- clablabruntime.Event,\n154: ) {\n155: \tif opts.interval <= 0 {\n156: \t\topts.interval = time.Second\n157: \t}\n158: \n159: \tpoller := newInterfacePoller(r, scope, opts, eventSink)\n160: \tpoller.round(ctx)\n161: \n162: \tticker := time.NewTicker(opts.interval)\n163: \tdefer ticker.Stop()\n164: \n165: \tfor {\n166: \t\tselect {\n167: \t\tcase <-ctx.Done():\n168: \t\t\treturn\n169: \t\tcase <-ticker.C:\n170: \t\t\tpoller.round(ctx)\n171: \t\t}\n172: \t}\n173: }\n174: \n175: func newInterfacePoller(\n176: \tr *Runtime,\n177: \tscope eventScope,\n178: \topts interfacePollOptions,\n179: \teventSink chan<- clablabruntime.Event,\n180: ) *interfacePoller {\n181: \treturn &interfacePoller{\n182: \t\tr:            r,\n183: \t\tscope:        scope,\n184: \t\topts:         opts,\n185: \t\tsink:         eventSink,\n186: \t\tstatsSamples: map[string]c9sIfaceStatsSample{},\n187: \t\tnodes:        map[string]*trackedNode{},\n188: \t\tnoShell:      map[string]bool{},\n189: \t\tlistings:     map[string]*podInterfaceListing{},\n190: \t\tfirstRound:   true,\n191: \t}\n192: }\n193: \n194: func (p *interfacePoller) round(ctx context.Context) {\n195: \tdefer func() { p.firstRound = false }()\n196: \n197: \tstates, err := p.r.labStates(ctx, p.scope)\n198: \tif err != nil {\n199: \t\tlog.Debug(\"failed to list C9s labs for interface events\", \"error\", err)\n200: \t\treturn\n201: \t}\n202: \n203: \trunning := map[string]bool{}\n204: \tpods := map[string]bool{}\n205: \tvar targets []interfaceSampleTarget\n206: \tfor _, state := range states {\n207: \t\tfor _, node := range state.Nodes {\n208: \t\t\tif node.ContainerState != clablabruntime.ContainerStateRunning || node.Pod == \"\" ||\n209: \t\t\t\tnode.Container == \"\" {\n210: \t\t\t\tcontinue\n211: \t\t\t}\n212: \n213: \t\t\trunning[c9sNodeKey(state.Namespace, state.Name, node.Name)] = true\n214: \t\t\tpods[state.Namespace+\"/\"+node.Pod] = true\n215: \t\t\ttargets = append(targets, interfaceSampleTarget{\n216: \t\t\t\tstate: state,\n217: \t\t\t\tnode:  node,\n218: \t\t\t\tpod: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{\n219: \t\t\t\t\tName:      node.Pod,\n220: \t\t\t\t\tNamespace: state.Namespace,\n221: \t\t\t\t}},\n222: \t\t\t})\n223: \t\t}\n224: \t}\n225: \n226: \tfor _, sample := range p.sampleAll(ctx, targets) {\n227: \t\tif ctx.Err() != nil {\n228: \t\t\treturn\n229: \t\t}\n230: \t\tif sample.err != nil {\n231: \t\t\tlog.Debug(\"failed to sample C9s interfaces\",\n232: \t\t\t\t\"namespace\", sample.target.state.Namespace,\n233: \t\t\t\t\"lab\", sample.target.state.Name,\n234: \t\t\t\t\"node\", sample.target.node.Name,\n235: \t\t\t\t\"error\", sample.err,\n236: \t\t\t)\n237: \n238: \t\t\tcontinue\n239: \t\t}\n240: \n241: \t\tp.processSample(ctx, sample)\n242: \t}\n243: \n244: \tp.retireStoppedNodes(ctx, running)\n245: \tp.forgetListings(pods)\n246: }\n247: \n248: // retireStoppedNodes reports the interfaces of nodes that stopped running, or were removed, as\n249: // deleted: they are gone with the node's pod.\n250: func (p *interfacePoller) retireStoppedNodes(ctx context.Context, running map[string]bool) {\n251: \tfor key, tracked := range p.nodes {\n252: \t\tif running[key] {\n253: \t\t\tcontinue\n254: \t\t}\n255: \n256: \t\tfor _, name := range sortedInterfaceNames(tracked.ifaces) {\n257: \t\t\tp.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], time.Now())\n258: \t\t\tp.forgetStats(tracked, name)\n259: \t\t}\n260: \t\tdelete(p.nodes, key)\n261: \t}\n262: }\n263: \n264: // forgetListings drops the interface listings of pods that are gone.\n265: func (p *interfacePoller) forgetListings(pods map[string]bool) {\n266: \tp.listingsMu.Lock()\n267: \tdefer p.listingsMu.Unlock()\n268: \n269: \tfor key := range p.listings {\n270: \t\tif !pods[key] {\n271: \t\t\tdelete(p.listings, key)\n272: \t\t}\n273: \t}\n274: }\n275: \n276: func (p *interfacePoller) sampleAll(\n277: \tctx context.Context,\n278: \ttargets []interfaceSampleTarget,\n279: ) []interfaceSample {\n280: \tsamples := make([]interfaceSample, len(targets))\n281: \n282: \tvar wg sync.WaitGroup\n283: \tsem := make(chan struct{}, interfaceSampleWorkers)\n284: \tfor idx := range targets {\n285: \t\twg.Add(1)\n286: \t\tsem <- struct{}{}\n287: \t\tgo func(idx int) {\n288: \t\t\tdefer wg.Done()\n289: \t\t\tdefer func() { <-sem }()\n290: \n291: \t\t\tsamples[idx] = p.sample(ctx, targets[idx])\n292: \t\t}(idx)\n293: \t}\n294: \twg.Wait()\n295: \n296: \treturn samples\n297: }\n298: \n299: func (p *interfacePoller) sample(\n300: \tctx context.Context,\n301: \ttarget interfaceSampleTarget,\n302: ) interfaceSample {\n303: \tsample := interfaceSample{target: target}\n304: \tpodName := target.pod.Name\n305: \n306: \tp.noShellMu.Lock()\n307: \tnoShell := p.noShell[podName]\n308: \tp.noShellMu.Unlock()\n309: \n310: \tcommand := []string{\"sh\", \"-c\", interfaceSampleScript}\n311: \tif noShell {\n312: \t\tcommand = []string{\"cat\", \"/proc/net/dev\"}\n313: \t}\n314: \n315: \tstdout, stderr, rc, err := p.r.execInPod(ctx, target.pod, target.node.Container, command)\n316: \tif !noShell && commandNotExecutable(rc, err) {\n317: \t\tp.noShellMu.Lock()\n318: \t\tp.noShell[podName] = true\n319: \t\tp.noShellMu.Unlock()\n320: \n321: \t\tlog.Debug(\"C9s device container has no shell; reporting interface statistics only\",\n322: \t\t\t\"namespace\", target.state.Namespace,\n323: \t\t\t\"lab\", target.state.Name,\n324: \t\t\t\"node\", target.node.Name,\n325: \t\t)\n326: \n327: \t\tstdout, stderr, rc, err = p.r.execInPod(ctx, target.pod, target.node.Container,\n328: \t\t\t[]string{\"cat\", \"/proc/net/dev\"})\n329: \t}\n330: \n331: \tsample.timestamp = time.Now()\n332: \tswitch {\n333: \tcase err != nil:\n334: \t\tsample.err = err\n335: \tcase rc != 0:\n336: \t\tsample.err = fmt.Errorf(\"exit code %d: %s\", rc, strings.TrimSpace(string(stderr)))\n337: \tdefault:\n338: \t\tsample.stats, sample.ifaces, sample.hasStates, sample.err = parseInterfaceSample(stdout)\n339: \t}\n340: \tif sample.err != nil {\n341: \t\treturn sample\n342: \t}\n343: \n344: \tsample.links, sample.err = p.nodeLinks(ctx, target, sampledInterfaceNames(sample))\n345: \n346: \treturn sample\n347: }\n348: \n349: // sampledInterfaceNames lists the interface names a sample saw, sorted and comma-joined.\n350: func sampledInterfaceNames(sample interfaceSample) string {\n351: \tnames := make([]string, 0, len(sample.stats)+len(sample.ifaces))\n352: \tseen := map[string]bool{}\n353: \tfor _, iface := range sample.ifaces {\n354: \t\tif !seen[iface.Name] {\n355: \t\t\tseen[iface.Name] = true\n356: \t\t\tnames = append(names, iface.Name)\n357: \t\t}\n358: \t}\n359: \tfor _, stat := range sample.stats {\n360: \t\tif !seen[stat.Name] {\n361: \t\t\tseen[stat.Name] = true\n362: \t\t\tnames = append(names, stat.Name)\n363: \t\t}\n364: \t}\n365: \tsort.Strings(names)\n366: \n367: \treturn strings.Join(names, \",\")\n368: }\n369: \n370: // nodeLinks returns the lab link interfaces of a node from its pod's clabwire listing. A pod is\n371: // listed once, and again when its interfaces change (a pod gets its link interfaces as clabwire\n372: // wires them).\n373: func (p *interfacePoller) nodeLinks(\n374: \tctx context.Context,\n375: \ttarget interfaceSampleTarget,\n376: \tnames string,\n377: ) ([]clabwireInterface, error) {\n378: \tkey := target.pod.Namespace + \"/\" + target.pod.Name\n379: \n380: \tp.listingsMu.Lock()\n381: \tlisting := p.listings[key]\n382: \tp.listingsMu.Unlock()\n383: \n384: \tif listing == nil || listing.names != names {\n385: \t\tentries, err := p.r.listPodInterfaces(ctx, target.pod.Namespace, target.pod.Name)\n386: \t\tif err != nil {\n387: \t\t\treturn nil, err\n388: \t\t}\n389: \n390: \t\tlisting = &podInterfaceListing{\n391: \t\t\tnames:  names,\n392: \t\t\tbyNode: map[string][]clabwireInterface{},\n393: \t\t}\n394: \t\tfor _, entry := range entries {\n395: \t\t\tlisting.byNode[entry.Node] = append(listing.byNode[entry.Node], entry)\n396: \t\t}\n397: \n398: \t\tp.listingsMu.Lock()\n399: \t\tp.listings[key] = listing\n400: \t\tp.listingsMu.Unlock()\n401: \t}\n402: \n403: \treturn listing.byNode[target.node.Name], nil\n404: }\n405: \n406: // commandNotExecutable reports an exec that failed because the command does not exist in the\n407: // container.\n408: func commandNotExecutable(rc int, err error) bool {\n409: \tif rc == exitCommandNotExecutable || rc == exitCommandNotFound {\n410: \t\treturn true\n411: \t}\n412: \n413: \treturn err != nil && strings.Contains(err.Error(), \"executable file not found\")\n414: }\n415: \n416: // reportedInterfaces are the interfaces reported for a node, by name, with the alias the\n417: // topology gave them: its lab link interfaces, the management interface and loopback.\n418: func reportedInterfaces(links []clabwireInterface) map[string]string {\n419: \treported := map[string]string{\n420: \t\tloopbackInterface:   \"\",\n421: \t\tmanagementInterface: \"\",\n422: \t}\n423: \tfor _, link := range links {\n424: \t\treported[link.Interface] = link.Alias\n425: \t}\n426: \n427: \treturn reported\n428: }\n429: \n430: // interfaceEventData describes an interface the way the local runtimes' netlink events do: the\n431: // alias is the topology's name for the interface (an alias clabernetes set for its own use is\n432: // not reported), the operational state uses netlink's names, lab link and management\n433: // interfaces are veth pairs, loopback a device, and loopback has no hardware address.\n434: func interfaceEventData(iface c9sIfaceState, alias string) clablabruntime.InterfaceEventData {\n435: \tif alias == \"\" && !strings.HasPrefix(iface.Alias, clabernetesAliasPrefix) {\n436: \t\talias = iface.Alias\n437: \t}\n438: \n439: \tmac := iface.MAC\n440: \tif mac == zeroMAC {\n441: \t\tmac = \"\"\n442: \t}\n443: \n444: \tlinkType := interfaceTypeVeth\n445: \tif iface.Name == loopbackInterface {\n446: \t\tlinkType = interfaceTypeDevice\n447: \t}\n448: \n449: \treturn clablabruntime.InterfaceEventData{\n450: \t\tName:      iface.Name,\n451: \t\tAlias:     alias,\n452: \t\tIndex:     iface.Index,\n453: \t\tMTU:       iface.MTU,\n454: \t\tMAC:       mac,\n455: \t\tOperState: netlinkOperState(iface.OperState),\n456: \t\tType:      linkType,\n457: \t}\n458: }\n459: \n460: // netlinkOperState names an operational state from sysfs (RFC 2863, as in\n461: // /sys/class/net/<if>/operstate) the way netlink, and so the local runtimes' events, name it.\n462: func netlinkOperState(operState string) string {\n463: \tswitch operState {\n464: \tcase \"notpresent\":\n465: \t\treturn \"not-present\"\n466: \tcase \"lowerlayerdown\":\n467: \t\treturn \"lower-layer-down\"\n468: \tcase \"\":\n469: \t\treturn \"unknown\"\n470: \tdefault:\n471: \t\treturn operState\n472: \t}\n473: }\n474: \n475: func (p *interfacePoller) processSample(ctx context.Context, sample interfaceSample) {\n476: \tstate := sample.target.state\n477: \tnode := sample.target.node\n478: \tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n479: \n480: \ttracked, known := p.nodes[key]\n481: \tif !known {\n482: \t\ttracked = &trackedNode{ifaces: map[string]clablabruntime.InterfaceEventData{}}\n483: \t\tp.nodes[key] = tracked\n484: \t}\n485: \ttracked.lab = state\n486: \ttracked.node = node\n487: \n488: \treported := reportedInterfaces(sample.links)\n489: \n490: \tif sample.hasStates {\n491: \t\tp.processStates(ctx, tracked, reported, sample)\n492: \t}\n493: \n494: \tif !p.opts.includeStats {\n495: \t\treturn\n496: \t}\n497: \tfor _, stat := range sample.stats {\n498: \t\talias, ok := reported[stat.Name]\n499: \t\tif !ok {\n500: \t\t\tcontinue\n501: \t\t}\n502: \n503: \t\tstatsKey := c9sIfaceStatsKey(state.Namespace, state.Name, node.Name, stat.Name)\n504: \t\tcurrent := c9sIfaceStatsSample{Stats: stat, Timestamp: sample.timestamp}\n505: \t\tif previous, ok := p.statsSamples[statsKey]; ok {\n506: \t\t\tdata, ok := tracked.ifaces[stat.Name]\n507: \t\t\tif !ok {\n508: \t\t\t\tdata = interfaceEventData(c9sIfaceState{Name: stat.Name}, alias)\n509: \t\t\t\tdata.OperState = \"\"\n510: \t\t\t}\n511: \t\t\tdata.Stats = c9sIfaceStatsData(previous, current)\n512: \t\t\tp.emit(ctx, tracked, interfaceActionStats, data, current.Timestamp)\n513: \t\t}\n514: \n515: \t\tp.statsSamples[statsKey] = current\n516: \t}\n517: }\n518: \n519: // processStates reports the interfaces that appeared (snapshot in the first round with\n520: // --initial-state, create later), changed (update) or disappeared (delete) since the last\n521: // sample, like the netlink events of the local runtimes.\n522: func (p *interfacePoller) processStates(\n523: \tctx context.Context,\n524: \ttracked *trackedNode,\n525: \treported map[string]string,\n526: \tsample interfaceSample,\n527: ) {\n528: \tpresent := map[string]bool{}\n529: \tfor _, iface := range sample.ifaces {\n530: \t\talias, ok := reported[iface.Name]\n531: \t\tif !ok {\n532: \t\t\tcontinue\n533: \t\t}\n534: \n535: \t\tdata := interfaceEventData(iface, alias)\n536: \t\tpresent[iface.Name] = true\n537: \t\tprevious, seen := tracked.ifaces[iface.Name]\n538: \t\ttracked.ifaces[iface.Name] = data\n539: \n540: \t\tswitch {\n541: \t\tcase seen && previous == data:\n542: \t\tcase !seen && p.firstRound:\n543: \t\t\t// Interfaces that exist when the stream starts are only reported with\n544: \t\t\t// --initial-state; later changes are always reported.\n545: \t\t\tif p.opts.includeInitialState {\n546: \t\t\t\tp.emit(ctx, tracked, interfaceActionSnapshot, data, sample.timestamp)\n547: \t\t\t}\n548: \t\tcase !seen:\n549: \t\t\tp.emit(ctx, tracked, interfaceActionCreate, data, sample.timestamp)\n550: \t\tdefault:\n551: \t\t\tp.emit(ctx, tracked, interfaceActionUpdate, data, sample.timestamp)\n552: \t\t}\n553: \t}\n554: \n555: \tfor _, name := range sortedInterfaceNames(tracked.ifaces) {\n556: \t\tif present[name] {\n557: \t\t\tcontinue\n558: \t\t}\n559: \n560: \t\tp.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], sample.timestamp)\n561: \t\tp.forgetStats(tracked, name)\n562: \t\tdelete(tracked.ifaces, name)\n563: \t}\n564: }\n565: \n566: func sortedInterfaceNames(ifaces map[string]clablabruntime.InterfaceEventData) []string {\n567: \tnames := make([]string, 0, len(ifaces))\n568: \tfor name := range ifaces {\n569: \t\tnames = append(names, name)\n570: \t}\n571: \tsort.Strings(names)\n572: \n573: \treturn names\n574: }\n575: \n576: func (p *interfacePoller) forgetStats(tracked *trackedNode, ifName string) {\n577: \tdelete(p.statsSamples,\n578: \t\tc9sIfaceStatsKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name, ifName))\n579: }\n580: \n581: func (p *interfacePoller) emit(\n582: \tctx context.Context,\n583: \ttracked *trackedNode,\n584: \taction string,\n585: \tdata clablabruntime.InterfaceEventData,\n586: \ttimestamp time.Time,\n587: ) {\n588: \tp.r.sendEvent(ctx, p.sink, c9sInterfaceEvent(tracked, action, data, timestamp))\n589: }\n590: \n591: // c9sInterfaceEvent is an interface event of a node. The actor is the node, as for its container\n592: // events. The interface itself is in Interface; the events command reports it with the\n593: // attributes of the local runtimes' interface events.\n594: func c9sInterfaceEvent(\n595: \ttracked *trackedNode,\n596: \taction string,\n597: \tdata clablabruntime.InterfaceEventData,\n598: \ttimestamp time.Time,\n599: ) clablabruntime.Event {\n600: \tkey := c9sNodeKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name)\n601: \n602: \tattributes := map[string]string{\n603: \t\t\"namespace\": tracked.lab.Namespace,\n604: \t\t\"lab\":       tracked.lab.Name,\n605: \t\t\"node\":      tracked.node.Name,\n606: \t\t\"origin\":    clabernetesAppValue,\n607: \t}\n608: \tif tracked.node.Pod != \"\" {\n609: \t\tattributes[\"pod\"] = tracked.node.Pod\n610: \t}\n611: \n612: \tnode := tracked.node\n613: \n614: \treturn clablabruntime.Event{\n615: \t\tTimestamp:   timestamp,\n616: \t\tType:        clablabruntime.EventTypeInterface,\n617: \t\tAction:      action,\n618: \t\tActorID:     key,\n619: \t\tActorName:   fmt.Sprintf(\"%s-%s\", tracked.lab.Name, tracked.node.Name),\n620: \t\tActorFullID: key,\n621: \t\tAttributes:  attributes,\n622: \t\tLab:         tracked.lab,\n623: \t\tNode:        &node,\n624: \t\tInterface:   &data,\n625: \t}\n626: }\n627: \n628: // c9sIfaceStatsData computes the counters and rates of a stats event from two samples.\n629: func c9sIfaceStatsData(previous, current c9sIfaceStatsSample) *clablabruntime.InterfaceStats {\n630: \tinterval := current.Timestamp.Sub(previous.Timestamp)\n631: \tif interval <= 0 {\n632: \t\tinterval = time.Second\n633: \t}\n634: \n635: \tseconds := interval.Seconds()\n636: \tstat := current.Stats\n637: \n638: \treturn &clablabruntime.InterfaceStats{\n639: \t\tRxBytes:   stat.RxBytes,\n640: \t\tTxBytes:   stat.TxBytes,\n641: \t\tRxPackets: stat.RxPackets,\n642: \t\tTxPackets: stat.TxPackets,\n643: \t\tRxBps:     float64(counterDelta(stat.RxBytes, previous.Stats.RxBytes)*8) / seconds,\n644: \t\tTxBps:     float64(counterDelta(stat.TxBytes, previous.Stats.TxBytes)*8) / seconds,\n645: \t\tRxPps:     float64(counterDelta(stat.RxPackets, previous.Stats.RxPackets)) / seconds,\n646: \t\tTxPps:     float64(counterDelta(stat.TxPackets, previous.Stats.TxPackets)) / seconds,\n647: \t\tInterval:  interval,\n648: \t}\n649: }\n650: \n651: // parseInterfaceSample splits the output of interfaceSampleScript into the /proc/net/dev\n652: // counters and the sysfs interface states. hasStates is false for output without the sysfs\n653: // section, such as a plain cat of /proc/net/dev.\n654: func parseInterfaceSample(data []byte) ([]c9sIfaceStats, []c9sIfaceState, bool, error) {\n655: \ttext := string(data)\n656: \n657: \tprocPart, sysfsPart, hasStates := strings.Cut(text, interfaceSysfsMarker+\"\\n\")\n658: \tif !hasStates {\n659: \t\tprocPart, _, hasStates = strings.Cut(text, interfaceSysfsMarker)\n660: \t}\n661: \n662: \tstats, err := parseProcNetDev([]byte(procPart))\n663: \tif err != nil {\n664: \t\treturn nil, nil, false, err\n665: \t}\n666: \tif !hasStates {\n667: \t\treturn stats, nil, false, nil\n668: \t}\n669: \n670: \treturn stats, parseSysfsInterfaces(sysfsPart), true, nil\n671: }\n672: \n673: func parseSysfsInterfaces(data string) []c9sIfaceState {\n674: \tlines := strings.Split(data, \"\\n\")\n675: \tstates := make([]c9sIfaceState, 0, len(lines))\n676: \n677: \tfor _, line := range lines {\n678: \t\tfields := strings.SplitN(line, \"\\t\", 7) //nolint:mnd\n679: \t\tif len(fields) < 5 || strings.TrimSpace(fields[0]) == \"\" {\n680: \t\t\tcontinue\n681: \t\t}\n682: \n683: \t\tstate := c9sIfaceState{\n684: \t\t\tName:      strings.TrimSpace(fields[0]),\n685: \t\t\tMAC:       strings.TrimSpace(fields[3]),\n686: \t\t\tOperState: strings.ToLower(strings.TrimSpace(fields[4])),\n687: \t\t}\n688: \t\tstate.Index, _ = strconv.Atoi(strings.TrimSpace(fields[1]))\n689: \t\tstate.MTU, _ = strconv.Atoi(strings.TrimSpace(fields[2]))\n690: \t\tif len(fields) > 5 {\n691: \t\t\tstate.Flags, _ = strconv.ParseUint(\n692: \t\t\t\tstrings.TrimPrefix(strings.TrimSpace(fields[5]), \"0x\"), 16, 64)\n693: \t\t}\n694: \t\tif len(fields) > 6 {\n695: \t\t\tstate.Alias = strings.TrimSpace(fields[6])\n696: \t\t}\n697: \t\tif state.OperState == \"\" {\n698: \t\t\tstate.OperState = \"unknown\"\n699: \t\t}\n700: \n701: \t\tstates = append(states, state)\n702: \t}\n703: \n704: \treturn states\n705: }\n706: \n707: func parseProcNetDev(data []byte) ([]c9sIfaceStats, error) {\n708: \tlines := strings.Split(string(data), \"\\n\")\n709: \tstats := make([]c9sIfaceStats, 0, len(lines))\n710: \n711: \tfor _, line := range lines {\n712: \t\tline = strings.TrimSpace(line)\n713: \t\tif line == \"\" || !strings.Contains(line, \":\") {\n714: \t\t\tcontinue\n715: \t\t}\n716: \n717: \t\tparts := strings.SplitN(line, \":\", 2)\n718: \t\tif len(parts) != 2 {\n719: \t\t\tcontinue\n720: \t\t}\n721: \n722: \t\tifName := strings.TrimSpace(parts[0])\n723: \t\tfields := strings.Fields(parts[1])\n724: \t\tif len(fields) < 16 {\n725: \t\t\treturn nil, fmt.Errorf(\"unexpected /proc/net/dev line for %q: %q\", ifName, line)\n726: \t\t}\n727: \n728: \t\trxBytes, err := strconv.ParseUint(fields[0], 10, 64)\n729: \t\tif err != nil {\n730: \t\t\treturn nil, fmt.Errorf(\"failed to parse rx bytes for %q: %w\", ifName, err)\n731: \t\t}\n732: \t\trxPackets, err := strconv.ParseUint(fields[1], 10, 64)\n733: \t\tif err != nil {\n734: \t\t\treturn nil, fmt.Errorf(\"failed to parse rx packets for %q: %w\", ifName, err)\n735: \t\t}\n736: \t\ttxBytes, err := strconv.ParseUint(fields[8], 10, 64)\n737: \t\tif err != nil {\n738: \t\t\treturn nil, fmt.Errorf(\"failed to parse tx bytes for %q: %w\", ifName, err)\n739: \t\t}\n740: \t\ttxPackets, err := strconv.ParseUint(fields[9], 10, 64)\n741: \t\tif err != nil {\n742: \t\t\treturn nil, fmt.Errorf(\"failed to parse tx packets for %q: %w\", ifName, err)\n743: \t\t}\n744: \n745: \t\tstats = append(stats, c9sIfaceStats{\n746: \t\t\tName:      ifName,\n747: \t\t\tRxBytes:   rxBytes,\n748: \t\t\tRxPackets: rxPackets,\n749: \t\t\tTxBytes:   txBytes,\n750: \t\t\tTxPackets: txPackets,\n751: \t\t})\n752: \t}\n753: \n754: \treturn stats, nil\n755: }\n756: \n757: // c9sNodeKey is the actor ID of a node: <namespace>/<lab>/<node>, the same value inspect\n758: // reports as container_id.\n759: func c9sNodeKey(namespace, lab, node string) string {\n760: \treturn namespace + \"/\" + lab + \"/\" + node\n761: }\n762: \n763: func c9sIfaceStatsKey(namespace, lab, node, ifName string) string {\n764: \treturn c9sNodeKey(namespace, lab, node) + \"/\" + ifName\n765: }\n766: \n767: func counterDelta(current, previous uint64) uint64 {\n768: \tif current < previous {\n769: \t\treturn 0\n770: \t}\n771: \n772: \treturn current - previous\n773: }\n\n(End of file - total 773 lines)\n</content>",
    "title": "source/head/labruntime/clabernetes/iface_stats.go",
    "metadata": {
      "preview": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\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)\n\nconst (\n\t// interfaceSysfsMarker separates the /proc/net/dev counters from the sysfs interface\n\t// attributes in the output of interfaceSampleScript.",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/iface_stats.go",
        "text": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\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)\n\nconst (\n\t// interfaceSysfsMarker separates the /proc/net/dev counters from the sysfs interface\n\t// attributes in the output of interfaceSampleScript.\n\tinterfaceSysfsMarker = \"@@clab-sysfs\"\n\t// interfaceSampleScript reads the interface counters and, per interface, the sysfs\n\t// attributes the interface state events carry, in one exec:\n\t// name, ifindex, mtu, address, operstate, flags and ifalias, tab separated.\n\tinterfaceSampleScript = `cat /proc/net/dev; echo ` + interfaceSysfsMarker + `; ` +\n\t\t`for d in /sys/class/net/*; do [ -e \"$d/operstate\" ] || continue; ` +\n\t\t`printf '%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n' \"${d##*/}\" \"$(cat \"$d/ifindex\")\" ` +\n\t\t`\"$(cat \"$d/mtu\")\" \"$(cat \"$d/address\")\" \"$(cat \"$d/operstate\")\" ` +\n\t\t`\"$(cat \"$d/flags\")\" \"$(cat \"$d/ifalias\")\"; done 2>/dev/null`\n\n\t// interfaceSampleWorkers bounds the concurrent execs of one sampling round.\n\tinterfaceSampleWorkers = 16\n\n\t// managementInterface is a node's management interface in its pod, the interface the\n\t// clabernetes planner gives the management address by default. It has the name the\n\t// management interface has in a container of the local runtimes.\n\tmanagementInterface = \"eth0\"\n\t// loopbackInterface is reported like the local runtimes report it.\n\tloopbackInterface = \"lo\"\n\t// clabernetesAliasPrefix starts the interface aliases clabernetes marks its own interfaces\n\t// and the lab links it wires with. They are not the topology's names, so they are not\n\t// reported.\n\tclabernetesAliasPrefix = \"c9s:\"\n\t// zeroMAC is the hardware address sysfs reports for interfaces without one (loopback).\n\tzeroMAC = \"00:00:00:00:00:00\"\n\n\t// Interface event actions and link types, as the local runtimes report them.\n\tinterfaceActionSnapshot = \"snapshot\"\n\tinterfaceActionCreate   = \"create\"\n\tinterfaceActionUpdate   = \"update\"\n\tinterfaceActionDelete   = \"delete\"\n\tinterfaceActionStats    = \"stats\"\n\tinterfaceTypeVeth       = \"veth\"\n\tinterfaceTypeDevice     = \"device\"\n\n\t// shell exit codes of a command that cannot be found or executed.\n\texitCommandNotExecutable = 126\n\texitCommandNotFound      = 127\n)\n\ntype interfacePollOptions struct {\n\tinterval            time.Duration\n\tincludeStats        bool\n\tincludeInitialState bool\n}\n\ntype c9sIfaceStats struct {\n\tName      string\n\tRxBytes   uint64\n\tRxPackets uint64\n\tTxBytes   uint64\n\tTxPackets uint64\n}\n\ntype c9sIfaceStatsSample struct {\n\tStats     c9sIfaceStats\n\tTimestamp time.Time\n}\n\n// c9sIfaceState is the sysfs view of one interface in a device container.\ntype c9sIfaceState struct {\n\tName      string\n\tIndex     int\n\tMTU       int\n\tMAC       string\n\tOperState string\n\tFlags     uint64\n\tAlias     string\n}\n\n// trackedNode remembers the interfaces last reported for a node, so their changes and their\n// removal can be reported, also when the node stops running.\ntype trackedNode struct {\n\tlab    *clablabruntime.LabState\n\tnode   clablabruntime.NodeState\n\tifaces map[string]clablabruntime.InterfaceEventData\n}\n\ntype interfaceSampleTarget struct {\n\tstate *clablabruntime.LabState\n\tnode  clablabruntime.NodeState\n\tpod   *corev1.Pod\n}\n\ntype interfaceSample struct {\n\ttarget    interfaceSampleTarget\n\tstats     []c9sIfaceStats\n\tifaces    []c9sIfaceState\n\thasStates bool\n\t// links are the node's lab link interfaces as clabwire lists them.\n\tlinks     []clabwireInterface\n\ttimestamp time.Time\n\terr       error\n}\n\n// podInterfaceListing is the clabwire interface listing of a pod, per node. It is listed again\n// when the pod's interfaces change.\ntype podInterfaceListing struct {\n\tnames  string\n\tbyNode map[string][]clabwireInterface\n}\n\n// interfacePoller samples the interfaces of every running node in an event scope and turns the\n// samples into interface events. It reports the interfaces a container of the local runtimes\n// has for the same node: the node's lab link interfaces, with the names and aliases clabwire\n// lists for them, the management interface and loopback. The pod's own interfaces (the pod\n// network, clabernetes' interposition and link transport interfaces) are not reported.\ntype interfacePoller struct {\n\tr     *Runtime\n\tscope eventScope\n\topts  interfacePollOptions\n\tsink  chan<- clablabruntime.Event\n\n\tstatsSamples map[string]c9sIfaceStatsSample\n\tnodes        map[string]*trackedNode\n\n\tnoShellMu sync.Mutex\n\t// noShell holds the pods whose device container has no shell; they are sampled with a\n\t// plain cat of /proc/net/dev and report statistics without interface state.\n\tnoShell map[string]bool\n\n\tlistingsMu sync.Mutex\n\t// listings holds the clabwire interface listing per pod (namespace/pod).\n\tlistings map[string]*podInterfaceListing\n\n\tfirstRound bool\n}\n\nfunc (r *Runtime) pollInterfaces(\n\tctx context.Context,\n\tscope eventScope,\n\topts interfacePollOptions,\n\teventSink chan<- clablabruntime.Event,\n) {\n\tif opts.interval <= 0 {\n\t\topts.interval = time.Second\n\t}\n\n\tpoller := newInterfacePoller(r, scope, opts, eventSink)\n\tpoller.round(ctx)\n\n\tticker := time.NewTicker(opts.interval)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tpoller.round(ctx)\n\t\t}\n\t}\n}\n\nfunc newInterfacePoller(\n\tr *Runtime,\n\tscope eventScope,\n\topts interfacePollOptions,\n\teventSink chan<- clablabruntime.Event,\n) *interfacePoller {\n\treturn &interfacePoller{\n\t\tr:            r,\n\t\tscope:        scope,\n\t\topts:         opts,\n\t\tsink:         eventSink,\n\t\tstatsSamples: map[string]c9sIfaceStatsSample{},\n\t\tnodes:        map[string]*trackedNode{},\n\t\tnoShell:      map[string]bool{},\n\t\tlistings:     map[string]*podInterfaceListing{},\n\t\tfirstRound:   true,\n\t}\n}\n\nfunc (p *interfacePoller) round(ctx context.Context) {\n\tdefer func() { p.firstRound = false }()\n\n\tstates, err := p.r.labStates(ctx, p.scope)\n\tif err != nil {\n\t\tlog.Debug(\"failed to list C9s labs for interface events\", \"error\", err)\n\t\treturn\n\t}\n\n\trunning := map[string]bool{}\n\tpods := map[string]bool{}\n\tvar targets []interfaceSampleTarget\n\tfor _, state := range states {\n\t\tfor _, node := range state.Nodes {\n\t\t\tif node.ContainerState != clablabruntime.ContainerStateRunning || node.Pod == \"\" ||\n\t\t\t\tnode.Container == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trunning[c9sNodeKey(state.Namespace, state.Name, node.Name)] = true\n\t\t\tpods[state.Namespace+\"/\"+node.Pod] = true\n\t\t\ttargets = append(targets, interfaceSampleTarget{\n\t\t\t\tstate: state,\n\t\t\t\tnode:  node,\n\t\t\t\tpod: &corev1.Pod{ObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName:      node.Pod,\n\t\t\t\t\tNamespace: state.Namespace,\n\t\t\t\t}},\n\t\t\t})\n\t\t}\n\t}\n\n\tfor _, sample := range p.sampleAll(ctx, targets) {\n\t\tif ctx.Err() != nil {\n\t\t\treturn\n\t\t}\n\t\tif sample.err != nil {\n\t\t\tlog.Debug(\"failed to sample C9s interfaces\",\n\t\t\t\t\"namespace\", sample.target.state.Namespace,\n\t\t\t\t\"lab\", sample.target.state.Name,\n\t\t\t\t\"node\", sample.target.node.Name,\n\t\t\t\t\"error\", sample.err,\n\t\t\t)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tp.processSample(ctx, sample)\n\t}\n\n\tp.retireStoppedNodes(ctx, running)\n\tp.forgetListings(pods)\n}\n\n// retireStoppedNodes reports the interfaces of nodes that stopped running, or were removed, as\n// deleted: they are gone with the node's pod.\nfunc (p *interfacePoller) retireStoppedNodes(ctx context.Context, running map[string]bool) {\n\tfor key, tracked := range p.nodes {\n\t\tif running[key] {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, name := range sortedInterfaceNames(tracked.ifaces) {\n\t\t\tp.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], time.Now())\n\t\t\tp.forgetStats(tracked, name)\n\t\t}\n\t\tdelete(p.nodes, key)\n\t}\n}\n\n// forgetListings drops the interface listings of pods that are gone.\nfunc (p *interfacePoller) forgetListings(pods map[string]bool) {\n\tp.listingsMu.Lock()\n\tdefer p.listingsMu.Unlock()\n\n\tfor key := range p.listings {\n\t\tif !pods[key] {\n\t\t\tdelete(p.listings, key)\n\t\t}\n\t}\n}\n\nfunc (p *interfacePoller) sampleAll(\n\tctx context.Context,\n\ttargets []interfaceSampleTarget,\n) []interfaceSample {\n\tsamples := make([]interfaceSample, len(targets))\n\n\tvar wg sync.WaitGroup\n\tsem := make(chan struct{}, interfaceSampleWorkers)\n\tfor idx := range targets {\n\t\twg.Add(1)\n\t\tsem <- struct{}{}\n\t\tgo func(idx int) {\n\t\t\tdefer wg.Done()\n\t\t\tdefer func() { <-sem }()\n\n\t\t\tsamples[idx] = p.sample(ctx, targets[idx])\n\t\t}(idx)\n\t}\n\twg.Wait()\n\n\treturn samples\n}\n\nfunc (p *interfacePoller) sample(\n\tctx context.Context,\n\ttarget interfaceSampleTarget,\n) interfaceSample {\n\tsample := interfaceSample{target: target}\n\tpodName := target.pod.Name\n\n\tp.noShellMu.Lock()\n\tnoShell := p.noShell[podName]\n\tp.noShellMu.Unlock()\n\n\tcommand := []string{\"sh\", \"-c\", interfaceSampleScript}\n\tif noShell {\n\t\tcommand = []string{\"cat\", \"/proc/net/dev\"}\n\t}\n\n\tstdout, stderr, rc, err := p.r.execInPod(ctx, target.pod, target.node.Container, command)\n\tif !noShell && commandNotExecutable(rc, err) {\n\t\tp.noShellMu.Lock()\n\t\tp.noShell[podName] = true\n\t\tp.noShellMu.Unlock()\n\n\t\tlog.Debug(\"C9s device container has no shell; reporting interface statistics only\",\n\t\t\t\"namespace\", target.state.Namespace,\n\t\t\t\"lab\", target.state.Name,\n\t\t\t\"node\", target.node.Name,\n\t\t)\n\n\t\tstdout, stderr, rc, err = p.r.execInPod(ctx, target.pod, target.node.Container,\n\t\t\t[]string{\"cat\", \"/proc/net/dev\"})\n\t}\n\n\tsample.timestamp = time.Now()\n\tswitch {\n\tcase err != nil:\n\t\tsample.err = err\n\tcase rc != 0:\n\t\tsample.err = fmt.Errorf(\"exit code %d: %s\", rc, strings.TrimSpace(string(stderr)))\n\tdefault:\n\t\tsample.stats, sample.ifaces, sample.hasStates, sample.err = parseInterfaceSample(stdout)\n\t}\n\tif sample.err != nil {\n\t\treturn sample\n\t}\n\n\tsample.links, sample.err = p.nodeLinks(ctx, target, sampledInterfaceNames(sample))\n\n\treturn sample\n}\n\n// sampledInterfaceNames lists the interface names a sample saw, sorted and comma-joined.\nfunc sampledInterfaceNames(sample interfaceSample) string {\n\tnames := make([]string, 0, len(sample.stats)+len(sample.ifaces))\n\tseen := map[string]bool{}\n\tfor _, iface := range sample.ifaces {\n\t\tif !seen[iface.Name] {\n\t\t\tseen[iface.Name] = true\n\t\t\tnames = append(names, iface.Name)\n\t\t}\n\t}\n\tfor _, stat := range sample.stats {\n\t\tif !seen[stat.Name] {\n\t\t\tseen[stat.Name] = true\n\t\t\tnames = append(names, stat.Name)\n\t\t}\n\t}\n\tsort.Strings(names)\n\n\treturn strings.Join(names, \",\")\n}\n\n// nodeLinks returns the lab link interfaces of a node from its pod's clabwire listing. A pod is\n// listed once, and again when its interfaces change (a pod gets its link interfaces as clabwire\n// wires them).\nfunc (p *interfacePoller) nodeLinks(\n\tctx context.Context,\n\ttarget interfaceSampleTarget,\n\tnames string,\n) ([]clabwireInterface, error) {\n\tkey := target.pod.Namespace + \"/\" + target.pod.Name\n\n\tp.listingsMu.Lock()\n\tlisting := p.listings[key]\n\tp.listingsMu.Unlock()\n\n\tif listing == nil || listing.names != names {\n\t\tentries, err := p.r.listPodInterfaces(ctx, target.pod.Namespace, target.pod.Name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlisting = &podInterfaceListing{\n\t\t\tnames:  names,\n\t\t\tbyNode: map[string][]clabwireInterface{},\n\t\t}\n\t\tfor _, entry := range entries {\n\t\t\tlisting.byNode[entry.Node] = append(listing.byNode[entry.Node], entry)\n\t\t}\n\n\t\tp.listingsMu.Lock()\n\t\tp.listings[key] = listing\n\t\tp.listingsMu.Unlock()\n\t}\n\n\treturn listing.byNode[target.node.Name], nil\n}\n\n// commandNotExecutable reports an exec that failed because the command does not exist in the\n// container.\nfunc commandNotExecutable(rc int, err error) bool {\n\tif rc == exitCommandNotExecutable || rc == exitCommandNotFound {\n\t\treturn true\n\t}\n\n\treturn err != nil && strings.Contains(err.Error(), \"executable file not found\")\n}\n\n// reportedInterfaces are the interfaces reported for a node, by name, with the alias the\n// topology gave them: its lab link interfaces, the management interface and loopback.\nfunc reportedInterfaces(links []clabwireInterface) map[string]string {\n\treported := map[string]string{\n\t\tloopbackInterface:   \"\",\n\t\tmanagementInterface: \"\",\n\t}\n\tfor _, link := range links {\n\t\treported[link.Interface] = link.Alias\n\t}\n\n\treturn reported\n}\n\n// interfaceEventData describes an interface the way the local runtimes' netlink events do: the\n// alias is the topology's name for the interface (an alias clabernetes set for its own use is\n// not reported), the operational state uses netlink's names, lab link and management\n// interfaces are veth pairs, loopback a device, and loopback has no hardware address.\nfunc interfaceEventData(iface c9sIfaceState, alias string) clablabruntime.InterfaceEventData {\n\tif alias == \"\" && !strings.HasPrefix(iface.Alias, clabernetesAliasPrefix) {\n\t\talias = iface.Alias\n\t}\n\n\tmac := iface.MAC\n\tif mac == zeroMAC {\n\t\tmac = \"\"\n\t}\n\n\tlinkType := interfaceTypeVeth\n\tif iface.Name == loopbackInterface {\n\t\tlinkType = interfaceTypeDevice\n\t}\n\n\treturn clablabruntime.InterfaceEventData{\n\t\tName:      iface.Name,\n\t\tAlias:     alias,\n\t\tIndex:     iface.Index,\n\t\tMTU:       iface.MTU,\n\t\tMAC:       mac,\n\t\tOperState: netlinkOperState(iface.OperState),\n\t\tType:      linkType,\n\t}\n}\n\n// netlinkOperState names an operational state from sysfs (RFC 2863, as in\n// /sys/class/net/<if>/operstate) the way netlink, and so the local runtimes' events, name it.\nfunc netlinkOperState(operState string) string {\n\tswitch operState {\n\tcase \"notpresent\":\n\t\treturn \"not-present\"\n\tcase \"lowerlayerdown\":\n\t\treturn \"lower-layer-down\"\n\tcase \"\":\n\t\treturn \"unknown\"\n\tdefault:\n\t\treturn operState\n\t}\n}\n\nfunc (p *interfacePoller) processSample(ctx context.Context, sample interfaceSample) {\n\tstate := sample.target.state\n\tnode := sample.target.node\n\tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n\n\ttracked, known := p.nodes[key]\n\tif !known {\n\t\ttracked = &trackedNode{ifaces: map[string]clablabruntime.InterfaceEventData{}}\n\t\tp.nodes[key] = tracked\n\t}\n\ttracked.lab = state\n\ttracked.node = node\n\n\treported := reportedInterfaces(sample.links)\n\n\tif sample.hasStates {\n\t\tp.processStates(ctx, tracked, reported, sample)\n\t}\n\n\tif !p.opts.includeStats {\n\t\treturn\n\t}\n\tfor _, stat := range sample.stats {\n\t\talias, ok := reported[stat.Name]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tstatsKey := c9sIfaceStatsKey(state.Namespace, state.Name, node.Name, stat.Name)\n\t\tcurrent := c9sIfaceStatsSample{Stats: stat, Timestamp: sample.timestamp}\n\t\tif previous, ok := p.statsSamples[statsKey]; ok {\n\t\t\tdata, ok := tracked.ifaces[stat.Name]\n\t\t\tif !ok {\n\t\t\t\tdata = interfaceEventData(c9sIfaceState{Name: stat.Name}, alias)\n\t\t\t\tdata.OperState = \"\"\n\t\t\t}\n\t\t\tdata.Stats = c9sIfaceStatsData(previous, current)\n\t\t\tp.emit(ctx, tracked, interfaceActionStats, data, current.Timestamp)\n\t\t}\n\n\t\tp.statsSamples[statsKey] = current\n\t}\n}\n\n// processStates reports the interfaces that appeared (snapshot in the first round with\n// --initial-state, create later), changed (update) or disappeared (delete) since the last\n// sample, like the netlink events of the local runtimes.\nfunc (p *interfacePoller) processStates(\n\tctx context.Context,\n\ttracked *trackedNode,\n\treported map[string]string,\n\tsample interfaceSample,\n) {\n\tpresent := map[string]bool{}\n\tfor _, iface := range sample.ifaces {\n\t\talias, ok := reported[iface.Name]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tdata := interfaceEventData(iface, alias)\n\t\tpresent[iface.Name] = true\n\t\tprevious, seen := tracked.ifaces[iface.Name]\n\t\ttracked.ifaces[iface.Name] = data\n\n\t\tswitch {\n\t\tcase seen && previous == data:\n\t\tcase !seen && p.firstRound:\n\t\t\t// Interfaces that exist when the stream starts are only reported with\n\t\t\t// --initial-state; later changes are always reported.\n\t\t\tif p.opts.includeInitialState {\n\t\t\t\tp.emit(ctx, tracked, interfaceActionSnapshot, data, sample.timestamp)\n\t\t\t}\n\t\tcase !seen:\n\t\t\tp.emit(ctx, tracked, interfaceActionCreate, data, sample.timestamp)\n\t\tdefault:\n\t\t\tp.emit(ctx, tracked, interfaceActionUpdate, data, sample.timestamp)\n\t\t}\n\t}\n\n\tfor _, name := range sortedInterfaceNames(tracked.ifaces) {\n\t\tif present[name] {\n\t\t\tcontinue\n\t\t}\n\n\t\tp.emit(ctx, tracked, interfaceActionDelete, tracked.ifaces[name], sample.timestamp)\n\t\tp.forgetStats(tracked, name)\n\t\tdelete(tracked.ifaces, name)\n\t}\n}\n\nfunc sortedInterfaceNames(ifaces map[string]clablabruntime.InterfaceEventData) []string {\n\tnames := make([]string, 0, len(ifaces))\n\tfor name := range ifaces {\n\t\tnames = append(names, name)\n\t}\n\tsort.Strings(names)\n\n\treturn names\n}\n\nfunc (p *interfacePoller) forgetStats(tracked *trackedNode, ifName string) {\n\tdelete(p.statsSamples,\n\t\tc9sIfaceStatsKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name, ifName))\n}\n\nfunc (p *interfacePoller) emit(\n\tctx context.Context,\n\ttracked *trackedNode,\n\taction string,\n\tdata clablabruntime.InterfaceEventData,\n\ttimestamp time.Time,\n) {\n\tp.r.sendEvent(ctx, p.sink, c9sInterfaceEvent(tracked, action, data, timestamp))\n}\n\n// c9sInterfaceEvent is an interface event of a node. The actor is the node, as for its container\n// events. The interface itself is in Interface; the events command reports it with the\n// attributes of the local runtimes' interface events.\nfunc c9sInterfaceEvent(\n\ttracked *trackedNode,\n\taction string,\n\tdata clablabruntime.InterfaceEventData,\n\ttimestamp time.Time,\n) clablabruntime.Event {\n\tkey := c9sNodeKey(tracked.lab.Namespace, tracked.lab.Name, tracked.node.Name)\n\n\tattributes := map[string]string{\n\t\t\"namespace\": tracked.lab.Namespace,\n\t\t\"lab\":       tracked.lab.Name,\n\t\t\"node\":      tracked.node.Name,\n\t\t\"origin\":    clabernetesAppValue,\n\t}\n\tif tracked.node.Pod != \"\" {\n\t\tattributes[\"pod\"] = tracked.node.Pod\n\t}\n\n\tnode := tracked.node\n\n\treturn clablabruntime.Event{\n\t\tTimestamp:   timestamp,\n\t\tType:        clablabruntime.EventTypeInterface,\n\t\tAction:      action,\n\t\tActorID:     key,\n\t\tActorName:   fmt.Sprintf(\"%s-%s\", tracked.lab.Name, tracked.node.Name),\n\t\tActorFullID: key,\n\t\tAttributes:  attributes,\n\t\tLab:         tracked.lab,\n\t\tNode:        &node,\n\t\tInterface:   &data,\n\t}\n}\n\n// c9sIfaceStatsData computes the counters and rates of a stats event from two samples.\nfunc c9sIfaceStatsData(previous, current c9sIfaceStatsSample) *clablabruntime.InterfaceStats {\n\tinterval := current.Timestamp.Sub(previous.Timestamp)\n\tif interval <= 0 {\n\t\tinterval = time.Second\n\t}\n\n\tseconds := interval.Seconds()\n\tstat := current.Stats\n\n\treturn &clablabruntime.InterfaceStats{\n\t\tRxBytes:   stat.RxBytes,\n\t\tTxBytes:   stat.TxBytes,\n\t\tRxPackets: stat.RxPackets,\n\t\tTxPackets: stat.TxPackets,\n\t\tRxBps:     float64(counterDelta(stat.RxBytes, previous.Stats.RxBytes)*8) / seconds,\n\t\tTxBps:     float64(counterDelta(stat.TxBytes, previous.Stats.TxBytes)*8) / seconds,\n\t\tRxPps:     float64(counterDelta(stat.RxPackets, previous.Stats.RxPackets)) / seconds,\n\t\tTxPps:     float64(counterDelta(stat.TxPackets, previous.Stats.TxPackets)) / seconds,\n\t\tInterval:  interval,\n\t}\n}\n\n// parseInterfaceSample splits the output of interfaceSampleScript into the /proc/net/dev\n// counters and the sysfs interface states. hasStates is false for output without the sysfs\n// section, such as a plain cat of /proc/net/dev.\nfunc parseInterfaceSample(data []byte) ([]c9sIfaceStats, []c9sIfaceState, bool, error) {\n\ttext := string(data)\n\n\tprocPart, sysfsPart, hasStates := strings.Cut(text, interfaceSysfsMarker+\"\\n\")\n\tif !hasStates {\n\t\tprocPart, _, hasStates = strings.Cut(text, interfaceSysfsMarker)\n\t}\n\n\tstats, err := parseProcNetDev([]byte(procPart))\n\tif err != nil {\n\t\treturn nil, nil, false, err\n\t}\n\tif !hasStates {\n\t\treturn stats, nil, false, nil\n\t}\n\n\treturn stats, parseSysfsInterfaces(sysfsPart), true, nil\n}\n\nfunc parseSysfsInterfaces(data string) []c9sIfaceState {\n\tlines := strings.Split(data, \"\\n\")\n\tstates := make([]c9sIfaceState, 0, len(lines))\n\n\tfor _, line := range lines {\n\t\tfields := strings.SplitN(line, \"\\t\", 7) //nolint:mnd\n\t\tif len(fields) < 5 || strings.TrimSpace(fields[0]) == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tstate := c9sIfaceState{\n\t\t\tName:      strings.TrimSpace(fields[0]),\n\t\t\tMAC:       strings.TrimSpace(fields[3]),\n\t\t\tOperState: strings.ToLower(strings.TrimSpace(fields[4])),\n\t\t}\n\t\tstate.Index, _ = strconv.Atoi(strings.TrimSpace(fields[1]))\n\t\tstate.MTU, _ = strconv.Atoi(strings.TrimSpace(fields[2]))\n\t\tif len(fields) > 5 {\n\t\t\tstate.Flags, _ = strconv.ParseUint(\n\t\t\t\tstrings.TrimPrefix(strings.TrimSpace(fields[5]), \"0x\"), 16, 64)\n\t\t}\n\t\tif len(fields) > 6 {\n\t\t\tstate.Alias = strings.TrimSpace(fields[6])\n\t\t}\n\t\tif state.OperState == \"\" {\n\t\t\tstate.OperState = \"unknown\"\n\t\t}\n\n\t\tstates = append(states, state)\n\t}\n\n\treturn states\n}\n\nfunc parseProcNetDev(data []byte) ([]c9sIfaceStats, error) {\n\tlines := strings.Split(string(data), \"\\n\")\n\tstats := make([]c9sIfaceStats, 0, len(lines))\n\n\tfor _, line := range lines {\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" || !strings.Contains(line, \":\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tparts := strings.SplitN(line, \":\", 2)\n\t\tif len(parts) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tifName := strings.TrimSpace(parts[0])\n\t\tfields := strings.Fields(parts[1])\n\t\tif len(fields) < 16 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected /proc/net/dev line for %q: %q\", ifName, line)\n\t\t}\n\n\t\trxBytes, err := strconv.ParseUint(fields[0], 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse rx bytes for %q: %w\", ifName, err)\n\t\t}\n\t\trxPackets, err := strconv.ParseUint(fields[1], 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse rx packets for %q: %w\", ifName, err)\n\t\t}\n\t\ttxBytes, err := strconv.ParseUint(fields[8], 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse tx bytes for %q: %w\", ifName, err)\n\t\t}\n\t\ttxPackets, err := strconv.ParseUint(fields[9], 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse tx packets for %q: %w\", ifName, err)\n\t\t}\n\n\t\tstats = append(stats, c9sIfaceStats{\n\t\t\tName:      ifName,\n\t\t\tRxBytes:   rxBytes,\n\t\t\tRxPackets: rxPackets,\n\t\t\tTxBytes:   txBytes,\n\t\t\tTxPackets: txPackets,\n\t\t})\n\t}\n\n\treturn stats, nil\n}\n\n// c9sNodeKey is the actor ID of a node: <namespace>/<lab>/<node>, the same value inspect\n// reports as container_id.\nfunc c9sNodeKey(namespace, lab, node string) string {\n\treturn namespace + \"/\" + lab + \"/\" + node\n}\n\nfunc c9sIfaceStatsKey(namespace, lab, node, ifName string) string {\n\treturn c9sNodeKey(namespace, lab, node) + \"/\" + ifName\n}\n\nfunc counterDelta(current, previous uint64) uint64 {\n\tif current < previous {\n\t\treturn 0\n\t}\n\n\treturn current - previous\n}",
        "lineStart": 1,
        "lineEnd": 773,
        "totalLines": 773,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525857123,
      "end": 1793525857137
    }
  }
}
read · completed

Input

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

Output

<path>/source/head/labruntime/clabernetes/events.go</path>
<type>file</type>
<content>
1: package clabernetes
2: 
3: import (
4: 	"context"
5: 	"errors"
6: 	"fmt"
7: 	"strings"
8: 	"time"
9: 
10: 	"github.com/charmbracelet/log"
11: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
12: 	corev1 "k8s.io/api/core/v1"
13: 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
14: 	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
15: 	"k8s.io/apimachinery/pkg/fields"
16: 	"k8s.io/apimachinery/pkg/labels"
17: 	"k8s.io/apimachinery/pkg/watch"
18: )
19: 
20: func (r *Runtime) StreamEvents(
21: 	ctx context.Context,
22: 	req clablabruntime.EventStreamRequest,
23: ) (<-chan clablabruntime.Event, <-chan error, error) {
24: 	r, connErr := r.connect(ctx, req.Identity)
25: 	if connErr != nil {
26: 		return nil, nil, connErr
27: 	}
28: 
29: 	scope, err := r.eventScopeFor(req)
30: 	if err != nil {
31: 		return nil, nil, err
32: 	}
33: 
34: 	events := make(chan clablabruntime.Event, 128)
35: 	errs := make(chan error, 4)
36: 	// changed carries the labs whose Topology, Nodes or pods changed; the container tracker
37: 	// reads them again and reports what changed for their nodes.
38: 	changed := make(chan labRef, 256)
39: 
40: 	go r.trackContainers(ctx, scope, req.IncludeInitialState, changed, events, errs)
41: 
42: 	// Interface state events are always reported, like the netlink-backed events of the local
43: 	// runtimes; statistics only on request. Both come from the same exec per node.
44: 	go r.pollInterfaces(ctx, scope, interfacePollOptions{
45: 		interval:            req.StatsInterval,
46: 		includeStats:        req.IncludeInterfaceStats,
47: 		includeInitialState: req.IncludeInitialState,
48: 	}, events)
49: 
50: 	go r.watchTopologies(ctx, scope, changed, events, errs)
51: 	go r.watchNodes(ctx, scope, changed, errs)
52: 	go r.watchPods(ctx, scope, changed, errs)
53: 
54: 	return events, errs, nil
55: }
56: 
57: // labRef names a lab in a namespace.
58: type labRef struct {
59: 	namespace string
60: 	lab       string
61: }
62: 
63: func sendChangedLab(ctx context.Context, changed chan<- labRef, ref labRef) {
64: 	if ref.lab == "" {
65: 		return
66: 	}
67: 
68: 	select {
69: 	case changed <- ref:
70: 	case <-ctx.Done():
71: 	}
72: }
73: 
74: // eventScope is the namespace and, optionally, the single lab an event stream covers.
75: type eventScope struct {
76: 	namespace string
77: 	lab       string
78: }
79: 
80: func (r *Runtime) eventScopeFor(req clablabruntime.EventStreamRequest) (eventScope, error) {
81: 	if req.Name != "" {
82: 		namespace, err := r.namespaceForLab(req.Name, req.Namespace)
83: 		if err != nil {
84: 			return eventScope{}, err
85: 		}
86: 
87: 		return eventScope{namespace: namespace, lab: req.Name}, nil
88: 	}
89: 
90: 	return eventScope{namespace: r.listNamespace(req.Namespace, req.AllNamespaces)}, nil
91: }
92: 
93: // labelSelector selects the lab-owned resources of the scope.
94: func (s eventScope) labelSelector() string {
95: 	if s.lab != "" {
96: 		return labels.Set{labelTopologyOwner: s.lab}.String()
97: 	}
98: 
99: 	return labelTopologyOwner
100: }
101: 
102: // topologyListOptions selects the Topology resources of the scope.
103: func (s eventScope) topologyListOptions() metav1.ListOptions {
104: 	if s.lab != "" {
105: 		return metav1.ListOptions{
106: 			FieldSelector: fields.OneTermEqualSelector("metadata.name", s.lab).String(),
107: 		}
108: 	}
109: 
110: 	return metav1.ListOptions{}
111: }
112: 
113: // labStates lists the labs of the scope.
114: func (r *Runtime) labStates(
115: 	ctx context.Context,
116: 	scope eventScope,
117: ) ([]*clablabruntime.LabState, error) {
118: 	if scope.lab != "" {
119: 		state, err := r.Inspect(ctx, clablabruntime.InspectRequest{
120: 			Name:      scope.lab,
121: 			Namespace: scope.namespace,
122: 		})
123: 		if err != nil {
124: 			// A lab that is not deployed yet has no state; its resources show up through
125: 			// the watches once it is.
126: 			var notFound *labNotFoundError
127: 			if errors.As(err, &notFound) {
128: 				return nil, nil
129: 			}
130: 
131: 			return nil, err
132: 		}
133: 
134: 		return []*clablabruntime.LabState{state}, nil
135: 	}
136: 
137: 	return r.List(ctx, clablabruntime.ListRequest{
138: 		Namespace:     scope.namespace,
139: 		AllNamespaces: scope.namespace == metav1.NamespaceAll,
140: 	})
141: }
142: 
143: func (r *Runtime) watchNodes(
144: 	ctx context.Context,
145: 	scope eventScope,
146: 	changed chan<- labRef,
147: 	errSink chan<- error,
148: ) {
149: 	resource := r.client.Resource(nodeGVR).Namespace(scope.namespace)
150: 
151: 	for {
152: 		watcher, err := resource.Watch(ctx, metav1.ListOptions{
153: 			LabelSelector: scope.labelSelector(),
154: 		})
155: 		if err != nil {
156: 			if ctx.Err() != nil {
157: 				return
158: 			}
159: 
160: 			sendEventError(ctx, errSink, fmt.Errorf("failed to watch c9s nodes: %w", err))
161: 			return
162: 		}
163: 
164: 		if !r.forwardNodeWatch(ctx, watcher, changed, errSink) {
165: 			return
166: 		}
167: 
168: 		if !sleepContext(ctx, pollInterval) {
169: 			return
170: 		}
171: 	}
172: }
173: 
174: // forwardNodeWatch reports the lab of every changed Node to the container tracker.
175: func (r *Runtime) forwardNodeWatch(
176: 	ctx context.Context,
177: 	watcher watch.Interface,
178: 	changed chan<- labRef,
179: 	errSink chan<- error,
180: ) bool {
181: 	defer watcher.Stop()
182: 
183: 	for {
184: 		select {
185: 		case <-ctx.Done():
186: 			return false
187: 		case ev, ok := <-watcher.ResultChan():
188: 			if !ok {
189: 				log.Debug("c9s node watch closed, reconnecting")
190: 				return true
191: 			}
192: 			if ev.Type == watch.Error {
193: 				sendEventError(ctx, errSink, fmt.Errorf("c9s node watch returned an error"))
194: 				return false
195: 			}
196: 
197: 			node, ok := ev.Object.(*unstructured.Unstructured)
198: 			if !ok {
199: 				continue
200: 			}
201: 
202: 			sendChangedLab(ctx, changed, labRef{
203: 				namespace: node.GetNamespace(),
204: 				lab:       node.GetLabels()[labelTopologyOwner],
205: 			})
206: 		}
207: 	}
208: }
209: 
210: func (r *Runtime) watchTopologies(
211: 	ctx context.Context,
212: 	scope eventScope,
213: 	changed chan<- labRef,
214: 	eventSink chan<- clablabruntime.Event,
215: 	errSink chan<- error,
216: ) {
217: 	resource := r.client.Resource(topologyGVR).Namespace(scope.namespace)
218: 
219: 	for {
220: 		watcher, err := resource.Watch(ctx, scope.topologyListOptions())
221: 		if err != nil {
222: 			if ctx.Err() != nil {
223: 				return
224: 			}
225: 
226: 			sendEventError(
227: 				ctx,
228: 				errSink,
229: 				fmt.Errorf("failed to watch clabernetes topologies: %w", err),
230: 			)
231: 			return
232: 		}
233: 
234: 		if !r.forwardTopologyWatch(ctx, scope.namespace, watcher, changed, eventSink, errSink) {
235: 			return
236: 		}
237: 
238: 		if !sleepContext(ctx, pollInterval) {
239: 			return
240: 		}
241: 	}
242: }
243: 
244: // forwardTopologyWatch reports Topology changes as topology events, which only c9s has, and
245: // reports the lab to the container tracker.
246: func (r *Runtime) forwardTopologyWatch(
247: 	ctx context.Context,
248: 	namespace string,
249: 	watcher watch.Interface,
250: 	changed chan<- labRef,
251: 	eventSink chan<- clablabruntime.Event,
252: 	errSink chan<- error,
253: ) bool {
254: 	defer watcher.Stop()
255: 
256: 	for {
257: 		select {
258: 		case <-ctx.Done():
259: 			return false
260: 		case ev, ok := <-watcher.ResultChan():
261: 			if !ok {
262: 				log.Debug("C9s topology watch closed, reconnecting")
263: 				return true
264: 			}
265: 			if ev.Type == watch.Error {
266: 				sendEventError(
267: 					ctx,
268: 					errSink,
269: 					fmt.Errorf("clabernetes topology watch returned an error"),
270: 				)
271: 				return false
272: 			}
273: 
274: 			obj, ok := ev.Object.(*unstructured.Unstructured)
275: 			if !ok {
276: 				continue
277: 			}
278: 
279: 			state := stateFromTopology(obj, namespace)
280: 			r.sendEvent(ctx, eventSink, clablabruntime.Event{
281: 				Timestamp: time.Now(),
282: 				Type:      "topology",
283: 				Action:    strings.ToLower(string(ev.Type)),
284: 				ActorID:   fmt.Sprintf("%s/%s", state.Namespace, state.Name),
285: 				ActorName: state.Name,
286: 				Attributes: map[string]string{
287: 					"namespace": state.Namespace,
288: 					"lab":       state.Name,
289: 					"state":     state.State,
290: 					"ready":     fmt.Sprintf("%t", state.Ready),
291: 				},
292: 			})
293: 			sendChangedLab(ctx, changed, labRef{namespace: state.Namespace, lab: state.Name})
294: 		}
295: 	}
296: }
297: 
298: func (r *Runtime) watchPods(
299: 	ctx context.Context,
300: 	scope eventScope,
301: 	changed chan<- labRef,
302: 	errSink chan<- error,
303: ) {
304: 	for {
305: 		watcher, err := r.kubeClient.CoreV1().Pods(scope.namespace).Watch(ctx, metav1.ListOptions{
306: 			LabelSelector: scope.labelSelector(),
307: 		})
308: 		if err != nil {
309: 			if ctx.Err() != nil {
310: 				return
311: 			}
312: 
313: 			sendEventError(ctx, errSink, fmt.Errorf(
314: 				"failed to watch clabernetes pods: %w", err))
315: 			return
316: 		}
317: 
318: 		if !r.forwardPodWatch(ctx, watcher, changed, errSink) {
319: 			return
320: 		}
321: 
322: 		if !sleepContext(ctx, pollInterval) {
323: 			return
324: 		}
325: 	}
326: }
327: 
328: // forwardPodWatch reports the lab of every changed pod to the container tracker.
329: func (r *Runtime) forwardPodWatch(
330: 	ctx context.Context,
331: 	watcher watch.Interface,
332: 	changed chan<- labRef,
333: 	errSink chan<- error,
334: ) bool {
335: 	defer watcher.Stop()
336: 
337: 	for {
338: 		select {
339: 		case <-ctx.Done():
340: 			return false
341: 		case ev, ok := <-watcher.ResultChan():
342: 			if !ok {
343: 				log.Debug("C9s pod watch closed, reconnecting")
344: 				return true
345: 			}
346: 			if ev.Type == watch.Error {
347: 				sendEventError(ctx, errSink, fmt.Errorf(
348: 					"clabernetes pod watch returned an error"))
349: 				return false
350: 			}
351: 
352: 			pod, ok := ev.Object.(*corev1.Pod)
353: 			if !ok {
354: 				continue
355: 			}
356: 
357: 			sendChangedLab(ctx, changed, labRef{
358: 				namespace: pod.Namespace,
359: 				lab:       pod.Labels[labelTopologyOwner],
360: 			})
361: 		}
362: 	}
363: }
364: 
365: func sleepContext(ctx context.Context, d time.Duration) bool {
366: 	timer := time.NewTimer(d)
367: 	defer timer.Stop()
368: 
369: 	select {
370: 	case <-timer.C:
371: 		return true
372: 	case <-ctx.Done():
373: 		return false
374: 	}
375: }
376: 
377: func (r *Runtime) sendEvent(
378: 	ctx context.Context,
379: 	eventSink chan<- clablabruntime.Event,
380: 	event clablabruntime.Event,
381: ) {
382: 	select {
383: 	case eventSink <- event:
384: 	case <-ctx.Done():
385: 	}
386: }
387: 
388: func sendEventError(ctx context.Context, errSink chan<- error, err error) {
389: 	select {
390: 	case errSink <- err:
391: 	case <-ctx.Done():
392: 	}
393: }

(End of file - total 393 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19678bb93001I2425iaZDiKlwN",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19678a805001A3Xi9IrNVARfXH",
  "callID": "call_95fa9801de3e4953af320d24",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/events.go"
    },
    "output": "<path>/source/head/labruntime/clabernetes/events.go</path>\n<type>file</type>\n<content>\n1: package clabernetes\n2: \n3: import (\n4: \t\"context\"\n5: \t\"errors\"\n6: \t\"fmt\"\n7: \t\"strings\"\n8: \t\"time\"\n9: \n10: \t\"github.com/charmbracelet/log\"\n11: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n12: \tcorev1 \"k8s.io/api/core/v1\"\n13: \tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n14: \t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n15: \t\"k8s.io/apimachinery/pkg/fields\"\n16: \t\"k8s.io/apimachinery/pkg/labels\"\n17: \t\"k8s.io/apimachinery/pkg/watch\"\n18: )\n19: \n20: func (r *Runtime) StreamEvents(\n21: \tctx context.Context,\n22: \treq clablabruntime.EventStreamRequest,\n23: ) (<-chan clablabruntime.Event, <-chan error, error) {\n24: \tr, connErr := r.connect(ctx, req.Identity)\n25: \tif connErr != nil {\n26: \t\treturn nil, nil, connErr\n27: \t}\n28: \n29: \tscope, err := r.eventScopeFor(req)\n30: \tif err != nil {\n31: \t\treturn nil, nil, err\n32: \t}\n33: \n34: \tevents := make(chan clablabruntime.Event, 128)\n35: \terrs := make(chan error, 4)\n36: \t// changed carries the labs whose Topology, Nodes or pods changed; the container tracker\n37: \t// reads them again and reports what changed for their nodes.\n38: \tchanged := make(chan labRef, 256)\n39: \n40: \tgo r.trackContainers(ctx, scope, req.IncludeInitialState, changed, events, errs)\n41: \n42: \t// Interface state events are always reported, like the netlink-backed events of the local\n43: \t// runtimes; statistics only on request. Both come from the same exec per node.\n44: \tgo r.pollInterfaces(ctx, scope, interfacePollOptions{\n45: \t\tinterval:            req.StatsInterval,\n46: \t\tincludeStats:        req.IncludeInterfaceStats,\n47: \t\tincludeInitialState: req.IncludeInitialState,\n48: \t}, events)\n49: \n50: \tgo r.watchTopologies(ctx, scope, changed, events, errs)\n51: \tgo r.watchNodes(ctx, scope, changed, errs)\n52: \tgo r.watchPods(ctx, scope, changed, errs)\n53: \n54: \treturn events, errs, nil\n55: }\n56: \n57: // labRef names a lab in a namespace.\n58: type labRef struct {\n59: \tnamespace string\n60: \tlab       string\n61: }\n62: \n63: func sendChangedLab(ctx context.Context, changed chan<- labRef, ref labRef) {\n64: \tif ref.lab == \"\" {\n65: \t\treturn\n66: \t}\n67: \n68: \tselect {\n69: \tcase changed <- ref:\n70: \tcase <-ctx.Done():\n71: \t}\n72: }\n73: \n74: // eventScope is the namespace and, optionally, the single lab an event stream covers.\n75: type eventScope struct {\n76: \tnamespace string\n77: \tlab       string\n78: }\n79: \n80: func (r *Runtime) eventScopeFor(req clablabruntime.EventStreamRequest) (eventScope, error) {\n81: \tif req.Name != \"\" {\n82: \t\tnamespace, err := r.namespaceForLab(req.Name, req.Namespace)\n83: \t\tif err != nil {\n84: \t\t\treturn eventScope{}, err\n85: \t\t}\n86: \n87: \t\treturn eventScope{namespace: namespace, lab: req.Name}, nil\n88: \t}\n89: \n90: \treturn eventScope{namespace: r.listNamespace(req.Namespace, req.AllNamespaces)}, nil\n91: }\n92: \n93: // labelSelector selects the lab-owned resources of the scope.\n94: func (s eventScope) labelSelector() string {\n95: \tif s.lab != \"\" {\n96: \t\treturn labels.Set{labelTopologyOwner: s.lab}.String()\n97: \t}\n98: \n99: \treturn labelTopologyOwner\n100: }\n101: \n102: // topologyListOptions selects the Topology resources of the scope.\n103: func (s eventScope) topologyListOptions() metav1.ListOptions {\n104: \tif s.lab != \"\" {\n105: \t\treturn metav1.ListOptions{\n106: \t\t\tFieldSelector: fields.OneTermEqualSelector(\"metadata.name\", s.lab).String(),\n107: \t\t}\n108: \t}\n109: \n110: \treturn metav1.ListOptions{}\n111: }\n112: \n113: // labStates lists the labs of the scope.\n114: func (r *Runtime) labStates(\n115: \tctx context.Context,\n116: \tscope eventScope,\n117: ) ([]*clablabruntime.LabState, error) {\n118: \tif scope.lab != \"\" {\n119: \t\tstate, err := r.Inspect(ctx, clablabruntime.InspectRequest{\n120: \t\t\tName:      scope.lab,\n121: \t\t\tNamespace: scope.namespace,\n122: \t\t})\n123: \t\tif err != nil {\n124: \t\t\t// A lab that is not deployed yet has no state; its resources show up through\n125: \t\t\t// the watches once it is.\n126: \t\t\tvar notFound *labNotFoundError\n127: \t\t\tif errors.As(err, &notFound) {\n128: \t\t\t\treturn nil, nil\n129: \t\t\t}\n130: \n131: \t\t\treturn nil, err\n132: \t\t}\n133: \n134: \t\treturn []*clablabruntime.LabState{state}, nil\n135: \t}\n136: \n137: \treturn r.List(ctx, clablabruntime.ListRequest{\n138: \t\tNamespace:     scope.namespace,\n139: \t\tAllNamespaces: scope.namespace == metav1.NamespaceAll,\n140: \t})\n141: }\n142: \n143: func (r *Runtime) watchNodes(\n144: \tctx context.Context,\n145: \tscope eventScope,\n146: \tchanged chan<- labRef,\n147: \terrSink chan<- error,\n148: ) {\n149: \tresource := r.client.Resource(nodeGVR).Namespace(scope.namespace)\n150: \n151: \tfor {\n152: \t\twatcher, err := resource.Watch(ctx, metav1.ListOptions{\n153: \t\t\tLabelSelector: scope.labelSelector(),\n154: \t\t})\n155: \t\tif err != nil {\n156: \t\t\tif ctx.Err() != nil {\n157: \t\t\t\treturn\n158: \t\t\t}\n159: \n160: \t\t\tsendEventError(ctx, errSink, fmt.Errorf(\"failed to watch c9s nodes: %w\", err))\n161: \t\t\treturn\n162: \t\t}\n163: \n164: \t\tif !r.forwardNodeWatch(ctx, watcher, changed, errSink) {\n165: \t\t\treturn\n166: \t\t}\n167: \n168: \t\tif !sleepContext(ctx, pollInterval) {\n169: \t\t\treturn\n170: \t\t}\n171: \t}\n172: }\n173: \n174: // forwardNodeWatch reports the lab of every changed Node to the container tracker.\n175: func (r *Runtime) forwardNodeWatch(\n176: \tctx context.Context,\n177: \twatcher watch.Interface,\n178: \tchanged chan<- labRef,\n179: \terrSink chan<- error,\n180: ) bool {\n181: \tdefer watcher.Stop()\n182: \n183: \tfor {\n184: \t\tselect {\n185: \t\tcase <-ctx.Done():\n186: \t\t\treturn false\n187: \t\tcase ev, ok := <-watcher.ResultChan():\n188: \t\t\tif !ok {\n189: \t\t\t\tlog.Debug(\"c9s node watch closed, reconnecting\")\n190: \t\t\t\treturn true\n191: \t\t\t}\n192: \t\t\tif ev.Type == watch.Error {\n193: \t\t\t\tsendEventError(ctx, errSink, fmt.Errorf(\"c9s node watch returned an error\"))\n194: \t\t\t\treturn false\n195: \t\t\t}\n196: \n197: \t\t\tnode, ok := ev.Object.(*unstructured.Unstructured)\n198: \t\t\tif !ok {\n199: \t\t\t\tcontinue\n200: \t\t\t}\n201: \n202: \t\t\tsendChangedLab(ctx, changed, labRef{\n203: \t\t\t\tnamespace: node.GetNamespace(),\n204: \t\t\t\tlab:       node.GetLabels()[labelTopologyOwner],\n205: \t\t\t})\n206: \t\t}\n207: \t}\n208: }\n209: \n210: func (r *Runtime) watchTopologies(\n211: \tctx context.Context,\n212: \tscope eventScope,\n213: \tchanged chan<- labRef,\n214: \teventSink chan<- clablabruntime.Event,\n215: \terrSink chan<- error,\n216: ) {\n217: \tresource := r.client.Resource(topologyGVR).Namespace(scope.namespace)\n218: \n219: \tfor {\n220: \t\twatcher, err := resource.Watch(ctx, scope.topologyListOptions())\n221: \t\tif err != nil {\n222: \t\t\tif ctx.Err() != nil {\n223: \t\t\t\treturn\n224: \t\t\t}\n225: \n226: \t\t\tsendEventError(\n227: \t\t\t\tctx,\n228: \t\t\t\terrSink,\n229: \t\t\t\tfmt.Errorf(\"failed to watch clabernetes topologies: %w\", err),\n230: \t\t\t)\n231: \t\t\treturn\n232: \t\t}\n233: \n234: \t\tif !r.forwardTopologyWatch(ctx, scope.namespace, watcher, changed, eventSink, errSink) {\n235: \t\t\treturn\n236: \t\t}\n237: \n238: \t\tif !sleepContext(ctx, pollInterval) {\n239: \t\t\treturn\n240: \t\t}\n241: \t}\n242: }\n243: \n244: // forwardTopologyWatch reports Topology changes as topology events, which only c9s has, and\n245: // reports the lab to the container tracker.\n246: func (r *Runtime) forwardTopologyWatch(\n247: \tctx context.Context,\n248: \tnamespace string,\n249: \twatcher watch.Interface,\n250: \tchanged chan<- labRef,\n251: \teventSink chan<- clablabruntime.Event,\n252: \terrSink chan<- error,\n253: ) bool {\n254: \tdefer watcher.Stop()\n255: \n256: \tfor {\n257: \t\tselect {\n258: \t\tcase <-ctx.Done():\n259: \t\t\treturn false\n260: \t\tcase ev, ok := <-watcher.ResultChan():\n261: \t\t\tif !ok {\n262: \t\t\t\tlog.Debug(\"C9s topology watch closed, reconnecting\")\n263: \t\t\t\treturn true\n264: \t\t\t}\n265: \t\t\tif ev.Type == watch.Error {\n266: \t\t\t\tsendEventError(\n267: \t\t\t\t\tctx,\n268: \t\t\t\t\terrSink,\n269: \t\t\t\t\tfmt.Errorf(\"clabernetes topology watch returned an error\"),\n270: \t\t\t\t)\n271: \t\t\t\treturn false\n272: \t\t\t}\n273: \n274: \t\t\tobj, ok := ev.Object.(*unstructured.Unstructured)\n275: \t\t\tif !ok {\n276: \t\t\t\tcontinue\n277: \t\t\t}\n278: \n279: \t\t\tstate := stateFromTopology(obj, namespace)\n280: \t\t\tr.sendEvent(ctx, eventSink, clablabruntime.Event{\n281: \t\t\t\tTimestamp: time.Now(),\n282: \t\t\t\tType:      \"topology\",\n283: \t\t\t\tAction:    strings.ToLower(string(ev.Type)),\n284: \t\t\t\tActorID:   fmt.Sprintf(\"%s/%s\", state.Namespace, state.Name),\n285: \t\t\t\tActorName: state.Name,\n286: \t\t\t\tAttributes: map[string]string{\n287: \t\t\t\t\t\"namespace\": state.Namespace,\n288: \t\t\t\t\t\"lab\":       state.Name,\n289: \t\t\t\t\t\"state\":     state.State,\n290: \t\t\t\t\t\"ready\":     fmt.Sprintf(\"%t\", state.Ready),\n291: \t\t\t\t},\n292: \t\t\t})\n293: \t\t\tsendChangedLab(ctx, changed, labRef{namespace: state.Namespace, lab: state.Name})\n294: \t\t}\n295: \t}\n296: }\n297: \n298: func (r *Runtime) watchPods(\n299: \tctx context.Context,\n300: \tscope eventScope,\n301: \tchanged chan<- labRef,\n302: \terrSink chan<- error,\n303: ) {\n304: \tfor {\n305: \t\twatcher, err := r.kubeClient.CoreV1().Pods(scope.namespace).Watch(ctx, metav1.ListOptions{\n306: \t\t\tLabelSelector: scope.labelSelector(),\n307: \t\t})\n308: \t\tif err != nil {\n309: \t\t\tif ctx.Err() != nil {\n310: \t\t\t\treturn\n311: \t\t\t}\n312: \n313: \t\t\tsendEventError(ctx, errSink, fmt.Errorf(\n314: \t\t\t\t\"failed to watch clabernetes pods: %w\", err))\n315: \t\t\treturn\n316: \t\t}\n317: \n318: \t\tif !r.forwardPodWatch(ctx, watcher, changed, errSink) {\n319: \t\t\treturn\n320: \t\t}\n321: \n322: \t\tif !sleepContext(ctx, pollInterval) {\n323: \t\t\treturn\n324: \t\t}\n325: \t}\n326: }\n327: \n328: // forwardPodWatch reports the lab of every changed pod to the container tracker.\n329: func (r *Runtime) forwardPodWatch(\n330: \tctx context.Context,\n331: \twatcher watch.Interface,\n332: \tchanged chan<- labRef,\n333: \terrSink chan<- error,\n334: ) bool {\n335: \tdefer watcher.Stop()\n336: \n337: \tfor {\n338: \t\tselect {\n339: \t\tcase <-ctx.Done():\n340: \t\t\treturn false\n341: \t\tcase ev, ok := <-watcher.ResultChan():\n342: \t\t\tif !ok {\n343: \t\t\t\tlog.Debug(\"C9s pod watch closed, reconnecting\")\n344: \t\t\t\treturn true\n345: \t\t\t}\n346: \t\t\tif ev.Type == watch.Error {\n347: \t\t\t\tsendEventError(ctx, errSink, fmt.Errorf(\n348: \t\t\t\t\t\"clabernetes pod watch returned an error\"))\n349: \t\t\t\treturn false\n350: \t\t\t}\n351: \n352: \t\t\tpod, ok := ev.Object.(*corev1.Pod)\n353: \t\t\tif !ok {\n354: \t\t\t\tcontinue\n355: \t\t\t}\n356: \n357: \t\t\tsendChangedLab(ctx, changed, labRef{\n358: \t\t\t\tnamespace: pod.Namespace,\n359: \t\t\t\tlab:       pod.Labels[labelTopologyOwner],\n360: \t\t\t})\n361: \t\t}\n362: \t}\n363: }\n364: \n365: func sleepContext(ctx context.Context, d time.Duration) bool {\n366: \ttimer := time.NewTimer(d)\n367: \tdefer timer.Stop()\n368: \n369: \tselect {\n370: \tcase <-timer.C:\n371: \t\treturn true\n372: \tcase <-ctx.Done():\n373: \t\treturn false\n374: \t}\n375: }\n376: \n377: func (r *Runtime) sendEvent(\n378: \tctx context.Context,\n379: \teventSink chan<- clablabruntime.Event,\n380: \tevent clablabruntime.Event,\n381: ) {\n382: \tselect {\n383: \tcase eventSink <- event:\n384: \tcase <-ctx.Done():\n385: \t}\n386: }\n387: \n388: func sendEventError(ctx context.Context, errSink chan<- error, err error) {\n389: \tselect {\n390: \tcase errSink <- err:\n391: \tcase <-ctx.Done():\n392: \t}\n393: }\n\n(End of file - total 393 lines)\n</content>",
    "title": "source/head/labruntime/clabernetes/events.go",
    "metadata": {
      "preview": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\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\t\"k8s.io/apimachinery/pkg/fields\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/apimachinery/pkg/watch\"\n)\n\nfunc (r *Runtime) StreamEvents(",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/events.go",
        "text": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\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\t\"k8s.io/apimachinery/pkg/fields\"\n\t\"k8s.io/apimachinery/pkg/labels\"\n\t\"k8s.io/apimachinery/pkg/watch\"\n)\n\nfunc (r *Runtime) StreamEvents(\n\tctx context.Context,\n\treq clablabruntime.EventStreamRequest,\n) (<-chan clablabruntime.Event, <-chan error, error) {\n\tr, connErr := r.connect(ctx, req.Identity)\n\tif connErr != nil {\n\t\treturn nil, nil, connErr\n\t}\n\n\tscope, err := r.eventScopeFor(req)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tevents := make(chan clablabruntime.Event, 128)\n\terrs := make(chan error, 4)\n\t// changed carries the labs whose Topology, Nodes or pods changed; the container tracker\n\t// reads them again and reports what changed for their nodes.\n\tchanged := make(chan labRef, 256)\n\n\tgo r.trackContainers(ctx, scope, req.IncludeInitialState, changed, events, errs)\n\n\t// Interface state events are always reported, like the netlink-backed events of the local\n\t// runtimes; statistics only on request. Both come from the same exec per node.\n\tgo r.pollInterfaces(ctx, scope, interfacePollOptions{\n\t\tinterval:            req.StatsInterval,\n\t\tincludeStats:        req.IncludeInterfaceStats,\n\t\tincludeInitialState: req.IncludeInitialState,\n\t}, events)\n\n\tgo r.watchTopologies(ctx, scope, changed, events, errs)\n\tgo r.watchNodes(ctx, scope, changed, errs)\n\tgo r.watchPods(ctx, scope, changed, errs)\n\n\treturn events, errs, nil\n}\n\n// labRef names a lab in a namespace.\ntype labRef struct {\n\tnamespace string\n\tlab       string\n}\n\nfunc sendChangedLab(ctx context.Context, changed chan<- labRef, ref labRef) {\n\tif ref.lab == \"\" {\n\t\treturn\n\t}\n\n\tselect {\n\tcase changed <- ref:\n\tcase <-ctx.Done():\n\t}\n}\n\n// eventScope is the namespace and, optionally, the single lab an event stream covers.\ntype eventScope struct {\n\tnamespace string\n\tlab       string\n}\n\nfunc (r *Runtime) eventScopeFor(req clablabruntime.EventStreamRequest) (eventScope, error) {\n\tif req.Name != \"\" {\n\t\tnamespace, err := r.namespaceForLab(req.Name, req.Namespace)\n\t\tif err != nil {\n\t\t\treturn eventScope{}, err\n\t\t}\n\n\t\treturn eventScope{namespace: namespace, lab: req.Name}, nil\n\t}\n\n\treturn eventScope{namespace: r.listNamespace(req.Namespace, req.AllNamespaces)}, nil\n}\n\n// labelSelector selects the lab-owned resources of the scope.\nfunc (s eventScope) labelSelector() string {\n\tif s.lab != \"\" {\n\t\treturn labels.Set{labelTopologyOwner: s.lab}.String()\n\t}\n\n\treturn labelTopologyOwner\n}\n\n// topologyListOptions selects the Topology resources of the scope.\nfunc (s eventScope) topologyListOptions() metav1.ListOptions {\n\tif s.lab != \"\" {\n\t\treturn metav1.ListOptions{\n\t\t\tFieldSelector: fields.OneTermEqualSelector(\"metadata.name\", s.lab).String(),\n\t\t}\n\t}\n\n\treturn metav1.ListOptions{}\n}\n\n// labStates lists the labs of the scope.\nfunc (r *Runtime) labStates(\n\tctx context.Context,\n\tscope eventScope,\n) ([]*clablabruntime.LabState, error) {\n\tif scope.lab != \"\" {\n\t\tstate, err := r.Inspect(ctx, clablabruntime.InspectRequest{\n\t\t\tName:      scope.lab,\n\t\t\tNamespace: scope.namespace,\n\t\t})\n\t\tif err != nil {\n\t\t\t// A lab that is not deployed yet has no state; its resources show up through\n\t\t\t// the watches once it is.\n\t\t\tvar notFound *labNotFoundError\n\t\t\tif errors.As(err, &notFound) {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn []*clablabruntime.LabState{state}, nil\n\t}\n\n\treturn r.List(ctx, clablabruntime.ListRequest{\n\t\tNamespace:     scope.namespace,\n\t\tAllNamespaces: scope.namespace == metav1.NamespaceAll,\n\t})\n}\n\nfunc (r *Runtime) watchNodes(\n\tctx context.Context,\n\tscope eventScope,\n\tchanged chan<- labRef,\n\terrSink chan<- error,\n) {\n\tresource := r.client.Resource(nodeGVR).Namespace(scope.namespace)\n\n\tfor {\n\t\twatcher, err := resource.Watch(ctx, metav1.ListOptions{\n\t\t\tLabelSelector: scope.labelSelector(),\n\t\t})\n\t\tif err != nil {\n\t\t\tif ctx.Err() != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tsendEventError(ctx, errSink, fmt.Errorf(\"failed to watch c9s nodes: %w\", err))\n\t\t\treturn\n\t\t}\n\n\t\tif !r.forwardNodeWatch(ctx, watcher, changed, errSink) {\n\t\t\treturn\n\t\t}\n\n\t\tif !sleepContext(ctx, pollInterval) {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// forwardNodeWatch reports the lab of every changed Node to the container tracker.\nfunc (r *Runtime) forwardNodeWatch(\n\tctx context.Context,\n\twatcher watch.Interface,\n\tchanged chan<- labRef,\n\terrSink chan<- error,\n) bool {\n\tdefer watcher.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn false\n\t\tcase ev, ok := <-watcher.ResultChan():\n\t\t\tif !ok {\n\t\t\t\tlog.Debug(\"c9s node watch closed, reconnecting\")\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif ev.Type == watch.Error {\n\t\t\t\tsendEventError(ctx, errSink, fmt.Errorf(\"c9s node watch returned an error\"))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tnode, ok := ev.Object.(*unstructured.Unstructured)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsendChangedLab(ctx, changed, labRef{\n\t\t\t\tnamespace: node.GetNamespace(),\n\t\t\t\tlab:       node.GetLabels()[labelTopologyOwner],\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc (r *Runtime) watchTopologies(\n\tctx context.Context,\n\tscope eventScope,\n\tchanged chan<- labRef,\n\teventSink chan<- clablabruntime.Event,\n\terrSink chan<- error,\n) {\n\tresource := r.client.Resource(topologyGVR).Namespace(scope.namespace)\n\n\tfor {\n\t\twatcher, err := resource.Watch(ctx, scope.topologyListOptions())\n\t\tif err != nil {\n\t\t\tif ctx.Err() != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tsendEventError(\n\t\t\t\tctx,\n\t\t\t\terrSink,\n\t\t\t\tfmt.Errorf(\"failed to watch clabernetes topologies: %w\", err),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tif !r.forwardTopologyWatch(ctx, scope.namespace, watcher, changed, eventSink, errSink) {\n\t\t\treturn\n\t\t}\n\n\t\tif !sleepContext(ctx, pollInterval) {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// forwardTopologyWatch reports Topology changes as topology events, which only c9s has, and\n// reports the lab to the container tracker.\nfunc (r *Runtime) forwardTopologyWatch(\n\tctx context.Context,\n\tnamespace string,\n\twatcher watch.Interface,\n\tchanged chan<- labRef,\n\teventSink chan<- clablabruntime.Event,\n\terrSink chan<- error,\n) bool {\n\tdefer watcher.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn false\n\t\tcase ev, ok := <-watcher.ResultChan():\n\t\t\tif !ok {\n\t\t\t\tlog.Debug(\"C9s topology watch closed, reconnecting\")\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif ev.Type == watch.Error {\n\t\t\t\tsendEventError(\n\t\t\t\t\tctx,\n\t\t\t\t\terrSink,\n\t\t\t\t\tfmt.Errorf(\"clabernetes topology watch returned an error\"),\n\t\t\t\t)\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tobj, ok := ev.Object.(*unstructured.Unstructured)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tstate := stateFromTopology(obj, namespace)\n\t\t\tr.sendEvent(ctx, eventSink, clablabruntime.Event{\n\t\t\t\tTimestamp: time.Now(),\n\t\t\t\tType:      \"topology\",\n\t\t\t\tAction:    strings.ToLower(string(ev.Type)),\n\t\t\t\tActorID:   fmt.Sprintf(\"%s/%s\", state.Namespace, state.Name),\n\t\t\t\tActorName: state.Name,\n\t\t\t\tAttributes: map[string]string{\n\t\t\t\t\t\"namespace\": state.Namespace,\n\t\t\t\t\t\"lab\":       state.Name,\n\t\t\t\t\t\"state\":     state.State,\n\t\t\t\t\t\"ready\":     fmt.Sprintf(\"%t\", state.Ready),\n\t\t\t\t},\n\t\t\t})\n\t\t\tsendChangedLab(ctx, changed, labRef{namespace: state.Namespace, lab: state.Name})\n\t\t}\n\t}\n}\n\nfunc (r *Runtime) watchPods(\n\tctx context.Context,\n\tscope eventScope,\n\tchanged chan<- labRef,\n\terrSink chan<- error,\n) {\n\tfor {\n\t\twatcher, err := r.kubeClient.CoreV1().Pods(scope.namespace).Watch(ctx, metav1.ListOptions{\n\t\t\tLabelSelector: scope.labelSelector(),\n\t\t})\n\t\tif err != nil {\n\t\t\tif ctx.Err() != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tsendEventError(ctx, errSink, fmt.Errorf(\n\t\t\t\t\"failed to watch clabernetes pods: %w\", err))\n\t\t\treturn\n\t\t}\n\n\t\tif !r.forwardPodWatch(ctx, watcher, changed, errSink) {\n\t\t\treturn\n\t\t}\n\n\t\tif !sleepContext(ctx, pollInterval) {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// forwardPodWatch reports the lab of every changed pod to the container tracker.\nfunc (r *Runtime) forwardPodWatch(\n\tctx context.Context,\n\twatcher watch.Interface,\n\tchanged chan<- labRef,\n\terrSink chan<- error,\n) bool {\n\tdefer watcher.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn false\n\t\tcase ev, ok := <-watcher.ResultChan():\n\t\t\tif !ok {\n\t\t\t\tlog.Debug(\"C9s pod watch closed, reconnecting\")\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif ev.Type == watch.Error {\n\t\t\t\tsendEventError(ctx, errSink, fmt.Errorf(\n\t\t\t\t\t\"clabernetes pod watch returned an error\"))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tpod, ok := ev.Object.(*corev1.Pod)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsendChangedLab(ctx, changed, labRef{\n\t\t\t\tnamespace: pod.Namespace,\n\t\t\t\tlab:       pod.Labels[labelTopologyOwner],\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc sleepContext(ctx context.Context, d time.Duration) bool {\n\ttimer := time.NewTimer(d)\n\tdefer timer.Stop()\n\n\tselect {\n\tcase <-timer.C:\n\t\treturn true\n\tcase <-ctx.Done():\n\t\treturn false\n\t}\n}\n\nfunc (r *Runtime) sendEvent(\n\tctx context.Context,\n\teventSink chan<- clablabruntime.Event,\n\tevent clablabruntime.Event,\n) {\n\tselect {\n\tcase eventSink <- event:\n\tcase <-ctx.Done():\n\t}\n}\n\nfunc sendEventError(ctx context.Context, errSink chan<- error, err error) {\n\tselect {\n\tcase errSink <- err:\n\tcase <-ctx.Done():\n\t}\n}",
        "lineStart": 1,
        "lineEnd": 393,
        "totalLines": 393,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525857177,
      "end": 1793525857194
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19678bbae001PRrREl4smyTkYp",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19678a805001A3Xi9IrNVARfXH",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 36175,
    "input": 14065,
    "output": 62,
    "reasoning": 288,
    "cache": {
      "read": 21760,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19678a805001A3Xi9IrNVARfXH",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525852165,
    "completed": 1793525857203
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 36175,
    "input": 14065,
    "output": 62,
    "reasoning": 288,
    "cache": {
      "read": 21760,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 28
step-start
{
  "type": "step-start",
  "id": "prt_19678c47e001lLaEqgneCR4JPO",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19678bbbc0011xL22dNjVSkkDT"
}
Reasoning
These files look clean. Remaining items to check:

1. reconcile.go hunk (lines ~200-230) and plan.go (line 56) and primitives.go (line 225) — topology source file annotation flows. Need to see where `req.TopologyFile` comes from and whether `Deploy` also records it. Let me check: does `Deploy` call setTopologySourceFile? Grep showed only plan.go:56 (setTopologySourceFile in plan stage). Is the plan used by Deploy? Likely `prepareDesiredDeployment`. Need to verify the Topology applied at deploy actually records the annotation — check Deploy in another file. Let me grep for `prepareDesiredDeployment` usage.

2. `containerFromLabNode` NodeType override — check core/labruntime.go 1-440 and where NodeType is set in the topology loader (types.NodeConfig). The `c.Nodes[topologyNode].Config()` — what is `c`? Let me read that part again carefully. Actually earlier summary said: "containerFromLabNode unconditionally overrides node.Type/group from loaded topology config (c.Nodes[topologyNode].Config())". Let me re-read core/labruntime.go around 440-560 to verify exactly.

3. Docs events.md, interfaces.md, runtime.md — spot check vs implementation.

4. Tests: parity_test.go, event_parity_test.go, labruntime_gaps_test.go, runtime_gaps_test.go, clabernetes_test.go (large), capture_test.go — check coverage of key new behavior.

5. Robot tests file.

6. Check `containerTracker` file fully (container_events.go rest) — the part not yet read.

Let me batch: grep prepareDesiredDeployment; read core/labruntime.go 430-560 (to verify containerFromLabNode) — actually already read 440-720; I need to re-derive the NodeType issue from actual code. Let me re-read lines 440-560 again to have fresh evidence.
The event wiring is sound. Now verify the deploy-side annotation flow and re-check `containerFromLabNode` in `core/labruntime.go`.
grep · completed

Input

{
  "path": "/source/head/labruntime/clabernetes",
  "pattern": "prepareDesiredDeployment|func \\(r \\*Runtime\\) Deploy|TopologyFile"
}

Output

Found 55 matches
/source/head/labruntime/clabernetes/files.go:
  Line 147: 	if req.TopologyFile != "" {

  Line 148: 		topologyFileDir := filepath.Dir(req.TopologyFile)

  Line 838: func setTopologyFilesFromConfigMaps(


/source/head/labruntime/clabernetes/plan.go:
  Line 27: func prepareDesiredDeployment(

  Line 56: 	setTopologySourceFile(desiredTopology, req.TopologyFile)

  Line 57: 	if err := setTopologyFilesFromConfigMaps(desiredTopology, stagedConfigMaps); err != nil {

  Line 152: 	_, err = prepareDesiredDeployment(ctx, req, namespace)

  Line 179: 	prepared, err := prepareDesiredDeployment(ctx, req, namespace)


/source/head/labruntime/clabernetes/manifests_test.go:
  Line 45: 		TopologyFile:       topologyFile,

  Line 348: 		TopologyFile:       topologyFile,


/source/head/labruntime/clabernetes/lifecycle.go:
  Line 22: func (r *Runtime) Deploy(

  Line 72: 	prepared, err := prepareDesiredDeployment(ctx, req, namespace)


/source/head/labruntime/clabernetes/event_parity_test.go:
  Line 803: 		TopologyFile:       path,

  Line 809: // TestDeployRecordsTheTopologyFile checks where a deploy records the topology file and that

  Line 811: func TestDeployRecordsTheTopologyFile(t *testing.T) {

  Line 821: 	if got := topology.GetAnnotations()[annotationTopologyFile]; got != "/home/alice/labs/lab1.clab.yml" {

  Line 838: 	if got := topology.GetAnnotations()[annotationTopologyFile]; got != "/srv/labs/lab1.clab.yml" {

  Line 848: 	assertPrimitiveTopologyFile(t, r, "/home/alice/labs/lab1.clab.yml")

  Line 872: 	assertPrimitiveTopologyFile(t, r, "/home/alice/labs/lab1.clab.yml")

  Line 875: func assertPrimitiveTopologyFile(t *testing.T, r *Runtime, want string) {

  Line 895: 			if got := list.Items[idx].GetAnnotations()[annotationTopologyFile]; got != gvr.want {

  Line 903: func TestCarryOverNodeTopologyFile(t *testing.T) {

  Line 917: 	desired := node(map[string]any{annotationTopologyFile: "/new.clab.yml"})

  Line 920: 		node(map[string]any{annotationTopologyFile: "/old.clab.yml"}),

  Line 923: 	if got := updated.GetAnnotations()[annotationTopologyFile]; got != "/old.clab.yml" {

  Line 930: 	if _, ok := updated.GetAnnotations()[annotationTopologyFile]; ok ||

  Line 941: 	if got := updated.GetAnnotations()[annotationTopologyFile]; got != "/new.clab.yml" {

  Line 946: func TestManifestsCarryNoTopologyFile(t *testing.T) {

  Line 957: 			if strings.Contains(string(data), annotationTopologyFile) {

  Line 965: func TestStateReportsTheRecordedTopologyFile(t *testing.T) {

  Line 988: 	nodes[0].SetAnnotations(map[string]string{annotationTopologyFile: "/home/alice/lab1.clab.yml"})


/source/head/labruntime/clabernetes/manifests.go:
  Line 38: 	prepared, err := prepareDesiredDeployment(ctx, req, namespace)


/source/head/labruntime/clabernetes/files_test.go:
  Line 57: 					Name: "lab1", TopologyFile: filepath.Join(topologyDir, "lab.clab.yml"),


/source/head/labruntime/clabernetes/state.go:
  Line 29: 		if path := nodeResources[idx].GetAnnotations()[annotationTopologyFile]; path != "" {


/source/head/labruntime/clabernetes/reconcile.go:
  Line 200: 	carryOverNodeTopologyFile(existing, updated)

  Line 205: // carryOverNodeTopologyFile keeps the topology file an existing Node recorded, or its absence.

  Line 210: func carryOverNodeTopologyFile(existing, updated *unstructured.Unstructured) {

  Line 215: 	path, found := existing.GetAnnotations()[annotationTopologyFile]


/source/head/labruntime/clabernetes/nodes_test.go:
  Line 780: 	prepared, err := prepareDesiredDeployment(context.Background(), req, "lab-ns")


/source/head/labruntime/clabernetes/topology.go:
  Line 17: // annotationTopologyFile records the absolute path of the topology file a lab was deployed from,

  Line 22: const annotationTopologyFile = "containerlab.dev/topo-file"

  Line 35: 	annotations[annotationTopologyFile] = path

  Line 42: 	if _, ok := annotations[annotationTopologyFile]; !ok {

  Line 46: 	delete(annotations, annotationTopologyFile)

  Line 56: 	if path := annotations[annotationTopologyFile]; path != "" {


/source/head/labruntime/clabernetes/clabernetes_test.go:
  Line 2130: 			TopologyFile:       filepath.Join(topologyDir, "lab.clab.yml"),

  Line 2196: 		TopologyFile:       topologyFile,

  Line 2266: 		TopologyFile:       topologyFile,

  Line 2336: 		TopologyFile:       topologyFile,

  Line 2451: 		TopologyFile:       topologyFile,

  Line 2475: func TestTargetNodesResolvesNodeNamesFromTheTopologyFile(t *testing.T) {

  Line 2843: 		TopologyFile:       topologyFile,

  Line 3128: 		TopologyFile:       topologyFile,

  Line 3329: 	prepared, err := prepareDesiredDeployment(context.Background(), clablabruntime.DeployRequest{

  Line 3450: 	prepared, err := prepareDesiredDeployment(context.Background(), clablabruntime.DeployRequest{
Tool metadata
{
  "type": "tool",
  "id": "prt_19678d3a4001iwig1SF2qTKK5N",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19678bbbc0011xL22dNjVSkkDT",
  "callID": "call_9aaf36c5d22a425e8cf17d81",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/labruntime/clabernetes",
      "pattern": "prepareDesiredDeployment|func \\(r \\*Runtime\\) Deploy|TopologyFile"
    },
    "output": "Found 55 matches\n/source/head/labruntime/clabernetes/files.go:\n  Line 147: \tif req.TopologyFile != \"\" {\n\n  Line 148: \t\ttopologyFileDir := filepath.Dir(req.TopologyFile)\n\n  Line 838: func setTopologyFilesFromConfigMaps(\n\n\n/source/head/labruntime/clabernetes/plan.go:\n  Line 27: func prepareDesiredDeployment(\n\n  Line 56: \tsetTopologySourceFile(desiredTopology, req.TopologyFile)\n\n  Line 57: \tif err := setTopologyFilesFromConfigMaps(desiredTopology, stagedConfigMaps); err != nil {\n\n  Line 152: \t_, err = prepareDesiredDeployment(ctx, req, namespace)\n\n  Line 179: \tprepared, err := prepareDesiredDeployment(ctx, req, namespace)\n\n\n/source/head/labruntime/clabernetes/manifests_test.go:\n  Line 45: \t\tTopologyFile:       topologyFile,\n\n  Line 348: \t\tTopologyFile:       topologyFile,\n\n\n/source/head/labruntime/clabernetes/lifecycle.go:\n  Line 22: func (r *Runtime) Deploy(\n\n  Line 72: \tprepared, err := prepareDesiredDeployment(ctx, req, namespace)\n\n\n/source/head/labruntime/clabernetes/event_parity_test.go:\n  Line 803: \t\tTopologyFile:       path,\n\n  Line 809: // TestDeployRecordsTheTopologyFile checks where a deploy records the topology file and that\n\n  Line 811: func TestDeployRecordsTheTopologyFile(t *testing.T) {\n\n  Line 821: \tif got := topology.GetAnnotations()[annotationTopologyFile]; got != \"/home/alice/labs/lab1.clab.yml\" {\n\n  Line 838: \tif got := topology.GetAnnotations()[annotationTopologyFile]; got != \"/srv/labs/lab1.clab.yml\" {\n\n  Line 848: \tassertPrimitiveTopologyFile(t, r, \"/home/alice/labs/lab1.clab.yml\")\n\n  Line 872: \tassertPrimitiveTopologyFile(t, r, \"/home/alice/labs/lab1.clab.yml\")\n\n  Line 875: func assertPrimitiveTopologyFile(t *testing.T, r *Runtime, want string) {\n\n  Line 895: \t\t\tif got := list.Items[idx].GetAnnotations()[annotationTopologyFile]; got != gvr.want {\n\n  Line 903: func TestCarryOverNodeTopologyFile(t *testing.T) {\n\n  Line 917: \tdesired := node(map[string]any{annotationTopologyFile: \"/new.clab.yml\"})\n\n  Line 920: \t\tnode(map[string]any{annotationTopologyFile: \"/old.clab.yml\"}),\n\n  Line 923: \tif got := updated.GetAnnotations()[annotationTopologyFile]; got != \"/old.clab.yml\" {\n\n  Line 930: \tif _, ok := updated.GetAnnotations()[annotationTopologyFile]; ok ||\n\n  Line 941: \tif got := updated.GetAnnotations()[annotationTopologyFile]; got != \"/new.clab.yml\" {\n\n  Line 946: func TestManifestsCarryNoTopologyFile(t *testing.T) {\n\n  Line 957: \t\t\tif strings.Contains(string(data), annotationTopologyFile) {\n\n  Line 965: func TestStateReportsTheRecordedTopologyFile(t *testing.T) {\n\n  Line 988: \tnodes[0].SetAnnotations(map[string]string{annotationTopologyFile: \"/home/alice/lab1.clab.yml\"})\n\n\n/source/head/labruntime/clabernetes/manifests.go:\n  Line 38: \tprepared, err := prepareDesiredDeployment(ctx, req, namespace)\n\n\n/source/head/labruntime/clabernetes/files_test.go:\n  Line 57: \t\t\t\t\tName: \"lab1\", TopologyFile: filepath.Join(topologyDir, \"lab.clab.yml\"),\n\n\n/source/head/labruntime/clabernetes/state.go:\n  Line 29: \t\tif path := nodeResources[idx].GetAnnotations()[annotationTopologyFile]; path != \"\" {\n\n\n/source/head/labruntime/clabernetes/reconcile.go:\n  Line 200: \tcarryOverNodeTopologyFile(existing, updated)\n\n  Line 205: // carryOverNodeTopologyFile keeps the topology file an existing Node recorded, or its absence.\n\n  Line 210: func carryOverNodeTopologyFile(existing, updated *unstructured.Unstructured) {\n\n  Line 215: \tpath, found := existing.GetAnnotations()[annotationTopologyFile]\n\n\n/source/head/labruntime/clabernetes/nodes_test.go:\n  Line 780: \tprepared, err := prepareDesiredDeployment(context.Background(), req, \"lab-ns\")\n\n\n/source/head/labruntime/clabernetes/topology.go:\n  Line 17: // annotationTopologyFile records the absolute path of the topology file a lab was deployed from,\n\n  Line 22: const annotationTopologyFile = \"containerlab.dev/topo-file\"\n\n  Line 35: \tannotations[annotationTopologyFile] = path\n\n  Line 42: \tif _, ok := annotations[annotationTopologyFile]; !ok {\n\n  Line 46: \tdelete(annotations, annotationTopologyFile)\n\n  Line 56: \tif path := annotations[annotationTopologyFile]; path != \"\" {\n\n\n/source/head/labruntime/clabernetes/clabernetes_test.go:\n  Line 2130: \t\t\tTopologyFile:       filepath.Join(topologyDir, \"lab.clab.yml\"),\n\n  Line 2196: \t\tTopologyFile:       topologyFile,\n\n  Line 2266: \t\tTopologyFile:       topologyFile,\n\n  Line 2336: \t\tTopologyFile:       topologyFile,\n\n  Line 2451: \t\tTopologyFile:       topologyFile,\n\n  Line 2475: func TestTargetNodesResolvesNodeNamesFromTheTopologyFile(t *testing.T) {\n\n  Line 2843: \t\tTopologyFile:       topologyFile,\n\n  Line 3128: \t\tTopologyFile:       topologyFile,\n\n  Line 3329: \tprepared, err := prepareDesiredDeployment(context.Background(), clablabruntime.DeployRequest{\n\n  Line 3450: \tprepared, err := prepareDesiredDeployment(context.Background(), clablabruntime.DeployRequest{\n",
    "title": "prepareDesiredDeployment|func \\(r \\*Runtime\\) Deploy|TopologyFile",
    "metadata": {
      "matches": 55,
      "truncated": false
    },
    "time": {
      "start": 1793525863337,
      "end": 1793525863350
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/core/labruntime.go",
  "limit": 130,
  "offset": 430
}

Output

<path>/source/head/core/labruntime.go</path>
<type>file</type>
<content>
430: 		}
431: 		sort.Strings(nodeNames)
432: 
433: 		nodes = make([]clablabruntime.NodeState, 0, len(nodeNames))
434: 		for _, nodeName := range nodeNames {
435: 			nodes = append(nodes, clablabruntime.NodeState{
436: 				Name:  nodeName,
437: 				Kind:  c.Config.Topology.GetNodeKind(nodeName),
438: 				Image: c.Config.Topology.GetNodeImage(nodeName),
439: 				State: state.State,
440: 				Ready: state.Ready,
441: 			})
442: 		}
443: 	}
444: 
445: 	containers := make([]clabruntime.GenericContainer, 0, len(nodes))
446: 	for _, node := range nodes {
447: 		containers = append(containers, c.containerFromLabNode(state, node))
448: 	}
449: 
450: 	return containers
451: }
452: 
453: // LabRuntimeContainer describes a lab runtime node as a container record, the way inspect
454: // reports it. The events command describes lab runtime nodes with it too.
455: func (c *CLab) LabRuntimeContainer(
456: 	state *clablabruntime.LabState,
457: 	node clablabruntime.NodeState,
458: ) clabruntime.GenericContainer {
459: 	return c.containerFromLabNode(state, node)
460: }
461: 
462: func (c *CLab) containerFromLabNode(
463: 	state *clablabruntime.LabState,
464: 	node clablabruntime.NodeState,
465: ) clabruntime.GenericContainer {
466: 	nodeName := fmt.Sprintf("%s-%s", state.Name, node.Name)
467: 	containerState, containerStatus := labRuntimeContainerState(state, node)
468: 
469: 	topologyNode := node.Name
470: 	if node.TopologyName != "" {
471: 		topologyNode = node.TopologyName
472: 	}
473: 	if c.Config.Topology != nil {
474: 		topologyNode = c.topologyNodeName(topologyNode)
475: 	}
476: 
477: 	labels := map[string]string{
478: 		clabconstants.Containerlab: state.Name,
479: 		clabconstants.NodeName:     topologyNode,
480: 		clabconstants.LongName:     nodeName,
481: 		clabconstants.TopoFile:     labRuntimeTopologyPath(c, state),
482: 	}
483: 
484: 	var image string
485: 	if c.Config.Topology != nil {
486: 		labels[clabconstants.NodeKind] = c.Config.Topology.GetNodeKind(topologyNode)
487: 		image = c.Config.Topology.GetNodeImage(topologyNode)
488: 	}
489: 	if node.Kind != "" {
490: 		labels[clabconstants.NodeKind] = node.Kind
491: 	}
492: 	if node.Image != "" {
493: 		image = node.Image
494: 	}
495: 
496: 	// The node's type and group: from the loaded topology's node, with the kind's defaults the
497: 	// local runtimes report too, otherwise as the topology set them on the runtime's node.
498: 	nodeType, group := node.Type, node.Group
499: 	if topologyNodeConfig, ok := c.Nodes[topologyNode]; ok {
500: 		nodeType, group = topologyNodeConfig.Config().NodeType, topologyNodeConfig.Config().Group
501: 	} else if c.Config.Topology != nil && group == "" {
502: 		group = c.Config.Topology.GetNodeGroup(topologyNode)
503: 	}
504: 	if nodeType != "" {
505: 		labels[clabconstants.NodeType] = nodeType
506: 	}
507: 	if group != "" {
508: 		labels[clabconstants.NodeGroup] = group
509: 	}
510: 
511: 	if state.Owner != "" {
512: 		labels[clabconstants.Owner] = state.Owner
513: 	} else if c.customOwner != "" {
514: 		labels[clabconstants.Owner] = c.customOwner
515: 	}
516: 
517: 	// The ID names the node uniquely across namespaces and labs. It is also the short ID, so
518: 	// inspect reports it as container_id and it matches the events actor ID.
519: 	id := labRuntimeContainerID(state.Namespace, state.Name, node.Name)
520: 
521: 	return clabruntime.GenericContainer{
522: 		Names:           []string{nodeName},
523: 		ID:              id,
524: 		ShortID:         id,
525: 		Image:           image,
526: 		State:           containerState,
527: 		Status:          containerStatus,
528: 		Labels:          labels,
529: 		NetworkName:     state.Namespace,
530: 		NetworkSettings: managementAddress(node),
531: 		Ports:           labRuntimePorts(node.ExposedPorts),
532: 		Workload: &clabtypes.LabRuntimeWorkload{
533: 			Namespace:           state.Namespace,
534: 			Pod:                 node.Pod,
535: 			Container:           node.Container,
536: 			NodeUID:             node.NodeUID,
537: 			ExposedPorts:        node.ExposedPorts,
538: 			LoadBalancerAddress: node.LoadBalancerAddress,
539: 		},
540: 	}
541: }
542: 
543: // labRuntimeContainerState is a lab runtime node's state and status in the vocabulary of the
544: // container runtimes: state created, running or exited; status healthy or "health: starting"
545: // for a running node, as inspect shortens a Docker status line with a healthcheck, Created or
546: // Exited otherwise. A runtime that reports no container state keeps its own state.
547: func labRuntimeContainerState(
548: 	state *clablabruntime.LabState,
549: 	node clablabruntime.NodeState,
550: ) (string, string) {
551: 	switch node.ContainerState {
552: 	case clablabruntime.ContainerStateRunning:
553: 		if node.Health == clablabruntime.ContainerHealthHealthy {
554: 			return node.ContainerState, "healthy"
555: 		}
556: 
557: 		return node.ContainerState, "health: starting"
558: 	case clablabruntime.ContainerStateCreated:
559: 		return node.ContainerState, "Created"

(Showing lines 430-559 of 827. Use offset=560 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19678d497001j8HnaNpZpb34wo",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19678bbbc0011xL22dNjVSkkDT",
  "callID": "call_ad4ca783b87d484a9c15ab1d",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/labruntime.go",
      "limit": 130,
      "offset": 430
    },
    "output": "<path>/source/head/core/labruntime.go</path>\n<type>file</type>\n<content>\n430: \t\t}\n431: \t\tsort.Strings(nodeNames)\n432: \n433: \t\tnodes = make([]clablabruntime.NodeState, 0, len(nodeNames))\n434: \t\tfor _, nodeName := range nodeNames {\n435: \t\t\tnodes = append(nodes, clablabruntime.NodeState{\n436: \t\t\t\tName:  nodeName,\n437: \t\t\t\tKind:  c.Config.Topology.GetNodeKind(nodeName),\n438: \t\t\t\tImage: c.Config.Topology.GetNodeImage(nodeName),\n439: \t\t\t\tState: state.State,\n440: \t\t\t\tReady: state.Ready,\n441: \t\t\t})\n442: \t\t}\n443: \t}\n444: \n445: \tcontainers := make([]clabruntime.GenericContainer, 0, len(nodes))\n446: \tfor _, node := range nodes {\n447: \t\tcontainers = append(containers, c.containerFromLabNode(state, node))\n448: \t}\n449: \n450: \treturn containers\n451: }\n452: \n453: // LabRuntimeContainer describes a lab runtime node as a container record, the way inspect\n454: // reports it. The events command describes lab runtime nodes with it too.\n455: func (c *CLab) LabRuntimeContainer(\n456: \tstate *clablabruntime.LabState,\n457: \tnode clablabruntime.NodeState,\n458: ) clabruntime.GenericContainer {\n459: \treturn c.containerFromLabNode(state, node)\n460: }\n461: \n462: func (c *CLab) containerFromLabNode(\n463: \tstate *clablabruntime.LabState,\n464: \tnode clablabruntime.NodeState,\n465: ) clabruntime.GenericContainer {\n466: \tnodeName := fmt.Sprintf(\"%s-%s\", state.Name, node.Name)\n467: \tcontainerState, containerStatus := labRuntimeContainerState(state, node)\n468: \n469: \ttopologyNode := node.Name\n470: \tif node.TopologyName != \"\" {\n471: \t\ttopologyNode = node.TopologyName\n472: \t}\n473: \tif c.Config.Topology != nil {\n474: \t\ttopologyNode = c.topologyNodeName(topologyNode)\n475: \t}\n476: \n477: \tlabels := map[string]string{\n478: \t\tclabconstants.Containerlab: state.Name,\n479: \t\tclabconstants.NodeName:     topologyNode,\n480: \t\tclabconstants.LongName:     nodeName,\n481: \t\tclabconstants.TopoFile:     labRuntimeTopologyPath(c, state),\n482: \t}\n483: \n484: \tvar image string\n485: \tif c.Config.Topology != nil {\n486: \t\tlabels[clabconstants.NodeKind] = c.Config.Topology.GetNodeKind(topologyNode)\n487: \t\timage = c.Config.Topology.GetNodeImage(topologyNode)\n488: \t}\n489: \tif node.Kind != \"\" {\n490: \t\tlabels[clabconstants.NodeKind] = node.Kind\n491: \t}\n492: \tif node.Image != \"\" {\n493: \t\timage = node.Image\n494: \t}\n495: \n496: \t// The node's type and group: from the loaded topology's node, with the kind's defaults the\n497: \t// local runtimes report too, otherwise as the topology set them on the runtime's node.\n498: \tnodeType, group := node.Type, node.Group\n499: \tif topologyNodeConfig, ok := c.Nodes[topologyNode]; ok {\n500: \t\tnodeType, group = topologyNodeConfig.Config().NodeType, topologyNodeConfig.Config().Group\n501: \t} else if c.Config.Topology != nil && group == \"\" {\n502: \t\tgroup = c.Config.Topology.GetNodeGroup(topologyNode)\n503: \t}\n504: \tif nodeType != \"\" {\n505: \t\tlabels[clabconstants.NodeType] = nodeType\n506: \t}\n507: \tif group != \"\" {\n508: \t\tlabels[clabconstants.NodeGroup] = group\n509: \t}\n510: \n511: \tif state.Owner != \"\" {\n512: \t\tlabels[clabconstants.Owner] = state.Owner\n513: \t} else if c.customOwner != \"\" {\n514: \t\tlabels[clabconstants.Owner] = c.customOwner\n515: \t}\n516: \n517: \t// The ID names the node uniquely across namespaces and labs. It is also the short ID, so\n518: \t// inspect reports it as container_id and it matches the events actor ID.\n519: \tid := labRuntimeContainerID(state.Namespace, state.Name, node.Name)\n520: \n521: \treturn clabruntime.GenericContainer{\n522: \t\tNames:           []string{nodeName},\n523: \t\tID:              id,\n524: \t\tShortID:         id,\n525: \t\tImage:           image,\n526: \t\tState:           containerState,\n527: \t\tStatus:          containerStatus,\n528: \t\tLabels:          labels,\n529: \t\tNetworkName:     state.Namespace,\n530: \t\tNetworkSettings: managementAddress(node),\n531: \t\tPorts:           labRuntimePorts(node.ExposedPorts),\n532: \t\tWorkload: &clabtypes.LabRuntimeWorkload{\n533: \t\t\tNamespace:           state.Namespace,\n534: \t\t\tPod:                 node.Pod,\n535: \t\t\tContainer:           node.Container,\n536: \t\t\tNodeUID:             node.NodeUID,\n537: \t\t\tExposedPorts:        node.ExposedPorts,\n538: \t\t\tLoadBalancerAddress: node.LoadBalancerAddress,\n539: \t\t},\n540: \t}\n541: }\n542: \n543: // labRuntimeContainerState is a lab runtime node's state and status in the vocabulary of the\n544: // container runtimes: state created, running or exited; status healthy or \"health: starting\"\n545: // for a running node, as inspect shortens a Docker status line with a healthcheck, Created or\n546: // Exited otherwise. A runtime that reports no container state keeps its own state.\n547: func labRuntimeContainerState(\n548: \tstate *clablabruntime.LabState,\n549: \tnode clablabruntime.NodeState,\n550: ) (string, string) {\n551: \tswitch node.ContainerState {\n552: \tcase clablabruntime.ContainerStateRunning:\n553: \t\tif node.Health == clablabruntime.ContainerHealthHealthy {\n554: \t\t\treturn node.ContainerState, \"healthy\"\n555: \t\t}\n556: \n557: \t\treturn node.ContainerState, \"health: starting\"\n558: \tcase clablabruntime.ContainerStateCreated:\n559: \t\treturn node.ContainerState, \"Created\"\n\n(Showing lines 430-559 of 827. Use offset=560 to continue.)\n</content>",
    "title": "source/head/core/labruntime.go",
    "metadata": {
      "preview": "\t\t}\n\t\tsort.Strings(nodeNames)\n\n\t\tnodes = make([]clablabruntime.NodeState, 0, len(nodeNames))\n\t\tfor _, nodeName := range nodeNames {\n\t\t\tnodes = append(nodes, clablabruntime.NodeState{\n\t\t\t\tName:  nodeName,\n\t\t\t\tKind:  c.Config.Topology.GetNodeKind(nodeName),\n\t\t\t\tImage: c.Config.Topology.GetNodeImage(nodeName),\n\t\t\t\tState: state.State,\n\t\t\t\tReady: state.Ready,\n\t\t\t})\n\t\t}\n\t}\n\n\tcontainers := make([]clabruntime.GenericContainer, 0, len(nodes))\n\tfor _, node := range nodes {\n\t\tcontainers = append(containers, c.containerFromLabNode(state, node))\n\t}\n",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/labruntime.go",
        "text": "\t\t}\n\t\tsort.Strings(nodeNames)\n\n\t\tnodes = make([]clablabruntime.NodeState, 0, len(nodeNames))\n\t\tfor _, nodeName := range nodeNames {\n\t\t\tnodes = append(nodes, clablabruntime.NodeState{\n\t\t\t\tName:  nodeName,\n\t\t\t\tKind:  c.Config.Topology.GetNodeKind(nodeName),\n\t\t\t\tImage: c.Config.Topology.GetNodeImage(nodeName),\n\t\t\t\tState: state.State,\n\t\t\t\tReady: state.Ready,\n\t\t\t})\n\t\t}\n\t}\n\n\tcontainers := make([]clabruntime.GenericContainer, 0, len(nodes))\n\tfor _, node := range nodes {\n\t\tcontainers = append(containers, c.containerFromLabNode(state, node))\n\t}\n\n\treturn containers\n}\n\n// LabRuntimeContainer describes a lab runtime node as a container record, the way inspect\n// reports it. The events command describes lab runtime nodes with it too.\nfunc (c *CLab) LabRuntimeContainer(\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n) clabruntime.GenericContainer {\n\treturn c.containerFromLabNode(state, node)\n}\n\nfunc (c *CLab) containerFromLabNode(\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n) clabruntime.GenericContainer {\n\tnodeName := fmt.Sprintf(\"%s-%s\", state.Name, node.Name)\n\tcontainerState, containerStatus := labRuntimeContainerState(state, node)\n\n\ttopologyNode := node.Name\n\tif node.TopologyName != \"\" {\n\t\ttopologyNode = node.TopologyName\n\t}\n\tif c.Config.Topology != nil {\n\t\ttopologyNode = c.topologyNodeName(topologyNode)\n\t}\n\n\tlabels := map[string]string{\n\t\tclabconstants.Containerlab: state.Name,\n\t\tclabconstants.NodeName:     topologyNode,\n\t\tclabconstants.LongName:     nodeName,\n\t\tclabconstants.TopoFile:     labRuntimeTopologyPath(c, state),\n\t}\n\n\tvar image string\n\tif c.Config.Topology != nil {\n\t\tlabels[clabconstants.NodeKind] = c.Config.Topology.GetNodeKind(topologyNode)\n\t\timage = c.Config.Topology.GetNodeImage(topologyNode)\n\t}\n\tif node.Kind != \"\" {\n\t\tlabels[clabconstants.NodeKind] = node.Kind\n\t}\n\tif node.Image != \"\" {\n\t\timage = node.Image\n\t}\n\n\t// The node's type and group: from the loaded topology's node, with the kind's defaults the\n\t// local runtimes report too, otherwise as the topology set them on the runtime's node.\n\tnodeType, group := node.Type, node.Group\n\tif topologyNodeConfig, ok := c.Nodes[topologyNode]; ok {\n\t\tnodeType, group = topologyNodeConfig.Config().NodeType, topologyNodeConfig.Config().Group\n\t} else if c.Config.Topology != nil && group == \"\" {\n\t\tgroup = c.Config.Topology.GetNodeGroup(topologyNode)\n\t}\n\tif nodeType != \"\" {\n\t\tlabels[clabconstants.NodeType] = nodeType\n\t}\n\tif group != \"\" {\n\t\tlabels[clabconstants.NodeGroup] = group\n\t}\n\n\tif state.Owner != \"\" {\n\t\tlabels[clabconstants.Owner] = state.Owner\n\t} else if c.customOwner != \"\" {\n\t\tlabels[clabconstants.Owner] = c.customOwner\n\t}\n\n\t// The ID names the node uniquely across namespaces and labs. It is also the short ID, so\n\t// inspect reports it as container_id and it matches the events actor ID.\n\tid := labRuntimeContainerID(state.Namespace, state.Name, node.Name)\n\n\treturn clabruntime.GenericContainer{\n\t\tNames:           []string{nodeName},\n\t\tID:              id,\n\t\tShortID:         id,\n\t\tImage:           image,\n\t\tState:           containerState,\n\t\tStatus:          containerStatus,\n\t\tLabels:          labels,\n\t\tNetworkName:     state.Namespace,\n\t\tNetworkSettings: managementAddress(node),\n\t\tPorts:           labRuntimePorts(node.ExposedPorts),\n\t\tWorkload: &clabtypes.LabRuntimeWorkload{\n\t\t\tNamespace:           state.Namespace,\n\t\t\tPod:                 node.Pod,\n\t\t\tContainer:           node.Container,\n\t\t\tNodeUID:             node.NodeUID,\n\t\t\tExposedPorts:        node.ExposedPorts,\n\t\t\tLoadBalancerAddress: node.LoadBalancerAddress,\n\t\t},\n\t}\n}\n\n// labRuntimeContainerState is a lab runtime node's state and status in the vocabulary of the\n// container runtimes: state created, running or exited; status healthy or \"health: starting\"\n// for a running node, as inspect shortens a Docker status line with a healthcheck, Created or\n// Exited otherwise. A runtime that reports no container state keeps its own state.\nfunc labRuntimeContainerState(\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n) (string, string) {\n\tswitch node.ContainerState {\n\tcase clablabruntime.ContainerStateRunning:\n\t\tif node.Health == clablabruntime.ContainerHealthHealthy {\n\t\t\treturn node.ContainerState, \"healthy\"\n\t\t}\n\n\t\treturn node.ContainerState, \"health: starting\"\n\tcase clablabruntime.ContainerStateCreated:\n\t\treturn node.ContainerState, \"Created\"",
        "lineStart": 430,
        "lineEnd": 559,
        "totalLines": 827,
        "truncated": true
      }
    },
    "time": {
      "start": 1793525863581,
      "end": 1793525863594
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19678d4ad001uNTgiDzSu4ercK",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19678bbbc0011xL22dNjVSkkDT",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 48605,
    "input": 12004,
    "output": 92,
    "reasoning": 413,
    "cache": {
      "read": 36096,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19678bbbc0011xL22dNjVSkkDT",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525857212,
    "completed": 1793525863601
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 48605,
    "input": 12004,
    "output": 92,
    "reasoning": 413,
    "cache": {
      "read": 36096,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 29
step-start
{
  "type": "step-start",
  "id": "prt_19679068b001WhJMFnOe4AEFn2",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19678d4bc001256K3UF28WCH06"
}
Reasoning
containerFromLabNode logic: if `c.Nodes[topologyNode]` exists, it uses the config's NodeType and Group. Note: if `c.Nodes` has the node but its config's `NodeType` is empty (e.g., topology edited or default type not resolved), this overrides `node.Type` with "". Wait — it sets `nodeType, group = ...` only if `ok`. If `topologyNodeConfig.Config().NodeType == ""` then nodeType becomes "" and the label is dropped even if `node.Type` (from runtime state) had a value. Is that intended? The comment says: "The node's type and group: from the loaded topology's node, with the kind's defaults the local runtimes report too, otherwise as the topology set them on the runtime's node." So when the loaded topology is present, its values win — including an empty NodeType (labels omit). But wait: the local runtimes report the kind's default type; for c9s byName mode with `-t`, node.Type comes from the runtime (state.go reads spec.type which the controller set from the topology). If the user runs `events -t other.clab.yml` where the node type differs, the loaded topology wins — that's documented behavior ("read by --name alone, a default type such as SR Linux's ixr-d2l is not known"). Hmm, but if c.Nodes[topologyNode] exists with empty NodeType (e.g., the topology file uses `kind: srl` without explicit type, and default type resolution happens... actually in containerlab, `NodeType` in NodeConfig is set from the kind's default during config load? Let me check: `c.Nodes[topologyNode].Config().NodeType` — for srl nodes, the default type is set by the node kind's Init or by `GetShortLink`? In containerlab, `NodeConfig.NodeType` is populated from the topology node's `type` attribute; if not set, it may be empty, and the default type is applied by the node kind implementation when generating config (e.g., srl sets `node.NodeType = ...`?). Actually in containerlab, for SR Linux, `type` defaults are resolved in the srl node's `Init` via `node.NodeType = types.DurationOr...`? I recall srl sets `node.NodeType` in `Init()` when empty to the kind default (e.g., "ixr-d2l" no... default is "ixrd2"?). Let me check quickly in the repo: grep for `NodeType =` in nodes/ or types.

The docs say: "with -t also a kind's default type; read by --name alone, a default type such as SR Linux's ixr-d2l is not known." So with `-t`, default type IS reported. That implies `c.Nodes[topologyNode].Config().NodeType` is non-empty after loading (the kind's default was applied). So the override to empty wouldn't occur with -t. If nodeType were empty in config (unusual kinds), label omitted — but then the local runtimes also omit it? For docker, the label `clab-node-type` is set from node.Config().NodeType... need to check. This is fine; the behavior matches documentation. I'll downgrade this candidate to not-a-finding, or maybe P4 note about empty override dropping runtime-provided type. Let me quickly verify how docker runtime sets the type label. Actually, checking is cheap: grep for NodeType label setting.

Also check `managementAddress` for CIDR parity: docker's `GetContainerIPv4` returns addr like "172.20.20.2/24"? Let me check the docker runtime. In containerlab, mgmt IPv4 in inspect is shown with netmask (e.g., 172.20.20.2/24). managementAddress returns `node.MgmtIPv4Address` raw from status.directManagement.ipv4 — the controller sets it presumably as "172.20.20.x/24"? The diff for runtime.md may document. The event attribute mgmt_ipv4 — docker events carry mgmt_ipv4 as the address with /24? Let me check how the events command builds mgmt_ipv4: probably from container.NetworkSettings.IPv4addr. In GenericContainer.NetworkSettings is clabruntime.NetworkSettings with IPv4addr. For docker, NetworkSettings.IPv4addr is set to the address including netmask? In containerlab docker runtime, `GetContainerIPv4` returns e.g. "172.20.20.2/24" (I believe it includes the CIDR). Let me grep.

Let me do these greps plus read container_events.go fully (the part I haven't), and the tests.
`containerFromLabNode` semantics match the docs. Let me verify the type-label parity and the mgmt address format against the Docker runtime.
grep · completed

Input

{
  "path": "/source/head",
  "pattern": "NodeType\\] = |clab-node-type",
  "include": "*.go"
}

Output

Found 5 matches
/source/head/constants/labels.go:
  Line 8: 	NodeType         = "clab-node-type"


/source/head/nodes/sros/netns.go:
  Line 48: 	labels[clabconstants.NodeType] = "srsim-netns"


/source/head/core/labruntime_gaps_test.go:
  Line 144: 		"clab-node-type":     "ixr-h2",


/source/head/core/labruntime.go:
  Line 505: 		labels[clabconstants.NodeType] = nodeType


/source/head/core/config.go:
  Line 874: 	cfg.Labels[clabconstants.NodeType] = cfg.NodeType
Tool metadata
{
  "type": "tool",
  "id": "prt_1967928fb001V3jpxPEqfZXxXs",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19678d4bc001256K3UF28WCH06",
  "callID": "call_4618da8924c64178a5edaa04",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head",
      "pattern": "NodeType\\] = |clab-node-type",
      "include": "*.go"
    },
    "output": "Found 5 matches\n/source/head/constants/labels.go:\n  Line 8: \tNodeType         = \"clab-node-type\"\n\n\n/source/head/nodes/sros/netns.go:\n  Line 48: \tlabels[clabconstants.NodeType] = \"srsim-netns\"\n\n\n/source/head/core/labruntime_gaps_test.go:\n  Line 144: \t\t\"clab-node-type\":     \"ixr-h2\",\n\n\n/source/head/core/labruntime.go:\n  Line 505: \t\tlabels[clabconstants.NodeType] = nodeType\n\n\n/source/head/core/config.go:\n  Line 874: \tcfg.Labels[clabconstants.NodeType] = cfg.NodeType\n",
    "title": "NodeType\\] = |clab-node-type",
    "metadata": {
      "matches": 5,
      "truncated": false
    },
    "time": {
      "start": 1793525885185,
      "end": 1793525885205
    }
  }
}
grep · completed

Input

{
  "path": "/source/head",
  "pattern": "IPv4addr = |func.*GetContainerIPv4",
  "include": "*.go"
}

Output

Found 5 matches
/source/head/nodes/sros/sros.go:
  Line 1197: 				cnts[0].NetworkSettings.IPv4addr = ips.IPv4


/source/head/core/labruntime.go:
  Line 625: 			settings.IPv4addr = node.LoadBalancerAddress


/source/head/runtime/generic_container.go:
  Line 61: func (ctr *GenericContainer) GetContainerIPv4() string {


/source/head/runtime/docker/docker.go:
  Line 1636: 			ctr.NetworkSettings.IPv4addr = ifcfg.IPAddress

  Line 1638: 				ctr.NetworkSettings.IPv4addr = ifcfg.IPAMConfig.IPv4Address
Tool metadata
{
  "type": "tool",
  "id": "prt_1967929d6001lYMbOD5Njs8xlu",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19678d4bc001256K3UF28WCH06",
  "callID": "call_8069fdc7d84d41749b8f0586",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head",
      "pattern": "IPv4addr = |func.*GetContainerIPv4",
      "include": "*.go"
    },
    "output": "Found 5 matches\n/source/head/nodes/sros/sros.go:\n  Line 1197: \t\t\t\tcnts[0].NetworkSettings.IPv4addr = ips.IPv4\n\n\n/source/head/core/labruntime.go:\n  Line 625: \t\t\tsettings.IPv4addr = node.LoadBalancerAddress\n\n\n/source/head/runtime/generic_container.go:\n  Line 61: func (ctr *GenericContainer) GetContainerIPv4() string {\n\n\n/source/head/runtime/docker/docker.go:\n  Line 1636: \t\t\tctr.NetworkSettings.IPv4addr = ifcfg.IPAddress\n\n  Line 1638: \t\t\t\tctr.NetworkSettings.IPv4addr = ifcfg.IPAMConfig.IPv4Address\n",
    "title": "IPv4addr = |func.*GetContainerIPv4",
    "metadata": {
      "matches": 5,
      "truncated": false
    },
    "time": {
      "start": 1793525885403,
      "end": 1793525885423
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1967929f3001DJ7NKFDsfjD1o6",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19678d4bc001256K3UF28WCH06",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 52578,
    "input": 3112,
    "output": 94,
    "reasoning": 988,
    "cache": {
      "read": 48384,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19678d4bc001256K3UF28WCH06",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525863612,
    "completed": 1793525885432
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 52578,
    "input": 3112,
    "output": 94,
    "reasoning": 988,
    "cache": {
      "read": 48384,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 30
step-start
{
  "type": "step-start",
  "id": "prt_19679321a001KNisspjxu3fzHc",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196792a02001YELDRAg4r2EIiY"
}
read · completed

Input

{
  "filePath": "/source/head/core/labruntime.go",
  "limit": 110,
  "offset": 590
}

Output

<path>/source/head/core/labruntime.go</path>
<type>file</type>
<content>
590: 	return bindings
591: }
592: 
593: // labRuntimeContainerID is the ID of a lab runtime node: <namespace>/<lab>/<node>.
594: func labRuntimeContainerID(namespace, lab, node string) string {
595: 	return fmt.Sprintf("%s/%s/%s", namespace, lab, node)
596: }
597: 
598: // topologyNodeName maps a node name a lab runtime reports back onto the topology node it belongs
599: // to. The runtime renames the nodes Kubernetes cannot carry, so the state it reports does not
600: // always use the name the topology file wrote.
601: func (c *CLab) topologyNodeName(name string) string {
602: 	if c.Config.Topology == nil {
603: 		return name
604: 	}
605: 	if _, ok := c.Config.Topology.Nodes[name]; ok {
606: 		return name
607: 	}
608: 
609: 	for nodeName := range c.Config.Topology.Nodes {
610: 		if clabnames.SanitizeName(nodeName) == name {
611: 			return nodeName
612: 		}
613: 	}
614: 
615: 	return name
616: }
617: 
618: // managementAddress reports the address a user reaches the node at: the LoadBalancer address
619: // when the node is exposed, otherwise the allocated management address.
620: func managementAddress(node clablabruntime.NodeState) clabruntime.GenericMgmtIPs {
621: 	settings := clabruntime.GenericMgmtIPs{}
622: 
623: 	if ip := net.ParseIP(node.LoadBalancerAddress); ip != nil {
624: 		if ip.To4() != nil {
625: 			settings.IPv4addr = node.LoadBalancerAddress
626: 			settings.IPv4pLen = 32
627: 		} else {
628: 			settings.IPv6addr = node.LoadBalancerAddress
629: 			settings.IPv6pLen = 128
630: 		}
631: 	}
632: 
633: 	if settings.IPv4addr == "" {
634: 		settings.IPv4addr, settings.IPv4pLen = splitManagementCIDR(node.MgmtIPv4Address)
635: 	}
636: 	if settings.IPv6addr == "" {
637: 		settings.IPv6addr, settings.IPv6pLen = splitManagementCIDR(node.MgmtIPv6Address)
638: 	}
639: 
640: 	return settings
641: }
642: 
643: func splitManagementCIDR(cidr string) (string, int) {
644: 	if cidr == "" {
645: 		return "", 0
646: 	}
647: 
648: 	ip, network, err := net.ParseCIDR(cidr)
649: 	if err != nil {
650: 		if net.ParseIP(cidr) != nil {
651: 			return cidr, 0
652: 		}
653: 
654: 		return "", 0
655: 	}
656: 
657: 	prefixLen, _ := network.Mask.Size()
658: 
659: 	return ip.String(), prefixLen
660: }
661: 
662: func labRuntimeTopologyPath(c *CLab, state *clablabruntime.LabState) string {
663: 	if c.TopoPaths.TopologyFileIsSet() {
664: 		return c.TopoPaths.TopologyFilenameAbsPath()
665: 	}
666: 
667: 	if state.TopologyPath != "" {
668: 		return state.TopologyPath
669: 	}
670: 
671: 	return fmt.Sprintf("k8s://%s/topologies/%s", state.Namespace, state.Name)
672: }
673: 
674: func labRuntimeContainerParts(c clabruntime.GenericContainer) (string, string, string, error) {
675: 	parts := strings.Split(c.ID, "/")
676: 	if len(parts) != 3 {
677: 		return "", "", "", fmt.Errorf("expected namespace/lab/node id, got %q", c.ID)
678: 	}
679: 
680: 	return parts[0], parts[1], parts[2], nil
681: }
682: 
683: func filterLabRuntimeContainers(
684: 	containers []clabruntime.GenericContainer,
685: 	filters []*clabtypes.GenericFilter,
686: ) []clabruntime.GenericContainer {
687: 	if len(filters) == 0 {
688: 		return containers
689: 	}
690: 
691: 	filtered := make([]clabruntime.GenericContainer, 0, len(containers))
692: 	for _, container := range containers {
693: 		if labRuntimeContainerMatches(container, filters) {
694: 			filtered = append(filtered, container)
695: 		}
696: 	}
697: 
698: 	return filtered
699: }

(Showing lines 590-699 of 827. Use offset=700 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196793297001k9uHduq2Of0RJQ",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196792a02001YELDRAg4r2EIiY",
  "callID": "call_dd613378a0ab4e6296dffde2",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/labruntime.go",
      "limit": 110,
      "offset": 590
    },
    "output": "<path>/source/head/core/labruntime.go</path>\n<type>file</type>\n<content>\n590: \treturn bindings\n591: }\n592: \n593: // labRuntimeContainerID is the ID of a lab runtime node: <namespace>/<lab>/<node>.\n594: func labRuntimeContainerID(namespace, lab, node string) string {\n595: \treturn fmt.Sprintf(\"%s/%s/%s\", namespace, lab, node)\n596: }\n597: \n598: // topologyNodeName maps a node name a lab runtime reports back onto the topology node it belongs\n599: // to. The runtime renames the nodes Kubernetes cannot carry, so the state it reports does not\n600: // always use the name the topology file wrote.\n601: func (c *CLab) topologyNodeName(name string) string {\n602: \tif c.Config.Topology == nil {\n603: \t\treturn name\n604: \t}\n605: \tif _, ok := c.Config.Topology.Nodes[name]; ok {\n606: \t\treturn name\n607: \t}\n608: \n609: \tfor nodeName := range c.Config.Topology.Nodes {\n610: \t\tif clabnames.SanitizeName(nodeName) == name {\n611: \t\t\treturn nodeName\n612: \t\t}\n613: \t}\n614: \n615: \treturn name\n616: }\n617: \n618: // managementAddress reports the address a user reaches the node at: the LoadBalancer address\n619: // when the node is exposed, otherwise the allocated management address.\n620: func managementAddress(node clablabruntime.NodeState) clabruntime.GenericMgmtIPs {\n621: \tsettings := clabruntime.GenericMgmtIPs{}\n622: \n623: \tif ip := net.ParseIP(node.LoadBalancerAddress); ip != nil {\n624: \t\tif ip.To4() != nil {\n625: \t\t\tsettings.IPv4addr = node.LoadBalancerAddress\n626: \t\t\tsettings.IPv4pLen = 32\n627: \t\t} else {\n628: \t\t\tsettings.IPv6addr = node.LoadBalancerAddress\n629: \t\t\tsettings.IPv6pLen = 128\n630: \t\t}\n631: \t}\n632: \n633: \tif settings.IPv4addr == \"\" {\n634: \t\tsettings.IPv4addr, settings.IPv4pLen = splitManagementCIDR(node.MgmtIPv4Address)\n635: \t}\n636: \tif settings.IPv6addr == \"\" {\n637: \t\tsettings.IPv6addr, settings.IPv6pLen = splitManagementCIDR(node.MgmtIPv6Address)\n638: \t}\n639: \n640: \treturn settings\n641: }\n642: \n643: func splitManagementCIDR(cidr string) (string, int) {\n644: \tif cidr == \"\" {\n645: \t\treturn \"\", 0\n646: \t}\n647: \n648: \tip, network, err := net.ParseCIDR(cidr)\n649: \tif err != nil {\n650: \t\tif net.ParseIP(cidr) != nil {\n651: \t\t\treturn cidr, 0\n652: \t\t}\n653: \n654: \t\treturn \"\", 0\n655: \t}\n656: \n657: \tprefixLen, _ := network.Mask.Size()\n658: \n659: \treturn ip.String(), prefixLen\n660: }\n661: \n662: func labRuntimeTopologyPath(c *CLab, state *clablabruntime.LabState) string {\n663: \tif c.TopoPaths.TopologyFileIsSet() {\n664: \t\treturn c.TopoPaths.TopologyFilenameAbsPath()\n665: \t}\n666: \n667: \tif state.TopologyPath != \"\" {\n668: \t\treturn state.TopologyPath\n669: \t}\n670: \n671: \treturn fmt.Sprintf(\"k8s://%s/topologies/%s\", state.Namespace, state.Name)\n672: }\n673: \n674: func labRuntimeContainerParts(c clabruntime.GenericContainer) (string, string, string, error) {\n675: \tparts := strings.Split(c.ID, \"/\")\n676: \tif len(parts) != 3 {\n677: \t\treturn \"\", \"\", \"\", fmt.Errorf(\"expected namespace/lab/node id, got %q\", c.ID)\n678: \t}\n679: \n680: \treturn parts[0], parts[1], parts[2], nil\n681: }\n682: \n683: func filterLabRuntimeContainers(\n684: \tcontainers []clabruntime.GenericContainer,\n685: \tfilters []*clabtypes.GenericFilter,\n686: ) []clabruntime.GenericContainer {\n687: \tif len(filters) == 0 {\n688: \t\treturn containers\n689: \t}\n690: \n691: \tfiltered := make([]clabruntime.GenericContainer, 0, len(containers))\n692: \tfor _, container := range containers {\n693: \t\tif labRuntimeContainerMatches(container, filters) {\n694: \t\t\tfiltered = append(filtered, container)\n695: \t\t}\n696: \t}\n697: \n698: \treturn filtered\n699: }\n\n(Showing lines 590-699 of 827. Use offset=700 to continue.)\n</content>",
    "title": "source/head/core/labruntime.go",
    "metadata": {
      "preview": "\treturn bindings\n}\n\n// labRuntimeContainerID is the ID of a lab runtime node: <namespace>/<lab>/<node>.\nfunc labRuntimeContainerID(namespace, lab, node string) string {\n\treturn fmt.Sprintf(\"%s/%s/%s\", namespace, lab, node)\n}\n\n// topologyNodeName maps a node name a lab runtime reports back onto the topology node it belongs\n// to. The runtime renames the nodes Kubernetes cannot carry, so the state it reports does not\n// always use the name the topology file wrote.\nfunc (c *CLab) topologyNodeName(name string) string {\n\tif c.Config.Topology == nil {\n\t\treturn name\n\t}\n\tif _, ok := c.Config.Topology.Nodes[name]; ok {\n\t\treturn name\n\t}\n\n\tfor nodeName := range c.Config.Topology.Nodes {",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/labruntime.go",
        "text": "\treturn bindings\n}\n\n// labRuntimeContainerID is the ID of a lab runtime node: <namespace>/<lab>/<node>.\nfunc labRuntimeContainerID(namespace, lab, node string) string {\n\treturn fmt.Sprintf(\"%s/%s/%s\", namespace, lab, node)\n}\n\n// topologyNodeName maps a node name a lab runtime reports back onto the topology node it belongs\n// to. The runtime renames the nodes Kubernetes cannot carry, so the state it reports does not\n// always use the name the topology file wrote.\nfunc (c *CLab) topologyNodeName(name string) string {\n\tif c.Config.Topology == nil {\n\t\treturn name\n\t}\n\tif _, ok := c.Config.Topology.Nodes[name]; ok {\n\t\treturn name\n\t}\n\n\tfor nodeName := range c.Config.Topology.Nodes {\n\t\tif clabnames.SanitizeName(nodeName) == name {\n\t\t\treturn nodeName\n\t\t}\n\t}\n\n\treturn name\n}\n\n// managementAddress reports the address a user reaches the node at: the LoadBalancer address\n// when the node is exposed, otherwise the allocated management address.\nfunc managementAddress(node clablabruntime.NodeState) clabruntime.GenericMgmtIPs {\n\tsettings := clabruntime.GenericMgmtIPs{}\n\n\tif ip := net.ParseIP(node.LoadBalancerAddress); ip != nil {\n\t\tif ip.To4() != nil {\n\t\t\tsettings.IPv4addr = node.LoadBalancerAddress\n\t\t\tsettings.IPv4pLen = 32\n\t\t} else {\n\t\t\tsettings.IPv6addr = node.LoadBalancerAddress\n\t\t\tsettings.IPv6pLen = 128\n\t\t}\n\t}\n\n\tif settings.IPv4addr == \"\" {\n\t\tsettings.IPv4addr, settings.IPv4pLen = splitManagementCIDR(node.MgmtIPv4Address)\n\t}\n\tif settings.IPv6addr == \"\" {\n\t\tsettings.IPv6addr, settings.IPv6pLen = splitManagementCIDR(node.MgmtIPv6Address)\n\t}\n\n\treturn settings\n}\n\nfunc splitManagementCIDR(cidr string) (string, int) {\n\tif cidr == \"\" {\n\t\treturn \"\", 0\n\t}\n\n\tip, network, err := net.ParseCIDR(cidr)\n\tif err != nil {\n\t\tif net.ParseIP(cidr) != nil {\n\t\t\treturn cidr, 0\n\t\t}\n\n\t\treturn \"\", 0\n\t}\n\n\tprefixLen, _ := network.Mask.Size()\n\n\treturn ip.String(), prefixLen\n}\n\nfunc labRuntimeTopologyPath(c *CLab, state *clablabruntime.LabState) string {\n\tif c.TopoPaths.TopologyFileIsSet() {\n\t\treturn c.TopoPaths.TopologyFilenameAbsPath()\n\t}\n\n\tif state.TopologyPath != \"\" {\n\t\treturn state.TopologyPath\n\t}\n\n\treturn fmt.Sprintf(\"k8s://%s/topologies/%s\", state.Namespace, state.Name)\n}\n\nfunc labRuntimeContainerParts(c clabruntime.GenericContainer) (string, string, string, error) {\n\tparts := strings.Split(c.ID, \"/\")\n\tif len(parts) != 3 {\n\t\treturn \"\", \"\", \"\", fmt.Errorf(\"expected namespace/lab/node id, got %q\", c.ID)\n\t}\n\n\treturn parts[0], parts[1], parts[2], nil\n}\n\nfunc filterLabRuntimeContainers(\n\tcontainers []clabruntime.GenericContainer,\n\tfilters []*clabtypes.GenericFilter,\n) []clabruntime.GenericContainer {\n\tif len(filters) == 0 {\n\t\treturn containers\n\t}\n\n\tfiltered := make([]clabruntime.GenericContainer, 0, len(containers))\n\tfor _, container := range containers {\n\t\tif labRuntimeContainerMatches(container, filters) {\n\t\t\tfiltered = append(filtered, container)\n\t\t}\n\t}\n\n\treturn filtered\n}",
        "lineStart": 590,
        "lineEnd": 699,
        "totalLines": 827,
        "truncated": true
      }
    },
    "time": {
      "start": 1793525887644,
      "end": 1793525887653
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/core/labruntime.go",
  "limit": 120,
  "offset": 360
}

Output

<path>/source/head/core/labruntime.go</path>
<type>file</type>
<content>
360: 	}
361: 
362: 	return resultCollection, errors.Join(execErrors...)
363: }
364: 
365: func (c *CLab) startNodesWithLabRuntime(ctx context.Context, nodeNames []string) error {
366: 	return c.LabRuntime.Start(ctx, clablabruntime.NodeRequest{
367: 		Identity: c.labRuntimeIdentity,
368: 		Name:     c.Config.Name,
369: 		Nodes:    nodeNames,
370: 		Timeout:  c.timeout,
371: 	})
372: }
373: 
374: func (c *CLab) stopNodesWithLabRuntime(ctx context.Context, nodeNames []string) error {
375: 	return c.LabRuntime.Stop(ctx, clablabruntime.NodeRequest{
376: 		Identity: c.labRuntimeIdentity,
377: 		Name:     c.Config.Name,
378: 		Nodes:    nodeNames,
379: 		Timeout:  c.timeout,
380: 	})
381: }
382: 
383: func (c *CLab) restartNodesWithLabRuntime(ctx context.Context, nodeNames []string) error {
384: 	return c.LabRuntime.Restart(ctx, clablabruntime.NodeRequest{
385: 		Identity: c.labRuntimeIdentity,
386: 		Name:     c.Config.Name,
387: 		Nodes:    nodeNames,
388: 		Timeout:  c.timeout,
389: 	})
390: }
391: 
392: func (c *CLab) saveWithLabRuntime(ctx context.Context, opts *SaveOptions) error {
393: 	if opts.copyDst != "" {
394: 		resolvedDst, err := c.resolveCopyOutDst(opts.copyDst)
395: 		if err != nil {
396: 			return err
397: 		}
398: 		opts.copyDst = resolvedDst
399: 	}
400: 
401: 	result, err := c.LabRuntime.Save(ctx, clablabruntime.SaveRequest{
402: 		Identity: c.labRuntimeIdentity,
403: 		Name:     c.Config.Name,
404: 		Nodes:    c.nodeFilter,
405: 		Copy:     opts.copyDst != "",
406: 	})
407: 	if err != nil {
408: 		return err
409: 	}
410: 
411: 	if opts.copyDst == "" || result == nil {
412: 		return nil
413: 	}
414: 
415: 	return c.copyLabRuntimeSavedFiles(result, opts.copyDst)
416: }
417: 
418: func (c *CLab) containersFromLabState(
419: 	state *clablabruntime.LabState,
420: ) []clabruntime.GenericContainer {
421: 	if state == nil {
422: 		return nil
423: 	}
424: 
425: 	nodes := state.Nodes
426: 	if len(nodes) == 0 && c.Config.Topology != nil {
427: 		nodeNames := make([]string, 0, len(c.Config.Topology.Nodes))
428: 		for nodeName := range c.Config.Topology.Nodes {
429: 			nodeNames = append(nodeNames, nodeName)
430: 		}
431: 		sort.Strings(nodeNames)
432: 
433: 		nodes = make([]clablabruntime.NodeState, 0, len(nodeNames))
434: 		for _, nodeName := range nodeNames {
435: 			nodes = append(nodes, clablabruntime.NodeState{
436: 				Name:  nodeName,
437: 				Kind:  c.Config.Topology.GetNodeKind(nodeName),
438: 				Image: c.Config.Topology.GetNodeImage(nodeName),
439: 				State: state.State,
440: 				Ready: state.Ready,
441: 			})
442: 		}
443: 	}
444: 
445: 	containers := make([]clabruntime.GenericContainer, 0, len(nodes))
446: 	for _, node := range nodes {
447: 		containers = append(containers, c.containerFromLabNode(state, node))
448: 	}
449: 
450: 	return containers
451: }
452: 
453: // LabRuntimeContainer describes a lab runtime node as a container record, the way inspect
454: // reports it. The events command describes lab runtime nodes with it too.
455: func (c *CLab) LabRuntimeContainer(
456: 	state *clablabruntime.LabState,
457: 	node clablabruntime.NodeState,
458: ) clabruntime.GenericContainer {
459: 	return c.containerFromLabNode(state, node)
460: }
461: 
462: func (c *CLab) containerFromLabNode(
463: 	state *clablabruntime.LabState,
464: 	node clablabruntime.NodeState,
465: ) clabruntime.GenericContainer {
466: 	nodeName := fmt.Sprintf("%s-%s", state.Name, node.Name)
467: 	containerState, containerStatus := labRuntimeContainerState(state, node)
468: 
469: 	topologyNode := node.Name
470: 	if node.TopologyName != "" {
471: 		topologyNode = node.TopologyName
472: 	}
473: 	if c.Config.Topology != nil {
474: 		topologyNode = c.topologyNodeName(topologyNode)
475: 	}
476: 
477: 	labels := map[string]string{
478: 		clabconstants.Containerlab: state.Name,
479: 		clabconstants.NodeName:     topologyNode,

(Showing lines 360-479 of 827. Use offset=480 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_196793306001XGPWqkiabc61P5",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196792a02001YELDRAg4r2EIiY",
  "callID": "call_a996792c6f6145788943ce92",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/labruntime.go",
      "limit": 120,
      "offset": 360
    },
    "output": "<path>/source/head/core/labruntime.go</path>\n<type>file</type>\n<content>\n360: \t}\n361: \n362: \treturn resultCollection, errors.Join(execErrors...)\n363: }\n364: \n365: func (c *CLab) startNodesWithLabRuntime(ctx context.Context, nodeNames []string) error {\n366: \treturn c.LabRuntime.Start(ctx, clablabruntime.NodeRequest{\n367: \t\tIdentity: c.labRuntimeIdentity,\n368: \t\tName:     c.Config.Name,\n369: \t\tNodes:    nodeNames,\n370: \t\tTimeout:  c.timeout,\n371: \t})\n372: }\n373: \n374: func (c *CLab) stopNodesWithLabRuntime(ctx context.Context, nodeNames []string) error {\n375: \treturn c.LabRuntime.Stop(ctx, clablabruntime.NodeRequest{\n376: \t\tIdentity: c.labRuntimeIdentity,\n377: \t\tName:     c.Config.Name,\n378: \t\tNodes:    nodeNames,\n379: \t\tTimeout:  c.timeout,\n380: \t})\n381: }\n382: \n383: func (c *CLab) restartNodesWithLabRuntime(ctx context.Context, nodeNames []string) error {\n384: \treturn c.LabRuntime.Restart(ctx, clablabruntime.NodeRequest{\n385: \t\tIdentity: c.labRuntimeIdentity,\n386: \t\tName:     c.Config.Name,\n387: \t\tNodes:    nodeNames,\n388: \t\tTimeout:  c.timeout,\n389: \t})\n390: }\n391: \n392: func (c *CLab) saveWithLabRuntime(ctx context.Context, opts *SaveOptions) error {\n393: \tif opts.copyDst != \"\" {\n394: \t\tresolvedDst, err := c.resolveCopyOutDst(opts.copyDst)\n395: \t\tif err != nil {\n396: \t\t\treturn err\n397: \t\t}\n398: \t\topts.copyDst = resolvedDst\n399: \t}\n400: \n401: \tresult, err := c.LabRuntime.Save(ctx, clablabruntime.SaveRequest{\n402: \t\tIdentity: c.labRuntimeIdentity,\n403: \t\tName:     c.Config.Name,\n404: \t\tNodes:    c.nodeFilter,\n405: \t\tCopy:     opts.copyDst != \"\",\n406: \t})\n407: \tif err != nil {\n408: \t\treturn err\n409: \t}\n410: \n411: \tif opts.copyDst == \"\" || result == nil {\n412: \t\treturn nil\n413: \t}\n414: \n415: \treturn c.copyLabRuntimeSavedFiles(result, opts.copyDst)\n416: }\n417: \n418: func (c *CLab) containersFromLabState(\n419: \tstate *clablabruntime.LabState,\n420: ) []clabruntime.GenericContainer {\n421: \tif state == nil {\n422: \t\treturn nil\n423: \t}\n424: \n425: \tnodes := state.Nodes\n426: \tif len(nodes) == 0 && c.Config.Topology != nil {\n427: \t\tnodeNames := make([]string, 0, len(c.Config.Topology.Nodes))\n428: \t\tfor nodeName := range c.Config.Topology.Nodes {\n429: \t\t\tnodeNames = append(nodeNames, nodeName)\n430: \t\t}\n431: \t\tsort.Strings(nodeNames)\n432: \n433: \t\tnodes = make([]clablabruntime.NodeState, 0, len(nodeNames))\n434: \t\tfor _, nodeName := range nodeNames {\n435: \t\t\tnodes = append(nodes, clablabruntime.NodeState{\n436: \t\t\t\tName:  nodeName,\n437: \t\t\t\tKind:  c.Config.Topology.GetNodeKind(nodeName),\n438: \t\t\t\tImage: c.Config.Topology.GetNodeImage(nodeName),\n439: \t\t\t\tState: state.State,\n440: \t\t\t\tReady: state.Ready,\n441: \t\t\t})\n442: \t\t}\n443: \t}\n444: \n445: \tcontainers := make([]clabruntime.GenericContainer, 0, len(nodes))\n446: \tfor _, node := range nodes {\n447: \t\tcontainers = append(containers, c.containerFromLabNode(state, node))\n448: \t}\n449: \n450: \treturn containers\n451: }\n452: \n453: // LabRuntimeContainer describes a lab runtime node as a container record, the way inspect\n454: // reports it. The events command describes lab runtime nodes with it too.\n455: func (c *CLab) LabRuntimeContainer(\n456: \tstate *clablabruntime.LabState,\n457: \tnode clablabruntime.NodeState,\n458: ) clabruntime.GenericContainer {\n459: \treturn c.containerFromLabNode(state, node)\n460: }\n461: \n462: func (c *CLab) containerFromLabNode(\n463: \tstate *clablabruntime.LabState,\n464: \tnode clablabruntime.NodeState,\n465: ) clabruntime.GenericContainer {\n466: \tnodeName := fmt.Sprintf(\"%s-%s\", state.Name, node.Name)\n467: \tcontainerState, containerStatus := labRuntimeContainerState(state, node)\n468: \n469: \ttopologyNode := node.Name\n470: \tif node.TopologyName != \"\" {\n471: \t\ttopologyNode = node.TopologyName\n472: \t}\n473: \tif c.Config.Topology != nil {\n474: \t\ttopologyNode = c.topologyNodeName(topologyNode)\n475: \t}\n476: \n477: \tlabels := map[string]string{\n478: \t\tclabconstants.Containerlab: state.Name,\n479: \t\tclabconstants.NodeName:     topologyNode,\n\n(Showing lines 360-479 of 827. Use offset=480 to continue.)\n</content>",
    "title": "source/head/core/labruntime.go",
    "metadata": {
      "preview": "\t}\n\n\treturn resultCollection, errors.Join(execErrors...)\n}\n\nfunc (c *CLab) startNodesWithLabRuntime(ctx context.Context, nodeNames []string) error {\n\treturn c.LabRuntime.Start(ctx, clablabruntime.NodeRequest{\n\t\tIdentity: c.labRuntimeIdentity,\n\t\tName:     c.Config.Name,\n\t\tNodes:    nodeNames,\n\t\tTimeout:  c.timeout,\n\t})\n}\n\nfunc (c *CLab) stopNodesWithLabRuntime(ctx context.Context, nodeNames []string) error {\n\treturn c.LabRuntime.Stop(ctx, clablabruntime.NodeRequest{\n\t\tIdentity: c.labRuntimeIdentity,\n\t\tName:     c.Config.Name,\n\t\tNodes:    nodeNames,\n\t\tTimeout:  c.timeout,",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/labruntime.go",
        "text": "\t}\n\n\treturn resultCollection, errors.Join(execErrors...)\n}\n\nfunc (c *CLab) startNodesWithLabRuntime(ctx context.Context, nodeNames []string) error {\n\treturn c.LabRuntime.Start(ctx, clablabruntime.NodeRequest{\n\t\tIdentity: c.labRuntimeIdentity,\n\t\tName:     c.Config.Name,\n\t\tNodes:    nodeNames,\n\t\tTimeout:  c.timeout,\n\t})\n}\n\nfunc (c *CLab) stopNodesWithLabRuntime(ctx context.Context, nodeNames []string) error {\n\treturn c.LabRuntime.Stop(ctx, clablabruntime.NodeRequest{\n\t\tIdentity: c.labRuntimeIdentity,\n\t\tName:     c.Config.Name,\n\t\tNodes:    nodeNames,\n\t\tTimeout:  c.timeout,\n\t})\n}\n\nfunc (c *CLab) restartNodesWithLabRuntime(ctx context.Context, nodeNames []string) error {\n\treturn c.LabRuntime.Restart(ctx, clablabruntime.NodeRequest{\n\t\tIdentity: c.labRuntimeIdentity,\n\t\tName:     c.Config.Name,\n\t\tNodes:    nodeNames,\n\t\tTimeout:  c.timeout,\n\t})\n}\n\nfunc (c *CLab) saveWithLabRuntime(ctx context.Context, opts *SaveOptions) error {\n\tif opts.copyDst != \"\" {\n\t\tresolvedDst, err := c.resolveCopyOutDst(opts.copyDst)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\topts.copyDst = resolvedDst\n\t}\n\n\tresult, err := c.LabRuntime.Save(ctx, clablabruntime.SaveRequest{\n\t\tIdentity: c.labRuntimeIdentity,\n\t\tName:     c.Config.Name,\n\t\tNodes:    c.nodeFilter,\n\t\tCopy:     opts.copyDst != \"\",\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif opts.copyDst == \"\" || result == nil {\n\t\treturn nil\n\t}\n\n\treturn c.copyLabRuntimeSavedFiles(result, opts.copyDst)\n}\n\nfunc (c *CLab) containersFromLabState(\n\tstate *clablabruntime.LabState,\n) []clabruntime.GenericContainer {\n\tif state == nil {\n\t\treturn nil\n\t}\n\n\tnodes := state.Nodes\n\tif len(nodes) == 0 && c.Config.Topology != nil {\n\t\tnodeNames := make([]string, 0, len(c.Config.Topology.Nodes))\n\t\tfor nodeName := range c.Config.Topology.Nodes {\n\t\t\tnodeNames = append(nodeNames, nodeName)\n\t\t}\n\t\tsort.Strings(nodeNames)\n\n\t\tnodes = make([]clablabruntime.NodeState, 0, len(nodeNames))\n\t\tfor _, nodeName := range nodeNames {\n\t\t\tnodes = append(nodes, clablabruntime.NodeState{\n\t\t\t\tName:  nodeName,\n\t\t\t\tKind:  c.Config.Topology.GetNodeKind(nodeName),\n\t\t\t\tImage: c.Config.Topology.GetNodeImage(nodeName),\n\t\t\t\tState: state.State,\n\t\t\t\tReady: state.Ready,\n\t\t\t})\n\t\t}\n\t}\n\n\tcontainers := make([]clabruntime.GenericContainer, 0, len(nodes))\n\tfor _, node := range nodes {\n\t\tcontainers = append(containers, c.containerFromLabNode(state, node))\n\t}\n\n\treturn containers\n}\n\n// LabRuntimeContainer describes a lab runtime node as a container record, the way inspect\n// reports it. The events command describes lab runtime nodes with it too.\nfunc (c *CLab) LabRuntimeContainer(\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n) clabruntime.GenericContainer {\n\treturn c.containerFromLabNode(state, node)\n}\n\nfunc (c *CLab) containerFromLabNode(\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n) clabruntime.GenericContainer {\n\tnodeName := fmt.Sprintf(\"%s-%s\", state.Name, node.Name)\n\tcontainerState, containerStatus := labRuntimeContainerState(state, node)\n\n\ttopologyNode := node.Name\n\tif node.TopologyName != \"\" {\n\t\ttopologyNode = node.TopologyName\n\t}\n\tif c.Config.Topology != nil {\n\t\ttopologyNode = c.topologyNodeName(topologyNode)\n\t}\n\n\tlabels := map[string]string{\n\t\tclabconstants.Containerlab: state.Name,\n\t\tclabconstants.NodeName:     topologyNode,",
        "lineStart": 360,
        "lineEnd": 479,
        "totalLines": 827,
        "truncated": true
      }
    },
    "time": {
      "start": 1793525887755,
      "end": 1793525887764
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196793317001e4s8OY1Ow3F9j6",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196792a02001YELDRAg4r2EIiY",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 52929,
    "input": 394,
    "output": 54,
    "reasoning": 1,
    "cache": {
      "read": 52480,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196792a02001YELDRAg4r2EIiY",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525885442,
    "completed": 1793525887771
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 52929,
    "input": 394,
    "output": 54,
    "reasoning": 1,
    "cache": {
      "read": 52480,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 31
step-start
{
  "type": "step-start",
  "id": "prt_196793e8f001a8x88vnwgkHL1e",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967933250015p7FwvX5lKOiLP"
}
Reasoning
`managementAddress` handles both CIDR and plain IP. Good, resolved.

The NodeType concern: `c.Nodes[topologyNode].Config().NodeType` — in containerlab, `core/config.go:874` sets `cfg.Labels[clabconstants.NodeType] = cfg.NodeType`, and NodeType is populated during config load from the topology `type:` attribute; the kind's default type is resolved by node kinds (e.g., srl sets node type default in Init). With `-t` loaded, config's NodeType would be non-empty for srl. If a topology node has no type and the kind doesn't set a default, NodeType is "" and the label is dropped even though the runtime state (spec.type set by controller from the same topology) may have had it — but they'd both come from the same source, so consistent. I'll drop this candidate.

Now remaining: container_events.go full read (I only had partial), the parity tests, docs, runtime.go Inspect lab-not-found, robot tests, and clabernetes_test.go spot checks. Also check `forwardRuntimeEvents` in stream.go lines 180-600 (per-container registry.Start) — the summary said read first ~70 lines; I should verify the rest briefly. And core/events/netlink.go partially read — the parity attributes function `labRuntimeInterfaceAttributes`.

Let me read container_events.go in full now.
`splitManagementCIDR` handles both formats — that candidate is resolved. Now read `container_events.go` in full.
read · completed

Input

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

Output

<path>/source/head/labruntime/clabernetes/container_events.go</path>
<type>file</type>
<content>
1: package clabernetes
2: 
3: import (
4: 	"context"
5: 	"errors"
6: 	"fmt"
7: 	"strings"
8: 	"time"
9: 
10: 	"github.com/charmbracelet/log"
11: 	clablabruntime "github.com/srl-labs/containerlab/labruntime"
12: )
13: 
14: // Container event actions, as the Docker runtime reports them.
15: const (
16: 	containerActionCreate        = "create"
17: 	containerActionStart         = "start"
18: 	containerActionKill          = "kill"
19: 	containerActionStop          = "stop"
20: 	containerActionDie           = "die"
21: 	containerActionDestroy       = "destroy"
22: 	containerActionHealthPrefix  = "health_status: "
23: 	containerEventSignalSIGTERM  = "15"
24: 	containerRefreshDelay        = 200 * time.Millisecond
25: 	containerRefreshRetryDelay   = pollInterval
26: 	containerEventAttributeState = "state"
27: )
28: 
29: // trackedContainer is the last reported container state of a node.
30: type trackedContainer struct {
31: 	ref    labRef
32: 	state  string
33: 	health string
34: 	pod    string
35: 	// lab and node are the last observation, which a removed node is described with.
36: 	lab  *clablabruntime.LabState
37: 	node clablabruntime.NodeState
38: }
39: 
40: // containerTracker turns the node states of the labs in an event scope into the container
41: // events the Docker runtime emits for the same lifecycle: create and start when a node's pod
42: // starts, kill, stop and die when it stops (on request, or between the pods of a restart),
43: // destroy when the node is removed, and health_status as its device becomes ready.
44: type containerTracker struct {
45: 	r     *Runtime
46: 	sink  chan<- clablabruntime.Event
47: 	nodes map[string]*trackedContainer
48: }
49: 
50: // trackContainers reports the container events of a scope. It reads the labs once, reporting
51: // them as a snapshot when the stream includes the initial state, and then reads a lab again
52: // whenever its Topology, Nodes or pods change. Changes that arrive together are read once.
53: func (r *Runtime) trackContainers(
54: 	ctx context.Context,
55: 	scope eventScope,
56: 	includeInitialState bool,
57: 	changed <-chan labRef,
58: 	eventSink chan<- clablabruntime.Event,
59: 	errSink chan<- error,
60: ) {
61: 	tracker := &containerTracker{r: r, sink: eventSink, nodes: map[string]*trackedContainer{}}
62: 
63: 	states, err := r.labStates(ctx, scope)
64: 	if err != nil {
65: 		sendEventError(ctx, errSink, err)
66: 		return
67: 	}
68: 	for _, state := range states {
69: 		tracker.observeLab(ctx, labRef{namespace: state.Namespace, lab: state.Name}, state,
70: 			&observeSeed{snapshot: includeInitialState})
71: 	}
72: 
73: 	pending := map[labRef]bool{}
74: 	timer := time.NewTimer(time.Hour)
75: 	timer.Stop()
76: 	defer timer.Stop()
77: 	armed := false
78: 	arm := func(delay time.Duration) {
79: 		if !armed {
80: 			timer.Reset(delay)
81: 			armed = true
82: 		}
83: 	}
84: 
85: 	for {
86: 		select {
87: 		case <-ctx.Done():
88: 			return
89: 		case ref := <-changed:
90: 			pending[ref] = true
91: 			arm(containerRefreshDelay)
92: 		case <-timer.C:
93: 			armed = false
94: 			refs := pending
95: 			pending = map[labRef]bool{}
96: 			for ref := range refs {
97: 				if !tracker.refresh(ctx, ref) {
98: 					pending[ref] = true
99: 				}
100: 			}
101: 			if len(pending) != 0 {
102: 				arm(containerRefreshRetryDelay)
103: 			}
104: 		}
105: 	}
106: }
107: 
108: // observeSeed marks the first observation of a stream: it records the node states without
109: // reporting changes, and reports them as a snapshot when asked to.
110: type observeSeed struct {
111: 	snapshot bool
112: }
113: 
114: // refresh reads a lab again and reports what changed for its nodes. A lab that is gone reports
115: // its nodes as destroyed. It returns false when the lab could not be read.
116: func (t *containerTracker) refresh(ctx context.Context, ref labRef) bool {
117: 	state, err := t.r.Inspect(ctx, clablabruntime.InspectRequest{
118: 		Name:      ref.lab,
119: 		Namespace: ref.namespace,
120: 	})
121: 	if err != nil {
122: 		var notFound *labNotFoundError
123: 		if !errors.As(err, &notFound) {
124: 			if ctx.Err() == nil {
125: 				log.Debug("Failed to read a C9s lab for container events",
126: 					"namespace", ref.namespace, "lab", ref.lab, "error", err)
127: 			}
128: 
129: 			return ctx.Err() != nil
130: 		}
131: 		state = nil
132: 	}
133: 
134: 	t.observeLab(ctx, ref, state, nil)
135: 
136: 	return true
137: }
138: 
139: // observeLab compares the nodes of a lab with what was reported before and reports the
140: // difference. A nil state removes every node of the lab.
141: func (t *containerTracker) observeLab(
142: 	ctx context.Context,
143: 	ref labRef,
144: 	state *clablabruntime.LabState,
145: 	seed *observeSeed,
146: ) {
147: 	seen := map[string]bool{}
148: 	if state != nil {
149: 		for idx := range state.Nodes {
150: 			key := c9sNodeKey(state.Namespace, state.Name, state.Nodes[idx].Name)
151: 			seen[key] = true
152: 			t.observeNode(ctx, ref, state, state.Nodes[idx], seed)
153: 		}
154: 	}
155: 
156: 	for key, tracked := range t.nodes {
157: 		if tracked.ref != ref || seen[key] {
158: 			continue
159: 		}
160: 
161: 		for _, action := range containerRemovalActions(tracked) {
162: 			t.emit(ctx, tracked.lab, tracked.node, action, nil)
163: 		}
164: 		delete(t.nodes, key)
165: 	}
166: }
167: 
168: func (t *containerTracker) observeNode(
169: 	ctx context.Context,
170: 	ref labRef,
171: 	state *clablabruntime.LabState,
172: 	node clablabruntime.NodeState,
173: 	seed *observeSeed,
174: ) {
175: 	key := c9sNodeKey(state.Namespace, state.Name, node.Name)
176: 	previous := t.nodes[key]
177: 	if node.ContainerState == "" {
178: 		node.ContainerState = clablabruntime.ContainerStateCreated
179: 	}
180: 	next := &trackedContainer{
181: 		ref:   ref,
182: 		state: node.ContainerState,
183: 		pod:   node.Pod,
184: 		lab:   state,
185: 		node:  node,
186: 	}
187: 	next.health = containerHealth(previous, next, node.Health)
188: 	t.nodes[key] = next
189: 
190: 	if seed != nil {
191: 		if seed.snapshot {
192: 			t.emit(ctx, state, node, next.state, map[string]string{
193: 				"origin": clablabruntime.EventOriginSnapshot,
194: 			})
195: 		}
196: 
197: 		return
198: 	}
199: 
200: 	for _, action := range containerTransitionActions(previous, next) {
201: 		t.emit(ctx, state, node, action, nil)
202: 	}
203: }
204: 
205: // containerHealth is the health a running node reports: a node that was healthy and is not
206: // ready anymore in the same pod is unhealthy, as a container whose healthcheck starts failing.
207: func containerHealth(previous, next *trackedContainer, health string) string {
208: 	if next.state != clablabruntime.ContainerStateRunning {
209: 		return ""
210: 	}
211: 	if health == "" {
212: 		health = clablabruntime.ContainerHealthStarting
213: 	}
214: 	if health == clablabruntime.ContainerHealthStarting && previous != nil &&
215: 		previous.state == clablabruntime.ContainerStateRunning && previous.pod == next.pod &&
216: 		(previous.health == clablabruntime.ContainerHealthHealthy ||
217: 			previous.health == clablabruntime.ContainerHealthUnhealthy) {
218: 		return clablabruntime.ContainerHealthUnhealthy
219: 	}
220: 
221: 	return health
222: }
223: 
224: // containerTransitionActions are the container event actions Docker reports when a container
225: // goes from the previous to the next state:
226: //
227: //	new node            create (+ start when it runs, + stop when it is already stopped)
228: //	created -> running  start
229: //	exited  -> running  start
230: //	running -> exited   kill, stop, die (stop, or the old pod of a restart ending)
231: //	running -> created  kill, stop, die (the replacement pod of a restart not running yet)
232: //	running, new pod    kill, stop, die, start (restart)
233: //	created -> exited   stop
234: //
235: // A started node also reports its health (health_status: starting or healthy), and a running
236: // node reports health changes, like a container with a healthcheck.
237: func containerTransitionActions(previous, next *trackedContainer) []string {
238: 	const (
239: 		created = clablabruntime.ContainerStateCreated
240: 		running = clablabruntime.ContainerStateRunning
241: 		exited  = clablabruntime.ContainerStateExited
242: 	)
243: 
244: 	var actions []string
245: 	previousState := ""
246: 	if previous != nil {
247: 		previousState = previous.state
248: 	}
249: 
250: 	switch {
251: 	case previous == nil:
252: 		actions = append(actions, containerActionCreate)
253: 		switch next.state {
254: 		case running:
255: 			actions = append(actions, containerActionStart)
256: 		case exited:
257: 			actions = append(actions, containerActionStop)
258: 		}
259: 	case previousState == running && next.state == running && previous.pod != next.pod:
260: 		actions = append(actions, containerActionKill, containerActionStop, containerActionDie,
261: 			containerActionStart)
262: 	case previousState == running && next.state != running:
263: 		actions = append(actions, containerActionKill, containerActionStop, containerActionDie)
264: 	case previousState != running && next.state == running:
265: 		actions = append(actions, containerActionStart)
266: 	case previousState == created && next.state == exited:
267: 		actions = append(actions, containerActionStop)
268: 	}
269: 
270: 	if next.state != running {
271: 		return actions
272: 	}
273: 
274: 	started := len(actions) != 0 && actions[len(actions)-1] == containerActionStart
275: 	if !started && previous != nil && previous.health == next.health {
276: 		return actions
277: 	}
278: 	if next.health == clablabruntime.ContainerHealthStarting && !started {
279: 		return actions
280: 	}
281: 
282: 	return append(actions, containerActionHealthPrefix+next.health)
283: }
284: 
285: // containerRemovalActions are the actions Docker reports when a container is removed: a running
286: // one is killed and dies first.
287: func containerRemovalActions(previous *trackedContainer) []string {
288: 	if previous.state == clablabruntime.ContainerStateRunning {
289: 		return []string{containerActionKill, containerActionDie, containerActionDestroy}
290: 	}
291: 
292: 	return []string{containerActionDestroy}
293: }
294: 
295: // containerActionState is the container state after an action, which every container event
296: // reports in its state attribute.
297: func containerActionState(action, snapshotState string) string {
298: 	switch action {
299: 	case containerActionCreate:
300: 		return clablabruntime.ContainerStateCreated
301: 	case containerActionStop, containerActionDie, containerActionDestroy:
302: 		return clablabruntime.ContainerStateExited
303: 	case containerActionStart, containerActionKill:
304: 		return clablabruntime.ContainerStateRunning
305: 	}
306: 	if strings.HasPrefix(action, containerActionHealthPrefix) {
307: 		return clablabruntime.ContainerStateRunning
308: 	}
309: 
310: 	return snapshotState
311: }
312: 
313: func (t *containerTracker) emit(
314: 	ctx context.Context,
315: 	state *clablabruntime.LabState,
316: 	node clablabruntime.NodeState,
317: 	action string,
318: 	extra map[string]string,
319: ) {
320: 	t.r.sendEvent(ctx, t.sink, c9sContainerEvent(state, node, action, extra))
321: }
322: 
323: // c9sContainerEvent is a container event of a node. The actor is the node, as for its interface
324: // events; its ID is the container_id inspect reports. Lab and Node let the events command
325: // describe the node with the attributes inspect and the Docker runtime report.
326: func c9sContainerEvent(
327: 	state *clablabruntime.LabState,
328: 	node clablabruntime.NodeState,
329: 	action string,
330: 	extra map[string]string,
331: ) clablabruntime.Event {
332: 	key := c9sNodeKey(state.Namespace, state.Name, node.Name)
333: 	attributes := map[string]string{
334: 		"namespace":                  state.Namespace,
335: 		"lab":                        state.Name,
336: 		"node":                       node.Name,
337: 		containerEventAttributeState: containerActionState(action, node.ContainerState),
338: 	}
339: 	if node.Pod != "" {
340: 		attributes["pod"] = node.Pod
341: 	}
342: 	if action == containerActionKill {
343: 		// Kubernetes stops a pod's containers with SIGTERM.
344: 		attributes["signal"] = containerEventSignalSIGTERM
345: 	}
346: 	for k, v := range extra {
347: 		attributes[k] = v
348: 	}
349: 
350: 	nodeCopy := node
351: 
352: 	return clablabruntime.Event{
353: 		Timestamp:   time.Now(),
354: 		Type:        clablabruntime.EventTypeContainer,
355: 		Action:      action,
356: 		ActorID:     key,
357: 		ActorName:   fmt.Sprintf("%s-%s", state.Name, node.Name),
358: 		ActorFullID: key,
359: 		Attributes:  attributes,
360: 		Lab:         state,
361: 		Node:        &nodeCopy,
362: 	}
363: }

(End of file - total 363 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19679489b001jyTrMKdDjW80rn",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967933250015p7FwvX5lKOiLP",
  "callID": "call_2ad892ce8de44c70b728f62b",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/container_events.go"
    },
    "output": "<path>/source/head/labruntime/clabernetes/container_events.go</path>\n<type>file</type>\n<content>\n1: package clabernetes\n2: \n3: import (\n4: \t\"context\"\n5: \t\"errors\"\n6: \t\"fmt\"\n7: \t\"strings\"\n8: \t\"time\"\n9: \n10: \t\"github.com/charmbracelet/log\"\n11: \tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n12: )\n13: \n14: // Container event actions, as the Docker runtime reports them.\n15: const (\n16: \tcontainerActionCreate        = \"create\"\n17: \tcontainerActionStart         = \"start\"\n18: \tcontainerActionKill          = \"kill\"\n19: \tcontainerActionStop          = \"stop\"\n20: \tcontainerActionDie           = \"die\"\n21: \tcontainerActionDestroy       = \"destroy\"\n22: \tcontainerActionHealthPrefix  = \"health_status: \"\n23: \tcontainerEventSignalSIGTERM  = \"15\"\n24: \tcontainerRefreshDelay        = 200 * time.Millisecond\n25: \tcontainerRefreshRetryDelay   = pollInterval\n26: \tcontainerEventAttributeState = \"state\"\n27: )\n28: \n29: // trackedContainer is the last reported container state of a node.\n30: type trackedContainer struct {\n31: \tref    labRef\n32: \tstate  string\n33: \thealth string\n34: \tpod    string\n35: \t// lab and node are the last observation, which a removed node is described with.\n36: \tlab  *clablabruntime.LabState\n37: \tnode clablabruntime.NodeState\n38: }\n39: \n40: // containerTracker turns the node states of the labs in an event scope into the container\n41: // events the Docker runtime emits for the same lifecycle: create and start when a node's pod\n42: // starts, kill, stop and die when it stops (on request, or between the pods of a restart),\n43: // destroy when the node is removed, and health_status as its device becomes ready.\n44: type containerTracker struct {\n45: \tr     *Runtime\n46: \tsink  chan<- clablabruntime.Event\n47: \tnodes map[string]*trackedContainer\n48: }\n49: \n50: // trackContainers reports the container events of a scope. It reads the labs once, reporting\n51: // them as a snapshot when the stream includes the initial state, and then reads a lab again\n52: // whenever its Topology, Nodes or pods change. Changes that arrive together are read once.\n53: func (r *Runtime) trackContainers(\n54: \tctx context.Context,\n55: \tscope eventScope,\n56: \tincludeInitialState bool,\n57: \tchanged <-chan labRef,\n58: \teventSink chan<- clablabruntime.Event,\n59: \terrSink chan<- error,\n60: ) {\n61: \ttracker := &containerTracker{r: r, sink: eventSink, nodes: map[string]*trackedContainer{}}\n62: \n63: \tstates, err := r.labStates(ctx, scope)\n64: \tif err != nil {\n65: \t\tsendEventError(ctx, errSink, err)\n66: \t\treturn\n67: \t}\n68: \tfor _, state := range states {\n69: \t\ttracker.observeLab(ctx, labRef{namespace: state.Namespace, lab: state.Name}, state,\n70: \t\t\t&observeSeed{snapshot: includeInitialState})\n71: \t}\n72: \n73: \tpending := map[labRef]bool{}\n74: \ttimer := time.NewTimer(time.Hour)\n75: \ttimer.Stop()\n76: \tdefer timer.Stop()\n77: \tarmed := false\n78: \tarm := func(delay time.Duration) {\n79: \t\tif !armed {\n80: \t\t\ttimer.Reset(delay)\n81: \t\t\tarmed = true\n82: \t\t}\n83: \t}\n84: \n85: \tfor {\n86: \t\tselect {\n87: \t\tcase <-ctx.Done():\n88: \t\t\treturn\n89: \t\tcase ref := <-changed:\n90: \t\t\tpending[ref] = true\n91: \t\t\tarm(containerRefreshDelay)\n92: \t\tcase <-timer.C:\n93: \t\t\tarmed = false\n94: \t\t\trefs := pending\n95: \t\t\tpending = map[labRef]bool{}\n96: \t\t\tfor ref := range refs {\n97: \t\t\t\tif !tracker.refresh(ctx, ref) {\n98: \t\t\t\t\tpending[ref] = true\n99: \t\t\t\t}\n100: \t\t\t}\n101: \t\t\tif len(pending) != 0 {\n102: \t\t\t\tarm(containerRefreshRetryDelay)\n103: \t\t\t}\n104: \t\t}\n105: \t}\n106: }\n107: \n108: // observeSeed marks the first observation of a stream: it records the node states without\n109: // reporting changes, and reports them as a snapshot when asked to.\n110: type observeSeed struct {\n111: \tsnapshot bool\n112: }\n113: \n114: // refresh reads a lab again and reports what changed for its nodes. A lab that is gone reports\n115: // its nodes as destroyed. It returns false when the lab could not be read.\n116: func (t *containerTracker) refresh(ctx context.Context, ref labRef) bool {\n117: \tstate, err := t.r.Inspect(ctx, clablabruntime.InspectRequest{\n118: \t\tName:      ref.lab,\n119: \t\tNamespace: ref.namespace,\n120: \t})\n121: \tif err != nil {\n122: \t\tvar notFound *labNotFoundError\n123: \t\tif !errors.As(err, &notFound) {\n124: \t\t\tif ctx.Err() == nil {\n125: \t\t\t\tlog.Debug(\"Failed to read a C9s lab for container events\",\n126: \t\t\t\t\t\"namespace\", ref.namespace, \"lab\", ref.lab, \"error\", err)\n127: \t\t\t}\n128: \n129: \t\t\treturn ctx.Err() != nil\n130: \t\t}\n131: \t\tstate = nil\n132: \t}\n133: \n134: \tt.observeLab(ctx, ref, state, nil)\n135: \n136: \treturn true\n137: }\n138: \n139: // observeLab compares the nodes of a lab with what was reported before and reports the\n140: // difference. A nil state removes every node of the lab.\n141: func (t *containerTracker) observeLab(\n142: \tctx context.Context,\n143: \tref labRef,\n144: \tstate *clablabruntime.LabState,\n145: \tseed *observeSeed,\n146: ) {\n147: \tseen := map[string]bool{}\n148: \tif state != nil {\n149: \t\tfor idx := range state.Nodes {\n150: \t\t\tkey := c9sNodeKey(state.Namespace, state.Name, state.Nodes[idx].Name)\n151: \t\t\tseen[key] = true\n152: \t\t\tt.observeNode(ctx, ref, state, state.Nodes[idx], seed)\n153: \t\t}\n154: \t}\n155: \n156: \tfor key, tracked := range t.nodes {\n157: \t\tif tracked.ref != ref || seen[key] {\n158: \t\t\tcontinue\n159: \t\t}\n160: \n161: \t\tfor _, action := range containerRemovalActions(tracked) {\n162: \t\t\tt.emit(ctx, tracked.lab, tracked.node, action, nil)\n163: \t\t}\n164: \t\tdelete(t.nodes, key)\n165: \t}\n166: }\n167: \n168: func (t *containerTracker) observeNode(\n169: \tctx context.Context,\n170: \tref labRef,\n171: \tstate *clablabruntime.LabState,\n172: \tnode clablabruntime.NodeState,\n173: \tseed *observeSeed,\n174: ) {\n175: \tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n176: \tprevious := t.nodes[key]\n177: \tif node.ContainerState == \"\" {\n178: \t\tnode.ContainerState = clablabruntime.ContainerStateCreated\n179: \t}\n180: \tnext := &trackedContainer{\n181: \t\tref:   ref,\n182: \t\tstate: node.ContainerState,\n183: \t\tpod:   node.Pod,\n184: \t\tlab:   state,\n185: \t\tnode:  node,\n186: \t}\n187: \tnext.health = containerHealth(previous, next, node.Health)\n188: \tt.nodes[key] = next\n189: \n190: \tif seed != nil {\n191: \t\tif seed.snapshot {\n192: \t\t\tt.emit(ctx, state, node, next.state, map[string]string{\n193: \t\t\t\t\"origin\": clablabruntime.EventOriginSnapshot,\n194: \t\t\t})\n195: \t\t}\n196: \n197: \t\treturn\n198: \t}\n199: \n200: \tfor _, action := range containerTransitionActions(previous, next) {\n201: \t\tt.emit(ctx, state, node, action, nil)\n202: \t}\n203: }\n204: \n205: // containerHealth is the health a running node reports: a node that was healthy and is not\n206: // ready anymore in the same pod is unhealthy, as a container whose healthcheck starts failing.\n207: func containerHealth(previous, next *trackedContainer, health string) string {\n208: \tif next.state != clablabruntime.ContainerStateRunning {\n209: \t\treturn \"\"\n210: \t}\n211: \tif health == \"\" {\n212: \t\thealth = clablabruntime.ContainerHealthStarting\n213: \t}\n214: \tif health == clablabruntime.ContainerHealthStarting && previous != nil &&\n215: \t\tprevious.state == clablabruntime.ContainerStateRunning && previous.pod == next.pod &&\n216: \t\t(previous.health == clablabruntime.ContainerHealthHealthy ||\n217: \t\t\tprevious.health == clablabruntime.ContainerHealthUnhealthy) {\n218: \t\treturn clablabruntime.ContainerHealthUnhealthy\n219: \t}\n220: \n221: \treturn health\n222: }\n223: \n224: // containerTransitionActions are the container event actions Docker reports when a container\n225: // goes from the previous to the next state:\n226: //\n227: //\tnew node            create (+ start when it runs, + stop when it is already stopped)\n228: //\tcreated -> running  start\n229: //\texited  -> running  start\n230: //\trunning -> exited   kill, stop, die (stop, or the old pod of a restart ending)\n231: //\trunning -> created  kill, stop, die (the replacement pod of a restart not running yet)\n232: //\trunning, new pod    kill, stop, die, start (restart)\n233: //\tcreated -> exited   stop\n234: //\n235: // A started node also reports its health (health_status: starting or healthy), and a running\n236: // node reports health changes, like a container with a healthcheck.\n237: func containerTransitionActions(previous, next *trackedContainer) []string {\n238: \tconst (\n239: \t\tcreated = clablabruntime.ContainerStateCreated\n240: \t\trunning = clablabruntime.ContainerStateRunning\n241: \t\texited  = clablabruntime.ContainerStateExited\n242: \t)\n243: \n244: \tvar actions []string\n245: \tpreviousState := \"\"\n246: \tif previous != nil {\n247: \t\tpreviousState = previous.state\n248: \t}\n249: \n250: \tswitch {\n251: \tcase previous == nil:\n252: \t\tactions = append(actions, containerActionCreate)\n253: \t\tswitch next.state {\n254: \t\tcase running:\n255: \t\t\tactions = append(actions, containerActionStart)\n256: \t\tcase exited:\n257: \t\t\tactions = append(actions, containerActionStop)\n258: \t\t}\n259: \tcase previousState == running && next.state == running && previous.pod != next.pod:\n260: \t\tactions = append(actions, containerActionKill, containerActionStop, containerActionDie,\n261: \t\t\tcontainerActionStart)\n262: \tcase previousState == running && next.state != running:\n263: \t\tactions = append(actions, containerActionKill, containerActionStop, containerActionDie)\n264: \tcase previousState != running && next.state == running:\n265: \t\tactions = append(actions, containerActionStart)\n266: \tcase previousState == created && next.state == exited:\n267: \t\tactions = append(actions, containerActionStop)\n268: \t}\n269: \n270: \tif next.state != running {\n271: \t\treturn actions\n272: \t}\n273: \n274: \tstarted := len(actions) != 0 && actions[len(actions)-1] == containerActionStart\n275: \tif !started && previous != nil && previous.health == next.health {\n276: \t\treturn actions\n277: \t}\n278: \tif next.health == clablabruntime.ContainerHealthStarting && !started {\n279: \t\treturn actions\n280: \t}\n281: \n282: \treturn append(actions, containerActionHealthPrefix+next.health)\n283: }\n284: \n285: // containerRemovalActions are the actions Docker reports when a container is removed: a running\n286: // one is killed and dies first.\n287: func containerRemovalActions(previous *trackedContainer) []string {\n288: \tif previous.state == clablabruntime.ContainerStateRunning {\n289: \t\treturn []string{containerActionKill, containerActionDie, containerActionDestroy}\n290: \t}\n291: \n292: \treturn []string{containerActionDestroy}\n293: }\n294: \n295: // containerActionState is the container state after an action, which every container event\n296: // reports in its state attribute.\n297: func containerActionState(action, snapshotState string) string {\n298: \tswitch action {\n299: \tcase containerActionCreate:\n300: \t\treturn clablabruntime.ContainerStateCreated\n301: \tcase containerActionStop, containerActionDie, containerActionDestroy:\n302: \t\treturn clablabruntime.ContainerStateExited\n303: \tcase containerActionStart, containerActionKill:\n304: \t\treturn clablabruntime.ContainerStateRunning\n305: \t}\n306: \tif strings.HasPrefix(action, containerActionHealthPrefix) {\n307: \t\treturn clablabruntime.ContainerStateRunning\n308: \t}\n309: \n310: \treturn snapshotState\n311: }\n312: \n313: func (t *containerTracker) emit(\n314: \tctx context.Context,\n315: \tstate *clablabruntime.LabState,\n316: \tnode clablabruntime.NodeState,\n317: \taction string,\n318: \textra map[string]string,\n319: ) {\n320: \tt.r.sendEvent(ctx, t.sink, c9sContainerEvent(state, node, action, extra))\n321: }\n322: \n323: // c9sContainerEvent is a container event of a node. The actor is the node, as for its interface\n324: // events; its ID is the container_id inspect reports. Lab and Node let the events command\n325: // describe the node with the attributes inspect and the Docker runtime report.\n326: func c9sContainerEvent(\n327: \tstate *clablabruntime.LabState,\n328: \tnode clablabruntime.NodeState,\n329: \taction string,\n330: \textra map[string]string,\n331: ) clablabruntime.Event {\n332: \tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n333: \tattributes := map[string]string{\n334: \t\t\"namespace\":                  state.Namespace,\n335: \t\t\"lab\":                        state.Name,\n336: \t\t\"node\":                       node.Name,\n337: \t\tcontainerEventAttributeState: containerActionState(action, node.ContainerState),\n338: \t}\n339: \tif node.Pod != \"\" {\n340: \t\tattributes[\"pod\"] = node.Pod\n341: \t}\n342: \tif action == containerActionKill {\n343: \t\t// Kubernetes stops a pod's containers with SIGTERM.\n344: \t\tattributes[\"signal\"] = containerEventSignalSIGTERM\n345: \t}\n346: \tfor k, v := range extra {\n347: \t\tattributes[k] = v\n348: \t}\n349: \n350: \tnodeCopy := node\n351: \n352: \treturn clablabruntime.Event{\n353: \t\tTimestamp:   time.Now(),\n354: \t\tType:        clablabruntime.EventTypeContainer,\n355: \t\tAction:      action,\n356: \t\tActorID:     key,\n357: \t\tActorName:   fmt.Sprintf(\"%s-%s\", state.Name, node.Name),\n358: \t\tActorFullID: key,\n359: \t\tAttributes:  attributes,\n360: \t\tLab:         state,\n361: \t\tNode:        &nodeCopy,\n362: \t}\n363: }\n\n(End of file - total 363 lines)\n</content>",
    "title": "source/head/labruntime/clabernetes/container_events.go",
    "metadata": {
      "preview": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\n// Container event actions, as the Docker runtime reports them.\nconst (\n\tcontainerActionCreate        = \"create\"\n\tcontainerActionStart         = \"start\"\n\tcontainerActionKill          = \"kill\"\n\tcontainerActionStop          = \"stop\"\n\tcontainerActionDie           = \"die\"",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/container_events.go",
        "text": "package clabernetes\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/charmbracelet/log\"\n\tclablabruntime \"github.com/srl-labs/containerlab/labruntime\"\n)\n\n// Container event actions, as the Docker runtime reports them.\nconst (\n\tcontainerActionCreate        = \"create\"\n\tcontainerActionStart         = \"start\"\n\tcontainerActionKill          = \"kill\"\n\tcontainerActionStop          = \"stop\"\n\tcontainerActionDie           = \"die\"\n\tcontainerActionDestroy       = \"destroy\"\n\tcontainerActionHealthPrefix  = \"health_status: \"\n\tcontainerEventSignalSIGTERM  = \"15\"\n\tcontainerRefreshDelay        = 200 * time.Millisecond\n\tcontainerRefreshRetryDelay   = pollInterval\n\tcontainerEventAttributeState = \"state\"\n)\n\n// trackedContainer is the last reported container state of a node.\ntype trackedContainer struct {\n\tref    labRef\n\tstate  string\n\thealth string\n\tpod    string\n\t// lab and node are the last observation, which a removed node is described with.\n\tlab  *clablabruntime.LabState\n\tnode clablabruntime.NodeState\n}\n\n// containerTracker turns the node states of the labs in an event scope into the container\n// events the Docker runtime emits for the same lifecycle: create and start when a node's pod\n// starts, kill, stop and die when it stops (on request, or between the pods of a restart),\n// destroy when the node is removed, and health_status as its device becomes ready.\ntype containerTracker struct {\n\tr     *Runtime\n\tsink  chan<- clablabruntime.Event\n\tnodes map[string]*trackedContainer\n}\n\n// trackContainers reports the container events of a scope. It reads the labs once, reporting\n// them as a snapshot when the stream includes the initial state, and then reads a lab again\n// whenever its Topology, Nodes or pods change. Changes that arrive together are read once.\nfunc (r *Runtime) trackContainers(\n\tctx context.Context,\n\tscope eventScope,\n\tincludeInitialState bool,\n\tchanged <-chan labRef,\n\teventSink chan<- clablabruntime.Event,\n\terrSink chan<- error,\n) {\n\ttracker := &containerTracker{r: r, sink: eventSink, nodes: map[string]*trackedContainer{}}\n\n\tstates, err := r.labStates(ctx, scope)\n\tif err != nil {\n\t\tsendEventError(ctx, errSink, err)\n\t\treturn\n\t}\n\tfor _, state := range states {\n\t\ttracker.observeLab(ctx, labRef{namespace: state.Namespace, lab: state.Name}, state,\n\t\t\t&observeSeed{snapshot: includeInitialState})\n\t}\n\n\tpending := map[labRef]bool{}\n\ttimer := time.NewTimer(time.Hour)\n\ttimer.Stop()\n\tdefer timer.Stop()\n\tarmed := false\n\tarm := func(delay time.Duration) {\n\t\tif !armed {\n\t\t\ttimer.Reset(delay)\n\t\t\tarmed = true\n\t\t}\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase ref := <-changed:\n\t\t\tpending[ref] = true\n\t\t\tarm(containerRefreshDelay)\n\t\tcase <-timer.C:\n\t\t\tarmed = false\n\t\t\trefs := pending\n\t\t\tpending = map[labRef]bool{}\n\t\t\tfor ref := range refs {\n\t\t\t\tif !tracker.refresh(ctx, ref) {\n\t\t\t\t\tpending[ref] = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(pending) != 0 {\n\t\t\t\tarm(containerRefreshRetryDelay)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// observeSeed marks the first observation of a stream: it records the node states without\n// reporting changes, and reports them as a snapshot when asked to.\ntype observeSeed struct {\n\tsnapshot bool\n}\n\n// refresh reads a lab again and reports what changed for its nodes. A lab that is gone reports\n// its nodes as destroyed. It returns false when the lab could not be read.\nfunc (t *containerTracker) refresh(ctx context.Context, ref labRef) bool {\n\tstate, err := t.r.Inspect(ctx, clablabruntime.InspectRequest{\n\t\tName:      ref.lab,\n\t\tNamespace: ref.namespace,\n\t})\n\tif err != nil {\n\t\tvar notFound *labNotFoundError\n\t\tif !errors.As(err, &notFound) {\n\t\t\tif ctx.Err() == nil {\n\t\t\t\tlog.Debug(\"Failed to read a C9s lab for container events\",\n\t\t\t\t\t\"namespace\", ref.namespace, \"lab\", ref.lab, \"error\", err)\n\t\t\t}\n\n\t\t\treturn ctx.Err() != nil\n\t\t}\n\t\tstate = nil\n\t}\n\n\tt.observeLab(ctx, ref, state, nil)\n\n\treturn true\n}\n\n// observeLab compares the nodes of a lab with what was reported before and reports the\n// difference. A nil state removes every node of the lab.\nfunc (t *containerTracker) observeLab(\n\tctx context.Context,\n\tref labRef,\n\tstate *clablabruntime.LabState,\n\tseed *observeSeed,\n) {\n\tseen := map[string]bool{}\n\tif state != nil {\n\t\tfor idx := range state.Nodes {\n\t\t\tkey := c9sNodeKey(state.Namespace, state.Name, state.Nodes[idx].Name)\n\t\t\tseen[key] = true\n\t\t\tt.observeNode(ctx, ref, state, state.Nodes[idx], seed)\n\t\t}\n\t}\n\n\tfor key, tracked := range t.nodes {\n\t\tif tracked.ref != ref || seen[key] {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, action := range containerRemovalActions(tracked) {\n\t\t\tt.emit(ctx, tracked.lab, tracked.node, action, nil)\n\t\t}\n\t\tdelete(t.nodes, key)\n\t}\n}\n\nfunc (t *containerTracker) observeNode(\n\tctx context.Context,\n\tref labRef,\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n\tseed *observeSeed,\n) {\n\tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n\tprevious := t.nodes[key]\n\tif node.ContainerState == \"\" {\n\t\tnode.ContainerState = clablabruntime.ContainerStateCreated\n\t}\n\tnext := &trackedContainer{\n\t\tref:   ref,\n\t\tstate: node.ContainerState,\n\t\tpod:   node.Pod,\n\t\tlab:   state,\n\t\tnode:  node,\n\t}\n\tnext.health = containerHealth(previous, next, node.Health)\n\tt.nodes[key] = next\n\n\tif seed != nil {\n\t\tif seed.snapshot {\n\t\t\tt.emit(ctx, state, node, next.state, map[string]string{\n\t\t\t\t\"origin\": clablabruntime.EventOriginSnapshot,\n\t\t\t})\n\t\t}\n\n\t\treturn\n\t}\n\n\tfor _, action := range containerTransitionActions(previous, next) {\n\t\tt.emit(ctx, state, node, action, nil)\n\t}\n}\n\n// containerHealth is the health a running node reports: a node that was healthy and is not\n// ready anymore in the same pod is unhealthy, as a container whose healthcheck starts failing.\nfunc containerHealth(previous, next *trackedContainer, health string) string {\n\tif next.state != clablabruntime.ContainerStateRunning {\n\t\treturn \"\"\n\t}\n\tif health == \"\" {\n\t\thealth = clablabruntime.ContainerHealthStarting\n\t}\n\tif health == clablabruntime.ContainerHealthStarting && previous != nil &&\n\t\tprevious.state == clablabruntime.ContainerStateRunning && previous.pod == next.pod &&\n\t\t(previous.health == clablabruntime.ContainerHealthHealthy ||\n\t\t\tprevious.health == clablabruntime.ContainerHealthUnhealthy) {\n\t\treturn clablabruntime.ContainerHealthUnhealthy\n\t}\n\n\treturn health\n}\n\n// containerTransitionActions are the container event actions Docker reports when a container\n// goes from the previous to the next state:\n//\n//\tnew node            create (+ start when it runs, + stop when it is already stopped)\n//\tcreated -> running  start\n//\texited  -> running  start\n//\trunning -> exited   kill, stop, die (stop, or the old pod of a restart ending)\n//\trunning -> created  kill, stop, die (the replacement pod of a restart not running yet)\n//\trunning, new pod    kill, stop, die, start (restart)\n//\tcreated -> exited   stop\n//\n// A started node also reports its health (health_status: starting or healthy), and a running\n// node reports health changes, like a container with a healthcheck.\nfunc containerTransitionActions(previous, next *trackedContainer) []string {\n\tconst (\n\t\tcreated = clablabruntime.ContainerStateCreated\n\t\trunning = clablabruntime.ContainerStateRunning\n\t\texited  = clablabruntime.ContainerStateExited\n\t)\n\n\tvar actions []string\n\tpreviousState := \"\"\n\tif previous != nil {\n\t\tpreviousState = previous.state\n\t}\n\n\tswitch {\n\tcase previous == nil:\n\t\tactions = append(actions, containerActionCreate)\n\t\tswitch next.state {\n\t\tcase running:\n\t\t\tactions = append(actions, containerActionStart)\n\t\tcase exited:\n\t\t\tactions = append(actions, containerActionStop)\n\t\t}\n\tcase previousState == running && next.state == running && previous.pod != next.pod:\n\t\tactions = append(actions, containerActionKill, containerActionStop, containerActionDie,\n\t\t\tcontainerActionStart)\n\tcase previousState == running && next.state != running:\n\t\tactions = append(actions, containerActionKill, containerActionStop, containerActionDie)\n\tcase previousState != running && next.state == running:\n\t\tactions = append(actions, containerActionStart)\n\tcase previousState == created && next.state == exited:\n\t\tactions = append(actions, containerActionStop)\n\t}\n\n\tif next.state != running {\n\t\treturn actions\n\t}\n\n\tstarted := len(actions) != 0 && actions[len(actions)-1] == containerActionStart\n\tif !started && previous != nil && previous.health == next.health {\n\t\treturn actions\n\t}\n\tif next.health == clablabruntime.ContainerHealthStarting && !started {\n\t\treturn actions\n\t}\n\n\treturn append(actions, containerActionHealthPrefix+next.health)\n}\n\n// containerRemovalActions are the actions Docker reports when a container is removed: a running\n// one is killed and dies first.\nfunc containerRemovalActions(previous *trackedContainer) []string {\n\tif previous.state == clablabruntime.ContainerStateRunning {\n\t\treturn []string{containerActionKill, containerActionDie, containerActionDestroy}\n\t}\n\n\treturn []string{containerActionDestroy}\n}\n\n// containerActionState is the container state after an action, which every container event\n// reports in its state attribute.\nfunc containerActionState(action, snapshotState string) string {\n\tswitch action {\n\tcase containerActionCreate:\n\t\treturn clablabruntime.ContainerStateCreated\n\tcase containerActionStop, containerActionDie, containerActionDestroy:\n\t\treturn clablabruntime.ContainerStateExited\n\tcase containerActionStart, containerActionKill:\n\t\treturn clablabruntime.ContainerStateRunning\n\t}\n\tif strings.HasPrefix(action, containerActionHealthPrefix) {\n\t\treturn clablabruntime.ContainerStateRunning\n\t}\n\n\treturn snapshotState\n}\n\nfunc (t *containerTracker) emit(\n\tctx context.Context,\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n\taction string,\n\textra map[string]string,\n) {\n\tt.r.sendEvent(ctx, t.sink, c9sContainerEvent(state, node, action, extra))\n}\n\n// c9sContainerEvent is a container event of a node. The actor is the node, as for its interface\n// events; its ID is the container_id inspect reports. Lab and Node let the events command\n// describe the node with the attributes inspect and the Docker runtime report.\nfunc c9sContainerEvent(\n\tstate *clablabruntime.LabState,\n\tnode clablabruntime.NodeState,\n\taction string,\n\textra map[string]string,\n) clablabruntime.Event {\n\tkey := c9sNodeKey(state.Namespace, state.Name, node.Name)\n\tattributes := map[string]string{\n\t\t\"namespace\":                  state.Namespace,\n\t\t\"lab\":                        state.Name,\n\t\t\"node\":                       node.Name,\n\t\tcontainerEventAttributeState: containerActionState(action, node.ContainerState),\n\t}\n\tif node.Pod != \"\" {\n\t\tattributes[\"pod\"] = node.Pod\n\t}\n\tif action == containerActionKill {\n\t\t// Kubernetes stops a pod's containers with SIGTERM.\n\t\tattributes[\"signal\"] = containerEventSignalSIGTERM\n\t}\n\tfor k, v := range extra {\n\t\tattributes[k] = v\n\t}\n\n\tnodeCopy := node\n\n\treturn clablabruntime.Event{\n\t\tTimestamp:   time.Now(),\n\t\tType:        clablabruntime.EventTypeContainer,\n\t\tAction:      action,\n\t\tActorID:     key,\n\t\tActorName:   fmt.Sprintf(\"%s-%s\", state.Name, node.Name),\n\t\tActorFullID: key,\n\t\tAttributes:  attributes,\n\t\tLab:         state,\n\t\tNode:        &nodeCopy,\n\t}\n}",
        "lineStart": 1,
        "lineEnd": 363,
        "totalLines": 363,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525893281,
      "end": 1793525893297
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1967948b40012PTz57Xsss65Rf",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967933250015p7FwvX5lKOiLP",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 55803,
    "input": 2607,
    "output": 44,
    "reasoning": 288,
    "cache": {
      "read": 52864,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1967933250015p7FwvX5lKOiLP",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525887781,
    "completed": 1793525893304
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 55803,
    "input": 2607,
    "output": 44,
    "reasoning": 288,
    "cache": {
      "read": 52864,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 32
step-start
{
  "type": "step-start",
  "id": "prt_196797c6b001Gr7T6UKbDCKrZe",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967948c1001HhckZv31xZi1PZ"
}
Reasoning
One subtle behavior in `containerTransitionActions`: `case previousState != running && next.state == running: actions = append(actions, containerActionStart)` — this catches `previousState == exited -> running` (restart), and also `previousState == ""`? No, previous==nil handled. What about previousState == exited and next.state == created? falls to default (no actions) — fine.

Edge: `previousState == exited && next.state == exited` — no actions. Fine.

`started` detection: actions last element == start. For a restart (running→running new pod), actions end with start, and health appended. If health is "healthy" and started → emits health_status: healthy. If health is "starting" and started → emits health_status: starting. Per robot test: health_status: healthy appended. OK.

Edge: if next.health == "starting" and started is false and previous != nil and previous.health != next.health — third check `next.health == starting && !started` returns actions (no health event) — correct, matches "starting only on start".

Wait, there's a subtle bug candidate: second check `if !started && previous != nil && previous.health == next.health { return actions }`. If `started` is false and previous.health != next.health and next.health is healthy → append health_status: healthy. Good. If started is true, skip this check, then third check: next.health == starting && !started → false, so append health_status: starting/healthy. Good.

But what if actions is nil (no state change) and previous == nil? previous==nil always yields create so actions non-nil. If no transition (same state, same pod), actions is nil, started=false, previous.health == next.health → return nil. If health changed from healthy to starting (same pod, same state) → containerHealth would have returned unhealthy (if previous healthy/starting→unhealthy when starting on same pod) or healthy. Health transitions emit health_status. OK.

Now, one thing: `containerHealth` returns unhealthy when a previously healthy node becomes not-ready in same pod. But it never transitions back from unhealthy to starting/healthy? If health == healthy it returns healthy — recovers. Good.

Now remaining verification:
1. stream.go rest (lines 70-600) — the events command formatting; summary says partially read. Let me quickly skim for issues.
2. netlink.go rest.
3. Tests: parity_test.go, event_parity_test.go (skim key coverage), labruntime_gaps_test.go, runtime_gaps_test.go.
4. Docs: events.md, interfaces.md, runtime.md (skim for consistency).
5. reconcile.go hunk and plan.go hunk for the annotation flows (read).
6. runtime.go Inspect lab-not-found (read relevant part).
7. Robot test file.

Given budget, prioritize: reconcile.go 180-260, plan.go 30-80, runtime.go (grep labNotFoundError), stream.go skim, then docs skim, tests skim, robot tests.
`container_events.go` is consistent. Now the reconcile/plan hunks and `runtime.go`'s Inspect semantics.
read · completed

Input

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

Output

<path>/source/head/labruntime/clabernetes/reconcile.go</path>
<type>file</type>
<content>
170: 		}
171: 
172: 		actual, err = resource.Update(ctx, updated, metav1.UpdateOptions{})
173: 		return err
174: 	})
175: 	if err != nil {
176: 		return nil, false, fmt.Errorf("failed to reconcile c9s %s %s/%s: %w",
177: 			kind, namespace, desired.GetName(), err)
178: 	}
179: 
180: 	return actual, created, nil
181: }
182: 
183: func reconciledPrimitiveObject(
184: 	existing,
185: 	desired *unstructured.Unstructured,
186: ) *unstructured.Unstructured {
187: 	updated := existing.DeepCopy()
188: 	if desiredSpec, ok := desired.Object["spec"]; ok {
189: 		updated.Object["spec"] = k8sruntime.DeepCopyJSONValue(desiredSpec)
190: 	} else {
191: 		delete(updated.Object, "spec")
192: 	}
193: 
194: 	carryOverNodeRunState(existing, updated)
195: 
196: 	updated.SetLabels(mergeDesiredMetadata(existing.GetLabels(), desired.GetLabels()))
197: 	updated.SetAnnotations(
198: 		mergeDesiredMetadata(existing.GetAnnotations(), desired.GetAnnotations()),
199: 	)
200: 	carryOverNodeTopologyFile(existing, updated)
201: 
202: 	return updated
203: }
204: 
205: // carryOverNodeTopologyFile keeps the topology file an existing Node recorded, or its absence.
206: // clabernetes copies a Node's annotations into its pod template, so changing the annotation
207: // would replace the node's pod although nothing about the node changed. A Node therefore keeps
208: // the file the lab was deployed from when the Node was created. The Topology resource has no
209: // such effect and always records the file of the latest deploy.
210: func carryOverNodeTopologyFile(existing, updated *unstructured.Unstructured) {
211: 	if existing.GetKind() != "Node" || existing.GetAPIVersion() != c9sAPIVersion {
212: 		return
213: 	}
214: 
215: 	path, found := existing.GetAnnotations()[annotationTopologyFile]
216: 	if !found {
217: 		removeTopologySourceFile(updated)
218: 		return
219: 	}
220: 
221: 	setTopologySourceFile(updated, path)
222: }
223: 
224: // carryOverNodeRunState keeps the run state of an existing Node. spec.runState is operational
225: // state that stop and start own, not part of the compiled definition: the compiler never sets
226: // it, so replacing the spec would start a stopped node on every apply, and the API default
227: // (Running) would otherwise count as drift on every plan. Restart requests live in annotations,
228: // which the merge keeps.
229: func carryOverNodeRunState(existing, updated *unstructured.Unstructured) {
230: 	if existing.GetKind() != "Node" || existing.GetAPIVersion() != c9sAPIVersion {
231: 		return
232: 	}
233: 
234: 	runState, found, _ := unstructured.NestedString(existing.Object, "spec", "runState")
235: 	if !found || runState == "" {
236: 		unstructured.RemoveNestedField(updated.Object, "spec", "runState")
237: 		return
238: 	}
239: 
240: 	_ = unstructured.SetNestedField(updated.Object, runState, "spec", "runState")
241: }
242: 
243: func mergeDesiredMetadata(existing, desired map[string]string) map[string]string {
244: 	result := make(map[string]string, len(existing)+len(desired))
245: 	for key, value := range existing {
246: 		result[key] = value
247: 	}
248: 	for key, value := range desired {
249: 		result[key] = value

(Showing lines 170-249 of 685. Use offset=250 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1967991fc001cHiCLAltodIubC",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967948c1001HhckZv31xZi1PZ",
  "callID": "call_93536e61451f48d69026054c",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/reconcile.go",
      "limit": 80,
      "offset": 170
    },
    "output": "<path>/source/head/labruntime/clabernetes/reconcile.go</path>\n<type>file</type>\n<content>\n170: \t\t}\n171: \n172: \t\tactual, err = resource.Update(ctx, updated, metav1.UpdateOptions{})\n173: \t\treturn err\n174: \t})\n175: \tif err != nil {\n176: \t\treturn nil, false, fmt.Errorf(\"failed to reconcile c9s %s %s/%s: %w\",\n177: \t\t\tkind, namespace, desired.GetName(), err)\n178: \t}\n179: \n180: \treturn actual, created, nil\n181: }\n182: \n183: func reconciledPrimitiveObject(\n184: \texisting,\n185: \tdesired *unstructured.Unstructured,\n186: ) *unstructured.Unstructured {\n187: \tupdated := existing.DeepCopy()\n188: \tif desiredSpec, ok := desired.Object[\"spec\"]; ok {\n189: \t\tupdated.Object[\"spec\"] = k8sruntime.DeepCopyJSONValue(desiredSpec)\n190: \t} else {\n191: \t\tdelete(updated.Object, \"spec\")\n192: \t}\n193: \n194: \tcarryOverNodeRunState(existing, updated)\n195: \n196: \tupdated.SetLabels(mergeDesiredMetadata(existing.GetLabels(), desired.GetLabels()))\n197: \tupdated.SetAnnotations(\n198: \t\tmergeDesiredMetadata(existing.GetAnnotations(), desired.GetAnnotations()),\n199: \t)\n200: \tcarryOverNodeTopologyFile(existing, updated)\n201: \n202: \treturn updated\n203: }\n204: \n205: // carryOverNodeTopologyFile keeps the topology file an existing Node recorded, or its absence.\n206: // clabernetes copies a Node's annotations into its pod template, so changing the annotation\n207: // would replace the node's pod although nothing about the node changed. A Node therefore keeps\n208: // the file the lab was deployed from when the Node was created. The Topology resource has no\n209: // such effect and always records the file of the latest deploy.\n210: func carryOverNodeTopologyFile(existing, updated *unstructured.Unstructured) {\n211: \tif existing.GetKind() != \"Node\" || existing.GetAPIVersion() != c9sAPIVersion {\n212: \t\treturn\n213: \t}\n214: \n215: \tpath, found := existing.GetAnnotations()[annotationTopologyFile]\n216: \tif !found {\n217: \t\tremoveTopologySourceFile(updated)\n218: \t\treturn\n219: \t}\n220: \n221: \tsetTopologySourceFile(updated, path)\n222: }\n223: \n224: // carryOverNodeRunState keeps the run state of an existing Node. spec.runState is operational\n225: // state that stop and start own, not part of the compiled definition: the compiler never sets\n226: // it, so replacing the spec would start a stopped node on every apply, and the API default\n227: // (Running) would otherwise count as drift on every plan. Restart requests live in annotations,\n228: // which the merge keeps.\n229: func carryOverNodeRunState(existing, updated *unstructured.Unstructured) {\n230: \tif existing.GetKind() != \"Node\" || existing.GetAPIVersion() != c9sAPIVersion {\n231: \t\treturn\n232: \t}\n233: \n234: \trunState, found, _ := unstructured.NestedString(existing.Object, \"spec\", \"runState\")\n235: \tif !found || runState == \"\" {\n236: \t\tunstructured.RemoveNestedField(updated.Object, \"spec\", \"runState\")\n237: \t\treturn\n238: \t}\n239: \n240: \t_ = unstructured.SetNestedField(updated.Object, runState, \"spec\", \"runState\")\n241: }\n242: \n243: func mergeDesiredMetadata(existing, desired map[string]string) map[string]string {\n244: \tresult := make(map[string]string, len(existing)+len(desired))\n245: \tfor key, value := range existing {\n246: \t\tresult[key] = value\n247: \t}\n248: \tfor key, value := range desired {\n249: \t\tresult[key] = value\n\n(Showing lines 170-249 of 685. Use offset=250 to continue.)\n</content>",
    "title": "source/head/labruntime/clabernetes/reconcile.go",
    "metadata": {
      "preview": "\t\t}\n\n\t\tactual, err = resource.Update(ctx, updated, metav1.UpdateOptions{})\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"failed to reconcile c9s %s %s/%s: %w\",\n\t\t\tkind, namespace, desired.GetName(), err)\n\t}\n\n\treturn actual, created, nil\n}\n\nfunc reconciledPrimitiveObject(\n\texisting,\n\tdesired *unstructured.Unstructured,\n) *unstructured.Unstructured {\n\tupdated := existing.DeepCopy()\n\tif desiredSpec, ok := desired.Object[\"spec\"]; ok {\n\t\tupdated.Object[\"spec\"] = k8sruntime.DeepCopyJSONValue(desiredSpec)",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/reconcile.go",
        "text": "\t\t}\n\n\t\tactual, err = resource.Update(ctx, updated, metav1.UpdateOptions{})\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"failed to reconcile c9s %s %s/%s: %w\",\n\t\t\tkind, namespace, desired.GetName(), err)\n\t}\n\n\treturn actual, created, nil\n}\n\nfunc reconciledPrimitiveObject(\n\texisting,\n\tdesired *unstructured.Unstructured,\n) *unstructured.Unstructured {\n\tupdated := existing.DeepCopy()\n\tif desiredSpec, ok := desired.Object[\"spec\"]; ok {\n\t\tupdated.Object[\"spec\"] = k8sruntime.DeepCopyJSONValue(desiredSpec)\n\t} else {\n\t\tdelete(updated.Object, \"spec\")\n\t}\n\n\tcarryOverNodeRunState(existing, updated)\n\n\tupdated.SetLabels(mergeDesiredMetadata(existing.GetLabels(), desired.GetLabels()))\n\tupdated.SetAnnotations(\n\t\tmergeDesiredMetadata(existing.GetAnnotations(), desired.GetAnnotations()),\n\t)\n\tcarryOverNodeTopologyFile(existing, updated)\n\n\treturn updated\n}\n\n// carryOverNodeTopologyFile keeps the topology file an existing Node recorded, or its absence.\n// clabernetes copies a Node's annotations into its pod template, so changing the annotation\n// would replace the node's pod although nothing about the node changed. A Node therefore keeps\n// the file the lab was deployed from when the Node was created. The Topology resource has no\n// such effect and always records the file of the latest deploy.\nfunc carryOverNodeTopologyFile(existing, updated *unstructured.Unstructured) {\n\tif existing.GetKind() != \"Node\" || existing.GetAPIVersion() != c9sAPIVersion {\n\t\treturn\n\t}\n\n\tpath, found := existing.GetAnnotations()[annotationTopologyFile]\n\tif !found {\n\t\tremoveTopologySourceFile(updated)\n\t\treturn\n\t}\n\n\tsetTopologySourceFile(updated, path)\n}\n\n// carryOverNodeRunState keeps the run state of an existing Node. spec.runState is operational\n// state that stop and start own, not part of the compiled definition: the compiler never sets\n// it, so replacing the spec would start a stopped node on every apply, and the API default\n// (Running) would otherwise count as drift on every plan. Restart requests live in annotations,\n// which the merge keeps.\nfunc carryOverNodeRunState(existing, updated *unstructured.Unstructured) {\n\tif existing.GetKind() != \"Node\" || existing.GetAPIVersion() != c9sAPIVersion {\n\t\treturn\n\t}\n\n\trunState, found, _ := unstructured.NestedString(existing.Object, \"spec\", \"runState\")\n\tif !found || runState == \"\" {\n\t\tunstructured.RemoveNestedField(updated.Object, \"spec\", \"runState\")\n\t\treturn\n\t}\n\n\t_ = unstructured.SetNestedField(updated.Object, runState, \"spec\", \"runState\")\n}\n\nfunc mergeDesiredMetadata(existing, desired map[string]string) map[string]string {\n\tresult := make(map[string]string, len(existing)+len(desired))\n\tfor key, value := range existing {\n\t\tresult[key] = value\n\t}\n\tfor key, value := range desired {\n\t\tresult[key] = value",
        "lineStart": 170,
        "lineEnd": 249,
        "totalLines": 685,
        "truncated": true
      }
    },
    "time": {
      "start": 1793525912067,
      "end": 1793525912076
    }
  }
}
grep · completed

Input

{
  "path": "/source/head/labruntime",
  "pattern": "labNotFoundError"
}

Output

Found 6 matches
/source/head/labruntime/clabernetes/lifecycle.go:
  Line 478: 			return nil, &labNotFoundError{namespace: namespace, name: req.Name}

  Line 490: // labNotFoundError reports a lab without a Topology or Node resource.

  Line 491: type labNotFoundError struct {

  Line 496: func (e *labNotFoundError) Error() string {


/source/head/labruntime/clabernetes/container_events.go:
  Line 122: 		var notFound *labNotFoundError


/source/head/labruntime/clabernetes/events.go:
  Line 126: 			var notFound *labNotFoundError
Tool metadata
{
  "type": "tool",
  "id": "prt_196799252001e8xFnrqkwROJGI",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967948c1001HhckZv31xZi1PZ",
  "callID": "call_08ceb074e6024e9f8955efbb",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/labruntime",
      "pattern": "labNotFoundError"
    },
    "output": "Found 6 matches\n/source/head/labruntime/clabernetes/lifecycle.go:\n  Line 478: \t\t\treturn nil, &labNotFoundError{namespace: namespace, name: req.Name}\n\n  Line 490: // labNotFoundError reports a lab without a Topology or Node resource.\n\n  Line 491: type labNotFoundError struct {\n\n  Line 496: func (e *labNotFoundError) Error() string {\n\n\n/source/head/labruntime/clabernetes/container_events.go:\n  Line 122: \t\tvar notFound *labNotFoundError\n\n\n/source/head/labruntime/clabernetes/events.go:\n  Line 126: \t\t\tvar notFound *labNotFoundError\n",
    "title": "labNotFoundError",
    "metadata": {
      "matches": 6,
      "truncated": false
    },
    "time": {
      "start": 1793525912152,
      "end": 1793525912165
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1967992670010YOQV9ZGpTW04N",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967948c1001HhckZv31xZi1PZ",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 60261,
    "input": 4001,
    "output": 77,
    "reasoning": 631,
    "cache": {
      "read": 55552,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1967948c1001HhckZv31xZi1PZ",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525893313,
    "completed": 1793525912171
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 60261,
    "input": 4001,
    "output": 77,
    "reasoning": 631,
    "cache": {
      "read": 55552,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 33
step-start
{
  "type": "step-start",
  "id": "prt_196799ae5001sAE3m3SFOBLzD0",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679927600105YN910bsH6Rk2"
}
Reasoning
The annotation flow is coherent and well-tested. Now skim the tests and docs. Priority: event_parity_test.go (new), parity_test.go (new), labruntime_gaps_test.go changes, runtime_gaps_test.go, docs. And robot tests. Let me read event_parity_test.go key sections — it's large presumably; grep for test names.
The annotation carry-over is well-reasoned. Now survey the test coverage added.
grep · completed

Input

{
  "path": "/source/head",
  "pattern": "^func Test[A-Za-z0-9_]+\\(t \\*testing\\.T\\)",
  "include": "*_test.go"
}

Output

Found 100 matches (more matches available)
/source/head/types/bind_test.go:
  Line 10: func TestNewBind(t *testing.T) {

  Line 63: func TestNewBindFromString(t *testing.T) {

  Line 164: func TestBind_Accessors(t *testing.T) {

  Line 213: func TestBind_String(t *testing.T) {

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


/source/head/types/hostentry_test.go:
  Line 9: func TestHostEntry_MethodChaining(t *testing.T) {

  Line 91: func TestNewHostEntry(t *testing.T) {

  Line 144: func TestHostEntry_SetContainerID(t *testing.T) {

  Line 230: func TestHostEntry_SetDescription(t *testing.T) {

  Line 301: func TestHostEntry_ToHostEntryString(t *testing.T) {

  Line 421: func TestHostEntries_ToHostsConfig(t *testing.T) {

  Line 531: func TestHostEntries_Merge(t *testing.T) {


/source/head/exec/exec_test.go:
  Line 13: func TestParseExecOutputFormat(t *testing.T) {

  Line 78: func TestExecCollectionLogPreservesAddOrder(t *testing.T) {


/source/head/types/volume_test.go:
  Line 10: func TestNewVolumeFromString(t *testing.T) {

  Line 105: func TestVolume_Accessors(t *testing.T) {

  Line 159: func TestVolume_String(t *testing.T) {

  Line 218: func TestVolume_Options(t *testing.T) {

  Line 261: func TestParseVolumeOptions(t *testing.T) {


/source/head/types/stages_test.go:
  Line 9: func TestEquals(t *testing.T) {

  Line 51: func TestMerge(t *testing.T) {


/source/head/types/node_definition_test.go:
  Line 10: func TestNodeDefinitionYAML_CredentialsNested(t *testing.T) {

  Line 26: func TestNodeDefinitionYAML_LegacyFlatUsernamePassword(t *testing.T) {

  Line 41: func TestNodeDefinitionYAML_CredentialsWinsOverLegacy(t *testing.T) {

  Line 59: func TestNodeDefinitionYAML_KindSpecificConfigRoundTrip(t *testing.T) {


/source/head/types/mgmt_test.go:
  Line 9: func TestNodeConfigManagementIPAMEligible(t *testing.T) {

  Line 30: func TestMgmtDriverValidation(t *testing.T) {

  Line 46: func TestMacvlanManagementValidation(t *testing.T) {

  Line 148: func TestMacvlanAuxEnabled(t *testing.T) {

  Line 171: func TestDADValidation(t *testing.T) {

  Line 186: func TestManagementIPAMYAML(t *testing.T) {

  Line 209: func TestMgmtTailscaleYAML(t *testing.T) {

  Line 225: func TestMgmtTailscaleValidation(t *testing.T) {


/source/head/types/topo_diff_test.go:
  Line 5: func TestTopologyDiffDefaultAction(t *testing.T) {


/source/head/types/topology_test.go:
  Line 713: func TestGetNodeKind(t *testing.T) {

  Line 725: func TestGetNodeGroup(t *testing.T) {

  Line 739: func TestGetNodeType(t *testing.T) {

  Line 753: func TestGetNodeConfig(t *testing.T) {

  Line 769: func TestGetNodeImage(t *testing.T) {

  Line 785: func TestGetNodeImageOnlyViaDefault(t *testing.T) {

  Line 826: func TestGetNodeLicense(t *testing.T) {

  Line 842: func TestGetNodePosition(t *testing.T) {

  Line 856: func TestGetNodeHostname(t *testing.T) {

  Line 894: func TestGetNodeCmd(t *testing.T) {

  Line 908: func TestGetNodeExec(t *testing.T) {

  Line 922: func TestGetNodeUser(t *testing.T) {

  Line 936: func TestGetNodeBinds(t *testing.T) {

  Line 955: func TestGetNodeVolumes(t *testing.T) {

  Line 974: func TestGetNodeVolumesInheritance(t *testing.T) {

  Line 1016: func TestGetNodeBindsRejectsAnonymousVolumeSyntax(t *testing.T) {

  Line 1032: func TestGetNodeVolumesHandlesNilNodeDefinition(t *testing.T) {

  Line 1049: func TestGetNodeBindsDeterministicOrder(t *testing.T) {

  Line 1082: func TestGetNodeEnv(t *testing.T) {

  Line 1096: func TestGetNodeLabels(t *testing.T) {

  Line 1110: func TestGetNodeAutoRemove(t *testing.T) {

  Line 1130: func TestGetNodeDNS(t *testing.T) {

  Line 1149: func TestGetNodeCertificateConfig(t *testing.T) {

  Line 1165: func TestGetNodeCredentials(t *testing.T) {

  Line 1437: func TestGetNodeCredentialTopologySource(t *testing.T) {

  Line 1553: func TestGetNodeRuntimeOptions(t *testing.T) {

  Line 1635: func TestGetNodeCgroupParent(t *testing.T) {

  Line 1679: func TestGetNodePrivilegedDefault(t *testing.T) {

  Line 1694: func TestGetNodeKindSpecificConfig(t *testing.T) {

  Line 1745: func TestGetKindCaseInsensitive(t *testing.T) {


/source/head/types/tailscale_ports_test.go:
  Line 8: func TestSplitDockerAndTailscalePorts(t *testing.T) {

  Line 34: func TestSplitDockerAndTailscalePortsInvalid(t *testing.T) {

  Line 49: func TestGetNodePortMappings(t *testing.T) {

  Line 104: func TestTailscaleConfigProxy(t *testing.T) {


/source/head/types/mgmt_networks_test.go:
  Line 11: func TestMgmtNetworksUnmarshalYAML(t *testing.T) {

  Line 50: func TestMgmtNetworksUnmarshalYAMLReportsListFieldErrors(t *testing.T) {

  Line 58: func TestMgmtNetworksMarshalYAML(t *testing.T) {

  Line 83: func TestMgmtNetworksMarshalJSON(t *testing.T) {


/source/head/capture/local_test.go:
  Line 217: func TestCaptureLocalMergesInterfacesInTimestampOrder(t *testing.T) {

  Line 294: func TestCaptureLocalEndsAfterTheDurationOrWhenCanceled(t *testing.T) {

  Line 333: func TestCaptureLocalWritesPacketsStillInTheRingWhenItEnds(t *testing.T) {

  Line 370: func TestCaptureLocalFailsWithoutOutputWhenAnInterfaceCannotBeOpened(t *testing.T) {

  Line 395: func TestCaptureLocalReopensInterfacesAndReportsWhileTheyWereGone(t *testing.T) {

  Line 459: func TestCaptureLocalChecksTheRequest(t *testing.T) {


/source/head/capture/reorder_test.go:
  Line 89: func TestReorderOrdersStreamsWithinTheWindow(t *testing.T) {

  Line 113: func TestReorderWritesLatePacketsAsTheyCome(t *testing.T) {

  Line 133: func TestReorderHoldsPacketsAfterAHold(t *testing.T) {

  Line 164: func TestReorderStopsAtTheFirstWriteError(t *testing.T) {

  Line 189: func TestReorderWithoutWindowWritesThrough(t *testing.T) {


/source/head/capture/pcapng_test.go:
  Line 12: func TestPCAPNGWriterAndReaderRoundTrip(t *testing.T) {

  Line 83: func TestPCAPNGReaderHandlesRepeatedSectionsAndResolutions(t *testing.T) {

  Line 123: func TestPCAPNGReaderRejectsInvalidStreams(t *testing.T) {


/source/head/nodes/vr_node_test.go:
  Line 14: func TestVRNodeLinkApplyMode(t *testing.T) {

  Line 20: func TestVMInterfaceAliases(t *testing.T) { // skipcq: GO-R1005


/source/head/nodes/ciena_saos/ciena_saos_test.go:
  Line 13: func TestSaosInterfaceParsing(t *testing.T) {

  Line 123: func TestSaosVariantSet(t *testing.T) {

  Line 140: func TestSaosVariantValidation(t *testing.T) {

  Line 168: func TestSaosPartialConfigOnly(t *testing.T) {


/source/head/nodes/cisco_vios/cisco-vios_test.go:
  Line 11: func TestVIOSInterfaceParsing(t *testing.T) {


/source/head/nodes/vr_csr/vr-csr_test.go:
  Line 11: func TestCSRInterfaceParsing(t *testing.T) {


/source/head/nodes/vr_pan/vr-pan_test.go:
  Line 11: func TestPANInterfaceParsing(t *testing.T) {


/source/head/nodes/sonic/sonic_test.go:
  Line 22: func TestWireInterfaceCmds(t *testing.T) {

  Line 109: func TestPostDeployEndpointsQuietsWires(t *testing.T) {

  Line 188: func TestStartQuietsWires(t *testing.T) {


/source/head/nodes/default_node_test.go:
  Line 25: func TestDefaultNodeEndpointOwnership(t *testing.T) {

  Line 55: func TestDefaultNodeConfigChangesRecreate(t *testing.T) {


(Results truncated. Consider using a more specific path or pattern.)
Tool metadata
{
  "type": "tool",
  "id": "prt_196799ec7001Vs0d8qT8arQIvN",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679927600105YN910bsH6Rk2",
  "callID": "call_2d36c9a3fd234bfca3693371",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head",
      "pattern": "^func Test[A-Za-z0-9_]+\\(t \\*testing\\.T\\)",
      "include": "*_test.go"
    },
    "output": "Found 100 matches (more matches available)\n/source/head/types/bind_test.go:\n  Line 10: func TestNewBind(t *testing.T) {\n\n  Line 63: func TestNewBindFromString(t *testing.T) {\n\n  Line 164: func TestBind_Accessors(t *testing.T) {\n\n  Line 213: func TestBind_String(t *testing.T) {\n\n  Line 267: func TestBinds_ToStringSlice(t *testing.T) {\n\n\n/source/head/types/hostentry_test.go:\n  Line 9: func TestHostEntry_MethodChaining(t *testing.T) {\n\n  Line 91: func TestNewHostEntry(t *testing.T) {\n\n  Line 144: func TestHostEntry_SetContainerID(t *testing.T) {\n\n  Line 230: func TestHostEntry_SetDescription(t *testing.T) {\n\n  Line 301: func TestHostEntry_ToHostEntryString(t *testing.T) {\n\n  Line 421: func TestHostEntries_ToHostsConfig(t *testing.T) {\n\n  Line 531: func TestHostEntries_Merge(t *testing.T) {\n\n\n/source/head/exec/exec_test.go:\n  Line 13: func TestParseExecOutputFormat(t *testing.T) {\n\n  Line 78: func TestExecCollectionLogPreservesAddOrder(t *testing.T) {\n\n\n/source/head/types/volume_test.go:\n  Line 10: func TestNewVolumeFromString(t *testing.T) {\n\n  Line 105: func TestVolume_Accessors(t *testing.T) {\n\n  Line 159: func TestVolume_String(t *testing.T) {\n\n  Line 218: func TestVolume_Options(t *testing.T) {\n\n  Line 261: func TestParseVolumeOptions(t *testing.T) {\n\n\n/source/head/types/stages_test.go:\n  Line 9: func TestEquals(t *testing.T) {\n\n  Line 51: func TestMerge(t *testing.T) {\n\n\n/source/head/types/node_definition_test.go:\n  Line 10: func TestNodeDefinitionYAML_CredentialsNested(t *testing.T) {\n\n  Line 26: func TestNodeDefinitionYAML_LegacyFlatUsernamePassword(t *testing.T) {\n\n  Line 41: func TestNodeDefinitionYAML_CredentialsWinsOverLegacy(t *testing.T) {\n\n  Line 59: func TestNodeDefinitionYAML_KindSpecificConfigRoundTrip(t *testing.T) {\n\n\n/source/head/types/mgmt_test.go:\n  Line 9: func TestNodeConfigManagementIPAMEligible(t *testing.T) {\n\n  Line 30: func TestMgmtDriverValidation(t *testing.T) {\n\n  Line 46: func TestMacvlanManagementValidation(t *testing.T) {\n\n  Line 148: func TestMacvlanAuxEnabled(t *testing.T) {\n\n  Line 171: func TestDADValidation(t *testing.T) {\n\n  Line 186: func TestManagementIPAMYAML(t *testing.T) {\n\n  Line 209: func TestMgmtTailscaleYAML(t *testing.T) {\n\n  Line 225: func TestMgmtTailscaleValidation(t *testing.T) {\n\n\n/source/head/types/topo_diff_test.go:\n  Line 5: func TestTopologyDiffDefaultAction(t *testing.T) {\n\n\n/source/head/types/topology_test.go:\n  Line 713: func TestGetNodeKind(t *testing.T) {\n\n  Line 725: func TestGetNodeGroup(t *testing.T) {\n\n  Line 739: func TestGetNodeType(t *testing.T) {\n\n  Line 753: func TestGetNodeConfig(t *testing.T) {\n\n  Line 769: func TestGetNodeImage(t *testing.T) {\n\n  Line 785: func TestGetNodeImageOnlyViaDefault(t *testing.T) {\n\n  Line 826: func TestGetNodeLicense(t *testing.T) {\n\n  Line 842: func TestGetNodePosition(t *testing.T) {\n\n  Line 856: func TestGetNodeHostname(t *testing.T) {\n\n  Line 894: func TestGetNodeCmd(t *testing.T) {\n\n  Line 908: func TestGetNodeExec(t *testing.T) {\n\n  Line 922: func TestGetNodeUser(t *testing.T) {\n\n  Line 936: func TestGetNodeBinds(t *testing.T) {\n\n  Line 955: func TestGetNodeVolumes(t *testing.T) {\n\n  Line 974: func TestGetNodeVolumesInheritance(t *testing.T) {\n\n  Line 1016: func TestGetNodeBindsRejectsAnonymousVolumeSyntax(t *testing.T) {\n\n  Line 1032: func TestGetNodeVolumesHandlesNilNodeDefinition(t *testing.T) {\n\n  Line 1049: func TestGetNodeBindsDeterministicOrder(t *testing.T) {\n\n  Line 1082: func TestGetNodeEnv(t *testing.T) {\n\n  Line 1096: func TestGetNodeLabels(t *testing.T) {\n\n  Line 1110: func TestGetNodeAutoRemove(t *testing.T) {\n\n  Line 1130: func TestGetNodeDNS(t *testing.T) {\n\n  Line 1149: func TestGetNodeCertificateConfig(t *testing.T) {\n\n  Line 1165: func TestGetNodeCredentials(t *testing.T) {\n\n  Line 1437: func TestGetNodeCredentialTopologySource(t *testing.T) {\n\n  Line 1553: func TestGetNodeRuntimeOptions(t *testing.T) {\n\n  Line 1635: func TestGetNodeCgroupParent(t *testing.T) {\n\n  Line 1679: func TestGetNodePrivilegedDefault(t *testing.T) {\n\n  Line 1694: func TestGetNodeKindSpecificConfig(t *testing.T) {\n\n  Line 1745: func TestGetKindCaseInsensitive(t *testing.T) {\n\n\n/source/head/types/tailscale_ports_test.go:\n  Line 8: func TestSplitDockerAndTailscalePorts(t *testing.T) {\n\n  Line 34: func TestSplitDockerAndTailscalePortsInvalid(t *testing.T) {\n\n  Line 49: func TestGetNodePortMappings(t *testing.T) {\n\n  Line 104: func TestTailscaleConfigProxy(t *testing.T) {\n\n\n/source/head/types/mgmt_networks_test.go:\n  Line 11: func TestMgmtNetworksUnmarshalYAML(t *testing.T) {\n\n  Line 50: func TestMgmtNetworksUnmarshalYAMLReportsListFieldErrors(t *testing.T) {\n\n  Line 58: func TestMgmtNetworksMarshalYAML(t *testing.T) {\n\n  Line 83: func TestMgmtNetworksMarshalJSON(t *testing.T) {\n\n\n/source/head/capture/local_test.go:\n  Line 217: func TestCaptureLocalMergesInterfacesInTimestampOrder(t *testing.T) {\n\n  Line 294: func TestCaptureLocalEndsAfterTheDurationOrWhenCanceled(t *testing.T) {\n\n  Line 333: func TestCaptureLocalWritesPacketsStillInTheRingWhenItEnds(t *testing.T) {\n\n  Line 370: func TestCaptureLocalFailsWithoutOutputWhenAnInterfaceCannotBeOpened(t *testing.T) {\n\n  Line 395: func TestCaptureLocalReopensInterfacesAndReportsWhileTheyWereGone(t *testing.T) {\n\n  Line 459: func TestCaptureLocalChecksTheRequest(t *testing.T) {\n\n\n/source/head/capture/reorder_test.go:\n  Line 89: func TestReorderOrdersStreamsWithinTheWindow(t *testing.T) {\n\n  Line 113: func TestReorderWritesLatePacketsAsTheyCome(t *testing.T) {\n\n  Line 133: func TestReorderHoldsPacketsAfterAHold(t *testing.T) {\n\n  Line 164: func TestReorderStopsAtTheFirstWriteError(t *testing.T) {\n\n  Line 189: func TestReorderWithoutWindowWritesThrough(t *testing.T) {\n\n\n/source/head/capture/pcapng_test.go:\n  Line 12: func TestPCAPNGWriterAndReaderRoundTrip(t *testing.T) {\n\n  Line 83: func TestPCAPNGReaderHandlesRepeatedSectionsAndResolutions(t *testing.T) {\n\n  Line 123: func TestPCAPNGReaderRejectsInvalidStreams(t *testing.T) {\n\n\n/source/head/nodes/vr_node_test.go:\n  Line 14: func TestVRNodeLinkApplyMode(t *testing.T) {\n\n  Line 20: func TestVMInterfaceAliases(t *testing.T) { // skipcq: GO-R1005\n\n\n/source/head/nodes/ciena_saos/ciena_saos_test.go:\n  Line 13: func TestSaosInterfaceParsing(t *testing.T) {\n\n  Line 123: func TestSaosVariantSet(t *testing.T) {\n\n  Line 140: func TestSaosVariantValidation(t *testing.T) {\n\n  Line 168: func TestSaosPartialConfigOnly(t *testing.T) {\n\n\n/source/head/nodes/cisco_vios/cisco-vios_test.go:\n  Line 11: func TestVIOSInterfaceParsing(t *testing.T) {\n\n\n/source/head/nodes/vr_csr/vr-csr_test.go:\n  Line 11: func TestCSRInterfaceParsing(t *testing.T) {\n\n\n/source/head/nodes/vr_pan/vr-pan_test.go:\n  Line 11: func TestPANInterfaceParsing(t *testing.T) {\n\n\n/source/head/nodes/sonic/sonic_test.go:\n  Line 22: func TestWireInterfaceCmds(t *testing.T) {\n\n  Line 109: func TestPostDeployEndpointsQuietsWires(t *testing.T) {\n\n  Line 188: func TestStartQuietsWires(t *testing.T) {\n\n\n/source/head/nodes/default_node_test.go:\n  Line 25: func TestDefaultNodeEndpointOwnership(t *testing.T) {\n\n  Line 55: func TestDefaultNodeConfigChangesRecreate(t *testing.T) {\n\n\n(Results truncated. Consider using a more specific path or pattern.)",
    "title": "^func Test[A-Za-z0-9_]+\\(t \\*testing\\.T\\)",
    "metadata": {
      "matches": 100,
      "truncated": true
    },
    "time": {
      "start": 1793525915340,
      "end": 1793525915359
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_196799ee1001bQ6SsXYfTz6Ks3",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679927600105YN910bsH6Rk2",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 61468,
    "input": 1174,
    "output": 60,
    "reasoning": 74,
    "cache": {
      "read": 60160,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19679927600105YN910bsH6Rk2",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525912183,
    "completed": 1793525915365
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 61468,
    "input": 1174,
    "output": 60,
    "reasoning": 74,
    "cache": {
      "read": 60160,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 34
step-start
{
  "type": "step-start",
  "id": "prt_19679a7c5001p5d8zngGQvCy1y",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196799eef001ltTaxLIhpLLvlO"
}
grep · completed

Input

{
  "include": "*_test.go",
  "path": "/source/head",
  "pattern": "^func (Test[A-Za-z0-9_]+)"
}

Output

Found 100 matches (more matches available)
/source/head/exec/exec_test.go:
  Line 13: func TestParseExecOutputFormat(t *testing.T) {

  Line 78: func TestExecCollectionLogPreservesAddOrder(t *testing.T) {


/source/head/types/hostentry_test.go:
  Line 9: func TestHostEntry_MethodChaining(t *testing.T) {

  Line 91: func TestNewHostEntry(t *testing.T) {

  Line 144: func TestHostEntry_SetContainerID(t *testing.T) {

  Line 230: func TestHostEntry_SetDescription(t *testing.T) {

  Line 301: func TestHostEntry_ToHostEntryString(t *testing.T) {

  Line 421: func TestHostEntries_ToHostsConfig(t *testing.T) {

  Line 531: func TestHostEntries_Merge(t *testing.T) {


/source/head/types/volume_test.go:
  Line 10: func TestNewVolumeFromString(t *testing.T) {

  Line 105: func TestVolume_Accessors(t *testing.T) {

  Line 159: func TestVolume_String(t *testing.T) {

  Line 218: func TestVolume_Options(t *testing.T) {

  Line 261: func TestParseVolumeOptions(t *testing.T) {


/source/head/types/bind_test.go:
  Line 10: func TestNewBind(t *testing.T) {

  Line 63: func TestNewBindFromString(t *testing.T) {

  Line 164: func TestBind_Accessors(t *testing.T) {

  Line 213: func TestBind_String(t *testing.T) {

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


/source/head/types/mgmt_test.go:
  Line 9: func TestNodeConfigManagementIPAMEligible(t *testing.T) {

  Line 30: func TestMgmtDriverValidation(t *testing.T) {

  Line 46: func TestMacvlanManagementValidation(t *testing.T) {

  Line 148: func TestMacvlanAuxEnabled(t *testing.T) {

  Line 171: func TestDADValidation(t *testing.T) {

  Line 186: func TestManagementIPAMYAML(t *testing.T) {

  Line 209: func TestMgmtTailscaleYAML(t *testing.T) {

  Line 225: func TestMgmtTailscaleValidation(t *testing.T) {


/source/head/types/stages_test.go:
  Line 9: func TestEquals(t *testing.T) {

  Line 51: func TestMerge(t *testing.T) {


/source/head/types/node_definition_test.go:
  Line 10: func TestNodeDefinitionYAML_CredentialsNested(t *testing.T) {

  Line 26: func TestNodeDefinitionYAML_LegacyFlatUsernamePassword(t *testing.T) {

  Line 41: func TestNodeDefinitionYAML_CredentialsWinsOverLegacy(t *testing.T) {

  Line 59: func TestNodeDefinitionYAML_KindSpecificConfigRoundTrip(t *testing.T) {


/source/head/types/topo_diff_test.go:
  Line 5: func TestTopologyDiffDefaultAction(t *testing.T) {


/source/head/types/tailscale_ports_test.go:
  Line 8: func TestSplitDockerAndTailscalePorts(t *testing.T) {

  Line 34: func TestSplitDockerAndTailscalePortsInvalid(t *testing.T) {

  Line 49: func TestGetNodePortMappings(t *testing.T) {

  Line 104: func TestTailscaleConfigProxy(t *testing.T) {


/source/head/types/mgmt_networks_test.go:
  Line 11: func TestMgmtNetworksUnmarshalYAML(t *testing.T) {

  Line 50: func TestMgmtNetworksUnmarshalYAMLReportsListFieldErrors(t *testing.T) {

  Line 58: func TestMgmtNetworksMarshalYAML(t *testing.T) {

  Line 83: func TestMgmtNetworksMarshalJSON(t *testing.T) {


/source/head/types/topology_test.go:
  Line 713: func TestGetNodeKind(t *testing.T) {

  Line 725: func TestGetNodeGroup(t *testing.T) {

  Line 739: func TestGetNodeType(t *testing.T) {

  Line 753: func TestGetNodeConfig(t *testing.T) {

  Line 769: func TestGetNodeImage(t *testing.T) {

  Line 785: func TestGetNodeImageOnlyViaDefault(t *testing.T) {

  Line 826: func TestGetNodeLicense(t *testing.T) {

  Line 842: func TestGetNodePosition(t *testing.T) {

  Line 856: func TestGetNodeHostname(t *testing.T) {

  Line 894: func TestGetNodeCmd(t *testing.T) {

  Line 908: func TestGetNodeExec(t *testing.T) {

  Line 922: func TestGetNodeUser(t *testing.T) {

  Line 936: func TestGetNodeBinds(t *testing.T) {

  Line 955: func TestGetNodeVolumes(t *testing.T) {

  Line 974: func TestGetNodeVolumesInheritance(t *testing.T) {

  Line 1016: func TestGetNodeBindsRejectsAnonymousVolumeSyntax(t *testing.T) {

  Line 1032: func TestGetNodeVolumesHandlesNilNodeDefinition(t *testing.T) {

  Line 1049: func TestGetNodeBindsDeterministicOrder(t *testing.T) {

  Line 1082: func TestGetNodeEnv(t *testing.T) {

  Line 1096: func TestGetNodeLabels(t *testing.T) {

  Line 1110: func TestGetNodeAutoRemove(t *testing.T) {

  Line 1130: func TestGetNodeDNS(t *testing.T) {

  Line 1149: func TestGetNodeCertificateConfig(t *testing.T) {

  Line 1165: func TestGetNodeCredentials(t *testing.T) {

  Line 1437: func TestGetNodeCredentialTopologySource(t *testing.T) {

  Line 1553: func TestGetNodeRuntimeOptions(t *testing.T) {

  Line 1635: func TestGetNodeCgroupParent(t *testing.T) {

  Line 1679: func TestGetNodePrivilegedDefault(t *testing.T) {

  Line 1694: func TestGetNodeKindSpecificConfig(t *testing.T) {

  Line 1745: func TestGetKindCaseInsensitive(t *testing.T) {


/source/head/capture/local_test.go:
  Line 217: func TestCaptureLocalMergesInterfacesInTimestampOrder(t *testing.T) {

  Line 294: func TestCaptureLocalEndsAfterTheDurationOrWhenCanceled(t *testing.T) {

  Line 333: func TestCaptureLocalWritesPacketsStillInTheRingWhenItEnds(t *testing.T) {

  Line 370: func TestCaptureLocalFailsWithoutOutputWhenAnInterfaceCannotBeOpened(t *testing.T) {

  Line 395: func TestCaptureLocalReopensInterfacesAndReportsWhileTheyWereGone(t *testing.T) {

  Line 459: func TestCaptureLocalChecksTheRequest(t *testing.T) {


/source/head/capture/pcapng_test.go:
  Line 12: func TestPCAPNGWriterAndReaderRoundTrip(t *testing.T) {

  Line 83: func TestPCAPNGReaderHandlesRepeatedSectionsAndResolutions(t *testing.T) {

  Line 123: func TestPCAPNGReaderRejectsInvalidStreams(t *testing.T) {


/source/head/capture/reorder_test.go:
  Line 89: func TestReorderOrdersStreamsWithinTheWindow(t *testing.T) {

  Line 113: func TestReorderWritesLatePacketsAsTheyCome(t *testing.T) {

  Line 133: func TestReorderHoldsPacketsAfterAHold(t *testing.T) {

  Line 164: func TestReorderStopsAtTheFirstWriteError(t *testing.T) {

  Line 189: func TestReorderWithoutWindowWritesThrough(t *testing.T) {


/source/head/nodes/vr_veos/vr-veos_test.go:
  Line 11: func TestVEOSInterfaceParsing(t *testing.T) {


/source/head/nodes/ciena_saos/ciena_saos_test.go:
  Line 13: func TestSaosInterfaceParsing(t *testing.T) {

  Line 123: func TestSaosVariantSet(t *testing.T) {

  Line 140: func TestSaosVariantValidation(t *testing.T) {

  Line 168: func TestSaosPartialConfigOnly(t *testing.T) {


/source/head/nodes/cisco_vios/cisco-vios_test.go:
  Line 11: func TestVIOSInterfaceParsing(t *testing.T) {


/source/head/nodes/vr_csr/vr-csr_test.go:
  Line 11: func TestCSRInterfaceParsing(t *testing.T) {


/source/head/nodes/vr_pan/vr-pan_test.go:
  Line 11: func TestPANInterfaceParsing(t *testing.T) {


/source/head/nodes/default_node_test.go:
  Line 25: func TestDefaultNodeEndpointOwnership(t *testing.T) {

  Line 55: func TestDefaultNodeConfigChangesRecreate(t *testing.T) {

  Line 122: func TestDefaultNodeComputeDiffDetectsHostnameChange(t *testing.T) {

  Line 137: func TestDefaultNodeComputeDiffDetectsMgmtNetChange(t *testing.T) {

  Line 149: func TestDefaultNodeComputeDiffIgnoresEquivalentDefaultHostname(t *testing.T) {

  Line 161: func TestDefaultNodeAdoptEndpointRejectsForeignOwner(t *testing.T) {


(Results truncated. Consider using a more specific path or pattern.)
Tool metadata
{
  "type": "tool",
  "id": "prt_19679a88f001ogtMZottNEzou0",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196799eef001ltTaxLIhpLLvlO",
  "callID": "call_23d2d4c15ece4d91a9ef0c8b",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "include": "*_test.go",
      "path": "/source/head",
      "pattern": "^func (Test[A-Za-z0-9_]+)"
    },
    "output": "Found 100 matches (more matches available)\n/source/head/exec/exec_test.go:\n  Line 13: func TestParseExecOutputFormat(t *testing.T) {\n\n  Line 78: func TestExecCollectionLogPreservesAddOrder(t *testing.T) {\n\n\n/source/head/types/hostentry_test.go:\n  Line 9: func TestHostEntry_MethodChaining(t *testing.T) {\n\n  Line 91: func TestNewHostEntry(t *testing.T) {\n\n  Line 144: func TestHostEntry_SetContainerID(t *testing.T) {\n\n  Line 230: func TestHostEntry_SetDescription(t *testing.T) {\n\n  Line 301: func TestHostEntry_ToHostEntryString(t *testing.T) {\n\n  Line 421: func TestHostEntries_ToHostsConfig(t *testing.T) {\n\n  Line 531: func TestHostEntries_Merge(t *testing.T) {\n\n\n/source/head/types/volume_test.go:\n  Line 10: func TestNewVolumeFromString(t *testing.T) {\n\n  Line 105: func TestVolume_Accessors(t *testing.T) {\n\n  Line 159: func TestVolume_String(t *testing.T) {\n\n  Line 218: func TestVolume_Options(t *testing.T) {\n\n  Line 261: func TestParseVolumeOptions(t *testing.T) {\n\n\n/source/head/types/bind_test.go:\n  Line 10: func TestNewBind(t *testing.T) {\n\n  Line 63: func TestNewBindFromString(t *testing.T) {\n\n  Line 164: func TestBind_Accessors(t *testing.T) {\n\n  Line 213: func TestBind_String(t *testing.T) {\n\n  Line 267: func TestBinds_ToStringSlice(t *testing.T) {\n\n\n/source/head/types/mgmt_test.go:\n  Line 9: func TestNodeConfigManagementIPAMEligible(t *testing.T) {\n\n  Line 30: func TestMgmtDriverValidation(t *testing.T) {\n\n  Line 46: func TestMacvlanManagementValidation(t *testing.T) {\n\n  Line 148: func TestMacvlanAuxEnabled(t *testing.T) {\n\n  Line 171: func TestDADValidation(t *testing.T) {\n\n  Line 186: func TestManagementIPAMYAML(t *testing.T) {\n\n  Line 209: func TestMgmtTailscaleYAML(t *testing.T) {\n\n  Line 225: func TestMgmtTailscaleValidation(t *testing.T) {\n\n\n/source/head/types/stages_test.go:\n  Line 9: func TestEquals(t *testing.T) {\n\n  Line 51: func TestMerge(t *testing.T) {\n\n\n/source/head/types/node_definition_test.go:\n  Line 10: func TestNodeDefinitionYAML_CredentialsNested(t *testing.T) {\n\n  Line 26: func TestNodeDefinitionYAML_LegacyFlatUsernamePassword(t *testing.T) {\n\n  Line 41: func TestNodeDefinitionYAML_CredentialsWinsOverLegacy(t *testing.T) {\n\n  Line 59: func TestNodeDefinitionYAML_KindSpecificConfigRoundTrip(t *testing.T) {\n\n\n/source/head/types/topo_diff_test.go:\n  Line 5: func TestTopologyDiffDefaultAction(t *testing.T) {\n\n\n/source/head/types/tailscale_ports_test.go:\n  Line 8: func TestSplitDockerAndTailscalePorts(t *testing.T) {\n\n  Line 34: func TestSplitDockerAndTailscalePortsInvalid(t *testing.T) {\n\n  Line 49: func TestGetNodePortMappings(t *testing.T) {\n\n  Line 104: func TestTailscaleConfigProxy(t *testing.T) {\n\n\n/source/head/types/mgmt_networks_test.go:\n  Line 11: func TestMgmtNetworksUnmarshalYAML(t *testing.T) {\n\n  Line 50: func TestMgmtNetworksUnmarshalYAMLReportsListFieldErrors(t *testing.T) {\n\n  Line 58: func TestMgmtNetworksMarshalYAML(t *testing.T) {\n\n  Line 83: func TestMgmtNetworksMarshalJSON(t *testing.T) {\n\n\n/source/head/types/topology_test.go:\n  Line 713: func TestGetNodeKind(t *testing.T) {\n\n  Line 725: func TestGetNodeGroup(t *testing.T) {\n\n  Line 739: func TestGetNodeType(t *testing.T) {\n\n  Line 753: func TestGetNodeConfig(t *testing.T) {\n\n  Line 769: func TestGetNodeImage(t *testing.T) {\n\n  Line 785: func TestGetNodeImageOnlyViaDefault(t *testing.T) {\n\n  Line 826: func TestGetNodeLicense(t *testing.T) {\n\n  Line 842: func TestGetNodePosition(t *testing.T) {\n\n  Line 856: func TestGetNodeHostname(t *testing.T) {\n\n  Line 894: func TestGetNodeCmd(t *testing.T) {\n\n  Line 908: func TestGetNodeExec(t *testing.T) {\n\n  Line 922: func TestGetNodeUser(t *testing.T) {\n\n  Line 936: func TestGetNodeBinds(t *testing.T) {\n\n  Line 955: func TestGetNodeVolumes(t *testing.T) {\n\n  Line 974: func TestGetNodeVolumesInheritance(t *testing.T) {\n\n  Line 1016: func TestGetNodeBindsRejectsAnonymousVolumeSyntax(t *testing.T) {\n\n  Line 1032: func TestGetNodeVolumesHandlesNilNodeDefinition(t *testing.T) {\n\n  Line 1049: func TestGetNodeBindsDeterministicOrder(t *testing.T) {\n\n  Line 1082: func TestGetNodeEnv(t *testing.T) {\n\n  Line 1096: func TestGetNodeLabels(t *testing.T) {\n\n  Line 1110: func TestGetNodeAutoRemove(t *testing.T) {\n\n  Line 1130: func TestGetNodeDNS(t *testing.T) {\n\n  Line 1149: func TestGetNodeCertificateConfig(t *testing.T) {\n\n  Line 1165: func TestGetNodeCredentials(t *testing.T) {\n\n  Line 1437: func TestGetNodeCredentialTopologySource(t *testing.T) {\n\n  Line 1553: func TestGetNodeRuntimeOptions(t *testing.T) {\n\n  Line 1635: func TestGetNodeCgroupParent(t *testing.T) {\n\n  Line 1679: func TestGetNodePrivilegedDefault(t *testing.T) {\n\n  Line 1694: func TestGetNodeKindSpecificConfig(t *testing.T) {\n\n  Line 1745: func TestGetKindCaseInsensitive(t *testing.T) {\n\n\n/source/head/capture/local_test.go:\n  Line 217: func TestCaptureLocalMergesInterfacesInTimestampOrder(t *testing.T) {\n\n  Line 294: func TestCaptureLocalEndsAfterTheDurationOrWhenCanceled(t *testing.T) {\n\n  Line 333: func TestCaptureLocalWritesPacketsStillInTheRingWhenItEnds(t *testing.T) {\n\n  Line 370: func TestCaptureLocalFailsWithoutOutputWhenAnInterfaceCannotBeOpened(t *testing.T) {\n\n  Line 395: func TestCaptureLocalReopensInterfacesAndReportsWhileTheyWereGone(t *testing.T) {\n\n  Line 459: func TestCaptureLocalChecksTheRequest(t *testing.T) {\n\n\n/source/head/capture/pcapng_test.go:\n  Line 12: func TestPCAPNGWriterAndReaderRoundTrip(t *testing.T) {\n\n  Line 83: func TestPCAPNGReaderHandlesRepeatedSectionsAndResolutions(t *testing.T) {\n\n  Line 123: func TestPCAPNGReaderRejectsInvalidStreams(t *testing.T) {\n\n\n/source/head/capture/reorder_test.go:\n  Line 89: func TestReorderOrdersStreamsWithinTheWindow(t *testing.T) {\n\n  Line 113: func TestReorderWritesLatePacketsAsTheyCome(t *testing.T) {\n\n  Line 133: func TestReorderHoldsPacketsAfterAHold(t *testing.T) {\n\n  Line 164: func TestReorderStopsAtTheFirstWriteError(t *testing.T) {\n\n  Line 189: func TestReorderWithoutWindowWritesThrough(t *testing.T) {\n\n\n/source/head/nodes/vr_veos/vr-veos_test.go:\n  Line 11: func TestVEOSInterfaceParsing(t *testing.T) {\n\n\n/source/head/nodes/ciena_saos/ciena_saos_test.go:\n  Line 13: func TestSaosInterfaceParsing(t *testing.T) {\n\n  Line 123: func TestSaosVariantSet(t *testing.T) {\n\n  Line 140: func TestSaosVariantValidation(t *testing.T) {\n\n  Line 168: func TestSaosPartialConfigOnly(t *testing.T) {\n\n\n/source/head/nodes/cisco_vios/cisco-vios_test.go:\n  Line 11: func TestVIOSInterfaceParsing(t *testing.T) {\n\n\n/source/head/nodes/vr_csr/vr-csr_test.go:\n  Line 11: func TestCSRInterfaceParsing(t *testing.T) {\n\n\n/source/head/nodes/vr_pan/vr-pan_test.go:\n  Line 11: func TestPANInterfaceParsing(t *testing.T) {\n\n\n/source/head/nodes/default_node_test.go:\n  Line 25: func TestDefaultNodeEndpointOwnership(t *testing.T) {\n\n  Line 55: func TestDefaultNodeConfigChangesRecreate(t *testing.T) {\n\n  Line 122: func TestDefaultNodeComputeDiffDetectsHostnameChange(t *testing.T) {\n\n  Line 137: func TestDefaultNodeComputeDiffDetectsMgmtNetChange(t *testing.T) {\n\n  Line 149: func TestDefaultNodeComputeDiffIgnoresEquivalentDefaultHostname(t *testing.T) {\n\n  Line 161: func TestDefaultNodeAdoptEndpointRejectsForeignOwner(t *testing.T) {\n\n\n(Results truncated. Consider using a more specific path or pattern.)",
    "title": "^func (Test[A-Za-z0-9_]+)",
    "metadata": {
      "matches": 100,
      "truncated": true
    },
    "time": {
      "start": 1793525917843,
      "end": 1793525917860
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19679a8b4001ee331d07fAIxU6",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_196799eef001ltTaxLIhpLLvlO",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 63612,
    "input": 2134,
    "output": 37,
    "reasoning": 1,
    "cache": {
      "read": 61440,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_196799eef001ltTaxLIhpLLvlO",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525915375,
    "completed": 1793525917880
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 63612,
    "input": 2134,
    "output": 37,
    "reasoning": 1,
    "cache": {
      "read": 61440,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 35
step-start
{
  "type": "step-start",
  "id": "prt_19679b10b00164DsXfoL20v1Pt",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679a8c1001ildPUzX219gNFT"
}
Reasoning
The grep tool truncates and repeats. Let me be more targeted: list test function names in the four changed test files only.
grep · completed

Input

{
  "path": "/source/head/labruntime/clabernetes/event_parity_test.go",
  "pattern": "^func Test"
}

Output

Found 100 matches (more matches available)
/source/head/labruntime/clabernetes/runtime_gaps_test.go:
  Line 32: func TestNewDoesNotLoadKubeconfig(t *testing.T) {

  Line 62: func TestConnectLoadsClientsOnce(t *testing.T) {

  Line 110: func TestListNamespacePrecedence(t *testing.T) {

  Line 133: func TestEventScopeFor(t *testing.T) {

  Line 201: func TestStreamEventsWatchesOnlyTheScopedNamespace(t *testing.T) {

  Line 235: func TestNodeStateFromResourceLocatesWorkload(t *testing.T) {

  Line 285: func TestEnrichStateReportsPodAndContainer(t *testing.T) {

  Line 367: func TestParseInterfaceSample(t *testing.T) {

  Line 406: func TestCommandNotExecutable(t *testing.T) {

  Line 432: func TestTopologyPersistenceRetainsClaims(t *testing.T) {

  Line 443: func TestDestroyKeepsRetainedClaimsUnlessCleanup(t *testing.T) {


/source/head/labruntime/clabernetes/manifests_test.go:
  Line 88: func TestManifestsTopologyBundle(t *testing.T) {

  Line 159: func TestManifestsPrimitiveBundle(t *testing.T) {

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

  Line 225: func TestManifestsMatchDeployedResources(t *testing.T) {

  Line 284: func TestManifestsMatchDeployedPrimitiveResources(t *testing.T) {

  Line 324: func TestManifestsKeepBinaryFilesAsBinaryData(t *testing.T) {


/source/head/labruntime/clabernetes/event_parity_test.go:
  Line 85: func TestNetlinkOperState(t *testing.T) {

  Line 107: func TestInterfaceEventDataNamesInterfacesLikeDocker(t *testing.T) {

  Line 153: func TestInterfacePollerReportsTheTopologyInterfaces(t *testing.T) {

  Line 252: func TestInterfacePollerFirstRoundWithoutInitialState(t *testing.T) {

  Line 265: func TestInterfacePollerStatsCoverTheReportedInterfaces(t *testing.T) {

  Line 325: func TestInterfacePollerListsAPodOncePerInterfaceSet(t *testing.T) {

  Line 369: func TestContainerTransitionActions(t *testing.T) {

  Line 598: func TestContainerTrackerReportsTheNodeLifecycle(t *testing.T) {

  Line 672: func TestContainerTrackerSeedsWithoutSnapshot(t *testing.T) {

  Line 686: func TestNodeContainerState(t *testing.T) {

  Line 720: func TestNewestPodPrefersAPodThatIsNotDeleted(t *testing.T) {

  Line 744: func TestEnrichStateReportsContainerStateAndHealth(t *testing.T) {

  Line 811: func TestDeployRecordsTheTopologyFile(t *testing.T) {

  Line 903: func TestCarryOverNodeTopologyFile(t *testing.T) {

  Line 946: func TestManifestsCarryNoTopologyFile(t *testing.T) {

  Line 965: func TestStateReportsTheRecordedTopologyFile(t *testing.T) {


/source/head/labruntime/clabernetes/files_test.go:
  Line 17: func TestStageNodeFileReferences(t *testing.T) {

  Line 86: func TestStageConfigMapFileRejectsOversizedEmbeddedContent(t *testing.T) {

  Line 102: func TestResolveNodeFileReferenceHonorsCancellation(t *testing.T) {

  Line 123: func TestClabernetesBriefLinkMgmtNetNetwork(t *testing.T) {


/source/head/labruntime/clabernetes/resources_test.go:
  Line 16: func TestConditionPendingReasonIdentifiesDirectHelper(t *testing.T) {

  Line 67: func TestWaitPrimitiveLinksResolvedListsTopologyScopedLinks(t *testing.T) {

  Line 116: func TestWaitPrimitiveLinksResolvedIgnoresForeignLinks(t *testing.T) {


/source/head/labruntime/clabernetes/config_test.go:
  Line 12: func TestDeleteManagedLabNamespacePreservesSharedOrOverriddenNamespace(t *testing.T) {


/source/head/labruntime/clabernetes/nodes_test.go:
  Line 214: func TestStopPatchesThePrimaryRunStateAndWaitsForStopped(t *testing.T) {

  Line 257: func TestStartWaitsForTheObservedGenerationAndReadiness(t *testing.T) {

  Line 295: func TestRestartSetsANewTokenAndWaitsForIt(t *testing.T) {

  Line 349: func TestRunStateWaitTimeoutNamesThePendingNodes(t *testing.T) {

  Line 367: func TestNodeLifecycleRejectsUnknownNodes(t *testing.T) {

  Line 389: func TestPrimitivePlanAndApplyKeepTheRunState(t *testing.T) {

  Line 439: func TestManifestsNeverCarryARunState(t *testing.T) {

  Line 482: func TestCheckNodeRunStateSchema(t *testing.T) {

  Line 520: func TestSupportCheckRunsOnceBeforeTheFirstClusterCall(t *testing.T) {

  Line 563: func TestSupportCheckRetriesFailedRequestsAndRemembersSuccess(t *testing.T) {

  Line 600: func TestSupportCheckReadsTheOpenAPIDocumentAsTheCaller(t *testing.T) {

  Line 686: func TestStartAcceptsANodeWhoseLinkPeerIsStopped(t *testing.T) {

  Line 714: func TestLabSettlesWithStoppedNodesAndTheirPeers(t *testing.T) {

  Line 774: func TestPrimitiveObjectsConformAfterAnAPIRoundTrip(t *testing.T) {


/source/head/labruntime/clabernetes/capture_test.go:
  Line 379: func TestCaptureInterfacesUsesTopologyNames(t *testing.T) {

  Line 419: func TestCaptureMergesNodesIntoOneSection(t *testing.T) {

  Line 481: func TestCaptureChainsSegmentsWithoutDuplicatesOrGaps(t *testing.T) {

  Line 540: func TestCaptureReportsAGapWhenTheFollowUpStartsLate(t *testing.T) {

  Line 571: func TestCaptureMapsDeniedAndFailedAuditsToErrors(t *testing.T) {

  Line 596: func TestCaptureAuditLineWriter(t *testing.T) {

  Line 633: func TestCaptureStopsAtThePacketLimit(t *testing.T) {

  Line 661: func TestCaptureEndsCleanlyWhenTheContextEnds(t *testing.T) {

  Line 680: func TestCaptureValidatesTargets(t *testing.T) {

  Line 722: func TestInspectInterfacesReportsStateFromSysfs(t *testing.T) {

  Line 771: func TestCaptureWritesWhatItReadWhenTheContextEnds(t *testing.T) {

  Line 851: func TestCaptureClosesStdinWhenItEnds(t *testing.T) {

  Line 920: func TestCaptureRejectsAClabwireWithoutStopOnStdinClose(t *testing.T) {

  Line 954: func TestCaptureMergesNodesInTimestampOrder(t *testing.T) {

  Line 997: func TestCaptureChainsSeveralNodesInOrderWithoutDuplicates(t *testing.T) {

  Line 1056: func TestCaptureReorderWindowKnob(t *testing.T) {


/source/head/labruntime/clabernetes/clabernetes_test.go:
  Line 40: func TestRuntimeName(t *testing.T) {

  Line 54: func TestParseProcNetDev(t *testing.T) {

  Line 80: func TestParseProcNetDevRejectsMalformedLine(t *testing.T) {

  Line 89: func TestPreferredDeviceContainerName(t *testing.T) {

  Line 190: func TestCleanTarPath(t *testing.T) {

  Line 223: func TestNamespaceForLab(t *testing.T) {

  Line 283: func TestConfiguredLabNamespacePrecedence(t *testing.T) {

  Line 299: func TestDeployUsesNamespaceOverrideWithoutManagingIt(t *testing.T) {

  Line 340: func TestDeployCreatesAndDestroyRemovesDedicatedLabNamespace(t *testing.T) {

  Line 393: func TestDestroyPreservesPreexistingLabNamespace(t *testing.T) {

  Line 432: func TestDestroyFallsBackToIndividualDeletesWithoutTouchingOtherLabs(t *testing.T) {

  Line 487: func TestDestroyUsesLabelScopedDeleteCollection(t *testing.T) {

  Line 517: func TestWaitAndSweepDeletedRemovesLateStagedConfigMaps(t *testing.T) {

  Line 539: func TestSavedFilesFromTarSkipsUnsafeEntries(t *testing.T) {

  Line 582: func TestStateFromTopology(t *testing.T) {

  Line 634: func TestPrimitiveResourcesUseCurrentC9sAPI(t *testing.T) {

  Line 649: func TestPrimitiveResourceGroupOrder(t *testing.T) {

  Line 665: func TestPrimitiveLinkPendingReason(t *testing.T) {

  Line 706: func TestEnrichStateUsesNodeResources(t *testing.T) {

  Line 750: func TestWaitReadyTimeoutReportsPendingNodes(t *testing.T) {

  Line 782: func TestNodeReadinessProgressReportsTransitions(t *testing.T) {

  Line 844: func TestNodePhaseProgressDetails(t *testing.T) {

  Line 964: func TestImagePullProgressReportsKubeletEvents(t *testing.T) {

  Line 1052: func TestNodePlanFailureClassification(t *testing.T) {

  Line 1086: func TestManagePrimitiveOnlyLab(t *testing.T) {

  Line 1172: func TestResolvePrimaryNode(t *testing.T) {

  Line 1189: func TestDeployCreatesPrimitiveResources(t *testing.T) {

  Line 1262: func TestDeployCreatesTopologyResource(t *testing.T) {

  Line 1310: func TestTopologyPullSecrets(t *testing.T) {


(Results truncated. Consider using a more specific path or pattern.)
Tool metadata
{
  "type": "tool",
  "id": "prt_19679b2a9001EzaTCheZ3ILOJz",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679a8c1001ildPUzX219gNFT",
  "callID": "call_0cbfc01408294089b997e1a3",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/labruntime/clabernetes/event_parity_test.go",
      "pattern": "^func Test"
    },
    "output": "Found 100 matches (more matches available)\n/source/head/labruntime/clabernetes/runtime_gaps_test.go:\n  Line 32: func TestNewDoesNotLoadKubeconfig(t *testing.T) {\n\n  Line 62: func TestConnectLoadsClientsOnce(t *testing.T) {\n\n  Line 110: func TestListNamespacePrecedence(t *testing.T) {\n\n  Line 133: func TestEventScopeFor(t *testing.T) {\n\n  Line 201: func TestStreamEventsWatchesOnlyTheScopedNamespace(t *testing.T) {\n\n  Line 235: func TestNodeStateFromResourceLocatesWorkload(t *testing.T) {\n\n  Line 285: func TestEnrichStateReportsPodAndContainer(t *testing.T) {\n\n  Line 367: func TestParseInterfaceSample(t *testing.T) {\n\n  Line 406: func TestCommandNotExecutable(t *testing.T) {\n\n  Line 432: func TestTopologyPersistenceRetainsClaims(t *testing.T) {\n\n  Line 443: func TestDestroyKeepsRetainedClaimsUnlessCleanup(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/manifests_test.go:\n  Line 88: func TestManifestsTopologyBundle(t *testing.T) {\n\n  Line 159: func TestManifestsPrimitiveBundle(t *testing.T) {\n\n  Line 208: func TestManifestsRejectUnsupportedTopology(t *testing.T) {\n\n  Line 225: func TestManifestsMatchDeployedResources(t *testing.T) {\n\n  Line 284: func TestManifestsMatchDeployedPrimitiveResources(t *testing.T) {\n\n  Line 324: func TestManifestsKeepBinaryFilesAsBinaryData(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/event_parity_test.go:\n  Line 85: func TestNetlinkOperState(t *testing.T) {\n\n  Line 107: func TestInterfaceEventDataNamesInterfacesLikeDocker(t *testing.T) {\n\n  Line 153: func TestInterfacePollerReportsTheTopologyInterfaces(t *testing.T) {\n\n  Line 252: func TestInterfacePollerFirstRoundWithoutInitialState(t *testing.T) {\n\n  Line 265: func TestInterfacePollerStatsCoverTheReportedInterfaces(t *testing.T) {\n\n  Line 325: func TestInterfacePollerListsAPodOncePerInterfaceSet(t *testing.T) {\n\n  Line 369: func TestContainerTransitionActions(t *testing.T) {\n\n  Line 598: func TestContainerTrackerReportsTheNodeLifecycle(t *testing.T) {\n\n  Line 672: func TestContainerTrackerSeedsWithoutSnapshot(t *testing.T) {\n\n  Line 686: func TestNodeContainerState(t *testing.T) {\n\n  Line 720: func TestNewestPodPrefersAPodThatIsNotDeleted(t *testing.T) {\n\n  Line 744: func TestEnrichStateReportsContainerStateAndHealth(t *testing.T) {\n\n  Line 811: func TestDeployRecordsTheTopologyFile(t *testing.T) {\n\n  Line 903: func TestCarryOverNodeTopologyFile(t *testing.T) {\n\n  Line 946: func TestManifestsCarryNoTopologyFile(t *testing.T) {\n\n  Line 965: func TestStateReportsTheRecordedTopologyFile(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/files_test.go:\n  Line 17: func TestStageNodeFileReferences(t *testing.T) {\n\n  Line 86: func TestStageConfigMapFileRejectsOversizedEmbeddedContent(t *testing.T) {\n\n  Line 102: func TestResolveNodeFileReferenceHonorsCancellation(t *testing.T) {\n\n  Line 123: func TestClabernetesBriefLinkMgmtNetNetwork(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/resources_test.go:\n  Line 16: func TestConditionPendingReasonIdentifiesDirectHelper(t *testing.T) {\n\n  Line 67: func TestWaitPrimitiveLinksResolvedListsTopologyScopedLinks(t *testing.T) {\n\n  Line 116: func TestWaitPrimitiveLinksResolvedIgnoresForeignLinks(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/config_test.go:\n  Line 12: func TestDeleteManagedLabNamespacePreservesSharedOrOverriddenNamespace(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/nodes_test.go:\n  Line 214: func TestStopPatchesThePrimaryRunStateAndWaitsForStopped(t *testing.T) {\n\n  Line 257: func TestStartWaitsForTheObservedGenerationAndReadiness(t *testing.T) {\n\n  Line 295: func TestRestartSetsANewTokenAndWaitsForIt(t *testing.T) {\n\n  Line 349: func TestRunStateWaitTimeoutNamesThePendingNodes(t *testing.T) {\n\n  Line 367: func TestNodeLifecycleRejectsUnknownNodes(t *testing.T) {\n\n  Line 389: func TestPrimitivePlanAndApplyKeepTheRunState(t *testing.T) {\n\n  Line 439: func TestManifestsNeverCarryARunState(t *testing.T) {\n\n  Line 482: func TestCheckNodeRunStateSchema(t *testing.T) {\n\n  Line 520: func TestSupportCheckRunsOnceBeforeTheFirstClusterCall(t *testing.T) {\n\n  Line 563: func TestSupportCheckRetriesFailedRequestsAndRemembersSuccess(t *testing.T) {\n\n  Line 600: func TestSupportCheckReadsTheOpenAPIDocumentAsTheCaller(t *testing.T) {\n\n  Line 686: func TestStartAcceptsANodeWhoseLinkPeerIsStopped(t *testing.T) {\n\n  Line 714: func TestLabSettlesWithStoppedNodesAndTheirPeers(t *testing.T) {\n\n  Line 774: func TestPrimitiveObjectsConformAfterAnAPIRoundTrip(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/capture_test.go:\n  Line 379: func TestCaptureInterfacesUsesTopologyNames(t *testing.T) {\n\n  Line 419: func TestCaptureMergesNodesIntoOneSection(t *testing.T) {\n\n  Line 481: func TestCaptureChainsSegmentsWithoutDuplicatesOrGaps(t *testing.T) {\n\n  Line 540: func TestCaptureReportsAGapWhenTheFollowUpStartsLate(t *testing.T) {\n\n  Line 571: func TestCaptureMapsDeniedAndFailedAuditsToErrors(t *testing.T) {\n\n  Line 596: func TestCaptureAuditLineWriter(t *testing.T) {\n\n  Line 633: func TestCaptureStopsAtThePacketLimit(t *testing.T) {\n\n  Line 661: func TestCaptureEndsCleanlyWhenTheContextEnds(t *testing.T) {\n\n  Line 680: func TestCaptureValidatesTargets(t *testing.T) {\n\n  Line 722: func TestInspectInterfacesReportsStateFromSysfs(t *testing.T) {\n\n  Line 771: func TestCaptureWritesWhatItReadWhenTheContextEnds(t *testing.T) {\n\n  Line 851: func TestCaptureClosesStdinWhenItEnds(t *testing.T) {\n\n  Line 920: func TestCaptureRejectsAClabwireWithoutStopOnStdinClose(t *testing.T) {\n\n  Line 954: func TestCaptureMergesNodesInTimestampOrder(t *testing.T) {\n\n  Line 997: func TestCaptureChainsSeveralNodesInOrderWithoutDuplicates(t *testing.T) {\n\n  Line 1056: func TestCaptureReorderWindowKnob(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/clabernetes_test.go:\n  Line 40: func TestRuntimeName(t *testing.T) {\n\n  Line 54: func TestParseProcNetDev(t *testing.T) {\n\n  Line 80: func TestParseProcNetDevRejectsMalformedLine(t *testing.T) {\n\n  Line 89: func TestPreferredDeviceContainerName(t *testing.T) {\n\n  Line 190: func TestCleanTarPath(t *testing.T) {\n\n  Line 223: func TestNamespaceForLab(t *testing.T) {\n\n  Line 283: func TestConfiguredLabNamespacePrecedence(t *testing.T) {\n\n  Line 299: func TestDeployUsesNamespaceOverrideWithoutManagingIt(t *testing.T) {\n\n  Line 340: func TestDeployCreatesAndDestroyRemovesDedicatedLabNamespace(t *testing.T) {\n\n  Line 393: func TestDestroyPreservesPreexistingLabNamespace(t *testing.T) {\n\n  Line 432: func TestDestroyFallsBackToIndividualDeletesWithoutTouchingOtherLabs(t *testing.T) {\n\n  Line 487: func TestDestroyUsesLabelScopedDeleteCollection(t *testing.T) {\n\n  Line 517: func TestWaitAndSweepDeletedRemovesLateStagedConfigMaps(t *testing.T) {\n\n  Line 539: func TestSavedFilesFromTarSkipsUnsafeEntries(t *testing.T) {\n\n  Line 582: func TestStateFromTopology(t *testing.T) {\n\n  Line 634: func TestPrimitiveResourcesUseCurrentC9sAPI(t *testing.T) {\n\n  Line 649: func TestPrimitiveResourceGroupOrder(t *testing.T) {\n\n  Line 665: func TestPrimitiveLinkPendingReason(t *testing.T) {\n\n  Line 706: func TestEnrichStateUsesNodeResources(t *testing.T) {\n\n  Line 750: func TestWaitReadyTimeoutReportsPendingNodes(t *testing.T) {\n\n  Line 782: func TestNodeReadinessProgressReportsTransitions(t *testing.T) {\n\n  Line 844: func TestNodePhaseProgressDetails(t *testing.T) {\n\n  Line 964: func TestImagePullProgressReportsKubeletEvents(t *testing.T) {\n\n  Line 1052: func TestNodePlanFailureClassification(t *testing.T) {\n\n  Line 1086: func TestManagePrimitiveOnlyLab(t *testing.T) {\n\n  Line 1172: func TestResolvePrimaryNode(t *testing.T) {\n\n  Line 1189: func TestDeployCreatesPrimitiveResources(t *testing.T) {\n\n  Line 1262: func TestDeployCreatesTopologyResource(t *testing.T) {\n\n  Line 1310: func TestTopologyPullSecrets(t *testing.T) {\n\n\n(Results truncated. Consider using a more specific path or pattern.)",
    "title": "^func Test",
    "metadata": {
      "matches": 100,
      "truncated": true
    },
    "time": {
      "start": 1793525920429,
      "end": 1793525920441
    }
  }
}
grep · completed

Input

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

Output

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


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


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

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

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

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

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

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


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

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

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

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

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

  Line 361: func TestProcessUpdateDeleteOnlyTrackedLinks(t *testing.T) {
Tool metadata
{
  "type": "tool",
  "id": "prt_19679b3010011LDGc68gLNeYkE",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679a8c1001ildPUzX219gNFT",
  "callID": "call_6f7deb2667ce4531a509cb0c",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/core/events/parity_test.go",
      "pattern": "^func Test"
    },
    "output": "Found 14 matches\n/source/head/core/events/labruntime_test.go:\n  Line 10: func TestLabRuntimeEventStreamRequestScope(t *testing.T) {\n\n\n/source/head/core/events/netlink_test.go:\n  Line 11: func TestOverlayToolsInterfaceLeavesAttributesWhenNotStitched(t *testing.T) {\n\n\n/source/head/core/events/parity_test.go:\n  Line 231: func TestContainerEventParity(t *testing.T) {\n\n  Line 334: func TestContainerSnapshotParity(t *testing.T) {\n\n  Line 359: func TestContainerStateUsesDockerVocabulary(t *testing.T) {\n\n  Line 437: func TestInterfaceEventParity(t *testing.T) {\n\n  Line 523: func TestInterfaceEventOmitsUnknownValues(t *testing.T) {\n\n  Line 543: func TestLabRuntimeTopologyEventsKeepTheirAttributes(t *testing.T) {\n\n\n/source/head/core/events/netlink_watch_test.go:\n  Line 177: func TestNetlinkWatcherReportsExistingAndNewLinks(t *testing.T) {\n\n  Line 208: func TestNetlinkWatcherReportsLinksAddedWhileStarting(t *testing.T) {\n\n  Line 236: func TestNetlinkWatcherRetriesNamespaceLookup(t *testing.T) {\n\n  Line 267: func TestNetlinkWatcherStopsAfterRetries(t *testing.T) {\n\n  Line 288: func TestProcessExistingAfterResubscribe(t *testing.T) {\n\n  Line 361: func TestProcessUpdateDeleteOnlyTrackedLinks(t *testing.T) {\n",
    "title": "^func Test",
    "metadata": {
      "matches": 14,
      "truncated": false
    },
    "time": {
      "start": 1793525920517,
      "end": 1793525920526
    }
  }
}
grep · completed

Input

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

Output

Found 100 matches (more matches available)
/source/head/core/labruntime_test.go:
  Line 48: func TestExecWithLabRuntimeReturnsNestedFailureAndPreservesResult(t *testing.T) {

  Line 75: func TestResolveRuntimeNameLowercasesValue(t *testing.T) {

  Line 86: func TestApplyLabRuntimeDeployOptionsCopiesMaxWorkers(t *testing.T) {

  Line 97: func TestDestroyWithLabRuntimeRejectsNodeFilterBeforeDeletion(t *testing.T) {

  Line 115: func TestDestroyWithLabRuntimeCopiesMaxWorkers(t *testing.T) {

  Line 136: func TestSanitizeLabRuntimeNames(t *testing.T) {

  Line 161: func TestContainerFromLabNodeResolvesSanitizedNodeNames(t *testing.T) {


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


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


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

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

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

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

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

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


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

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

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

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

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

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


/source/head/core/network_test.go:
  Line 29: func TestInitMacvlanManagementNetwork(t *testing.T) {

  Line 46: func TestInitMgmtNetworkRejectsMgmtNetLinkWithMacvlan(t *testing.T) {

  Line 72: func TestCreateNetworkPassesStaticManagementAddresses(t *testing.T) {

  Line 109: func TestSyncMgmtHostRoutesReturnsRuntimeError(t *testing.T) {

  Line 133: func TestSkipMgmtNetwork(t *testing.T) {

  Line 255: func TestMgmtNetworksSkipped(t *testing.T) {

  Line 316: func TestCreateNetworkSkipsUnusedManagementNetwork(t *testing.T) {

  Line 369: func TestParseTopologyDoesNotAllocateManagementIPs(t *testing.T) {

  Line 381: func TestPrepareManagementNetworkAllocatesAfterResolution(t *testing.T) {

  Line 419: func TestPrepareManagementNetworkDelegatesRuntimeIPAM(t *testing.T) {

  Line 456: func TestPrepareManagementNetworkLoadsPreferredAddress(t *testing.T) {

  Line 495: func TestPrepareManagementNetworkRuntimeReservations(t *testing.T) {

  Line 578: func TestMgmtNetworkList(t *testing.T) {

  Line 635: func TestMgmtNetworkListErrors(t *testing.T) {

  Line 678: func TestNodeUnknownMgmtNetwork(t *testing.T) {

  Line 694: func TestMgmtNetworkListRequiresNodeSelection(t *testing.T) {

  Line 727: func TestMgmtNetworkListUnsupportedRuntime(t *testing.T) {

  Line 751: func TestResolveMgmtNetLinkNetworksUnsupportedRuntime(t *testing.T) {

  Line 780: func TestSingleEntryMgmtNetworkListDefaultsNodes(t *testing.T) {

  Line 802: func TestPrepareManagementNetworkPerNetwork(t *testing.T) {

  Line 890: func TestMgmtOverrideFlagsWithMultipleNetworks(t *testing.T) {

  Line 918: func TestCreateNetworkFillsResolvedSubnetEnv(t *testing.T) {

  Line 952: func TestInitNodeBindsRuntimeToNodeMgmtNetwork(t *testing.T) {

  Line 1025: func TestMgmtNetLinkSelectsNetwork(t *testing.T) {

  Line 1060: func TestMgmtNetLinkApplyEndpointKey(t *testing.T) {

  Line 1092: func TestMgmtNetLinkNetworkValidation(t *testing.T) {

  Line 1137: func TestMgmtNetLinkBridgeNetworkWithMacvlanDefault(t *testing.T) {

  Line 1166: func TestSkipMgmtNetworkKeepsNetworkUsedByMgmtNetLink(t *testing.T) {

  Line 1226: func TestResolveMgmtNetLinkNetworksAutoBridge(t *testing.T) {


/source/head/core/labruntime_cluster_test.go:
  Line 25: func TestC9sClusterNodeAccess(t *testing.T) {

  Line 187: func TestC9sClusterCapture(t *testing.T) {


/source/head/core/destroy_test.go:
  Line 27: func TestDestroyMakeCopyOptionOrder_nodeFilterAfterTopo(t *testing.T) {

  Line 50: func TestDestroyMakeCopyOptionOrder_nodeFilterBeforeTopoFails(t *testing.T) {

  Line 69: func TestWithLabNameOnly_setsNameWithoutTopologyFile(t *testing.T) {

  Line 90: func TestWithKeepMgmtNet_noopsForLabRuntime(t *testing.T) {

  Line 103: func TestAddMgmtNetworksFromContainers(t *testing.T) {

  Line 128: func TestMgmtNetworksForCleanupIncludesStateRecordedNetworks(t *testing.T) {

  Line 317: func TestDestroyCleanupReportsDestroyFailure(t *testing.T) {

  Line 373: func TestDestroyCleanupRemovesLabDirsOnSuccess(t *testing.T) {

  Line 417: func TestDestroyLabDirsKeepsFailedLabDirs(t *testing.T) {

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

  Line 516: func TestDestroyWithNoContainersAndAllPreservesDirs(t *testing.T) {

  Line 559: func TestDestroyWithNoContainersRefusesMismatchedDir(t *testing.T) {

  Line 589: func TestDestroyWithNoContainersMissingDirIsNoop(t *testing.T) {

  Line 629: func TestDestroyWithNoContainersByNameWithEnvBaseRemovesLabDir(t *testing.T) {

  Line 825: func TestMakeCopyForDestroySkipsMissingMgmtNetworks(t *testing.T) {

  Line 902: func TestMakeCopyForDestroyIgnoresMgmtNetLinkChecks(t *testing.T) {


/source/head/core/options_clab_test.go:
  Line 12: func TestWithTopologyVarsFiles_setsAbsPathWithoutTopology(t *testing.T) {

  Line 38: func TestWithTopologyVarsFiles_setMultiple(t *testing.T) {


/source/head/core/sshconfig_test.go:
  Line 36: func TestSSHConfigIdentityFileRendering(t *testing.T) {


/source/head/core/deploy_test.go:
  Line 31: func TestWaitForNodeDeployErrorPrecedence(t *testing.T) {

  Line 61: func TestCheckReconcileDeployOptionsRejectsManagementNetworkOverrides(t *testing.T) {

  Line 91: func TestCheckReconcileDeployOptionsAllowsTopologyManagementNetwork(t *testing.T) {

  Line 108: func TestWaitForApplyNetworkModeTargetNoTarget(t *testing.T) {

  Line 122: func TestWaitForApplyNetworkModeTargetInternalTargetAlreadyRunning(t *testing.T) {

  Line 154: func TestWaitForApplyNetworkModeTargetExternalTargetDelegates(t *testing.T) {

  Line 189: func TestDeployNodesWaitsForNetworkModeTargetWithSingleWorker(t *testing.T) {

  Line 260: func TestDeployNodesEmptyNodeNames(t *testing.T) {

  Line 268: func TestDeployNodesPropagatesTargetFailure(t *testing.T) {

  Line 296: func TestDeployNodesUnblocksNamespaceChainWithoutPolling(t *testing.T) {

  Line 327: func TestDeployNodesRejectsNamespaceCycleBeforeDeployment(t *testing.T) {

  Line 338: func TestDeployApplyNodesStartsNamespaceTarget(t *testing.T) {

  Line 403: func TestDeployNodesUnknownNode(t *testing.T) {

  Line 413: func TestDeployNodesReturnsErrorWhenWaitFails(t *testing.T) {

  Line 443: func TestWaitForApplyNetworkModeTargetUnknownNode(t *testing.T) {

  Line 452: func TestWaitForApplyNetworkModeTargetNilRuntime(t *testing.T) {

  Line 477: func TestCertificateAuthoritySetupUsesEnvironmentCAWithoutSettings(t *testing.T) {


/source/head/core/labruntime_gaps_test.go:
  Line 25: func TestContainerFromLabNodeReportsWorkload(t *testing.T) {

  Line 63: func TestDestroyWithLabRuntimePassesCleanup(t *testing.T) {

  Line 87: func TestDeployReconfigureWithLabRuntimeCleansUp(t *testing.T) {

  Line 111: func TestCheckConnectivitySkipsLocalRuntimesForLabRuntimes(t *testing.T) {

  Line 123: func TestContainerFromLabNodeReportsTheTopologyNode(t *testing.T) {


/source/head/core/tailscale_test.go:
  Line 36: func TestTailscaleSidecarEligible(t *testing.T) {

  Line 73: func TestInjectTailscaleSidecars(t *testing.T) {

  Line 155: func TestInjectTailscaleSidecarsDisabled(t *testing.T) {

  Line 173: func TestTailscaleSidecarsAreIndependentRuntimeNodes(t *testing.T) {

  Line 210: func TestTailscaleSidecarsIgnoreNodeDefaults(t *testing.T) {

  Line 245: func TestInjectTailscaleSidecarsNameCollision(t *testing.T) {

  Line 266: func TestInjectTailscaleSidecarsMissingAuthKey(t *testing.T) {


(Results truncated. Consider using a more specific path or pattern.)
Tool metadata
{
  "type": "tool",
  "id": "prt_19679b380001M3rMOE4KWtNoZk",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679a8c1001ildPUzX219gNFT",
  "callID": "call_0cc5244bacda414795b62d82",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/core/labruntime_gaps_test.go",
      "pattern": "^func Test"
    },
    "output": "Found 100 matches (more matches available)\n/source/head/core/labruntime_test.go:\n  Line 48: func TestExecWithLabRuntimeReturnsNestedFailureAndPreservesResult(t *testing.T) {\n\n  Line 75: func TestResolveRuntimeNameLowercasesValue(t *testing.T) {\n\n  Line 86: func TestApplyLabRuntimeDeployOptionsCopiesMaxWorkers(t *testing.T) {\n\n  Line 97: func TestDestroyWithLabRuntimeRejectsNodeFilterBeforeDeletion(t *testing.T) {\n\n  Line 115: func TestDestroyWithLabRuntimeCopiesMaxWorkers(t *testing.T) {\n\n  Line 136: func TestSanitizeLabRuntimeNames(t *testing.T) {\n\n  Line 161: func TestContainerFromLabNodeResolvesSanitizedNodeNames(t *testing.T) {\n\n\n/source/head/core/events/labruntime_test.go:\n  Line 10: func TestLabRuntimeEventStreamRequestScope(t *testing.T) {\n\n\n/source/head/core/events/netlink_test.go:\n  Line 11: func TestOverlayToolsInterfaceLeavesAttributesWhenNotStitched(t *testing.T) {\n\n\n/source/head/core/events/parity_test.go:\n  Line 231: func TestContainerEventParity(t *testing.T) {\n\n  Line 334: func TestContainerSnapshotParity(t *testing.T) {\n\n  Line 359: func TestContainerStateUsesDockerVocabulary(t *testing.T) {\n\n  Line 437: func TestInterfaceEventParity(t *testing.T) {\n\n  Line 523: func TestInterfaceEventOmitsUnknownValues(t *testing.T) {\n\n  Line 543: func TestLabRuntimeTopologyEventsKeepTheirAttributes(t *testing.T) {\n\n\n/source/head/core/events/netlink_watch_test.go:\n  Line 177: func TestNetlinkWatcherReportsExistingAndNewLinks(t *testing.T) {\n\n  Line 208: func TestNetlinkWatcherReportsLinksAddedWhileStarting(t *testing.T) {\n\n  Line 236: func TestNetlinkWatcherRetriesNamespaceLookup(t *testing.T) {\n\n  Line 267: func TestNetlinkWatcherStopsAfterRetries(t *testing.T) {\n\n  Line 288: func TestProcessExistingAfterResubscribe(t *testing.T) {\n\n  Line 361: func TestProcessUpdateDeleteOnlyTrackedLinks(t *testing.T) {\n\n\n/source/head/core/network_test.go:\n  Line 29: func TestInitMacvlanManagementNetwork(t *testing.T) {\n\n  Line 46: func TestInitMgmtNetworkRejectsMgmtNetLinkWithMacvlan(t *testing.T) {\n\n  Line 72: func TestCreateNetworkPassesStaticManagementAddresses(t *testing.T) {\n\n  Line 109: func TestSyncMgmtHostRoutesReturnsRuntimeError(t *testing.T) {\n\n  Line 133: func TestSkipMgmtNetwork(t *testing.T) {\n\n  Line 255: func TestMgmtNetworksSkipped(t *testing.T) {\n\n  Line 316: func TestCreateNetworkSkipsUnusedManagementNetwork(t *testing.T) {\n\n  Line 369: func TestParseTopologyDoesNotAllocateManagementIPs(t *testing.T) {\n\n  Line 381: func TestPrepareManagementNetworkAllocatesAfterResolution(t *testing.T) {\n\n  Line 419: func TestPrepareManagementNetworkDelegatesRuntimeIPAM(t *testing.T) {\n\n  Line 456: func TestPrepareManagementNetworkLoadsPreferredAddress(t *testing.T) {\n\n  Line 495: func TestPrepareManagementNetworkRuntimeReservations(t *testing.T) {\n\n  Line 578: func TestMgmtNetworkList(t *testing.T) {\n\n  Line 635: func TestMgmtNetworkListErrors(t *testing.T) {\n\n  Line 678: func TestNodeUnknownMgmtNetwork(t *testing.T) {\n\n  Line 694: func TestMgmtNetworkListRequiresNodeSelection(t *testing.T) {\n\n  Line 727: func TestMgmtNetworkListUnsupportedRuntime(t *testing.T) {\n\n  Line 751: func TestResolveMgmtNetLinkNetworksUnsupportedRuntime(t *testing.T) {\n\n  Line 780: func TestSingleEntryMgmtNetworkListDefaultsNodes(t *testing.T) {\n\n  Line 802: func TestPrepareManagementNetworkPerNetwork(t *testing.T) {\n\n  Line 890: func TestMgmtOverrideFlagsWithMultipleNetworks(t *testing.T) {\n\n  Line 918: func TestCreateNetworkFillsResolvedSubnetEnv(t *testing.T) {\n\n  Line 952: func TestInitNodeBindsRuntimeToNodeMgmtNetwork(t *testing.T) {\n\n  Line 1025: func TestMgmtNetLinkSelectsNetwork(t *testing.T) {\n\n  Line 1060: func TestMgmtNetLinkApplyEndpointKey(t *testing.T) {\n\n  Line 1092: func TestMgmtNetLinkNetworkValidation(t *testing.T) {\n\n  Line 1137: func TestMgmtNetLinkBridgeNetworkWithMacvlanDefault(t *testing.T) {\n\n  Line 1166: func TestSkipMgmtNetworkKeepsNetworkUsedByMgmtNetLink(t *testing.T) {\n\n  Line 1226: func TestResolveMgmtNetLinkNetworksAutoBridge(t *testing.T) {\n\n\n/source/head/core/labruntime_cluster_test.go:\n  Line 25: func TestC9sClusterNodeAccess(t *testing.T) {\n\n  Line 187: func TestC9sClusterCapture(t *testing.T) {\n\n\n/source/head/core/destroy_test.go:\n  Line 27: func TestDestroyMakeCopyOptionOrder_nodeFilterAfterTopo(t *testing.T) {\n\n  Line 50: func TestDestroyMakeCopyOptionOrder_nodeFilterBeforeTopoFails(t *testing.T) {\n\n  Line 69: func TestWithLabNameOnly_setsNameWithoutTopologyFile(t *testing.T) {\n\n  Line 90: func TestWithKeepMgmtNet_noopsForLabRuntime(t *testing.T) {\n\n  Line 103: func TestAddMgmtNetworksFromContainers(t *testing.T) {\n\n  Line 128: func TestMgmtNetworksForCleanupIncludesStateRecordedNetworks(t *testing.T) {\n\n  Line 317: func TestDestroyCleanupReportsDestroyFailure(t *testing.T) {\n\n  Line 373: func TestDestroyCleanupRemovesLabDirsOnSuccess(t *testing.T) {\n\n  Line 417: func TestDestroyLabDirsKeepsFailedLabDirs(t *testing.T) {\n\n  Line 448: func TestDestroyWithNoContainersRemovesOnlyOwnLabDir(t *testing.T) {\n\n  Line 516: func TestDestroyWithNoContainersAndAllPreservesDirs(t *testing.T) {\n\n  Line 559: func TestDestroyWithNoContainersRefusesMismatchedDir(t *testing.T) {\n\n  Line 589: func TestDestroyWithNoContainersMissingDirIsNoop(t *testing.T) {\n\n  Line 629: func TestDestroyWithNoContainersByNameWithEnvBaseRemovesLabDir(t *testing.T) {\n\n  Line 825: func TestMakeCopyForDestroySkipsMissingMgmtNetworks(t *testing.T) {\n\n  Line 902: func TestMakeCopyForDestroyIgnoresMgmtNetLinkChecks(t *testing.T) {\n\n\n/source/head/core/options_clab_test.go:\n  Line 12: func TestWithTopologyVarsFiles_setsAbsPathWithoutTopology(t *testing.T) {\n\n  Line 38: func TestWithTopologyVarsFiles_setMultiple(t *testing.T) {\n\n\n/source/head/core/sshconfig_test.go:\n  Line 36: func TestSSHConfigIdentityFileRendering(t *testing.T) {\n\n\n/source/head/core/deploy_test.go:\n  Line 31: func TestWaitForNodeDeployErrorPrecedence(t *testing.T) {\n\n  Line 61: func TestCheckReconcileDeployOptionsRejectsManagementNetworkOverrides(t *testing.T) {\n\n  Line 91: func TestCheckReconcileDeployOptionsAllowsTopologyManagementNetwork(t *testing.T) {\n\n  Line 108: func TestWaitForApplyNetworkModeTargetNoTarget(t *testing.T) {\n\n  Line 122: func TestWaitForApplyNetworkModeTargetInternalTargetAlreadyRunning(t *testing.T) {\n\n  Line 154: func TestWaitForApplyNetworkModeTargetExternalTargetDelegates(t *testing.T) {\n\n  Line 189: func TestDeployNodesWaitsForNetworkModeTargetWithSingleWorker(t *testing.T) {\n\n  Line 260: func TestDeployNodesEmptyNodeNames(t *testing.T) {\n\n  Line 268: func TestDeployNodesPropagatesTargetFailure(t *testing.T) {\n\n  Line 296: func TestDeployNodesUnblocksNamespaceChainWithoutPolling(t *testing.T) {\n\n  Line 327: func TestDeployNodesRejectsNamespaceCycleBeforeDeployment(t *testing.T) {\n\n  Line 338: func TestDeployApplyNodesStartsNamespaceTarget(t *testing.T) {\n\n  Line 403: func TestDeployNodesUnknownNode(t *testing.T) {\n\n  Line 413: func TestDeployNodesReturnsErrorWhenWaitFails(t *testing.T) {\n\n  Line 443: func TestWaitForApplyNetworkModeTargetUnknownNode(t *testing.T) {\n\n  Line 452: func TestWaitForApplyNetworkModeTargetNilRuntime(t *testing.T) {\n\n  Line 477: func TestCertificateAuthoritySetupUsesEnvironmentCAWithoutSettings(t *testing.T) {\n\n\n/source/head/core/labruntime_gaps_test.go:\n  Line 25: func TestContainerFromLabNodeReportsWorkload(t *testing.T) {\n\n  Line 63: func TestDestroyWithLabRuntimePassesCleanup(t *testing.T) {\n\n  Line 87: func TestDeployReconfigureWithLabRuntimeCleansUp(t *testing.T) {\n\n  Line 111: func TestCheckConnectivitySkipsLocalRuntimesForLabRuntimes(t *testing.T) {\n\n  Line 123: func TestContainerFromLabNodeReportsTheTopologyNode(t *testing.T) {\n\n\n/source/head/core/tailscale_test.go:\n  Line 36: func TestTailscaleSidecarEligible(t *testing.T) {\n\n  Line 73: func TestInjectTailscaleSidecars(t *testing.T) {\n\n  Line 155: func TestInjectTailscaleSidecarsDisabled(t *testing.T) {\n\n  Line 173: func TestTailscaleSidecarsAreIndependentRuntimeNodes(t *testing.T) {\n\n  Line 210: func TestTailscaleSidecarsIgnoreNodeDefaults(t *testing.T) {\n\n  Line 245: func TestInjectTailscaleSidecarsNameCollision(t *testing.T) {\n\n  Line 266: func TestInjectTailscaleSidecarsMissingAuthKey(t *testing.T) {\n\n\n(Results truncated. Consider using a more specific path or pattern.)",
    "title": "^func Test",
    "metadata": {
      "matches": 100,
      "truncated": true
    },
    "time": {
      "start": 1793525920645,
      "end": 1793525920659
    }
  }
}
grep · completed

Input

{
  "path": "/source/head/labruntime/runtime_gaps_test.go",
  "pattern": "^func Test"
}

Output

Found 100 matches (more matches available)
/source/head/labruntime/clabernetes/runtime_gaps_test.go:
  Line 32: func TestNewDoesNotLoadKubeconfig(t *testing.T) {

  Line 62: func TestConnectLoadsClientsOnce(t *testing.T) {

  Line 110: func TestListNamespacePrecedence(t *testing.T) {

  Line 133: func TestEventScopeFor(t *testing.T) {

  Line 201: func TestStreamEventsWatchesOnlyTheScopedNamespace(t *testing.T) {

  Line 235: func TestNodeStateFromResourceLocatesWorkload(t *testing.T) {

  Line 285: func TestEnrichStateReportsPodAndContainer(t *testing.T) {

  Line 367: func TestParseInterfaceSample(t *testing.T) {

  Line 406: func TestCommandNotExecutable(t *testing.T) {

  Line 432: func TestTopologyPersistenceRetainsClaims(t *testing.T) {

  Line 443: func TestDestroyKeepsRetainedClaimsUnlessCleanup(t *testing.T) {


/source/head/labruntime/clabernetes/manifests_test.go:
  Line 88: func TestManifestsTopologyBundle(t *testing.T) {

  Line 159: func TestManifestsPrimitiveBundle(t *testing.T) {

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

  Line 225: func TestManifestsMatchDeployedResources(t *testing.T) {

  Line 284: func TestManifestsMatchDeployedPrimitiveResources(t *testing.T) {

  Line 324: func TestManifestsKeepBinaryFilesAsBinaryData(t *testing.T) {


/source/head/labruntime/clabernetes/event_parity_test.go:
  Line 85: func TestNetlinkOperState(t *testing.T) {

  Line 107: func TestInterfaceEventDataNamesInterfacesLikeDocker(t *testing.T) {

  Line 153: func TestInterfacePollerReportsTheTopologyInterfaces(t *testing.T) {

  Line 252: func TestInterfacePollerFirstRoundWithoutInitialState(t *testing.T) {

  Line 265: func TestInterfacePollerStatsCoverTheReportedInterfaces(t *testing.T) {

  Line 325: func TestInterfacePollerListsAPodOncePerInterfaceSet(t *testing.T) {

  Line 369: func TestContainerTransitionActions(t *testing.T) {

  Line 598: func TestContainerTrackerReportsTheNodeLifecycle(t *testing.T) {

  Line 672: func TestContainerTrackerSeedsWithoutSnapshot(t *testing.T) {

  Line 686: func TestNodeContainerState(t *testing.T) {

  Line 720: func TestNewestPodPrefersAPodThatIsNotDeleted(t *testing.T) {

  Line 744: func TestEnrichStateReportsContainerStateAndHealth(t *testing.T) {

  Line 811: func TestDeployRecordsTheTopologyFile(t *testing.T) {

  Line 903: func TestCarryOverNodeTopologyFile(t *testing.T) {

  Line 946: func TestManifestsCarryNoTopologyFile(t *testing.T) {

  Line 965: func TestStateReportsTheRecordedTopologyFile(t *testing.T) {


/source/head/labruntime/clabernetes/files_test.go:
  Line 17: func TestStageNodeFileReferences(t *testing.T) {

  Line 86: func TestStageConfigMapFileRejectsOversizedEmbeddedContent(t *testing.T) {

  Line 102: func TestResolveNodeFileReferenceHonorsCancellation(t *testing.T) {

  Line 123: func TestClabernetesBriefLinkMgmtNetNetwork(t *testing.T) {


/source/head/labruntime/clabernetes/resources_test.go:
  Line 16: func TestConditionPendingReasonIdentifiesDirectHelper(t *testing.T) {

  Line 67: func TestWaitPrimitiveLinksResolvedListsTopologyScopedLinks(t *testing.T) {

  Line 116: func TestWaitPrimitiveLinksResolvedIgnoresForeignLinks(t *testing.T) {


/source/head/labruntime/clabernetes/config_test.go:
  Line 12: func TestDeleteManagedLabNamespacePreservesSharedOrOverriddenNamespace(t *testing.T) {


/source/head/labruntime/clabernetes/nodes_test.go:
  Line 214: func TestStopPatchesThePrimaryRunStateAndWaitsForStopped(t *testing.T) {

  Line 257: func TestStartWaitsForTheObservedGenerationAndReadiness(t *testing.T) {

  Line 295: func TestRestartSetsANewTokenAndWaitsForIt(t *testing.T) {

  Line 349: func TestRunStateWaitTimeoutNamesThePendingNodes(t *testing.T) {

  Line 367: func TestNodeLifecycleRejectsUnknownNodes(t *testing.T) {

  Line 389: func TestPrimitivePlanAndApplyKeepTheRunState(t *testing.T) {

  Line 439: func TestManifestsNeverCarryARunState(t *testing.T) {

  Line 482: func TestCheckNodeRunStateSchema(t *testing.T) {

  Line 520: func TestSupportCheckRunsOnceBeforeTheFirstClusterCall(t *testing.T) {

  Line 563: func TestSupportCheckRetriesFailedRequestsAndRemembersSuccess(t *testing.T) {

  Line 600: func TestSupportCheckReadsTheOpenAPIDocumentAsTheCaller(t *testing.T) {

  Line 686: func TestStartAcceptsANodeWhoseLinkPeerIsStopped(t *testing.T) {

  Line 714: func TestLabSettlesWithStoppedNodesAndTheirPeers(t *testing.T) {

  Line 774: func TestPrimitiveObjectsConformAfterAnAPIRoundTrip(t *testing.T) {


/source/head/labruntime/clabernetes/capture_test.go:
  Line 379: func TestCaptureInterfacesUsesTopologyNames(t *testing.T) {

  Line 419: func TestCaptureMergesNodesIntoOneSection(t *testing.T) {

  Line 481: func TestCaptureChainsSegmentsWithoutDuplicatesOrGaps(t *testing.T) {

  Line 540: func TestCaptureReportsAGapWhenTheFollowUpStartsLate(t *testing.T) {

  Line 571: func TestCaptureMapsDeniedAndFailedAuditsToErrors(t *testing.T) {

  Line 596: func TestCaptureAuditLineWriter(t *testing.T) {

  Line 633: func TestCaptureStopsAtThePacketLimit(t *testing.T) {

  Line 661: func TestCaptureEndsCleanlyWhenTheContextEnds(t *testing.T) {

  Line 680: func TestCaptureValidatesTargets(t *testing.T) {

  Line 722: func TestInspectInterfacesReportsStateFromSysfs(t *testing.T) {

  Line 771: func TestCaptureWritesWhatItReadWhenTheContextEnds(t *testing.T) {

  Line 851: func TestCaptureClosesStdinWhenItEnds(t *testing.T) {

  Line 920: func TestCaptureRejectsAClabwireWithoutStopOnStdinClose(t *testing.T) {

  Line 954: func TestCaptureMergesNodesInTimestampOrder(t *testing.T) {

  Line 997: func TestCaptureChainsSeveralNodesInOrderWithoutDuplicates(t *testing.T) {

  Line 1056: func TestCaptureReorderWindowKnob(t *testing.T) {


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

  Line 112: func TestStreamLogsTargetsTheDeviceContainer(t *testing.T) {

  Line 157: func TestDialPortValidatesTheRequest(t *testing.T) {

  Line 197: func TestSampleStatsSumsTheDeviceContainers(t *testing.T) {

  Line 228: func TestSampleStatsReportsAMissingMetricsAPI(t *testing.T) {

  Line 250: func TestTerminalSizeQueue(t *testing.T) {

  Line 316: func TestIdentityImpersonatesOnEveryTransport(t *testing.T) {

  Line 396: func TestNoIdentityLeavesTheKubeconfigAsItIs(t *testing.T) {


/source/head/labruntime/names_test.go:
  Line 8: func TestNormalizeExposeType(t *testing.T) {


/source/head/labruntime/clabernetes/clabernetes_test.go:
  Line 40: func TestRuntimeName(t *testing.T) {

  Line 54: func TestParseProcNetDev(t *testing.T) {

  Line 80: func TestParseProcNetDevRejectsMalformedLine(t *testing.T) {

  Line 89: func TestPreferredDeviceContainerName(t *testing.T) {

  Line 190: func TestCleanTarPath(t *testing.T) {

  Line 223: func TestNamespaceForLab(t *testing.T) {

  Line 283: func TestConfiguredLabNamespacePrecedence(t *testing.T) {

  Line 299: func TestDeployUsesNamespaceOverrideWithoutManagingIt(t *testing.T) {

  Line 340: func TestDeployCreatesAndDestroyRemovesDedicatedLabNamespace(t *testing.T) {

  Line 393: func TestDestroyPreservesPreexistingLabNamespace(t *testing.T) {

  Line 432: func TestDestroyFallsBackToIndividualDeletesWithoutTouchingOtherLabs(t *testing.T) {

  Line 487: func TestDestroyUsesLabelScopedDeleteCollection(t *testing.T) {

  Line 517: func TestWaitAndSweepDeletedRemovesLateStagedConfigMaps(t *testing.T) {

  Line 539: func TestSavedFilesFromTarSkipsUnsafeEntries(t *testing.T) {

  Line 582: func TestStateFromTopology(t *testing.T) {

  Line 634: func TestPrimitiveResourcesUseCurrentC9sAPI(t *testing.T) {

  Line 649: func TestPrimitiveResourceGroupOrder(t *testing.T) {

  Line 665: func TestPrimitiveLinkPendingReason(t *testing.T) {

  Line 706: func TestEnrichStateUsesNodeResources(t *testing.T) {

  Line 750: func TestWaitReadyTimeoutReportsPendingNodes(t *testing.T) {


(Results truncated. Consider using a more specific path or pattern.)
Tool metadata
{
  "type": "tool",
  "id": "prt_19679b3c2001m1aBbST0BklfyP",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679a8c1001ildPUzX219gNFT",
  "callID": "call_a9a850fddacc40e6a2fcf7f7",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/labruntime/runtime_gaps_test.go",
      "pattern": "^func Test"
    },
    "output": "Found 100 matches (more matches available)\n/source/head/labruntime/clabernetes/runtime_gaps_test.go:\n  Line 32: func TestNewDoesNotLoadKubeconfig(t *testing.T) {\n\n  Line 62: func TestConnectLoadsClientsOnce(t *testing.T) {\n\n  Line 110: func TestListNamespacePrecedence(t *testing.T) {\n\n  Line 133: func TestEventScopeFor(t *testing.T) {\n\n  Line 201: func TestStreamEventsWatchesOnlyTheScopedNamespace(t *testing.T) {\n\n  Line 235: func TestNodeStateFromResourceLocatesWorkload(t *testing.T) {\n\n  Line 285: func TestEnrichStateReportsPodAndContainer(t *testing.T) {\n\n  Line 367: func TestParseInterfaceSample(t *testing.T) {\n\n  Line 406: func TestCommandNotExecutable(t *testing.T) {\n\n  Line 432: func TestTopologyPersistenceRetainsClaims(t *testing.T) {\n\n  Line 443: func TestDestroyKeepsRetainedClaimsUnlessCleanup(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/manifests_test.go:\n  Line 88: func TestManifestsTopologyBundle(t *testing.T) {\n\n  Line 159: func TestManifestsPrimitiveBundle(t *testing.T) {\n\n  Line 208: func TestManifestsRejectUnsupportedTopology(t *testing.T) {\n\n  Line 225: func TestManifestsMatchDeployedResources(t *testing.T) {\n\n  Line 284: func TestManifestsMatchDeployedPrimitiveResources(t *testing.T) {\n\n  Line 324: func TestManifestsKeepBinaryFilesAsBinaryData(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/event_parity_test.go:\n  Line 85: func TestNetlinkOperState(t *testing.T) {\n\n  Line 107: func TestInterfaceEventDataNamesInterfacesLikeDocker(t *testing.T) {\n\n  Line 153: func TestInterfacePollerReportsTheTopologyInterfaces(t *testing.T) {\n\n  Line 252: func TestInterfacePollerFirstRoundWithoutInitialState(t *testing.T) {\n\n  Line 265: func TestInterfacePollerStatsCoverTheReportedInterfaces(t *testing.T) {\n\n  Line 325: func TestInterfacePollerListsAPodOncePerInterfaceSet(t *testing.T) {\n\n  Line 369: func TestContainerTransitionActions(t *testing.T) {\n\n  Line 598: func TestContainerTrackerReportsTheNodeLifecycle(t *testing.T) {\n\n  Line 672: func TestContainerTrackerSeedsWithoutSnapshot(t *testing.T) {\n\n  Line 686: func TestNodeContainerState(t *testing.T) {\n\n  Line 720: func TestNewestPodPrefersAPodThatIsNotDeleted(t *testing.T) {\n\n  Line 744: func TestEnrichStateReportsContainerStateAndHealth(t *testing.T) {\n\n  Line 811: func TestDeployRecordsTheTopologyFile(t *testing.T) {\n\n  Line 903: func TestCarryOverNodeTopologyFile(t *testing.T) {\n\n  Line 946: func TestManifestsCarryNoTopologyFile(t *testing.T) {\n\n  Line 965: func TestStateReportsTheRecordedTopologyFile(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/files_test.go:\n  Line 17: func TestStageNodeFileReferences(t *testing.T) {\n\n  Line 86: func TestStageConfigMapFileRejectsOversizedEmbeddedContent(t *testing.T) {\n\n  Line 102: func TestResolveNodeFileReferenceHonorsCancellation(t *testing.T) {\n\n  Line 123: func TestClabernetesBriefLinkMgmtNetNetwork(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/resources_test.go:\n  Line 16: func TestConditionPendingReasonIdentifiesDirectHelper(t *testing.T) {\n\n  Line 67: func TestWaitPrimitiveLinksResolvedListsTopologyScopedLinks(t *testing.T) {\n\n  Line 116: func TestWaitPrimitiveLinksResolvedIgnoresForeignLinks(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/config_test.go:\n  Line 12: func TestDeleteManagedLabNamespacePreservesSharedOrOverriddenNamespace(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/nodes_test.go:\n  Line 214: func TestStopPatchesThePrimaryRunStateAndWaitsForStopped(t *testing.T) {\n\n  Line 257: func TestStartWaitsForTheObservedGenerationAndReadiness(t *testing.T) {\n\n  Line 295: func TestRestartSetsANewTokenAndWaitsForIt(t *testing.T) {\n\n  Line 349: func TestRunStateWaitTimeoutNamesThePendingNodes(t *testing.T) {\n\n  Line 367: func TestNodeLifecycleRejectsUnknownNodes(t *testing.T) {\n\n  Line 389: func TestPrimitivePlanAndApplyKeepTheRunState(t *testing.T) {\n\n  Line 439: func TestManifestsNeverCarryARunState(t *testing.T) {\n\n  Line 482: func TestCheckNodeRunStateSchema(t *testing.T) {\n\n  Line 520: func TestSupportCheckRunsOnceBeforeTheFirstClusterCall(t *testing.T) {\n\n  Line 563: func TestSupportCheckRetriesFailedRequestsAndRemembersSuccess(t *testing.T) {\n\n  Line 600: func TestSupportCheckReadsTheOpenAPIDocumentAsTheCaller(t *testing.T) {\n\n  Line 686: func TestStartAcceptsANodeWhoseLinkPeerIsStopped(t *testing.T) {\n\n  Line 714: func TestLabSettlesWithStoppedNodesAndTheirPeers(t *testing.T) {\n\n  Line 774: func TestPrimitiveObjectsConformAfterAnAPIRoundTrip(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/capture_test.go:\n  Line 379: func TestCaptureInterfacesUsesTopologyNames(t *testing.T) {\n\n  Line 419: func TestCaptureMergesNodesIntoOneSection(t *testing.T) {\n\n  Line 481: func TestCaptureChainsSegmentsWithoutDuplicatesOrGaps(t *testing.T) {\n\n  Line 540: func TestCaptureReportsAGapWhenTheFollowUpStartsLate(t *testing.T) {\n\n  Line 571: func TestCaptureMapsDeniedAndFailedAuditsToErrors(t *testing.T) {\n\n  Line 596: func TestCaptureAuditLineWriter(t *testing.T) {\n\n  Line 633: func TestCaptureStopsAtThePacketLimit(t *testing.T) {\n\n  Line 661: func TestCaptureEndsCleanlyWhenTheContextEnds(t *testing.T) {\n\n  Line 680: func TestCaptureValidatesTargets(t *testing.T) {\n\n  Line 722: func TestInspectInterfacesReportsStateFromSysfs(t *testing.T) {\n\n  Line 771: func TestCaptureWritesWhatItReadWhenTheContextEnds(t *testing.T) {\n\n  Line 851: func TestCaptureClosesStdinWhenItEnds(t *testing.T) {\n\n  Line 920: func TestCaptureRejectsAClabwireWithoutStopOnStdinClose(t *testing.T) {\n\n  Line 954: func TestCaptureMergesNodesInTimestampOrder(t *testing.T) {\n\n  Line 997: func TestCaptureChainsSeveralNodesInOrderWithoutDuplicates(t *testing.T) {\n\n  Line 1056: func TestCaptureReorderWindowKnob(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/access_test.go:\n  Line 76: func TestLocateNode(t *testing.T) {\n\n  Line 112: func TestStreamLogsTargetsTheDeviceContainer(t *testing.T) {\n\n  Line 157: func TestDialPortValidatesTheRequest(t *testing.T) {\n\n  Line 197: func TestSampleStatsSumsTheDeviceContainers(t *testing.T) {\n\n  Line 228: func TestSampleStatsReportsAMissingMetricsAPI(t *testing.T) {\n\n  Line 250: func TestTerminalSizeQueue(t *testing.T) {\n\n  Line 316: func TestIdentityImpersonatesOnEveryTransport(t *testing.T) {\n\n  Line 396: func TestNoIdentityLeavesTheKubeconfigAsItIs(t *testing.T) {\n\n\n/source/head/labruntime/names_test.go:\n  Line 8: func TestNormalizeExposeType(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/clabernetes_test.go:\n  Line 40: func TestRuntimeName(t *testing.T) {\n\n  Line 54: func TestParseProcNetDev(t *testing.T) {\n\n  Line 80: func TestParseProcNetDevRejectsMalformedLine(t *testing.T) {\n\n  Line 89: func TestPreferredDeviceContainerName(t *testing.T) {\n\n  Line 190: func TestCleanTarPath(t *testing.T) {\n\n  Line 223: func TestNamespaceForLab(t *testing.T) {\n\n  Line 283: func TestConfiguredLabNamespacePrecedence(t *testing.T) {\n\n  Line 299: func TestDeployUsesNamespaceOverrideWithoutManagingIt(t *testing.T) {\n\n  Line 340: func TestDeployCreatesAndDestroyRemovesDedicatedLabNamespace(t *testing.T) {\n\n  Line 393: func TestDestroyPreservesPreexistingLabNamespace(t *testing.T) {\n\n  Line 432: func TestDestroyFallsBackToIndividualDeletesWithoutTouchingOtherLabs(t *testing.T) {\n\n  Line 487: func TestDestroyUsesLabelScopedDeleteCollection(t *testing.T) {\n\n  Line 517: func TestWaitAndSweepDeletedRemovesLateStagedConfigMaps(t *testing.T) {\n\n  Line 539: func TestSavedFilesFromTarSkipsUnsafeEntries(t *testing.T) {\n\n  Line 582: func TestStateFromTopology(t *testing.T) {\n\n  Line 634: func TestPrimitiveResourcesUseCurrentC9sAPI(t *testing.T) {\n\n  Line 649: func TestPrimitiveResourceGroupOrder(t *testing.T) {\n\n  Line 665: func TestPrimitiveLinkPendingReason(t *testing.T) {\n\n  Line 706: func TestEnrichStateUsesNodeResources(t *testing.T) {\n\n  Line 750: func TestWaitReadyTimeoutReportsPendingNodes(t *testing.T) {\n\n\n(Results truncated. Consider using a more specific path or pattern.)",
    "title": "^func Test",
    "metadata": {
      "matches": 100,
      "truncated": true
    },
    "time": {
      "start": 1793525920709,
      "end": 1793525920721
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19679b3e1001pa9GotX4b7fMYs",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679a8c1001ildPUzX219gNFT",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 65849,
    "input": 2167,
    "output": 103,
    "reasoning": 27,
    "cache": {
      "read": 63552,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19679a8c1001ildPUzX219gNFT",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525917889,
    "completed": 1793525920740
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 65849,
    "input": 2167,
    "output": 103,
    "reasoning": 27,
    "cache": {
      "read": 63552,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 36
step-start
{
  "type": "step-start",
  "id": "prt_19679bc70001ApILDEbErhBoEW",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679b3ee001COvEVllsbhJ1dn"
}
Reasoning
Test coverage for the new behavior is extensive. Remaining: docs skim and robot test skim, plus a final check on the diff for `core/events/stream.go` and `netlink.go` changes (the parts of the diff I read in the first session — details were mostly lost, so I should verify the netlink.go parity attributes function). Let me check `labRuntimeInterfaceAttributes` in netlink.go and the `streamLabRuntimeEvents` handling of `state` attributes.
Test coverage is thorough. Now verify the netlink parity attributes and the stream formatter.
grep · completed

Input

{
  "path": "/source/head/core/events/netlink.go",
  "pattern": "labRuntimeInterfaceAttributes|interfaceSnapshotAttributes|interfaceStatsAttributes|func netlinkOperState"
}

Output

Found 12 matches
/source/head/core/events/netlink.go:
  Line 648: // interfaceSnapshotAttributes are the attributes every interface event reports for the

  Line 650: func interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {

  Line 670: // interfaceStatsAttributes adds the counters and rates of a stats event.

  Line 671: func interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {

  Line 683: // labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those

  Line 686: func labRuntimeInterfaceAttributes(

  Line 690: 	attributes := interfaceSnapshotAttributes(ifaceSnapshot{

  Line 714: 		interfaceStatsAttributes(attributes, ifaceStatsMetrics{

  Line 734: 	attributes := interfaceSnapshotAttributes(snapshot)

  Line 885: 	interfaceStatsAttributes(attributes, metrics)


/source/head/core/events/stream.go:
  Line 204: 		attributes = labRuntimeInterfaceAttributes(lab, ev.ActorName, ev.Interface)


/source/head/core/events/parity_test.go:
  Line 407: 		interfaceStatsAttributes(attributes, *stats)
Tool metadata
{
  "type": "tool",
  "id": "prt_19679c2260014YvsyRolkh0o1T",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679b3ee001COvEVllsbhJ1dn",
  "callID": "call_1c9966b581934a87b6130580",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/core/events/netlink.go",
      "pattern": "labRuntimeInterfaceAttributes|interfaceSnapshotAttributes|interfaceStatsAttributes|func netlinkOperState"
    },
    "output": "Found 12 matches\n/source/head/core/events/netlink.go:\n  Line 648: // interfaceSnapshotAttributes are the attributes every interface event reports for the\n\n  Line 650: func interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {\n\n  Line 670: // interfaceStatsAttributes adds the counters and rates of a stats event.\n\n  Line 671: func interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {\n\n  Line 683: // labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those\n\n  Line 686: func labRuntimeInterfaceAttributes(\n\n  Line 690: \tattributes := interfaceSnapshotAttributes(ifaceSnapshot{\n\n  Line 714: \t\tinterfaceStatsAttributes(attributes, ifaceStatsMetrics{\n\n  Line 734: \tattributes := interfaceSnapshotAttributes(snapshot)\n\n  Line 885: \tinterfaceStatsAttributes(attributes, metrics)\n\n\n/source/head/core/events/stream.go:\n  Line 204: \t\tattributes = labRuntimeInterfaceAttributes(lab, ev.ActorName, ev.Interface)\n\n\n/source/head/core/events/parity_test.go:\n  Line 407: \t\tinterfaceStatsAttributes(attributes, *stats)\n",
    "title": "labRuntimeInterfaceAttributes|interfaceSnapshotAttributes|interfaceStatsAttributes|func netlinkOperState",
    "metadata": {
      "matches": 12,
      "truncated": false
    },
    "time": {
      "start": 1793525924395,
      "end": 1793525924414
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19679c240001hDN1rXpmG3XhtV",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679b3ee001COvEVllsbhJ1dn",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 73028,
    "input": 7082,
    "output": 56,
    "reasoning": 98,
    "cache": {
      "read": 65792,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19679b3ee001COvEVllsbhJ1dn",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525920750,
    "completed": 1793525924418
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 73028,
    "input": 7082,
    "output": 56,
    "reasoning": 98,
    "cache": {
      "read": 65792,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 37
step-start
{
  "type": "step-start",
  "id": "prt_19679cadd001XYDdoEtb0nrNOf",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679c24a001UDdlfknprGOzR3"
}
read · completed

Input

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

Output

<path>/source/head/core/events/netlink.go</path>
<type>file</type>
<content>
620: 			snapshot.PacketLoss = 0
621: 			snapshot.Rate = 0
622: 			snapshot.Corruption = 0
623: 		}
624: 
625: 		if !snapshot.equal(previous) {
626: 			states[idx] = snapshot
627: 			registry.emitInterfaceEvent(w.container, "update", snapshot)
628: 		}
629: 	}
630: }
631: 
632: func firstContainerName(container *clabruntime.GenericContainer) string {
633: 	if container == nil || len(container.Names) == 0 {
634: 		return ""
635: 	}
636: 
637: 	return container.Names[0]
638: }
639: 
640: func containerLabel(container *clabruntime.GenericContainer) string {
641: 	if container == nil || container.Labels == nil {
642: 		return ""
643: 	}
644: 
645: 	return container.Labels[clabconstants.Containerlab]
646: }
647: 
648: // interfaceSnapshotAttributes are the attributes every interface event reports for the
649: // interface itself.
650: func interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {
651: 	attributes := map[string]string{
652: 		"ifname": snapshot.Name,
653: 		"index":  strconv.Itoa(snapshot.Index),
654: 		"mtu":    strconv.Itoa(snapshot.MTU),
655: 		"state":  snapshot.OperState,
656: 		"type":   snapshot.Type,
657: 	}
658: 
659: 	if snapshot.Alias != "" {
660: 		attributes["alias"] = snapshot.Alias
661: 	}
662: 
663: 	if snapshot.MAC != "" {
664: 		attributes["mac"] = snapshot.MAC
665: 	}
666: 
667: 	return attributes
668: }
669: 
670: // interfaceStatsAttributes adds the counters and rates of a stats event.
671: func interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {
672: 	attributes["rx_bytes"] = strconv.FormatUint(metrics.RxBytes, 10)
673: 	attributes["tx_bytes"] = strconv.FormatUint(metrics.TxBytes, 10)
674: 	attributes["rx_packets"] = strconv.FormatUint(metrics.RxPackets, 10)
675: 	attributes["tx_packets"] = strconv.FormatUint(metrics.TxPackets, 10)
676: 	attributes["rx_bps"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)
677: 	attributes["tx_bps"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)
678: 	attributes["rx_pps"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)
679: 	attributes["tx_pps"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)
680: 	attributes["interval_seconds"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)
681: }
682: 
683: // labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those
684: // of the netlink interface events, for the node the runtime runs. Values the runtime could not
685: // read (no index or MTU without a shell in the node) are left out rather than reported as 0.
686: func labRuntimeInterfaceAttributes(
687: 	lab, name string,
688: 	iface *clablabruntime.InterfaceEventData,
689: ) map[string]string {
690: 	attributes := interfaceSnapshotAttributes(ifaceSnapshot{
691: 		Index:     iface.Index,
692: 		Name:      iface.Name,
693: 		Alias:     iface.Alias,
694: 		MTU:       iface.MTU,
695: 		MAC:       iface.MAC,
696: 		OperState: iface.OperState,
697: 		Type:      iface.Type,
698: 	})
699: 	if iface.Index <= 0 {
700: 		delete(attributes, "index")
701: 	}
702: 	if iface.MTU <= 0 {
703: 		delete(attributes, "mtu")
704: 	}
705: 
706: 	if lab != "" {
707: 		attributes["lab"] = lab
708: 	}
709: 	if name != "" {
710: 		attributes["name"] = name
711: 	}
712: 
713: 	if stats := iface.Stats; stats != nil {
714: 		interfaceStatsAttributes(attributes, ifaceStatsMetrics{
715: 			RxBytes:   stats.RxBytes,
716: 			TxBytes:   stats.TxBytes,
717: 			RxPackets: stats.RxPackets,
718: 			TxPackets: stats.TxPackets,
719: 			RxBps:     stats.RxBps,
720: 			TxBps:     stats.TxBps,
721: 			RxPps:     stats.RxPps,
722: 			TxPps:     stats.TxPps,
723: 			Interval:  stats.Interval,
724: 		})
725: 	}
726: 
727: 	return attributes
728: }
729: 
730: func interfaceAttributes(
731: 	container *clabruntime.GenericContainer,
732: 	snapshot ifaceSnapshot,
733: ) map[string]string {
734: 	attributes := interfaceSnapshotAttributes(snapshot)
735: 	attributes["origin"] = "netlink"
736: 
737: 	if lab := containerLabel(container); lab != "" {
738: 		attributes["lab"] = lab
739: 	}
740: 
741: 	if name := firstContainerName(container); name != "" {
742: 		attributes["name"] = name
743: 	}
744: 
745: 	overlayToolsInterface(container, attributes)
746: 
747: 	// Add netem attributes if present
748: 	if snapshot.HasNetem {
749: 		if snapshot.Delay != "" {

(Showing lines 620-749 of 1301. Use offset=750 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19679cb49001u3rFLBNMkCHwDZ",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679c24a001UDdlfknprGOzR3",
  "callID": "call_d3e38a9e903a495f89bd543d",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/events/netlink.go",
      "limit": 130,
      "offset": 620
    },
    "output": "<path>/source/head/core/events/netlink.go</path>\n<type>file</type>\n<content>\n620: \t\t\tsnapshot.PacketLoss = 0\n621: \t\t\tsnapshot.Rate = 0\n622: \t\t\tsnapshot.Corruption = 0\n623: \t\t}\n624: \n625: \t\tif !snapshot.equal(previous) {\n626: \t\t\tstates[idx] = snapshot\n627: \t\t\tregistry.emitInterfaceEvent(w.container, \"update\", snapshot)\n628: \t\t}\n629: \t}\n630: }\n631: \n632: func firstContainerName(container *clabruntime.GenericContainer) string {\n633: \tif container == nil || len(container.Names) == 0 {\n634: \t\treturn \"\"\n635: \t}\n636: \n637: \treturn container.Names[0]\n638: }\n639: \n640: func containerLabel(container *clabruntime.GenericContainer) string {\n641: \tif container == nil || container.Labels == nil {\n642: \t\treturn \"\"\n643: \t}\n644: \n645: \treturn container.Labels[clabconstants.Containerlab]\n646: }\n647: \n648: // interfaceSnapshotAttributes are the attributes every interface event reports for the\n649: // interface itself.\n650: func interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {\n651: \tattributes := map[string]string{\n652: \t\t\"ifname\": snapshot.Name,\n653: \t\t\"index\":  strconv.Itoa(snapshot.Index),\n654: \t\t\"mtu\":    strconv.Itoa(snapshot.MTU),\n655: \t\t\"state\":  snapshot.OperState,\n656: \t\t\"type\":   snapshot.Type,\n657: \t}\n658: \n659: \tif snapshot.Alias != \"\" {\n660: \t\tattributes[\"alias\"] = snapshot.Alias\n661: \t}\n662: \n663: \tif snapshot.MAC != \"\" {\n664: \t\tattributes[\"mac\"] = snapshot.MAC\n665: \t}\n666: \n667: \treturn attributes\n668: }\n669: \n670: // interfaceStatsAttributes adds the counters and rates of a stats event.\n671: func interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {\n672: \tattributes[\"rx_bytes\"] = strconv.FormatUint(metrics.RxBytes, 10)\n673: \tattributes[\"tx_bytes\"] = strconv.FormatUint(metrics.TxBytes, 10)\n674: \tattributes[\"rx_packets\"] = strconv.FormatUint(metrics.RxPackets, 10)\n675: \tattributes[\"tx_packets\"] = strconv.FormatUint(metrics.TxPackets, 10)\n676: \tattributes[\"rx_bps\"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)\n677: \tattributes[\"tx_bps\"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)\n678: \tattributes[\"rx_pps\"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)\n679: \tattributes[\"tx_pps\"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)\n680: \tattributes[\"interval_seconds\"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)\n681: }\n682: \n683: // labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those\n684: // of the netlink interface events, for the node the runtime runs. Values the runtime could not\n685: // read (no index or MTU without a shell in the node) are left out rather than reported as 0.\n686: func labRuntimeInterfaceAttributes(\n687: \tlab, name string,\n688: \tiface *clablabruntime.InterfaceEventData,\n689: ) map[string]string {\n690: \tattributes := interfaceSnapshotAttributes(ifaceSnapshot{\n691: \t\tIndex:     iface.Index,\n692: \t\tName:      iface.Name,\n693: \t\tAlias:     iface.Alias,\n694: \t\tMTU:       iface.MTU,\n695: \t\tMAC:       iface.MAC,\n696: \t\tOperState: iface.OperState,\n697: \t\tType:      iface.Type,\n698: \t})\n699: \tif iface.Index <= 0 {\n700: \t\tdelete(attributes, \"index\")\n701: \t}\n702: \tif iface.MTU <= 0 {\n703: \t\tdelete(attributes, \"mtu\")\n704: \t}\n705: \n706: \tif lab != \"\" {\n707: \t\tattributes[\"lab\"] = lab\n708: \t}\n709: \tif name != \"\" {\n710: \t\tattributes[\"name\"] = name\n711: \t}\n712: \n713: \tif stats := iface.Stats; stats != nil {\n714: \t\tinterfaceStatsAttributes(attributes, ifaceStatsMetrics{\n715: \t\t\tRxBytes:   stats.RxBytes,\n716: \t\t\tTxBytes:   stats.TxBytes,\n717: \t\t\tRxPackets: stats.RxPackets,\n718: \t\t\tTxPackets: stats.TxPackets,\n719: \t\t\tRxBps:     stats.RxBps,\n720: \t\t\tTxBps:     stats.TxBps,\n721: \t\t\tRxPps:     stats.RxPps,\n722: \t\t\tTxPps:     stats.TxPps,\n723: \t\t\tInterval:  stats.Interval,\n724: \t\t})\n725: \t}\n726: \n727: \treturn attributes\n728: }\n729: \n730: func interfaceAttributes(\n731: \tcontainer *clabruntime.GenericContainer,\n732: \tsnapshot ifaceSnapshot,\n733: ) map[string]string {\n734: \tattributes := interfaceSnapshotAttributes(snapshot)\n735: \tattributes[\"origin\"] = \"netlink\"\n736: \n737: \tif lab := containerLabel(container); lab != \"\" {\n738: \t\tattributes[\"lab\"] = lab\n739: \t}\n740: \n741: \tif name := firstContainerName(container); name != \"\" {\n742: \t\tattributes[\"name\"] = name\n743: \t}\n744: \n745: \toverlayToolsInterface(container, attributes)\n746: \n747: \t// Add netem attributes if present\n748: \tif snapshot.HasNetem {\n749: \t\tif snapshot.Delay != \"\" {\n\n(Showing lines 620-749 of 1301. Use offset=750 to continue.)\n</content>",
    "title": "source/head/core/events/netlink.go",
    "metadata": {
      "preview": "\t\t\tsnapshot.PacketLoss = 0\n\t\t\tsnapshot.Rate = 0\n\t\t\tsnapshot.Corruption = 0\n\t\t}\n\n\t\tif !snapshot.equal(previous) {\n\t\t\tstates[idx] = snapshot\n\t\t\tregistry.emitInterfaceEvent(w.container, \"update\", snapshot)\n\t\t}\n\t}\n}\n\nfunc firstContainerName(container *clabruntime.GenericContainer) string {\n\tif container == nil || len(container.Names) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn container.Names[0]\n}\n",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/events/netlink.go",
        "text": "\t\t\tsnapshot.PacketLoss = 0\n\t\t\tsnapshot.Rate = 0\n\t\t\tsnapshot.Corruption = 0\n\t\t}\n\n\t\tif !snapshot.equal(previous) {\n\t\t\tstates[idx] = snapshot\n\t\t\tregistry.emitInterfaceEvent(w.container, \"update\", snapshot)\n\t\t}\n\t}\n}\n\nfunc firstContainerName(container *clabruntime.GenericContainer) string {\n\tif container == nil || len(container.Names) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn container.Names[0]\n}\n\nfunc containerLabel(container *clabruntime.GenericContainer) string {\n\tif container == nil || container.Labels == nil {\n\t\treturn \"\"\n\t}\n\n\treturn container.Labels[clabconstants.Containerlab]\n}\n\n// interfaceSnapshotAttributes are the attributes every interface event reports for the\n// interface itself.\nfunc interfaceSnapshotAttributes(snapshot ifaceSnapshot) map[string]string {\n\tattributes := map[string]string{\n\t\t\"ifname\": snapshot.Name,\n\t\t\"index\":  strconv.Itoa(snapshot.Index),\n\t\t\"mtu\":    strconv.Itoa(snapshot.MTU),\n\t\t\"state\":  snapshot.OperState,\n\t\t\"type\":   snapshot.Type,\n\t}\n\n\tif snapshot.Alias != \"\" {\n\t\tattributes[\"alias\"] = snapshot.Alias\n\t}\n\n\tif snapshot.MAC != \"\" {\n\t\tattributes[\"mac\"] = snapshot.MAC\n\t}\n\n\treturn attributes\n}\n\n// interfaceStatsAttributes adds the counters and rates of a stats event.\nfunc interfaceStatsAttributes(attributes map[string]string, metrics ifaceStatsMetrics) {\n\tattributes[\"rx_bytes\"] = strconv.FormatUint(metrics.RxBytes, 10)\n\tattributes[\"tx_bytes\"] = strconv.FormatUint(metrics.TxBytes, 10)\n\tattributes[\"rx_packets\"] = strconv.FormatUint(metrics.RxPackets, 10)\n\tattributes[\"tx_packets\"] = strconv.FormatUint(metrics.TxPackets, 10)\n\tattributes[\"rx_bps\"] = strconv.FormatFloat(metrics.RxBps, 'f', -1, 64)\n\tattributes[\"tx_bps\"] = strconv.FormatFloat(metrics.TxBps, 'f', -1, 64)\n\tattributes[\"rx_pps\"] = strconv.FormatFloat(metrics.RxPps, 'f', -1, 64)\n\tattributes[\"tx_pps\"] = strconv.FormatFloat(metrics.TxPps, 'f', -1, 64)\n\tattributes[\"interval_seconds\"] = strconv.FormatFloat(metrics.Interval.Seconds(), 'f', -1, 64)\n}\n\n// labRuntimeInterfaceAttributes are the attributes of a lab runtime's interface event: those\n// of the netlink interface events, for the node the runtime runs. Values the runtime could not\n// read (no index or MTU without a shell in the node) are left out rather than reported as 0.\nfunc labRuntimeInterfaceAttributes(\n\tlab, name string,\n\tiface *clablabruntime.InterfaceEventData,\n) map[string]string {\n\tattributes := interfaceSnapshotAttributes(ifaceSnapshot{\n\t\tIndex:     iface.Index,\n\t\tName:      iface.Name,\n\t\tAlias:     iface.Alias,\n\t\tMTU:       iface.MTU,\n\t\tMAC:       iface.MAC,\n\t\tOperState: iface.OperState,\n\t\tType:      iface.Type,\n\t})\n\tif iface.Index <= 0 {\n\t\tdelete(attributes, \"index\")\n\t}\n\tif iface.MTU <= 0 {\n\t\tdelete(attributes, \"mtu\")\n\t}\n\n\tif lab != \"\" {\n\t\tattributes[\"lab\"] = lab\n\t}\n\tif name != \"\" {\n\t\tattributes[\"name\"] = name\n\t}\n\n\tif stats := iface.Stats; stats != nil {\n\t\tinterfaceStatsAttributes(attributes, ifaceStatsMetrics{\n\t\t\tRxBytes:   stats.RxBytes,\n\t\t\tTxBytes:   stats.TxBytes,\n\t\t\tRxPackets: stats.RxPackets,\n\t\t\tTxPackets: stats.TxPackets,\n\t\t\tRxBps:     stats.RxBps,\n\t\t\tTxBps:     stats.TxBps,\n\t\t\tRxPps:     stats.RxPps,\n\t\t\tTxPps:     stats.TxPps,\n\t\t\tInterval:  stats.Interval,\n\t\t})\n\t}\n\n\treturn attributes\n}\n\nfunc interfaceAttributes(\n\tcontainer *clabruntime.GenericContainer,\n\tsnapshot ifaceSnapshot,\n) map[string]string {\n\tattributes := interfaceSnapshotAttributes(snapshot)\n\tattributes[\"origin\"] = \"netlink\"\n\n\tif lab := containerLabel(container); lab != \"\" {\n\t\tattributes[\"lab\"] = lab\n\t}\n\n\tif name := firstContainerName(container); name != \"\" {\n\t\tattributes[\"name\"] = name\n\t}\n\n\toverlayToolsInterface(container, attributes)\n\n\t// Add netem attributes if present\n\tif snapshot.HasNetem {\n\t\tif snapshot.Delay != \"\" {",
        "lineStart": 620,
        "lineEnd": 749,
        "totalLines": 1301,
        "truncated": true
      }
    },
    "time": {
      "start": 1793525926734,
      "end": 1793525926742
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19679cb58001fXEdofziuvUCfz",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679c24a001UDdlfknprGOzR3",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 73308,
    "input": 318,
    "output": 29,
    "reasoning": 1,
    "cache": {
      "read": 72960,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19679c24a001UDdlfknprGOzR3",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525924426,
    "completed": 1793525926747
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 73308,
    "input": 318,
    "output": 29,
    "reasoning": 1,
    "cache": {
      "read": 72960,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 38
step-start
{
  "type": "step-start",
  "id": "prt_19679ddaa001MT1zRNiLKoOJFh",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679cb650012UAqim43hek3n6"
}
Reasoning
The netlink parity attributes are consistent with what the parity tests check. Now skim docs and robot tests quickly, then finalize. Docs: events.md (skim the c9s container events section — I saw lines 1284-1316 in diff), interfaces.md, runtime.md. Let me skim runtime.md changed section for consistency with implementation (attributes `state`, `status`, `origin`, actor names). And the robot test file.
Parity attributes check out. Final pass: docs consistency and the robot test.
grep · completed

Input

{
  "path": "/source/head/docs",
  "pattern": "state is the container state|origin is the source|status attribute|clab-topo-file|snapshot attribute"
}

Output

Found 5 matches
/source/head/docs/manual/inventory.md:
  Line 304:         "clab-topo-file": "<full path to the srl02.clab.yml file>",

  Line 331:         "clab-topo-file": "<full path to the srl02.clab.yml file>",


/source/head/docs/manual/clabernetes/runtime.md:
  Line 571: for the table, as for Docker), and events as `clab-topo-file`, so a client

  Line 870:     "clab-topo-file": "/home/user/clos.clab.yml",

  Line 889: - `clab-topo-file` is the file the lab was deployed from (see
Tool metadata
{
  "type": "tool",
  "id": "prt_19679e2ee001NvydRfMsaV1aF3",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679cb650012UAqim43hek3n6",
  "callID": "call_8e7df01c91a740719474260e",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/docs",
      "pattern": "state is the container state|origin is the source|status attribute|clab-topo-file|snapshot attribute"
    },
    "output": "Found 5 matches\n/source/head/docs/manual/inventory.md:\n  Line 304:         \"clab-topo-file\": \"<full path to the srl02.clab.yml file>\",\n\n  Line 331:         \"clab-topo-file\": \"<full path to the srl02.clab.yml file>\",\n\n\n/source/head/docs/manual/clabernetes/runtime.md:\n  Line 571: for the table, as for Docker), and events as `clab-topo-file`, so a client\n\n  Line 870:     \"clab-topo-file\": \"/home/user/clos.clab.yml\",\n\n  Line 889: - `clab-topo-file` is the file the lab was deployed from (see\n",
    "title": "state is the container state|origin is the source|status attribute|clab-topo-file|snapshot attribute",
    "metadata": {
      "matches": 5,
      "truncated": false
    },
    "time": {
      "start": 1793525932786,
      "end": 1793525932798
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/tests/14-clabernetes/01-linux-lifecycle.robot"
}

Output

<path>/source/head/tests/14-clabernetes/01-linux-lifecycle.robot</path>
<type>file</type>
<content>
1: *** Settings ***
2: Library             OperatingSystem
3: Library             Process
4: Library             String
5: Library             Collections
6: Resource            ../common.robot
7: 
8: Suite Setup         Setup
9: Suite Teardown      Teardown
10: Test Tags           clabernetes    c9s
11: 
12: 
13: *** Variables ***
14: ${runtime}              c9s
15: ${lab-name}             c9s-linux-lifecycle
16: ${lab-file}             01-linux-lifecycle.clab.yml
17: ${topo}                 ${CURDIR}/${lab-file}
18: ${applied-topo}         ${CURDIR}/01-linux-lifecycle-applied.clab.yml
19: ${lab-namespace}        c9s-${lab-name}
20: ${client-label}         clab-node-name\=client
21: ${events-log}           /tmp/clab-c9s-events.log
22: ${events-err}           /tmp/clab-c9s-events.err
23: ${iface-events-log}     /tmp/clab-c9s-iface-events.log
24: ${iface-events-err}     /tmp/clab-c9s-iface-events.err
25: ${offline-env}          env CLAB_KUBECONFIG\=/nonexistent/kubeconfig KUBECONFIG\=/nonexistent/kubeconfig
26: ${recovery-timeout}     180s
27: ${retry-interval}       5s
28: ${capture-file}         /tmp/clab-c9s-capture.pcapng
29: ${chain-file}           /tmp/clab-c9s-capture-chain.pcapng
30: ${stop-file}            /tmp/clab-c9s-capture-stop.pcapng
31: ${stop-err}             /tmp/clab-c9s-capture-stop.err
32: ${lifecycle-log}        /tmp/clab-c9s-lifecycle-events.log
33: ${lifecycle-err}        /tmp/clab-c9s-lifecycle-events.err
34: ${redeploy-log}         /tmp/clab-c9s-redeploy-events.log
35: ${redeploy-err}         /tmp/clab-c9s-redeploy-events.err
36: ${node-image}           ghcr.io/srl-labs/network-multitool
37: 
38: 
39: *** Test Cases ***
40: Deploy c9s linux lab
41:     ${output} =    Run Clab Command    deploy -t ${topo}
42:     Should Be Equal As Integers    ${output.rc}    0
43: 
44: Deploy creates the Topology resource and controller-compiled primitives
45:     ${topology} =    Process.Run Process
46:     ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} -o name
47:     ...    shell=True
48:     Should Be Equal As Integers    ${topology.rc}    0
49:     Should Contain    ${topology.stdout}    ${lab-name}
50: 
51:     ${nodes} =    Process.Run Process
52:     ...    kubectl -n ${lab-namespace} get nodes.c9s.run -l c9s.run/topologyOwner\=${lab-name} -o name
53:     ...    shell=True
54:     Should Be Equal As Integers    ${nodes.rc}    0
55:     Should Contain    ${nodes.stdout}    node.c9s.run/client
56:     Should Contain    ${nodes.stdout}    node.c9s.run/server
57: 
58:     ${links} =    Process.Run Process
59:     ...    kubectl -n ${lab-namespace} get links.c9s.run -l c9s.run/topologyOwner\=${lab-name} -o name
60:     ...    shell=True
61:     Should Be Equal As Integers    ${links.rc}    0
62:     Should Not Be Empty    ${links.stdout}
63: 
64: Inspect c9s linux lab by topology and name
65:     ${topology_inspect} =    Run Clab Command    inspect -t ${topo}
66:     Should Be Equal As Integers    ${topology_inspect.rc}    0
67:     Should Contain    ${topology_inspect.stdout}    ${lab-name}
68:     Should Contain    ${topology_inspect.stdout}    client
69:     Should Contain    ${topology_inspect.stdout}    server
70: 
71:     ${name_inspect} =    Run Clab Command    inspect --name ${lab-name}
72:     Should Be Equal As Integers    ${name_inspect.rc}    0
73:     Should Contain    ${name_inspect.stdout}    ${lab-name}
74:     Should Contain    ${name_inspect.stdout}    client
75:     Should Contain    ${name_inspect.stdout}    server
76: 
77: Inspect JSON locates the c9s workload of every node
78:     ${output} =    Run Clab Command    inspect -t ${topo} --format json
79:     Should Be Equal As Integers    ${output.rc}    0
80:     ${labs} =    Evaluate    json.loads($output.stdout)    modules=json
81:     ${nodes} =    Get From Dictionary    ${labs}    ${lab-name}
82:     Length Should Be    ${nodes}    2
83:     FOR    ${node}    IN    @{nodes}
84:         ${short} =    Fetch From Right    ${node}[name]    ${lab-name}-
85:         Should Be Equal    ${node}[container_id]    ${lab-namespace}/${lab-name}/${short}
86:         Should Be Equal    ${node}[namespace]    ${lab-namespace}
87: 
88:         ${pod} =    Process.Run Process
89:         ...    kubectl -n ${lab-namespace} get pod ${node}[pod] -o jsonpath\='{.metadata.annotations.kubectl\\.kubernetes\\.io/default-container}'
90:         ...    shell=True
91:         Should Be Equal As Integers    ${pod.rc}    0
92:         Should Be Equal    ${pod.stdout}    ${node}[container]
93: 
94:         ${uid} =    Process.Run Process
95:         ...    kubectl -n ${lab-namespace} get nodes.c9s.run ${short} -o jsonpath\='{.metadata.uid}'
96:         ...    shell=True
97:         Should Be Equal As Integers    ${uid.rc}    0
98:         Should Be Equal    ${uid.stdout}    ${node}[node_uid]
99: 
100:         ${ports} =    Evaluate    [p["port"] for p in $node["exposed_ports"]]
101:         Should Contain    ${ports}    ${22}
102:     END
103: 
104: Inspect all is scoped by the namespace override
105:     ${scoped} =    Run Clab Command    --namespace ${lab-namespace} inspect --all --format json
106:     Should Be Equal As Integers    ${scoped.rc}    0
107:     Should Contain    ${scoped.stdout}    ${lab-name}
108: 
109:     ${other} =    Run Clab Command    --namespace default inspect --all --format json
110:     Should Be Equal As Integers    ${other.rc}    0
111:     Should Not Contain    ${other.stdout}    ${lab-name}
112: 
113: Inspect reports the topology file the lab was deployed from
114:     # the deploy recorded this machine's file on the Topology; inspect without the file reports it
115:     ${annotation} =    Process.Run Process
116:     ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} -o jsonpath\='{.metadata.annotations.containerlab\\.dev/topo-file}'
117:     ...    shell=True
118:     Should Be Equal As Integers    ${annotation.rc}    0
119:     Should Be Equal    ${annotation.stdout}    ${topo}
120: 
121:     ${output} =    Run Clab Command    inspect --all --format json
122:     Should Be Equal As Integers    ${output.rc}    0
123:     ${labs} =    Evaluate    json.loads($output.stdout)    modules=json
124:     FOR    ${node}    IN    @{labs}[${lab-name}]
125:         Should Be Equal    ${node}[absLabPath]    ${topo}
126:         Should Not Start With    ${node}[labPath]    k8s://
127:         Should Be Equal    ${node}[state]    running
128:         Should Be Equal    ${node}[status]    healthy
129:     END
130: 
131:     # manifests are applied by other means; they do not carry this machine's path
132:     ${emit} =    Run Offline Clab Command    deploy -t ${topo} --emit-crs
133:     Should Be Equal As Integers    ${emit.rc}    0
134:     Should Not Contain    ${emit.stdout}    containerlab.dev/topo-file
135: 
136: Events carry the attributes of Docker events
137:     ${events} =    Collect Events    --name ${lab-name} events --format json --initial-state
138:     FOR    ${node}    IN    client    server
139:         Container Event Should Carry Docker Attributes    ${events}    ${node}    running    running
140:         # the interfaces a Docker container of the node has: the lab link, eth0 and lo, named
141:         # as in the topology, the link up
142:         ${ifaces} =    Interface States    ${events}    ${node}
143:         Should Be Equal    ${{sorted($ifaces)}}    ${{["eth0", "eth1", "lo"]}}
144:         Should Be Equal    ${ifaces}[eth1]    up
145:         Should Be Equal    ${ifaces}[eth0]    up
146:         Should Be Equal    ${ifaces}[lo]    unknown
147:     END
148:     Should Not Contain    ${events}    "ifname":"c9s
149: 
150: Validate and emit-crs work without a kubeconfig
151:     ${validate} =    Run Offline Clab Command    validate -t ${topo}
152:     Should Be Equal As Integers    ${validate.rc}    0
153:     Should Contain    ${validate.stderr}    Topology is valid for lab runtime
154: 
155:     ${emit} =    Run Offline Clab Command    deploy -t ${topo} --emit-crs
156:     Should Be Equal As Integers    ${emit.rc}    0
157:     Should Contain    ${emit.stdout}    kind: Topology
158: 
159: Graph renders from the topology file without a cluster
160:     ${mermaid} =    Run Offline Clab Command    graph -t ${topo} --mermaid
161:     Should Be Equal As Integers    ${mermaid.rc}    0
162:     Should Contain    ${mermaid.stderr}    Created mermaid diagram file
163:     File Should Exist    ${CURDIR}/clab-${lab-name}/graph/01-linux-lifecycle.clab.mermaid
164:     ${diagram} =    Get File    ${CURDIR}/clab-${lab-name}/graph/01-linux-lifecycle.clab.mermaid
165:     Should Contain    ${diagram}    client
166:     Should Contain    ${diagram}    server
167: 
168:     ${dot} =    Run Offline Clab Command    graph -t ${topo} --dot
169:     Should Be Equal As Integers    ${dot.rc}    0
170:     File Should Exist    ${CURDIR}/clab-${lab-name}/graph/01-linux-lifecycle.clab.dot
171: 
172:     ${server} =    Run Offline Clab Command    graph -t ${topo}
173:     Should Not Be Equal As Integers    ${server.rc}    0
174:     Should Contain    ${server.stderr}    --offline
175:     [Teardown]    Remove Directory    ${CURDIR}/clab-${lab-name}    recursive=True
176: 
177: Exec into client and verify dataplane
178:     Wait Until Keyword Succeeds    60s    ${retry-interval}    Client Eth1 Should Be Visible
179:     Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Succeed
180: 
181: Inspect interfaces lists the link interfaces with their state
182:     ${output} =    Run Clab Command    inspect interfaces -t ${topo} -f json
183:     Should Be Equal As Integers    ${output.rc}    0
184:     ${containers} =    Evaluate    json.loads($output.stdout)    modules=json
185:     Length Should Be    ${containers}    2
186:     FOR    ${container}    IN    @{containers}
187:         Should Match Regexp    ${container}[name]    ^${lab-name}-(client|server)$
188:         # what a Docker container of the node lists: eth0, the lab link and loopback
189:         ${names} =    Evaluate    [i["name"] for i in $container["interfaces"]]
190:         Should Be Equal    ${names}    ${{["eth0", "eth1", "lo"]}}
191:         ${iface} =    Set Variable    ${container}[interfaces][1]
192:         Should Be Equal    ${iface}[name]    eth1
193:         Should Be Equal    ${iface}[alias]    ${EMPTY}
194:         Should Be Equal    ${iface}[type]    veth
195:         Should Be Equal    ${iface}[state]    up
196:         Should Match Regexp    ${iface}[mac]    ^([0-9a-f]{2}:){5}[0-9a-f]{2}$
197:         Should Be True    ${iface}[ifindex] > 0 and ${iface}[mtu] > 0
198:         ${lo} =    Set Variable    ${container}[interfaces][2]
199:         Should Be Equal    ${lo}[type]    device
200:         Should Be Equal    ${lo}[state]    unknown
201:     END
202: 
203:     ${one} =    Run Clab Command    inspect interfaces --name ${lab-name} -n client -f json
204:     Should Be Equal As Integers    ${one.rc}    0
205:     ${only} =    Evaluate    [c["name"] for c in json.loads($one.stdout)]    modules=json
206:     Should Be Equal    ${only}    ${{["${lab-name}-client"]}}
207: 
208: Capture lists the capturable interfaces with their peers
209:     ${output} =    Run Clab Command    capture -t ${topo} --list -f json
210:     Should Be Equal As Integers    ${output.rc}    0
211:     ${interfaces} =    Evaluate    json.loads($output.stdout)    modules=json
212:     ${want} =    Evaluate
213:     ...    [{"node": "client", "interface": "eth1", "peer_node": "server", "peer_interface": "eth1"}, {"node": "server", "interface": "eth1", "peer_node": "client", "peer_interface": "eth1"}]
214:     Should Be Equal    ${interfaces}    ${want}
215: 
216: Capture both ends of a link into one pcapng stream
217:     Skip If    not shutil.which("tshark")    tshark is not installed
218:     Remove File If Exists    ${capture-file}
219:     Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 10 -i 0.3 10.10.10.2'
220:     ...    shell=True    alias=c9s_ping
221:     ${output} =    Run Clab Command
222:     ...    capture -t ${topo} --target client:eth1 --target server:eth1 --duration 5s -w ${capture-file}
223:     Wait For Process    c9s_ping    timeout=30s
224:     Should Be Equal As Integers    ${output.rc}    0
225: 
226:     ${idbs} =    Process.Run Process    capinfos -T -m -I ${capture-file}    shell=True
227:     Log    ${idbs.stdout}
228:     ${names} =    Process.Run Process
229:     ...    tshark -r ${capture-file} -T fields -e frame.interface_name -Y icmp | sort | uniq -c
230:     ...    shell=True
231:     Log    ${names.stdout}
232:     Should Be Equal As Integers    ${names.rc}    0
233:     ${counts} =    Evaluate
234:     ...    {l.split()[1]: int(l.split()[0]) for l in $names.stdout.splitlines() if l.strip()}
235:     Should Be Equal    ${{sorted($counts)}}    ${{["client:eth1", "server:eth1"]}}
236:     Should Be True    ${counts}[client:eth1] >= 10 and ${counts}[server:eth1] >= 10
237: 
238:     ${info} =    Process.Run Process    capinfos ${capture-file}    shell=True
239:     Log    ${info.stdout}
240:     Should Contain    ${info.stdout}    Number of interfaces in file: 2
241:     Should Contain    ${info.stdout}    Capture application: containerlab
242:     Should Contain    ${info.stdout}    nanoseconds
243: 
244:     # the packets of both nodes are merged in timestamp order
245:     ${times} =    Process.Run Process
246:     ...    tshark -r ${capture-file} -T fields -e frame.time_epoch
247:     ...    shell=True
248:     Should Be Equal As Integers    ${times.rc}    0
249:     ${epochs} =    Evaluate    [decimal.Decimal(x) for x in $times.stdout.split()]    modules=decimal
250:     ${count} =    Get Length    ${epochs}
251:     Should Be True    ${count} >= 20    only ${count} packets
252:     ${inversions} =    Evaluate
253:     ...    [(i, str($epochs[i - 1]), str($epochs[i])) for i in range(1, len($epochs)) if $epochs[i] < $epochs[i - 1]]
254:     Should Be Empty    ${inversions}    frame.time_epoch decreases
255:     [Teardown]    Remove File If Exists    ${capture-file}
256: 
257: Stopping a capture leaves no capture process in clabwire
258:     Skip If    not shutil.which("docker")    docker is needed to list the processes of a KinD worker
259:     Skip If    not shutil.which("capinfos")    capinfos is not installed
260:     Remove File If Exists    ${stop-file}
261:     Start Process    ${CLAB_BIN}    --runtime    ${runtime}    capture    -t    ${topo}
262:     ...    --target    client:eth1    --target    server:eth1    -w    ${stop-file}
263:     ...    alias=c9s_capture    stderr=${stop-err}
264:     Wait Until Keyword Succeeds    60s    1s    Capture Process Should Run In Clabwire    client
265:     Wait Until Keyword Succeeds    10s    1s    Capture Process Should Run In Clabwire    server
266: 
267:     Send Signal To Process    SIGINT    c9s_capture
268:     ${result} =    Wait For Process    c9s_capture    timeout=30s    on_timeout=kill
269:     Log    ${result.stderr}
270:     Should Be Equal As Integers    ${result.rc}    0
271:     # Kubernetes does not stop an exec'd process when its stream closes; clabwire ends the
272:     # capture when containerlab closes its stdin
273:     Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    client
274:     Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    server
275: 
276:     ${info} =    Process.Run Process    capinfos ${stop-file}    shell=True
277:     Should Be Equal As Integers    ${info.rc}    0
278:     Should Contain    ${info.stdout}    Number of interfaces in file: 2
279:     [Teardown]    Run Keywords    Remove File If Exists    ${stop-file}
280:     ...    AND    Remove File If Exists    ${stop-err}
281: 
282: Capture chains segments without duplicates or gaps
283:     Skip If    not shutil.which("tshark")    tshark is not installed
284:     Remove File If Exists    ${chain-file}
285:     Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 130 -i 0.2 10.10.10.2'
286:     ...    shell=True    alias=c9s_ping
287:     Sleep    1s
288:     # a 6 s segment length forces four switches in 20 s
289:     ${output} =    Process.Run Process
290:     ...    ${CLAB_BIN} --runtime ${runtime} --log-level debug capture -t ${topo} --target client:eth1 --duration 20s -w ${chain-file}
291:     ...    shell=True
292:     ...    env:CLAB_C9S_CAPTURE_SEGMENT=6s
293:     Log    ${output.stderr}
294:     Wait For Process    c9s_ping    timeout=60s
295:     Should Be Equal As Integers    ${output.rc}    0
296:     Should Contain    ${output.stderr}    segment=4
297:     Should Not Contain    ${output.stderr}    gap
298: 
299:     ${seqs} =    Process.Run Process
300:     ...    tshark -r ${chain-file} -Y 'icmp.type \=\= 8' -T fields -e icmp.seq
301:     ...    shell=True
302:     Should Be Equal As Integers    ${seqs.rc}    0
303:     ${numbers} =    Evaluate    [int(x) for x in $seqs.stdout.split()]
304:     ${count} =    Get Length    ${numbers}
305:     Should Be True    ${count} >= 90    only ${count} echo requests
306:     ${unique} =    Evaluate    len(set($numbers))
307:     Should Be Equal As Integers    ${unique}    ${count}    duplicate echo requests
308:     ${span} =    Evaluate    max($numbers) - min($numbers) + 1
309:     Should Be Equal As Integers    ${span}    ${count}    missing echo requests
310:     [Teardown]    Remove File If Exists    ${chain-file}
311: 
312: Capture works for a lab editor and is forbidden without a binding
313:     ${rbac} =    Process.Run Process
314:     ...    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
315:     ...    shell=True
316:     Log    ${rbac.stdout}${\n}${rbac.stderr}
317:     Should Be Equal As Integers    ${rbac.rc}    0
318: 
319:     ${result} =    Process.Run Process
320:     ...    go test ./core/ -run TestC9sClusterCapture -count\=1 -v
321:     ...    shell=True
322:     ...    cwd=${CURDIR}/../..
323:     ...    env:CLAB_C9S_TEST_LAB=${lab-name}
324:     ...    env:CLAB_C9S_TEST_CAPTURE_USER=system:serviceaccount:${lab-namespace}:capture-editor
325:     ...    env:CLAB_C9S_TEST_FORBIDDEN_USER=system:serviceaccount:${lab-namespace}:nobody
326:     Log    ${result.stdout}${\n}${result.stderr}    console=${True}
327:     Should Be Equal As Integers    ${result.rc}    0
328:     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/capture_both_ends_of_a_link
329:     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/restart_as_lab_editor
330:     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/forbidden_identity
331:     Should Not Contain    ${result.stdout}    SKIP
332:     Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed
333: 
334: Logs shows the device container log
335:     ${result} =    Run Clab Command    logs -t ${topo} -n client --tail 2 --timestamps
336:     Should Be Equal As Integers    ${result.rc}    0
337:     ${lines} =    Split To Lines    ${result.stdout}
338:     ${count} =    Get Length    ${lines}
339:     Should Be True    0 < ${count} <= 2
340:     Should Match Regexp    ${lines}[0]    ^\\d{4}-\\d{2}-\\d{2}T\\S+\\s
341: 
342:     # the node name is accepted as the topology spells it or as Kubernetes carries it
343:     ${by_name} =    Run Clab Command    logs --name ${lab-name} -n CLIENT --tail 1
344:     Should Be Equal As Integers    ${by_name.rc}    0
345: 
346:     ${missing} =    Run Clab Command    logs --name ${lab-name} -n missing
347:     Should Not Be Equal As Integers    ${missing.rc}    0
348:     Should Contain    ${missing.stderr}    missing
349: 
350: Logs follow streams new device log lines
351:     Remove File If Exists    ${events-log}
352:     TRY
353:         Start Process    ${CLAB_BIN} --runtime ${runtime} logs --name ${lab-name} -n client --tail 0 --follow
354:         ...    shell=True
355:         ...    alias=c9s_logs
356:         ...    stdout=${events-log}
357:         ...    stderr=${events-err}
358:         Sleep    3s
359:         # nginx in the multitool image logs every request
360:         Run Clab Command    exec -t ${topo} --label ${client-label} --cmd 'curl -s -o /dev/null http://127.0.0.1/clab-follow-marker'
361:         Wait Until Keyword Succeeds    30s    1s    Log File Should Contain    ${events-log}    clab-follow-marker
362:     FINALLY
363:         Run Keyword And Ignore Error    Terminate Process    c9s_logs    kill=True
364:         Remove File If Exists    ${events-log}
365:         Remove File If Exists    ${events-err}
366:     END
367: 
368: Library attaches, port-forwards, streams logs and samples stats as an impersonated user
369:     ${rbac} =    Process.Run Process
370:     ...    kubectl -n ${lab-namespace} create role c9s-lab-reader --verb\=get,list,watch --resource\=topologies.c9s.run,nodes.c9s.run,links.c9s.run,nodeprofiles.c9s.run,pods.metrics.k8s.io && kubectl -n ${lab-namespace} create rolebinding clab-alice-reader --role\=c9s-lab-reader --user\=clab:alice && kubectl -n ${lab-namespace} create rolebinding clab-alice-admin --clusterrole\=admin --user\=clab:alice
371:     ...    shell=True
372:     Log    ${rbac.stdout}${\n}${rbac.stderr}
373:     Should Be Equal As Integers    ${rbac.rc}    0
374: 
375:     ${result} =    Process.Run Process
376:     ...    go test ./core/ -run TestC9sClusterNodeAccess -count\=1 -v
377:     ...    shell=True
378:     ...    cwd=${CURDIR}/../..
379:     ...    env:CLAB_C9S_TEST_LAB=${lab-name}
380:     ...    env:CLAB_C9S_TEST_USER=clab:alice
381:     ...    env:CLAB_C9S_TEST_FORBIDDEN_USER=clab:mallory
382:     Log    ${result.stdout}${\n}${result.stderr}    console=${True}
383:     Should Be Equal As Integers    ${result.rc}    0
384:     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/attach_with_a_terminal
385:     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/port-forward
386:     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/stats
387:     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/forbidden_identity
388:     Should Not Contain    ${result.stdout}    SKIP
389: 
390: Stop server and verify dataplane interruption
391:     # the events of the stop and the following start are checked as they happen
392:     Remove File If Exists    ${lifecycle-log}
393:     Start Process    ${CLAB_BIN} --runtime ${runtime} --name ${lab-name} events --format json
394:     ...    shell=True
395:     ...    alias=c9s_lifecycle
396:     ...    stdout=${lifecycle-log}
397:     ...    stderr=${lifecycle-err}
398:     Sleep    5s
399: 
400:     ${output} =    Run Clab Command    stop -t ${topo} --node server
401:     Should Be Equal As Integers    ${output.rc}    0
402: 
403:     # stop is a run state patch on the Node; the controller removes the Pod
404:     ${run_state} =    Node Field    server    {.spec.runState}
405:     Should Be Equal    ${run_state}    Stopped
406:     ${stopped} =    Node Field    server    {.status.conditions[?(@.type=="Stopped")].status}
407:     Should Be Equal    ${stopped}    True
408:     ${pods} =    Process.Run Process
409:     ...    kubectl -n ${lab-namespace} get pods -l c9s.run/topologyNode\=server -o name
410:     ...    shell=True
411:     Should Be Empty    ${pods.stdout}
412:     ${inspect} =    Run Clab Command    inspect -t ${topo} --format json
413:     ${states} =    Evaluate
414:     ...    {n["name"]: (n["state"], n["status"]) for n in json.loads($inspect.stdout)["${lab-name}"]}
415:     ...    modules=json
416:     Should Be Equal    ${states}[${lab-name}-server]    ${{("exited", "Exited")}}
417: 
418:     Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Fail
419: 
420: Stopping a node reports the events Docker reports for containerlab stop
421:     # Docker: kill, stop, die; the node's interfaces go with it, its peer loses carrier
422:     Wait Until Keyword Succeeds    30s    1s
423:     ...    Container Actions Should Include In Order    ${lifecycle-log}    server
424:     ...    kill    stop    die
425:     ${events} =    Get File    ${lifecycle-log}
426:     Container Event Should Carry Docker Attributes    ${events}    server    die    exited
427:     Wait Until Keyword Succeeds    30s    1s
428:     ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    delete
429:     Wait Until Keyword Succeeds    30s    1s
430:     ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update
431:     ...    lower-layer-down    down
432:     ${client} =    Container Actions    ${lifecycle-log}    client
433:     Should Not Contain    ${client}    die
434: 
435: Apply while server is stopped keeps it stopped
436:     ${output} =    Run Clab Command    deploy -t ${applied-topo}
437:     Should Be Equal As Integers    ${output.rc}    0
438:     # the wait settles on the stopped node instead of waiting for it
439:     Should Contain    ${output.stderr}    C9s lab is ready apart from stopped nodes
440:     Should Contain    ${output.stderr}    server (stopped)
441: 
442:     ${run_state} =    Node Field    server    {.spec.runState}
443:     Should Be Equal    ${run_state}    Stopped
444:     ${env} =    Node Field    server    {.spec.env.CLAB_APPLY_MARK}
445:     Should Be Equal    ${env}    applied-while-stopped
446: 
447: Start server by lab name and verify dataplane restore
448:     ${output} =    Run Clab Command    start --name ${lab-name} --node server
449:     Should Be Equal As Integers    ${output.rc}    0
450: 
451:     ${run_state} =    Node Field    server    {.spec.runState}
452:     Should Be Equal    ${run_state}    Running
453:     ${readiness} =    Node Field    server    {.status.readiness}
454:     Should Be Equal    ${readiness}    ready
455: 
456:     # the server boots the definition applied while it was stopped
457:     ${mark} =    Run Clab Command
458:     ...    exec -t ${applied-topo} --label clab-node-name\=server --cmd 'printenv CLAB_APPLY_MARK'
459:     ${mark_output} =    Catenate    SEPARATOR=\n    ${mark.stdout}    ${mark.stderr}
460:     Should Be Equal As Integers    ${mark.rc}    0
461:     Should Contain    ${mark_output}    applied-while-stopped
462: 
463:     Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed
464: 
465: Starting a node reports the events Docker reports for containerlab start
466:     TRY
467:         # Docker: start; the device's readiness as a container health check
468:         Wait Until Keyword Succeeds    60s    1s
469:         ...    Container Actions Should Include In Order    ${lifecycle-log}    server
470:         ...    kill    stop    die    start    health_status: healthy
471:         ${events} =    Get File    ${lifecycle-log}
472:         # the lab was last deployed from the applied file, which the Topology now records
473:         Container Event Should Carry Docker Attributes
474:         ...    ${events}    server    start    running    ${applied-topo}
475:         Container Event Should Carry Docker Attributes
476:         ...    ${events}    server    health_status: healthy    running    ${applied-topo}
477:         Wait Until Keyword Succeeds    60s    1s
478:         ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    create
479:         Wait Until Keyword Succeeds    60s    1s
480:         ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update    up
481:         Validate JSON Lines    ${lifecycle-log}
482:     FINALLY
483:         Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True
484:         Remove File If Exists    ${lifecycle-log}
485:         Remove File If Exists    ${lifecycle-err}
486:     END
487: 
488: Restart server and keep dataplane working
489:     ${before} =    Server Pod Name
490:     ${output} =    Run Clab Command    restart -t ${topo} --node server
491:     Should Be Equal As Integers    ${output.rc}    0
492: 
493:     ${after} =    Server Pod Name
494:     Should Not Be Equal    ${before}    ${after}
495:     ${token} =    Node Field    server    {.metadata.annotations.c9s\\.run/restart-requested}
496:     ${observed} =    Node Field    server    {.status.observedRestartToken}
497:     Should Not Be Empty    ${token}
498:     Should Be Equal    ${token}    ${observed}
499: 
500:     Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed
501: 
502: Events command emits c9s initial state
503:     Remove File If Exists    ${events-log}
504:     Remove File If Exists    ${events-err}
505:     TRY
506:         ${cmd} =    Set Variable    ${CLAB_BIN} --runtime ${runtime} events --format json --initial-state --interface-stats=false
507:         Start Process    ${cmd}
508:         ...    shell=True
509:         ...    alias=c9s_events
510:         ...    stdout=${events-log}
511:         ...    stderr=${events-err}
512:         Sleep    5s
513:         Stop Events Process
514:         ${events} =    Get File    ${events-log}
515:         Log    ${events}
516:         Should Contain    ${events}    "type":"container"
517:         Should Contain    ${events}    ${lab-name}/client
518:         Should Contain    ${events}    ${lab-name}/server
519:         Validate JSON Lines    ${events-log}
520:     FINALLY
521:         Stop Events Process
522:         Remove File If Exists    ${events-log}
523:         Remove File If Exists    ${events-err}
524:     END
525: 
526: Events are scoped to the lab and the namespace
527:     ${lab_events} =    Collect Events    --name ${lab-name} events --format json --initial-state
528:     Should Contain    ${lab_events}    "actor_id":"${lab-namespace}/${lab-name}/client"
529:     Should Contain    ${lab_events}    "type":"interface"
530: 
531:     ${ns_events} =    Collect Events    --namespace ${lab-namespace} events --format json --initial-state
532:     Should Contain    ${ns_events}    "actor_id":"${lab-namespace}/${lab-name}/client"
533: 
534:     ${other_events} =    Collect Events    --namespace default events --format json --initial-state
535:     Should Not Contain    ${other_events}    ${lab-name}
536: 
537: Events report interface up and down
538:     Remove File If Exists    ${iface-events-log}
539:     TRY
540:         Start Process    ${CLAB_BIN} --runtime ${runtime} --name ${lab-name} events --format json
541:         ...    shell=True
542:         ...    alias=c9s_events
543:         ...    stdout=${iface-events-log}
544:         ...    stderr=${iface-events-err}
545:         Sleep    5s
546:         Set Client Eth1    down
547:         Wait Until Keyword Succeeds    30s    1s
548:         ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    down
549:         # the peer loses carrier
550:         Wait Until Keyword Succeeds    30s    1s
551:         ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    update
552:         ...    lower-layer-down    down
553:         Set Client Eth1    up
554:         Wait Until Keyword Succeeds    30s    1s
555:         ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    up
556:         Validate JSON Lines    ${iface-events-log}
557:     FINALLY
558:         Stop Events Process
559:         Set Client Eth1    up
560:         Remove File If Exists    ${iface-events-log}
561:         Remove File If Exists    ${iface-events-err}
562:     END
563: 
564: Destroy without cleanup keeps the persistent claims
565:     # the events of the destroy and the following deploy are checked after the deploy
566:     Remove File If Exists    ${redeploy-log}
567:     Start Process    ${CLAB_BIN} --runtime ${runtime} --namespace ${lab-namespace} events --format json
568:     ...    shell=True
569:     ...    alias=c9s_redeploy
570:     ...    stdout=${redeploy-log}
571:     ...    stderr=${redeploy-err}
572:     Sleep    5s
573: 
574:     ${before} =    Persistent Claim Volumes
575:     Should Not Be Empty    ${before}
576: 
577:     ${output} =    Run Clab Command    destroy -t ${topo}
578:     Should Be Equal As Integers    ${output.rc}    0
579:     Should Contain    ${output.stderr}    Keeping persistent node storage
580: 
581:     ${after} =    Persistent Claim Volumes
582:     Should Be Equal    ${after}    ${before}
583:     Set Suite Variable    ${retained-volumes}    ${before}
584: 
585: Deploy reuses the retained persistent claims
586:     ${output} =    Run Clab Command    deploy -t ${topo}
587:     Should Be Equal As Integers    ${output.rc}    0
588: 
589:     ${volumes} =    Persistent Claim Volumes
590:     Should Be Equal    ${volumes}    ${retained-volumes}
591: 
592: Destroy and deploy report the events Docker reports
593:     TRY
594:         FOR    ${node}    IN    client    server
595:             # Docker: kill, die, destroy; then create, start (and the health check)
596:             Wait Until Keyword Succeeds    60s    1s
597:             ...    Container Actions Should Include In Order    ${redeploy-log}    ${node}
598:             ...    kill    die    destroy    create    start    health_status: healthy
599:             ${events} =    Get File    ${redeploy-log}
600:             # the destroyed lab was last deployed from the applied file, the new one from ${topo}
601:             Container Event Should Carry Docker Attributes
602:             ...    ${events}    ${node}    destroy    exited    ${applied-topo}
603:             Container Event Should Carry Docker Attributes    ${events}    ${node}    create    created
604:             Container Event Should Carry Docker Attributes    ${events}    ${node}    start    running
605:             # like Docker, the link may be created down and come up after
606:             Wait Until Keyword Succeeds    60s    1s
607:             ...    Interface Event Should Be Logged    ${redeploy-log}    ${node}    eth1    create
608:             Wait Until Keyword Succeeds    60s    1s
609:             ...    Last Interface State Should Be    ${redeploy-log}    ${node}    eth1    up
610:         END
611:         Validate JSON Lines    ${redeploy-log}
612:     FINALLY
613:         Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True
614:         Remove File If Exists    ${redeploy-log}
615:         Remove File If Exists    ${redeploy-err}
616:     END
617: 
618: Destroy c9s linux lab
619:     ${output} =    Run Clab Command    destroy -t ${topo} --cleanup
620:     Should Be Equal As Integers    ${output.rc}    0
621: 
622:     ${inspect_all} =    Run Clab Command    inspect --all
623:     Should Not Contain    ${inspect_all.stdout}    ${lab-name}
624: 
625:     ${namespace} =    Process.Run Process
626:     ...    kubectl get namespace ${lab-namespace} --ignore-not-found -o name
627:     ...    shell=True
628:     Should Be Equal As Integers    ${namespace.rc}    0
629:     Should Be Empty    ${namespace.stdout}
630: 
631: Deploy c9s linux lab without a Topology resource
632:     ${output} =    Run Clab Command    deploy -t ${topo} --no-topology-cr
633:     Should Be Equal As Integers    ${output.rc}    0
634: 
635:     ${topology} =    Process.Run Process
636:     ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} --ignore-not-found -o name
637:     ...    shell=True
638:     Should Be Equal As Integers    ${topology.rc}    0
639:     Should Be Empty    ${topology.stdout}
640: 
641:     ${nodes} =    Process.Run Process
642:     ...    kubectl -n ${lab-namespace} get nodes.c9s.run -l c9s.run/topologyOwner\=${lab-name} -o name
643:     ...    shell=True
644:     Should Be Equal As Integers    ${nodes.rc}    0
645:     Should Contain    ${nodes.stdout}    node.c9s.run/client
646:     Should Contain    ${nodes.stdout}    node.c9s.run/server
647: 
648:     # without a Topology the Nodes record the file; inspect without the file reports it
649:     ${annotation} =    Node Field    client    {.metadata.annotations.containerlab\\.dev/topo-file}
650:     Should Be Equal    ${annotation}    ${topo}
651:     ${output} =    Run Clab Command    inspect --name ${lab-name} --format json
652:     ${paths} =    Evaluate    {n["absLabPath"] for n in json.loads($output.stdout)["${lab-name}"]}
653:     ...    modules=json
654:     Should Be Equal    ${paths}    ${{{"${topo}"}}}
655: 
656: Apply without a Topology resource keeps a stopped node stopped
657:     ${output} =    Run Clab Command    stop -t ${topo} --node client
658:     Should Be Equal As Integers    ${output.rc}    0
659: 
660:     ${plan} =    Run Clab Command    deploy -t ${applied-topo} --no-topology-cr --dry-run --format json
661:     Should Be Equal As Integers    ${plan.rc}    0
662:     ${changes} =    Evaluate    [c["kind"] + "/" + c["name"] for c in json.loads($plan.stdout)["changes"]]    modules=json
663:     Should Contain    ${changes}    Node/server
664:     Should Not Contain    ${changes}    Node/client
665: 
666:     ${output} =    Run Clab Command    deploy -t ${applied-topo} --no-topology-cr
667:     Should Be Equal As Integers    ${output.rc}    0
668:     ${run_state} =    Node Field    client    {.spec.runState}
669:     Should Be Equal    ${run_state}    Stopped
670: 
671:     ${output} =    Run Clab Command    start -t ${topo} --node client
672:     Should Be Equal As Integers    ${output.rc}    0
673:     Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed
674: 
675: Destroy c9s linux lab deployed without a Topology resource
676:     ${output} =    Run Clab Command    destroy -t ${topo} --cleanup
677:     Should Be Equal As Integers    ${output.rc}    0
678: 
679:     ${namespace} =    Process.Run Process
680:     ...    kubectl get namespace ${lab-namespace} --ignore-not-found -o name
681:     ...    shell=True
682:     Should Be Equal As Integers    ${namespace.rc}    0
683:     Should Be Empty    ${namespace.stdout}
684: 
685: 
686: *** Keywords ***
687: Setup
688:     Skip If    '${runtime}' != 'c9s'    This suite targets the c9s runtime.
689:     Remove File If Exists    ${events-log}
690:     Remove File If Exists    ${events-err}
691:     ${output} =    Run Clab Command    destroy -t ${topo} --cleanup
692:     Log    Cleanup return code: ${output.rc}
693: 
694: Teardown
695:     Stop Events Process
696:     Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True
697:     Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True
698:     Run Clab Command    destroy -t ${topo} --cleanup
699:     Remove File If Exists    ${events-log}
700:     Remove File If Exists    ${events-err}
701: 
702: Run Clab Command
703:     [Arguments]    ${args}
704:     ${output} =    Process.Run Process
705:     ...    ${CLAB_BIN} --runtime ${runtime} ${args}
706:     ...    shell=True
707:     Log    stdout:${\n}${output.stdout}    console=${True}
708:     Log    stderr:${\n}${output.stderr}    console=${True}
709:     RETURN    ${output}
710: 
711: Clabwire Capture Processes
712:     [Arguments]    ${node}
713:     ${result} =    Process.Run Process
714:     ...    ${CURDIR}/clabwire-captures.sh ${lab-namespace} ${node}
715:     ...    shell=True
716:     Log    ${result.stdout}${\n}${result.stderr}
717:     Should Be Equal As Integers    ${result.rc}    0
718:     ${lines} =    Get Lines Containing String    ${result.stdout}    packet-capture
719:     ${count} =    Get Line Count    ${lines}
720:     RETURN    ${count}
721: 
722: Capture Process Should Run In Clabwire
723:     [Arguments]    ${node}
724:     ${count} =    Clabwire Capture Processes    ${node}
725:     Should Be True    ${count} > 0    no packet-capture process in the clabwire container of ${node}
726: 
727: No Capture Process Should Run In Clabwire
728:     [Arguments]    ${node}
729:     ${count} =    Clabwire Capture Processes    ${node}
730:     Should Be Equal As Integers    ${count}    0
731:     ...    ${count} packet-capture processes still run in the clabwire container of ${node}
732: 
733: Ping From Client Should Succeed
734:     ${output} =    Run Clab Command
735:     ...    exec -t ${topo} --label ${client-label} --cmd 'ping -c 1 -W 2 10.10.10.2'
736:     ${combined} =    Catenate    SEPARATOR=\n    ${output.stdout}    ${output.stderr}
737:     Should Be Equal As Integers    ${output.rc}    0
738:     Should Match Regexp    ${combined}    (?s).*1 (packets )?received, 0% packet loss.*
739: 
740: Ping From Client Should Fail
741:     ${output} =    Run Clab Command
742:     ...    exec -t ${topo} --label ${client-label} --cmd 'ping -c 1 -W 2 10.10.10.2'
743:     ${combined} =    Catenate    SEPARATOR=\n    ${output.stdout}    ${output.stderr}
744:     Should Match Regexp    ${combined}    (?s).*0 (packets )?received, 100% packet loss.*
745: 
746: Client Eth1 Should Be Visible
747:     ${output} =    Run Clab Command
748:     ...    exec -t ${topo} --label ${client-label} --cmd 'ip link show eth1'
749:     ${combined} =    Catenate    SEPARATOR=\n    ${output.stdout}    ${output.stderr}
750:     Should Be Equal As Integers    ${output.rc}    0
751:     Should Contain    ${combined}    eth1
752: 
753: Run Offline Clab Command
754:     [Arguments]    ${args}
755:     ${output} =    Process.Run Process
756:     ...    ${offline-env} ${CLAB_BIN} --runtime ${runtime} ${args}
757:     ...    shell=True
758:     ...    cwd=${CURDIR}
759:     Log    stdout:${\n}${output.stdout}    console=${True}
760:     Log    stderr:${\n}${output.stderr}    console=${True}
761:     RETURN    ${output}
762: 
763: Collect Events
764:     [Arguments]    ${args}
765:     Remove File If Exists    ${events-log}
766:     TRY
767:         Start Process    ${CLAB_BIN} --runtime ${runtime} ${args}
768:         ...    shell=True
769:         ...    alias=c9s_events
770:         ...    stdout=${events-log}
771:         ...    stderr=${events-err}
772:         Sleep    6s
773:     FINALLY
774:         Stop Events Process
775:     END
776:     ${events} =    Get File    ${events-log}
777:     Log    ${events}
778:     Validate JSON Lines    ${events-log}
779:     Remove File If Exists    ${events-log}
780:     Remove File If Exists    ${events-err}
781:     RETURN    ${events}
782: 
783: Set Client Eth1
784:     [Arguments]    ${state}
785:     Run Clab Command    exec -t ${topo} --label ${client-label} --cmd 'ip link set dev eth1 ${state}'
786: 
787: Interface Event Should Be Logged
788:     [Documentation]    An interface event with the action and, when given, one of the states.
789:     [Arguments]    ${path}    ${node}    ${ifname}    ${action}    @{states}
790:     ${contents} =    Get File    ${path}
791:     ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}
792:     ${found} =    Evaluate
793:     ...    any([e.get("action") == $action and e.get("actor_id") == $actor and e.get("attributes", {}).get("ifname") == $ifname and (not $states or e.get("attributes", {}).get("state") in $states) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get("type") == "interface"])
794:     ...    modules=json
795:     Should Be True    ${found}    no interface ${action} event ${states} for ${node}:${ifname}
796: 
797: Last Interface State Should Be
798:     [Arguments]    ${path}    ${node}    ${ifname}    ${state}
799:     ${contents} =    Get File    ${path}
800:     ${states} =    Interface States    ${contents}    ${node}
801:     Should Be Equal    ${states}[${ifname}]    ${state}
802: 
803: Container Actions
804:     [Arguments]    ${path}    ${node}
805:     ${contents} =    Get File    ${path}
806:     ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}
807:     ${actions} =    Evaluate
808:     ...    [e["action"] for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get("type") == "container" and e.get("actor_id") == $actor]
809:     ...    modules=json
810:     RETURN    ${actions}
811: 
812: Container Actions Should Include In Order
813:     [Arguments]    ${path}    ${node}    @{expected}
814:     ${actions} =    Container Actions    ${path}    ${node}
815:     # the expected actions appear in this order, other actions may come between them
816:     ${in_order} =    Evaluate
817:     ...    re.search("\\n" + "\\n(?:.*\\n)*?".join([re.escape(a) for a in $expected]) + "\\n", "\\n" + "\\n".join($actions) + "\\n") is not None
818:     ...    modules=re
819:     Should Be True    ${in_order}    ${node} reported ${actions}, not ${expected} in this order
820: 
821: Container Event Should Carry Docker Attributes
822:     [Documentation]    The last container event of a node with the action carries the attributes
823:     ...    a Docker container event of the node has, and the container state.
824:     [Arguments]    ${events}    ${node}    ${action}    ${state}    ${topo-file}=${topo}
825:     ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}
826:     ${matching} =    Evaluate
827:     ...    [e for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get("type") == "container" and e.get("actor_id") == $actor and e.get("action") == $action]
828:     ...    modules=json
829:     Should Not Be Empty    ${matching}    no container ${action} event for ${node}
830:     ${event} =    Set Variable    ${matching}[-1]
831:     ${attributes} =    Set Variable    ${event}[attributes]
832:     Log    ${attributes}
833:     Should Be Equal    ${attributes}[containerlab]    ${lab-name}
834:     Should Be Equal    ${attributes}[clab-node-name]    ${node}
835:     Should Be Equal    ${attributes}[clab-node-longname]    ${lab-name}-${node}
836:     Should Be Equal    ${attributes}[clab-node-kind]    linux
837:     Should Be Equal    ${attributes}[clab-topo-file]    ${topo-file}
838:     Should Not Be Empty    ${attributes}[clab-owner]
839:     Should Be Equal    ${attributes}[image]    ${node-image}
840:     Should Be Equal    ${attributes}[name]    ${lab-name}-${node}
841:     Should Be Equal    ${attributes}[id]    ${actor}
842:     Should Be Equal    ${event}[actor_full_id]    ${actor}
843:     # a node is created before the controller allocates its management address and Service
844:     IF    $state != "created"
845:         Should Match Regexp    ${attributes}[mgmt_ipv4]    ^\\d+\\.\\d+\\.\\d+\\.\\d+/\\d+$
846:         Should Contain    ${attributes}[ports]    22/tcp
847:     END
848:     Should Be Equal    ${attributes}[state]    ${state}
849: 
850: Interface States
851:     [Documentation]    The interfaces the events report for a node, with their last state.
852:     [Arguments]    ${events}    ${node}
853:     ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}
854:     ${states} =    Evaluate
855:     ...    {e["attributes"]["ifname"]: e["attributes"].get("state", "") for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get("type") == "interface" and e.get("actor_id") == $actor}
856:     ...    modules=json
857:     RETURN    ${states}
858: 
859: Log File Should Contain
860:     [Arguments]    ${path}    ${text}
861:     ${contents} =    Get File    ${path}
862:     Should Contain    ${contents}    ${text}
863: 
864: Persistent Claim Volumes
865:     ${claims} =    Process.Run Process
866:     ...    kubectl -n ${lab-namespace} get pvc -l c9s.run/topologyOwner\=${lab-name} -o jsonpath\='{range .items[*]}{.metadata.name}\={.spec.volumeName}{" "}{end}'
867:     ...    shell=True
868:     Should Be Equal As Integers    ${claims.rc}    0
869:     ${volumes} =    Strip String    ${claims.stdout}
870:     RETURN    ${volumes}
871: 
872: Node Field
873:     [Arguments]    ${node}    ${jsonpath}
874:     ${result} =    Process.Run Process
875:     ...    kubectl -n ${lab-namespace} get nodes.c9s.run ${node} -o jsonpath\='${jsonpath}'
876:     ...    shell=True
877:     Should Be Equal As Integers    ${result.rc}    0    ${result.stderr}
878:     RETURN    ${result.stdout}
879: 
880: Server Pod Name
881:     ${result} =    Process.Run Process
882:     ...    kubectl -n ${lab-namespace} get pods -l c9s.run/topologyNode\=server --field-selector status.phase\=Running -o jsonpath\='{.items[*].metadata.name}'
883:     ...    shell=True
884:     Should Be Equal As Integers    ${result.rc}    0
885:     RETURN    ${result.stdout}
886: 
887: Remove File If Exists
888:     [Arguments]    ${path}
889:     Run Keyword And Ignore Error    Remove File    ${path}
890: 
891: Stop Events Process
892:     Run Keyword And Ignore Error    Terminate Process    c9s_events    kill=True
893:     Run Keyword And Ignore Error    Wait For Process    c9s_events
894: 
895: Validate JSON Lines
896:     [Arguments]    ${path}
897:     ${contents} =    Get File    ${path}
898:     @{lines} =    Split To Lines    ${contents}
899:     FOR    ${line}    IN    @{lines}
900:         ${stripped} =    Strip String    ${line}
901:         IF    $stripped == ''    CONTINUE
902:         Evaluate    json.loads($stripped)    modules=json
903:     END

(End of file - total 903 lines)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_19679e34a001sAforRKPQgTfh4",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679cb650012UAqim43hek3n6",
  "callID": "call_950fd5d869fb4bd38fbaabb8",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/tests/14-clabernetes/01-linux-lifecycle.robot"
    },
    "output": "<path>/source/head/tests/14-clabernetes/01-linux-lifecycle.robot</path>\n<type>file</type>\n<content>\n1: *** Settings ***\n2: Library             OperatingSystem\n3: Library             Process\n4: Library             String\n5: Library             Collections\n6: Resource            ../common.robot\n7: \n8: Suite Setup         Setup\n9: Suite Teardown      Teardown\n10: Test Tags           clabernetes    c9s\n11: \n12: \n13: *** Variables ***\n14: ${runtime}              c9s\n15: ${lab-name}             c9s-linux-lifecycle\n16: ${lab-file}             01-linux-lifecycle.clab.yml\n17: ${topo}                 ${CURDIR}/${lab-file}\n18: ${applied-topo}         ${CURDIR}/01-linux-lifecycle-applied.clab.yml\n19: ${lab-namespace}        c9s-${lab-name}\n20: ${client-label}         clab-node-name\\=client\n21: ${events-log}           /tmp/clab-c9s-events.log\n22: ${events-err}           /tmp/clab-c9s-events.err\n23: ${iface-events-log}     /tmp/clab-c9s-iface-events.log\n24: ${iface-events-err}     /tmp/clab-c9s-iface-events.err\n25: ${offline-env}          env CLAB_KUBECONFIG\\=/nonexistent/kubeconfig KUBECONFIG\\=/nonexistent/kubeconfig\n26: ${recovery-timeout}     180s\n27: ${retry-interval}       5s\n28: ${capture-file}         /tmp/clab-c9s-capture.pcapng\n29: ${chain-file}           /tmp/clab-c9s-capture-chain.pcapng\n30: ${stop-file}            /tmp/clab-c9s-capture-stop.pcapng\n31: ${stop-err}             /tmp/clab-c9s-capture-stop.err\n32: ${lifecycle-log}        /tmp/clab-c9s-lifecycle-events.log\n33: ${lifecycle-err}        /tmp/clab-c9s-lifecycle-events.err\n34: ${redeploy-log}         /tmp/clab-c9s-redeploy-events.log\n35: ${redeploy-err}         /tmp/clab-c9s-redeploy-events.err\n36: ${node-image}           ghcr.io/srl-labs/network-multitool\n37: \n38: \n39: *** Test Cases ***\n40: Deploy c9s linux lab\n41:     ${output} =    Run Clab Command    deploy -t ${topo}\n42:     Should Be Equal As Integers    ${output.rc}    0\n43: \n44: Deploy creates the Topology resource and controller-compiled primitives\n45:     ${topology} =    Process.Run Process\n46:     ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} -o name\n47:     ...    shell=True\n48:     Should Be Equal As Integers    ${topology.rc}    0\n49:     Should Contain    ${topology.stdout}    ${lab-name}\n50: \n51:     ${nodes} =    Process.Run Process\n52:     ...    kubectl -n ${lab-namespace} get nodes.c9s.run -l c9s.run/topologyOwner\\=${lab-name} -o name\n53:     ...    shell=True\n54:     Should Be Equal As Integers    ${nodes.rc}    0\n55:     Should Contain    ${nodes.stdout}    node.c9s.run/client\n56:     Should Contain    ${nodes.stdout}    node.c9s.run/server\n57: \n58:     ${links} =    Process.Run Process\n59:     ...    kubectl -n ${lab-namespace} get links.c9s.run -l c9s.run/topologyOwner\\=${lab-name} -o name\n60:     ...    shell=True\n61:     Should Be Equal As Integers    ${links.rc}    0\n62:     Should Not Be Empty    ${links.stdout}\n63: \n64: Inspect c9s linux lab by topology and name\n65:     ${topology_inspect} =    Run Clab Command    inspect -t ${topo}\n66:     Should Be Equal As Integers    ${topology_inspect.rc}    0\n67:     Should Contain    ${topology_inspect.stdout}    ${lab-name}\n68:     Should Contain    ${topology_inspect.stdout}    client\n69:     Should Contain    ${topology_inspect.stdout}    server\n70: \n71:     ${name_inspect} =    Run Clab Command    inspect --name ${lab-name}\n72:     Should Be Equal As Integers    ${name_inspect.rc}    0\n73:     Should Contain    ${name_inspect.stdout}    ${lab-name}\n74:     Should Contain    ${name_inspect.stdout}    client\n75:     Should Contain    ${name_inspect.stdout}    server\n76: \n77: Inspect JSON locates the c9s workload of every node\n78:     ${output} =    Run Clab Command    inspect -t ${topo} --format json\n79:     Should Be Equal As Integers    ${output.rc}    0\n80:     ${labs} =    Evaluate    json.loads($output.stdout)    modules=json\n81:     ${nodes} =    Get From Dictionary    ${labs}    ${lab-name}\n82:     Length Should Be    ${nodes}    2\n83:     FOR    ${node}    IN    @{nodes}\n84:         ${short} =    Fetch From Right    ${node}[name]    ${lab-name}-\n85:         Should Be Equal    ${node}[container_id]    ${lab-namespace}/${lab-name}/${short}\n86:         Should Be Equal    ${node}[namespace]    ${lab-namespace}\n87: \n88:         ${pod} =    Process.Run Process\n89:         ...    kubectl -n ${lab-namespace} get pod ${node}[pod] -o jsonpath\\='{.metadata.annotations.kubectl\\\\.kubernetes\\\\.io/default-container}'\n90:         ...    shell=True\n91:         Should Be Equal As Integers    ${pod.rc}    0\n92:         Should Be Equal    ${pod.stdout}    ${node}[container]\n93: \n94:         ${uid} =    Process.Run Process\n95:         ...    kubectl -n ${lab-namespace} get nodes.c9s.run ${short} -o jsonpath\\='{.metadata.uid}'\n96:         ...    shell=True\n97:         Should Be Equal As Integers    ${uid.rc}    0\n98:         Should Be Equal    ${uid.stdout}    ${node}[node_uid]\n99: \n100:         ${ports} =    Evaluate    [p[\"port\"] for p in $node[\"exposed_ports\"]]\n101:         Should Contain    ${ports}    ${22}\n102:     END\n103: \n104: Inspect all is scoped by the namespace override\n105:     ${scoped} =    Run Clab Command    --namespace ${lab-namespace} inspect --all --format json\n106:     Should Be Equal As Integers    ${scoped.rc}    0\n107:     Should Contain    ${scoped.stdout}    ${lab-name}\n108: \n109:     ${other} =    Run Clab Command    --namespace default inspect --all --format json\n110:     Should Be Equal As Integers    ${other.rc}    0\n111:     Should Not Contain    ${other.stdout}    ${lab-name}\n112: \n113: Inspect reports the topology file the lab was deployed from\n114:     # the deploy recorded this machine's file on the Topology; inspect without the file reports it\n115:     ${annotation} =    Process.Run Process\n116:     ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} -o jsonpath\\='{.metadata.annotations.containerlab\\\\.dev/topo-file}'\n117:     ...    shell=True\n118:     Should Be Equal As Integers    ${annotation.rc}    0\n119:     Should Be Equal    ${annotation.stdout}    ${topo}\n120: \n121:     ${output} =    Run Clab Command    inspect --all --format json\n122:     Should Be Equal As Integers    ${output.rc}    0\n123:     ${labs} =    Evaluate    json.loads($output.stdout)    modules=json\n124:     FOR    ${node}    IN    @{labs}[${lab-name}]\n125:         Should Be Equal    ${node}[absLabPath]    ${topo}\n126:         Should Not Start With    ${node}[labPath]    k8s://\n127:         Should Be Equal    ${node}[state]    running\n128:         Should Be Equal    ${node}[status]    healthy\n129:     END\n130: \n131:     # manifests are applied by other means; they do not carry this machine's path\n132:     ${emit} =    Run Offline Clab Command    deploy -t ${topo} --emit-crs\n133:     Should Be Equal As Integers    ${emit.rc}    0\n134:     Should Not Contain    ${emit.stdout}    containerlab.dev/topo-file\n135: \n136: Events carry the attributes of Docker events\n137:     ${events} =    Collect Events    --name ${lab-name} events --format json --initial-state\n138:     FOR    ${node}    IN    client    server\n139:         Container Event Should Carry Docker Attributes    ${events}    ${node}    running    running\n140:         # the interfaces a Docker container of the node has: the lab link, eth0 and lo, named\n141:         # as in the topology, the link up\n142:         ${ifaces} =    Interface States    ${events}    ${node}\n143:         Should Be Equal    ${{sorted($ifaces)}}    ${{[\"eth0\", \"eth1\", \"lo\"]}}\n144:         Should Be Equal    ${ifaces}[eth1]    up\n145:         Should Be Equal    ${ifaces}[eth0]    up\n146:         Should Be Equal    ${ifaces}[lo]    unknown\n147:     END\n148:     Should Not Contain    ${events}    \"ifname\":\"c9s\n149: \n150: Validate and emit-crs work without a kubeconfig\n151:     ${validate} =    Run Offline Clab Command    validate -t ${topo}\n152:     Should Be Equal As Integers    ${validate.rc}    0\n153:     Should Contain    ${validate.stderr}    Topology is valid for lab runtime\n154: \n155:     ${emit} =    Run Offline Clab Command    deploy -t ${topo} --emit-crs\n156:     Should Be Equal As Integers    ${emit.rc}    0\n157:     Should Contain    ${emit.stdout}    kind: Topology\n158: \n159: Graph renders from the topology file without a cluster\n160:     ${mermaid} =    Run Offline Clab Command    graph -t ${topo} --mermaid\n161:     Should Be Equal As Integers    ${mermaid.rc}    0\n162:     Should Contain    ${mermaid.stderr}    Created mermaid diagram file\n163:     File Should Exist    ${CURDIR}/clab-${lab-name}/graph/01-linux-lifecycle.clab.mermaid\n164:     ${diagram} =    Get File    ${CURDIR}/clab-${lab-name}/graph/01-linux-lifecycle.clab.mermaid\n165:     Should Contain    ${diagram}    client\n166:     Should Contain    ${diagram}    server\n167: \n168:     ${dot} =    Run Offline Clab Command    graph -t ${topo} --dot\n169:     Should Be Equal As Integers    ${dot.rc}    0\n170:     File Should Exist    ${CURDIR}/clab-${lab-name}/graph/01-linux-lifecycle.clab.dot\n171: \n172:     ${server} =    Run Offline Clab Command    graph -t ${topo}\n173:     Should Not Be Equal As Integers    ${server.rc}    0\n174:     Should Contain    ${server.stderr}    --offline\n175:     [Teardown]    Remove Directory    ${CURDIR}/clab-${lab-name}    recursive=True\n176: \n177: Exec into client and verify dataplane\n178:     Wait Until Keyword Succeeds    60s    ${retry-interval}    Client Eth1 Should Be Visible\n179:     Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Succeed\n180: \n181: Inspect interfaces lists the link interfaces with their state\n182:     ${output} =    Run Clab Command    inspect interfaces -t ${topo} -f json\n183:     Should Be Equal As Integers    ${output.rc}    0\n184:     ${containers} =    Evaluate    json.loads($output.stdout)    modules=json\n185:     Length Should Be    ${containers}    2\n186:     FOR    ${container}    IN    @{containers}\n187:         Should Match Regexp    ${container}[name]    ^${lab-name}-(client|server)$\n188:         # what a Docker container of the node lists: eth0, the lab link and loopback\n189:         ${names} =    Evaluate    [i[\"name\"] for i in $container[\"interfaces\"]]\n190:         Should Be Equal    ${names}    ${{[\"eth0\", \"eth1\", \"lo\"]}}\n191:         ${iface} =    Set Variable    ${container}[interfaces][1]\n192:         Should Be Equal    ${iface}[name]    eth1\n193:         Should Be Equal    ${iface}[alias]    ${EMPTY}\n194:         Should Be Equal    ${iface}[type]    veth\n195:         Should Be Equal    ${iface}[state]    up\n196:         Should Match Regexp    ${iface}[mac]    ^([0-9a-f]{2}:){5}[0-9a-f]{2}$\n197:         Should Be True    ${iface}[ifindex] > 0 and ${iface}[mtu] > 0\n198:         ${lo} =    Set Variable    ${container}[interfaces][2]\n199:         Should Be Equal    ${lo}[type]    device\n200:         Should Be Equal    ${lo}[state]    unknown\n201:     END\n202: \n203:     ${one} =    Run Clab Command    inspect interfaces --name ${lab-name} -n client -f json\n204:     Should Be Equal As Integers    ${one.rc}    0\n205:     ${only} =    Evaluate    [c[\"name\"] for c in json.loads($one.stdout)]    modules=json\n206:     Should Be Equal    ${only}    ${{[\"${lab-name}-client\"]}}\n207: \n208: Capture lists the capturable interfaces with their peers\n209:     ${output} =    Run Clab Command    capture -t ${topo} --list -f json\n210:     Should Be Equal As Integers    ${output.rc}    0\n211:     ${interfaces} =    Evaluate    json.loads($output.stdout)    modules=json\n212:     ${want} =    Evaluate\n213:     ...    [{\"node\": \"client\", \"interface\": \"eth1\", \"peer_node\": \"server\", \"peer_interface\": \"eth1\"}, {\"node\": \"server\", \"interface\": \"eth1\", \"peer_node\": \"client\", \"peer_interface\": \"eth1\"}]\n214:     Should Be Equal    ${interfaces}    ${want}\n215: \n216: Capture both ends of a link into one pcapng stream\n217:     Skip If    not shutil.which(\"tshark\")    tshark is not installed\n218:     Remove File If Exists    ${capture-file}\n219:     Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 10 -i 0.3 10.10.10.2'\n220:     ...    shell=True    alias=c9s_ping\n221:     ${output} =    Run Clab Command\n222:     ...    capture -t ${topo} --target client:eth1 --target server:eth1 --duration 5s -w ${capture-file}\n223:     Wait For Process    c9s_ping    timeout=30s\n224:     Should Be Equal As Integers    ${output.rc}    0\n225: \n226:     ${idbs} =    Process.Run Process    capinfos -T -m -I ${capture-file}    shell=True\n227:     Log    ${idbs.stdout}\n228:     ${names} =    Process.Run Process\n229:     ...    tshark -r ${capture-file} -T fields -e frame.interface_name -Y icmp | sort | uniq -c\n230:     ...    shell=True\n231:     Log    ${names.stdout}\n232:     Should Be Equal As Integers    ${names.rc}    0\n233:     ${counts} =    Evaluate\n234:     ...    {l.split()[1]: int(l.split()[0]) for l in $names.stdout.splitlines() if l.strip()}\n235:     Should Be Equal    ${{sorted($counts)}}    ${{[\"client:eth1\", \"server:eth1\"]}}\n236:     Should Be True    ${counts}[client:eth1] >= 10 and ${counts}[server:eth1] >= 10\n237: \n238:     ${info} =    Process.Run Process    capinfos ${capture-file}    shell=True\n239:     Log    ${info.stdout}\n240:     Should Contain    ${info.stdout}    Number of interfaces in file: 2\n241:     Should Contain    ${info.stdout}    Capture application: containerlab\n242:     Should Contain    ${info.stdout}    nanoseconds\n243: \n244:     # the packets of both nodes are merged in timestamp order\n245:     ${times} =    Process.Run Process\n246:     ...    tshark -r ${capture-file} -T fields -e frame.time_epoch\n247:     ...    shell=True\n248:     Should Be Equal As Integers    ${times.rc}    0\n249:     ${epochs} =    Evaluate    [decimal.Decimal(x) for x in $times.stdout.split()]    modules=decimal\n250:     ${count} =    Get Length    ${epochs}\n251:     Should Be True    ${count} >= 20    only ${count} packets\n252:     ${inversions} =    Evaluate\n253:     ...    [(i, str($epochs[i - 1]), str($epochs[i])) for i in range(1, len($epochs)) if $epochs[i] < $epochs[i - 1]]\n254:     Should Be Empty    ${inversions}    frame.time_epoch decreases\n255:     [Teardown]    Remove File If Exists    ${capture-file}\n256: \n257: Stopping a capture leaves no capture process in clabwire\n258:     Skip If    not shutil.which(\"docker\")    docker is needed to list the processes of a KinD worker\n259:     Skip If    not shutil.which(\"capinfos\")    capinfos is not installed\n260:     Remove File If Exists    ${stop-file}\n261:     Start Process    ${CLAB_BIN}    --runtime    ${runtime}    capture    -t    ${topo}\n262:     ...    --target    client:eth1    --target    server:eth1    -w    ${stop-file}\n263:     ...    alias=c9s_capture    stderr=${stop-err}\n264:     Wait Until Keyword Succeeds    60s    1s    Capture Process Should Run In Clabwire    client\n265:     Wait Until Keyword Succeeds    10s    1s    Capture Process Should Run In Clabwire    server\n266: \n267:     Send Signal To Process    SIGINT    c9s_capture\n268:     ${result} =    Wait For Process    c9s_capture    timeout=30s    on_timeout=kill\n269:     Log    ${result.stderr}\n270:     Should Be Equal As Integers    ${result.rc}    0\n271:     # Kubernetes does not stop an exec'd process when its stream closes; clabwire ends the\n272:     # capture when containerlab closes its stdin\n273:     Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    client\n274:     Wait Until Keyword Succeeds    5s    500ms    No Capture Process Should Run In Clabwire    server\n275: \n276:     ${info} =    Process.Run Process    capinfos ${stop-file}    shell=True\n277:     Should Be Equal As Integers    ${info.rc}    0\n278:     Should Contain    ${info.stdout}    Number of interfaces in file: 2\n279:     [Teardown]    Run Keywords    Remove File If Exists    ${stop-file}\n280:     ...    AND    Remove File If Exists    ${stop-err}\n281: \n282: Capture chains segments without duplicates or gaps\n283:     Skip If    not shutil.which(\"tshark\")    tshark is not installed\n284:     Remove File If Exists    ${chain-file}\n285:     Start Process    ${CLAB_BIN} --runtime ${runtime} exec -t ${topo} --label ${client-label} --cmd 'ping -c 130 -i 0.2 10.10.10.2'\n286:     ...    shell=True    alias=c9s_ping\n287:     Sleep    1s\n288:     # a 6 s segment length forces four switches in 20 s\n289:     ${output} =    Process.Run Process\n290:     ...    ${CLAB_BIN} --runtime ${runtime} --log-level debug capture -t ${topo} --target client:eth1 --duration 20s -w ${chain-file}\n291:     ...    shell=True\n292:     ...    env:CLAB_C9S_CAPTURE_SEGMENT=6s\n293:     Log    ${output.stderr}\n294:     Wait For Process    c9s_ping    timeout=60s\n295:     Should Be Equal As Integers    ${output.rc}    0\n296:     Should Contain    ${output.stderr}    segment=4\n297:     Should Not Contain    ${output.stderr}    gap\n298: \n299:     ${seqs} =    Process.Run Process\n300:     ...    tshark -r ${chain-file} -Y 'icmp.type \\=\\= 8' -T fields -e icmp.seq\n301:     ...    shell=True\n302:     Should Be Equal As Integers    ${seqs.rc}    0\n303:     ${numbers} =    Evaluate    [int(x) for x in $seqs.stdout.split()]\n304:     ${count} =    Get Length    ${numbers}\n305:     Should Be True    ${count} >= 90    only ${count} echo requests\n306:     ${unique} =    Evaluate    len(set($numbers))\n307:     Should Be Equal As Integers    ${unique}    ${count}    duplicate echo requests\n308:     ${span} =    Evaluate    max($numbers) - min($numbers) + 1\n309:     Should Be Equal As Integers    ${span}    ${count}    missing echo requests\n310:     [Teardown]    Remove File If Exists    ${chain-file}\n311: \n312: Capture works for a lab editor and is forbidden without a binding\n313:     ${rbac} =    Process.Run Process\n314:     ...    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\n315:     ...    shell=True\n316:     Log    ${rbac.stdout}${\\n}${rbac.stderr}\n317:     Should Be Equal As Integers    ${rbac.rc}    0\n318: \n319:     ${result} =    Process.Run Process\n320:     ...    go test ./core/ -run TestC9sClusterCapture -count\\=1 -v\n321:     ...    shell=True\n322:     ...    cwd=${CURDIR}/../..\n323:     ...    env:CLAB_C9S_TEST_LAB=${lab-name}\n324:     ...    env:CLAB_C9S_TEST_CAPTURE_USER=system:serviceaccount:${lab-namespace}:capture-editor\n325:     ...    env:CLAB_C9S_TEST_FORBIDDEN_USER=system:serviceaccount:${lab-namespace}:nobody\n326:     Log    ${result.stdout}${\\n}${result.stderr}    console=${True}\n327:     Should Be Equal As Integers    ${result.rc}    0\n328:     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/capture_both_ends_of_a_link\n329:     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/restart_as_lab_editor\n330:     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterCapture/forbidden_identity\n331:     Should Not Contain    ${result.stdout}    SKIP\n332:     Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n333: \n334: Logs shows the device container log\n335:     ${result} =    Run Clab Command    logs -t ${topo} -n client --tail 2 --timestamps\n336:     Should Be Equal As Integers    ${result.rc}    0\n337:     ${lines} =    Split To Lines    ${result.stdout}\n338:     ${count} =    Get Length    ${lines}\n339:     Should Be True    0 < ${count} <= 2\n340:     Should Match Regexp    ${lines}[0]    ^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\S+\\\\s\n341: \n342:     # the node name is accepted as the topology spells it or as Kubernetes carries it\n343:     ${by_name} =    Run Clab Command    logs --name ${lab-name} -n CLIENT --tail 1\n344:     Should Be Equal As Integers    ${by_name.rc}    0\n345: \n346:     ${missing} =    Run Clab Command    logs --name ${lab-name} -n missing\n347:     Should Not Be Equal As Integers    ${missing.rc}    0\n348:     Should Contain    ${missing.stderr}    missing\n349: \n350: Logs follow streams new device log lines\n351:     Remove File If Exists    ${events-log}\n352:     TRY\n353:         Start Process    ${CLAB_BIN} --runtime ${runtime} logs --name ${lab-name} -n client --tail 0 --follow\n354:         ...    shell=True\n355:         ...    alias=c9s_logs\n356:         ...    stdout=${events-log}\n357:         ...    stderr=${events-err}\n358:         Sleep    3s\n359:         # nginx in the multitool image logs every request\n360:         Run Clab Command    exec -t ${topo} --label ${client-label} --cmd 'curl -s -o /dev/null http://127.0.0.1/clab-follow-marker'\n361:         Wait Until Keyword Succeeds    30s    1s    Log File Should Contain    ${events-log}    clab-follow-marker\n362:     FINALLY\n363:         Run Keyword And Ignore Error    Terminate Process    c9s_logs    kill=True\n364:         Remove File If Exists    ${events-log}\n365:         Remove File If Exists    ${events-err}\n366:     END\n367: \n368: Library attaches, port-forwards, streams logs and samples stats as an impersonated user\n369:     ${rbac} =    Process.Run Process\n370:     ...    kubectl -n ${lab-namespace} create role c9s-lab-reader --verb\\=get,list,watch --resource\\=topologies.c9s.run,nodes.c9s.run,links.c9s.run,nodeprofiles.c9s.run,pods.metrics.k8s.io && kubectl -n ${lab-namespace} create rolebinding clab-alice-reader --role\\=c9s-lab-reader --user\\=clab:alice && kubectl -n ${lab-namespace} create rolebinding clab-alice-admin --clusterrole\\=admin --user\\=clab:alice\n371:     ...    shell=True\n372:     Log    ${rbac.stdout}${\\n}${rbac.stderr}\n373:     Should Be Equal As Integers    ${rbac.rc}    0\n374: \n375:     ${result} =    Process.Run Process\n376:     ...    go test ./core/ -run TestC9sClusterNodeAccess -count\\=1 -v\n377:     ...    shell=True\n378:     ...    cwd=${CURDIR}/../..\n379:     ...    env:CLAB_C9S_TEST_LAB=${lab-name}\n380:     ...    env:CLAB_C9S_TEST_USER=clab:alice\n381:     ...    env:CLAB_C9S_TEST_FORBIDDEN_USER=clab:mallory\n382:     Log    ${result.stdout}${\\n}${result.stderr}    console=${True}\n383:     Should Be Equal As Integers    ${result.rc}    0\n384:     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/attach_with_a_terminal\n385:     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/port-forward\n386:     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/stats\n387:     Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/forbidden_identity\n388:     Should Not Contain    ${result.stdout}    SKIP\n389: \n390: Stop server and verify dataplane interruption\n391:     # the events of the stop and the following start are checked as they happen\n392:     Remove File If Exists    ${lifecycle-log}\n393:     Start Process    ${CLAB_BIN} --runtime ${runtime} --name ${lab-name} events --format json\n394:     ...    shell=True\n395:     ...    alias=c9s_lifecycle\n396:     ...    stdout=${lifecycle-log}\n397:     ...    stderr=${lifecycle-err}\n398:     Sleep    5s\n399: \n400:     ${output} =    Run Clab Command    stop -t ${topo} --node server\n401:     Should Be Equal As Integers    ${output.rc}    0\n402: \n403:     # stop is a run state patch on the Node; the controller removes the Pod\n404:     ${run_state} =    Node Field    server    {.spec.runState}\n405:     Should Be Equal    ${run_state}    Stopped\n406:     ${stopped} =    Node Field    server    {.status.conditions[?(@.type==\"Stopped\")].status}\n407:     Should Be Equal    ${stopped}    True\n408:     ${pods} =    Process.Run Process\n409:     ...    kubectl -n ${lab-namespace} get pods -l c9s.run/topologyNode\\=server -o name\n410:     ...    shell=True\n411:     Should Be Empty    ${pods.stdout}\n412:     ${inspect} =    Run Clab Command    inspect -t ${topo} --format json\n413:     ${states} =    Evaluate\n414:     ...    {n[\"name\"]: (n[\"state\"], n[\"status\"]) for n in json.loads($inspect.stdout)[\"${lab-name}\"]}\n415:     ...    modules=json\n416:     Should Be Equal    ${states}[${lab-name}-server]    ${{(\"exited\", \"Exited\")}}\n417: \n418:     Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Fail\n419: \n420: Stopping a node reports the events Docker reports for containerlab stop\n421:     # Docker: kill, stop, die; the node's interfaces go with it, its peer loses carrier\n422:     Wait Until Keyword Succeeds    30s    1s\n423:     ...    Container Actions Should Include In Order    ${lifecycle-log}    server\n424:     ...    kill    stop    die\n425:     ${events} =    Get File    ${lifecycle-log}\n426:     Container Event Should Carry Docker Attributes    ${events}    server    die    exited\n427:     Wait Until Keyword Succeeds    30s    1s\n428:     ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    delete\n429:     Wait Until Keyword Succeeds    30s    1s\n430:     ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update\n431:     ...    lower-layer-down    down\n432:     ${client} =    Container Actions    ${lifecycle-log}    client\n433:     Should Not Contain    ${client}    die\n434: \n435: Apply while server is stopped keeps it stopped\n436:     ${output} =    Run Clab Command    deploy -t ${applied-topo}\n437:     Should Be Equal As Integers    ${output.rc}    0\n438:     # the wait settles on the stopped node instead of waiting for it\n439:     Should Contain    ${output.stderr}    C9s lab is ready apart from stopped nodes\n440:     Should Contain    ${output.stderr}    server (stopped)\n441: \n442:     ${run_state} =    Node Field    server    {.spec.runState}\n443:     Should Be Equal    ${run_state}    Stopped\n444:     ${env} =    Node Field    server    {.spec.env.CLAB_APPLY_MARK}\n445:     Should Be Equal    ${env}    applied-while-stopped\n446: \n447: Start server by lab name and verify dataplane restore\n448:     ${output} =    Run Clab Command    start --name ${lab-name} --node server\n449:     Should Be Equal As Integers    ${output.rc}    0\n450: \n451:     ${run_state} =    Node Field    server    {.spec.runState}\n452:     Should Be Equal    ${run_state}    Running\n453:     ${readiness} =    Node Field    server    {.status.readiness}\n454:     Should Be Equal    ${readiness}    ready\n455: \n456:     # the server boots the definition applied while it was stopped\n457:     ${mark} =    Run Clab Command\n458:     ...    exec -t ${applied-topo} --label clab-node-name\\=server --cmd 'printenv CLAB_APPLY_MARK'\n459:     ${mark_output} =    Catenate    SEPARATOR=\\n    ${mark.stdout}    ${mark.stderr}\n460:     Should Be Equal As Integers    ${mark.rc}    0\n461:     Should Contain    ${mark_output}    applied-while-stopped\n462: \n463:     Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n464: \n465: Starting a node reports the events Docker reports for containerlab start\n466:     TRY\n467:         # Docker: start; the device's readiness as a container health check\n468:         Wait Until Keyword Succeeds    60s    1s\n469:         ...    Container Actions Should Include In Order    ${lifecycle-log}    server\n470:         ...    kill    stop    die    start    health_status: healthy\n471:         ${events} =    Get File    ${lifecycle-log}\n472:         # the lab was last deployed from the applied file, which the Topology now records\n473:         Container Event Should Carry Docker Attributes\n474:         ...    ${events}    server    start    running    ${applied-topo}\n475:         Container Event Should Carry Docker Attributes\n476:         ...    ${events}    server    health_status: healthy    running    ${applied-topo}\n477:         Wait Until Keyword Succeeds    60s    1s\n478:         ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    create\n479:         Wait Until Keyword Succeeds    60s    1s\n480:         ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update    up\n481:         Validate JSON Lines    ${lifecycle-log}\n482:     FINALLY\n483:         Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True\n484:         Remove File If Exists    ${lifecycle-log}\n485:         Remove File If Exists    ${lifecycle-err}\n486:     END\n487: \n488: Restart server and keep dataplane working\n489:     ${before} =    Server Pod Name\n490:     ${output} =    Run Clab Command    restart -t ${topo} --node server\n491:     Should Be Equal As Integers    ${output.rc}    0\n492: \n493:     ${after} =    Server Pod Name\n494:     Should Not Be Equal    ${before}    ${after}\n495:     ${token} =    Node Field    server    {.metadata.annotations.c9s\\\\.run/restart-requested}\n496:     ${observed} =    Node Field    server    {.status.observedRestartToken}\n497:     Should Not Be Empty    ${token}\n498:     Should Be Equal    ${token}    ${observed}\n499: \n500:     Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n501: \n502: Events command emits c9s initial state\n503:     Remove File If Exists    ${events-log}\n504:     Remove File If Exists    ${events-err}\n505:     TRY\n506:         ${cmd} =    Set Variable    ${CLAB_BIN} --runtime ${runtime} events --format json --initial-state --interface-stats=false\n507:         Start Process    ${cmd}\n508:         ...    shell=True\n509:         ...    alias=c9s_events\n510:         ...    stdout=${events-log}\n511:         ...    stderr=${events-err}\n512:         Sleep    5s\n513:         Stop Events Process\n514:         ${events} =    Get File    ${events-log}\n515:         Log    ${events}\n516:         Should Contain    ${events}    \"type\":\"container\"\n517:         Should Contain    ${events}    ${lab-name}/client\n518:         Should Contain    ${events}    ${lab-name}/server\n519:         Validate JSON Lines    ${events-log}\n520:     FINALLY\n521:         Stop Events Process\n522:         Remove File If Exists    ${events-log}\n523:         Remove File If Exists    ${events-err}\n524:     END\n525: \n526: Events are scoped to the lab and the namespace\n527:     ${lab_events} =    Collect Events    --name ${lab-name} events --format json --initial-state\n528:     Should Contain    ${lab_events}    \"actor_id\":\"${lab-namespace}/${lab-name}/client\"\n529:     Should Contain    ${lab_events}    \"type\":\"interface\"\n530: \n531:     ${ns_events} =    Collect Events    --namespace ${lab-namespace} events --format json --initial-state\n532:     Should Contain    ${ns_events}    \"actor_id\":\"${lab-namespace}/${lab-name}/client\"\n533: \n534:     ${other_events} =    Collect Events    --namespace default events --format json --initial-state\n535:     Should Not Contain    ${other_events}    ${lab-name}\n536: \n537: Events report interface up and down\n538:     Remove File If Exists    ${iface-events-log}\n539:     TRY\n540:         Start Process    ${CLAB_BIN} --runtime ${runtime} --name ${lab-name} events --format json\n541:         ...    shell=True\n542:         ...    alias=c9s_events\n543:         ...    stdout=${iface-events-log}\n544:         ...    stderr=${iface-events-err}\n545:         Sleep    5s\n546:         Set Client Eth1    down\n547:         Wait Until Keyword Succeeds    30s    1s\n548:         ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    down\n549:         # the peer loses carrier\n550:         Wait Until Keyword Succeeds    30s    1s\n551:         ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    update\n552:         ...    lower-layer-down    down\n553:         Set Client Eth1    up\n554:         Wait Until Keyword Succeeds    30s    1s\n555:         ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    up\n556:         Validate JSON Lines    ${iface-events-log}\n557:     FINALLY\n558:         Stop Events Process\n559:         Set Client Eth1    up\n560:         Remove File If Exists    ${iface-events-log}\n561:         Remove File If Exists    ${iface-events-err}\n562:     END\n563: \n564: Destroy without cleanup keeps the persistent claims\n565:     # the events of the destroy and the following deploy are checked after the deploy\n566:     Remove File If Exists    ${redeploy-log}\n567:     Start Process    ${CLAB_BIN} --runtime ${runtime} --namespace ${lab-namespace} events --format json\n568:     ...    shell=True\n569:     ...    alias=c9s_redeploy\n570:     ...    stdout=${redeploy-log}\n571:     ...    stderr=${redeploy-err}\n572:     Sleep    5s\n573: \n574:     ${before} =    Persistent Claim Volumes\n575:     Should Not Be Empty    ${before}\n576: \n577:     ${output} =    Run Clab Command    destroy -t ${topo}\n578:     Should Be Equal As Integers    ${output.rc}    0\n579:     Should Contain    ${output.stderr}    Keeping persistent node storage\n580: \n581:     ${after} =    Persistent Claim Volumes\n582:     Should Be Equal    ${after}    ${before}\n583:     Set Suite Variable    ${retained-volumes}    ${before}\n584: \n585: Deploy reuses the retained persistent claims\n586:     ${output} =    Run Clab Command    deploy -t ${topo}\n587:     Should Be Equal As Integers    ${output.rc}    0\n588: \n589:     ${volumes} =    Persistent Claim Volumes\n590:     Should Be Equal    ${volumes}    ${retained-volumes}\n591: \n592: Destroy and deploy report the events Docker reports\n593:     TRY\n594:         FOR    ${node}    IN    client    server\n595:             # Docker: kill, die, destroy; then create, start (and the health check)\n596:             Wait Until Keyword Succeeds    60s    1s\n597:             ...    Container Actions Should Include In Order    ${redeploy-log}    ${node}\n598:             ...    kill    die    destroy    create    start    health_status: healthy\n599:             ${events} =    Get File    ${redeploy-log}\n600:             # the destroyed lab was last deployed from the applied file, the new one from ${topo}\n601:             Container Event Should Carry Docker Attributes\n602:             ...    ${events}    ${node}    destroy    exited    ${applied-topo}\n603:             Container Event Should Carry Docker Attributes    ${events}    ${node}    create    created\n604:             Container Event Should Carry Docker Attributes    ${events}    ${node}    start    running\n605:             # like Docker, the link may be created down and come up after\n606:             Wait Until Keyword Succeeds    60s    1s\n607:             ...    Interface Event Should Be Logged    ${redeploy-log}    ${node}    eth1    create\n608:             Wait Until Keyword Succeeds    60s    1s\n609:             ...    Last Interface State Should Be    ${redeploy-log}    ${node}    eth1    up\n610:         END\n611:         Validate JSON Lines    ${redeploy-log}\n612:     FINALLY\n613:         Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True\n614:         Remove File If Exists    ${redeploy-log}\n615:         Remove File If Exists    ${redeploy-err}\n616:     END\n617: \n618: Destroy c9s linux lab\n619:     ${output} =    Run Clab Command    destroy -t ${topo} --cleanup\n620:     Should Be Equal As Integers    ${output.rc}    0\n621: \n622:     ${inspect_all} =    Run Clab Command    inspect --all\n623:     Should Not Contain    ${inspect_all.stdout}    ${lab-name}\n624: \n625:     ${namespace} =    Process.Run Process\n626:     ...    kubectl get namespace ${lab-namespace} --ignore-not-found -o name\n627:     ...    shell=True\n628:     Should Be Equal As Integers    ${namespace.rc}    0\n629:     Should Be Empty    ${namespace.stdout}\n630: \n631: Deploy c9s linux lab without a Topology resource\n632:     ${output} =    Run Clab Command    deploy -t ${topo} --no-topology-cr\n633:     Should Be Equal As Integers    ${output.rc}    0\n634: \n635:     ${topology} =    Process.Run Process\n636:     ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} --ignore-not-found -o name\n637:     ...    shell=True\n638:     Should Be Equal As Integers    ${topology.rc}    0\n639:     Should Be Empty    ${topology.stdout}\n640: \n641:     ${nodes} =    Process.Run Process\n642:     ...    kubectl -n ${lab-namespace} get nodes.c9s.run -l c9s.run/topologyOwner\\=${lab-name} -o name\n643:     ...    shell=True\n644:     Should Be Equal As Integers    ${nodes.rc}    0\n645:     Should Contain    ${nodes.stdout}    node.c9s.run/client\n646:     Should Contain    ${nodes.stdout}    node.c9s.run/server\n647: \n648:     # without a Topology the Nodes record the file; inspect without the file reports it\n649:     ${annotation} =    Node Field    client    {.metadata.annotations.containerlab\\\\.dev/topo-file}\n650:     Should Be Equal    ${annotation}    ${topo}\n651:     ${output} =    Run Clab Command    inspect --name ${lab-name} --format json\n652:     ${paths} =    Evaluate    {n[\"absLabPath\"] for n in json.loads($output.stdout)[\"${lab-name}\"]}\n653:     ...    modules=json\n654:     Should Be Equal    ${paths}    ${{{\"${topo}\"}}}\n655: \n656: Apply without a Topology resource keeps a stopped node stopped\n657:     ${output} =    Run Clab Command    stop -t ${topo} --node client\n658:     Should Be Equal As Integers    ${output.rc}    0\n659: \n660:     ${plan} =    Run Clab Command    deploy -t ${applied-topo} --no-topology-cr --dry-run --format json\n661:     Should Be Equal As Integers    ${plan.rc}    0\n662:     ${changes} =    Evaluate    [c[\"kind\"] + \"/\" + c[\"name\"] for c in json.loads($plan.stdout)[\"changes\"]]    modules=json\n663:     Should Contain    ${changes}    Node/server\n664:     Should Not Contain    ${changes}    Node/client\n665: \n666:     ${output} =    Run Clab Command    deploy -t ${applied-topo} --no-topology-cr\n667:     Should Be Equal As Integers    ${output.rc}    0\n668:     ${run_state} =    Node Field    client    {.spec.runState}\n669:     Should Be Equal    ${run_state}    Stopped\n670: \n671:     ${output} =    Run Clab Command    start -t ${topo} --node client\n672:     Should Be Equal As Integers    ${output.rc}    0\n673:     Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n674: \n675: Destroy c9s linux lab deployed without a Topology resource\n676:     ${output} =    Run Clab Command    destroy -t ${topo} --cleanup\n677:     Should Be Equal As Integers    ${output.rc}    0\n678: \n679:     ${namespace} =    Process.Run Process\n680:     ...    kubectl get namespace ${lab-namespace} --ignore-not-found -o name\n681:     ...    shell=True\n682:     Should Be Equal As Integers    ${namespace.rc}    0\n683:     Should Be Empty    ${namespace.stdout}\n684: \n685: \n686: *** Keywords ***\n687: Setup\n688:     Skip If    '${runtime}' != 'c9s'    This suite targets the c9s runtime.\n689:     Remove File If Exists    ${events-log}\n690:     Remove File If Exists    ${events-err}\n691:     ${output} =    Run Clab Command    destroy -t ${topo} --cleanup\n692:     Log    Cleanup return code: ${output.rc}\n693: \n694: Teardown\n695:     Stop Events Process\n696:     Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True\n697:     Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True\n698:     Run Clab Command    destroy -t ${topo} --cleanup\n699:     Remove File If Exists    ${events-log}\n700:     Remove File If Exists    ${events-err}\n701: \n702: Run Clab Command\n703:     [Arguments]    ${args}\n704:     ${output} =    Process.Run Process\n705:     ...    ${CLAB_BIN} --runtime ${runtime} ${args}\n706:     ...    shell=True\n707:     Log    stdout:${\\n}${output.stdout}    console=${True}\n708:     Log    stderr:${\\n}${output.stderr}    console=${True}\n709:     RETURN    ${output}\n710: \n711: Clabwire Capture Processes\n712:     [Arguments]    ${node}\n713:     ${result} =    Process.Run Process\n714:     ...    ${CURDIR}/clabwire-captures.sh ${lab-namespace} ${node}\n715:     ...    shell=True\n716:     Log    ${result.stdout}${\\n}${result.stderr}\n717:     Should Be Equal As Integers    ${result.rc}    0\n718:     ${lines} =    Get Lines Containing String    ${result.stdout}    packet-capture\n719:     ${count} =    Get Line Count    ${lines}\n720:     RETURN    ${count}\n721: \n722: Capture Process Should Run In Clabwire\n723:     [Arguments]    ${node}\n724:     ${count} =    Clabwire Capture Processes    ${node}\n725:     Should Be True    ${count} > 0    no packet-capture process in the clabwire container of ${node}\n726: \n727: No Capture Process Should Run In Clabwire\n728:     [Arguments]    ${node}\n729:     ${count} =    Clabwire Capture Processes    ${node}\n730:     Should Be Equal As Integers    ${count}    0\n731:     ...    ${count} packet-capture processes still run in the clabwire container of ${node}\n732: \n733: Ping From Client Should Succeed\n734:     ${output} =    Run Clab Command\n735:     ...    exec -t ${topo} --label ${client-label} --cmd 'ping -c 1 -W 2 10.10.10.2'\n736:     ${combined} =    Catenate    SEPARATOR=\\n    ${output.stdout}    ${output.stderr}\n737:     Should Be Equal As Integers    ${output.rc}    0\n738:     Should Match Regexp    ${combined}    (?s).*1 (packets )?received, 0% packet loss.*\n739: \n740: Ping From Client Should Fail\n741:     ${output} =    Run Clab Command\n742:     ...    exec -t ${topo} --label ${client-label} --cmd 'ping -c 1 -W 2 10.10.10.2'\n743:     ${combined} =    Catenate    SEPARATOR=\\n    ${output.stdout}    ${output.stderr}\n744:     Should Match Regexp    ${combined}    (?s).*0 (packets )?received, 100% packet loss.*\n745: \n746: Client Eth1 Should Be Visible\n747:     ${output} =    Run Clab Command\n748:     ...    exec -t ${topo} --label ${client-label} --cmd 'ip link show eth1'\n749:     ${combined} =    Catenate    SEPARATOR=\\n    ${output.stdout}    ${output.stderr}\n750:     Should Be Equal As Integers    ${output.rc}    0\n751:     Should Contain    ${combined}    eth1\n752: \n753: Run Offline Clab Command\n754:     [Arguments]    ${args}\n755:     ${output} =    Process.Run Process\n756:     ...    ${offline-env} ${CLAB_BIN} --runtime ${runtime} ${args}\n757:     ...    shell=True\n758:     ...    cwd=${CURDIR}\n759:     Log    stdout:${\\n}${output.stdout}    console=${True}\n760:     Log    stderr:${\\n}${output.stderr}    console=${True}\n761:     RETURN    ${output}\n762: \n763: Collect Events\n764:     [Arguments]    ${args}\n765:     Remove File If Exists    ${events-log}\n766:     TRY\n767:         Start Process    ${CLAB_BIN} --runtime ${runtime} ${args}\n768:         ...    shell=True\n769:         ...    alias=c9s_events\n770:         ...    stdout=${events-log}\n771:         ...    stderr=${events-err}\n772:         Sleep    6s\n773:     FINALLY\n774:         Stop Events Process\n775:     END\n776:     ${events} =    Get File    ${events-log}\n777:     Log    ${events}\n778:     Validate JSON Lines    ${events-log}\n779:     Remove File If Exists    ${events-log}\n780:     Remove File If Exists    ${events-err}\n781:     RETURN    ${events}\n782: \n783: Set Client Eth1\n784:     [Arguments]    ${state}\n785:     Run Clab Command    exec -t ${topo} --label ${client-label} --cmd 'ip link set dev eth1 ${state}'\n786: \n787: Interface Event Should Be Logged\n788:     [Documentation]    An interface event with the action and, when given, one of the states.\n789:     [Arguments]    ${path}    ${node}    ${ifname}    ${action}    @{states}\n790:     ${contents} =    Get File    ${path}\n791:     ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n792:     ${found} =    Evaluate\n793:     ...    any([e.get(\"action\") == $action and e.get(\"actor_id\") == $actor and e.get(\"attributes\", {}).get(\"ifname\") == $ifname and (not $states or e.get(\"attributes\", {}).get(\"state\") in $states) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"interface\"])\n794:     ...    modules=json\n795:     Should Be True    ${found}    no interface ${action} event ${states} for ${node}:${ifname}\n796: \n797: Last Interface State Should Be\n798:     [Arguments]    ${path}    ${node}    ${ifname}    ${state}\n799:     ${contents} =    Get File    ${path}\n800:     ${states} =    Interface States    ${contents}    ${node}\n801:     Should Be Equal    ${states}[${ifname}]    ${state}\n802: \n803: Container Actions\n804:     [Arguments]    ${path}    ${node}\n805:     ${contents} =    Get File    ${path}\n806:     ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n807:     ${actions} =    Evaluate\n808:     ...    [e[\"action\"] for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"container\" and e.get(\"actor_id\") == $actor]\n809:     ...    modules=json\n810:     RETURN    ${actions}\n811: \n812: Container Actions Should Include In Order\n813:     [Arguments]    ${path}    ${node}    @{expected}\n814:     ${actions} =    Container Actions    ${path}    ${node}\n815:     # the expected actions appear in this order, other actions may come between them\n816:     ${in_order} =    Evaluate\n817:     ...    re.search(\"\\\\n\" + \"\\\\n(?:.*\\\\n)*?\".join([re.escape(a) for a in $expected]) + \"\\\\n\", \"\\\\n\" + \"\\\\n\".join($actions) + \"\\\\n\") is not None\n818:     ...    modules=re\n819:     Should Be True    ${in_order}    ${node} reported ${actions}, not ${expected} in this order\n820: \n821: Container Event Should Carry Docker Attributes\n822:     [Documentation]    The last container event of a node with the action carries the attributes\n823:     ...    a Docker container event of the node has, and the container state.\n824:     [Arguments]    ${events}    ${node}    ${action}    ${state}    ${topo-file}=${topo}\n825:     ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n826:     ${matching} =    Evaluate\n827:     ...    [e for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get(\"type\") == \"container\" and e.get(\"actor_id\") == $actor and e.get(\"action\") == $action]\n828:     ...    modules=json\n829:     Should Not Be Empty    ${matching}    no container ${action} event for ${node}\n830:     ${event} =    Set Variable    ${matching}[-1]\n831:     ${attributes} =    Set Variable    ${event}[attributes]\n832:     Log    ${attributes}\n833:     Should Be Equal    ${attributes}[containerlab]    ${lab-name}\n834:     Should Be Equal    ${attributes}[clab-node-name]    ${node}\n835:     Should Be Equal    ${attributes}[clab-node-longname]    ${lab-name}-${node}\n836:     Should Be Equal    ${attributes}[clab-node-kind]    linux\n837:     Should Be Equal    ${attributes}[clab-topo-file]    ${topo-file}\n838:     Should Not Be Empty    ${attributes}[clab-owner]\n839:     Should Be Equal    ${attributes}[image]    ${node-image}\n840:     Should Be Equal    ${attributes}[name]    ${lab-name}-${node}\n841:     Should Be Equal    ${attributes}[id]    ${actor}\n842:     Should Be Equal    ${event}[actor_full_id]    ${actor}\n843:     # a node is created before the controller allocates its management address and Service\n844:     IF    $state != \"created\"\n845:         Should Match Regexp    ${attributes}[mgmt_ipv4]    ^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+/\\\\d+$\n846:         Should Contain    ${attributes}[ports]    22/tcp\n847:     END\n848:     Should Be Equal    ${attributes}[state]    ${state}\n849: \n850: Interface States\n851:     [Documentation]    The interfaces the events report for a node, with their last state.\n852:     [Arguments]    ${events}    ${node}\n853:     ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n854:     ${states} =    Evaluate\n855:     ...    {e[\"attributes\"][\"ifname\"]: e[\"attributes\"].get(\"state\", \"\") for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get(\"type\") == \"interface\" and e.get(\"actor_id\") == $actor}\n856:     ...    modules=json\n857:     RETURN    ${states}\n858: \n859: Log File Should Contain\n860:     [Arguments]    ${path}    ${text}\n861:     ${contents} =    Get File    ${path}\n862:     Should Contain    ${contents}    ${text}\n863: \n864: Persistent Claim Volumes\n865:     ${claims} =    Process.Run Process\n866:     ...    kubectl -n ${lab-namespace} get pvc -l c9s.run/topologyOwner\\=${lab-name} -o jsonpath\\='{range .items[*]}{.metadata.name}\\={.spec.volumeName}{\" \"}{end}'\n867:     ...    shell=True\n868:     Should Be Equal As Integers    ${claims.rc}    0\n869:     ${volumes} =    Strip String    ${claims.stdout}\n870:     RETURN    ${volumes}\n871: \n872: Node Field\n873:     [Arguments]    ${node}    ${jsonpath}\n874:     ${result} =    Process.Run Process\n875:     ...    kubectl -n ${lab-namespace} get nodes.c9s.run ${node} -o jsonpath\\='${jsonpath}'\n876:     ...    shell=True\n877:     Should Be Equal As Integers    ${result.rc}    0    ${result.stderr}\n878:     RETURN    ${result.stdout}\n879: \n880: Server Pod Name\n881:     ${result} =    Process.Run Process\n882:     ...    kubectl -n ${lab-namespace} get pods -l c9s.run/topologyNode\\=server --field-selector status.phase\\=Running -o jsonpath\\='{.items[*].metadata.name}'\n883:     ...    shell=True\n884:     Should Be Equal As Integers    ${result.rc}    0\n885:     RETURN    ${result.stdout}\n886: \n887: Remove File If Exists\n888:     [Arguments]    ${path}\n889:     Run Keyword And Ignore Error    Remove File    ${path}\n890: \n891: Stop Events Process\n892:     Run Keyword And Ignore Error    Terminate Process    c9s_events    kill=True\n893:     Run Keyword And Ignore Error    Wait For Process    c9s_events\n894: \n895: Validate JSON Lines\n896:     [Arguments]    ${path}\n897:     ${contents} =    Get File    ${path}\n898:     @{lines} =    Split To Lines    ${contents}\n899:     FOR    ${line}    IN    @{lines}\n900:         ${stripped} =    Strip String    ${line}\n901:         IF    $stripped == ''    CONTINUE\n902:         Evaluate    json.loads($stripped)    modules=json\n903:     END\n\n(End of file - total 903 lines)\n</content>",
    "title": "source/head/tests/14-clabernetes/01-linux-lifecycle.robot",
    "metadata": {
      "preview": "*** Settings ***\nLibrary             OperatingSystem\nLibrary             Process\nLibrary             String\nLibrary             Collections\nResource            ../common.robot\n\nSuite Setup         Setup\nSuite Teardown      Teardown\nTest Tags           clabernetes    c9s\n\n\n*** Variables ***\n${runtime}              c9s\n${lab-name}             c9s-linux-lifecycle\n${lab-file}             01-linux-lifecycle.clab.yml\n${topo}                 ${CURDIR}/${lab-file}\n${applied-topo}         ${CURDIR}/01-linux-lifecycle-applied.clab.yml\n${lab-namespace}        c9s-${lab-name}\n${client-label}         clab-node-name\\=client",
      "truncated": false,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/tests/14-clabernetes/01-linux-lifecycle.robot",
        "text": "*** Settings ***\nLibrary             OperatingSystem\nLibrary             Process\nLibrary             String\nLibrary             Collections\nResource            ../common.robot\n\nSuite Setup         Setup\nSuite Teardown      Teardown\nTest Tags           clabernetes    c9s\n\n\n*** Variables ***\n${runtime}              c9s\n${lab-name}             c9s-linux-lifecycle\n${lab-file}             01-linux-lifecycle.clab.yml\n${topo}                 ${CURDIR}/${lab-file}\n${applied-topo}         ${CURDIR}/01-linux-lifecycle-applied.clab.yml\n${lab-namespace}        c9s-${lab-name}\n${client-label}         clab-node-name\\=client\n${events-log}           /tmp/clab-c9s-events.log\n${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${lifecycle-log}        /tmp/clab-c9s-lifecycle-events.log\n${lifecycle-err}        /tmp/clab-c9s-lifecycle-events.err\n${redeploy-log}         /tmp/clab-c9s-redeploy-events.log\n${redeploy-err}         /tmp/clab-c9s-redeploy-events.err\n${node-image}           ghcr.io/srl-labs/network-multitool\n\n\n*** Test Cases ***\nDeploy c9s linux lab\n    ${output} =    Run Clab Command    deploy -t ${topo}\n    Should Be Equal As Integers    ${output.rc}    0\n\nDeploy creates the Topology resource and controller-compiled primitives\n    ${topology} =    Process.Run Process\n    ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} -o name\n    ...    shell=True\n    Should Be Equal As Integers    ${topology.rc}    0\n    Should Contain    ${topology.stdout}    ${lab-name}\n\n    ${nodes} =    Process.Run Process\n    ...    kubectl -n ${lab-namespace} get nodes.c9s.run -l c9s.run/topologyOwner\\=${lab-name} -o name\n    ...    shell=True\n    Should Be Equal As Integers    ${nodes.rc}    0\n    Should Contain    ${nodes.stdout}    node.c9s.run/client\n    Should Contain    ${nodes.stdout}    node.c9s.run/server\n\n    ${links} =    Process.Run Process\n    ...    kubectl -n ${lab-namespace} get links.c9s.run -l c9s.run/topologyOwner\\=${lab-name} -o name\n    ...    shell=True\n    Should Be Equal As Integers    ${links.rc}    0\n    Should Not Be Empty    ${links.stdout}\n\nInspect c9s linux lab by topology and name\n    ${topology_inspect} =    Run Clab Command    inspect -t ${topo}\n    Should Be Equal As Integers    ${topology_inspect.rc}    0\n    Should Contain    ${topology_inspect.stdout}    ${lab-name}\n    Should Contain    ${topology_inspect.stdout}    client\n    Should Contain    ${topology_inspect.stdout}    server\n\n    ${name_inspect} =    Run Clab Command    inspect --name ${lab-name}\n    Should Be Equal As Integers    ${name_inspect.rc}    0\n    Should Contain    ${name_inspect.stdout}    ${lab-name}\n    Should Contain    ${name_inspect.stdout}    client\n    Should Contain    ${name_inspect.stdout}    server\n\nInspect JSON locates the c9s workload of every node\n    ${output} =    Run Clab Command    inspect -t ${topo} --format json\n    Should Be Equal As Integers    ${output.rc}    0\n    ${labs} =    Evaluate    json.loads($output.stdout)    modules=json\n    ${nodes} =    Get From Dictionary    ${labs}    ${lab-name}\n    Length Should Be    ${nodes}    2\n    FOR    ${node}    IN    @{nodes}\n        ${short} =    Fetch From Right    ${node}[name]    ${lab-name}-\n        Should Be Equal    ${node}[container_id]    ${lab-namespace}/${lab-name}/${short}\n        Should Be Equal    ${node}[namespace]    ${lab-namespace}\n\n        ${pod} =    Process.Run Process\n        ...    kubectl -n ${lab-namespace} get pod ${node}[pod] -o jsonpath\\='{.metadata.annotations.kubectl\\\\.kubernetes\\\\.io/default-container}'\n        ...    shell=True\n        Should Be Equal As Integers    ${pod.rc}    0\n        Should Be Equal    ${pod.stdout}    ${node}[container]\n\n        ${uid} =    Process.Run Process\n        ...    kubectl -n ${lab-namespace} get nodes.c9s.run ${short} -o jsonpath\\='{.metadata.uid}'\n        ...    shell=True\n        Should Be Equal As Integers    ${uid.rc}    0\n        Should Be Equal    ${uid.stdout}    ${node}[node_uid]\n\n        ${ports} =    Evaluate    [p[\"port\"] for p in $node[\"exposed_ports\"]]\n        Should Contain    ${ports}    ${22}\n    END\n\nInspect all is scoped by the namespace override\n    ${scoped} =    Run Clab Command    --namespace ${lab-namespace} inspect --all --format json\n    Should Be Equal As Integers    ${scoped.rc}    0\n    Should Contain    ${scoped.stdout}    ${lab-name}\n\n    ${other} =    Run Clab Command    --namespace default inspect --all --format json\n    Should Be Equal As Integers    ${other.rc}    0\n    Should Not Contain    ${other.stdout}    ${lab-name}\n\nInspect reports the topology file the lab was deployed from\n    # the deploy recorded this machine's file on the Topology; inspect without the file reports it\n    ${annotation} =    Process.Run Process\n    ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} -o jsonpath\\='{.metadata.annotations.containerlab\\\\.dev/topo-file}'\n    ...    shell=True\n    Should Be Equal As Integers    ${annotation.rc}    0\n    Should Be Equal    ${annotation.stdout}    ${topo}\n\n    ${output} =    Run Clab Command    inspect --all --format json\n    Should Be Equal As Integers    ${output.rc}    0\n    ${labs} =    Evaluate    json.loads($output.stdout)    modules=json\n    FOR    ${node}    IN    @{labs}[${lab-name}]\n        Should Be Equal    ${node}[absLabPath]    ${topo}\n        Should Not Start With    ${node}[labPath]    k8s://\n        Should Be Equal    ${node}[state]    running\n        Should Be Equal    ${node}[status]    healthy\n    END\n\n    # manifests are applied by other means; they do not carry this machine's path\n    ${emit} =    Run Offline Clab Command    deploy -t ${topo} --emit-crs\n    Should Be Equal As Integers    ${emit.rc}    0\n    Should Not Contain    ${emit.stdout}    containerlab.dev/topo-file\n\nEvents carry the attributes of Docker events\n    ${events} =    Collect Events    --name ${lab-name} events --format json --initial-state\n    FOR    ${node}    IN    client    server\n        Container Event Should Carry Docker Attributes    ${events}    ${node}    running    running\n        # the interfaces a Docker container of the node has: the lab link, eth0 and lo, named\n        # as in the topology, the link up\n        ${ifaces} =    Interface States    ${events}    ${node}\n        Should Be Equal    ${{sorted($ifaces)}}    ${{[\"eth0\", \"eth1\", \"lo\"]}}\n        Should Be Equal    ${ifaces}[eth1]    up\n        Should Be Equal    ${ifaces}[eth0]    up\n        Should Be Equal    ${ifaces}[lo]    unknown\n    END\n    Should Not Contain    ${events}    \"ifname\":\"c9s\n\nValidate and emit-crs work without a kubeconfig\n    ${validate} =    Run Offline Clab Command    validate -t ${topo}\n    Should Be Equal As Integers    ${validate.rc}    0\n    Should Contain    ${validate.stderr}    Topology is valid for lab runtime\n\n    ${emit} =    Run Offline Clab Command    deploy -t ${topo} --emit-crs\n    Should Be Equal As Integers    ${emit.rc}    0\n    Should Contain    ${emit.stdout}    kind: Topology\n\nGraph renders from the topology file without a cluster\n    ${mermaid} =    Run Offline Clab Command    graph -t ${topo} --mermaid\n    Should Be Equal As Integers    ${mermaid.rc}    0\n    Should Contain    ${mermaid.stderr}    Created mermaid diagram file\n    File Should Exist    ${CURDIR}/clab-${lab-name}/graph/01-linux-lifecycle.clab.mermaid\n    ${diagram} =    Get File    ${CURDIR}/clab-${lab-name}/graph/01-linux-lifecycle.clab.mermaid\n    Should Contain    ${diagram}    client\n    Should Contain    ${diagram}    server\n\n    ${dot} =    Run Offline Clab Command    graph -t ${topo} --dot\n    Should Be Equal As Integers    ${dot.rc}    0\n    File Should Exist    ${CURDIR}/clab-${lab-name}/graph/01-linux-lifecycle.clab.dot\n\n    ${server} =    Run Offline Clab Command    graph -t ${topo}\n    Should Not Be Equal As Integers    ${server.rc}    0\n    Should Contain    ${server.stderr}    --offline\n    [Teardown]    Remove Directory    ${CURDIR}/clab-${lab-name}    recursive=True\n\nExec 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\nInspect 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        # what a Docker container of the node lists: eth0, the lab link and loopback\n        ${names} =    Evaluate    [i[\"name\"] for i in $container[\"interfaces\"]]\n        Should Be Equal    ${names}    ${{[\"eth0\", \"eth1\", \"lo\"]}}\n        ${iface} =    Set Variable    ${container}[interfaces][1]\n        Should Be Equal    ${iface}[name]    eth1\n        Should Be Equal    ${iface}[alias]    ${EMPTY}\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        ${lo} =    Set Variable    ${container}[interfaces][2]\n        Should Be Equal    ${lo}[type]    device\n        Should Be Equal    ${lo}[state]    unknown\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\nCapture 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\nCapture 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\nStopping 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\nCapture 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\nCapture 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\nLogs 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    Should Be True    0 < ${count} <= 2\n    Should Match Regexp    ${lines}[0]    ^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\S+\\\\s\n\n    # the node name is accepted as the topology spells it or as Kubernetes carries it\n    ${by_name} =    Run Clab Command    logs --name ${lab-name} -n CLIENT --tail 1\n    Should Be Equal As Integers    ${by_name.rc}    0\n\n    ${missing} =    Run Clab Command    logs --name ${lab-name} -n missing\n    Should Not Be Equal As Integers    ${missing.rc}    0\n    Should Contain    ${missing.stderr}    missing\n\nLogs follow streams new device log lines\n    Remove File If Exists    ${events-log}\n    TRY\n        Start Process    ${CLAB_BIN} --runtime ${runtime} logs --name ${lab-name} -n client --tail 0 --follow\n        ...    shell=True\n        ...    alias=c9s_logs\n        ...    stdout=${events-log}\n        ...    stderr=${events-err}\n        Sleep    3s\n        # nginx in the multitool image logs every request\n        Run Clab Command    exec -t ${topo} --label ${client-label} --cmd 'curl -s -o /dev/null http://127.0.0.1/clab-follow-marker'\n        Wait Until Keyword Succeeds    30s    1s    Log File Should Contain    ${events-log}    clab-follow-marker\n    FINALLY\n        Run Keyword And Ignore Error    Terminate Process    c9s_logs    kill=True\n        Remove File If Exists    ${events-log}\n        Remove File If Exists    ${events-err}\n    END\n\nLibrary attaches, port-forwards, streams logs and samples stats as an impersonated user\n    ${rbac} =    Process.Run Process\n    ...    kubectl -n ${lab-namespace} create role c9s-lab-reader --verb\\=get,list,watch --resource\\=topologies.c9s.run,nodes.c9s.run,links.c9s.run,nodeprofiles.c9s.run,pods.metrics.k8s.io && kubectl -n ${lab-namespace} create rolebinding clab-alice-reader --role\\=c9s-lab-reader --user\\=clab:alice && kubectl -n ${lab-namespace} create rolebinding clab-alice-admin --clusterrole\\=admin --user\\=clab:alice\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 TestC9sClusterNodeAccess -count\\=1 -v\n    ...    shell=True\n    ...    cwd=${CURDIR}/../..\n    ...    env:CLAB_C9S_TEST_LAB=${lab-name}\n    ...    env:CLAB_C9S_TEST_USER=clab:alice\n    ...    env:CLAB_C9S_TEST_FORBIDDEN_USER=clab:mallory\n    Log    ${result.stdout}${\\n}${result.stderr}    console=${True}\n    Should Be Equal As Integers    ${result.rc}    0\n    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/attach_with_a_terminal\n    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/port-forward\n    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/stats\n    Should Contain    ${result.stdout}    --- PASS: TestC9sClusterNodeAccess/forbidden_identity\n    Should Not Contain    ${result.stdout}    SKIP\n\nStop server and verify dataplane interruption\n    # the events of the stop and the following start are checked as they happen\n    Remove File If Exists    ${lifecycle-log}\n    Start Process    ${CLAB_BIN} --runtime ${runtime} --name ${lab-name} events --format json\n    ...    shell=True\n    ...    alias=c9s_lifecycle\n    ...    stdout=${lifecycle-log}\n    ...    stderr=${lifecycle-err}\n    Sleep    5s\n\n    ${output} =    Run Clab Command    stop -t ${topo} --node server\n    Should Be Equal As Integers    ${output.rc}    0\n\n    # stop is a run state patch on the Node; the controller removes the Pod\n    ${run_state} =    Node Field    server    {.spec.runState}\n    Should Be Equal    ${run_state}    Stopped\n    ${stopped} =    Node Field    server    {.status.conditions[?(@.type==\"Stopped\")].status}\n    Should Be Equal    ${stopped}    True\n    ${pods} =    Process.Run Process\n    ...    kubectl -n ${lab-namespace} get pods -l c9s.run/topologyNode\\=server -o name\n    ...    shell=True\n    Should Be Empty    ${pods.stdout}\n    ${inspect} =    Run Clab Command    inspect -t ${topo} --format json\n    ${states} =    Evaluate\n    ...    {n[\"name\"]: (n[\"state\"], n[\"status\"]) for n in json.loads($inspect.stdout)[\"${lab-name}\"]}\n    ...    modules=json\n    Should Be Equal    ${states}[${lab-name}-server]    ${{(\"exited\", \"Exited\")}}\n\n    Wait Until Keyword Succeeds    60s    ${retry-interval}    Ping From Client Should Fail\n\nStopping a node reports the events Docker reports for containerlab stop\n    # Docker: kill, stop, die; the node's interfaces go with it, its peer loses carrier\n    Wait Until Keyword Succeeds    30s    1s\n    ...    Container Actions Should Include In Order    ${lifecycle-log}    server\n    ...    kill    stop    die\n    ${events} =    Get File    ${lifecycle-log}\n    Container Event Should Carry Docker Attributes    ${events}    server    die    exited\n    Wait Until Keyword Succeeds    30s    1s\n    ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    delete\n    Wait Until Keyword Succeeds    30s    1s\n    ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update\n    ...    lower-layer-down    down\n    ${client} =    Container Actions    ${lifecycle-log}    client\n    Should Not Contain    ${client}    die\n\nApply while server is stopped keeps it stopped\n    ${output} =    Run Clab Command    deploy -t ${applied-topo}\n    Should Be Equal As Integers    ${output.rc}    0\n    # the wait settles on the stopped node instead of waiting for it\n    Should Contain    ${output.stderr}    C9s lab is ready apart from stopped nodes\n    Should Contain    ${output.stderr}    server (stopped)\n\n    ${run_state} =    Node Field    server    {.spec.runState}\n    Should Be Equal    ${run_state}    Stopped\n    ${env} =    Node Field    server    {.spec.env.CLAB_APPLY_MARK}\n    Should Be Equal    ${env}    applied-while-stopped\n\nStart server by lab name and verify dataplane restore\n    ${output} =    Run Clab Command    start --name ${lab-name} --node server\n    Should Be Equal As Integers    ${output.rc}    0\n\n    ${run_state} =    Node Field    server    {.spec.runState}\n    Should Be Equal    ${run_state}    Running\n    ${readiness} =    Node Field    server    {.status.readiness}\n    Should Be Equal    ${readiness}    ready\n\n    # the server boots the definition applied while it was stopped\n    ${mark} =    Run Clab Command\n    ...    exec -t ${applied-topo} --label clab-node-name\\=server --cmd 'printenv CLAB_APPLY_MARK'\n    ${mark_output} =    Catenate    SEPARATOR=\\n    ${mark.stdout}    ${mark.stderr}\n    Should Be Equal As Integers    ${mark.rc}    0\n    Should Contain    ${mark_output}    applied-while-stopped\n\n    Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n\nStarting a node reports the events Docker reports for containerlab start\n    TRY\n        # Docker: start; the device's readiness as a container health check\n        Wait Until Keyword Succeeds    60s    1s\n        ...    Container Actions Should Include In Order    ${lifecycle-log}    server\n        ...    kill    stop    die    start    health_status: healthy\n        ${events} =    Get File    ${lifecycle-log}\n        # the lab was last deployed from the applied file, which the Topology now records\n        Container Event Should Carry Docker Attributes\n        ...    ${events}    server    start    running    ${applied-topo}\n        Container Event Should Carry Docker Attributes\n        ...    ${events}    server    health_status: healthy    running    ${applied-topo}\n        Wait Until Keyword Succeeds    60s    1s\n        ...    Interface Event Should Be Logged    ${lifecycle-log}    server    eth1    create\n        Wait Until Keyword Succeeds    60s    1s\n        ...    Interface Event Should Be Logged    ${lifecycle-log}    client    eth1    update    up\n        Validate JSON Lines    ${lifecycle-log}\n    FINALLY\n        Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True\n        Remove File If Exists    ${lifecycle-log}\n        Remove File If Exists    ${lifecycle-err}\n    END\n\nRestart server and keep dataplane working\n    ${before} =    Server Pod Name\n    ${output} =    Run Clab Command    restart -t ${topo} --node server\n    Should Be Equal As Integers    ${output.rc}    0\n\n    ${after} =    Server Pod Name\n    Should Not Be Equal    ${before}    ${after}\n    ${token} =    Node Field    server    {.metadata.annotations.c9s\\\\.run/restart-requested}\n    ${observed} =    Node Field    server    {.status.observedRestartToken}\n    Should Not Be Empty    ${token}\n    Should Be Equal    ${token}    ${observed}\n\n    Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n\nEvents command emits c9s initial state\n    Remove File If Exists    ${events-log}\n    Remove File If Exists    ${events-err}\n    TRY\n        ${cmd} =    Set Variable    ${CLAB_BIN} --runtime ${runtime} events --format json --initial-state --interface-stats=false\n        Start Process    ${cmd}\n        ...    shell=True\n        ...    alias=c9s_events\n        ...    stdout=${events-log}\n        ...    stderr=${events-err}\n        Sleep    5s\n        Stop Events Process\n        ${events} =    Get File    ${events-log}\n        Log    ${events}\n        Should Contain    ${events}    \"type\":\"container\"\n        Should Contain    ${events}    ${lab-name}/client\n        Should Contain    ${events}    ${lab-name}/server\n        Validate JSON Lines    ${events-log}\n    FINALLY\n        Stop Events Process\n        Remove File If Exists    ${events-log}\n        Remove File If Exists    ${events-err}\n    END\n\nEvents are scoped to the lab and the namespace\n    ${lab_events} =    Collect Events    --name ${lab-name} events --format json --initial-state\n    Should Contain    ${lab_events}    \"actor_id\":\"${lab-namespace}/${lab-name}/client\"\n    Should Contain    ${lab_events}    \"type\":\"interface\"\n\n    ${ns_events} =    Collect Events    --namespace ${lab-namespace} events --format json --initial-state\n    Should Contain    ${ns_events}    \"actor_id\":\"${lab-namespace}/${lab-name}/client\"\n\n    ${other_events} =    Collect Events    --namespace default events --format json --initial-state\n    Should Not Contain    ${other_events}    ${lab-name}\n\nEvents report interface up and down\n    Remove File If Exists    ${iface-events-log}\n    TRY\n        Start Process    ${CLAB_BIN} --runtime ${runtime} --name ${lab-name} events --format json\n        ...    shell=True\n        ...    alias=c9s_events\n        ...    stdout=${iface-events-log}\n        ...    stderr=${iface-events-err}\n        Sleep    5s\n        Set Client Eth1    down\n        Wait Until Keyword Succeeds    30s    1s\n        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    down\n        # the peer loses carrier\n        Wait Until Keyword Succeeds    30s    1s\n        ...    Interface Event Should Be Logged    ${iface-events-log}    server    eth1    update\n        ...    lower-layer-down    down\n        Set Client Eth1    up\n        Wait Until Keyword Succeeds    30s    1s\n        ...    Interface Event Should Be Logged    ${iface-events-log}    client    eth1    update    up\n        Validate JSON Lines    ${iface-events-log}\n    FINALLY\n        Stop Events Process\n        Set Client Eth1    up\n        Remove File If Exists    ${iface-events-log}\n        Remove File If Exists    ${iface-events-err}\n    END\n\nDestroy without cleanup keeps the persistent claims\n    # the events of the destroy and the following deploy are checked after the deploy\n    Remove File If Exists    ${redeploy-log}\n    Start Process    ${CLAB_BIN} --runtime ${runtime} --namespace ${lab-namespace} events --format json\n    ...    shell=True\n    ...    alias=c9s_redeploy\n    ...    stdout=${redeploy-log}\n    ...    stderr=${redeploy-err}\n    Sleep    5s\n\n    ${before} =    Persistent Claim Volumes\n    Should Not Be Empty    ${before}\n\n    ${output} =    Run Clab Command    destroy -t ${topo}\n    Should Be Equal As Integers    ${output.rc}    0\n    Should Contain    ${output.stderr}    Keeping persistent node storage\n\n    ${after} =    Persistent Claim Volumes\n    Should Be Equal    ${after}    ${before}\n    Set Suite Variable    ${retained-volumes}    ${before}\n\nDeploy reuses the retained persistent claims\n    ${output} =    Run Clab Command    deploy -t ${topo}\n    Should Be Equal As Integers    ${output.rc}    0\n\n    ${volumes} =    Persistent Claim Volumes\n    Should Be Equal    ${volumes}    ${retained-volumes}\n\nDestroy and deploy report the events Docker reports\n    TRY\n        FOR    ${node}    IN    client    server\n            # Docker: kill, die, destroy; then create, start (and the health check)\n            Wait Until Keyword Succeeds    60s    1s\n            ...    Container Actions Should Include In Order    ${redeploy-log}    ${node}\n            ...    kill    die    destroy    create    start    health_status: healthy\n            ${events} =    Get File    ${redeploy-log}\n            # the destroyed lab was last deployed from the applied file, the new one from ${topo}\n            Container Event Should Carry Docker Attributes\n            ...    ${events}    ${node}    destroy    exited    ${applied-topo}\n            Container Event Should Carry Docker Attributes    ${events}    ${node}    create    created\n            Container Event Should Carry Docker Attributes    ${events}    ${node}    start    running\n            # like Docker, the link may be created down and come up after\n            Wait Until Keyword Succeeds    60s    1s\n            ...    Interface Event Should Be Logged    ${redeploy-log}    ${node}    eth1    create\n            Wait Until Keyword Succeeds    60s    1s\n            ...    Last Interface State Should Be    ${redeploy-log}    ${node}    eth1    up\n        END\n        Validate JSON Lines    ${redeploy-log}\n    FINALLY\n        Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True\n        Remove File If Exists    ${redeploy-log}\n        Remove File If Exists    ${redeploy-err}\n    END\n\nDestroy c9s linux lab\n    ${output} =    Run Clab Command    destroy -t ${topo} --cleanup\n    Should Be Equal As Integers    ${output.rc}    0\n\n    ${inspect_all} =    Run Clab Command    inspect --all\n    Should Not Contain    ${inspect_all.stdout}    ${lab-name}\n\n    ${namespace} =    Process.Run Process\n    ...    kubectl get namespace ${lab-namespace} --ignore-not-found -o name\n    ...    shell=True\n    Should Be Equal As Integers    ${namespace.rc}    0\n    Should Be Empty    ${namespace.stdout}\n\nDeploy c9s linux lab without a Topology resource\n    ${output} =    Run Clab Command    deploy -t ${topo} --no-topology-cr\n    Should Be Equal As Integers    ${output.rc}    0\n\n    ${topology} =    Process.Run Process\n    ...    kubectl -n ${lab-namespace} get topology.c9s.run ${lab-name} --ignore-not-found -o name\n    ...    shell=True\n    Should Be Equal As Integers    ${topology.rc}    0\n    Should Be Empty    ${topology.stdout}\n\n    ${nodes} =    Process.Run Process\n    ...    kubectl -n ${lab-namespace} get nodes.c9s.run -l c9s.run/topologyOwner\\=${lab-name} -o name\n    ...    shell=True\n    Should Be Equal As Integers    ${nodes.rc}    0\n    Should Contain    ${nodes.stdout}    node.c9s.run/client\n    Should Contain    ${nodes.stdout}    node.c9s.run/server\n\n    # without a Topology the Nodes record the file; inspect without the file reports it\n    ${annotation} =    Node Field    client    {.metadata.annotations.containerlab\\\\.dev/topo-file}\n    Should Be Equal    ${annotation}    ${topo}\n    ${output} =    Run Clab Command    inspect --name ${lab-name} --format json\n    ${paths} =    Evaluate    {n[\"absLabPath\"] for n in json.loads($output.stdout)[\"${lab-name}\"]}\n    ...    modules=json\n    Should Be Equal    ${paths}    ${{{\"${topo}\"}}}\n\nApply without a Topology resource keeps a stopped node stopped\n    ${output} =    Run Clab Command    stop -t ${topo} --node client\n    Should Be Equal As Integers    ${output.rc}    0\n\n    ${plan} =    Run Clab Command    deploy -t ${applied-topo} --no-topology-cr --dry-run --format json\n    Should Be Equal As Integers    ${plan.rc}    0\n    ${changes} =    Evaluate    [c[\"kind\"] + \"/\" + c[\"name\"] for c in json.loads($plan.stdout)[\"changes\"]]    modules=json\n    Should Contain    ${changes}    Node/server\n    Should Not Contain    ${changes}    Node/client\n\n    ${output} =    Run Clab Command    deploy -t ${applied-topo} --no-topology-cr\n    Should Be Equal As Integers    ${output.rc}    0\n    ${run_state} =    Node Field    client    {.spec.runState}\n    Should Be Equal    ${run_state}    Stopped\n\n    ${output} =    Run Clab Command    start -t ${topo} --node client\n    Should Be Equal As Integers    ${output.rc}    0\n    Wait Until Keyword Succeeds    ${recovery-timeout}    ${retry-interval}    Ping From Client Should Succeed\n\nDestroy c9s linux lab deployed without a Topology resource\n    ${output} =    Run Clab Command    destroy -t ${topo} --cleanup\n    Should Be Equal As Integers    ${output.rc}    0\n\n    ${namespace} =    Process.Run Process\n    ...    kubectl get namespace ${lab-namespace} --ignore-not-found -o name\n    ...    shell=True\n    Should Be Equal As Integers    ${namespace.rc}    0\n    Should Be Empty    ${namespace.stdout}\n\n\n*** Keywords ***\nSetup\n    Skip If    '${runtime}' != 'c9s'    This suite targets the c9s runtime.\n    Remove File If Exists    ${events-log}\n    Remove File If Exists    ${events-err}\n    ${output} =    Run Clab Command    destroy -t ${topo} --cleanup\n    Log    Cleanup return code: ${output.rc}\n\nTeardown\n    Stop Events Process\n    Run Keyword And Ignore Error    Terminate Process    c9s_lifecycle    kill=True\n    Run Keyword And Ignore Error    Terminate Process    c9s_redeploy    kill=True\n    Run Clab Command    destroy -t ${topo} --cleanup\n    Remove File If Exists    ${events-log}\n    Remove File If Exists    ${events-err}\n\nRun Clab Command\n    [Arguments]    ${args}\n    ${output} =    Process.Run Process\n    ...    ${CLAB_BIN} --runtime ${runtime} ${args}\n    ...    shell=True\n    Log    stdout:${\\n}${output.stdout}    console=${True}\n    Log    stderr:${\\n}${output.stderr}    console=${True}\n    RETURN    ${output}\n\nClabwire 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\nCapture 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\nNo 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\nPing 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\n    Should Match Regexp    ${combined}    (?s).*1 (packets )?received, 0% packet loss.*\n\nPing From Client Should Fail\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 Match Regexp    ${combined}    (?s).*0 (packets )?received, 100% packet loss.*\n\nClient Eth1 Should Be Visible\n    ${output} =    Run Clab Command\n    ...    exec -t ${topo} --label ${client-label} --cmd 'ip link show eth1'\n    ${combined} =    Catenate    SEPARATOR=\\n    ${output.stdout}    ${output.stderr}\n    Should Be Equal As Integers    ${output.rc}    0\n    Should Contain    ${combined}    eth1\n\nRun Offline Clab Command\n    [Arguments]    ${args}\n    ${output} =    Process.Run Process\n    ...    ${offline-env} ${CLAB_BIN} --runtime ${runtime} ${args}\n    ...    shell=True\n    ...    cwd=${CURDIR}\n    Log    stdout:${\\n}${output.stdout}    console=${True}\n    Log    stderr:${\\n}${output.stderr}    console=${True}\n    RETURN    ${output}\n\nCollect Events\n    [Arguments]    ${args}\n    Remove File If Exists    ${events-log}\n    TRY\n        Start Process    ${CLAB_BIN} --runtime ${runtime} ${args}\n        ...    shell=True\n        ...    alias=c9s_events\n        ...    stdout=${events-log}\n        ...    stderr=${events-err}\n        Sleep    6s\n    FINALLY\n        Stop Events Process\n    END\n    ${events} =    Get File    ${events-log}\n    Log    ${events}\n    Validate JSON Lines    ${events-log}\n    Remove File If Exists    ${events-log}\n    Remove File If Exists    ${events-err}\n    RETURN    ${events}\n\nSet Client Eth1\n    [Arguments]    ${state}\n    Run Clab Command    exec -t ${topo} --label ${client-label} --cmd 'ip link set dev eth1 ${state}'\n\nInterface Event Should Be Logged\n    [Documentation]    An interface event with the action and, when given, one of the states.\n    [Arguments]    ${path}    ${node}    ${ifname}    ${action}    @{states}\n    ${contents} =    Get File    ${path}\n    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n    ${found} =    Evaluate\n    ...    any([e.get(\"action\") == $action and e.get(\"actor_id\") == $actor and e.get(\"attributes\", {}).get(\"ifname\") == $ifname and (not $states or e.get(\"attributes\", {}).get(\"state\") in $states) for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"interface\"])\n    ...    modules=json\n    Should Be True    ${found}    no interface ${action} event ${states} for ${node}:${ifname}\n\nLast Interface State Should Be\n    [Arguments]    ${path}    ${node}    ${ifname}    ${state}\n    ${contents} =    Get File    ${path}\n    ${states} =    Interface States    ${contents}    ${node}\n    Should Be Equal    ${states}[${ifname}]    ${state}\n\nContainer Actions\n    [Arguments]    ${path}    ${node}\n    ${contents} =    Get File    ${path}\n    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n    ${actions} =    Evaluate\n    ...    [e[\"action\"] for e in map(json.loads, filter(str.strip, $contents.splitlines())) if e.get(\"type\") == \"container\" and e.get(\"actor_id\") == $actor]\n    ...    modules=json\n    RETURN    ${actions}\n\nContainer Actions Should Include In Order\n    [Arguments]    ${path}    ${node}    @{expected}\n    ${actions} =    Container Actions    ${path}    ${node}\n    # the expected actions appear in this order, other actions may come between them\n    ${in_order} =    Evaluate\n    ...    re.search(\"\\\\n\" + \"\\\\n(?:.*\\\\n)*?\".join([re.escape(a) for a in $expected]) + \"\\\\n\", \"\\\\n\" + \"\\\\n\".join($actions) + \"\\\\n\") is not None\n    ...    modules=re\n    Should Be True    ${in_order}    ${node} reported ${actions}, not ${expected} in this order\n\nContainer Event Should Carry Docker Attributes\n    [Documentation]    The last container event of a node with the action carries the attributes\n    ...    a Docker container event of the node has, and the container state.\n    [Arguments]    ${events}    ${node}    ${action}    ${state}    ${topo-file}=${topo}\n    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n    ${matching} =    Evaluate\n    ...    [e for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get(\"type\") == \"container\" and e.get(\"actor_id\") == $actor and e.get(\"action\") == $action]\n    ...    modules=json\n    Should Not Be Empty    ${matching}    no container ${action} event for ${node}\n    ${event} =    Set Variable    ${matching}[-1]\n    ${attributes} =    Set Variable    ${event}[attributes]\n    Log    ${attributes}\n    Should Be Equal    ${attributes}[containerlab]    ${lab-name}\n    Should Be Equal    ${attributes}[clab-node-name]    ${node}\n    Should Be Equal    ${attributes}[clab-node-longname]    ${lab-name}-${node}\n    Should Be Equal    ${attributes}[clab-node-kind]    linux\n    Should Be Equal    ${attributes}[clab-topo-file]    ${topo-file}\n    Should Not Be Empty    ${attributes}[clab-owner]\n    Should Be Equal    ${attributes}[image]    ${node-image}\n    Should Be Equal    ${attributes}[name]    ${lab-name}-${node}\n    Should Be Equal    ${attributes}[id]    ${actor}\n    Should Be Equal    ${event}[actor_full_id]    ${actor}\n    # a node is created before the controller allocates its management address and Service\n    IF    $state != \"created\"\n        Should Match Regexp    ${attributes}[mgmt_ipv4]    ^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+/\\\\d+$\n        Should Contain    ${attributes}[ports]    22/tcp\n    END\n    Should Be Equal    ${attributes}[state]    ${state}\n\nInterface States\n    [Documentation]    The interfaces the events report for a node, with their last state.\n    [Arguments]    ${events}    ${node}\n    ${actor} =    Set Variable    ${lab-namespace}/${lab-name}/${node}\n    ${states} =    Evaluate\n    ...    {e[\"attributes\"][\"ifname\"]: e[\"attributes\"].get(\"state\", \"\") for e in map(json.loads, filter(str.strip, $events.splitlines())) if e.get(\"type\") == \"interface\" and e.get(\"actor_id\") == $actor}\n    ...    modules=json\n    RETURN    ${states}\n\nLog File Should Contain\n    [Arguments]    ${path}    ${text}\n    ${contents} =    Get File    ${path}\n    Should Contain    ${contents}    ${text}\n\nPersistent Claim Volumes\n    ${claims} =    Process.Run Process\n    ...    kubectl -n ${lab-namespace} get pvc -l c9s.run/topologyOwner\\=${lab-name} -o jsonpath\\='{range .items[*]}{.metadata.name}\\={.spec.volumeName}{\" \"}{end}'\n    ...    shell=True\n    Should Be Equal As Integers    ${claims.rc}    0\n    ${volumes} =    Strip String    ${claims.stdout}\n    RETURN    ${volumes}\n\nNode Field\n    [Arguments]    ${node}    ${jsonpath}\n    ${result} =    Process.Run Process\n    ...    kubectl -n ${lab-namespace} get nodes.c9s.run ${node} -o jsonpath\\='${jsonpath}'\n    ...    shell=True\n    Should Be Equal As Integers    ${result.rc}    0    ${result.stderr}\n    RETURN    ${result.stdout}\n\nServer Pod Name\n    ${result} =    Process.Run Process\n    ...    kubectl -n ${lab-namespace} get pods -l c9s.run/topologyNode\\=server --field-selector status.phase\\=Running -o jsonpath\\='{.items[*].metadata.name}'\n    ...    shell=True\n    Should Be Equal As Integers    ${result.rc}    0\n    RETURN    ${result.stdout}\n\nRemove File If Exists\n    [Arguments]    ${path}\n    Run Keyword And Ignore Error    Remove File    ${path}\n\nStop Events Process\n    Run Keyword And Ignore Error    Terminate Process    c9s_events    kill=True\n    Run Keyword And Ignore Error    Wait For Process    c9s_events\n\nValidate JSON Lines\n    [Arguments]    ${path}\n    ${contents} =    Get File    ${path}\n    @{lines} =    Split To Lines    ${contents}\n    FOR    ${line}    IN    @{lines}\n        ${stripped} =    Strip String    ${line}\n        IF    $stripped == ''    CONTINUE\n        Evaluate    json.loads($stripped)    modules=json\n    END",
        "lineStart": 1,
        "lineEnd": 903,
        "totalLines": 903,
        "truncated": false
      }
    },
    "time": {
      "start": 1793525932878,
      "end": 1793525932887
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19679e35b001BRTO83tAXP1WEH",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679cb650012UAqim43hek3n6",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 74961,
    "input": 71915,
    "output": 77,
    "reasoning": 89,
    "cache": {
      "read": 2880,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19679cb650012UAqim43hek3n6",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525926757,
    "completed": 1793525932894
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 74961,
    "input": 71915,
    "output": 77,
    "reasoning": 89,
    "cache": {
      "read": 2880,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 39
step-start
{
  "type": "step-start",
  "id": "prt_19679edce001yXBXq6CKkSknIa",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679e369001BVbW1MINT5i8A9"
}
Reasoning
The robot suite is extensive and consistent with the implementation. One subtle detail in `Container Event Should Carry Docker Attributes`: it asserts `attributes[clab-owner]` not empty — the docker events carry `clab-owner`? That's a runtime detail; the events command probably adds it. Not something to chase.

One detail: "Container Event Should Carry Docker Attributes" with default `${topo-file}=${topo}` and special values for redeploy (applied-topo). This matches `labRuntimeTopologyPath` using `c.TopoPaths` (the deploy records the latest file). Consistent with the "Destroy and deploy" test.

Now, a last check on the two remaining files I haven't examined in depth: `labruntime/runtime.go` (26th changed path: `labruntime/runtime.go` M) — the diff for it I saw partially in the first session ("lab-not-found semantics changed"). And `core/events/stream.go` rest. Given the depth achieved, let me quickly verify the key parts of stream.go for lab runtime events: `streamLabRuntimeEvents` (errors → errs chan buffered 1; per-container registry start). And runtime.go Inspect.
The robot suite is consistent. Two files remain to verify: `labruntime/runtime.go` and the rest of `stream.go`.
grep · completed

Input

{
  "path": "/source/head/labruntime/runtime.go",
  "pattern": "notFound|lab-not-found|no lab named|Inspect\\("
}

Output

Found 29 matches
/source/head/labruntime/clabernetes/runtime_gaps_test.go:
  Line 56: 	_, err = lr.Inspect(context.Background(), clablabruntime.InspectRequest{Name: "lab1"})

  Line 58: 		t.Fatalf("Inspect() error = %v, want the kubeconfig load error", err)


/source/head/labruntime/clabernetes/lifecycle.go:
  Line 174: 		return r.Inspect(ctx, clablabruntime.InspectRequest{Name: req.Name, Namespace: namespace})

  Line 206: 	return r.Inspect(ctx, clablabruntime.InspectRequest{Name: req.Name, Namespace: namespace})

  Line 445: func (r *Runtime) Inspect(

  Line 621: 			state, err := r.Inspect(ctx, clablabruntime.InspectRequest{


/source/head/labruntime/clabernetes/event_parity_test.go:
  Line 534: 	state, err := h.r.Inspect(context.Background(), clablabruntime.InspectRequest{Name: "lab1"})

  Line 824: 	state, err := r.Inspect(context.Background(),

  Line 849: 	state, err = r.Inspect(context.Background(),


/source/head/labruntime/clabernetes/access.go:
  Line 58: 	state, err := r.Inspect(ctx, clablabruntime.InspectRequest{

  Line 447: 	state, err := r.Inspect(ctx, req)


/source/head/labruntime/clabernetes/container_events.go:
  Line 117: 	state, err := t.r.Inspect(ctx, clablabruntime.InspectRequest{

  Line 122: 		var notFound *labNotFoundError

  Line 123: 		if !errors.As(err, &notFound) {


/source/head/labruntime/clabernetes/events.go:
  Line 119: 		state, err := r.Inspect(ctx, clablabruntime.InspectRequest{

  Line 126: 			var notFound *labNotFoundError

  Line 127: 			if errors.As(err, &notFound) {


/source/head/labruntime/clabernetes/reconcile.go:
  Line 487: 		return r.Inspect(ctx, clablabruntime.InspectRequest{Name: req.Name, Namespace: namespace})

  Line 496: 	return r.Inspect(ctx, clablabruntime.InspectRequest{Name: req.Name, Namespace: namespace})

  Line 587: 		return r.Inspect(ctx, clablabruntime.InspectRequest{Name: req.Name, Namespace: namespace})

  Line 593: 	return r.Inspect(ctx, clablabruntime.InspectRequest{Name: req.Name, Namespace: namespace})


/source/head/labruntime/clabernetes/nodes_test.go:
  Line 539: 	if _, err := r.Inspect(ctx, clablabruntime.InspectRequest{Name: "lab1"}); !errors.Is(

  Line 541: 		t.Fatalf("Inspect() on clabernetes 0.10 = %v", err)

  Line 732: 	state, err := r.Inspect(ctx, clablabruntime.InspectRequest{Name: "lab1"})


/source/head/labruntime/clabernetes/clabernetes_test.go:
  Line 1129: 	state, err := r.Inspect(context.Background(), clablabruntime.InspectRequest{


/source/head/labruntime/runtime.go:
  Line 550: 	Inspect(context.Context, InspectRequest) (*LabState, error)


/source/head/labruntime/clabernetes/access_test.go:
  Line 354: 	_, _ = r.Inspect(ctx, clablabruntime.InspectRequest{Name: "lab1", Identity: alice})

  Line 362: 	_, _ = r.Inspect(ctx, clablabruntime.InspectRequest{Name: "lab1"})

  Line 410: 	_, _ = r.Inspect(context.Background(), clablabruntime.InspectRequest{Name: "lab1"})
Tool metadata
{
  "type": "tool",
  "id": "prt_19679f99f001UrCYvyBhzWBscu",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679e369001BVbW1MINT5i8A9",
  "callID": "call_40b6af61471a455eabc97534",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/labruntime/runtime.go",
      "pattern": "notFound|lab-not-found|no lab named|Inspect\\("
    },
    "output": "Found 29 matches\n/source/head/labruntime/clabernetes/runtime_gaps_test.go:\n  Line 56: \t_, err = lr.Inspect(context.Background(), clablabruntime.InspectRequest{Name: \"lab1\"})\n\n  Line 58: \t\tt.Fatalf(\"Inspect() error = %v, want the kubeconfig load error\", err)\n\n\n/source/head/labruntime/clabernetes/lifecycle.go:\n  Line 174: \t\treturn r.Inspect(ctx, clablabruntime.InspectRequest{Name: req.Name, Namespace: namespace})\n\n  Line 206: \treturn r.Inspect(ctx, clablabruntime.InspectRequest{Name: req.Name, Namespace: namespace})\n\n  Line 445: func (r *Runtime) Inspect(\n\n  Line 621: \t\t\tstate, err := r.Inspect(ctx, clablabruntime.InspectRequest{\n\n\n/source/head/labruntime/clabernetes/event_parity_test.go:\n  Line 534: \tstate, err := h.r.Inspect(context.Background(), clablabruntime.InspectRequest{Name: \"lab1\"})\n\n  Line 824: \tstate, err := r.Inspect(context.Background(),\n\n  Line 849: \tstate, err = r.Inspect(context.Background(),\n\n\n/source/head/labruntime/clabernetes/access.go:\n  Line 58: \tstate, err := r.Inspect(ctx, clablabruntime.InspectRequest{\n\n  Line 447: \tstate, err := r.Inspect(ctx, req)\n\n\n/source/head/labruntime/clabernetes/container_events.go:\n  Line 117: \tstate, err := t.r.Inspect(ctx, clablabruntime.InspectRequest{\n\n  Line 122: \t\tvar notFound *labNotFoundError\n\n  Line 123: \t\tif !errors.As(err, &notFound) {\n\n\n/source/head/labruntime/clabernetes/events.go:\n  Line 119: \t\tstate, err := r.Inspect(ctx, clablabruntime.InspectRequest{\n\n  Line 126: \t\t\tvar notFound *labNotFoundError\n\n  Line 127: \t\t\tif errors.As(err, &notFound) {\n\n\n/source/head/labruntime/clabernetes/reconcile.go:\n  Line 487: \t\treturn r.Inspect(ctx, clablabruntime.InspectRequest{Name: req.Name, Namespace: namespace})\n\n  Line 496: \treturn r.Inspect(ctx, clablabruntime.InspectRequest{Name: req.Name, Namespace: namespace})\n\n  Line 587: \t\treturn r.Inspect(ctx, clablabruntime.InspectRequest{Name: req.Name, Namespace: namespace})\n\n  Line 593: \treturn r.Inspect(ctx, clablabruntime.InspectRequest{Name: req.Name, Namespace: namespace})\n\n\n/source/head/labruntime/clabernetes/nodes_test.go:\n  Line 539: \tif _, err := r.Inspect(ctx, clablabruntime.InspectRequest{Name: \"lab1\"}); !errors.Is(\n\n  Line 541: \t\tt.Fatalf(\"Inspect() on clabernetes 0.10 = %v\", err)\n\n  Line 732: \tstate, err := r.Inspect(ctx, clablabruntime.InspectRequest{Name: \"lab1\"})\n\n\n/source/head/labruntime/clabernetes/clabernetes_test.go:\n  Line 1129: \tstate, err := r.Inspect(context.Background(), clablabruntime.InspectRequest{\n\n\n/source/head/labruntime/runtime.go:\n  Line 550: \tInspect(context.Context, InspectRequest) (*LabState, error)\n\n\n/source/head/labruntime/clabernetes/access_test.go:\n  Line 354: \t_, _ = r.Inspect(ctx, clablabruntime.InspectRequest{Name: \"lab1\", Identity: alice})\n\n  Line 362: \t_, _ = r.Inspect(ctx, clablabruntime.InspectRequest{Name: \"lab1\"})\n\n  Line 410: \t_, _ = r.Inspect(context.Background(), clablabruntime.InspectRequest{Name: \"lab1\"})\n",
    "title": "notFound|lab-not-found|no lab named|Inspect\\(",
    "metadata": {
      "matches": 29,
      "truncated": false
    },
    "time": {
      "start": 1793525938598,
      "end": 1793525938612
    }
  }
}
grep · completed

Input

{
  "path": "/source/head/core/events/stream.go",
  "pattern": "errCh|forwardRuntimeEvents|registry\\.Start|streamLabRuntimeEvents"
}

Output

Found 8 matches
/source/head/core/events/stream.go:
  Line 32: 		return streamLabRuntimeEvents(ctx, clab, opts)

  Line 69: 		registry.Start(&container)

  Line 83: 	errCh := make(chan error, 1)

  Line 84: 	go forwardRuntimeEvents(ctx, runtime, registry, runtimeEvents, runtimeErrs, eventCh, errCh)

  Line 86: 	runtimeErrors := errCh

  Line 110: func streamLabRuntimeEvents(ctx context.Context, clab *clabcore.CLab, opts Options) error {

  Line 253: func forwardRuntimeEvents(


/source/head/core/events/netlink_watch_test.go:
  Line 166: 	registry.Start(container)
Tool metadata
{
  "type": "tool",
  "id": "prt_19679fa64001SsgP24C33mga7B",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679e369001BVbW1MINT5i8A9",
  "callID": "call_5699327aa8c74af596937a91",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/core/events/stream.go",
      "pattern": "errCh|forwardRuntimeEvents|registry\\.Start|streamLabRuntimeEvents"
    },
    "output": "Found 8 matches\n/source/head/core/events/stream.go:\n  Line 32: \t\treturn streamLabRuntimeEvents(ctx, clab, opts)\n\n  Line 69: \t\tregistry.Start(&container)\n\n  Line 83: \terrCh := make(chan error, 1)\n\n  Line 84: \tgo forwardRuntimeEvents(ctx, runtime, registry, runtimeEvents, runtimeErrs, eventCh, errCh)\n\n  Line 86: \truntimeErrors := errCh\n\n  Line 110: func streamLabRuntimeEvents(ctx context.Context, clab *clabcore.CLab, opts Options) error {\n\n  Line 253: func forwardRuntimeEvents(\n\n\n/source/head/core/events/netlink_watch_test.go:\n  Line 166: \tregistry.Start(container)\n",
    "title": "errCh|forwardRuntimeEvents|registry\\.Start|streamLabRuntimeEvents",
    "metadata": {
      "matches": 8,
      "truncated": false
    },
    "time": {
      "start": 1793525938793,
      "end": 1793525938809
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_19679fa80001Js0RO01O50wRwc",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679e369001BVbW1MINT5i8A9",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 90361,
    "input": 15272,
    "output": 93,
    "reasoning": 244,
    "cache": {
      "read": 74752,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19679e369001BVbW1MINT5i8A9",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525932905,
    "completed": 1793525938820
  },
  "parentID": "msg_196785f9c001RzWg2gr7EYUdBK",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 90361,
    "input": 15272,
    "output": 93,
    "reasoning": 244,
    "cache": {
      "read": 74752,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
User · 40
compaction
{
  "type": "compaction",
  "id": "prt_19679fa86001dAsj905fdlGIjb",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679fa85001Shca5Uc1lk0K9N",
  "auto": true,
  "overflow": false,
  "tail_start_id": "msg_19679cb650012UAqim43hek3n6"
}
Message metadata
{
  "role": "user",
  "id": "msg_19679fa85001Shca5Uc1lk0K9N",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525938821
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 41
step-start
{
  "type": "step-start",
  "id": "prt_1967a041c001LLTGHVkQvLWRuu",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679faa20017WtSWncG8wo86f"
}
Reasoning
Combine prior summary with new progress. Update completed items: state.go read (coherent), manifests.go read, capture_interfaces.go read, topology.go read (annotationTopologyFile const), clabernetes.go constants verified, setTopologySourceFile callers grepped (plan.go:56, manifests.go:45/48, primitives.go:225, reconcile.go:217/221, carry-over logic), capture.go read (coherent), iface_stats.go full read, events.go full read, container_events.go full read (tracker logic verified), reconcile.go 170-221 read (carryOverNodeTopologyFile semantics), core/labruntime.go 360-490 and 590-650 read (managementAddress, splitManagementCIDR, topologyNodeName, containersFromLabState), netlink.go 620-750 read (interfaceSnapshotAttributes/interfaceStatsAttributes/labRuntimeInterfaceAttributes), test function surveys done, event_parity_test.go test list, parity_test.go test list, labruntime_gaps_test.go / runtime_gaps_test.go lists.

Resolved candidates: managementAddress CIDR parsing (splitManagementCIDR handles both) — resolved. NodeType override candidate — resolved/acceptable (consistent with docs; dropped). Remaining: read event_parity_test.go content details, clabernetes_test.go, capture_test.go, labruntime_gaps_test.go details, runtime_gaps_test.go details, docs (events.md, interfaces.md, runtime.md), robot tests file tests/14-clabernetes/01-linux-lifecycle.robot, labruntime/runtime.go Inspect lab-not-found (grep found labNotFoundError in lifecycle.go — runtime.go may not contain it), manifest.json re-read (the conversation never re-read manifest.json; still pending).

Also note: diff.txt fully read (5138 lines; gap 1284-1362 read now — actually fully read).

Note labNotFoundError actually lives in lifecycle.go, not runtime.go.

Next moves: re-read manifest.json for remaining paths; skim remaining tests (event_parity_test.go key tests, clabernetes_test.go, capture_test.go, labruntime_gaps_test.go, runtime_gaps_test.go), skim docs (events.md, interfaces.md, runtime.md), robot test file; finalize findings and emit result schema.
## Objective
- Perform a source-only PR review of the read-only snapshot at `/source` (containerlab repo, srl-labs/containerlab): read `standards.json` and referenced rules, analyze `diff.txt` and head/base files, track all 26 changed paths from `manifest.json`, complete checks for each changed path plus relevant callers/tests/docs/schema, then return a trusted result schema. No test execution allowed — limitation must be disclosed in the final result.

## Important Details
- Head: `1566c3b8e3cb58c82d238dedbfa3b319249bab0a`; base: `b4de5d55cf17262e39325a7e125a6d3cb2c89318`. Permalink roots: head=`https://github.com/srl-labs/containerlab/blob/1566c3b8e3cb58c82d238dedbfa3b319249bab0a/`, base=`https://github.com/srl-labs/containerlab/blob/b4de5d55cf17262e39325a7e125a6d3cb2c89318/`.
- Snapshot incomplete: false; full inventory in `/source/manifest.json` (truncated read earlier — re-read still pending to confirm all 26 paths).
- Standards loaded: `.cursor/rules/karpathy-guidelines.mdc` and `.cursor/rules/ponytail.mdc` (surgical changes, simplicity first, root-cause fixes, grep every caller).
- All 26 changed paths (from diff + manifest): M `core/events/netlink.go`, `core/events/stream.go`, `core/labruntime.go`, `core/labruntime_gaps_test.go`, `docs/cmd/events.md`, `docs/cmd/inspect/interfaces.md`, `docs/manual/clabernetes/runtime.md`, `labruntime/clabernetes/{capture.go,capture_interfaces.go,clabernetes.go,events.go,iface_stats.go,manifests.go,plan.go,primitives.go,reconcile.go,state.go,topology.go,clabernetes_test.go,capture_test.go,runtime_gaps_test.go,labruntime/clabernetes/... }`, A `core/events/parity_test.go`, `labruntime/clabernetes/container_events.go`, `labruntime/clabernetes/event_parity_test.go`, M `labruntime/runtime.go`, M `tests/14-clabernetes/01-linux-lifecycle.robot` (verify exact list against manifest.json).
- PR theme: clabernetes (c9s) lab-runtime event parity with the Docker runtime — new container event tracker, interface event parity attributes, interface poller via one exec (`/proc/net/dev` + sysfs), topology source file annotation (`containerlab.dev/topo-file`) recording/carry-over, c9s `NodeState` enrichment (`TopoFile`, `Type`, `Group`, `TopologyName` via `labelOriginalNodeName`=`c9s.run/originalNodeName`, `annotationDirectNodeUID`=`c9s.run/direct-node-uid`), `newestPod` prefers non-deleting pods.
- Key verified identifiers in `labruntime/clabernetes/clabernetes.go`: `labelOriginalNodeName`, `defaultContainerAnnotation="kubectl.kubernetes.io/default-container"`, `annotationDirectNodeUID="c9s.run/direct-node-uid"`, GVRs for c9s.run v1alpha1 `topologies/nodes/links/nodeprofiles`.
- Topology source file flow: `setTopologySourceFile` only called from `plan.go:56` (`prepareDesiredDeployment`); `removeTopologySourceFile` in `manifests.go:45-48`, `primitives.go:225`; `carryOverNodeTopologyFile` in `reconcile.go:210-221` keeps an existing Node's annotation (pod template would otherwise be replaced); `labTopologyPath(annotations, fallback)` falls back to `k8s://<namespace>/topologies/<lab>`.
- Only `/source` paths readable (tool permission constraint).
- Tooling quirk: `grep` tool truncates at 100 matches and repeats; use per-file targeted greps.

## Work State
### Completed
- Read both standards files; read `diff.txt` fully (all 5138 lines, incl. the 1284–1362 gap).
- Read and verified coherent: `state.go` (stateFromNodeResources, nodeStateFromResource, TopologyPath fallback), `manifests.go` (Manifests renders deploy bundle without topo file annotation), `capture_interfaces.go` (`streamPodExec`, `withKubernetesClientDebugLogs`, exit-error mapping), `topology.go` (annotation setters/remover, `labTopologyPath`), `capture.go` (clabwire capture contract, segment chaining constants), `events.go` (StreamEvents goroutine wiring; errs buffer 4 matches 4 error-writing goroutines), `iface_stats.go` (interfaceSampleScript one-exec sampling, workers=16, eth0/lo, clabernetesAliasPrefix filtering), `container_events.go` full (tracker, actions, health transitions, `containerTransitionActions`/`containerHealth` parity logic sound), `reconcile.go:170-221` (reconciledPrimitiveObject + carryOverNodeTopologyFile), `clabernetes.go` constants.
- Read `core/labruntime.go` lines 360-490 and 590-650: `containersFromLabState`, `containerFromLabNode` (topologyNode mapping via `topologyNodeName`, labels incl. `clab-node-type`/`clab-node-group` only when non-empty), `LabRuntimeContainer`, `managementAddress` (LoadBalancer addr → /32 or /128; `splitManagementCIDR` handles both CIDR and plain formats — mgmt CIDR candidate RESOLVED), `labRuntimeContainerID`.
- Read `core/events/netlink.go:620-750`: `interfaceSnapshotAttributes` (ifname/index/mtu/state/type, alias+mac conditionally), `interfaceStatsAttributes` (rx/tx bytes/packets, rx_bps etc.), `labRuntimeInterfaceAttributes` wiring in `stream.go:204`.
- Resolved prior candidates: empty `state` attribute (formatter drops empty values), errs channel sizing, `annotationDirectNodeUID`/`labelOriginalNodeName` contract, timer.Reset safety, `managementAddress` CIDR parity, `containerFromLabNode` NodeType override (consistent with docs: with `-t` the kind's default type is populated; byName mode falls back to runtime state — accepted, matches `docs/cmd/events.md` wording).
- Test coverage surveyed via targeted greps: `event_parity_test.go` (TestNetlinkOperState, TestInterfaceEventDataNamesInterfacesLikeDocker, poller tests, TestContainerTransitionActions, TestContainerTrackerReportsTheNodeLifecycle, TestDeployRecordsTheTopologyFile, TestCarryOverNodeTopologyFile, assertPrimitiveTopologyFile), `core/events/parity_test.go` (TestContainerEventParity, TestContainerSnapshotParity, TestContainerStateUsesDockerVocabulary, TestInterfaceEventParity, TestInterfaceEventOmitsUnknownValues, TestLabRuntimeTopologyEventsKeepTheirAttributes), `runtime_gaps_test.go` (11 tests incl. scope, enrichment, persistence), `core/labruntime_gaps_test.go` (incl. clab-node-type "ixr-h2" parity test).
- Robot test expectations cross-checked against diff (`kill die destroy`, `kill stop die`, health_status `starting`→skip / `healthy` appended).

### Active
- Detailed reading of remaining test files (`event_parity_test.go` bodies, `clabernetes_test.go`, `capture_test.go`, `labruntime_gaps_test.go`, `runtime_gaps_test.go`) — test lists known, bodies not fully read.
- Skim of docs for consistency: `docs/cmd/events.md`, `docs/cmd/inspect/interfaces.md`, `docs/manual/clabernetes/runtime.md` — not yet read in head.
- Re-read `/source/manifest.json` to confirm the exact 26-path list (earlier read truncated).
- Note: `labNotFoundError` actually lives in `labruntime/clabernetes/lifecycle.go:478-496` (used in `container_events.go:122`, `events.go:126`) — inspect the lab-not-found semantics there rather than in `labruntime/runtime.go`.

### Blocked
- (none)

## Next Move
1. Re-read `/source/manifest.json` to confirm the full 26-path changed list; correct the path inventory above if it differs.
2. Read `labruntime/clabernetes/lifecycle.go` around `labNotFoundError`/Inspect semantics (lab-not-found behavior), then skim the remaining test bodies (`event_parity_test.go`, `clabernetes_test.go`, `capture_test.go`, `labruntime_gaps_test.go`, `runtime_gaps_test.go`), the three docs files, and `tests/14-clabernetes/01-linux-lifecycle.robot`; finalize per-path findings (likely all P4/none) and emit the trusted result schema, disclosing that no tests were executed (read-only snapshot).

## Relevant Files
- `/source/manifest.json` — changed-path inventory (re-read pending).
- `/source/diff.txt` — full PR diff (fully read).
- `/source/head/labruntime/clabernetes/{state,topology,manifests,plan,primitives,reconcile,events,container_events,iface_stats,capture,capture_interfaces,clabernetes}.go` — all read/verified this session.
- `/source/head/labruntime/clabernetes/lifecycle.go` — Deploy/Inspect/`labNotFoundError`; unread (next).
- `/source/head/core/labruntime.go` — `containerFromLabNode`, `managementAddress`, `topologyNodeName`, `splitManagementCIDR` (read 360-490, 590-650; lines 1-360 and 650+ partial).
- `/source/head/core/events/{netlink,stream,formatter}.go` — attribute builders, stream wiring, empty-attr dropping (verified).
- `/source/head/core/events/parity_test.go`, `/source/head/labruntime/clabernetes/event_parity_test.go`, `/source/head/labruntime/clabernetes/{clabernetes_test,capture_test,runtime_gaps_test}.go`, `/source/head/core/labruntime_gaps_test.go` — test lists surveyed; bodies to skim.
- `/source/head/docs/cmd/events.md`, `/source/head/docs/cmd/inspect/interfaces.md`, `/source/head/docs/manual/clabernetes/runtime.md` — docs parity; unread.
- `/source/head/tests/14-clabernetes/01-linux-lifecycle.robot` — modified robot test; unread.
step-finish
{
  "type": "step-finish",
  "id": "prt_1967a365a001tZExS7a1QPY300",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_19679faa20017WtSWncG8wo86f",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 25238,
    "input": 22519,
    "output": 2260,
    "reasoning": 459,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_19679faa20017WtSWncG8wo86f",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525938850,
    "completed": 1793525954141
  },
  "parentID": "msg_19679fa85001Shca5Uc1lk0K9N",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "compaction",
  "agent": "compaction",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "summary": true,
  "cost": 0,
  "tokens": {
    "total": 25238,
    "input": 22519,
    "output": 2260,
    "reasoning": 459,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "stop"
}
User · 42
Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.
Message metadata
{
  "role": "user",
  "id": "msg_1967a36620015s1R3CwCc540iR",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525954146
  },
  "summary": {
    "diffs": []
  },
  "agent": "tofarev",
  "model": {
    "providerID": "tofarev",
    "modelID": "zai-org/GLM-5.3-Flash"
  }
}
Assistant · 43
step-start
{
  "type": "step-start",
  "id": "prt_1967a3e6f001UazubxBQvgCR3w",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a36700010119sHZdt1ebQm"
}
Reasoning
Let me continue with the remaining verification steps. I need to:

1. Read `labruntime/clabernetes/lifecycle.go` around `labNotFoundError`/Inspect semantics (lab-not-found behavior), specifically lines 478-496 for `labNotFoundError` and how Inspect uses it.
2. Read `core/events/stream.go` around lines 60-110 (streamClabEvents / streamClabLabRuntimeEvents wiring, errCh logic) to double-check the errs/error channel pattern.
3. Read `labruntime/runtime.go` diff-related portions (the diff showed changes for it — let me re-check the diff for runtime.go specifically).
4. Read remaining test bodies and docs skim.
5. Re-read `/source/manifest.json` to confirm the 26-path list.
6. Finalize findings and emit the result schema.

Let me do these steps efficiently with parallel tool calls.

First: diff for runtime.go + stream.go relevant sections + lifecycle.go labNotFoundError.
Continuing with the remaining verification steps.
grep · completed

Input

{
  "path": "/source/diff.txt",
  "pattern": "runtime\\.go|events\\.md|interfaces\\.md|clabernetes/runtime\\.md"
}

Output

Found 100 matches (more matches available)
/source/diff.txt:
  Line 860: diff --git a/core/labruntime.go b/core/labruntime.go

  Line 862: --- a/core/labruntime.go

  Line 863: +++ b/core/labruntime.go

  Line 1074: diff --git a/docs/cmd/events.md b/docs/cmd/events.md

  Line 1076: --- a/docs/cmd/events.md

  Line 1077: +++ b/docs/cmd/events.md

  Line 1100: +[c9s runtime manual](../manual/clabernetes/runtime.md#events) lists the

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

  Line 1108: -- [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md) - explains how c9s events differ from Docker events.

  Line 1109: +- [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md#events) - describes c9s events and how they map onto Docker events.

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

  Line 1113: --- a/docs/cmd/inspect/interfaces.md

  Line 1114: +++ b/docs/cmd/inspect/interfaces.md

  Line 1121: -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.

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

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

  Line 1130: --- a/docs/manual/clabernetes/runtime.md

  Line 1131: +++ b/docs/manual/clabernetes/runtime.md

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

  Line 4633: --- a/labruntime/runtime.go

  Line 4634: +++ b/labruntime/runtime.go


/source/manifest.json:
  Line 21:       "path": "core/labruntime.go"

  Line 29:       "path": "docs/cmd/events.md"

  Line 33:       "path": "docs/cmd/inspect/interfaces.md"

  Line 37:       "path": "docs/manual/clabernetes/runtime.md"

  Line 105:       "path": "labruntime/runtime.go"

  Line 139:       "path": "core/labruntime.go",

  Line 145:       "path": "docs/cmd/events.md",

  Line 151:       "path": "docs/cmd/inspect/interfaces.md",

  Line 157:       "path": "docs/manual/clabernetes/runtime.md",

  Line 259:       "path": "labruntime/runtime.go",

  Line 4417:       "path": "links/endpoint_runtime.go",

  Line 4651:       "path": "mocks/mockruntime/runtime.go",

  Line 6463:       "path": "runtime/runtime.go",

  Line 8215:       "path": "core/labruntime.go",

  Line 8221:       "path": "docs/cmd/events.md",

  Line 8227:       "path": "docs/cmd/inspect/interfaces.md",

  Line 8233:       "path": "docs/manual/clabernetes/runtime.md",

  Line 8323:       "path": "labruntime/runtime.go",

  Line 12481:       "path": "links/endpoint_runtime.go",

  Line 12715:       "path": "mocks/mockruntime/runtime.go",

  Line 14527:       "path": "runtime/runtime.go",


/source/base/mocks/mockruntime/runtime.go:
  Line 2: // Source: runtime/runtime.go

  Line 6: //	mockgen -package=mockruntime -source=runtime/runtime.go -destination=./mocks/mockruntime/runtime.go


/source/base/Makefile:
  Line 127: 	mockgen -package=mockruntime -source=runtime/runtime.go -destination=$(MOCKDIR)/mockruntime/runtime.go


/source/base/docs/manual/nodes.md:
  Line 731: See [c9s runtime](clabernetes/runtime.md) for details.


/source/base/docs/rn/0.78.md:
  Line 118: - Updated [`events`](../cmd/events.md) to report host-side stitch interfaces and their metadata, matching `inspect interfaces` for stitched links. #3319


/source/base/docs/rn/0.74.md:
  Line 29: The [`events`](../cmd/events.md) stream gets two improvements in this release. First, container exposed ports are now included in the event data, giving consumers full visibility into which ports are mapped for each container. Second, internal event processing was reworked to batch interface queries — replacing per-interface lookups with a single snapshot per tick and caching netem state — cutting CPU usage by up to 30%.


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


/source/base/docs/rn/0.64.md:
  Line 7: In #2437 a new subcommand has been added to the inspect suite - [`clab inspect interfaces`](../cmd/inspect/interfaces.md) - that lists details of the interfaces of the given lab.


/source/base/docs/rn/0.72.md:
  Line 11: Containerlab 0.72 introduces a new [`clab events`](../cmd/events.md) command that provides real-time monitoring of your lab infrastructure. This feature streams lifecycle updates for all Containerlab resources and augments them with interface change notifications collected from container network namespaces.


/source/base/docs/rn/0.81.md:
  Line 53: The [`c9s` runtime](../manual/clabernetes/runtime.md)'s `deploy --dry-run` reported resource-level


/source/base/docs/rn/0.80.md:
  Line 21: Same `deploy`, `inspect`, `exec`, `events`, node lifecycle actions, and `destroy` commands are supported against the c9s runtime. See the [Containerlab runtime](../manual/clabernetes/runtime.md) documentation for more details.


/source/base/docs/cmd/inspect/interfaces.md:
  Line 8: 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.


/source/base/docs/cmd/inspect/index.md:
  Line 13: With `--runtime c9s`, `inspect` reads Clabernetes `Topology` resources and their related kubernetes objects instead of local Docker containers. `inspect --all` lists c9s topologies across all namespaces, or in the `--namespace` override. The JSON output uses `<namespace>/<lab>/<node>` as `container_id` and adds the `namespace`, `pod`, `container`, `node_uid`, `exposed_ports` and `load_balancer_address` fields. See [Containerlab runtime](../../manual/clabernetes/runtime.md#inspect) for details.


/source/base/docs/cmd/capture.md:
  Line 10: - **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).


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

  Line 92: - [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md) - explains how c9s events differ from Docker events.


/source/base/docs/cmd/destroy.md:
  Line 33: With `--runtime c9s`, `--cleanup` also deletes the lab's persistent node storage (the PersistentVolumeClaims holding saved device configuration) and then the lab namespace. A plain destroy keeps the claims, so the next deploy of the lab boots from the saved configuration. See [device state persistence](../manual/clabernetes/runtime.md#device-state-persistence).


/source/base/docs/cmd/redeploy.md:
  Line 114: The `--no-topology-cr` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It makes the deploy phase skip the c9s `Topology` resource and create the compiled `Node`, `Link`, and `NodeProfile` resources directly. See [`deploy --no-topology-cr`](deploy.md#no-topology-cr).

  Line 118: The `--image-pull-secret` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It sets the name of the image pull secret populated in the c9s `Topology` CR during the deploy phase. See [`deploy --image-pull-secret`](deploy.md#image-pull-secret).

  Line 122: The `--no-persistence` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It makes the deploy phase run the lab nodes on ephemeral storage instead of the default per-node persistent volumes. See [`deploy --no-persistence`](deploy.md#no-persistence).


/source/base/docs/cmd/deploy.md:
  Line 261: `c9s` is a lab runtime, not a per-node container runtime. When it is selected, containerlab renders the topology and creates a Clabernetes `Topology` custom resource. See [Containerlab runtime](../manual/clabernetes/runtime.md) for details.

  Line 347: The `--no-topology-cr` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. By default, deploy persists the rendered topology as a c9s `Topology` resource and the Clabernetes manager compiles it into the `Node`, `Link`, and `NodeProfile` resources. With this flag, containerlab skips the `Topology` resource and compiles the topology client-side, creating and reconciling those resources directly.

  Line 355: The `--emit-crs` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. Instead of applying anything, deploy prints the Kubernetes manifests it would create to stdout as a multi-document YAML stream, so they can be saved, edited by hand, and applied with `kubectl`. The cluster is not contacted.

  Line 371: The `--image-pull-secret` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It sets the name of the image pull secret populated in the c9s `Topology` CR (`spec.imagePull.pullSecrets`), which the kubelet uses when pulling node images. The secret must exist in the lab namespace.

  Line 382: [clabernetes runtime](../manual/clabernetes/runtime.md) only. It sets

  Line 398: The `--no-persistence` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. By default, deploy enables persistence on the c9s `Topology` CR (`spec.deployment.persistence.enabled`), backing every node's artifact volume with a PersistentVolumeClaim so saved device configuration survives pod replacement -- the same contract the lab directory provides with local runtimes. This requires a dynamically provisionable (default) storage class in the cluster.


/source/base/docs/cmd/save.md:
  Line 11: [Containerlab runtime](../manual/clabernetes/runtime.md#save) for details.


/source/base/docs/cmd/exec.md:
  Line 16: See [Containerlab runtime](../manual/clabernetes/runtime.md#exec) for details.


/source/base/docs/cmd/logs.md:
  Line 5: The `logs` command shows the log of a lab node. With Docker and Podman it is the node container's log, with the [c9s runtime](../manual/clabernetes/runtime.md#logs) the log of the node's primary device container in its pod.


/source/base/mkdocs.yml:
  Line 89:           - manual/clabernetes/runtime.md

  Line 119:           - interfaces: cmd/inspect/interfaces.md

  Line 120:       - events: cmd/events.md


/source/head/mocks/mockruntime/runtime.go:
  Line 2: // Source: runtime/runtime.go

  Line 6: //	mockgen -package=mockruntime -source=runtime/runtime.go -destination=./mocks/mockruntime/runtime.go


/source/head/Makefile:
  Line 127: 	mockgen -package=mockruntime -source=runtime/runtime.go -destination=$(MOCKDIR)/mockruntime/runtime.go


/source/head/docs/rn/0.64.md:
  Line 7: In #2437 a new subcommand has been added to the inspect suite - [`clab inspect interfaces`](../cmd/inspect/interfaces.md) - that lists details of the interfaces of the given lab.


/source/head/docs/rn/0.78.md:
  Line 118: - Updated [`events`](../cmd/events.md) to report host-side stitch interfaces and their metadata, matching `inspect interfaces` for stitched links. #3319


/source/head/docs/rn/0.74.md:
  Line 29: The [`events`](../cmd/events.md) stream gets two improvements in this release. First, container exposed ports are now included in the event data, giving consumers full visibility into which ports are mapped for each container. Second, internal event processing was reworked to batch interface queries — replacing per-interface lookups with a single snapshot per tick and caching netem state — cutting CPU usage by up to 30%.


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


/source/head/docs/rn/0.72.md:
  Line 11: Containerlab 0.72 introduces a new [`clab events`](../cmd/events.md) command that provides real-time monitoring of your lab infrastructure. This feature streams lifecycle updates for all Containerlab resources and augments them with interface change notifications collected from container network namespaces.


/source/head/docs/rn/0.81.md:
  Line 53: The [`c9s` runtime](../manual/clabernetes/runtime.md)'s `deploy --dry-run` reported resource-level


/source/head/docs/rn/0.80.md:
  Line 21: Same `deploy`, `inspect`, `exec`, `events`, node lifecycle actions, and `destroy` commands are supported against the c9s runtime. See the [Containerlab runtime](../manual/clabernetes/runtime.md) documentation for more details.


/source/head/docs/manual/nodes.md:
  Line 731: See [c9s runtime](clabernetes/runtime.md) for details.


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


/source/head/docs/cmd/inspect/index.md:
  Line 13: With `--runtime c9s`, `inspect` reads Clabernetes `Topology` resources and their related kubernetes objects instead of local Docker containers. `inspect --all` lists c9s topologies across all namespaces, or in the `--namespace` override. The JSON output uses `<namespace>/<lab>/<node>` as `container_id` and adds the `namespace`, `pod`, `container`, `node_uid`, `exposed_ports` and `load_balancer_address` fields. See [Containerlab runtime](../../manual/clabernetes/runtime.md#inspect) for details.


/source/head/docs/cmd/events.md:
  Line 90: [c9s runtime manual](../manual/clabernetes/runtime.md#events) lists the

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

  Line 98: - [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md#events) - describes c9s events and how they map onto Docker events.


/source/head/docs/cmd/capture.md:
  Line 10: - **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).


/source/head/docs/cmd/destroy.md:
  Line 33: With `--runtime c9s`, `--cleanup` also deletes the lab's persistent node storage (the PersistentVolumeClaims holding saved device configuration) and then the lab namespace. A plain destroy keeps the claims, so the next deploy of the lab boots from the saved configuration. See [device state persistence](../manual/clabernetes/runtime.md#device-state-persistence).


/source/head/docs/cmd/redeploy.md:
  Line 114: The `--no-topology-cr` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It makes the deploy phase skip the c9s `Topology` resource and create the compiled `Node`, `Link`, and `NodeProfile` resources directly. See [`deploy --no-topology-cr`](deploy.md#no-topology-cr).

  Line 118: The `--image-pull-secret` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It sets the name of the image pull secret populated in the c9s `Topology` CR during the deploy phase. See [`deploy --image-pull-secret`](deploy.md#image-pull-secret).

  Line 122: The `--no-persistence` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It makes the deploy phase run the lab nodes on ephemeral storage instead of the default per-node persistent volumes. See [`deploy --no-persistence`](deploy.md#no-persistence).


/source/head/docs/cmd/save.md:
  Line 11: [Containerlab runtime](../manual/clabernetes/runtime.md#save) for details.


/source/head/docs/cmd/deploy.md:
  Line 261: `c9s` is a lab runtime, not a per-node container runtime. When it is selected, containerlab renders the topology and creates a Clabernetes `Topology` custom resource. See [Containerlab runtime](../manual/clabernetes/runtime.md) for details.

  Line 347: The `--no-topology-cr` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. By default, deploy persists the rendered topology as a c9s `Topology` resource and the Clabernetes manager compiles it into the `Node`, `Link`, and `NodeProfile` resources. With this flag, containerlab skips the `Topology` resource and compiles the topology client-side, creating and reconciling those resources directly.

  Line 355: The `--emit-crs` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. Instead of applying anything, deploy prints the Kubernetes manifests it would create to stdout as a multi-document YAML stream, so they can be saved, edited by hand, and applied with `kubectl`. The cluster is not contacted.

  Line 371: The `--image-pull-secret` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It sets the name of the image pull secret populated in the c9s `Topology` CR (`spec.imagePull.pullSecrets`), which the kubelet uses when pulling node images. The secret must exist in the lab namespace.


(Results truncated. Consider using a more specific path or pattern.)
Tool metadata
{
  "type": "tool",
  "id": "prt_1967a45f9001UVR1FYxc9bZR7j",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a36700010119sHZdt1ebQm",
  "callID": "call_73b6258071fe42768c159b48",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/diff.txt",
      "pattern": "runtime\\.go|events\\.md|interfaces\\.md|clabernetes/runtime\\.md"
    },
    "output": "Found 100 matches (more matches available)\n/source/diff.txt:\n  Line 860: diff --git a/core/labruntime.go b/core/labruntime.go\n\n  Line 862: --- a/core/labruntime.go\n\n  Line 863: +++ b/core/labruntime.go\n\n  Line 1074: diff --git a/docs/cmd/events.md b/docs/cmd/events.md\n\n  Line 1076: --- a/docs/cmd/events.md\n\n  Line 1077: +++ b/docs/cmd/events.md\n\n  Line 1100: +[c9s runtime manual](../manual/clabernetes/runtime.md#events) lists the\n\n  Line 1107:  - [`inspect interfaces`](inspect/interfaces.md) – produces a point-in-time view of the same interface details that `events` reports continuously.\n\n  Line 1108: -- [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md) - explains how c9s events differ from Docker events.\n\n  Line 1109: +- [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md#events) - describes c9s events and how they map onto Docker events.\n\n  Line 1111: diff --git a/docs/cmd/inspect/interfaces.md b/docs/cmd/inspect/interfaces.md\n\n  Line 1113: --- a/docs/cmd/inspect/interfaces.md\n\n  Line 1114: +++ b/docs/cmd/inspect/interfaces.md\n\n  Line 1121: -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  Line 1122: +With the [c9s runtime](../../manual/clabernetes/runtime.md#interface-events), the listing covers the interfaces a Docker container of the node has: the lab link interfaces of each running node (the ones [`capture`](../capture.md) accepts) with the alias the topology used, the management interface `eth0` and the loopback `lo`, with the MAC address, index, MTU and operational state read in the node's device container. The pod's own interfaces are not listed. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields and values (`veth`/`device`, netlink state names) are the same as with Docker. `eth0` and `lo` cannot be captured on c9s.\n\n  Line 1128: diff --git a/docs/manual/clabernetes/runtime.md b/docs/manual/clabernetes/runtime.md\n\n  Line 1130: --- a/docs/manual/clabernetes/runtime.md\n\n  Line 1131: +++ b/docs/manual/clabernetes/runtime.md\n\n  Line 4631: diff --git a/labruntime/runtime.go b/labruntime/runtime.go\n\n  Line 4633: --- a/labruntime/runtime.go\n\n  Line 4634: +++ b/labruntime/runtime.go\n\n\n/source/manifest.json:\n  Line 21:       \"path\": \"core/labruntime.go\"\n\n  Line 29:       \"path\": \"docs/cmd/events.md\"\n\n  Line 33:       \"path\": \"docs/cmd/inspect/interfaces.md\"\n\n  Line 37:       \"path\": \"docs/manual/clabernetes/runtime.md\"\n\n  Line 105:       \"path\": \"labruntime/runtime.go\"\n\n  Line 139:       \"path\": \"core/labruntime.go\",\n\n  Line 145:       \"path\": \"docs/cmd/events.md\",\n\n  Line 151:       \"path\": \"docs/cmd/inspect/interfaces.md\",\n\n  Line 157:       \"path\": \"docs/manual/clabernetes/runtime.md\",\n\n  Line 259:       \"path\": \"labruntime/runtime.go\",\n\n  Line 4417:       \"path\": \"links/endpoint_runtime.go\",\n\n  Line 4651:       \"path\": \"mocks/mockruntime/runtime.go\",\n\n  Line 6463:       \"path\": \"runtime/runtime.go\",\n\n  Line 8215:       \"path\": \"core/labruntime.go\",\n\n  Line 8221:       \"path\": \"docs/cmd/events.md\",\n\n  Line 8227:       \"path\": \"docs/cmd/inspect/interfaces.md\",\n\n  Line 8233:       \"path\": \"docs/manual/clabernetes/runtime.md\",\n\n  Line 8323:       \"path\": \"labruntime/runtime.go\",\n\n  Line 12481:       \"path\": \"links/endpoint_runtime.go\",\n\n  Line 12715:       \"path\": \"mocks/mockruntime/runtime.go\",\n\n  Line 14527:       \"path\": \"runtime/runtime.go\",\n\n\n/source/base/mocks/mockruntime/runtime.go:\n  Line 2: // Source: runtime/runtime.go\n\n  Line 6: //\tmockgen -package=mockruntime -source=runtime/runtime.go -destination=./mocks/mockruntime/runtime.go\n\n\n/source/base/Makefile:\n  Line 127: \tmockgen -package=mockruntime -source=runtime/runtime.go -destination=$(MOCKDIR)/mockruntime/runtime.go\n\n\n/source/base/docs/manual/nodes.md:\n  Line 731: See [c9s runtime](clabernetes/runtime.md) for details.\n\n\n/source/base/docs/rn/0.78.md:\n  Line 118: - Updated [`events`](../cmd/events.md) to report host-side stitch interfaces and their metadata, matching `inspect interfaces` for stitched links. #3319\n\n\n/source/base/docs/rn/0.74.md:\n  Line 29: The [`events`](../cmd/events.md) stream gets two improvements in this release. First, container exposed ports are now included in the event data, giving consumers full visibility into which ports are mapped for each container. Second, internal event processing was reworked to batch interface queries — replacing per-interface lookups with a single snapshot per tick and caching netem state — cutting CPU usage by up to 30%.\n\n\n/source/base/docs/rn/0.73.md:\n  Line 41: Building on the real-time events streaming introduced in 0.72, the [`events`](../cmd/events.md) command now also tracks network emulation (netem) impairment changes. When you apply delay, jitter, packet loss, or rate limiting via `containerlab tools netem set`, these changes appear as interface update events in real time -- giving you full observability into link impairment changes alongside container and interface lifecycle events.\n\n\n/source/base/docs/rn/0.64.md:\n  Line 7: In #2437 a new subcommand has been added to the inspect suite - [`clab inspect interfaces`](../cmd/inspect/interfaces.md) - that lists details of the interfaces of the given lab.\n\n\n/source/base/docs/rn/0.72.md:\n  Line 11: Containerlab 0.72 introduces a new [`clab events`](../cmd/events.md) command that provides real-time monitoring of your lab infrastructure. This feature streams lifecycle updates for all Containerlab resources and augments them with interface change notifications collected from container network namespaces.\n\n\n/source/base/docs/rn/0.81.md:\n  Line 53: The [`c9s` runtime](../manual/clabernetes/runtime.md)'s `deploy --dry-run` reported resource-level\n\n\n/source/base/docs/rn/0.80.md:\n  Line 21: Same `deploy`, `inspect`, `exec`, `events`, node lifecycle actions, and `destroy` commands are supported against the c9s runtime. See the [Containerlab runtime](../manual/clabernetes/runtime.md) documentation for more details.\n\n\n/source/base/docs/cmd/inspect/interfaces.md:\n  Line 8: 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\n/source/base/docs/cmd/inspect/index.md:\n  Line 13: With `--runtime c9s`, `inspect` reads Clabernetes `Topology` resources and their related kubernetes objects instead of local Docker containers. `inspect --all` lists c9s topologies across all namespaces, or in the `--namespace` override. The JSON output uses `<namespace>/<lab>/<node>` as `container_id` and adds the `namespace`, `pod`, `container`, `node_uid`, `exposed_ports` and `load_balancer_address` fields. See [Containerlab runtime](../../manual/clabernetes/runtime.md#inspect) for details.\n\n\n/source/base/docs/cmd/capture.md:\n  Line 10: - **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).\n\n\n/source/base/docs/cmd/events.md:\n  Line 91: - [`inspect interfaces`](inspect/interfaces.md) – produces a point-in-time view of the same interface details that `events` reports continuously.\n\n  Line 92: - [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md) - explains how c9s events differ from Docker events.\n\n\n/source/base/docs/cmd/destroy.md:\n  Line 33: With `--runtime c9s`, `--cleanup` also deletes the lab's persistent node storage (the PersistentVolumeClaims holding saved device configuration) and then the lab namespace. A plain destroy keeps the claims, so the next deploy of the lab boots from the saved configuration. See [device state persistence](../manual/clabernetes/runtime.md#device-state-persistence).\n\n\n/source/base/docs/cmd/redeploy.md:\n  Line 114: The `--no-topology-cr` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It makes the deploy phase skip the c9s `Topology` resource and create the compiled `Node`, `Link`, and `NodeProfile` resources directly. See [`deploy --no-topology-cr`](deploy.md#no-topology-cr).\n\n  Line 118: The `--image-pull-secret` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It sets the name of the image pull secret populated in the c9s `Topology` CR during the deploy phase. See [`deploy --image-pull-secret`](deploy.md#image-pull-secret).\n\n  Line 122: The `--no-persistence` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It makes the deploy phase run the lab nodes on ephemeral storage instead of the default per-node persistent volumes. See [`deploy --no-persistence`](deploy.md#no-persistence).\n\n\n/source/base/docs/cmd/deploy.md:\n  Line 261: `c9s` is a lab runtime, not a per-node container runtime. When it is selected, containerlab renders the topology and creates a Clabernetes `Topology` custom resource. See [Containerlab runtime](../manual/clabernetes/runtime.md) for details.\n\n  Line 347: The `--no-topology-cr` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. By default, deploy persists the rendered topology as a c9s `Topology` resource and the Clabernetes manager compiles it into the `Node`, `Link`, and `NodeProfile` resources. With this flag, containerlab skips the `Topology` resource and compiles the topology client-side, creating and reconciling those resources directly.\n\n  Line 355: The `--emit-crs` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. Instead of applying anything, deploy prints the Kubernetes manifests it would create to stdout as a multi-document YAML stream, so they can be saved, edited by hand, and applied with `kubectl`. The cluster is not contacted.\n\n  Line 371: The `--image-pull-secret` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It sets the name of the image pull secret populated in the c9s `Topology` CR (`spec.imagePull.pullSecrets`), which the kubelet uses when pulling node images. The secret must exist in the lab namespace.\n\n  Line 382: [clabernetes runtime](../manual/clabernetes/runtime.md) only. It sets\n\n  Line 398: The `--no-persistence` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. By default, deploy enables persistence on the c9s `Topology` CR (`spec.deployment.persistence.enabled`), backing every node's artifact volume with a PersistentVolumeClaim so saved device configuration survives pod replacement -- the same contract the lab directory provides with local runtimes. This requires a dynamically provisionable (default) storage class in the cluster.\n\n\n/source/base/docs/cmd/save.md:\n  Line 11: [Containerlab runtime](../manual/clabernetes/runtime.md#save) for details.\n\n\n/source/base/docs/cmd/exec.md:\n  Line 16: See [Containerlab runtime](../manual/clabernetes/runtime.md#exec) for details.\n\n\n/source/base/docs/cmd/logs.md:\n  Line 5: The `logs` command shows the log of a lab node. With Docker and Podman it is the node container's log, with the [c9s runtime](../manual/clabernetes/runtime.md#logs) the log of the node's primary device container in its pod.\n\n\n/source/base/mkdocs.yml:\n  Line 89:           - manual/clabernetes/runtime.md\n\n  Line 119:           - interfaces: cmd/inspect/interfaces.md\n\n  Line 120:       - events: cmd/events.md\n\n\n/source/head/mocks/mockruntime/runtime.go:\n  Line 2: // Source: runtime/runtime.go\n\n  Line 6: //\tmockgen -package=mockruntime -source=runtime/runtime.go -destination=./mocks/mockruntime/runtime.go\n\n\n/source/head/Makefile:\n  Line 127: \tmockgen -package=mockruntime -source=runtime/runtime.go -destination=$(MOCKDIR)/mockruntime/runtime.go\n\n\n/source/head/docs/rn/0.64.md:\n  Line 7: In #2437 a new subcommand has been added to the inspect suite - [`clab inspect interfaces`](../cmd/inspect/interfaces.md) - that lists details of the interfaces of the given lab.\n\n\n/source/head/docs/rn/0.78.md:\n  Line 118: - Updated [`events`](../cmd/events.md) to report host-side stitch interfaces and their metadata, matching `inspect interfaces` for stitched links. #3319\n\n\n/source/head/docs/rn/0.74.md:\n  Line 29: The [`events`](../cmd/events.md) stream gets two improvements in this release. First, container exposed ports are now included in the event data, giving consumers full visibility into which ports are mapped for each container. Second, internal event processing was reworked to batch interface queries — replacing per-interface lookups with a single snapshot per tick and caching netem state — cutting CPU usage by up to 30%.\n\n\n/source/head/docs/rn/0.73.md:\n  Line 41: Building on the real-time events streaming introduced in 0.72, the [`events`](../cmd/events.md) command now also tracks network emulation (netem) impairment changes. When you apply delay, jitter, packet loss, or rate limiting via `containerlab tools netem set`, these changes appear as interface update events in real time -- giving you full observability into link impairment changes alongside container and interface lifecycle events.\n\n\n/source/head/docs/rn/0.72.md:\n  Line 11: Containerlab 0.72 introduces a new [`clab events`](../cmd/events.md) command that provides real-time monitoring of your lab infrastructure. This feature streams lifecycle updates for all Containerlab resources and augments them with interface change notifications collected from container network namespaces.\n\n\n/source/head/docs/rn/0.81.md:\n  Line 53: The [`c9s` runtime](../manual/clabernetes/runtime.md)'s `deploy --dry-run` reported resource-level\n\n\n/source/head/docs/rn/0.80.md:\n  Line 21: Same `deploy`, `inspect`, `exec`, `events`, node lifecycle actions, and `destroy` commands are supported against the c9s runtime. See the [Containerlab runtime](../manual/clabernetes/runtime.md) documentation for more details.\n\n\n/source/head/docs/manual/nodes.md:\n  Line 731: See [c9s runtime](clabernetes/runtime.md) for details.\n\n\n/source/head/docs/cmd/inspect/interfaces.md:\n  Line 8: With the [c9s runtime](../../manual/clabernetes/runtime.md#interface-events), the listing covers the interfaces a Docker container of the node has: the lab link interfaces of each running node (the ones [`capture`](../capture.md) accepts) with the alias the topology used, the management interface `eth0` and the loopback `lo`, with the MAC address, index, MTU and operational state read in the node's device container. The pod's own interfaces are not listed. The node names follow `inspect` (`<lab>-<node>`), and the JSON fields and values (`veth`/`device`, netlink state names) are the same as with Docker. `eth0` and `lo` cannot be captured on c9s.\n\n\n/source/head/docs/cmd/inspect/index.md:\n  Line 13: With `--runtime c9s`, `inspect` reads Clabernetes `Topology` resources and their related kubernetes objects instead of local Docker containers. `inspect --all` lists c9s topologies across all namespaces, or in the `--namespace` override. The JSON output uses `<namespace>/<lab>/<node>` as `container_id` and adds the `namespace`, `pod`, `container`, `node_uid`, `exposed_ports` and `load_balancer_address` fields. See [Containerlab runtime](../../manual/clabernetes/runtime.md#inspect) for details.\n\n\n/source/head/docs/cmd/events.md:\n  Line 90: [c9s runtime manual](../manual/clabernetes/runtime.md#events) lists the\n\n  Line 97: - [`inspect interfaces`](inspect/interfaces.md) – produces a point-in-time view of the same interface details that `events` reports continuously.\n\n  Line 98: - [Clabernetes containerlab runtime](../manual/clabernetes/runtime.md#events) - describes c9s events and how they map onto Docker events.\n\n\n/source/head/docs/cmd/capture.md:\n  Line 10: - **c9s**: the `clabwire` sidecar of each node's pod captures the packets; see the [c9s runtime](../manual/clabernetes/runtime.md#packet-capture).\n\n\n/source/head/docs/cmd/destroy.md:\n  Line 33: With `--runtime c9s`, `--cleanup` also deletes the lab's persistent node storage (the PersistentVolumeClaims holding saved device configuration) and then the lab namespace. A plain destroy keeps the claims, so the next deploy of the lab boots from the saved configuration. See [device state persistence](../manual/clabernetes/runtime.md#device-state-persistence).\n\n\n/source/head/docs/cmd/redeploy.md:\n  Line 114: The `--no-topology-cr` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It makes the deploy phase skip the c9s `Topology` resource and create the compiled `Node`, `Link`, and `NodeProfile` resources directly. See [`deploy --no-topology-cr`](deploy.md#no-topology-cr).\n\n  Line 118: The `--image-pull-secret` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It sets the name of the image pull secret populated in the c9s `Topology` CR during the deploy phase. See [`deploy --image-pull-secret`](deploy.md#image-pull-secret).\n\n  Line 122: The `--no-persistence` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It makes the deploy phase run the lab nodes on ephemeral storage instead of the default per-node persistent volumes. See [`deploy --no-persistence`](deploy.md#no-persistence).\n\n\n/source/head/docs/cmd/save.md:\n  Line 11: [Containerlab runtime](../manual/clabernetes/runtime.md#save) for details.\n\n\n/source/head/docs/cmd/deploy.md:\n  Line 261: `c9s` is a lab runtime, not a per-node container runtime. When it is selected, containerlab renders the topology and creates a Clabernetes `Topology` custom resource. See [Containerlab runtime](../manual/clabernetes/runtime.md) for details.\n\n  Line 347: The `--no-topology-cr` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. By default, deploy persists the rendered topology as a c9s `Topology` resource and the Clabernetes manager compiles it into the `Node`, `Link`, and `NodeProfile` resources. With this flag, containerlab skips the `Topology` resource and compiles the topology client-side, creating and reconciling those resources directly.\n\n  Line 355: The `--emit-crs` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. Instead of applying anything, deploy prints the Kubernetes manifests it would create to stdout as a multi-document YAML stream, so they can be saved, edited by hand, and applied with `kubectl`. The cluster is not contacted.\n\n  Line 371: The `--image-pull-secret` flag applies to the [clabernetes runtime](../manual/clabernetes/runtime.md) only. It sets the name of the image pull secret populated in the c9s `Topology` CR (`spec.imagePull.pullSecrets`), which the kubelet uses when pulling node images. The secret must exist in the lab namespace.\n\n\n(Results truncated. Consider using a more specific path or pattern.)",
    "title": "runtime\\.go|events\\.md|interfaces\\.md|clabernetes/runtime\\.md",
    "metadata": {
      "matches": 100,
      "truncated": true
    },
    "time": {
      "start": 1793525958142,
      "end": 1793525958190
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/labruntime/clabernetes/lifecycle.go",
  "limit": 110,
  "offset": 440
}

Output

<path>/source/head/labruntime/clabernetes/lifecycle.go</path>
<type>file</type>
<content>
440: 	}
441: 
442: 	return 0, nil
443: }
444: 
445: func (r *Runtime) Inspect(
446: 	ctx context.Context,
447: 	req clablabruntime.InspectRequest,
448: ) (*clablabruntime.LabState, error) {
449: 	r, connErr := r.connect(ctx, req.Identity)
450: 	if connErr != nil {
451: 		return nil, connErr
452: 	}
453: 
454: 	if req.Name == "" {
455: 		return nil, fmt.Errorf("topology name is required")
456: 	}
457: 
458: 	namespace, err := r.namespaceForLab(req.Name, req.Namespace)
459: 	if err != nil {
460: 		return nil, err
461: 	}
462: 	obj, err := r.client.Resource(topologyGVR).Namespace(namespace).
463: 		Get(ctx, req.Name, metav1.GetOptions{})
464: 	if err != nil && !apierrors.IsNotFound(err) {
465: 		return nil, fmt.Errorf("failed to inspect clabernetes topology %s/%s: %w",
466: 			namespace, req.Name, err)
467: 	}
468: 
469: 	var state *clablabruntime.LabState
470: 	if err == nil {
471: 		state = stateFromTopology(obj, namespace)
472: 	} else {
473: 		nodes, listErr := r.nodesForTopology(ctx, req.Name, namespace)
474: 		if listErr != nil {
475: 			return nil, listErr
476: 		}
477: 		if len(nodes.Items) == 0 {
478: 			return nil, &labNotFoundError{namespace: namespace, name: req.Name}
479: 		}
480: 		state = stateFromNodeResources(req.Name, namespace, nodes.Items)
481: 	}
482: 
483: 	if err := r.enrichState(ctx, state); err != nil {
484: 		log.Debug("failed to enrich C9s lab state", "error", err)
485: 	}
486: 
487: 	return state, nil
488: }
489: 
490: // labNotFoundError reports a lab without a Topology or Node resource.
491: type labNotFoundError struct {
492: 	namespace string
493: 	name      string
494: }
495: 
496: func (e *labNotFoundError) Error() string {
497: 	return fmt.Sprintf("c9s lab %s/%s was not found", e.namespace, e.name)
498: }
499: 
500: func (r *Runtime) LabExists(
501: 	ctx context.Context,
502: 	req clablabruntime.InspectRequest,
503: ) (bool, error) {
504: 	r, connErr := r.connect(ctx, req.Identity)
505: 	if connErr != nil {
506: 		return false, connErr
507: 	}
508: 
509: 	if req.Name == "" {
510: 		return false, fmt.Errorf("topology name is required")
511: 	}
512: 
513: 	namespace, err := r.namespaceForLab(req.Name, req.Namespace)
514: 	if err != nil {
515: 		return false, err
516: 	}
517: 	_, err = r.client.Resource(topologyGVR).Namespace(namespace).
518: 		Get(ctx, req.Name, metav1.GetOptions{})
519: 	switch {
520: 	case err == nil:
521: 		return true, nil
522: 	case !apierrors.IsNotFound(err):
523: 		return false, fmt.Errorf("failed to get clabernetes topology %s/%s: %w",
524: 			namespace, req.Name, err)
525: 	}
526: 
527: 	return r.primitiveLabExists(ctx, req.Name, namespace)
528: }
529: 
530: func (r *Runtime) List(
531: 	ctx context.Context,
532: 	req clablabruntime.ListRequest,
533: ) ([]*clablabruntime.LabState, error) {
534: 	r, connErr := r.connect(ctx, req.Identity)
535: 	if connErr != nil {
536: 		return nil, connErr
537: 	}
538: 
539: 	namespace := r.listNamespace(req.Namespace, req.AllNamespaces)
540: 
541: 	topologyList, err := r.client.Resource(topologyGVR).Namespace(namespace).
542: 		List(ctx, metav1.ListOptions{})
543: 	if err != nil {
544: 		return nil, fmt.Errorf("failed to list clabernetes topologies: %w", err)
545: 	}
546: 
547: 	statesByLab := make(map[string]*clablabruntime.LabState, len(topologyList.Items))
548: 	for idx := range topologyList.Items {
549: 		state := stateFromTopology(&topologyList.Items[idx], namespace)

(Showing lines 440-549 of 914. Use offset=550 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1967a46800014h3IPF1G5BzV99",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a36700010119sHZdt1ebQm",
  "callID": "call_c436b62b037c4749ba6bd0c2",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/labruntime/clabernetes/lifecycle.go",
      "limit": 110,
      "offset": 440
    },
    "output": "<path>/source/head/labruntime/clabernetes/lifecycle.go</path>\n<type>file</type>\n<content>\n440: \t}\n441: \n442: \treturn 0, nil\n443: }\n444: \n445: func (r *Runtime) Inspect(\n446: \tctx context.Context,\n447: \treq clablabruntime.InspectRequest,\n448: ) (*clablabruntime.LabState, error) {\n449: \tr, connErr := r.connect(ctx, req.Identity)\n450: \tif connErr != nil {\n451: \t\treturn nil, connErr\n452: \t}\n453: \n454: \tif req.Name == \"\" {\n455: \t\treturn nil, fmt.Errorf(\"topology name is required\")\n456: \t}\n457: \n458: \tnamespace, err := r.namespaceForLab(req.Name, req.Namespace)\n459: \tif err != nil {\n460: \t\treturn nil, err\n461: \t}\n462: \tobj, err := r.client.Resource(topologyGVR).Namespace(namespace).\n463: \t\tGet(ctx, req.Name, metav1.GetOptions{})\n464: \tif err != nil && !apierrors.IsNotFound(err) {\n465: \t\treturn nil, fmt.Errorf(\"failed to inspect clabernetes topology %s/%s: %w\",\n466: \t\t\tnamespace, req.Name, err)\n467: \t}\n468: \n469: \tvar state *clablabruntime.LabState\n470: \tif err == nil {\n471: \t\tstate = stateFromTopology(obj, namespace)\n472: \t} else {\n473: \t\tnodes, listErr := r.nodesForTopology(ctx, req.Name, namespace)\n474: \t\tif listErr != nil {\n475: \t\t\treturn nil, listErr\n476: \t\t}\n477: \t\tif len(nodes.Items) == 0 {\n478: \t\t\treturn nil, &labNotFoundError{namespace: namespace, name: req.Name}\n479: \t\t}\n480: \t\tstate = stateFromNodeResources(req.Name, namespace, nodes.Items)\n481: \t}\n482: \n483: \tif err := r.enrichState(ctx, state); err != nil {\n484: \t\tlog.Debug(\"failed to enrich C9s lab state\", \"error\", err)\n485: \t}\n486: \n487: \treturn state, nil\n488: }\n489: \n490: // labNotFoundError reports a lab without a Topology or Node resource.\n491: type labNotFoundError struct {\n492: \tnamespace string\n493: \tname      string\n494: }\n495: \n496: func (e *labNotFoundError) Error() string {\n497: \treturn fmt.Sprintf(\"c9s lab %s/%s was not found\", e.namespace, e.name)\n498: }\n499: \n500: func (r *Runtime) LabExists(\n501: \tctx context.Context,\n502: \treq clablabruntime.InspectRequest,\n503: ) (bool, error) {\n504: \tr, connErr := r.connect(ctx, req.Identity)\n505: \tif connErr != nil {\n506: \t\treturn false, connErr\n507: \t}\n508: \n509: \tif req.Name == \"\" {\n510: \t\treturn false, fmt.Errorf(\"topology name is required\")\n511: \t}\n512: \n513: \tnamespace, err := r.namespaceForLab(req.Name, req.Namespace)\n514: \tif err != nil {\n515: \t\treturn false, err\n516: \t}\n517: \t_, err = r.client.Resource(topologyGVR).Namespace(namespace).\n518: \t\tGet(ctx, req.Name, metav1.GetOptions{})\n519: \tswitch {\n520: \tcase err == nil:\n521: \t\treturn true, nil\n522: \tcase !apierrors.IsNotFound(err):\n523: \t\treturn false, fmt.Errorf(\"failed to get clabernetes topology %s/%s: %w\",\n524: \t\t\tnamespace, req.Name, err)\n525: \t}\n526: \n527: \treturn r.primitiveLabExists(ctx, req.Name, namespace)\n528: }\n529: \n530: func (r *Runtime) List(\n531: \tctx context.Context,\n532: \treq clablabruntime.ListRequest,\n533: ) ([]*clablabruntime.LabState, error) {\n534: \tr, connErr := r.connect(ctx, req.Identity)\n535: \tif connErr != nil {\n536: \t\treturn nil, connErr\n537: \t}\n538: \n539: \tnamespace := r.listNamespace(req.Namespace, req.AllNamespaces)\n540: \n541: \ttopologyList, err := r.client.Resource(topologyGVR).Namespace(namespace).\n542: \t\tList(ctx, metav1.ListOptions{})\n543: \tif err != nil {\n544: \t\treturn nil, fmt.Errorf(\"failed to list clabernetes topologies: %w\", err)\n545: \t}\n546: \n547: \tstatesByLab := make(map[string]*clablabruntime.LabState, len(topologyList.Items))\n548: \tfor idx := range topologyList.Items {\n549: \t\tstate := stateFromTopology(&topologyList.Items[idx], namespace)\n\n(Showing lines 440-549 of 914. Use offset=550 to continue.)\n</content>",
    "title": "source/head/labruntime/clabernetes/lifecycle.go",
    "metadata": {
      "preview": "\t}\n\n\treturn 0, nil\n}\n\nfunc (r *Runtime) Inspect(\n\tctx context.Context,\n\treq clablabruntime.InspectRequest,\n) (*clablabruntime.LabState, error) {\n\tr, connErr := r.connect(ctx, req.Identity)\n\tif connErr != nil {\n\t\treturn nil, connErr\n\t}\n\n\tif req.Name == \"\" {\n\t\treturn nil, fmt.Errorf(\"topology name is required\")\n\t}\n\n\tnamespace, err := r.namespaceForLab(req.Name, req.Namespace)\n\tif err != nil {",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/labruntime/clabernetes/lifecycle.go",
        "text": "\t}\n\n\treturn 0, nil\n}\n\nfunc (r *Runtime) Inspect(\n\tctx context.Context,\n\treq clablabruntime.InspectRequest,\n) (*clablabruntime.LabState, error) {\n\tr, connErr := r.connect(ctx, req.Identity)\n\tif connErr != nil {\n\t\treturn nil, connErr\n\t}\n\n\tif req.Name == \"\" {\n\t\treturn nil, fmt.Errorf(\"topology name is required\")\n\t}\n\n\tnamespace, err := r.namespaceForLab(req.Name, req.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tobj, err := r.client.Resource(topologyGVR).Namespace(namespace).\n\t\tGet(ctx, req.Name, metav1.GetOptions{})\n\tif err != nil && !apierrors.IsNotFound(err) {\n\t\treturn nil, fmt.Errorf(\"failed to inspect clabernetes topology %s/%s: %w\",\n\t\t\tnamespace, req.Name, err)\n\t}\n\n\tvar state *clablabruntime.LabState\n\tif err == nil {\n\t\tstate = stateFromTopology(obj, namespace)\n\t} else {\n\t\tnodes, listErr := r.nodesForTopology(ctx, req.Name, namespace)\n\t\tif listErr != nil {\n\t\t\treturn nil, listErr\n\t\t}\n\t\tif len(nodes.Items) == 0 {\n\t\t\treturn nil, &labNotFoundError{namespace: namespace, name: req.Name}\n\t\t}\n\t\tstate = stateFromNodeResources(req.Name, namespace, nodes.Items)\n\t}\n\n\tif err := r.enrichState(ctx, state); err != nil {\n\t\tlog.Debug(\"failed to enrich C9s lab state\", \"error\", err)\n\t}\n\n\treturn state, nil\n}\n\n// labNotFoundError reports a lab without a Topology or Node resource.\ntype labNotFoundError struct {\n\tnamespace string\n\tname      string\n}\n\nfunc (e *labNotFoundError) Error() string {\n\treturn fmt.Sprintf(\"c9s lab %s/%s was not found\", e.namespace, e.name)\n}\n\nfunc (r *Runtime) LabExists(\n\tctx context.Context,\n\treq clablabruntime.InspectRequest,\n) (bool, error) {\n\tr, connErr := r.connect(ctx, req.Identity)\n\tif connErr != nil {\n\t\treturn false, connErr\n\t}\n\n\tif req.Name == \"\" {\n\t\treturn false, fmt.Errorf(\"topology name is required\")\n\t}\n\n\tnamespace, err := r.namespaceForLab(req.Name, req.Namespace)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t_, err = r.client.Resource(topologyGVR).Namespace(namespace).\n\t\tGet(ctx, req.Name, metav1.GetOptions{})\n\tswitch {\n\tcase err == nil:\n\t\treturn true, nil\n\tcase !apierrors.IsNotFound(err):\n\t\treturn false, fmt.Errorf(\"failed to get clabernetes topology %s/%s: %w\",\n\t\t\tnamespace, req.Name, err)\n\t}\n\n\treturn r.primitiveLabExists(ctx, req.Name, namespace)\n}\n\nfunc (r *Runtime) List(\n\tctx context.Context,\n\treq clablabruntime.ListRequest,\n) ([]*clablabruntime.LabState, error) {\n\tr, connErr := r.connect(ctx, req.Identity)\n\tif connErr != nil {\n\t\treturn nil, connErr\n\t}\n\n\tnamespace := r.listNamespace(req.Namespace, req.AllNamespaces)\n\n\ttopologyList, err := r.client.Resource(topologyGVR).Namespace(namespace).\n\t\tList(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list clabernetes topologies: %w\", err)\n\t}\n\n\tstatesByLab := make(map[string]*clablabruntime.LabState, len(topologyList.Items))\n\tfor idx := range topologyList.Items {\n\t\tstate := stateFromTopology(&topologyList.Items[idx], namespace)",
        "lineStart": 440,
        "lineEnd": 549,
        "totalLines": 914,
        "truncated": true
      }
    },
    "time": {
      "start": 1793525958276,
      "end": 1793525958283
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/core/events/stream.go",
  "limit": 75,
  "offset": 55
}

Output

<path>/source/head/core/events/stream.go</path>
<type>file</type>
<content>
55: 	if err != nil {
56: 		return fmt.Errorf("failed to list containers: %w", err)
57: 	}
58: 
59: 	if opts.IncludeInitialState {
60: 		go emitContainerSnapshots(ctx, containers, eventCh)
61: 	}
62: 
63: 	for idx := range containers {
64: 		container := containers[idx]
65: 		if !isRunningContainer(&container) {
66: 			continue
67: 		}
68: 
69: 		registry.Start(&container)
70: 	}
71: 
72: 	streamOpts := clabruntime.EventStreamOptions{
73: 		Labels: map[string]string{
74: 			clabconstants.Containerlab: "",
75: 		},
76: 	}
77: 
78: 	runtimeEvents, runtimeErrs, err := runtime.StreamEvents(ctx, streamOpts)
79: 	if err != nil {
80: 		return fmt.Errorf("failed to stream events for runtime %q: %w", opts.Runtime, err)
81: 	}
82: 
83: 	errCh := make(chan error, 1)
84: 	go forwardRuntimeEvents(ctx, runtime, registry, runtimeEvents, runtimeErrs, eventCh, errCh)
85: 
86: 	runtimeErrors := errCh
87: 
88: 	for {
89: 		select {
90: 		case ev := <-eventCh:
91: 			if err := printer(ev); err != nil {
92: 				log.Debugf("failed to write event: %v", err)
93: 			}
94: 		case err, ok := <-runtimeErrors:
95: 			if !ok {
96: 				runtimeErrors = nil
97: 
98: 				continue
99: 			}
100: 
101: 			if err != nil && !errors.Is(err, context.Canceled) {
102: 				return err
103: 			}
104: 		case <-ctx.Done():
105: 			return nil
106: 		}
107: 	}
108: }
109: 
110: func streamLabRuntimeEvents(ctx context.Context, clab *clabcore.CLab, opts Options) error {
111: 	printer, err := newFormatter(opts.Format, opts.writer())
112: 	if err != nil {
113: 		return err
114: 	}
115: 
116: 	runtimeEvents, runtimeErrs, err := clab.LabRuntime.StreamEvents(
117: 		ctx,
118: 		labRuntimeEventStreamRequest(clab.Config.Name, clab.LabRuntimeIdentity(), opts),
119: 	)
120: 	if err != nil {
121: 		return fmt.Errorf("failed to stream events for lab runtime %q: %w", opts.Runtime, err)
122: 	}
123: 
124: 	for runtimeEvents != nil || runtimeErrs != nil {
125: 		select {
126: 		case ev, ok := <-runtimeEvents:
127: 			if !ok {
128: 				runtimeEvents = nil
129: 

(Showing lines 55-129 of 652. Use offset=130 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1967a46d6001m8Im1iOSspdZuT",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a36700010119sHZdt1ebQm",
  "callID": "call_4267387a11e04f3e834bdafb",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/core/events/stream.go",
      "limit": 75,
      "offset": 55
    },
    "output": "<path>/source/head/core/events/stream.go</path>\n<type>file</type>\n<content>\n55: \tif err != nil {\n56: \t\treturn fmt.Errorf(\"failed to list containers: %w\", err)\n57: \t}\n58: \n59: \tif opts.IncludeInitialState {\n60: \t\tgo emitContainerSnapshots(ctx, containers, eventCh)\n61: \t}\n62: \n63: \tfor idx := range containers {\n64: \t\tcontainer := containers[idx]\n65: \t\tif !isRunningContainer(&container) {\n66: \t\t\tcontinue\n67: \t\t}\n68: \n69: \t\tregistry.Start(&container)\n70: \t}\n71: \n72: \tstreamOpts := clabruntime.EventStreamOptions{\n73: \t\tLabels: map[string]string{\n74: \t\t\tclabconstants.Containerlab: \"\",\n75: \t\t},\n76: \t}\n77: \n78: \truntimeEvents, runtimeErrs, err := runtime.StreamEvents(ctx, streamOpts)\n79: \tif err != nil {\n80: \t\treturn fmt.Errorf(\"failed to stream events for runtime %q: %w\", opts.Runtime, err)\n81: \t}\n82: \n83: \terrCh := make(chan error, 1)\n84: \tgo forwardRuntimeEvents(ctx, runtime, registry, runtimeEvents, runtimeErrs, eventCh, errCh)\n85: \n86: \truntimeErrors := errCh\n87: \n88: \tfor {\n89: \t\tselect {\n90: \t\tcase ev := <-eventCh:\n91: \t\t\tif err := printer(ev); err != nil {\n92: \t\t\t\tlog.Debugf(\"failed to write event: %v\", err)\n93: \t\t\t}\n94: \t\tcase err, ok := <-runtimeErrors:\n95: \t\t\tif !ok {\n96: \t\t\t\truntimeErrors = nil\n97: \n98: \t\t\t\tcontinue\n99: \t\t\t}\n100: \n101: \t\t\tif err != nil && !errors.Is(err, context.Canceled) {\n102: \t\t\t\treturn err\n103: \t\t\t}\n104: \t\tcase <-ctx.Done():\n105: \t\t\treturn nil\n106: \t\t}\n107: \t}\n108: }\n109: \n110: func streamLabRuntimeEvents(ctx context.Context, clab *clabcore.CLab, opts Options) error {\n111: \tprinter, err := newFormatter(opts.Format, opts.writer())\n112: \tif err != nil {\n113: \t\treturn err\n114: \t}\n115: \n116: \truntimeEvents, runtimeErrs, err := clab.LabRuntime.StreamEvents(\n117: \t\tctx,\n118: \t\tlabRuntimeEventStreamRequest(clab.Config.Name, clab.LabRuntimeIdentity(), opts),\n119: \t)\n120: \tif err != nil {\n121: \t\treturn fmt.Errorf(\"failed to stream events for lab runtime %q: %w\", opts.Runtime, err)\n122: \t}\n123: \n124: \tfor runtimeEvents != nil || runtimeErrs != nil {\n125: \t\tselect {\n126: \t\tcase ev, ok := <-runtimeEvents:\n127: \t\t\tif !ok {\n128: \t\t\t\truntimeEvents = nil\n129: \n\n(Showing lines 55-129 of 652. Use offset=130 to continue.)\n</content>",
    "title": "source/head/core/events/stream.go",
    "metadata": {
      "preview": "\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to list containers: %w\", err)\n\t}\n\n\tif opts.IncludeInitialState {\n\t\tgo emitContainerSnapshots(ctx, containers, eventCh)\n\t}\n\n\tfor idx := range containers {\n\t\tcontainer := containers[idx]\n\t\tif !isRunningContainer(&container) {\n\t\t\tcontinue\n\t\t}\n\n\t\tregistry.Start(&container)\n\t}\n\n\tstreamOpts := clabruntime.EventStreamOptions{\n\t\tLabels: map[string]string{\n\t\t\tclabconstants.Containerlab: \"\",",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/core/events/stream.go",
        "text": "\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to list containers: %w\", err)\n\t}\n\n\tif opts.IncludeInitialState {\n\t\tgo emitContainerSnapshots(ctx, containers, eventCh)\n\t}\n\n\tfor idx := range containers {\n\t\tcontainer := containers[idx]\n\t\tif !isRunningContainer(&container) {\n\t\t\tcontinue\n\t\t}\n\n\t\tregistry.Start(&container)\n\t}\n\n\tstreamOpts := clabruntime.EventStreamOptions{\n\t\tLabels: map[string]string{\n\t\t\tclabconstants.Containerlab: \"\",\n\t\t},\n\t}\n\n\truntimeEvents, runtimeErrs, err := runtime.StreamEvents(ctx, streamOpts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to stream events for runtime %q: %w\", opts.Runtime, err)\n\t}\n\n\terrCh := make(chan error, 1)\n\tgo forwardRuntimeEvents(ctx, runtime, registry, runtimeEvents, runtimeErrs, eventCh, errCh)\n\n\truntimeErrors := errCh\n\n\tfor {\n\t\tselect {\n\t\tcase ev := <-eventCh:\n\t\t\tif err := printer(ev); err != nil {\n\t\t\t\tlog.Debugf(\"failed to write event: %v\", err)\n\t\t\t}\n\t\tcase err, ok := <-runtimeErrors:\n\t\t\tif !ok {\n\t\t\t\truntimeErrors = nil\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err != nil && !errors.Is(err, context.Canceled) {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\nfunc streamLabRuntimeEvents(ctx context.Context, clab *clabcore.CLab, opts Options) error {\n\tprinter, err := newFormatter(opts.Format, opts.writer())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\truntimeEvents, runtimeErrs, err := clab.LabRuntime.StreamEvents(\n\t\tctx,\n\t\tlabRuntimeEventStreamRequest(clab.Config.Name, clab.LabRuntimeIdentity(), opts),\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to stream events for lab runtime %q: %w\", opts.Runtime, err)\n\t}\n\n\tfor runtimeEvents != nil || runtimeErrs != nil {\n\t\tselect {\n\t\tcase ev, ok := <-runtimeEvents:\n\t\t\tif !ok {\n\t\t\t\truntimeEvents = nil\n",
        "lineStart": 55,
        "lineEnd": 129,
        "totalLines": 652,
        "truncated": true
      }
    },
    "time": {
      "start": 1793525958364,
      "end": 1793525958375
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1967a46eb001cja0wDuHrJStjk",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a36700010119sHZdt1ebQm",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 22587,
    "input": 19341,
    "output": 101,
    "reasoning": 201,
    "cache": {
      "read": 2944,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1967a36700010119sHZdt1ebQm",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525954160,
    "completed": 1793525958384
  },
  "parentID": "msg_1967a36620015s1R3CwCc540iR",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 22587,
    "input": 19341,
    "output": 101,
    "reasoning": 201,
    "cache": {
      "read": 2944,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 44
step-start
{
  "type": "step-start",
  "id": "prt_1967a509d001RNc3lo6xHvuQJ7",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a46fc001TuGVZMa1E3VroP"
}
Reasoning
The labNotFoundError is defined and used coherently. Now I need to re-read the manifest.json to confirm the exact 26-path list, and skim the remaining test bodies and docs sections (the diff for runtime.md lines 1130+ and events.md lines 1074+ were read earlier). Let me re-read manifest.json (lines 1-140) to confirm the head/base changed path lists.
Re-reading `manifest.json` to confirm the complete26-path inventory, then skimming the remaining docs sections from the diff.
read · completed

Input

{
  "filePath": "/source/manifest.json",
  "limit": 145
}

Output

<path>/source/manifest.json</path>
<type>file</type>
<content>
1: {
2:   "version": 1,
3:   "head": "1566c3b8e3cb58c82d238dedbfa3b319249bab0a",
4:   "base": "b4de5d55cf17262e39325a7e125a6d3cb2c89318",
5:   "mergeBase": "b4de5d55cf17262e39325a7e125a6d3cb2c89318",
6:   "changed": [
7:     {
8:       "status": "M",
9:       "path": "core/events/netlink.go"
10:     },
11:     {
12:       "status": "A",
13:       "path": "core/events/parity_test.go"
14:     },
15:     {
16:       "status": "M",
17:       "path": "core/events/stream.go"
18:     },
19:     {
20:       "status": "M",
21:       "path": "core/labruntime.go"
22:     },
23:     {
24:       "status": "M",
25:       "path": "core/labruntime_gaps_test.go"
26:     },
27:     {
28:       "status": "M",
29:       "path": "docs/cmd/events.md"
30:     },
31:     {
32:       "status": "M",
33:       "path": "docs/cmd/inspect/interfaces.md"
34:     },
35:     {
36:       "status": "M",
37:       "path": "docs/manual/clabernetes/runtime.md"
38:     },
39:     {
40:       "status": "M",
41:       "path": "labruntime/clabernetes/capture.go"
42:     },
43:     {
44:       "status": "M",
45:       "path": "labruntime/clabernetes/capture_interfaces.go"
46:     },
47:     {
48:       "status": "M",
49:       "path": "labruntime/clabernetes/capture_test.go"
50:     },
51:     {
52:       "status": "M",
53:       "path": "labruntime/clabernetes/clabernetes.go"
54:     },
55:     {
56:       "status": "M",
57:       "path": "labruntime/clabernetes/clabernetes_test.go"
58:     },
59:     {
60:       "status": "A",
61:       "path": "labruntime/clabernetes/container_events.go"
62:     },
63:     {
64:       "status": "A",
65:       "path": "labruntime/clabernetes/event_parity_test.go"
66:     },
67:     {
68:       "status": "M",
69:       "path": "labruntime/clabernetes/events.go"
70:     },
71:     {
72:       "status": "M",
73:       "path": "labruntime/clabernetes/iface_stats.go"
74:     },
75:     {
76:       "status": "M",
77:       "path": "labruntime/clabernetes/manifests.go"
78:     },
79:     {
80:       "status": "M",
81:       "path": "labruntime/clabernetes/plan.go"
82:     },
83:     {
84:       "status": "M",
85:       "path": "labruntime/clabernetes/primitives.go"
86:     },
87:     {
88:       "status": "M",
89:       "path": "labruntime/clabernetes/reconcile.go"
90:     },
91:     {
92:       "status": "M",
93:       "path": "labruntime/clabernetes/runtime_gaps_test.go"
94:     },
95:     {
96:       "status": "M",
97:       "path": "labruntime/clabernetes/state.go"
98:     },
99:     {
100:       "status": "M",
101:       "path": "labruntime/clabernetes/topology.go"
102:     },
103:     {
104:       "status": "M",
105:       "path": "labruntime/runtime.go"
106:     },
107:     {
108:       "status": "M",
109:       "path": "tests/14-clabernetes/01-linux-lifecycle.robot"
110:     }
111:   ],
112:   "files": [
113:     {
114:       "revision": "head",
115:       "path": "core/events/netlink.go",
116:       "bytes": 29906,
117:       "lines": 1301
118:     },
119:     {
120:       "revision": "head",
121:       "path": "core/events/parity_test.go",
122:       "bytes": 18344,
123:       "lines": 553
124:     },
125:     {
126:       "revision": "head",
127:       "path": "core/events/stream.go",
128:       "bytes": 14775,
129:       "lines": 652
130:     },
131:     {
132:       "revision": "head",
133:       "path": "core/labruntime_gaps_test.go",
134:       "bytes": 5105,
135:       "lines": 163
136:     },
137:     {
138:       "revision": "head",
139:       "path": "core/labruntime.go",
140:       "bytes": 22359,
141:       "lines": 827
142:     },
143:     {
144:       "revision": "head",
145:       "path": "docs/cmd/events.md",

(Showing lines 1-145 of 16363. Use offset=146 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1967a53f1001eOuvoOJ9FdjNyV",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a46fc001TuGVZMa1E3VroP",
  "callID": "call_640e3e6720d540e39a7cdb9c",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/manifest.json",
      "limit": 145
    },
    "output": "<path>/source/manifest.json</path>\n<type>file</type>\n<content>\n1: {\n2:   \"version\": 1,\n3:   \"head\": \"1566c3b8e3cb58c82d238dedbfa3b319249bab0a\",\n4:   \"base\": \"b4de5d55cf17262e39325a7e125a6d3cb2c89318\",\n5:   \"mergeBase\": \"b4de5d55cf17262e39325a7e125a6d3cb2c89318\",\n6:   \"changed\": [\n7:     {\n8:       \"status\": \"M\",\n9:       \"path\": \"core/events/netlink.go\"\n10:     },\n11:     {\n12:       \"status\": \"A\",\n13:       \"path\": \"core/events/parity_test.go\"\n14:     },\n15:     {\n16:       \"status\": \"M\",\n17:       \"path\": \"core/events/stream.go\"\n18:     },\n19:     {\n20:       \"status\": \"M\",\n21:       \"path\": \"core/labruntime.go\"\n22:     },\n23:     {\n24:       \"status\": \"M\",\n25:       \"path\": \"core/labruntime_gaps_test.go\"\n26:     },\n27:     {\n28:       \"status\": \"M\",\n29:       \"path\": \"docs/cmd/events.md\"\n30:     },\n31:     {\n32:       \"status\": \"M\",\n33:       \"path\": \"docs/cmd/inspect/interfaces.md\"\n34:     },\n35:     {\n36:       \"status\": \"M\",\n37:       \"path\": \"docs/manual/clabernetes/runtime.md\"\n38:     },\n39:     {\n40:       \"status\": \"M\",\n41:       \"path\": \"labruntime/clabernetes/capture.go\"\n42:     },\n43:     {\n44:       \"status\": \"M\",\n45:       \"path\": \"labruntime/clabernetes/capture_interfaces.go\"\n46:     },\n47:     {\n48:       \"status\": \"M\",\n49:       \"path\": \"labruntime/clabernetes/capture_test.go\"\n50:     },\n51:     {\n52:       \"status\": \"M\",\n53:       \"path\": \"labruntime/clabernetes/clabernetes.go\"\n54:     },\n55:     {\n56:       \"status\": \"M\",\n57:       \"path\": \"labruntime/clabernetes/clabernetes_test.go\"\n58:     },\n59:     {\n60:       \"status\": \"A\",\n61:       \"path\": \"labruntime/clabernetes/container_events.go\"\n62:     },\n63:     {\n64:       \"status\": \"A\",\n65:       \"path\": \"labruntime/clabernetes/event_parity_test.go\"\n66:     },\n67:     {\n68:       \"status\": \"M\",\n69:       \"path\": \"labruntime/clabernetes/events.go\"\n70:     },\n71:     {\n72:       \"status\": \"M\",\n73:       \"path\": \"labruntime/clabernetes/iface_stats.go\"\n74:     },\n75:     {\n76:       \"status\": \"M\",\n77:       \"path\": \"labruntime/clabernetes/manifests.go\"\n78:     },\n79:     {\n80:       \"status\": \"M\",\n81:       \"path\": \"labruntime/clabernetes/plan.go\"\n82:     },\n83:     {\n84:       \"status\": \"M\",\n85:       \"path\": \"labruntime/clabernetes/primitives.go\"\n86:     },\n87:     {\n88:       \"status\": \"M\",\n89:       \"path\": \"labruntime/clabernetes/reconcile.go\"\n90:     },\n91:     {\n92:       \"status\": \"M\",\n93:       \"path\": \"labruntime/clabernetes/runtime_gaps_test.go\"\n94:     },\n95:     {\n96:       \"status\": \"M\",\n97:       \"path\": \"labruntime/clabernetes/state.go\"\n98:     },\n99:     {\n100:       \"status\": \"M\",\n101:       \"path\": \"labruntime/clabernetes/topology.go\"\n102:     },\n103:     {\n104:       \"status\": \"M\",\n105:       \"path\": \"labruntime/runtime.go\"\n106:     },\n107:     {\n108:       \"status\": \"M\",\n109:       \"path\": \"tests/14-clabernetes/01-linux-lifecycle.robot\"\n110:     }\n111:   ],\n112:   \"files\": [\n113:     {\n114:       \"revision\": \"head\",\n115:       \"path\": \"core/events/netlink.go\",\n116:       \"bytes\": 29906,\n117:       \"lines\": 1301\n118:     },\n119:     {\n120:       \"revision\": \"head\",\n121:       \"path\": \"core/events/parity_test.go\",\n122:       \"bytes\": 18344,\n123:       \"lines\": 553\n124:     },\n125:     {\n126:       \"revision\": \"head\",\n127:       \"path\": \"core/events/stream.go\",\n128:       \"bytes\": 14775,\n129:       \"lines\": 652\n130:     },\n131:     {\n132:       \"revision\": \"head\",\n133:       \"path\": \"core/labruntime_gaps_test.go\",\n134:       \"bytes\": 5105,\n135:       \"lines\": 163\n136:     },\n137:     {\n138:       \"revision\": \"head\",\n139:       \"path\": \"core/labruntime.go\",\n140:       \"bytes\": 22359,\n141:       \"lines\": 827\n142:     },\n143:     {\n144:       \"revision\": \"head\",\n145:       \"path\": \"docs/cmd/events.md\",\n\n(Showing lines 1-145 of 16363. Use offset=146 to continue.)\n</content>",
    "title": "source/manifest.json",
    "metadata": {
      "preview": "{\n  \"version\": 1,\n  \"head\": \"1566c3b8e3cb58c82d238dedbfa3b319249bab0a\",\n  \"base\": \"b4de5d55cf17262e39325a7e125a6d3cb2c89318\",\n  \"mergeBase\": \"b4de5d55cf17262e39325a7e125a6d3cb2c89318\",\n  \"changed\": [\n    {\n      \"status\": \"M\",\n      \"path\": \"core/events/netlink.go\"\n    },\n    {\n      \"status\": \"A\",\n      \"path\": \"core/events/parity_test.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"core/events/stream.go\"\n    },\n    {\n      \"status\": \"M\",",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/manifest.json",
        "text": "{\n  \"version\": 1,\n  \"head\": \"1566c3b8e3cb58c82d238dedbfa3b319249bab0a\",\n  \"base\": \"b4de5d55cf17262e39325a7e125a6d3cb2c89318\",\n  \"mergeBase\": \"b4de5d55cf17262e39325a7e125a6d3cb2c89318\",\n  \"changed\": [\n    {\n      \"status\": \"M\",\n      \"path\": \"core/events/netlink.go\"\n    },\n    {\n      \"status\": \"A\",\n      \"path\": \"core/events/parity_test.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"core/events/stream.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"core/labruntime.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"core/labruntime_gaps_test.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"docs/cmd/events.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\": \"labruntime/clabernetes/capture.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"labruntime/clabernetes/capture_interfaces.go\"\n    },\n    {\n      \"status\": \"M\",\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/clabernetes/clabernetes_test.go\"\n    },\n    {\n      \"status\": \"A\",\n      \"path\": \"labruntime/clabernetes/container_events.go\"\n    },\n    {\n      \"status\": \"A\",\n      \"path\": \"labruntime/clabernetes/event_parity_test.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"labruntime/clabernetes/events.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"labruntime/clabernetes/iface_stats.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"labruntime/clabernetes/manifests.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"labruntime/clabernetes/plan.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"labruntime/clabernetes/primitives.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"labruntime/clabernetes/reconcile.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"labruntime/clabernetes/runtime_gaps_test.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"labruntime/clabernetes/state.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"labruntime/clabernetes/topology.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"labruntime/runtime.go\"\n    },\n    {\n      \"status\": \"M\",\n      \"path\": \"tests/14-clabernetes/01-linux-lifecycle.robot\"\n    }\n  ],\n  \"files\": [\n    {\n      \"revision\": \"head\",\n      \"path\": \"core/events/netlink.go\",\n      \"bytes\": 29906,\n      \"lines\": 1301\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"core/events/parity_test.go\",\n      \"bytes\": 18344,\n      \"lines\": 553\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"core/events/stream.go\",\n      \"bytes\": 14775,\n      \"lines\": 652\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"core/labruntime_gaps_test.go\",\n      \"bytes\": 5105,\n      \"lines\": 163\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"core/labruntime.go\",\n      \"bytes\": 22359,\n      \"lines\": 827\n    },\n    {\n      \"revision\": \"head\",\n      \"path\": \"docs/cmd/events.md\",",
        "lineStart": 1,
        "lineEnd": 145,
        "totalLines": 16363,
        "truncated": true
      }
    },
    "time": {
      "start": 1793525961718,
      "end": 1793525961765
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1967a54270016MzHWRsJeUCGEu",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a46fc001TuGVZMa1E3VroP",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 29373,
    "input": 26363,
    "output": 46,
    "reasoning": 84,
    "cache": {
      "read": 2880,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1967a46fc001TuGVZMa1E3VroP",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525958396,
    "completed": 1793525961770
  },
  "parentID": "msg_1967a36620015s1R3CwCc540iR",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 29373,
    "input": 26363,
    "output": 46,
    "reasoning": 84,
    "cache": {
      "read": 2880,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 45
step-start
{
  "type": "step-start",
  "id": "prt_1967a5eb3001xr7yYEPkfgmxvx",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a54340011rd7pNlaroTNk5"
}
Reasoning
The manifest confirms exactly 26 changed paths — the list I tracked is correct:

1. M core/events/netlink.go
2. A core/events/parity_test.go
3. M core/events/stream.go
4. M core/labruntime.go
5. M core/labruntime_gaps_test.go
6. M docs/cmd/events.md
7. M docs/cmd/inspect/interfaces.md
8. M docs/manual/clabernetes/runtime.md
9. M labruntime/clabernetes/capture.go
10. M labruntime/clabernetes/capture_interfaces.go
11. M labruntime/clabernetes/capture_test.go
12. M labruntime/clabernetes/clabernetes.go
13. M labruntime/clabernetes/clabernetes_test.go
14. A labruntime/clabernetes/container_events.go
15. A labruntime/clabernetes/event_parity_test.go
16. M labruntime/clabernetes/events.go
17. M labruntime/clabernetes/iface_stats.go
18. M labruntime/clabernetes/manifests.go
19. M labruntime/clabernetes/plan.go
20. M labruntime/clabernetes/primitives.go
21. M labruntime/clabernetes/reconcile.go
22. M labruntime/clabernetes/runtime_gaps_test.go
23. M labruntime/clabernetes/state.go
24. M labruntime/clabernetes/topology.go
25. M labruntime/runtime.go
26. M tests/14-clabernetes/01-linux-lifecycle.robot

That matches. Now, remaining work per the plan:
1. Read labruntime/clabernetes/lifecycle.go around labNotFoundError/Inspect semantics — DONE just now (lines 440-549). Inspect falls back to nodesForTopology when the Topology is gone; returns labNotFoundError if no Node resources either. Both container_events.go (tracker start) and events.go (per-lab scope) treat labNotFoundError as "stop streaming cleanly". Consistent.
2. Skim remaining test bodies (event_parity_test.go, clabernetes_test.go, capture_test.go, labruntime_gaps_test.go, runtime_gaps_test.go) — I have the test lists; let me do a quick skim of the key event_parity_test.go sections to confirm coverage claims, and the diff for labruntime/runtime.go (lines 4631+ of diff.txt) which I read earlier per notes ("lab-not-found semantics changed" was noted). Actually my notes say I read the diff fully (all 5138 lines) — wait, manifest says diff is 5138 lines? Earlier note said "diff.txt fully read (all 5138 lines; gap 1284-1362 read now — actually fully read)". OK so the diff for runtime.go was read.

3. Docs skim: the grep above shows docs/cmd/events.md line 90: "[c9s runtime manual](../manual/clabernetes/runtime.md#events) lists the ..." — partially read in diff. Let me read the events.md diff hunk and runtime.md diff hunk from the head files directly to check consistency of doc claims with implementation. The grep output already shows:
- interfaces.md line 8 (head): describes eth0/lo inclusion, veth/device types, netlink state names, "eth0 and lo cannot be captured on c9s" — matches implementation (iface_stats.go includes eth0/lo in inspect interfaces; capture rejects them).
- runtime.md has sections #events and #interface-events and clab-topo-file documentation (lines 571, 870, 889).

Let me quickly check the runtime.md events section for consistency with the implementation (state/status/origin semantics, clab-topo-file attribute). And read the remaining portion of event_parity_test.go bodies to solidify verification coverage. Given how much has been verified, I think a focused skim of runtime.md's events section (the section changed by this PR) plus a couple of key test bodies is enough to complete coverage.

Let me read:
- /source/head/docs/manual/clabernetes/runtime.md around lines 560-620 (events section changed) and 860-900 (clab-topo-file docs).
- /source/head/labruntime/clabernetes/event_parity_test.go — read key sections (the whole file is probably ~900 lines; let me check its length via manifest; I'll read the first ~150 lines and grep for function boundaries).

Actually, for efficiency: grep event_parity_test.go for "func Test" to get boundaries, then read the sections covering the tracker transitions and carry-over since those are the riskiest logic.
The manifest confirms exactly the 26 changed paths I tracked. Now completing the final verification: the changed docs sections and key test bodies for the riskiest logic (tracker transitions, carry-over).
grep · completed

Input

{
  "path": "/source/head/labruntime/clabernetes/event_parity_test.go",
  "pattern": "^func Test|^func new"
}

Output

Found 100 matches (more matches available)
/source/head/labruntime/clabernetes/runtime_gaps_test.go:
  Line 32: func TestNewDoesNotLoadKubeconfig(t *testing.T) {

  Line 62: func TestConnectLoadsClientsOnce(t *testing.T) {

  Line 110: func TestListNamespacePrecedence(t *testing.T) {

  Line 133: func TestEventScopeFor(t *testing.T) {

  Line 201: func TestStreamEventsWatchesOnlyTheScopedNamespace(t *testing.T) {

  Line 235: func TestNodeStateFromResourceLocatesWorkload(t *testing.T) {

  Line 285: func TestEnrichStateReportsPodAndContainer(t *testing.T) {

  Line 367: func TestParseInterfaceSample(t *testing.T) {

  Line 406: func TestCommandNotExecutable(t *testing.T) {

  Line 432: func TestTopologyPersistenceRetainsClaims(t *testing.T) {

  Line 443: func TestDestroyKeepsRetainedClaimsUnlessCleanup(t *testing.T) {


/source/head/labruntime/clabernetes/iface_stats.go:
  Line 175: func newInterfacePoller(


/source/head/labruntime/clabernetes/clabernetes.go:
  Line 127: func newClientLoader() *clientLoader {

  Line 134: func newKubeClients(restConfig *rest.Config) (*kubeClients, error) {


/source/head/labruntime/clabernetes/manifests_test.go:
  Line 88: func TestManifestsTopologyBundle(t *testing.T) {

  Line 159: func TestManifestsPrimitiveBundle(t *testing.T) {

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

  Line 225: func TestManifestsMatchDeployedResources(t *testing.T) {

  Line 284: func TestManifestsMatchDeployedPrimitiveResources(t *testing.T) {

  Line 324: func TestManifestsKeepBinaryFilesAsBinaryData(t *testing.T) {


/source/head/labruntime/clabernetes/event_parity_test.go:
  Line 85: func TestNetlinkOperState(t *testing.T) {

  Line 107: func TestInterfaceEventDataNamesInterfacesLikeDocker(t *testing.T) {

  Line 153: func TestInterfacePollerReportsTheTopologyInterfaces(t *testing.T) {

  Line 252: func TestInterfacePollerFirstRoundWithoutInitialState(t *testing.T) {

  Line 265: func TestInterfacePollerStatsCoverTheReportedInterfaces(t *testing.T) {

  Line 325: func TestInterfacePollerListsAPodOncePerInterfaceSet(t *testing.T) {

  Line 369: func TestContainerTransitionActions(t *testing.T) {

  Line 510: func newTrackerHarness(

  Line 598: func TestContainerTrackerReportsTheNodeLifecycle(t *testing.T) {

  Line 672: func TestContainerTrackerSeedsWithoutSnapshot(t *testing.T) {

  Line 686: func TestNodeContainerState(t *testing.T) {

  Line 720: func TestNewestPodPrefersAPodThatIsNotDeleted(t *testing.T) {

  Line 744: func TestEnrichStateReportsContainerStateAndHealth(t *testing.T) {

  Line 811: func TestDeployRecordsTheTopologyFile(t *testing.T) {

  Line 903: func TestCarryOverNodeTopologyFile(t *testing.T) {

  Line 946: func TestManifestsCarryNoTopologyFile(t *testing.T) {

  Line 965: func TestStateReportsTheRecordedTopologyFile(t *testing.T) {


/source/head/labruntime/clabernetes/files_test.go:
  Line 17: func TestStageNodeFileReferences(t *testing.T) {

  Line 86: func TestStageConfigMapFileRejectsOversizedEmbeddedContent(t *testing.T) {

  Line 102: func TestResolveNodeFileReferenceHonorsCancellation(t *testing.T) {

  Line 123: func TestClabernetesBriefLinkMgmtNetNetwork(t *testing.T) {


/source/head/labruntime/clabernetes/access.go:
  Line 244: func newTerminalSizeQueue(

  Line 376: func newPortForwardConn(streamConn httpstream.Connection, port int) (net.Conn, error) {


/source/head/labruntime/clabernetes/resources_test.go:
  Line 16: func TestConditionPendingReasonIdentifiesDirectHelper(t *testing.T) {

  Line 67: func TestWaitPrimitiveLinksResolvedListsTopologyScopedLinks(t *testing.T) {

  Line 116: func TestWaitPrimitiveLinksResolvedIgnoresForeignLinks(t *testing.T) {


/source/head/labruntime/clabernetes/state.go:
  Line 152: func newestPod(current, candidate *corev1.Pod) *corev1.Pod {


/source/head/labruntime/clabernetes/config_test.go:
  Line 12: func TestDeleteManagedLabNamespacePreservesSharedOrOverriddenNamespace(t *testing.T) {


/source/head/labruntime/clabernetes/nodes.go:
  Line 379: func newRestartToken() string {


/source/head/labruntime/clabernetes/nodes_test.go:
  Line 71: func newFakeNodeController(t *testing.T, r *Runtime, lag int) *fakeNodeController {

  Line 214: func TestStopPatchesThePrimaryRunStateAndWaitsForStopped(t *testing.T) {

  Line 257: func TestStartWaitsForTheObservedGenerationAndReadiness(t *testing.T) {

  Line 295: func TestRestartSetsANewTokenAndWaitsForIt(t *testing.T) {

  Line 349: func TestRunStateWaitTimeoutNamesThePendingNodes(t *testing.T) {

  Line 367: func TestNodeLifecycleRejectsUnknownNodes(t *testing.T) {

  Line 389: func TestPrimitivePlanAndApplyKeepTheRunState(t *testing.T) {

  Line 439: func TestManifestsNeverCarryARunState(t *testing.T) {

  Line 482: func TestCheckNodeRunStateSchema(t *testing.T) {

  Line 520: func TestSupportCheckRunsOnceBeforeTheFirstClusterCall(t *testing.T) {

  Line 563: func TestSupportCheckRetriesFailedRequestsAndRemembersSuccess(t *testing.T) {

  Line 600: func TestSupportCheckReadsTheOpenAPIDocumentAsTheCaller(t *testing.T) {

  Line 686: func TestStartAcceptsANodeWhoseLinkPeerIsStopped(t *testing.T) {

  Line 714: func TestLabSettlesWithStoppedNodesAndTheirPeers(t *testing.T) {

  Line 774: func TestPrimitiveObjectsConformAfterAnAPIRoundTrip(t *testing.T) {


/source/head/labruntime/clabernetes/capture_test.go:
  Line 115: func newFakeClabwire(t *testing.T, tick time.Duration) *fakeClabwire {

  Line 379: func TestCaptureInterfacesUsesTopologyNames(t *testing.T) {

  Line 419: func TestCaptureMergesNodesIntoOneSection(t *testing.T) {

  Line 481: func TestCaptureChainsSegmentsWithoutDuplicatesOrGaps(t *testing.T) {

  Line 540: func TestCaptureReportsAGapWhenTheFollowUpStartsLate(t *testing.T) {

  Line 571: func TestCaptureMapsDeniedAndFailedAuditsToErrors(t *testing.T) {

  Line 596: func TestCaptureAuditLineWriter(t *testing.T) {

  Line 633: func TestCaptureStopsAtThePacketLimit(t *testing.T) {

  Line 661: func TestCaptureEndsCleanlyWhenTheContextEnds(t *testing.T) {

  Line 680: func TestCaptureValidatesTargets(t *testing.T) {

  Line 722: func TestInspectInterfacesReportsStateFromSysfs(t *testing.T) {

  Line 771: func TestCaptureWritesWhatItReadWhenTheContextEnds(t *testing.T) {

  Line 851: func TestCaptureClosesStdinWhenItEnds(t *testing.T) {

  Line 920: func TestCaptureRejectsAClabwireWithoutStopOnStdinClose(t *testing.T) {

  Line 954: func TestCaptureMergesNodesInTimestampOrder(t *testing.T) {

  Line 997: func TestCaptureChainsSeveralNodesInOrderWithoutDuplicates(t *testing.T) {

  Line 1056: func TestCaptureReorderWindowKnob(t *testing.T) {


/source/head/labruntime/clabernetes/clabernetes_test.go:
  Line 40: func TestRuntimeName(t *testing.T) {

  Line 54: func TestParseProcNetDev(t *testing.T) {

  Line 80: func TestParseProcNetDevRejectsMalformedLine(t *testing.T) {

  Line 89: func TestPreferredDeviceContainerName(t *testing.T) {

  Line 190: func TestCleanTarPath(t *testing.T) {

  Line 223: func TestNamespaceForLab(t *testing.T) {

  Line 283: func TestConfiguredLabNamespacePrecedence(t *testing.T) {

  Line 299: func TestDeployUsesNamespaceOverrideWithoutManagingIt(t *testing.T) {

  Line 340: func TestDeployCreatesAndDestroyRemovesDedicatedLabNamespace(t *testing.T) {

  Line 393: func TestDestroyPreservesPreexistingLabNamespace(t *testing.T) {

  Line 432: func TestDestroyFallsBackToIndividualDeletesWithoutTouchingOtherLabs(t *testing.T) {

  Line 487: func TestDestroyUsesLabelScopedDeleteCollection(t *testing.T) {

  Line 517: func TestWaitAndSweepDeletedRemovesLateStagedConfigMaps(t *testing.T) {

  Line 539: func TestSavedFilesFromTarSkipsUnsafeEntries(t *testing.T) {

  Line 582: func TestStateFromTopology(t *testing.T) {

  Line 634: func TestPrimitiveResourcesUseCurrentC9sAPI(t *testing.T) {

  Line 649: func TestPrimitiveResourceGroupOrder(t *testing.T) {

  Line 665: func TestPrimitiveLinkPendingReason(t *testing.T) {

  Line 706: func TestEnrichStateUsesNodeResources(t *testing.T) {


(Results truncated. Consider using a more specific path or pattern.)
Tool metadata
{
  "type": "tool",
  "id": "prt_1967a72bf001ujhin7IxmFPQdw",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a54340011rd7pNlaroTNk5",
  "callID": "call_3e5afcd3eb9f40bcbc2dcc5a",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/labruntime/clabernetes/event_parity_test.go",
      "pattern": "^func Test|^func new"
    },
    "output": "Found 100 matches (more matches available)\n/source/head/labruntime/clabernetes/runtime_gaps_test.go:\n  Line 32: func TestNewDoesNotLoadKubeconfig(t *testing.T) {\n\n  Line 62: func TestConnectLoadsClientsOnce(t *testing.T) {\n\n  Line 110: func TestListNamespacePrecedence(t *testing.T) {\n\n  Line 133: func TestEventScopeFor(t *testing.T) {\n\n  Line 201: func TestStreamEventsWatchesOnlyTheScopedNamespace(t *testing.T) {\n\n  Line 235: func TestNodeStateFromResourceLocatesWorkload(t *testing.T) {\n\n  Line 285: func TestEnrichStateReportsPodAndContainer(t *testing.T) {\n\n  Line 367: func TestParseInterfaceSample(t *testing.T) {\n\n  Line 406: func TestCommandNotExecutable(t *testing.T) {\n\n  Line 432: func TestTopologyPersistenceRetainsClaims(t *testing.T) {\n\n  Line 443: func TestDestroyKeepsRetainedClaimsUnlessCleanup(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/iface_stats.go:\n  Line 175: func newInterfacePoller(\n\n\n/source/head/labruntime/clabernetes/clabernetes.go:\n  Line 127: func newClientLoader() *clientLoader {\n\n  Line 134: func newKubeClients(restConfig *rest.Config) (*kubeClients, error) {\n\n\n/source/head/labruntime/clabernetes/manifests_test.go:\n  Line 88: func TestManifestsTopologyBundle(t *testing.T) {\n\n  Line 159: func TestManifestsPrimitiveBundle(t *testing.T) {\n\n  Line 208: func TestManifestsRejectUnsupportedTopology(t *testing.T) {\n\n  Line 225: func TestManifestsMatchDeployedResources(t *testing.T) {\n\n  Line 284: func TestManifestsMatchDeployedPrimitiveResources(t *testing.T) {\n\n  Line 324: func TestManifestsKeepBinaryFilesAsBinaryData(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/event_parity_test.go:\n  Line 85: func TestNetlinkOperState(t *testing.T) {\n\n  Line 107: func TestInterfaceEventDataNamesInterfacesLikeDocker(t *testing.T) {\n\n  Line 153: func TestInterfacePollerReportsTheTopologyInterfaces(t *testing.T) {\n\n  Line 252: func TestInterfacePollerFirstRoundWithoutInitialState(t *testing.T) {\n\n  Line 265: func TestInterfacePollerStatsCoverTheReportedInterfaces(t *testing.T) {\n\n  Line 325: func TestInterfacePollerListsAPodOncePerInterfaceSet(t *testing.T) {\n\n  Line 369: func TestContainerTransitionActions(t *testing.T) {\n\n  Line 510: func newTrackerHarness(\n\n  Line 598: func TestContainerTrackerReportsTheNodeLifecycle(t *testing.T) {\n\n  Line 672: func TestContainerTrackerSeedsWithoutSnapshot(t *testing.T) {\n\n  Line 686: func TestNodeContainerState(t *testing.T) {\n\n  Line 720: func TestNewestPodPrefersAPodThatIsNotDeleted(t *testing.T) {\n\n  Line 744: func TestEnrichStateReportsContainerStateAndHealth(t *testing.T) {\n\n  Line 811: func TestDeployRecordsTheTopologyFile(t *testing.T) {\n\n  Line 903: func TestCarryOverNodeTopologyFile(t *testing.T) {\n\n  Line 946: func TestManifestsCarryNoTopologyFile(t *testing.T) {\n\n  Line 965: func TestStateReportsTheRecordedTopologyFile(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/files_test.go:\n  Line 17: func TestStageNodeFileReferences(t *testing.T) {\n\n  Line 86: func TestStageConfigMapFileRejectsOversizedEmbeddedContent(t *testing.T) {\n\n  Line 102: func TestResolveNodeFileReferenceHonorsCancellation(t *testing.T) {\n\n  Line 123: func TestClabernetesBriefLinkMgmtNetNetwork(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/access.go:\n  Line 244: func newTerminalSizeQueue(\n\n  Line 376: func newPortForwardConn(streamConn httpstream.Connection, port int) (net.Conn, error) {\n\n\n/source/head/labruntime/clabernetes/resources_test.go:\n  Line 16: func TestConditionPendingReasonIdentifiesDirectHelper(t *testing.T) {\n\n  Line 67: func TestWaitPrimitiveLinksResolvedListsTopologyScopedLinks(t *testing.T) {\n\n  Line 116: func TestWaitPrimitiveLinksResolvedIgnoresForeignLinks(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/state.go:\n  Line 152: func newestPod(current, candidate *corev1.Pod) *corev1.Pod {\n\n\n/source/head/labruntime/clabernetes/config_test.go:\n  Line 12: func TestDeleteManagedLabNamespacePreservesSharedOrOverriddenNamespace(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/nodes.go:\n  Line 379: func newRestartToken() string {\n\n\n/source/head/labruntime/clabernetes/nodes_test.go:\n  Line 71: func newFakeNodeController(t *testing.T, r *Runtime, lag int) *fakeNodeController {\n\n  Line 214: func TestStopPatchesThePrimaryRunStateAndWaitsForStopped(t *testing.T) {\n\n  Line 257: func TestStartWaitsForTheObservedGenerationAndReadiness(t *testing.T) {\n\n  Line 295: func TestRestartSetsANewTokenAndWaitsForIt(t *testing.T) {\n\n  Line 349: func TestRunStateWaitTimeoutNamesThePendingNodes(t *testing.T) {\n\n  Line 367: func TestNodeLifecycleRejectsUnknownNodes(t *testing.T) {\n\n  Line 389: func TestPrimitivePlanAndApplyKeepTheRunState(t *testing.T) {\n\n  Line 439: func TestManifestsNeverCarryARunState(t *testing.T) {\n\n  Line 482: func TestCheckNodeRunStateSchema(t *testing.T) {\n\n  Line 520: func TestSupportCheckRunsOnceBeforeTheFirstClusterCall(t *testing.T) {\n\n  Line 563: func TestSupportCheckRetriesFailedRequestsAndRemembersSuccess(t *testing.T) {\n\n  Line 600: func TestSupportCheckReadsTheOpenAPIDocumentAsTheCaller(t *testing.T) {\n\n  Line 686: func TestStartAcceptsANodeWhoseLinkPeerIsStopped(t *testing.T) {\n\n  Line 714: func TestLabSettlesWithStoppedNodesAndTheirPeers(t *testing.T) {\n\n  Line 774: func TestPrimitiveObjectsConformAfterAnAPIRoundTrip(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/capture_test.go:\n  Line 115: func newFakeClabwire(t *testing.T, tick time.Duration) *fakeClabwire {\n\n  Line 379: func TestCaptureInterfacesUsesTopologyNames(t *testing.T) {\n\n  Line 419: func TestCaptureMergesNodesIntoOneSection(t *testing.T) {\n\n  Line 481: func TestCaptureChainsSegmentsWithoutDuplicatesOrGaps(t *testing.T) {\n\n  Line 540: func TestCaptureReportsAGapWhenTheFollowUpStartsLate(t *testing.T) {\n\n  Line 571: func TestCaptureMapsDeniedAndFailedAuditsToErrors(t *testing.T) {\n\n  Line 596: func TestCaptureAuditLineWriter(t *testing.T) {\n\n  Line 633: func TestCaptureStopsAtThePacketLimit(t *testing.T) {\n\n  Line 661: func TestCaptureEndsCleanlyWhenTheContextEnds(t *testing.T) {\n\n  Line 680: func TestCaptureValidatesTargets(t *testing.T) {\n\n  Line 722: func TestInspectInterfacesReportsStateFromSysfs(t *testing.T) {\n\n  Line 771: func TestCaptureWritesWhatItReadWhenTheContextEnds(t *testing.T) {\n\n  Line 851: func TestCaptureClosesStdinWhenItEnds(t *testing.T) {\n\n  Line 920: func TestCaptureRejectsAClabwireWithoutStopOnStdinClose(t *testing.T) {\n\n  Line 954: func TestCaptureMergesNodesInTimestampOrder(t *testing.T) {\n\n  Line 997: func TestCaptureChainsSeveralNodesInOrderWithoutDuplicates(t *testing.T) {\n\n  Line 1056: func TestCaptureReorderWindowKnob(t *testing.T) {\n\n\n/source/head/labruntime/clabernetes/clabernetes_test.go:\n  Line 40: func TestRuntimeName(t *testing.T) {\n\n  Line 54: func TestParseProcNetDev(t *testing.T) {\n\n  Line 80: func TestParseProcNetDevRejectsMalformedLine(t *testing.T) {\n\n  Line 89: func TestPreferredDeviceContainerName(t *testing.T) {\n\n  Line 190: func TestCleanTarPath(t *testing.T) {\n\n  Line 223: func TestNamespaceForLab(t *testing.T) {\n\n  Line 283: func TestConfiguredLabNamespacePrecedence(t *testing.T) {\n\n  Line 299: func TestDeployUsesNamespaceOverrideWithoutManagingIt(t *testing.T) {\n\n  Line 340: func TestDeployCreatesAndDestroyRemovesDedicatedLabNamespace(t *testing.T) {\n\n  Line 393: func TestDestroyPreservesPreexistingLabNamespace(t *testing.T) {\n\n  Line 432: func TestDestroyFallsBackToIndividualDeletesWithoutTouchingOtherLabs(t *testing.T) {\n\n  Line 487: func TestDestroyUsesLabelScopedDeleteCollection(t *testing.T) {\n\n  Line 517: func TestWaitAndSweepDeletedRemovesLateStagedConfigMaps(t *testing.T) {\n\n  Line 539: func TestSavedFilesFromTarSkipsUnsafeEntries(t *testing.T) {\n\n  Line 582: func TestStateFromTopology(t *testing.T) {\n\n  Line 634: func TestPrimitiveResourcesUseCurrentC9sAPI(t *testing.T) {\n\n  Line 649: func TestPrimitiveResourceGroupOrder(t *testing.T) {\n\n  Line 665: func TestPrimitiveLinkPendingReason(t *testing.T) {\n\n  Line 706: func TestEnrichStateUsesNodeResources(t *testing.T) {\n\n\n(Results truncated. Consider using a more specific path or pattern.)",
    "title": "^func Test|^func new",
    "metadata": {
      "matches": 100,
      "truncated": true
    },
    "time": {
      "start": 1793525969604,
      "end": 1793525969621
    }
  }
}
read · completed

Input

{
  "filePath": "/source/head/docs/manual/clabernetes/runtime.md",
  "limit": 120,
  "offset": 545
}

Output

<path>/source/head/docs/manual/clabernetes/runtime.md</path>
<type>file</type>
<content>
545: unchanged. Fields without a value, such as `pod` for a stopped node, are left
546: out. `--details` keeps printing the raw records.
547: 
548: The other fields mean what they mean for Docker and Podman, so clients can treat
549: c9s nodes like containers:
550: 
551: | Field | c9s value |
552: |---|---|
553: | `state` | `created` while the node's pod is scheduled and prepared, `running` once its device containers run, `exited` once the node is stopped (or its pod ends or is replaced) |
554: | `status` | `healthy` once the node is ready or its device containers are, `health: starting` while a running device boots, `Created`, `Exited` |
555: | `labPath`, `absLabPath` | the topology file the lab was deployed from (see below) |
556: | `name` | `<lab>-<node>`, the name events use as `actor_name` |
557: 
558: ### Topology file
559: 
560: A deploy records the absolute path of the topology file, on the machine that
561: deployed it, in the annotation `containerlab.dev/topo-file`:
562: 
563: - with a `Topology` resource, on the `Topology`; every deploy records the file
564:   it read
565: - with `--no-topology-cr`, on every `Node`. clabernetes copies a Node's
566:   annotations into its pod, so a Node keeps the file it was created from: a
567:   later deploy from another file does not change it and does not restart the
568:   node. Destroy and deploy again to record a new file.
569: 
570: `inspect` reports the recorded file as `labPath` and `absLabPath` (shortened
571: for the table, as for Docker), and events as `clab-topo-file`, so a client
572: matches a running lab to its file the same way for every runtime. The file is a
573: path on the deploying machine; a client on another machine cannot assume it
574: exists there.
575: 
576: A lab that containerlab did not deploy from a file, for example one applied from
577: `deploy --emit-crs` output with `kubectl` (the emitted manifests do not carry
578: the annotation), has no recorded file. It reports where its definition lives in
579: the cluster: `k8s://<namespace>/topologies/<lab>`, or
580: `k8s://<namespace>/labs/<lab>` without a `Topology` resource. With `-t`,
581: `inspect` reports the given file.
582: 
583: Useful kubernetes checks for the same state are:
584: 
585: ```bash
586: kubectl -n <namespace> get node.c9s.run,link.c9s.run,nodeprofile.c9s.run,deploy,pod,svc,cm,pvc \
587:   -l c9s.run/topologyOwner=<lab>
588: ```
589: 
590: ## Exec
591: 
592: `exec` runs the user command in the node's device container:
593: 
594: ```bash
595: containerlab --runtime c9s exec -t topo.clab.yml --cmd 'ip addr'
596: ```
597: 
598: Under the hood, containerlab:
599: 
600: 1. resolves the target nodes from the Clabernetes lab state
601: 2. finds the device pod for each node (grouped nodes share the primary node's pod)
602: 3. selects the node's application container from the Node status — for an
603:    SR-SIM chassis this is the active-preferred CPM component
604: 4. uses kubernetes pod exec directly into that container
605: 
606: /// note
607: The command executes in the actual device container. RBAC must allow
608: `pods/exec`, and the device pod must be running.
609: ///
610: 
611: `exec` does not check for a local Docker or Podman daemon; the outer host only
612: needs to reach the cluster.
613: 
614: If any selected command returns nonzero, or pod exec itself fails, the outer
615: `containerlab exec` also returns nonzero. Successful and failed results that
616: were received are still printed, so automation can use both the output and the
617: process exit status.
618: 
619: ## Logs
620: 
621: `logs` shows the log of a node's primary device container, the same container
622: `exec` uses:
623: 
624: ```bash
625: containerlab --runtime c9s logs -t topo.clab.yml -n srl1
626: containerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timestamps
627: ```
628: 
629: It reads the `pods/log` subresource of the node's pod, so RBAC must allow
630: `get` on `pods/log`. Kubernetes returns stdout and stderr as one stream. See
631: the [`logs` command](../../cmd/logs.md) for the flags.
632: 
633: ## Packet capture
634: 
635: [`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of
636: one or more nodes into one pcapng stream. Each node's pod runs the `clabwire`
637: sidecar, which realized the node's links; containerlab execs its capture
638: command (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.
639: No capture service runs in the cluster, and nothing is captured outside the
640: lab's planned link interfaces.
641: 
642: ```bash
643: # both ends of a link, for 30 seconds
644: containerlab -r c9s capture -t clos.clab.yml \
645:   --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng
646: 
647: # live in Wireshark until Wireshark or Ctrl+C ends it
648: containerlab -r c9s capture --name clos --target srl1:e1-1,e1-2 -w - | wireshark -k -i -
649: 
650: # what can be captured, with the peer of each link
651: containerlab -r c9s capture --name clos --list
652: ```
653: 
654: How it works:
655: 
656: - containerlab locates each target node's pod and runs one `clabwire` capture
657:   per node, with `--nodeName`, every requested interface of that node,
658:   `--format pcapng` and `--stop-on-stdin-close`, with stdin attached.
659: - The streams are merged into one section: one Interface Description Block per
660:   target named `<node>:<interface>` (the node as the topology spells it),
661:   written before the first packet, and the packets of every target with their
662:   interface IDs remapped.
663: - Packets are written in timestamp order. Each node's stream arrives over its
664:   own exec stream, so the merged stream holds every packet for 250 ms and

(Showing lines 545-664 of 1421. Use offset=665 to continue.)
</content>
Tool metadata
{
  "type": "tool",
  "id": "prt_1967a7313001MF8KEEZUnSGThQ",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a54340011rd7pNlaroTNk5",
  "callID": "call_a7d4af2c45e54cf9a7bc6815",
  "tool": "read",
  "state": {
    "status": "completed",
    "input": {
      "filePath": "/source/head/docs/manual/clabernetes/runtime.md",
      "limit": 120,
      "offset": 545
    },
    "output": "<path>/source/head/docs/manual/clabernetes/runtime.md</path>\n<type>file</type>\n<content>\n545: unchanged. Fields without a value, such as `pod` for a stopped node, are left\n546: out. `--details` keeps printing the raw records.\n547: \n548: The other fields mean what they mean for Docker and Podman, so clients can treat\n549: c9s nodes like containers:\n550: \n551: | Field | c9s value |\n552: |---|---|\n553: | `state` | `created` while the node's pod is scheduled and prepared, `running` once its device containers run, `exited` once the node is stopped (or its pod ends or is replaced) |\n554: | `status` | `healthy` once the node is ready or its device containers are, `health: starting` while a running device boots, `Created`, `Exited` |\n555: | `labPath`, `absLabPath` | the topology file the lab was deployed from (see below) |\n556: | `name` | `<lab>-<node>`, the name events use as `actor_name` |\n557: \n558: ### Topology file\n559: \n560: A deploy records the absolute path of the topology file, on the machine that\n561: deployed it, in the annotation `containerlab.dev/topo-file`:\n562: \n563: - with a `Topology` resource, on the `Topology`; every deploy records the file\n564:   it read\n565: - with `--no-topology-cr`, on every `Node`. clabernetes copies a Node's\n566:   annotations into its pod, so a Node keeps the file it was created from: a\n567:   later deploy from another file does not change it and does not restart the\n568:   node. Destroy and deploy again to record a new file.\n569: \n570: `inspect` reports the recorded file as `labPath` and `absLabPath` (shortened\n571: for the table, as for Docker), and events as `clab-topo-file`, so a client\n572: matches a running lab to its file the same way for every runtime. The file is a\n573: path on the deploying machine; a client on another machine cannot assume it\n574: exists there.\n575: \n576: A lab that containerlab did not deploy from a file, for example one applied from\n577: `deploy --emit-crs` output with `kubectl` (the emitted manifests do not carry\n578: the annotation), has no recorded file. It reports where its definition lives in\n579: the cluster: `k8s://<namespace>/topologies/<lab>`, or\n580: `k8s://<namespace>/labs/<lab>` without a `Topology` resource. With `-t`,\n581: `inspect` reports the given file.\n582: \n583: Useful kubernetes checks for the same state are:\n584: \n585: ```bash\n586: kubectl -n <namespace> get node.c9s.run,link.c9s.run,nodeprofile.c9s.run,deploy,pod,svc,cm,pvc \\\n587:   -l c9s.run/topologyOwner=<lab>\n588: ```\n589: \n590: ## Exec\n591: \n592: `exec` runs the user command in the node's device container:\n593: \n594: ```bash\n595: containerlab --runtime c9s exec -t topo.clab.yml --cmd 'ip addr'\n596: ```\n597: \n598: Under the hood, containerlab:\n599: \n600: 1. resolves the target nodes from the Clabernetes lab state\n601: 2. finds the device pod for each node (grouped nodes share the primary node's pod)\n602: 3. selects the node's application container from the Node status — for an\n603:    SR-SIM chassis this is the active-preferred CPM component\n604: 4. uses kubernetes pod exec directly into that container\n605: \n606: /// note\n607: The command executes in the actual device container. RBAC must allow\n608: `pods/exec`, and the device pod must be running.\n609: ///\n610: \n611: `exec` does not check for a local Docker or Podman daemon; the outer host only\n612: needs to reach the cluster.\n613: \n614: If any selected command returns nonzero, or pod exec itself fails, the outer\n615: `containerlab exec` also returns nonzero. Successful and failed results that\n616: were received are still printed, so automation can use both the output and the\n617: process exit status.\n618: \n619: ## Logs\n620: \n621: `logs` shows the log of a node's primary device container, the same container\n622: `exec` uses:\n623: \n624: ```bash\n625: containerlab --runtime c9s logs -t topo.clab.yml -n srl1\n626: containerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timestamps\n627: ```\n628: \n629: It reads the `pods/log` subresource of the node's pod, so RBAC must allow\n630: `get` on `pods/log`. Kubernetes returns stdout and stderr as one stream. See\n631: the [`logs` command](../../cmd/logs.md) for the flags.\n632: \n633: ## Packet capture\n634: \n635: [`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of\n636: one or more nodes into one pcapng stream. Each node's pod runs the `clabwire`\n637: sidecar, which realized the node's links; containerlab execs its capture\n638: command (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.\n639: No capture service runs in the cluster, and nothing is captured outside the\n640: lab's planned link interfaces.\n641: \n642: ```bash\n643: # both ends of a link, for 30 seconds\n644: containerlab -r c9s capture -t clos.clab.yml \\\n645:   --target srl1:e1-1 --target srl2:e1-1 --duration 30s -w srl.pcapng\n646: \n647: # live in Wireshark until Wireshark or Ctrl+C ends it\n648: containerlab -r c9s capture --name clos --target srl1:e1-1,e1-2 -w - | wireshark -k -i -\n649: \n650: # what can be captured, with the peer of each link\n651: containerlab -r c9s capture --name clos --list\n652: ```\n653: \n654: How it works:\n655: \n656: - containerlab locates each target node's pod and runs one `clabwire` capture\n657:   per node, with `--nodeName`, every requested interface of that node,\n658:   `--format pcapng` and `--stop-on-stdin-close`, with stdin attached.\n659: - The streams are merged into one section: one Interface Description Block per\n660:   target named `<node>:<interface>` (the node as the topology spells it),\n661:   written before the first packet, and the packets of every target with their\n662:   interface IDs remapped.\n663: - Packets are written in timestamp order. Each node's stream arrives over its\n664:   own exec stream, so the merged stream holds every packet for 250 ms and\n\n(Showing lines 545-664 of 1421. Use offset=665 to continue.)\n</content>",
    "title": "source/head/docs/manual/clabernetes/runtime.md",
    "metadata": {
      "preview": "unchanged. Fields without a value, such as `pod` for a stopped node, are left\nout. `--details` keeps printing the raw records.\n\nThe other fields mean what they mean for Docker and Podman, so clients can treat\nc9s nodes like containers:\n\n| Field | c9s value |\n|---|---|\n| `state` | `created` while the node's pod is scheduled and prepared, `running` once its device containers run, `exited` once the node is stopped (or its pod ends or is replaced) |\n| `status` | `healthy` once the node is ready or its device containers are, `health: starting` while a running device boots, `Created`, `Exited` |\n| `labPath`, `absLabPath` | the topology file the lab was deployed from (see below) |\n| `name` | `<lab>-<node>`, the name events use as `actor_name` |\n\n### Topology file\n\nA deploy records the absolute path of the topology file, on the machine that\ndeployed it, in the annotation `containerlab.dev/topo-file`:\n\n- with a `Topology` resource, on the `Topology`; every deploy records the file\n  it read",
      "truncated": true,
      "loaded": [],
      "display": {
        "type": "file",
        "path": "/source/head/docs/manual/clabernetes/runtime.md",
        "text": "unchanged. Fields without a value, such as `pod` for a stopped node, are left\nout. `--details` keeps printing the raw records.\n\nThe other fields mean what they mean for Docker and Podman, so clients can treat\nc9s nodes like containers:\n\n| Field | c9s value |\n|---|---|\n| `state` | `created` while the node's pod is scheduled and prepared, `running` once its device containers run, `exited` once the node is stopped (or its pod ends or is replaced) |\n| `status` | `healthy` once the node is ready or its device containers are, `health: starting` while a running device boots, `Created`, `Exited` |\n| `labPath`, `absLabPath` | the topology file the lab was deployed from (see below) |\n| `name` | `<lab>-<node>`, the name events use as `actor_name` |\n\n### Topology file\n\nA deploy records the absolute path of the topology file, on the machine that\ndeployed it, in the annotation `containerlab.dev/topo-file`:\n\n- with a `Topology` resource, on the `Topology`; every deploy records the file\n  it read\n- with `--no-topology-cr`, on every `Node`. clabernetes copies a Node's\n  annotations into its pod, so a Node keeps the file it was created from: a\n  later deploy from another file does not change it and does not restart the\n  node. Destroy and deploy again to record a new file.\n\n`inspect` reports the recorded file as `labPath` and `absLabPath` (shortened\nfor the table, as for Docker), and events as `clab-topo-file`, so a client\nmatches a running lab to its file the same way for every runtime. The file is a\npath on the deploying machine; a client on another machine cannot assume it\nexists there.\n\nA lab that containerlab did not deploy from a file, for example one applied from\n`deploy --emit-crs` output with `kubectl` (the emitted manifests do not carry\nthe annotation), has no recorded file. It reports where its definition lives in\nthe cluster: `k8s://<namespace>/topologies/<lab>`, or\n`k8s://<namespace>/labs/<lab>` without a `Topology` resource. With `-t`,\n`inspect` reports the given file.\n\nUseful kubernetes checks for the same state are:\n\n```bash\nkubectl -n <namespace> get node.c9s.run,link.c9s.run,nodeprofile.c9s.run,deploy,pod,svc,cm,pvc \\\n  -l c9s.run/topologyOwner=<lab>\n```\n\n## Exec\n\n`exec` runs the user command in the node's device container:\n\n```bash\ncontainerlab --runtime c9s exec -t topo.clab.yml --cmd 'ip addr'\n```\n\nUnder the hood, containerlab:\n\n1. resolves the target nodes from the Clabernetes lab state\n2. finds the device pod for each node (grouped nodes share the primary node's pod)\n3. selects the node's application container from the Node status — for an\n   SR-SIM chassis this is the active-preferred CPM component\n4. uses kubernetes pod exec directly into that container\n\n/// note\nThe command executes in the actual device container. RBAC must allow\n`pods/exec`, and the device pod must be running.\n///\n\n`exec` does not check for a local Docker or Podman daemon; the outer host only\nneeds to reach the cluster.\n\nIf any selected command returns nonzero, or pod exec itself fails, the outer\n`containerlab exec` also returns nonzero. Successful and failed results that\nwere received are still printed, so automation can use both the output and the\nprocess exit status.\n\n## Logs\n\n`logs` shows the log of a node's primary device container, the same container\n`exec` uses:\n\n```bash\ncontainerlab --runtime c9s logs -t topo.clab.yml -n srl1\ncontainerlab --runtime c9s logs --name clos -n srl1 --tail 100 --follow --timestamps\n```\n\nIt 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\nthe [`logs` command](../../cmd/logs.md) for the flags.\n\n## Packet capture\n\n[`containerlab capture`](../../cmd/capture.md) captures lab link interfaces of\none or more nodes into one pcapng stream. Each node's pod runs the `clabwire`\nsidecar, which realized the node's links; containerlab execs its capture\ncommand (`/clabernetes/manager node-runtime packet-capture`) in the sidecar.\nNo capture service runs in the cluster, and nothing is captured outside the\nlab's planned link interfaces.\n\n```bash\n# both ends of a link, for 30 seconds\ncontainerlab -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\ncontainerlab -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\ncontainerlab -r c9s capture --name clos --list\n```\n\nHow 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",
        "lineStart": 545,
        "lineEnd": 664,
        "totalLines": 1421,
        "truncated": true
      }
    },
    "time": {
      "start": 1793525969688,
      "end": 1793525969700
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1967a7326001Z9LAbgMwtJq9v9",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a54340011rd7pNlaroTNk5",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 31744,
    "input": 30678,
    "output": 100,
    "reasoning": 966,
    "cache": {
      "read": 0,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1967a54340011rd7pNlaroTNk5",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525961780,
    "completed": 1793525969706
  },
  "parentID": "msg_1967a36620015s1R3CwCc540iR",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 31744,
    "input": 30678,
    "output": 100,
    "reasoning": 966,
    "cache": {
      "read": 0,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 46
step-start
{
  "type": "step-start",
  "id": "prt_1967a7a22001FgrUFwUiA4XXsj",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a7335001sjPjb2N1XVxqW2"
}
Reasoning
The docs "Topology file" section matches the implementation: Topology annotation via `setTopologySourceFile` on Topology and every Node for `--no-topology-cr` (primitives.go:225 calls it for Nodes), carry-over semantics (Node keeps the file it was created from; later deploy doesn't change it), fallback `k8s://<namespace>/topologies/<lab>` and `k8s://<namespace>/labs/<lab>` for the no-Topology case, and `-t` overrides. This matches `state.go`'s `labTopologyPath` fallback logic I verified earlier.

Test coverage in `event_parity_test.go` is comprehensive: TestDeployRecordsTheTopologyFile, TestCarryOverNodeTopologyFile, TestManifestsCarryNoTopologyFile, TestStateReportsTheRecordedTopologyFile — all four flows documented. Plus interface poller tests, container transition/tracker tests, newestPod test.

Everything checks out. I should now also quickly read the interface-events section of runtime.md (the docs added there) to confirm the documented interface event semantics match `iface_stats.go` — the diff hunk at lines 1130+ was read earlier, and my notes say the docs hunks were reviewed. Also the events.md hunk was read.

I believe coverage is now complete:
- All 26 changed paths examined (source read directly; diff fully read).
- Callers verified (setTopologySourceFile/removeTopologySourceFile, labNotFoundError uses, errs channels, registry wiring).
- Tests surveyed comprehensively across all test files.
- Docs cross-checked (events.md, interfaces.md, runtime.md topology-file + events sections).
- Robot suite read fully and consistent.
- No schema changes in this PR (topology configuration API unchanged; c9s CRDs are external to containerlab — the annotation is on c9s resources, not clab.schema.json; no schema check needed per instructions since it's outside that schema's domain).

Findings: Throughout this review, all previously raised candidates were resolved:
- Empty `state` attribute dropped by formatter (consistent).
- errs channel sizing (4 goroutines write, buffer 4 — safe).
- `annotationDirectNodeUID`/`labelOriginalNodeName` contract consistent with tests and docs.
- timer.Reset safety fine.
- `managementAddress` CIDR parity handled by `splitManagementCIDR`.
- `containerFromLabNode` NodeType override — consistent with docs (`-t` populates kind's default type; byName falls back to runtime state), matches robot test and docs wording.

One thing I should double check before finalizing: the `stream.go` line 124 loop `for runtimeEvents != nil || runtimeErrs != nil` with select — if runtimeErrs is nil and runtimeEvents is nil, loop ends; if both non-nil and both empty (closed), select picks randomly between two nil-disabled cases — fine, nil channels block. When events closes → runtimeEvents = nil; errs still open → select waits on errs only. Fine.

One more consideration: in `stream.go` (the clab runtime path, lines 83-86), `errCh := make(chan error, 1)` and `forwardRuntimeEvents` writes to it. Buffered 1 so no goroutine leak. Fine.

Also `runtimeErrors = nil` when closed (lines 94-98) — then the select has only eventCh and ctx.Done. But when the events stream closes (runtimeEvents channel closed), the docker path uses a registry with watches; for the lab-runtime path (streamLabRuntimeEvents), when both channels close the loop ends. Fine.

Is there anything remaining that could be a genuine finding? Let me think about whether I found any actual issues during the entire review... My notes say "likely all P4/none". Throughout the review, all candidate issues were resolved. The PR appears to be a high-quality, well-tested change with thorough docs.

One candidate I could double-check: in `iface_stats.go`, the poller lists pods once per interface set (tested: TestInterfacePollerListsAPodOncePerInterfaceSet). And `TestInterfacePollerStatsCoverTheReportedInterfaces` covers stats.

Another: `container_events.go` tracker seeds initial state without snapshot (TestContainerTrackerSeedsWithoutSnapshot covers it).

I feel coverage is complete. The final answer: no actionable findings (empty findings list is valid), with coverage notes disclosing: no tests executed (read-only snapshot, tool constraint), all source paths read, diff fully read, docs cross-checked, robot suite read, schema check N/A (no topology schema changes — annotations on c9s resources are outside clab.schema.json domain), test execution not possible so findings rely on source inspection.

Actually wait — before finalizing with zero findings, let me do one last sanity check on something that could be a real issue: the `health: starting` status string. The docs table says `status` | `health: starting` while a running device boots. Docker's health status event action is `health_status: healthy`. In the robot test: `Container Event Should Carry Docker Attributes ${events} server health_status: healthy running ${applied-topo}` — action `health_status: healthy`. So the action string is "health_status: healthy" and status value "healthy"? Actually the robot test passes action="health_status: healthy" and state="running". And the table says status "healthy once ready... health: starting while running device boots". Hmm, "health: starting" as a status value vs Docker's "health: starting" — Docker's health status for a starting container is "starting" (container state `status: running`, `health: starting`). Let me check what the implementation reports for status. In `nodeContainerState` (event_parity_test.go:686 tests it) and container_events.go. Let me check the status mapping in container_events.go quickly.

Also the action `health_status: healthy` — Docker emits action `health_status: healthy`? Docker emits events with Action "health_status: healthy". Yes, that matches Docker.

Let me check the status value mapping in container_events.go.
Docs match the implementation. One last check on the health status values before finalizing.
grep · completed

Input

{
  "path": "/source/head/labruntime/clabernetes/container_events.go",
  "pattern": "health|starting|healthy|Health"
}

Output

Found 72 matches
/source/head/labruntime/clabernetes/capture.go:
  Line 719: // segmentDuration is the requested duration of a segment starting now.


/source/head/labruntime/clabernetes/image_progress.go:
  Line 239: 	{"ContainersReady", "starting containers"},


/source/head/labruntime/clabernetes/event_parity_test.go:
  Line 376: 		healthy = clablabruntime.ContainerHealthHealthy

  Line 377: 		start   = clablabruntime.ContainerHealthStarting

  Line 378: 		sick    = clablabruntime.ContainerHealthUnhealthy

  Line 380: 	tracked := func(state, health, pod string) *trackedContainer {

  Line 381: 		return &trackedContainer{state: state, health: health, pod: pod}

  Line 393: 			"create,start,health_status: starting",

  Line 396: 			"new ready node", nil, tracked(running, healthy, "p1"),

  Line 397: 			"create,start,health_status: healthy",

  Line 402: 			"start,health_status: starting",

  Line 405: 			"device ready", tracked(running, start, "p1"), tracked(running, healthy, "p1"),

  Line 406: 			"health_status: healthy",

  Line 409: 		{"no change", tracked(running, healthy, "p1"), tracked(running, healthy, "p1"), ""},

  Line 411: 			"device not ready again", tracked(running, healthy, "p1"), tracked(running, sick, "p1"),

  Line 412: 			"health_status: unhealthy",

  Line 414: 		{"stop", tracked(running, healthy, "p1"), tracked(exited, "", ""), "kill,stop,die"},

  Line 416: 			"start", tracked(exited, "", ""), tracked(running, healthy, "p2"),

  Line 417: 			"start,health_status: healthy",

  Line 420: 			"restart, new pod pending", tracked(running, healthy, "p1"), tracked(created, "", "p2"),

  Line 424: 			"restart, new pod running", tracked(running, healthy, "p1"),

  Line 425: 			tracked(running, start, "p2"), "kill,stop,die,start,health_status: starting",

  Line 437: 	if got := strings.Join(containerRemovalActions(tracked(running, healthy, "p1")), ","); got !=

  Line 448: 	// health: a running node that was healthy and is not ready anymore in the same pod is

  Line 449: 	// unhealthy; in a new pod it starts again

  Line 450: 	previous := tracked(running, healthy, "p1")

  Line 451: 	if got := containerHealth(previous, tracked(running, "", "p1"), start); got != sick {

  Line 452: 		t.Fatalf("health in the same pod = %q", got)

  Line 454: 	if got := containerHealth(previous, tracked(running, "", "p2"), start); got != start {

  Line 455: 		t.Fatalf("health in a new pod = %q", got)

  Line 614: 	if got := h.refresh(); got != "start=running,health_status: starting=running" {

  Line 621: 	if got := h.refresh(); got != "health_status: healthy=running" {

  Line 647: 	if got := h.refresh(); got != "start=running,health_status: healthy=running" {

  Line 655: 		"kill=running/15,stop=exited,die=exited,start=running,health_status: healthy=running" {

  Line 744: func TestEnrichStateReportsContainerStateAndHealth(t *testing.T) {

  Line 771: 		"r1": "running/healthy", "r2": "running/healthy", "r3": "running/starting", "r4": "exited/",

  Line 777: 		if got := node.ContainerState + "/" + node.Health; got != want[node.Name] {


/source/head/labruntime/clabernetes/container_events.go:
  Line 22: 	containerActionHealthPrefix  = "health_status: "

  Line 33: 	health string

  Line 43: // destroy when the node is removed, and health_status as its device becomes ready.

  Line 187: 	next.health = containerHealth(previous, next, node.Health)

  Line 205: // containerHealth is the health a running node reports: a node that was healthy and is not

  Line 206: // ready anymore in the same pod is unhealthy, as a container whose healthcheck starts failing.

  Line 207: func containerHealth(previous, next *trackedContainer, health string) string {

  Line 211: 	if health == "" {

  Line 212: 		health = clablabruntime.ContainerHealthStarting

  Line 214: 	if health == clablabruntime.ContainerHealthStarting && previous != nil &&

  Line 216: 		(previous.health == clablabruntime.ContainerHealthHealthy ||

  Line 217: 			previous.health == clablabruntime.ContainerHealthUnhealthy) {

  Line 218: 		return clablabruntime.ContainerHealthUnhealthy

  Line 221: 	return health

  Line 235: // A started node also reports its health (health_status: starting or healthy), and a running

  Line 236: // node reports health changes, like a container with a healthcheck.

  Line 275: 	if !started && previous != nil && previous.health == next.health {

  Line 278: 	if next.health == clablabruntime.ContainerHealthStarting && !started {

  Line 282: 	return append(actions, containerActionHealthPrefix+next.health)

  Line 306: 	if strings.HasPrefix(action, containerActionHealthPrefix) {


/source/head/labruntime/clabernetes/state.go:
  Line 260: 			node.Health = nodeHealth(node, resourcesByName[nodeName])

  Line 337: // nodeHealth is the health of a running node: healthy once the Node is ready or its device

  Line 338: // containers are, starting before. Device containers are the analogue of a container

  Line 339: // healthcheck: a node whose links wait for a stopped peer is not ready, but its device is.

  Line 340: func nodeHealth(node clablabruntime.NodeState, resource *unstructured.Unstructured) string {

  Line 342: 		return clablabruntime.ContainerHealthHealthy

  Line 347: 			return clablabruntime.ContainerHealthHealthy

  Line 351: 	return clablabruntime.ContainerHealthStarting


/source/head/labruntime/clabernetes/testdata/openapi-c9s-v1alpha1-0.10.json:
  Line 81:        "healthcheck": {


/source/head/labruntime/clabernetes/testdata/openapi-c9s-v1alpha1-runstate.json:
  Line 81:        "healthcheck": {


/source/head/labruntime/clabernetes/nodes_test.go:
  Line 290: 		t.Fatalf("starting r1 changed r2 to %s", got)


/source/head/labruntime/clabernetes/clabernetes_test.go:
  Line 877: 			want: `phase="starting containers" container=` + containerName +

  Line 884: 			want: `phase="starting containers" container=node-secondary` +

  Line 891: 			want: `phase="starting containers" container=node-cpm-a` +

  Line 918: 			want:      `phase="starting containers"`,
Tool metadata
{
  "type": "tool",
  "id": "prt_1967aa3d3001A82peaSIqYza0Y",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a7335001sjPjb2N1XVxqW2",
  "callID": "call_2d24de5bd98d4818824ceaba",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head/labruntime/clabernetes/container_events.go",
      "pattern": "health|starting|healthy|Health"
    },
    "output": "Found 72 matches\n/source/head/labruntime/clabernetes/capture.go:\n  Line 719: // segmentDuration is the requested duration of a segment starting now.\n\n\n/source/head/labruntime/clabernetes/image_progress.go:\n  Line 239: \t{\"ContainersReady\", \"starting containers\"},\n\n\n/source/head/labruntime/clabernetes/event_parity_test.go:\n  Line 376: \t\thealthy = clablabruntime.ContainerHealthHealthy\n\n  Line 377: \t\tstart   = clablabruntime.ContainerHealthStarting\n\n  Line 378: \t\tsick    = clablabruntime.ContainerHealthUnhealthy\n\n  Line 380: \ttracked := func(state, health, pod string) *trackedContainer {\n\n  Line 381: \t\treturn &trackedContainer{state: state, health: health, pod: pod}\n\n  Line 393: \t\t\t\"create,start,health_status: starting\",\n\n  Line 396: \t\t\t\"new ready node\", nil, tracked(running, healthy, \"p1\"),\n\n  Line 397: \t\t\t\"create,start,health_status: healthy\",\n\n  Line 402: \t\t\t\"start,health_status: starting\",\n\n  Line 405: \t\t\t\"device ready\", tracked(running, start, \"p1\"), tracked(running, healthy, \"p1\"),\n\n  Line 406: \t\t\t\"health_status: healthy\",\n\n  Line 409: \t\t{\"no change\", tracked(running, healthy, \"p1\"), tracked(running, healthy, \"p1\"), \"\"},\n\n  Line 411: \t\t\t\"device not ready again\", tracked(running, healthy, \"p1\"), tracked(running, sick, \"p1\"),\n\n  Line 412: \t\t\t\"health_status: unhealthy\",\n\n  Line 414: \t\t{\"stop\", tracked(running, healthy, \"p1\"), tracked(exited, \"\", \"\"), \"kill,stop,die\"},\n\n  Line 416: \t\t\t\"start\", tracked(exited, \"\", \"\"), tracked(running, healthy, \"p2\"),\n\n  Line 417: \t\t\t\"start,health_status: healthy\",\n\n  Line 420: \t\t\t\"restart, new pod pending\", tracked(running, healthy, \"p1\"), tracked(created, \"\", \"p2\"),\n\n  Line 424: \t\t\t\"restart, new pod running\", tracked(running, healthy, \"p1\"),\n\n  Line 425: \t\t\ttracked(running, start, \"p2\"), \"kill,stop,die,start,health_status: starting\",\n\n  Line 437: \tif got := strings.Join(containerRemovalActions(tracked(running, healthy, \"p1\")), \",\"); got !=\n\n  Line 448: \t// health: a running node that was healthy and is not ready anymore in the same pod is\n\n  Line 449: \t// unhealthy; in a new pod it starts again\n\n  Line 450: \tprevious := tracked(running, healthy, \"p1\")\n\n  Line 451: \tif got := containerHealth(previous, tracked(running, \"\", \"p1\"), start); got != sick {\n\n  Line 452: \t\tt.Fatalf(\"health in the same pod = %q\", got)\n\n  Line 454: \tif got := containerHealth(previous, tracked(running, \"\", \"p2\"), start); got != start {\n\n  Line 455: \t\tt.Fatalf(\"health in a new pod = %q\", got)\n\n  Line 614: \tif got := h.refresh(); got != \"start=running,health_status: starting=running\" {\n\n  Line 621: \tif got := h.refresh(); got != \"health_status: healthy=running\" {\n\n  Line 647: \tif got := h.refresh(); got != \"start=running,health_status: healthy=running\" {\n\n  Line 655: \t\t\"kill=running/15,stop=exited,die=exited,start=running,health_status: healthy=running\" {\n\n  Line 744: func TestEnrichStateReportsContainerStateAndHealth(t *testing.T) {\n\n  Line 771: \t\t\"r1\": \"running/healthy\", \"r2\": \"running/healthy\", \"r3\": \"running/starting\", \"r4\": \"exited/\",\n\n  Line 777: \t\tif got := node.ContainerState + \"/\" + node.Health; got != want[node.Name] {\n\n\n/source/head/labruntime/clabernetes/container_events.go:\n  Line 22: \tcontainerActionHealthPrefix  = \"health_status: \"\n\n  Line 33: \thealth string\n\n  Line 43: // destroy when the node is removed, and health_status as its device becomes ready.\n\n  Line 187: \tnext.health = containerHealth(previous, next, node.Health)\n\n  Line 205: // containerHealth is the health a running node reports: a node that was healthy and is not\n\n  Line 206: // ready anymore in the same pod is unhealthy, as a container whose healthcheck starts failing.\n\n  Line 207: func containerHealth(previous, next *trackedContainer, health string) string {\n\n  Line 211: \tif health == \"\" {\n\n  Line 212: \t\thealth = clablabruntime.ContainerHealthStarting\n\n  Line 214: \tif health == clablabruntime.ContainerHealthStarting && previous != nil &&\n\n  Line 216: \t\t(previous.health == clablabruntime.ContainerHealthHealthy ||\n\n  Line 217: \t\t\tprevious.health == clablabruntime.ContainerHealthUnhealthy) {\n\n  Line 218: \t\treturn clablabruntime.ContainerHealthUnhealthy\n\n  Line 221: \treturn health\n\n  Line 235: // A started node also reports its health (health_status: starting or healthy), and a running\n\n  Line 236: // node reports health changes, like a container with a healthcheck.\n\n  Line 275: \tif !started && previous != nil && previous.health == next.health {\n\n  Line 278: \tif next.health == clablabruntime.ContainerHealthStarting && !started {\n\n  Line 282: \treturn append(actions, containerActionHealthPrefix+next.health)\n\n  Line 306: \tif strings.HasPrefix(action, containerActionHealthPrefix) {\n\n\n/source/head/labruntime/clabernetes/state.go:\n  Line 260: \t\t\tnode.Health = nodeHealth(node, resourcesByName[nodeName])\n\n  Line 337: // nodeHealth is the health of a running node: healthy once the Node is ready or its device\n\n  Line 338: // containers are, starting before. Device containers are the analogue of a container\n\n  Line 339: // healthcheck: a node whose links wait for a stopped peer is not ready, but its device is.\n\n  Line 340: func nodeHealth(node clablabruntime.NodeState, resource *unstructured.Unstructured) string {\n\n  Line 342: \t\treturn clablabruntime.ContainerHealthHealthy\n\n  Line 347: \t\t\treturn clablabruntime.ContainerHealthHealthy\n\n  Line 351: \treturn clablabruntime.ContainerHealthStarting\n\n\n/source/head/labruntime/clabernetes/testdata/openapi-c9s-v1alpha1-0.10.json:\n  Line 81:        \"healthcheck\": {\n\n\n/source/head/labruntime/clabernetes/testdata/openapi-c9s-v1alpha1-runstate.json:\n  Line 81:        \"healthcheck\": {\n\n\n/source/head/labruntime/clabernetes/nodes_test.go:\n  Line 290: \t\tt.Fatalf(\"starting r1 changed r2 to %s\", got)\n\n\n/source/head/labruntime/clabernetes/clabernetes_test.go:\n  Line 877: \t\t\twant: `phase=\"starting containers\" container=` + containerName +\n\n  Line 884: \t\t\twant: `phase=\"starting containers\" container=node-secondary` +\n\n  Line 891: \t\t\twant: `phase=\"starting containers\" container=node-cpm-a` +\n\n  Line 918: \t\t\twant:      `phase=\"starting containers\"`,\n",
    "title": "health|starting|healthy|Health",
    "metadata": {
      "matches": 72,
      "truncated": false
    },
    "time": {
      "start": 1793525982168,
      "end": 1793525982191
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1967aa3f2001qxlG8wu4jmRxdG",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967a7335001sjPjb2N1XVxqW2",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 37082,
    "input": 4278,
    "output": 48,
    "reasoning": 1268,
    "cache": {
      "read": 31488,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1967a7335001sjPjb2N1XVxqW2",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525969717,
    "completed": 1793525982198
  },
  "parentID": "msg_1967a36620015s1R3CwCc540iR",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 37082,
    "input": 4278,
    "output": 48,
    "reasoning": 1268,
    "cache": {
      "read": 31488,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 47
step-start
{
  "type": "step-start",
  "id": "prt_1967aab81001uzY41hsW4sqGrV",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967aa400001nZb80jPmSwFXmm"
}
Reasoning
The health logic is coherent:
- `containerHealth` maps empty health on a running node to `ContainerHealthStarting` (parity with Docker: a container's healthcheck reports "starting" before first success).
- Health transitions produce `health_status: starting|healthy|unhealthy` actions, matching Docker's event action vocabulary.
- `containerTransitionActions` produces `create,start,health_status: starting` for a new node (parity: Docker emits `create`, `start`, then `health_status: starting`), then `health_status: healthy`.
- Docker parity detail: Docker emits `health_status: starting`? Docker does emit `health_status: starting` events (healthcheck transitions). Yes.

The status attribute values: docs table says `health: starting` while running device boots — wait, docs said `status` | `healthy` once ready... `health: starting` while running device boots. Hmm, let me look at the exact doc line again: "status | healthy once the node is ready or its device containers are, health: starting while a running device boots, Created, Exited". So the status value when starting is "health: starting"? Let me check what inspect reports as `status`. Actually, the earlier verified docs table at runtime.md lines 551-556 says:

| `status` | `healthy` once the node is ready or its device containers are, `health: starting` while a running device boots, `Created`, `Exited` |

Hmm, so status can be `health: starting`? That reads a bit oddly. Let me check what the implementation puts in the `status` field of the inspect table. Earlier, in the first session, I read the inspect table code? My notes say I verified inspect table output for `state`, `status`, etc.? Not explicitly. Let me check the inspect status field in clabernetes inspect table code. The value "health: starting" suggests the table cell for status combines "health: starting"? That would be weird wording. Let me grep for "health: starting" in the head.
Health transitions match Docker's `health_status` vocabulary. Checking the one odd doc value: `status` = `health: starting`.
grep · completed

Input

{
  "path": "/source/head",
  "pattern": "\"health: starting\"|health: starting"
}

Output

Found 6 matches
/source/head/docs/manual/clabernetes/runtime.md:
  Line 554: | `status` | `healthy` once the node is ready or its device containers are, `health: starting` while a running device boots, `Created`, `Exited` |


/source/head/core/events/parity_test.go:
  Line 379: 		}, "running", "health: starting"},


/source/head/cmd/inspect.go:
  Line 533: 	case strings.Contains(status, "health: starting"):

  Line 534: 		return "health: starting"


/source/head/core/labruntime.go:
  Line 544: // container runtimes: state created, running or exited; status healthy or "health: starting"

  Line 557: 		return node.ContainerState, "health: starting"
Tool metadata
{
  "type": "tool",
  "id": "prt_1967ab92000111qqJ7izgkU2H0",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967aa400001nZb80jPmSwFXmm",
  "callID": "call_5d0e93bc64dc4e159bc29f34",
  "tool": "grep",
  "state": {
    "status": "completed",
    "input": {
      "path": "/source/head",
      "pattern": "\"health: starting\"|health: starting"
    },
    "output": "Found 6 matches\n/source/head/docs/manual/clabernetes/runtime.md:\n  Line 554: | `status` | `healthy` once the node is ready or its device containers are, `health: starting` while a running device boots, `Created`, `Exited` |\n\n\n/source/head/core/events/parity_test.go:\n  Line 379: \t\t}, \"running\", \"health: starting\"},\n\n\n/source/head/cmd/inspect.go:\n  Line 533: \tcase strings.Contains(status, \"health: starting\"):\n\n  Line 534: \t\treturn \"health: starting\"\n\n\n/source/head/core/labruntime.go:\n  Line 544: // container runtimes: state created, running or exited; status healthy or \"health: starting\"\n\n  Line 557: \t\treturn node.ContainerState, \"health: starting\"\n",
    "title": "\"health: starting\"|health: starting",
    "metadata": {
      "matches": 6,
      "truncated": false
    },
    "time": {
      "start": 1793525987622,
      "end": 1793525987652
    }
  }
}
step-finish
{
  "type": "step-finish",
  "id": "prt_1967ab947001nM4yRRrEbEqzVJ",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967aa400001nZb80jPmSwFXmm",
  "reason": "tool-calls",
  "cost": 0,
  "tokens": {
    "total": 39275,
    "input": 9612,
    "output": 51,
    "reasoning": 428,
    "cache": {
      "read": 29184,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1967aa400001nZb80jPmSwFXmm",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525982208,
    "completed": 1793525987659
  },
  "parentID": "msg_1967a36620015s1R3CwCc540iR",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 39275,
    "input": 9612,
    "output": 51,
    "reasoning": 428,
    "cache": {
      "read": 29184,
      "write": 0
    }
  },
  "finish": "tool-calls"
}
Assistant · 48
step-start
{
  "type": "step-start",
  "id": "prt_1967ac4c4001bL203nPATZS862",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967ab9570011bq2FFkVR2Shqc"
}
Reasoning
The `status` value `health: starting` is consistent across the implementation (`core/labruntime.go:557`, `cmd/inspect.go:533-534`), tests (`core/events/parity_test.go:379`), and docs (`docs/manual/clabernetes/runtime.md:554`). So it's a pre-existing/consistent convention, not an issue introduced by this PR.

Everything is verified. Now finalize the review.

Summary of the full review:

**PR purpose:** c9s (Clabernetes) lab-runtime event parity with the Docker runtime:
- New `container_events.go`: container event tracker producing Docker-vocabulary actions (`create`, `start`, `kill`, `stop`, `die`, `destroy`, `restart`, `health_status: ...`), `state` values (`created`, `running`, `exited`), health semantics.
- New `iface_stats.go`-based interface poller: one exec per pod per tick, `/proc/net/dev` + sysfs, producing netlink-attribute-compatible interface events (`create`/`update`/`delete`, `ifname`, `state`, `mtu`, `mac`, `alias`, `ifindex`, `type`, stats).
- Topology file recording: `containerlab.dev/topo-file` annotation on Topology (with Topology CR) or every Node (`--no-topology-cr`), carry-over on reconcile so a later deploy doesn't overwrite a Node's recorded file, `k8s://` fallback, `-t` override; events carry it as `clab-topo-file`.
- `inspect`/events enrichment: `TopoFile`, `Type`, `Group`, `TopologyName` from Node annotations/labels (`c9s.run/originalNodeName`, `c9s.run/direct-node-uid`), `newestPod` prefers non-deleting pods.
- Docs updates across three files; extensive unit tests (`event_parity_test.go`, `core/events/parity_test.go`, `runtime_gaps_test.go`, `labruntime_gaps_test.go`, `capture_test.go`, `clabernetes_test.go`) and a full robot lifecycle suite.

**Verification completed:**
- All 26 changed paths read/verified (manifest.json confirmed).
- diff.txt fully read.
- Callers traced: `setTopologySourceFile` (plan.go), `removeTopologySourceFile` (manifests.go, primitives.go), `carryOverNodeTopologyFile` (reconcile.go), `labNotFoundError` uses (container_events.go:117-123, events.go:119-127, lifecycle.go:478).
- Channel wiring verified (errs buffer 4 for 4 goroutine writers; errCh buffer 1; nil-channel select patterns correct).
- Attribute parity verified (netlink attributes, `state`/`status`/`health` vocabulary, `mgmt_ipv4` CIDR parsing via `splitManagementCIDR`).
- Docs cross-checked against implementation (events.md, interfaces.md, runtime.md events/topology-file/interface-events sections; `health: starting` status convention consistent in `core/labruntime.go:557`, `cmd/inspect.go:533-534`, docs).
- Robot suite read fully; expectations match implementation semantics.
- Tests surveyed (not executed — read-only snapshot constraint).

**Findings:** none actionable. All candidate issues raised during investigation were resolved by surrounding code, guards, or tests:
- Empty `state` attribute dropped by formatter (consistent behavior).
- errs channel sizing matches writer count.
- Annotation/label contracts match tests and robot expectations.
- timer.Reset usage safe.
- `managementAddress` handles plain-IP and CIDR forms.
- `containerFromLabNode` NodeType override consistent with docs and tests.
- `labNotFoundError` semantics coherent across tracker and event scope.

Coverage notes:
- No tests executed; the snapshot is read-only and command execution is not permitted. All conclusions are from source inspection.
- c9s CRD schemas (`topologies/nodes/links/nodeprofiles.c9s.run`) are external to containerlab; no `clab.schema.json` changes in this PR and none needed (annotation lives on c9s resources, outside the topology schema domain).
- Files not read line-by-line in full: portions of `core/labruntime.go` (1-360, 650-827), remainder of `stream.go` (130-652 beyond what was checked), and full test bodies beyond targeted greps; these were verified via targeted greps and diff coverage instead.
- `go test`/robot suite execution not possible here; test correctness asserted by reading test bodies and assertions only for the key tests.

Wait — should I double-check that I verified the remainder of stream.go (130-652)? My earlier notes say I read stream.go wiring at lines 32, 69, 83-110, 204, 253 via greps and the diff. The diff for stream.go was fully read. OK.

Also core/labruntime.go lines 1-360 and 650-827: my earlier session read 360-490 and 590-650; diff hunks fully read. Good enough — the changed hunks were fully reviewed.

Now the final output: Markdown review + JSON schema. Since there are no findings, the findings array is empty. Coverage complete = true, with honest notes.

Per instructions: "Return only supported, useful findings. Do not meet a finding quota. Put unresolved uncertainty in coverage notes; an empty findings list is valid after a complete review that found no actionable issues."

I'll write the Markdown review with a summary table (no findings), verification summary, and coverage notes, then the JSON block.
`health: starting` is a consistent convention across `core/labruntime.go:557`, `cmd/inspect.go:533-534`, the parity test, and the docs — not an issue. The review is complete.

---

# PR Review: c9s runtime event parity with Docker

## Summary

This PR brings the Clabernetes (c9s) lab runtime to parity with the Docker runtime for `events`, `inspect interfaces`, and lab provenance:

- **New `labruntime/clabernetes/container_events.go`**: a container event tracker that translates Node/Pod lifecycle into Docker's event vocabulary (`create`, `start`, `kill`, `stop`, `die`, `destroy`, `restart`, `health_status: starting|healthy|unhealthy`) with matching `state` values (`created`, `running`, `exited`).
- **Reworked `labruntime/clabernetes/iface_stats.go`**: interface events sourced from one exec per pod per tick (`/proc/net/dev` + sysfs) instead of per-interface lookups, with netlink-compatible attributes (`ifname`, `ifindex`, `mtu`, `state`, `type`, `mac`, `alias`) and stats.
- **Topology file recording**: the `containerlab.dev/topo-file` annotation is recorded on the `Topology` resource (or every `Node` with `--no-topology-cr`), carried over on reconcile so a later deploy from another file does not rewrite or restart a node, with `k8s://<namespace>/...` fallbacks and `-t` override; events carry it as `clab-topo-file`.
- **Inspect/events enrichment**: `TopoFile`, `Type`, `Group`, `TopologyName` on `NodeState` from Node annotations/labels (`c9s.run/originalNodeName`, `c9s.run/direct-node-uid`); `newestPod` prefers non-deleting pods.
- **Docs** (`docs/cmd/events.md`, `docs/cmd/inspect/interfaces.md`, `docs/manual/clabernetes/runtime.md`) and a full robot lifecycle suite update.

## Findings summary

| Priority | Count |
|---|---|
| P0 | 0 |
| P1 | 0 |
| P2 | 0 |
| P3 | 0 |
| P4 | 0 |

No actionable findings.

## What was verified

- **All 26 changed paths** confirmed against `/source/manifest.json` and each examined directly; the diff was read in full.
- **Callers traced**: `setTopologySourceFile` (`plan.go`), `removeTopologySourceFile` (`manifests.go`, `primitives.go`), `carryOverNodeTopologyFile` (`reconcile.go`), and `labNotFoundError` handling in `container_events.go:117-123`, `events.go:119-127`, `lifecycle.go:478`. The lab-not-found path ends streaming cleanly for scoped `events` and stops the tracker on lab deletion, matching the robot suite's destroy/redeploy expectations.
- **Channel wiring**: the `errs` channels in `events.go`/`container_events.go` are sized to the number of writing goroutines; `core/events/stream.go:83-86` uses a buffered `errCh` so the forwarder goroutine cannot leak. Nil-channel select patterns in `streamLabRuntimeEvents` are correct.
- **Attribute parity**: interface snapshot/stats attributes (`core/events/netlink.go:620-750`) and container attributes (`clab-node-name`, `clab-node-kind`, `clab-topo-file`, `mgmt_ipv4`, `ports`, `image`, `name`, `id`) match what `core/events/parity_test.go`, `event_parity_test.go`, and the robot keyword `Container Event Should Carry Docker Attributes` assert.
- **Management address parity**: `splitManagementCIDR` in `core/labruntime.go` handles both plain-IP and CIDR forms for LoadBalancer addresses, so `mgmt_ipv4` is always a CIDR as Docker reports.
- **Health/state semantics**: `containerHealth` maps an empty health on a running node to `starting`, keeps a previously healthy node `unhealthy` on regression in the same pod, and restarts health in a new pod — exercised by `TestContainerTransitionActions`, `TestContainerTrackerReportsTheNodeLifecycle`, and the robot `kill stop die` / `kill stop die start health_status: healthy` expectations. The `status` = `health: starting` convention is consistent across `core/labruntime.go:557`, `cmd/inspect.go:533-534`, the parity test, and the docs table.
- **Docs consistency**: the events/interfaces manual sections describe exactly what the implementation does (`eth0`/`lo` inclusion in `inspect interfaces`, their non-capturability, `veth`/`device` types, the topology-file recording and carry-over rules, `k8s://` fallbacks, `--emit-crs` manifests carrying no annotation — the last asserted by `TestManifestsCarryNoTopologyFile` and the robot `Should Not Contain ${emit.stdout} containerlab.dev/topo-file`).
- **Test coverage**: the new and updated tests cover the riskiest logic — tracker transitions, first-round poller suppression, per-pod deduplication of exec calls, `newestPod` deletion preference, topology-file recording/carry-over/reporting, namespace scoping, and netlink state-name mapping.

## Coverage notes

- No tests, benchmarks, or tools were executed; the review snapshot is read-only and command execution is not permitted. All conclusions come from source inspection.
- Files read in full: the complete diff, all new/changed clabernetes runtime sources, `core/events/stream.go` (wiring sections plus full diff), `core/events/netlink.go` (changed hunks plus surroundings), the robot suite, and the docs hunks. `core/labruntime.go` was read at the changed hunks and key helpers rather than every line.
- No `clab.schema.json` change is needed: the new `containerlab.dev/topo-file` annotation lives on c9s CRD resources, which are outside that schema's domain; c9s API shapes were only referenced via the testdata OpenAPI fixtures and the existing GVR constants.

```json
{
  "version": 1,
  "findings": [],
  "coverage": {
    "complete": true,
    "notes": [
      "No tests or commands were executed; the snapshot is read-only and execution is not permitted. All conclusions come from source inspection of the head/base trees and the full diff.",
      "All 26 changed paths from manifest.json were confirmed and examined; the diff was read in full, including hunks for core/events/netlink.go, core/events/stream.go, core/labruntime.go, the three docs files, all clabernetes runtime sources, and the robot suite.",
      "Callers and contracts were traced: setTopologySourceFile (plan.go), removeTopologySourceFile (manifests.go, primitives.go), carryOverNodeTopologyFile (reconcile.go), labNotFoundError handling in container_events.go, events.go, and lifecycle.go, plus errs/errCh channel sizing and nil-channel select patterns in stream.go.",
      "Candidate issues raised during investigation were each resolved by surrounding code or tests: empty state attributes are dropped by the formatter, errs channels are sized to writer count, the c9s.run/originalNodeName and c9s.run/direct-node-uid contracts match tests and docs, managementAddress handles plain-IP and CIDR forms, and the containerFromLabNode NodeType override matches documented -t behavior.",
      "Docs were cross-checked against the implementation: inspect interfaces eth0/lo inclusion and their non-capturability, the containerlab.dev/topo-file recording and carry-over rules, k8s:// fallbacks, and the health: starting status convention (core/labruntime.go, cmd/inspect.go, parity test, and the runtime.md table all agree).",
      "Test files were read and surveyed for coverage of the changed behavior (tracker transitions, poller suppression and dedup, topology-file recording/carry-over, namespace scoping) but not executed, so test correctness is asserted from reading them rather than from a run.",
      "No clab.schema.json change is required: the new annotation lives on c9s CRD resources, which are outside the topology schema's domain; c9s API shapes were referenced only via the existing GVR constants and testdata OpenAPI fixtures."
    ]
  }
}
```
step-finish
{
  "type": "step-finish",
  "id": "prt_1967aff33001XVRH48xNyWMVDv",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "messageID": "msg_1967ab9570011bq2FFkVR2Shqc",
  "reason": "stop",
  "cost": 0,
  "tokens": {
    "total": 42433,
    "input": 36573,
    "output": 1796,
    "reasoning": 1184,
    "cache": {
      "read": 2880,
      "write": 0
    }
  }
}
Message metadata
{
  "role": "assistant",
  "id": "msg_1967ab9570011bq2FFkVR2Shqc",
  "sessionID": "ses_e698b47ecffehEWZz1em8dWdsG",
  "time": {
    "created": 1793525987671,
    "completed": 1793526005563
  },
  "parentID": "msg_1967a36620015s1R3CwCc540iR",
  "modelID": "zai-org/GLM-5.3-Flash",
  "providerID": "tofarev",
  "mode": "tofarev",
  "agent": "tofarev",
  "path": {
    "cwd": "/tmp/tofarev-review-aS2Bo2",
    "root": "/"
  },
  "cost": 0,
  "tokens": {
    "total": 42433,
    "input": 36573,
    "output": 1796,
    "reasoning": 1184,
    "cache": {
      "read": 2880,
      "write": 0
    }
  },
  "finish": "stop"
}