Compare commits

...
Author SHA1 Message Date
dependabot[bot] 25af3d5fff Bump watchdog from 6.0.0 to 7.1.0
Bumps [watchdog](https://github.com/gorakhargosh/watchdog) from 6.0.0 to 7.1.0.
- [Release notes](https://github.com/gorakhargosh/watchdog/releases)
- [Changelog](https://github.com/gorakhargosh/watchdog/blob/master/changelog.rst)
- [Commits](https://github.com/gorakhargosh/watchdog/compare/v6.0.0...v7.1.0)

---
updated-dependencies:
- dependency-name: watchdog
  dependency-version: 7.1.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-19 11:22:57 +00:00
Guobin Yue 8411392233 Add snapshot description support (#3094)
Pass the description when creating a snapshot instead of silently
dropping it, and add a PUT endpoint to edit the description later.
An empty description resets to the default text. Also accept an
optional description in the MCP snapshot_create tool.
2026-11-16 14:24:20 +01:00
Guobin Yue fe51feec66 Fix console WebSocket authentication for nodes on remote computes (#3078)
* Use the compute credentials for console and VNC WebSocket forwarding

The controller forwarded the console and VNC WebSocket to a compute with
its own local server credentials instead of the credentials stored on the
compute. Any remote compute with its own credentials rejected the
connection with a 401 error, so the web console could not open for nodes
running on a remote compute.

Fixes #3076

* Do not start the console when compute WebSocket authentication fails

The VPCS and VirtualBox console WebSocket routes still called
start_websocket_console() with None after the authentication dependency
rejected the client and closed the socket. The handler crashed with
"AttributeError: 'NoneType' object has no attribute 'client'".

Add the same guard the other node types already have. See #3076
2026-11-14 18:58:44 +01:00
Jeremy 3aaf125b88 Merge pull request #3074 from GNS3/feat/pcie-network-layout
Add PCIe network layout support with adapter limits and compatibility checks
2026-11-14 16:47:07 +01:00
Jeremy Grossmann 7b1d09d97d Merge pull request #3075 from GNS3/feat/default-symbol-appliances
Add support for symbol resolution based on active theme for appliances
2026-11-13 06:34:58 +01:00
grossmj 6289f81298 feat: add support for symbol resolution based on active theme in appliance templates 2026-11-13 12:08:36 +07:00
Jeremy Grossmann 8cd82f3b6c Merge pull request #3073 from GNS3/dependabot/pip/3.1/langchain-anthropic-gte-1.7.10
Update langchain-anthropic requirement from >=1.3.4 to >=1.7.10
2026-11-12 12:55:22 +01:00
Jeremy Grossmann 89b88a5e88 Merge pull request #3072 from GNS3/dependabot/pip/3.1/websockets-17.4
Bump websockets from 16.1.1 to 17.4
2026-11-12 12:55:08 +01:00
Jeremy Grossmann c24e332d79 Update requirements.txt 2026-11-12 12:44:42 +01:00
Jeremy Grossmann dbee7110da Merge pull request #3071 from GNS3/dependabot/pip/3.1/sqlalchemy-2.1.8
Bump sqlalchemy from 2.1.6 to 2.1.8
2026-11-12 12:39:26 +01:00
Jeremy Grossmann 5e30ce4b13 Merge pull request #3070 from GNS3/dependabot/pip/3.1/nornir-gte-3.6.1
Update nornir requirement from >=3.6.0 to >=3.6.1
2026-11-12 12:39:08 +01:00
Jeremy Grossmann e142aa68bd Merge pull request #3069 from GNS3/dependabot/pip/3.1/paramiko-gte-5.1.0
Update paramiko requirement from >=5.0.0 to >=5.1.0
2026-11-12 12:38:50 +01:00
dependabot[bot] 4f79fc21db Update langchain-anthropic requirement from >=1.3.4 to >=1.7.10
Updates the requirements on [langchain-anthropic](https://github.com/langchain-ai/langchain) to permit the latest version.
- [Release notes](https://github.com/langchain-ai/langchain/releases)
- [Commits](https://github.com/langchain-ai/langchain/compare/langchain-anthropic==1.3.4...langchain-anthropic==1.7.10)

---
updated-dependencies:
- dependency-name: langchain-anthropic
  dependency-version: 1.7.10
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-12 11:23:07 +00:00
dependabot[bot] 353ca2ec93 Bump websockets from 16.1.1 to 17.4
Bumps [websockets](https://github.com/python-websockets/websockets) from 16.1.1 to 17.4.
- [Release notes](https://github.com/python-websockets/websockets/releases)
- [Commits](https://github.com/python-websockets/websockets/compare/16.1.1...17.4)

---
updated-dependencies:
- dependency-name: websockets
  dependency-version: '17.4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-12 11:22:56 +00:00
dependabot[bot] dd429e9385 Bump sqlalchemy from 2.1.6 to 2.1.8
Bumps [sqlalchemy](https://github.com/sqlalchemy/sqlalchemy) from 2.1.6 to 2.1.8.
- [Release notes](https://github.com/sqlalchemy/sqlalchemy/releases)
- [Changelog](https://github.com/sqlalchemy/sqlalchemy/blob/main/CHANGES.rst)
- [Commits](https://github.com/sqlalchemy/sqlalchemy/commits)

---
updated-dependencies:
- dependency-name: sqlalchemy
  dependency-version: 2.1.8
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-12 11:22:49 +00:00
dependabot[bot] 6891e7e66f Update nornir requirement from >=3.6.0 to >=3.6.1
Updates the requirements on [nornir](https://github.com/nornir-automation/nornir) to permit the latest version.
- [Release notes](https://github.com/nornir-automation/nornir/releases)
- [Changelog](https://github.com/nornir-automation/nornir/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/nornir-automation/nornir/compare/v3.6.0...v3.6.1)

---
updated-dependencies:
- dependency-name: nornir
  dependency-version: 3.6.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-12 11:22:40 +00:00
dependabot[bot] 984bf4232d Update paramiko requirement from >=5.0.0 to >=5.1.0
Updates the requirements on [paramiko](https://github.com/paramiko/paramiko) to permit the latest version.
- [Commits](https://github.com/paramiko/paramiko/compare/5.0.0...5.1.0)

---
updated-dependencies:
- dependency-name: paramiko
  dependency-version: 5.1.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-12 11:22:34 +00:00
Jeremy Grossmann ce8d5591a1 Merge pull request #3062 from yueguobin/feat/docker-image-upload
Allow uploading, deleting and pulling Docker images on computes
2026-11-07 16:49:26 +01:00
YueGuobin c066434959 refactor: move Docker image management to its own module
pull, load, list and delete images, the image id translation bookkeeping
and their helpers move from the Docker manager to DockerImagesMixin in
docker_images.py. The manager keeps the daemon connection, the HTTP layer
and the node factory. The mixin is listed before BaseManager so its
list_images overrides the file-system one. The C901 ruff exemption moves
with pull_image.
2026-11-07 19:36:00 +08:00
YueGuobin 653ea386a5 fix: use the OCI created label when the daemon reports no build time
Images built for reproducibility, such as the Ubuntu images assembled
with rockcraft, carry no created timestamp in their config and Docker
reports 0, shown as 1970-01-01. Fall back to the
org.opencontainers.image.created label in list_images so the image list
shows the real build time.
2026-11-07 19:27:55 +08:00
YueGuobin 076c949a4e fix: default tagless Docker image pulls to the latest tag
The daemon pulls every tag of a repository when the tag parameter is
empty. The docker CLI never hits this because it adds :latest before
calling the API, so only raw API callers do. Pulling "debian" through
the API downloaded dozens of images until the registry rate limit
stopped the pull.

Pass tag=latest when the reference has no tag and no digest. Only a
':' after the last '/' counts as a tag separator: before it, it is a
registry port (e.g. registry:5000/repo).

This covers both the /docker/images/pull route and the automatic pull
fallback when a node image is missing.
2026-11-07 14:43:13 +08:00
Jeremy Grossmann 01c20adac5 Merge pull request #3065 from yueguobin/feat/project-privileges-endpoint
Add endpoint for the current user's privileges on a project
2026-11-07 05:31:29 +01:00
Jeremy Grossmann fcf8490d90 Merge pull request #3064 from yueguobin/feat/rbac-in-memory
Keep RBAC state in memory for permission checks
2026-11-07 05:27:01 +01:00
YueGuobin f8eedae9fc feat: add endpoint for the current user's privileges on a project
GET /projects/{project_id}/me/privileges returns the effective privileges
of the logged in user, evaluated on the project's resource path. Unlike
/access/users/me/privileges, ACEs scoped to the project and resource
pools containing it are reflected. This gives clients what they need to
show or hide buttons inside a project view.
2026-11-07 00:27:32 +08:00
YueGuobin 0914f44273 fix: use the /access prefix when cleaning up ACEs on delete
The users, groups and roles routes are mounted under /access and ACE
paths follow the real route paths. The cleanup after deleting a user,
group or role looked at /users, /groups and /roles, so it never matched
any ACE. Typed ACEs were still removed by the foreign key cascade, but
an ACE on the resource path granted to another principal survived the
deletion.
2026-11-07 00:02:20 +08:00
YueGuobin f87f20cb27 fix: commit the bulk ACE deletion in the repository
delete_all_ace_starting_with_path was the only RBAC write method
without a commit. The request session is only closed at teardown, so
the deletion was rolled back and the ACEs came back on the next
snapshot reload. Tests did not catch it because they share one
session for the whole class.
2026-11-06 23:55:12 +08:00
YueGuobin 2244d730bb perf: keep RBAC state in memory for permission checks
Permission checks ran several queries per request, including a full
scan of the resources table. The controller already keeps projects,
computes and notifications in process memory: apply the same idea to
the RBAC tables.

Roles, ACEs, group memberships and resource pool memberships are
loaded into a process-wide snapshot. Checks run against the snapshot
in memory. Repository write methods mark the snapshot dirty and the
next read reloads it from the database, so privilege changes apply
right away. The database stays the source of truth.

The evaluation is a faithful port of the previous SQL version, quirks
included (reverse path traversal, deny raising PermissionError, pool
checks with the "/pool" prefix, group ACEs in natural order).

The two RBAC tests that mutated ORM objects directly now write through
the repository, like the rest of the code. The /projects ACE they
relied on was created by another test, so they were order dependent:
they now create it when missing.
2026-11-06 23:47:29 +08:00
YueGuobin c846c2ae90 fix: refuse Docker image deletion while templates reference the image
A deletion the user must confirm belongs in the response of the delete
request, not in a notification sent after the fact. The controller now
refuses with a 409 (code image_referenced_by_templates, the template
names in details) while any Docker template references the image,
before the compute is touched. force=true confirms the deletion.

The docker.image.deleted notification stays as a change signal so
clients can refresh their image lists.
2026-11-06 22:15:52 +08:00
YueGuobin de986e890e feat: name nodes and templates in Docker image delete conflicts
The compute translates the container ids in a daemon delete conflict
into the GNS3 node and project behind each container. Leftover
containers from closed projects and containers created outside GNS3
are named as such.

The controller lists the templates referencing the image in the
conflict error, matched through the canonical image name. After a
successful deletion it emits a docker.image.deleted notification with
those templates: their nodes can no longer start.
2026-11-06 22:05:52 +08:00
YueGuobin 04a8ba06a8 fix: start pull events when the pull begins and reject unsafe image names
The pull started event was emitted by the route before the pull took
its per compute lock, so a request queued behind another pull claimed
to be running while it was still waiting. The pull now reports the
started state itself, once it owns the lock.

Deleting an image interpolates the name into the daemon API path. The
pattern on the path parameter limits it to the characters of an image
reference and validate_docker_image_name also rejects "..", so a name
cannot escape that path. Applied on both the controller and compute
routes.
2026-11-06 15:42:51 +08:00
YueGuobin d5d25eba06 fix: stop reporting a missing image as a network problem
A 404 from the registry means the image name is wrong or the registry
needs authentication, but the pull wrapped every error with "please
check your Internet connection". Say what actually failed and keep the
network advice for the other errors.
2026-11-06 15:23:34 +08:00
YueGuobin 8c98142d26 feat: report Docker pull progress and add an idle timeout
A pull now reports docker.image.pull notifications on the controller
stream: started, throttled downloading events with the layer counts
and the latest daemon message, then completed or failed. An optional
progress_id is echoed in every event so a client can correlate them
with its own request. Image operations belong to a compute, not to a
project, so the events go to the controller stream and reach clients
that have no project open.

The pull also has an idle socket read timeout of 60 seconds. Without
it an unreachable registry left the pull, the compute request and the
client request hanging forever with no feedback at all. The timeout
is idle time, not total time: the daemon streams progress during the
whole pull, so a minute without data means the registry is gone. When
it fires, the daemon connection closes and Docker cancels the pull.

Docker.http_query now accepts an aiohttp ClientTimeout object so a
caller can ask for a policy finer than a total timeout.
2026-11-06 15:03:34 +08:00
YueGuobin 424ba919d8 fix: skip non-image files when scanning the image roots
The image inventory scanned every file under the image roots and
reported anything without an image header as an invalid image. Files
users legitimately keep next to their images, such as the Cisco IOU
keygen script, made every scan report errors and the sync job partial.

Extend the existing ignore filter with the extensions of scripts,
documentation and certificates. They are skipped by both the scan and
the file watcher, so they no longer trigger rescans either. Real
corrupted images are still reported.
2026-11-06 14:36:03 +08:00
YueGuobin 54cfcef6e2 fix: send the docker force query parameter as a string
The aiohttp URL builder only accepts strings, ints and floats as query
values and raises a TypeError on a Python bool, so deleting an image
answered a 500. Send true/false like the controller does.
2026-11-06 14:31:26 +08:00
YueGuobin c1e03194d3 api: list Docker image details and delete images
GET /computes/{compute_id}/docker/images now returns the daemon image
id, size and creation date in addition to the tag, so a UI can show
and compare images instead of bare names. The fields are optional to
keep the response compatible with older computes.

Add DELETE /computes/{compute_id}/docker/images/{image} which removes
the image from the compute Docker daemon. The image name is passed as
a path so names with a slash or a tag separator work. A daemon that
refuses because a container uses the image answers a conflict; the
force query parameter removes it anyway.

The compute also drops the controller digest to local id translation
recorded when the image was synced, since it no longer matches
anything on the daemon.
2026-11-06 14:22:22 +08:00
YueGuobin 4c00d223e4 fix: pass the leading slash to the compute load endpoint path
getUrl joins the path directly after /v3/compute, so a path without
the leading slash produces /v3/computedocker/images/load and the
compute answers 404. Match the path shape used by forward() and the
image sync path.
2026-11-06 12:46:21 +08:00
YueGuobin 092202615e api: add controller endpoint to load Docker images on a compute
Add POST /computes/{compute_id}/docker/images/load. It streams an
uploaded docker save tar (plain or gzip) to the compute, which loads
it into its Docker daemon. Clients can now install image packages
such as iol-xe-17-18-02.tar.gz without SSH access to the server.

The body is proxied without buffering (async iterable to chunked
transfer) and runs with no total timeout, like the existing image
sync path between computes.
2026-11-06 10:00:17 +08:00
Jeremy Grossmann 111a4b756c Merge pull request #3061 from yueguobin/fix/remove-ace-route-dump
Remove leftover debug print dumping all routes on ACE creation
2026-11-05 17:26:11 +01:00
Jeremy Grossmann c80bea5279 Merge pull request #3060 from yueguobin/feat/user-privileges-endpoint
Add endpoint returning the current user's privileges
2026-11-05 17:25:29 +01:00
YueGuobin 425d91c085 fix: remove leftover debug print dumping all routes on ACE creation
Creating an ACE printed every route path of the application to stdout.
The debug loop was left behind when the route iteration moved to
_iter_route_paths() in 021991410.
2026-11-05 23:13:42 +08:00
YueGuobin 3ddfe0254d api: add endpoint returning the current user's privileges
Add GET /access/users/me/privileges. It returns the effective privileges
of the logged in user, flattened across all roles assigned to the user
(directly or through group membership). Superadmins get the full
privilege list.

This gives clients a way to render their UI based on permissions. The
server stays the authority for permission checks: a privilege in the
list can still be denied on a specific resource path.
2026-11-05 23:05:28 +08:00
Jeremy Grossmann 94077b4884 Merge pull request #3051 from GNS3/arm64-qemu-support
Enhance aarch64 support with UEFI and improved console options
2026-11-05 14:06:29 +01:00
Jeremy Grossmann 2e5e761c3e Merge pull request #3057 from GNS3/dependabot/pip/3.1/langgraph-gte-1.2.19
Update langgraph requirement from >=1.0.9 to >=1.2.19
2026-11-05 14:04:49 +01:00
Jeremy Grossmann ac54b6d717 Merge branch '3.1' into dependabot/pip/3.1/langgraph-gte-1.2.19 2026-11-05 13:21:28 +01:00
Jeremy Grossmann ddd1f61b6a Merge pull request #3056 from GNS3/dependabot/pip/3.1/python-dotenv-gte-1.2.4
Update python-dotenv requirement from >=1.2.1 to >=1.2.4
2026-11-05 13:20:27 +01:00
Jeremy Grossmann 0a04d084cc Merge pull request #3055 from GNS3/dependabot/pip/3.1/langchain-core-gte-1.7.3
Update langchain-core requirement from >=1.2.16 to >=1.7.3
2026-11-05 13:20:01 +01:00
Jeremy Grossmann 0331cfd2f3 Merge pull request #3054 from GNS3/dependabot/pip/3.1/langchain-openai-gte-1.7.3
Update langchain-openai requirement from >=1.7.2 to >=1.7.3
2026-11-05 13:19:44 +01:00
Jeremy Grossmann d6e70da9ff Merge pull request #3053 from GNS3/dependabot/pip/3.1/langgraph-checkpoint-sqlite-gte-3.1.3
Update langgraph-checkpoint-sqlite requirement from >=3.1.2 to >=3.1.3
2026-11-05 13:19:29 +01:00
Jeremy Grossmann 5943887031 Merge pull request #3058 from GNS3/dependabot/pip/3.1/langchain-xai-gte-1.3.0
Update langchain-xai requirement from >=1.2.2 to >=1.3.0
2026-11-05 13:19:06 +01:00
Jeremy Grossmann b539793281 Merge pull request #3059 from yueguobin/fix/duplicate-project-created-by
fix: attribute duplicated project to the user who duplicated it
2026-11-05 12:49:08 +01:00
dependabot[bot] c327055703 Update langchain-xai requirement from >=1.2.2 to >=1.3.0
Updates the requirements on [langchain-xai](https://github.com/langchain-ai/langchain) to permit the latest version.
- [Release notes](https://github.com/langchain-ai/langchain/releases)
- [Commits](https://github.com/langchain-ai/langchain/compare/langchain-xai==1.2.2...langchain-xai==1.3.0)

---
updated-dependencies:
- dependency-name: langchain-xai
  dependency-version: 1.3.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-05 11:26:06 +00:00
dependabot[bot] 9429dad9d0 Update langgraph requirement from >=1.0.9 to >=1.2.19
Updates the requirements on [langgraph](https://github.com/langchain-ai/langgraph) to permit the latest version.
- [Release notes](https://github.com/langchain-ai/langgraph/releases)
- [Commits](https://github.com/langchain-ai/langgraph/compare/1.0.9...1.2.19)

---
updated-dependencies:
- dependency-name: langgraph
  dependency-version: 1.2.19
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-05 11:23:29 +00:00
dependabot[bot] 2480fb669e Update python-dotenv requirement from >=1.2.1 to >=1.2.4
Updates the requirements on [python-dotenv](https://github.com/theskumar/python-dotenv) to permit the latest version.
- [Release notes](https://github.com/theskumar/python-dotenv/releases)
- [Changelog](https://github.com/theskumar/python-dotenv/blob/main/CHANGELOG.md)
- [Commits](https://github.com/theskumar/python-dotenv/compare/v1.2.1...v1.2.4)

---
updated-dependencies:
- dependency-name: python-dotenv
  dependency-version: 1.2.4
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-05 11:23:18 +00:00
dependabot[bot] 70155eac83 Update langchain-core requirement from >=1.2.16 to >=1.7.3
Updates the requirements on [langchain-core](https://github.com/langchain-ai/langchain) to permit the latest version.
- [Release notes](https://github.com/langchain-ai/langchain/releases)
- [Commits](https://github.com/langchain-ai/langchain/compare/langchain-core==1.2.16...langchain-core==1.7.3)

---
updated-dependencies:
- dependency-name: langchain-core
  dependency-version: 1.7.3
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-05 11:23:13 +00:00
dependabot[bot] e7b901de30 Update langchain-openai requirement from >=1.7.2 to >=1.7.3
Updates the requirements on [langchain-openai](https://github.com/langchain-ai/langchain) to permit the latest version.
- [Release notes](https://github.com/langchain-ai/langchain/releases)
- [Commits](https://github.com/langchain-ai/langchain/compare/langchain-openai==1.7.2...langchain-openai==1.7.3)

---
updated-dependencies:
- dependency-name: langchain-openai
  dependency-version: 1.7.3
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-05 11:22:59 +00:00
dependabot[bot] 6a7c9e4417 Update langgraph-checkpoint-sqlite requirement from >=3.1.2 to >=3.1.3
Updates the requirements on [langgraph-checkpoint-sqlite](https://github.com/langchain-ai/langgraph) to permit the latest version.
- [Release notes](https://github.com/langchain-ai/langgraph/releases)
- [Commits](https://github.com/langchain-ai/langgraph/compare/checkpointsqlite==3.1.2...checkpointsqlite==3.1.3)

---
updated-dependencies:
- dependency-name: langgraph-checkpoint-sqlite
  dependency-version: 3.1.3
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-05 11:22:40 +00:00
YueGuobin 517b0b0d85 fix: attribute duplicated project to the user who duplicated it
duplicate() kept the original author in created_by. The project list
filters on created_by, so a non-admin user could not see the copy they
just made. Pass the caller through both duplication paths, the same way
import already does since #3017.
2026-11-05 19:22:27 +08:00
Jeremy Grossmann 7230e86c15 Merge pull request #3052 from yueguobin/fix/legacy-project-list-visibility
fix: keep legacy projects visible to non-admin users
2026-11-05 09:49:00 +01:00
YueGuobin 70ef92b55f fix: keep legacy projects visible to non-admin users
Projects created before GNS3 3.1 have no created_by field. The project
list filtered them out for every non-superadmin user, so all old
projects disappeared from the list after an upgrade.

Fall back to the pre-3.1 ACE-only visibility rule when created_by is
not set. Projects owned by another user stay hidden.
2026-11-05 15:42:51 +08:00
grossmj 5e11378a03 feat(qemu): improve UEFI boot configuration and add KVM acceleration warning 2026-11-04 13:07:21 +07:00
Jeremy Grossmann bbb1dc4f80 Merge pull request #3050 from yueguobin/fix/graceful-shutdown-timeout
Bound graceful shutdown and stop notification WebSockets on exit
2026-11-04 06:40:42 +01:00
YueGuobin a56fce4c36 fix: do not monkeypatch attributes on Starlette State in tests
pytest 9.2 reads the old value of a monkeypatched attribute from the
instance __dict__. Starlette State keeps attributes in an internal
dict, so the old value looks unset and the teardown deletes the
attribute for the rest of the test session. The first test that
touches app.state.exiting passes but removes it, and every later
monkeypatch.setattr on it fails with AttributeError.

Use plain assignments instead.
2026-11-04 09:22:15 +08:00
grossmj 0a88127e33 feat(qemu): enhance aarch64 support with UEFI and improved console options 2026-11-04 00:31:52 +07:00
Guobin Yue 8f763c0439 Merge branch '3.1' into fix/graceful-shutdown-timeout 2026-11-04 00:59:22 +08:00
Jeremy Grossmann 9bcffab41e Merge pull request #3049 from yueguobin/copilot-tool-name-align
copilot: reuse MCP tools, align tool names, and manage the step budget
2026-11-03 17:37:42 +01:00
YueGuobin 52c19002f2 fix: bound graceful shutdown and stop notification WebSockets on exit
By default uvicorn waits for open connections forever. A long-lived
streaming response keeps the server waiting after Ctrl+C. One common
case is the MCP Streamable HTTP transport: the client opens a
standalone GET request and the server answers with an SSE stream
(not the old SSE transport). A second Ctrl+C sets force_exit. Uvicorn
then skips the lifespan shutdown, so project and controller cleanup
does not run.

Add timeout_graceful_shutdown. After the timeout uvicorn cancels the
remaining tasks and runs the lifespan shutdown. Also make the four
notification WebSocket handlers stop when app.state.exiting is set.
The HTTP stream handlers already do this.
2026-11-04 00:32:34 +08:00
YueGuobin 42e0a5dd5b fix(copilot): bound LLM requests with a timeout and one retry
A field log showed one request stayed silent for 604s (the OpenAI SDK
default timeout), then the SDK retried on a fresh connection and got
200 OK in under a second. The abort signal did not cancel the in-flight
HTTP call, so the turn could look hung for ten minutes.

- set timeout (default 120s, request_timeout in the LLM config wins),
  max_retries=1 and stream_usage=True for the providers that accept them
  (openai, deepseek, anthropic, xai). ollama and google-genai reject
  these kwargs, so they keep the old behavior.
- log the elapsed time of each LLM call. A slow first token or an SDK
  retry now shows up in the log line.
- add request_timeout to the LLM config schemas and docs (JSON column,
  no migration).
- tests: cover the defaults, the override, invalid values, provider
  filtering and the title model.
2026-11-03 23:57:07 +08:00
YueGuobin f2f42c4817 docs(mcp): document show_filters_icon on link tools
The server link schema has show_filters_icon (default true) and the PUT
passes it through, but the MCP tool docs did not mention it. The old
copilot packet filter tool always set it to false to hide the filter icon
during fault injection; after the move to link_update the icon stayed
visible because the model had no way to know the field exists.

- link_update: add show_filters_icon to the supported kwargs
- link_list: add show_filters_icon to the available response fields
2026-11-03 23:19:00 +08:00
YueGuobin 5a294461e8 fix(copilot): make the step budget real, configurable and visible
The graph passed remaining_steps=20 (50 for injection) in the run inputs.
RemainingSteps is a LangGraph managed value derived from recursion_limit,
so the input was ignored and the real budget was 25 (100 for injection).
No one could see those numbers, and a turn that hit the cap ended on a
bare tool result with no explanation.

- Remove the dead remaining_steps input.
- Add resolve_recursion_limit(): max_steps from the LLM model config wins;
  otherwise 25 teaching_assistant, 50 lab_automation_assistant, 100
  troubleshooting_injection.
- When fewer than 4 steps remain after a tool run, route to the new
  budget_wrapup node. The next llm_call binds no tools and gets a wrap-up
  instruction, so the turn ends with a short summary of what was done and
  what remains.
- should_continue skips the title call after a wrap-up (no step left).
- budget_exhausted is reset at the start of every user turn.
- Add max_steps to the LLM config schemas. The config is a JSON column,
  so no migration is needed.
- Tests: 16 new tests cover the resolver, the routing, the tool-free
  wrap-up call and the removed input. Docs updated.
2026-11-03 23:16:26 +08:00
YueGuobin e8462507a5 feat(copilot): surface console, snapshot, capture and marker tools per mode
The bridge made 49 project-scoped MCP tools available, but the mode
tables still mirrored the old copilot capability set. Expand them:

- lab_automation_assistant: node_console_exec (raw console for nodes
  without a device_type tag), node_list, snapshot_list/create/delete/
  restore
- teaching_assistant: node_list/node_get, link_list, link_marker
  (read-only diagnostics plus traffic-insight markers)
- troubleshooting_injection: link_capture_start/stop/download and
  marker_definition (inject -> capture -> verify loop)

Also fix the tools_by_name registry: it was built from the lab and
injection tables only, which worked while teaching was a strict subset
of lab. Teaching-only tools would have raised KeyError in tool_node
when the LLM called them; the registry now unions all three mode
tables. A new test pins each mode's exact toolset, checks that no
administration tool leaks in, and asserts every referenced name is
resolvable.
2026-11-03 22:57:09 +08:00
YueGuobin 6a4cbe39c1 refactor(copilot): reuse MCP tools via a bridge; extract shared device runners
The copilot and the MCP service maintained two parallel wrapper layers
(LangChain BaseTool classes vs @mcp.tool() functions) over the same
handlers in gns3_client/api_handlers.py. Descriptions and parameters
drifted apart (compute_id and link_type were missing on the copilot
side). This makes the MCP registration the single source of truth and
removes the duplicated wrappers.

tools_v2/mcp_bridge.py adapts the MCP server's tool registration into
LangChain tools: names, descriptions and argument schemas come from the
MCP tools. The pool is filtered to project-scoped tools
(MCP_ALLOWED_TOOLS) because the copilot runs inside one open project —
project management, compute/appliance/image administration and server
info tools stay out. The bridge carries the copilot's request JWT into
the MCP contextvars (username/token_version decoded from the token so
ticket-minting tools work) and runs the async MCP functions from the
copilot's sync tool node on either thread flavor.

Mode toolsets (teaching / lab_automation / troubleshooting_injection)
are now composed from adapted MCP tools plus a few copilot-native ones
that add value the MCP versions lack: link_create (port-name
resolution), wait_seconds, packet_analysis(+skills), and the topology
reader. Eight orphaned LangChain wrappers are deleted.

The device command tools had the dependency inverted (the MCP handlers
instantiated the copilot LangChain classes and round-tripped through
JSON strings). The Nornir/Netmiko classes moved verbatim (git mv) into
the shared layer as plain runners — DeviceConfigCommandRunner,
DeviceShowCommandRunner, VpcsCommandRunner — with _run(json_string)
becoming run(params, gns3_ctx). The optional Jinja2 template rendering
moved from the MCP handlers into the runners (and into
utils/device_configs.render_device_template), so both entry paths get
it; the MCP handlers are now pure delegation. This also drops the
json.dumps/json.loads detour the MCP path used to take.

test_tool_params consistency gate extended: a handler that forwards the
whole params dict to a callee is a wildcard (same rationale as the
params.items() case) — the per-key check cannot see through delegation.
2026-11-03 22:04:57 +08:00
YueGuobin 9c27a293d0 refactor(copilot): align tool names with MCP convention
Rename five copilot tools to the MCP <object>_<verb> naming so both
agent surfaces expose the same names:

- create_gns3_node              -> node_create
- create_gns3_link              -> link_create
- create_gns3_text_drawing      -> drawing_create_text
- create_gns3_rectangle_drawing -> drawing_create_rectangle
- create_gns3_ellipse_drawing   -> drawing_create_ellipse

Also close two capability gaps found during the comparison:

- node_create: accept optional per-node compute_id (passed through to
  the shared handler; before, every node landed on local)
- link_create: accept optional per-link link_type (ethernet default,
  serial supported; before, serial links were impossible)

All tools keep calling the same shared handlers in
gns3_client/api_handlers.py, so the rename has no effect on execution
semantics. Old names appeared nowhere else (prompts, tests, mode tool
lists are clean); docs updated accordingly.
2026-11-03 15:30:44 +08:00
Jeremy Grossmann bfe25641fc Merge pull request #3048 from yueguobin/mcp-console-exec-websocat
feat(mcp): node_console_exec — run console commands in one tool call
2026-11-03 06:22:26 +01:00
YueGuobin c63b2e3e14 docs(mcp): node_console_exec — QEMU serial getty login needs one call
Field finding from the smoke test: login flushes typed-ahead input
before printing "Password: ", so a password sent in a separate call is
lost (Login incorrect loop). Sending username and password in the same
command string logs in reliably; the shell then persists across calls.
2026-11-03 00:32:55 +08:00
YueGuobin 78199d14a4 fix(mcp): collect the console stream in websocat binary mode (-b)
websocat's text mode (-t, and also the default) appends a newline after
every received WebSocket message and turns CR/LF inside a message into
spaces. The compute ships console output as one BINARY frame per
arbitrary read(1024) burst, so text mode diced the stream at every frame
boundary — prompts split into pieces, short "narrow-column" lines, lost
carriage-return redraws (field report: Password: broken in three).

Measured against a local WS server sending known frames:
  -t:  A\nB\nC\na b\na  b\n  ("a\rb" -> "a b")
  -b:  ABCa\rba\r\nb        (byte-exact, both directions)

Binary command frames stay console data on the compute side (only a line
that is itself a JSON {cols,rows} object would be taken as a resize
frame). The regression test fails on -t and passes on -b.
2026-11-03 00:02:58 +08:00
YueGuobin 7bf18ac2e8 feat(mcp): node_console_exec — one-shot console session via the host's websocat
Replaces node_console (which handed a URL + ticket to the client for a
bash websocat chain) with a tool that runs the whole session server-side:
spawn `timeout N websocat -t --no-close <console-ws-url>`, feed the
command lines through stdin (paced, CRLF), read stdout until the timeout
kills websocat, return the collected output as plain text.

- plain text replies: "output: ..." or bare error text — no JSON
  envelope, no status field (the server cannot judge command success)
- raw output: UTF-8 decode with replacement only, no telnet/ANSI
  stripping; control keys are real characters (description teaches
  \u0003, no \x03 translation)
- output funnel: grep=<python regex> filter; <=50 lines return as-is;
  beyond that a 10-line sample plus hints — regrep=true re-filters the
  node's cached capture (no re-run), full=true returns the last 400
  lines / 64 KiB, and the full capture is written to the node's files
  (console-capture.txt) with a ticketed curl download URL
- get_node_console_info_handler removed with its hashlib/TTL imports;
  the node-bound console ticket redemption path stays (comment updated,
  no current producer)
2026-11-02 22:52:46 +08:00
Jeremy Grossmann 0afd646856 Merge pull request #3039 from yueguobin/mcp-console-exec
MCP: Streamable HTTP transport (SDK 2.3) + skills knowledge tools + VPCS/auth fixes
2026-11-02 03:55:27 +01:00
yueguobin 92feea2a51 test(vpcs): assert the pcname-derived prompt pattern
The window-size tests still asserted the old hardcoded PC\d+> default;
the driver now derives the prompt from the node name.
2026-11-01 23:09:38 +08:00
yueguobin efc097f0ad feat(mcp): injection_skill_get — expose fault-injection skills to MCP
The skills repository carries per-protocol fault-injection knowledge
(symptoms, injection commands, verification steps) that only the
copilot could read through InjectionSkillsTool. Add the MCP counterpart
with the same multi-call protocol:

  list (context REQUIRED) -> category index -> single fault

The list step is topology-filtered: context matches a skill's category,
key and declared protocols (case-insensitive), so aliases such as ebgp,
ospfv3 and stp select the right category instead of relying only on key
substrings. Fault bodies stay gated behind detail/issue requests.

Fault category keys are derived from repository filenames
(injection_<file>_issues). Correct the stale injection_ospf examples in
the registry docstrings, the loader comment and the copilot docs, which
pointed at keys that never existed.

Docs: 84 tools; new Fault Injection Skills section.
2026-11-01 23:09:38 +08:00
yueguobin 21fb84e91c fix(skills): load categories independently and support non-git checkouts
SkillsManager refused to start when the local skills directory was not a
git repository (cloning into a non-empty path fails), and reload_skills()
returned early when injection/ was missing, so device and feature skills
never loaded. reload_packet_analysis_protocols() had the opposite bug:
an empty result wiped the registry while still reporting success.

- initialize(): accept a non-empty directory without .git as a local-only
  source (skip automatic updates, keep loading files); degrade to local
  files when GitPython is unavailable.
- _update_if_needed(): re-create/clone when the local directory vanished
  or moved, instead of reusing a stale handle forever.
- reload_skills(): injection, device and feature load independently; a
  missing category keeps its previously loaded entries.
- reload_packet_analysis_protocols(): an empty/missing directory keeps
  the existing registry and reports failure.
- reload_skills_repository(): drop the console guard cache so
  config/console_guard.txt applies on reload.

MCP device_skill_get now exposes the category filter, documents the
single-file (topic-less) layout, and returns a sections list for
index/summary of skills that have no topics/issues. An uninitialized
skills repository fails with a clear error instead of an empty list.
2026-11-01 23:09:38 +08:00
yueguobin 5ed252455d feat(mcp): device_skill_get — expose the GNS3-Skills repository to MCP clients
The skills repository carries per-device operational knowledge the
generic tools cannot know (FRR's console lands in vtysh, its ping has
no -c, scripted config needs 'do' prefixes; VPCS syntax; IOS paging
pitfalls), but only the embedded copilot could read it — MCP's sole
consumer was console_guard.txt.

device_skill_get reuses the copilot's framework-free core
(get_skill/list_available_skills) rather than the LangChain tool shell,
so both surfaces share the same access protocol by construction:
list -> device topic index -> one targeted topic body, bodies only on
an explicit topic request. The caller passes the skill key exactly as
the list returned it; there is no name mapping or node-based resolution
in this layer.

The tool description also tells clients that support subagents to
delegate the discovery steps on long tasks, keeping the full skill
bodies out of the main conversation's context.
2026-11-01 23:09:38 +08:00
yueguobin abb59b3d06 test(vpcs): mock read_channel in the strip-ansi test
The send_command read loop polls read_channel (netmiko decorates it
with a session-lock wrapper that only __init__ can satisfy), so the
old read_until_pattern mock died with AttributeError on instances
built via __new__.
2026-11-01 23:09:38 +08:00
yueguobin b184ea4c70 fix(mcp): renew an API-key session's JWT when it ages out
Tool handlers run in the session task created at initialize and inherit
its context; contextvars set by later requests never reach them. In a
long-lived API-key session (the documented setup — keys never expire)
the minted 24h JWT eventually expired while the transport kept
authenticating, so every tool call failed with 401.

Remember the raw API key at initialize; when the session's JWT has aged
out, take the current one from the per-request API-key cache (every
tools/call POST refreshes it) or re-mint synchronously. JWT logins are
unchanged: the client's own credential expiring is the client's
business.
2026-11-01 23:09:38 +08:00
yueguobin 68c8c0f1a0 fix(vpcs): wire pcname into the nornir inventory; keep partial output on read timeout
The pcname kwarg was added to VPCSTelnet but never passed by the only
production instantiation path, so a node renamed away from PC<n> never
matched the prompt pattern and every command stalled the full read
timeout. Pass pcname via the netmiko connection extras (the host key is
the node name).

send_command now owns its read loop instead of delegating to netmiko's
read_until_pattern: that helper raises ReadTimeout discarding accumulated
output, so a command slower than the timeout returned an empty string
that looked like success. The partial output is returned instead.
2026-11-01 23:09:38 +08:00
yueguobin eea1b807d1 docs(mcp): add Claude Code verification and scope examples 2026-11-01 23:09:38 +08:00
yueguobin 571646c296 docs: record the SIGHUP session-disconnect mass-node-death known issue
SSH disconnect SIGHUPs the session; the server absorbs it (reload) while
every emulator child default-terminates without cleanup, leaving stale
anchor TAPs that 409 the first start afterwards. Root-caused with a
second-level journalctl/gns3.log correlation; addressed by deployment
guidance (systemd / setsid nohup / tmux), product-side hardening noted
as deferred. Indexed under Known Issues.
2026-11-01 23:09:38 +08:00
yueguobin fe1b2a5cb0 Upgrade MCP SDK to 2.3 and switch transport from SSE to Streamable HTTP
- Drop the unused fastmcp wrapper pin (mcp-requirements.txt) and depend on
  the official SDK directly: mcp>=2.3,<3. The code only ever imported
  mcp.server.* modules; fastmcp was pulled in solely as a dependency
  vehicle and its <4 pin kept mcp locked at 1.x.
- Migrate to the SDK 2.x API: FastMCP -> MCPServer
  (mcp.server.mcpserver); transport_security moves from the constructor
  into streamable_http_app().
- Replace the deprecated SSE transport (spec-deprecated 2025-06-18) with
  Streamable HTTP at POST/GET/DELETE /v3/mcp/transport, mounted at /v3/mcp.
- Run the StreamableHTTP session manager in the FastAPI lifespan
  (Starlette does not execute mounted sub-app lifespans), entered before
  startup finishes so no request passes the MCP ready gate first.
- Authenticate every request (the SSE wrapper only checked the opening
  GET and trusted POSTs by session). Add a 5-minute TTL cache for API-key
  resolutions so the stricter per-request check does not cost a bcrypt
  round on every call.
- Update docs to the new endpoint, auth flow, and client configuration.

Wire-format verified unchanged against SDK 1.30 (structured output
auto-detection and content conversion are byte-identical for the
list[dict] returns used by all tool handlers).
2026-11-01 23:09:38 +08:00
Jeremy Grossmann a5e98e2109 Merge pull request #3046 from GNS3/feat/aarch64-qemu-vms
Add support for running aarch64 Qemu VMs
2026-11-01 12:55:51 +01:00
grossmj 5af41c7e8d Sync appliances 2026-11-01 18:50:55 +07:00
grossmj 524fff814b feat: add support for running aarch64 Qemu VMs 2026-11-01 18:48:41 +07:00
grossmj 47944067f7 fix: suppress deprecation warnings in pyproject.toml 2026-11-01 16:11:22 +07:00
Jeremy Grossmann 09ad329db3 Merge pull request #3045 from GNS3/update-dependencies
Update dependencies
2026-11-01 07:04:47 +01:00
grossmj 5afd9bf384 chore(deps): update dependencies 2026-11-01 12:46:50 +07:00
Jeremy Grossmann 368d1af3d5 Merge pull request #3043 from GNS3/bugfix/3019
Hardware acceleration support for ARM architectures in QEMU
2026-10-31 17:45:44 +01:00
grossmj af7b70001a fix: hardware acceleration support for ARM architectures in QEMU 2026-10-31 23:38:29 +07:00
Jeremy Grossmann f06166da71 Merge pull request #3042 from GNS3/fix-pytest-warnings
Fix pytest warnings
2026-10-31 16:07:44 +01:00
grossmj ac65698eea refactor: update authentication handling to use aiohttp.encode_basic_auth and adjust request options + fix other pytest warnings 2026-10-31 22:00:21 +07:00
Jeremy Grossmann 1608a65a01 Merge pull request #3041 from GNS3/update-dependencies
Update dependencies
2026-10-31 13:52:58 +01:00
grossmj 110638d81a refactor: replace os.path.commonprefix with os.path.commonpath for path comparisons 2026-10-31 19:43:52 +07:00
grossmj be368dd222 chore: update dependencies to latest versions in dev-requirements.txt 2026-10-31 19:38:58 +07:00
grossmj bef6e9d019 chore: update dependencies to latest versions in requirements.txt 2026-10-31 19:29:18 +07:00
Jeremy Grossmann 2821cbdf80 Merge pull request #3040 from GNS3/cleanup-windows-darwin-code
Remove platform-specific code for Darwin and Windows
2026-10-31 13:23:42 +01:00
grossmj 1f2b79cff2 refactor: remove macOS and Windows crash report info 2026-10-31 19:14:43 +07:00
grossmj c7e085e23c refactor: remove local gns3vm support and remove more platform-specific code 2026-10-31 17:51:37 +07:00
grossmj bad48286a5 refactor: remove platform-specific code for Darwin and Windows. Clean up Qemu options handling 2026-10-31 16:49:23 +07:00
grossmj 4d1b9e4700 fix: update web-ui bundling commit message to include release link 2026-10-31 12:20:42 +07:00
Jeremy Grossmann 4cbc339ab1 Merge pull request #3038 from GNS3/dependabot/pip/3.1/langchain-deepseek-gte-1.1.1
Update langchain-deepseek requirement from >=1.0.1 to >=1.1.1
2026-10-29 13:44:13 +01:00
Jeremy Grossmann 6b5863a5df Merge pull request #3037 from GNS3/dependabot/pip/3.1/langchain-openai-gte-1.7.2
Update langchain-openai requirement from >=1.1.10 to >=1.7.2
2026-10-29 13:43:53 +01:00
Jeremy Grossmann 331531de1b Merge pull request #3036 from GNS3/dependabot/pip/3.1/langgraph-checkpoint-sqlite-gte-3.1.2
Update langgraph-checkpoint-sqlite requirement from >=3.0.3 to >=3.1.2
2026-10-29 13:35:03 +01:00
dependabot[bot] 1d30cb49e9 Update langchain-deepseek requirement from >=1.0.1 to >=1.1.1
Updates the requirements on [langchain-deepseek](https://github.com/langchain-ai/langchain) to permit the latest version.
- [Release notes](https://github.com/langchain-ai/langchain/releases)
- [Commits](https://github.com/langchain-ai/langchain/compare/langchain-deepseek==1.0.1...langchain-deepseek==1.1.1)

---
updated-dependencies:
- dependency-name: langchain-deepseek
  dependency-version: 1.1.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-29 12:32:18 +00:00
dependabot[bot] d7d5231853 Update langchain-openai requirement from >=1.1.10 to >=1.7.2
Updates the requirements on [langchain-openai](https://github.com/langchain-ai/langchain) to permit the latest version.
- [Release notes](https://github.com/langchain-ai/langchain/releases)
- [Commits](https://github.com/langchain-ai/langchain/compare/langchain-openai==1.1.10...langchain-openai==1.7.2)

---
updated-dependencies:
- dependency-name: langchain-openai
  dependency-version: 1.7.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-29 12:32:18 +00:00
Jeremy Grossmann e9b9bea1df Merge pull request #3034 from GNS3/dependabot/pip/3.1/langchain-google-genai-gte-4.4.2
Update langchain-google-genai requirement from >=4.2.1 to >=4.4.2
2026-10-29 13:29:48 +01:00
dependabot[bot] 62cb8af70b Update langgraph-checkpoint-sqlite requirement from >=3.0.3 to >=3.1.2
Updates the requirements on [langgraph-checkpoint-sqlite](https://github.com/langchain-ai/langgraph) to permit the latest version.
- [Release notes](https://github.com/langchain-ai/langgraph/releases)
- [Commits](https://github.com/langchain-ai/langgraph/compare/checkpointsqlite==3.0.3...checkpointsqlite==3.1.2)

---
updated-dependencies:
- dependency-name: langgraph-checkpoint-sqlite
  dependency-version: 3.1.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-29 11:22:59 +00:00
dependabot[bot] cbd7065584 Update langchain-google-genai requirement from >=4.2.1 to >=4.4.2
Updates the requirements on [langchain-google-genai](https://github.com/langchain-ai/langchain-google) to permit the latest version.
- [Release notes](https://github.com/langchain-ai/langchain-google/releases)
- [Commits](https://github.com/langchain-ai/langchain-google/compare/libs/genai/v4.2.1...libs/genai/v4.4.2)

---
updated-dependencies:
- dependency-name: langchain-google-genai
  dependency-version: 4.4.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-29 11:22:37 +00:00
Jeremy Grossmann 0c34520017 Merge pull request #3032 from tikD1337/fix/ai-stub-shadows-access-routes
fix(api): keep the LLM stub from shadowing /access routes without AI extras
2026-10-28 16:09:02 +01:00
Jeremy Grossmann 16c5d028dc Merge pull request #3033 from tikD1337/fix/web-ui-lib-assets
fix(web-ui): ship the bundled consoles' lib/ files (VNC and xpra)
2026-10-26 15:34:29 +01:00
tikD1337andClaude Opus 5.5 406086c177 fix(web-ui): ship the bundled consoles' lib/ files (VNC and xpra)
The ".gitignore" rules "lib" and "lib64" (from the Python template, meant
for a virtualenv at the repository root) match a directory with that name
at any depth. They kept two folders of the bundled web UI out of git:

- assets/vnc-console/novnc/vendor/pako/lib/ (12 files, zlib for noVNC)
- assets/xpra-html5/js/lib/ (20 files)

Anything built from a git checkout (GitHub archives, Docker images) ships
without them. The server answers a missing asset with the web UI page, so
noVNC's module graph fails to load (a module served as text/html) and the
VNC console stays on "Initializing VNC Console..."; the xpra console loses
its scripts the same way.

Anchor both rules to the repository root and add the 32 files, taken from
gns3-web-ui v3.1.0a7 (the bundled version); every blob is identical to the
one in that tag. A test walks the VNC console's module imports and the xpra
pages' scripts and fails on any file that is not in the package.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 12:09:50 +01:00
tikD1337andClaude Opus 5.5 09b8420354 fix(api): keep the LLM stub from shadowing /access routes without AI extras
Without the AI dependencies the LLM model configuration router is replaced
by a stub that answers 501. It was a catch-all ("/{path:path}") included
under the /access prefix, so it also answered every /access route included
after it: creating an API key (POST /v3/access/api-keys) failed with "AI
Copilot is not available", which left API keys unusable on servers without
the AI extras.

The LLM stub now covers only the LLM model configuration paths, under
/access/users/{user_id}/ and /access/groups/{group_id}/. The stub routers
are built by build_ai_stub_routers() so tests can check them with or
without the extras, and add_stub_routes() takes the paths to stub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 10:35:12 +01:00
Jeremy Grossmann ac01ee6190 Merge pull request #3031 from yueguobin/docs/netem-seed-kernel-requirement
docs: state the Linux 6.6 requirement of the netem seed filter
2026-10-26 08:02:53 +01:00
yueguobin c988ede19c docs: state the Linux 6.6 requirement of the netem seed filter
Aligns with uBridge's tc.md correction: TCA_NETEM_PRNG_SEED (uapi slot 14,
added in Linux 6.6 — not the nonexistent TCA_NETEM_SEED at "5.1") is what
the seed filter rides on; pre-6.6 kernels parse qdisc options
non-strictly and silently drop the attribute, so seed determinism is
unavailable there while every other netem knob applies. Stated in both
filter tables and the seed section of packet-filters.md, the seed rows of
the MCP and copilot tool descriptions, and the kernel-impairment spec.
2026-10-26 13:23:05 +08:00
Jeremy Grossmann fa4b763640 Merge pull request #3027 from tikD1337/fix/ubridge-kernel-datapath-version
Require uBridge >= 1.3.1
2026-10-25 02:49:15 +02:00
tikD1337andClaude Opus 5.5 07b0c21fe5 Require uBridge >= 1.3.1 instead of gating the kernel datapath
Review feedback: 3.1 is still in alpha and the GNS3 VM ships a matching
uBridge, so a hard minimum is simpler than a version-based degrade path,
and it also covers Docker endpoints and the builtin Ethernet switch,
which never went through the anchor probes. Raise minimum_required_version
to 1.3.1 and drop supports_kernel_datapath and its uses; the relay
fallback for capability problems (no CAP_NET_ADMIN) is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 01:39:52 +02:00
Jeremy Grossmann dc6a9b3c7e Merge pull request #3028 from tikD1337/fix/switch-stale-bridge
fix(ethernet-switch): release a leftover bridge's ports before the crash-recovery delete
2026-10-24 17:31:11 +02:00
Jeremy Grossmann dd19d96fbf Merge pull request #3029 from tikD1337/fix/qemu-tap-partial-csum
fix(qemu): open the adapter TAP with vnet_hdr=off so relay links carry finished checksums
2026-10-24 09:20:16 +02:00
tikD1337andClaude Opus 5.5 156b77000c fix(qemu): open the adapter TAP without a vnet header
The TAP netdev kept QEMU's default vnet_hdr, so virtio-net, e1000e, igb
and vmxnet3 guests offload TCP/UDP checksums (and TSO) to the TAP: their
frames carry only the pseudo-header sum in the checksum field. A kernel
bridge link finishes them, but the uBridge relay (cloud, NAT, hub, ...)
reads the TAP with libpcap and forwards the frames as they are, so DNS
and TCP through a cloud fail while ICMP and DHCP work.

With vnet_hdr=off QEMU stops offering the offloads and the guest (or the
emulated NIC) sends finished frames, as with the 2.x socket netdev.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:28:53 +02:00
tikD1337andClaude Opus 5.5 d440849886 fix(ethernet-switch): release a leftover bridge's ports before the crash-recovery delete
A server killed before close() leaves the switch's kernel bridge behind
with its ports still enslaved: a peer's persistent anchor TAP and cascade
veth ends outlive uBridge. uBridge's brctl delete refuses a bridge that
still has ports (EBUSY), so the best-effort recovery delete in
_ensure_bridge() failed silently and brctl create hit EEXIST: the switch,
and the project holding it, could no longer be opened (HTTP 409 "Could
not create bridge gns3xxxxxx: File exists").

List the leftover bridge's ports from /sys/class/net/<bridge>/brif and
release each with brctl delif before the delete. uBridge's brctl show
reports no ports, and the switch already reads sysfs on the same host.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:10:13 +02:00
tikD1337andClaude Opus 5.5 52fcc83494 Gate the TAP/kernel datapath on uBridge >= 1.3.1
uBridge 1.2.3 already has the tap module, so the persistent-TAP probes
(_probe_persistent_taps on the node, probe_tap_support and siblings for
/capabilities) pass on it. QEMU, Dynamips and VPCS nodes then anchor on
TAPs and the controller builds kernel links that need 1.3.x commands:
kernel markers and the eBPF tc modes (1.3.0) and per-interface kernel
captures (`capture stop_kernel <ifc>`, 1.3.1). On 1.2.3 a MikroTik CHR
node sent frames but never got DHCP past DISCOVER/OFFER, and stopping
a capture failed with "Bad number of parameters".

Add Hypervisor.supports_kernel_datapath (version >= 1.3.1) and refuse
older builds in the node-side probe and the four anchoring capability
probes (tap, iol tap, bridge tap, vxlan). The existing fallback then
applies: nodes keep the legacy relay datapath with the usual warning,
which now names the installed version, and links stay on the relay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:00:27 +02:00
Jeremy Grossmann 2c10782635 Merge pull request #3026 from tikD1337/fix/node-names-adapter-type
fix: node names from templates with "+" and custom adapters with a null type
2026-10-23 14:08:47 +02:00
Jeremy Grossmann efc77267fa Merge pull request #3025 from tikD1337/fix/qemu-kvmclock-hyperv
fix(qemu): turn off kvmclock and TSC deadline timer on Hyper-V hosts without a usable TSC
2026-10-23 14:04:53 +02:00
tikD1337andClaude Opus 5.5 7e9ecf2a61 docs(config): add the Qemu kvmclock setting to the sample config
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 13:50:04 +02:00
tikD1337andClaude Opus 5.5 dd69a01fba fix(controller): make node names from template names valid hostnames
Creating a node from a template whose name has characters invalid in a
hostname, such as "MikroTik CCR1072-1G-8S+", failed on the compute with
"'MikroTikCCR1072-1G-8S+-1' is an invalid name to create a Qemu node":
the template name was only stripped of spaces.

Replace the other invalid characters by hyphens, following the rules the
compute validates node names with (RFC 1123 for Qemu and Docker, IOS for
Dynamips and IOU), as project import already does for existing nodes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 09:56:49 +02:00
tikD1337andClaude Opus 5.5 b9cf9158ca fix(compute): ignore null settings of custom adapters
When only a port is renamed in a template's custom adapters, the adapter is
saved with "adapter_type": null. The emulators read it with
custom_adapter.get("adapter_type", self._adapter_type), which returns None
for a key set to null: QEMU was then started with "-device None,..." and
died ("'None' is not a valid device model name"), GNS3 only reporting
"Could not start Telnet QEMU console". VirtualBox and VMware read the
adapter type the same way.

Drop the null settings in _get_custom_adapter_settings so the node's own
adapter type (and MAC address) applies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 09:56:48 +02:00
Tikhon Ulyanov 23edfc0269 Merge branch '3.1' into fix/qemu-kvmclock-hyperv 2026-10-22 19:28:50 +02:00
Jeremy Grossmann 4d55cb1b9c Merge pull request #3023 from GNS3/dependabot/pip/3.1/langchain-aws-gte-1.9.0
Update langchain-aws requirement from >=1.8.1 to >=1.9.0
2026-10-22 18:43:12 +02:00
dependabot[bot] fdf6e36555 Update langchain-aws requirement from >=1.8.1 to >=1.9.0
Updates the requirements on [langchain-aws](https://github.com/langchain-ai/langchain-aws) to permit the latest version.
- [Release notes](https://github.com/langchain-ai/langchain-aws/releases)
- [Commits](https://github.com/langchain-ai/langchain-aws/compare/langchain-aws==1.8.1...langchain-aws==1.9.0)

---
updated-dependencies:
- dependency-name: langchain-aws
  dependency-version: 1.9.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-22 16:26:05 +00:00
Jeremy Grossmann ab5eb192ad Merge pull request #3024 from GNS3/dependabot/pip/3.1/sentry-sdk-gte-2.72.0-and-lt-3
Update sentry-sdk requirement from <3,>=2.70.0 to >=2.72.0,<3
2026-10-22 18:25:39 +02:00
Jeremy Grossmann 85493aad77 Merge pull request #3022 from GNS3/dependabot/pip/3.1/langchain-ollama-gte-1.1.0
Update langchain-ollama requirement from >=1.0.1 to >=1.1.0
2026-10-22 18:24:52 +02:00
Jeremy Grossmann 532b2cdf8d Merge pull request #3021 from GNS3/dependabot/pip/3.1/rust-just-1.59.0
Bump rust-just from 1.58.0 to 1.59.0
2026-10-22 18:24:26 +02:00
Jeremy Grossmann bd5e3c6412 Merge pull request #3020 from GNS3/dependabot/pip/3.1/nornir-gte-3.6.0
Update nornir requirement from >=3.5.0 to >=3.6.0
2026-10-22 18:24:03 +02:00
tikD1337andClaude Opus 5.5 53164eccee fix(qemu): turn off kvmclock and TSC deadline timer on Hyper-V hosts without a usable TSC
When the compute is itself a Hyper-V guest without an invariant TSC (e.g.
the GNS3 VM on hosts whose CPU lacks TSC scaling), Linux falls back to the
hyperv_clocksource_tsc_page clocksource and the guest timekeeping KVM
derives from the TSC is broken with recent kernels:

- kvmclock runs thousands of times too fast: Linux guests (MikroTik
  RouterOS, ...) panic with "watchdog: BUG: soft lockup - CPU#0 stuck for
  29604s" and reboot in a loop right after boot;
- TSC deadline timers fire far too late: guests with -cpu host hang.

The only workaround so far was -machine accel=tcg, i.e. no KVM at all.

Add a kvmclock setting to the [Qemu] section (auto, enabled, disabled).
In auto mode, KVM guests started on a host whose clocksource is a Hyper-V
one get kvmclock and tsc-deadline turned off: on the -cpu given in the
additional options (unless it sets these features itself), otherwise on
QEMU's default CPU model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:38:10 +02:00
dependabot[bot] 9549425924 Update sentry-sdk requirement from <3,>=2.70.0 to >=2.72.0,<3
Updates the requirements on [sentry-sdk](https://github.com/getsentry/sentry-python) to permit the latest version.
- [Release notes](https://github.com/getsentry/sentry-python/releases)
- [Changelog](https://github.com/getsentry/sentry-python/blob/master/CHANGELOG.md)
- [Commits](https://github.com/getsentry/sentry-python/compare/2.70.0...2.72.0)

---
updated-dependencies:
- dependency-name: sentry-sdk
  dependency-version: 2.72.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-22 11:22:58 +00:00
dependabot[bot] 3d304a01ea Update langchain-ollama requirement from >=1.0.1 to >=1.1.0
Updates the requirements on [langchain-ollama](https://github.com/langchain-ai/langchain) to permit the latest version.
- [Release notes](https://github.com/langchain-ai/langchain/releases)
- [Commits](https://github.com/langchain-ai/langchain/compare/langchain-ollama==1.0.1...langchain-ollama==1.1.0)

---
updated-dependencies:
- dependency-name: langchain-ollama
  dependency-version: 1.1.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-22 11:22:47 +00:00
dependabot[bot] 176fc4bb5d Bump rust-just from 1.58.0 to 1.59.0
Bumps [rust-just](https://github.com/gnpaone/rust-just) from 1.58.0 to 1.59.0.
- [Release notes](https://github.com/gnpaone/rust-just/releases)
- [Changelog](https://github.com/gnpaone/rust-just/blob/master/CHANGELOG.md)
- [Commits](https://github.com/gnpaone/rust-just/compare/1.58.0...1.59.0)

---
updated-dependencies:
- dependency-name: rust-just
  dependency-version: 1.59.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-22 11:22:37 +00:00
dependabot[bot] 926900dd08 Update nornir requirement from >=3.5.0 to >=3.6.0
Updates the requirements on [nornir](https://github.com/nornir-automation/nornir) to permit the latest version.
- [Release notes](https://github.com/nornir-automation/nornir/releases)
- [Changelog](https://github.com/nornir-automation/nornir/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/nornir-automation/nornir/compare/v3.5.0...v3.6.0)

---
updated-dependencies:
- dependency-name: nornir
  dependency-version: 3.6.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-22 11:22:32 +00:00
grossmj 09ad486966 Development on 3.1.0.dev8 2026-10-21 16:04:23 +07:00
grossmj 2ea13ca49a Release v3.1.0a7 2026-10-21 15:47:16 +07:00
grossmj 179e7e0d17 Bundle web-ui v3.1.0a7 2026-10-21 15:24:00 +07:00
Jeremy Grossmann c1fdd55cb3 Merge pull request #3018 from aastefanov/3.1
Change project creator on import
2026-10-21 04:44:35 +02:00
Albert Stefanov cf2b455bf1 Reformat file
Signed-off-by: Albert Stefanov <aastefanov@outlook.com>
2026-10-20 20:44:21 +03:00
Albert Stefanov 63d7fec8a7 Change project creator on import
Fixes #3017

Signed-off-by: Albert Stefanov <aastefanov@outlook.com>
2026-10-20 20:29:51 +03:00
grossmj 68c929e224 Sync appliances 2026-10-20 18:53:07 +07:00
Jeremy Grossmann ada64e39a1 Merge pull request #3016 from GNS3/qemu-minimum-version-support
Add QEMU support documentation and enforce minimum version requirement
2026-10-20 13:14:38 +02:00
grossmj a82b06d676 feat: add QEMU support documentation and enforce minimum version requirement 2026-10-20 18:01:25 +07:00
Jeremy Grossmann aab5432a5f Merge pull request #3015 from GNS3/bugfix/3007
Fix SPICE socket binding failure
2026-10-20 12:23:59 +02:00
grossmj cfba748677 fix: SPICE socket binding failure 2026-10-20 17:16:44 +07:00
Jeremy Grossmann 1498282c6b Merge pull request #3014 from GNS3/remove-windows-code
Remove Windows code
2026-10-20 07:04:37 +02:00
grossmj 437f68961b chore: clean up Windows specific code 2026-10-20 11:51:29 +07:00
Jeremy Grossmann 9e9f1316aa Merge pull request #3009 from markparonyan/3.1
refactor(gns3server,tests): ruff fixes
2026-10-19 18:49:33 +02:00
grossmj 569b46d272 refactor: fix lint issues 2026-10-19 23:28:49 +07:00
Jeremy Grossmann 68b5e89bfa Merge branch '3.1' into 3.1 2026-10-19 18:11:29 +02:00
Jeremy Grossmann b956bba917 Merge pull request #3013 from cristian-ciobanu/feat-#2496
feat(cloud): attach TAP interfaces to existing Linux bridges
2026-10-19 17:34:34 +02:00
Cristi 53aa7ab0d9 fix(cloud): keep ports_mapping getter and setter adjacent 2026-10-19 16:02:39 +03:00
Cristi a9f5306f16 feat(cloud): attach TAP interfaces to existing Linux bridges 2026-10-19 15:42:18 +03:00
Jeremy Grossmann e57acfb7b1 Merge pull request #3011 from cristian-ciobanu/feat-#3049
feat(qemu): support two CD/DVD images and consistent ISO handling
2026-10-19 04:42:18 +02:00
Cristi 58e5591935 feat(qemu): support SATA CD-ROM interfaces
- Add per-drive IDE/SATA selection with backward-compatible IDE defaults
- Persist interfaces in nodes, templates, and appliance imports
- Add database migration support for versioned and unversioned databases
- Prevent partial updates when rejecting live interface changes
- Validate interfaces and support SATA media changes through the monitor
2026-10-18 22:07:37 +03:00
Jeremy Grossmann a1e483b894 Merge pull request #3012 from yueguobin/fix/marker-replay-remote-computes
fix: fetch remote-compute marker pcaps in tag replay
2026-10-18 14:06:25 +02:00
YueGuobin 33b28a3b5f fix: fetch remote-compute marker pcaps in tag replay
Marker pcaps are written by uBridge on the compute that hosts the capture
node. The tag replay only looked in the project folder on the controller.
So a source from a remote compute showed count 0 and no frames, with no
error. Its frame detail returned 404 and said nothing ever matched (#3010).

Each source now gets its pcap through the compute of its capture node.
Local files are read as before. Remote files are fetched over HTTP on
every acquire into a small cache (32 idle files, cleared at shutdown).
A file is replaced only when its bytes changed. This keeps the old mtime,
so the sharkd session for that file stays alive.

When a compute cannot be reached, its source now shows an error message
in the timeline instead of just showing nothing. The detail endpoint now
returns an error instead of 404.
2026-10-18 16:36:11 +08:00
Cristi 84b4c05b9f feat(qemu): support two CD/DVD images and consistent ISO handling 2026-10-17 23:08:11 +03:00
Jeremy Grossmann d047ca0a5f Merge pull request #3006 from yueguobin/feat/vxlan-cross-compute
feat: cross-compute VXLAN kernel datapath
2026-10-17 13:39:13 +02:00
Mark Paronyan 4c311baabf refactor(gns3server,tests): StrEnum, ASYNC109 and others 2026-10-17 12:02:53 +03:00
Mark Paronyan b7e6c02647 refactor: ruff autofixes 2026-10-17 11:43:36 +03:00
Mark Paronyan 54139dced2 chore(ruff): target version to py311 2026-10-17 11:43:20 +03:00
YueGuobin 0d91d9252b feat: default vxlan_dstport to the IANA VXLAN port 4789
The custom 14789 was picked to keep our demux socket off the ports other
VXLAN software listens on, but a private default surprises operators and
blocks interop with gear that pins the standard port. Default to the
IANA-assigned 4789 instead; the gns3_server.conf override is unchanged
for computes where swarm overlay/flannel-style VXLAN already owns 4789.

Mixed-version deployments must pin the port on every compute until they
all run the new default, or the two tunnel ends will disagree.
2026-10-17 14:11:00 +08:00
YueGuobin 6679774de7 docs: spell out how the VXLAN lower device is chosen
Per tunnel, not a host setting: a connected UDP socket runs the
kernel's route lookup for the peer, the chosen source address is
matched back to its owning interface, and that interface becomes
the dev= (and with it the derived MTU and the outer source
address). Different peers may ride different lower devices with
independently derived MTUs; an unresolvable peer is a wiring error
that degrades the link to the relay. Re-creation re-resolves too,
so route changes ride the same node-start / link-recreation paths
as MTU changes.
2026-10-17 14:11:00 +08:00
YueGuobin 577be9b94e docs: pin down the VXLAN MTU derivation and its re-derivation paths
Verified against the running kernel's sources (7.2.6): the 50-byte
headroom is 20 outer IPv4 + 8 UDP + 8 VXLAN + 14 inner Ethernet
header (vxlan_headroom(), include/net/vxlan.h); the vxlan driver has
no NETDEV_CHANGEMTU handler so a live tunnel never follows its lower
device, while the bridge does follow its ports at runtime
(NETDEV_CHANGEMTU -> br_mtu_auto_adjust). Document the operational
consequence: the wiring path re-creates the device on every node
start and link (re)creation, so raising the underlay MTU on both
computes and stop/start-ing the nodes is the fix — no manual
ip link needed.
2026-10-17 14:11:00 +08:00
YueGuobin ca31031fdc test: drop the cross-compute VXLAN e2e scenario
The scenario needed root for its network namespace and its fabric subnet
turned out host-specific: policy routing (a proxy's table consulted
before main) sends any non-RFC1918 destination out the default route, so
the peer compute was unreachable behind the veth — unfixable by picking
another subnet, and the failure paths leaked namespaces and processes.
Too environment-coupled to keep in the suite.

Unit coverage is unchanged (selection matrix, tunnel spec derivation,
VNI retry/degrade/self-heal, device lifecycle, capability probe); the
feature doc's Verification section now carries the manual two-compute
checklist instead of the e2e reference.
2026-10-17 14:11:00 +08:00
YueGuobin 21b866aeed feat: cross-compute VXLAN kernel datapath
Cross-compute links can ride kernel VXLAN tunnels instead of the uBridge
UDP relay: each endpoint creates one VXLAN device (uBridge's rtnetlink
vxlan module) enslaved into the same per-link Linux bridge the same-host
datapath uses, so filters, markers, capture and suspend keep running on
the anchor unchanged. Opt-in (Server.enable_vxlan_cross_compute, default
off) because the tunnel caps the usable MTU at the underlay minus the
outer headers; the relay stays the default and the fallback.

The controller derives what the pair must agree on: one VNI per link
(upper VNI space, per-link random salt) and deterministic device names
(gvl{link}{node}) that make crashed-run leftovers claimable
(show -> delete -> create). Same-host compute pairs, switch endpoints
and serial/unix-socket containers stay on the relay.

A VNI the kernel refuses self-heals on every path it can surface:
interactive create retries a fresh salt then degrades to the relay;
project open re-dispatches refused batch entries the same way; node
start recognises the refused device, stops the half-started node,
re-wires both ends on a fresh VNI (or degrades the link) and retries
the start. The device MTU is derived from the lower device (dev=) and
the per-link bridge inherits it - no configuration. The capability
probe (ubridge_vxlan in /capabilities) runs one scratch create/delete
on a scratch port that never equals the configured dstport.

The e2e scenario runs two computes on one machine (a network namespace
joined by a veth pair as the fabric) and needs root.
2026-10-17 14:11:00 +08:00
Jeremy Grossmann 5514b2e929 Merge pull request #3008 from yueguobin/fix/mypy-2-4-username-mapped
Fix mypy 2.4 type error on User.username and bump mypy to 2.4.0
2026-10-17 08:09:26 +02:00
YueGuobin c557324bcb chore: bump mypy to 2.4.0
Supersedes the dependabot bump in #2998; the tree is mypy 2.4-clean after
the previous commit.
2026-10-17 14:00:23 +08:00
YueGuobin 9887e3d5d7 fix: type User.username as str via Mapped-style column
mypy 2.4 (native parser by default) flags _jwt_username_var.set(user.username)
in agent/mcp/__init__.py: with the legacy `username = Column(String)`
declaration, instance access is typed Column[str], not str. Migrate the
column to the Mapped/mapped_column style already used by token_version and
last_login in the same table, with an explicit nullable=True so the schema
stays identical to the former Column(String) declaration.
2026-10-17 14:00:23 +08:00
Jeremy Grossmann 344a342924 Merge pull request #3004 from Xeriioo/fix/docker-vnc-display-race
fix(docker): give each VNC node its own X display
2026-10-16 12:57:38 +02:00
Jeremy Grossmann 8801e5fd4b Merge pull request #3005 from yueguobin/fix/node-update-while-running
fix: refuse Docker node updates that would recreate a running container
2026-10-16 12:17:57 +02:00
Guobin Yue 03c1564482 Merge branch '3.1' into fix/node-update-while-running 2026-10-16 17:07:39 +08:00
Jeremy Grossmann ddaf4b9376 Merge pull request #2999 from GNS3/dependabot/pip/3.1/nornir-utils-gte-0.3.0
Update nornir-utils requirement from >=0.2.0 to >=0.3.0
2026-10-16 11:03:08 +02:00
Guobin Yue d2b851f148 Merge branch '3.1' into fix/node-update-while-running 2026-10-16 16:56:40 +08:00
Jeremy Grossmann 7b8bb7140f Merge branch '3.1' into dependabot/pip/3.1/nornir-utils-gte-0.3.0 2026-10-16 10:54:32 +02:00
Jeremy Grossmann d20bcab40b Merge pull request #2997 from GNS3/dependabot/pip/3.1/pyjwt-gte-2.15.1
Update pyjwt requirement from >=2.10.1 to >=2.15.1
2026-10-16 10:53:12 +02:00
Jeremy Grossmann 642dd976a8 Merge pull request #2996 from GNS3/dependabot/pip/3.1/langsmith-gte-0.14.7
Update langsmith requirement from >=0.7.7 to >=0.14.7
2026-10-16 10:52:55 +02:00
Jeremy Grossmann ae3739e2b2 Merge pull request #2995 from GNS3/dependabot/pip/3.1/tiktoken-gte-0.14.0
Update tiktoken requirement from >=0.8.0 to >=0.14.0
2026-10-16 10:52:34 +02:00
Jeremy Grossmann 57f2a687de Merge pull request #2977 from GNS3/python-3.15-support
Python 3.15 support
2026-10-16 10:51:54 +02:00
Jeremy Grossmann 578dbdceeb Merge pull request #3003 from yueguobin/fix/mcp-device-config-remote-compute
Fix MCP device tools for nodes on remote computes
2026-10-16 10:49:56 +02:00
YueGuobin 1090a32bbb fix: refuse Docker node updates that recreate a running container
Updating any Docker node property destroys and recreates the container
(the route calls DockerVM.update() as soon as the property diff is
non-empty), so it discards everything written inside it. On a running
node that happened silently, as a side effect of an unrelated edit: the
user only saw the node restart.

Refuse the update while the container is up and say what stopping it is
for, like QEMU, IOU, Dynamips, VPCS, VirtualBox and VMware already do
for their own restart-requiring settings. The check runs before anything
is applied — a refused update leaves the node untouched — and only when
the PUT really changes a property, since Web clients send the whole node
back on every edit.

is_running() is not reusable for the question: it reports a paused
container as not running and stops crashed containers as a side effect,
so DockerVM gains is_up() for "running or paused".
2026-10-16 16:49:11 +08:00
YueGuobin 290c542afe fix: roll back a node update the compute refused
A compute 409 (for instance "must be stopped to change the console type
to vnc") left every value that had already been applied locally on the
controller node, because the update loop sets them before the PUT.
Nothing was dumped at that point, but project.dump() serializes the
whole topology: the next successful change anywhere in the project wrote
the refused values to disk, and the next project open recreated the node
with them — this time accepted by a stopped node. A refused change
silently landed later.

Restore the applied properties, the node properties, custom adapters,
missing images and the derived ports before re-raising, the way the
degraded-image create() path already cleans up after its own failure.
2026-10-16 16:49:06 +08:00
Jeremy Grossmann 2821fbd42a Merge branch '3.1' into python-3.15-support 2026-10-16 10:39:56 +02:00
ClemandClaude Opus 5.5 c736d5863b fix(docker): give each VNC node its own X display
When a project is opened, Docker nodes are created in parallel. The free
display was found by checking whether /tmp/.X11-unix/X<n> exists, but that
socket only appears once Xvnc has started, so several nodes got the same
display. Only the first Xvnc started; the others exited with "Server is
already active for display N" ("The vnc process has stopped with return
code 1"), and their containers drew on the screen of another node.

- reserve the displays given to the nodes of this server, and also skip a
  display whose lock file belongs to a live process
- restart a crashed Xvnc on the display the container was created with,
  after removing its stale socket, instead of picking a new display the
  container cannot reach (black screen)
- on close, only remove the X socket of our own Xvnc, never the socket of
  the node that owns the display

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 09:29:19 +02:00
Jeremy Grossmann 638a8be180 Merge pull request #3000 from yueguobin/feat/compute-auto-connect
Auto-connect flag and disconnect endpoint for computes
2026-10-16 07:08:07 +02:00
YueGuobin f47cb56495 fix: dial per-node console hosts in MCP device config tools
The device tools (device_config_send / device_show_run / vpcs_config_set)
built their Nornir inventory with only the console port and inherited the
group hostname, which is always the controller host. Console ports of
nodes on remote computes are bound on the compute's own host, so those
nodes were unreachable from the MCP tools - only local-compute nodes
worked.

Pass the per-node console_host through the project inventory and inject
it as a host-level Nornir hostname (which overrides the group's
controller-wide default). Missing or wildcard (0.0.0.0/::) values keep
the group inheritance, so single-machine setups behave exactly as
before. VPCS builds its own host entries, so it carries the hostname
over explicitly.
2026-10-16 10:29:19 +08:00
Guobin Yue 0130048baa Merge branch '3.1' into feat/compute-auto-connect 2026-10-15 23:04:52 +08:00
YueGuobin 7737630cb4 fix(tests): derive head revision in the migration round-trip test
The round-trip test builds its catalog from the models (which already
carry the head schema), then stamps the revision that was newest when the
test was written and replays everything above it. Any migration landing
on top therefore ran its DDL against a schema it had not rolled back -
the new computes.auto_connect migration failed with "duplicate column
name: auto_connect".

Stamp the current head instead and let the downgrade roll back every
revision above the inventory one before the upgrade replays them.
2026-10-15 23:02:53 +08:00
Jeremy Grossmann b79dcaa49d Merge pull request #3001 from yueguobin/chore/pre-commit-hooks
chore: add pre-commit hook running ruff and mypy checks on staged files
2026-10-15 16:52:47 +02:00
YueGuobin 6734d2d666 feat: add auto_connect flag and disconnect endpoint for computes
Computes can now be flagged auto_connect in the database. The controller
connects to flagged computes in the background at startup (reusing the
one-second delayed fire-and-forget mechanism), and enabling the flag via
PUT /computes/{id} triggers a background connection without the request
ever waiting for it. Disabling the flag does not drop an existing
connection.

Add POST /computes/{id}/disconnect to tear a compute down manually: the
notification stream and HTTP session are closed and every reconnection
path (retry backoff, notification stream reconnect, lazy connection in
http_query) is blocked until connect() is called again or the controller
restarts with auto_connect enabled. Disconnecting a compute used by an
opened project is rejected with 409 unless force=true; forcing only
drops the controller-side control channel, nodes keep running unmanaged.
The local compute cannot be disconnected.

Also make test_compute_list create its own compute (it relied on rows
from earlier tests and failed under reordering), and stop scheduling the
delayed add_compute connection during tests: the timer leaked real
connection attempts into other tests' event loops.
2026-10-15 22:50:22 +08:00
YueGuobin fa3dd827f9 chore: add pre-commit hook running ruff and mypy checks on staged files
Mirrors the fast static checks from CI (justfile lint + type-check):
ruff check, ruff format --check and mypy (gns3server package only,
matching the files = ["gns3server"] scope in pyproject.toml). Only
staged Python files are checked; pytest and pip check are left to CI.

Enable with: just install-hooks
2026-10-15 22:44:24 +08:00
dependabot[bot] 35a2d54740 Update nornir-utils requirement from >=0.2.0 to >=0.3.0
Updates the requirements on [nornir-utils](https://github.com/nornir-automation/nornir-utils) to permit the latest version.
- [Release notes](https://github.com/nornir-automation/nornir-utils/releases)
- [Changelog](https://github.com/nornir-automation/nornir-utils/blob/main/CHANGELOG.md)
- [Commits](https://github.com/nornir-automation/nornir-utils/compare/v0.2.0...v0.3.0)

---
updated-dependencies:
- dependency-name: nornir-utils
  dependency-version: 0.3.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-15 11:22:59 +00:00
dependabot[bot] c9a367a32f Update pyjwt requirement from >=2.10.1 to >=2.15.1
Updates the requirements on [pyjwt](https://github.com/jpadilla/pyjwt) to permit the latest version.
- [Release notes](https://github.com/jpadilla/pyjwt/releases)
- [Changelog](https://github.com/jpadilla/pyjwt/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/jpadilla/pyjwt/compare/2.10.1...2.15.1)

---
updated-dependencies:
- dependency-name: pyjwt
  dependency-version: 2.15.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-15 11:22:50 +00:00
dependabot[bot] cf75aeeac0 Update langsmith requirement from >=0.7.7 to >=0.14.7
Updates the requirements on [langsmith](https://github.com/langchain-ai/langsmith-sdk) to permit the latest version.
- [Release notes](https://github.com/langchain-ai/langsmith-sdk/releases)
- [Commits](https://github.com/langchain-ai/langsmith-sdk/compare/v0.7.7...v0.14.7)

---
updated-dependencies:
- dependency-name: langsmith
  dependency-version: 0.14.7
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-15 11:22:45 +00:00
dependabot[bot] a27c135840 Update tiktoken requirement from >=0.8.0 to >=0.14.0
Updates the requirements on [tiktoken](https://github.com/openai/tiktoken) to permit the latest version.
- [Release notes](https://github.com/openai/tiktoken/releases)
- [Changelog](https://github.com/openai/tiktoken/blob/main/CHANGELOG.md)
- [Commits](https://github.com/openai/tiktoken/compare/0.8.0...0.14.0)

---
updated-dependencies:
- dependency-name: tiktoken
  dependency-version: 0.14.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-15 11:22:35 +00:00
Jeremy Grossmann 716edc3a6a Merge pull request #2993 from yueguobin/feat/multi-kernel-capture
Concurrent kernel captures, one per interface
2026-10-15 06:02:58 +02:00
Jeremy Grossmann 59759f8963 Merge pull request #2994 from yueguobin/docs/packet-filters-guide
docs: packet filters — parameter reference, per-filter guide and REST examples
2026-10-15 05:59:47 +02:00
YueGuobin eda2d640ab docs: packet filters — deepen the per-filter guide with mechanism notes
Follow-up enrichments to the Per-filter guide, one per filter, each
answering the question a reader asks right after "what does it do":

- window_drop: explicit recurrence formula ([Start + k*Period, +Outage),
  duty cycle) and ASCII timelines of the three forms (one-shot /
  recurring / jittered); Chance spelled out as an independent per-packet
  draw gated to the window; jitter explained as per-cycle re-draws that
  break phase-locking with protocol timers
- quota: transparent until the budget is consumed; Chance equals
  packet_loss in draw mathematics but runs in the eBPF classifier stage
  (no correlation parameter, outside seed, invisible to captures)
- limit: the phantom-loss symptom (throughput below the configured rate
  with rate+delay set = the 1000 default overflowing)
- seed: reproduction also requires the same traffic pattern (draws are
  consumed per arriving packet); one pinned realization is not the
  distribution — statistical conclusions need several seeds
- gemodel: scattered-vs-bursty timeline at the same 5% mean (fast
  retransmit vs RTO), and a parameter recipe (M and L -> r, p)
- reorder: the mechanism is queue-jumping on the netem delay queue —
  hence the delay requirement, the limit overflow interaction and the
  delay-bounded reorder depth
- rate: per-direction independent shaping (symmetric full duplex, no
  shared budget); asymmetric rates need in-guest netem
- duplicate: real-world prototype (802.11 ARQ retransmissions), example
  values with the correlation-collapse anchors (10/25 -> ~1.8%, 25/25
  -> ~16.7%)
2026-10-15 01:08:53 +08:00
YueGuobin 63873f6041 docs: packet filters — parameter reference, per-filter guide and REST examples
Make the feature doc usable as a standalone reference:

- Parameter reference: all 13 filters' parameters, ranges and units, the
  cross-filter rules (reorder+delay, gemodel/packet_loss exclusivity,
  period>=outage, distribution needs jitter), the zero-means-disabled
  convention, and the UI display names served by available_filters
  (the Web UI labels gemodel as "Gilbert-Elliot loss", never by type)
- Per-filter guide: purpose, per-parameter meaning, caveats and a copyable
  example for each of the 13 types, including the four jitter
  distributions compared (uniform/normal/pareto/paretonormal)
- REST surface: endpoint table with privileges, a filters PUT example,
  and common recipes (WAN latency, bursty loss via gemodel, rate cap,
  ICMP blackhole, scheduled outage)
- Clarify gemodel's "one-way" mean: per direction, independent instances
  per endpoint, round trip compounds to 1-(1-mean)^2; one-directional
  loss is not expressible through the link filters dict
- Fix an inaccuracy: available_filters is a dedicated endpoint's response,
  not a field of the link payload
2026-10-15 00:50:46 +08:00
YueGuobin 3e6a53c4b9 style: apply ruff format to the files this branch touches 2026-10-14 22:13:58 +08:00
YueGuobin 97b5514134 style: zip() with strict= in the capture e2e assert message 2026-10-14 22:09:53 +08:00
YueGuobin 9e0d5050db feat: concurrent kernel captures, one per interface
uBridge's capture module now serves one AF_PACKET capture per interface,
any number per process, and `capture stop_kernel` takes the interface it
stops — this rides that (breaking, paired-binary) protocol change.

The server-side single-slot tracker (_kernel_capture_ifc with its
reserve/release/owned_by helpers) is gone: same-port duplicates were
already refused by the NIO capturing flag, uBridge answers EALREADY on a
same-interface duplicate, and per-interface stops removed the process-
wide stop the ownership gating guarded against.

The docker e2e drives ten concurrent captures on one node's uBridge and
asserts a per-interface stop freezes exactly the stopped half while the
live half keeps recording.
2026-10-14 21:52:34 +08:00
Jeremy Grossmann 149549e029 Merge pull request #2990 from yueguobin/fix/cloud-hide-kernel-datapath-interfaces
Hide kernel-datapath interfaces from the cloud node
2026-10-14 05:55:34 +02:00
YueGuobin c0568dc25f fix: hide kernel-datapath interfaces from the cloud node
The cloud node offered the kernel datapath's host-side interfaces —
node anchors (gv/gq/gi/gd/gx/gp), switch cascade veth ends (gs) and
cross-compute VXLAN devices (gvl) — in its interface list and even
pre-filled them as ports on a freshly created cloud: none of them is
flagged special and only "gns3*" names were filtered. These interfaces
belong to the link or node that created them for the project's whole
lifetime, so bridging a cloud to one would race its owner.

Add is_kernel_datapath_interface() next to the naming contract in
utils/kernel_anchor.py: exact-shape matching (prefix plus its
fixed-length id-derived tail), so a user interface that merely starts
with "gv" is never swallowed. The cloud keeps managed names out of its
host-interface list and default ports mapping, while saved mappings
keep working (the existence checks still see the full interface list).
2026-10-14 10:11:49 +08:00
Jeremy Grossmann b08441b9ad Merge pull request #2983 from yueguobin/fix/docker-image-digest-translation
fix(docker): accept the pinned image id when the two daemons report different ids for the same content
2026-10-13 16:23:39 +02:00
Jeremy Grossmann c188a7f21a Merge pull request #2989 from GNS3/dependabot/pip/3.1/pyyaml-gte-6.0.3
Update pyyaml requirement from >=6.0.0 to >=6.0.3
2026-10-13 16:20:58 +02:00
Jeremy Grossmann 3a0b00e8ab Merge pull request #2988 from GNS3/dependabot/pip/3.1/langchain-aws-gte-1.8.1
Update langchain-aws requirement from >=1.3.1 to >=1.8.1
2026-10-13 16:17:33 +02:00
Jeremy Grossmann 126b6dd14e Merge pull request #2986 from GNS3/dependabot/pip/3.1/nornir-salt-gte-0.23.4
Update nornir-salt requirement from >=0.23.0 to >=0.23.4
2026-10-13 15:58:14 +02:00
Jeremy Grossmann 56aa77b809 Merge pull request #2985 from GNS3/dependabot/pip/3.1/setuptools-gte-84.0.0
Update setuptools requirement from >=61.0 to >=84.0.0
2026-10-13 15:56:35 +02:00
dependabot[bot] af430439ce Update pyyaml requirement from >=6.0.0 to >=6.0.3
Updates the requirements on [pyyaml](https://github.com/yaml/pyyaml) to permit the latest version.
- [Release notes](https://github.com/yaml/pyyaml/releases)
- [Changelog](https://github.com/yaml/pyyaml/blob/6.0.3/CHANGES)
- [Commits](https://github.com/yaml/pyyaml/compare/6.0...6.0.3)

---
updated-dependencies:
- dependency-name: pyyaml
  dependency-version: 6.0.3
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-13 13:32:08 +00:00
dependabot[bot] 1ec79601ac Update langchain-aws requirement from >=1.3.1 to >=1.8.1
Updates the requirements on [langchain-aws](https://github.com/langchain-ai/langchain-aws) to permit the latest version.
- [Release notes](https://github.com/langchain-ai/langchain-aws/releases)
- [Commits](https://github.com/langchain-ai/langchain-aws/compare/langchain-aws==1.3.1...langchain-aws==1.8.1)

---
updated-dependencies:
- dependency-name: langchain-aws
  dependency-version: 1.8.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-13 13:32:04 +00:00
dependabot[bot] 6bb44d0efc Update nornir-salt requirement from >=0.23.0 to >=0.23.4
Updates the requirements on [nornir-salt](https://github.com/dmulyalin/nornir-salt) to permit the latest version.
- [Release notes](https://github.com/dmulyalin/nornir-salt/releases)
- [Commits](https://github.com/dmulyalin/nornir-salt/compare/0.23.0...0.23.4)

---
updated-dependencies:
- dependency-name: nornir-salt
  dependency-version: 0.23.4
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-13 13:31:53 +00:00
dependabot[bot] a839a90e65 Update setuptools requirement from >=61.0 to >=84.0.0
Updates the requirements on [setuptools](https://github.com/pypa/setuptools) to permit the latest version.
- [Release notes](https://github.com/pypa/setuptools/releases)
- [Changelog](https://github.com/pypa/setuptools/blob/main/NEWS.rst)
- [Commits](https://github.com/pypa/setuptools/compare/v61.0.0...v84.0.0)

---
updated-dependencies:
- dependency-name: setuptools
  dependency-version: 84.0.0
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-13 13:31:48 +00:00
grossmj e8c641bd08 docs: update comments regarding Ethernet switch replacement with Linux bridge 2026-10-13 20:18:29 +07:00
YueGuobin 90917c4a2c fix(docker): accept the pinned image id when the stores report different ids
Docker ids are not comparable across image stores: for the same content a
classic store reports the config digest while a containerd store (or an
image loaded from an OCI archive) reports the manifest digest. The
controller pins the id of its own daemon, so a compute whose store reports
another id for that content answered ImageMissingError forever: every node
creation streamed the image again (save/load round trip) without ever
converging, then failed with "The image 'x' is missing" after the six
retries. Docker 29 makes this easy to hit, since the id a daemon reports
now depends on how the image entered it.

The load endpoint now takes the tag and the digest pinned by the
controller, and the compute records how its own daemon identifies the
image it just received. Node creation accepts the pin through that pair,
and only while the tag still resolves to the synced content: a tag moved
to some other image, or an image the controller never pushed here, still
counts as missing. The pair lives in the compute process, so a restarted
compute syncs once more.

Computes that predate the new endpoint parameters keep the previous
behaviour, as do controllers that do not send them.
2026-10-13 17:10:17 +08:00
Jeremy Grossmann 2799780eca Merge pull request #2980 from yueguobin/docs/vpcs-anchor-startup
docs: amend vpcs-kernel-datapath.md with the anchor startup sequence
2026-10-12 14:58:25 +02:00
YueGuobin 031abf0e52 docs: record the VPCS anchor startup sequence and capability model
The ordered startup (uBridge creates the persistent TAP and hands it to
the server's uid before vpcs is launched, vpcs attaches with -e -d), why
the attach needs no privileges while creating a TAP does, that uBridge
stays off the data path, and that the setcap in the vpcs install target
is for standalone use only.
2026-10-12 20:10:56 +08:00
Jeremy Grossmann 6d838c890d Merge pull request #2979 from yueguobin/feat/vpcs-kernel-datapath
feat: VPCS kernel datapath
2026-10-12 13:12:43 +02:00
YueGuobin 3f2b44101f style: apply ruff format to the VPCS datapath test 2026-10-12 17:26:46 +08:00
YueGuobin c7ffe919dc feat: VPCS kernel datapath
A VPCS node's single adapter anchors on a persistent TAP the server
creates (tap create + set_owner via uBridge) and the vpcs process
attaches to by name: -e -d <gp{id8}e0p0> -n, the same
server-creates/guest-attaches shape as QEMU's netdev. -n (a vpcs fork
feature) keeps the guest's ip command from ifconfig'ing the anchor on
the host; the vpcs build is probed once per binary identity
(vpcs_tap capability, usage scan) and gates kernel links together
with ubridge_tap — anything else keeps the node on the relay (the
legacy local UDP tunnel on a stock binary, an AF_PACKET endpoint on
the anchor with a capable one).

VPCSVM takes KernelDatapathMixin: _connect_nio dispatches kernel
(enslave into the per-link bridge) / relay-on-anchor / legacy,
captures pick capture start_kernel vs the bridge engine, stop runs
under an execute lock and terminates the process before deleting the
anchor TAPs (a held device refuses deletion), and the duplicate-port
guard backstops the controller's. The NIO routes accept nio_bridge
and write suspend back on update.

_delete_anchor_taps verifies each tap is gone from sysfs and retries
a bounded three times: a holder can release its fd a moment after its
process was reaped (vpcs's daemon parent kills its console child and
exits first), so the unconditional delete raced EBUSY and leaked the
anchor intermittently.

The vpcs side needs IFNAMSIZ (16) instead of its own IFNAMESIZ (12)
for the -d name buffer — anchor names are 14 chars and truncated to a
nonexistent device, which TUNSETIFF then tries to create without
CAP_NET_ADMIN (fixed in the vpcs fork).

e2e (tests/e2e/test_vpcs_kernel_datapath.py): kernel and relay
scenarios green against the real binary — real ICMP both ways, §E.1/§
E.2 on the anchors, delay/suspend/capture, link delete/re-create,
node stop/restart self-heal, zero leftovers; the relay control passes
with both the fork binary and a stock one.
2026-10-12 17:19:57 +08:00
Jeremy Grossmann ad8f5430e2 Merge branch '3.1' into python-3.15-support 2026-10-11 16:59:19 +02:00
Jeremy Grossmann 4ced753e8d Merge pull request #2969 from GNS3/cache-apt-packages
ci: add caching for APT packages
2026-10-11 16:59:01 +02:00
grossmj 806f7b6cf2 ci: use cache-apt-pkgs-action to install sharkd 2026-10-11 21:34:56 +07:00
grossmj 5592bad023 feat: add support for Python 3.15 2026-10-11 16:58:39 +07:00
Jeremy Grossmann cb8918b584 Merge pull request #2976 from GNS3/enable-iou-l1-keepalive
fix: enable Layer 1 keepalives by default at the template level
2026-10-11 11:57:22 +02:00
grossmj dff5fbfd7d fix: enable Layer 1 keepalives by default at the template level 2026-10-11 16:50:14 +07:00
grossmj a437d46138 Revert "fix: enable Layer 1 keepalives by default. Ref #2975"
This reverts commit e4c25549f0.
2026-10-11 16:44:07 +07:00
grossmj e4c25549f0 fix: enable Layer 1 keepalives by default. Ref #2975 2026-10-11 16:34:44 +07:00
Jeremy Grossmann 2e3557d534 Merge pull request #2974 from GNS3/bugfix/2935
fix: update error logging to handle exceptions in WebSockets
2026-10-10 12:40:48 +02:00
grossmj 6aaa0c578c fix: update error logging to handle exceptions in WebSockets 2026-10-10 17:32:44 +07:00
Jeremy Grossmann bf9278adbc Merge branch '3.1' into cache-apt-packages 2026-10-10 12:15:43 +02:00
Jeremy Grossmann d50b1996e3 Merge pull request #2971 from yueguobin/feat/mcp-text-drawing-tool
feat(mcp): Web UI compatible drawing creation (text tool + shared SVG builders)
2026-10-10 12:15:27 +02:00
Guobin Yue c66d678e35 Merge branch '3.1' into feat/mcp-text-drawing-tool 2026-10-10 15:00:57 +08:00
Jeremy Grossmann e4e117013d Merge pull request #2973 from GNS3/depfix/2725
Fix CVE-2026-44405
2026-10-10 08:53:57 +02:00
grossmj 3f76d43ffc fix(deps): update paramiko and netmiko versions to address security vulnerability 2026-10-10 13:45:34 +07:00
YueGuobin 23f117de51 style: apply ruff format to drawing builder files 2026-10-10 14:34:28 +08:00
Guobin Yue cff42e32e8 Merge branch '3.1' into feat/mcp-text-drawing-tool 2026-10-10 14:22:47 +08:00
Jeremy Grossmann be06f753ab Merge pull request #2970 from yueguobin/fix/node-lifecycle-status-flood
fix(controller): stop flooding clients with transitional node statuses
2026-10-10 07:22:56 +02:00
Jeremy Grossmann 11c10dd85c Merge branch '3.1' into fix/node-lifecycle-status-flood 2026-10-10 06:49:50 +02:00
Jeremy Grossmann 2bf35c31e4 Merge branch '3.1' into feat/mcp-text-drawing-tool 2026-10-10 06:49:24 +02:00
Jeremy Grossmann 15dd9f7d18 Merge pull request #2959 from markparonyan/api-issue-10-0eztih
feat: add response models for endpoints returning untyped objects
2026-10-10 06:49:07 +02:00
grossmj 4fc601e919 refactor: remove unused link filter schemas and fix test_add_v8_version_appliance 2026-10-10 06:40:52 +02:00
grossmj 6004e06499 Merge branch '3.1' into fork/markparonyan/api-issue-10-0eztih
# Conflicts:
#	gns3server/schemas/__init__.py
2026-10-10 06:39:15 +02:00
grossmj 64d4defae2 ci: add cache hit status logging 2026-10-09 19:06:55 +02:00
grossmj e206e70300 ci: update APT cache key 2026-10-09 18:56:05 +02:00
grossmj 5497b0368a ci: use cache@v6 2026-10-09 18:31:22 +02:00
YueGuobin 0796d455a0 test: make the version output test order-independent
controller_host is recorded on the mounted compute sub-application
when the controller queries the compute capabilities; the test relied
on another test having made that call first and failed when run on
its own. Set the state directly in the test.
2026-10-10 00:29:17 +08:00
grossmj 437fa5458e ci: add caching for APT packages 2026-10-09 18:27:49 +02:00
YueGuobin 82015dcb5c fix(controller): stop flooding clients with transitional node statuses
Every node lifecycle call (start/stop) emitted a "starting"/"stopping"
node.updated notification on entry, and for the whole duration of the
call asdict() masked the real status with the transitional one — every
compute event forwarded in that window was re-emitted as a duplicate
transitional status.

Stop-all/start-all on a 13-node project pushed two transitional events
per node before the final state. Clients that do not render these
transitional statuses (the Web UI) showed nodes flickering through an
unexpected suspended-looking state before reaching started/stopped.

Remove the transitional notification and the status masking: clients
see the real statuses again (started/stopped), from the forwarded
compute events plus the controller-side confirmation. The wait option
on the lifecycle routes, the strict stop error handling and
wait_for_status() are unchanged.
2026-10-10 00:24:20 +08:00
Jeremy Grossmann 5c6478e77e Merge pull request #2944 from yueguobin/fix/duplicate-device-configs-merge
Kernel datapath: wire local Ethernet links through host kernel interfaces (veth/TAP + Linux bridges)
2026-10-09 17:00:22 +02:00
Guobin Yue 7df7ce1c96 Merge branch '3.1' into fix/duplicate-device-configs-merge 2026-10-09 21:23:38 +08:00
Jeremy Grossmann fbe93c4c4e Merge pull request #2954 from markparonyan/api-issue-05-2xftmd
feat(api): add strict_names and batch node and link creation
2026-10-09 14:39:10 +02:00
grossmj 4195f3b7c1 fix: remove incorrectly merged code 2026-10-09 14:29:04 +02:00
grossmj 868973bb7c Revert "fix: "LinkFilterParameter" already defined"
This reverts commit 8fee1d4c36.
2026-10-09 13:22:41 +02:00
YueGuobin 4de6758e2f refactor(mcp): drop the raw drawing_create tool
The templated drawing_create_text/_rectangle/_ellipse tools cover the
LLM-relevant creation paths, and line/image/curve creation is not
needed from MCP or copilot for now. The management tools stay, so
existing drawings (including images and lines created in the Web UI)
remain fully manageable; drawing_update's raw svg parameter remains
the escape hatch for edits.
2026-10-09 11:12:18 +08:00
YueGuobin 5e8272fdd8 feat(agent): share Web UI compatible drawing builders between MCP and copilot
The text drawing tool was MCP-only; the copilot needs the same
capability and its area-annotation helper carried the same Web UI
compat bugs. Split into three layers with a single implementation:

- gns3server/utils/drawings.py: pure SVG builders (text, rectangle,
  ellipse) with full input validation (ValueError) — the Web UI
  format knowledge lives in core utils next to picture.py
- api_handlers.py: shared REST handlers (create_text_drawing_handler
  moved here, create_rectangle/ellipse_drawing_handler added) — the
  layer both consumers already share
- thin shells: MCP tools (drawing_create_text unchanged, plus new
  drawing_create_rectangle/_ellipse) and three LangChain tools
  (tools_v2/gns3_create_drawing.py) registered in both copilot mode
  lists

Shape builder details:

- rectangle: solid fill or "none", stroke block emitted only when a
  stroke is given, rx corner radius, dasharray validated against the
  Web UI's Qt remap table (QtDasharrayFixer rewrites those patterns)
- ellipse: bounding-box API; cx/cy derived as offsets inside the
  drawing box (the Web UI treats them as box-relative, not canvas
  coordinates); odd sizes round down and the actual size is returned

gns3_drawing_utils now delegates to the shared builders, fixing the
px-blind sizing, the ignored text-anchor/x/y centering and the
missing XML escaping in the area-annotation path.
2026-10-09 11:12:18 +08:00
YueGuobin 73cbb0387c feat(mcp): add drawing_create_text tool with Web UI compatible SVG assembly
The Web UI re-parses drawing SVG into its own element model instead of
rendering it raw, which makes hand-assembled SVG error-prone for LLM
callers. The new tool assembles the SVG server-side, mirroring what the
Web UI itself serializes for text drawings:

- XML-escaped text content, validated color (#RGB/#RGBA/#RRGGBB/
  #RRGGBBAA) and font family (attribute-safe charset)
- multi-line support: literal newlines render as stacked lines in the
  Web UI (tspan split), width/height computed from the longest line
- pt-aware sizing: the Web UI renders font-size in pt (1pt = 4/3 px),
  so width uses a 0.8/char factor for monospace (1.0 proportional) and
  line height 1.9 x font_size, instead of the px-based 0.62 estimate
- ET.fromstring pre-check so bad input fails loudly instead of hitting
  the controller's silent drop of unparseable 500+ char SVG
- computed width/height/line_height returned for label layout

Also correct the raw drawing_create docstring: root width/height are
required (the parser reads them for the selection box), x/y on rect are
ignored, <g> is unsupported, <path> is re-interpreted as a freehand
curve, and the old examples lacked the mandatory root dimensions.
2026-10-09 11:12:18 +08:00
YueGuobin 1e0d123f4b Merge branch '3.1' into fix/duplicate-device-configs-merge
Resolve conflicts against the upstream wave (PRs #2952-#2965, incl. the
typed-response/schema hardening and the drop of Python 3.10):

- controller/node.py: keep upstream's _transitioning/_confirm_status
  lifecycle guard; the kernel-anchor link wiring (node_started) runs
  after the transition completes.
- controller/link.py: keep upstream's add_node rollback (release_ports
  on create failure) and delete via release_ports; release_ports now
  resolves ports live (same staleness reason as _bind_members) and
  discards the node link unconditionally.
- schemas/controller/links.py: extend LinkFilterType with the eight
  kernel-datapath filter types and LinkFilterParameter.type with "str"
  so the newly typed /available_filters response validates; Link.filters
  stays a free-form dict — the vocabulary is capability-gated per link
  and validated by the controller (409), not by a strict request schema.
- schemas/controller/topology.py: drop the type: ignore made redundant
  by the dict filters field.
- tests: route-level filter validation now expects the controller's 409
  (unknown types, out-of-range values); packet_loss correlation is a
  valid kernel parameter (positive test added); OpenAPI assertions match
  the free-form filters property.
2026-10-09 10:03:50 +08:00
Jeremy Grossmann aab707a48e Merge branch '3.1' into api-issue-10-0eztih 2026-10-08 19:31:48 +02:00
grossmj 8fee1d4c36 fix: "LinkFilterParameter" already defined 2026-10-08 19:31:25 +02:00
Jeremy Grossmann acfd4f9c1b Merge pull request #2956 from markparonyan/api-issue-07-x7z6we
feat(api): generate unique readable OpenAPI operationIds
2026-10-08 19:26:08 +02:00
Mark Paronyan 719d9cc667 refactor: ruff fixes 2026-10-08 20:25:20 +03:00
Jeremy Grossmann aeac649c7f Merge branch '3.1' into api-issue-10-0eztih 2026-10-08 19:21:07 +02:00
grossmj 34266d9d7b style: reorder imports for comply with lint 2026-10-08 19:16:57 +02:00
Jeremy Grossmann 2dd1652e8a Merge branch '3.1' into api-issue-07-x7z6we 2026-10-08 19:10:42 +02:00
Jeremy Grossmann 044b23564d Merge pull request #2955 from markparonyan/api-issue-06-8s9swu
fix(api): declare binary and streaming bodies in OpenAPI
2026-10-08 19:08:42 +02:00
Jeremy Grossmann 57e4d1632d Merge branch '3.1' into api-issue-05-2xftmd 2026-10-08 19:04:36 +02:00
Jeremy Grossmann 7a3a34d3fc Merge branch '3.1' into api-issue-06-8s9swu 2026-10-08 19:01:57 +02:00
Jeremy Grossmann 24634b8f0d Merge pull request #2965 from GNS3/drop-python-3.10
Drop Python 3.10 support
2026-10-08 19:01:34 +02:00
grossmj d1d4e7dce5 fix(deps): install the SQLAlchemy asyncio module so the 'greenlet' library is installed 2026-10-08 18:45:04 +02:00
grossmj e0260f27c7 fix(rbac): annotate query variables with Select type for better type checking 2026-10-08 18:39:20 +02:00
Jeremy Grossmann 8dd438190d Merge pull request #2960 from markparonyan/api-issue-12-cu0jkp
feat(api): add discriminators to link iface, appliance version and template settings schemas
2026-10-08 17:17:02 +02:00
grossmj d8118fa355 chore(deps): downgrade websockets to v16.1.1 2026-10-08 17:08:17 +02:00
grossmj f50653107b style: fix import and lint errors after merging 2026-10-08 16:57:41 +02:00
Jeremy Grossmann 48ac1ee5b7 Merge branch '3.1' into drop-python-3.10 2026-10-08 16:56:36 +02:00
Jeremy Grossmann 451e947d65 Merge pull request #2962 from markparonyan/api-issue-15-r12z73
fix(api): derive OpenAPI version from package, add servers, hide AI stub routes
2026-10-08 16:50:59 +02:00
Jeremy Grossmann cea858acc4 Merge branch '3.1' into api-issue-12-cu0jkp 2026-10-08 16:46:37 +02:00
Jeremy Grossmann 029983260c Merge branch '3.1' into api-issue-15-r12z73 2026-10-08 16:42:57 +02:00
grossmj 57286c4f09 style: fix lint errors 2026-10-08 16:01:51 +02:00
Jeremy Grossmann ddcf661e11 Merge branch '3.1' into api-issue-07-x7z6we 2026-10-08 15:51:11 +02:00
grossmj 917b19d808 chore(deps): update dependencies 2026-10-08 15:40:29 +02:00
grossmj 2642345b0a fix: import errors 2026-10-08 15:33:53 +02:00
grossmj 059056e97f Revert "Set target-version = "py310" in pyproject.toml"
This reverts commit 330741598a.
2026-10-08 15:27:53 +02:00
grossmj 330741598a Set target-version = "py310" in pyproject.toml 2026-10-08 15:25:32 +02:00
grossmj 90a98e7a45 Python 3.15 is not yet available on GA 2026-10-08 15:16:58 +02:00
grossmj 811b45f863 fix: drop Python 3.10 and add Python 3.15 support 2026-10-08 15:14:34 +02:00
Jeremy Grossmann 3187828325 Merge branch '3.1' into api-issue-06-8s9swu 2026-10-08 15:02:51 +02:00
Jeremy Grossmann a9e5f859c8 Reorder import statements in test_nodes.py 2026-10-08 14:49:12 +02:00
Jeremy Grossmann 71da996362 Merge branch '3.1' into api-issue-05-2xftmd 2026-10-08 14:40:53 +02:00
Jeremy Grossmann 83d5bf6835 Merge pull request #2953 from markparonyan/api-issue-04-burx2g
fix(links): reserve ports on add, accept port name and auto, add port_in_use code
2026-10-08 14:26:50 +02:00
Jeremy Grossmann 53f3169107 Fix module list after merging 2026-10-08 14:17:07 +02:00
Jeremy Grossmann a32f466183 Merge branch '3.1' into api-issue-04-burx2g 2026-10-08 13:59:00 +02:00
YueGuobin d640050d4b docs(features): quantify the kernel netem correl bias that collapses small rates
The kernel's correlated-random generator (get_crandom, sch_netem.c) truncates
instead of wrapping, starving both edges of the stationary distribution: an
event threshold below the correlation value is almost never reached. Measured
with stock iproute2 on this kernel — uBridge's netlink encoding is identical:
loss 1% + correl 25% drops nothing over 2000 pings (expected ~2%), 10%/25%
measures ~1.8% one way, only the 50% symmetry point survives. duplicate and
reorder correl share the same comparison structure and collapse the same way;
gemodel is immune (Markov chain over plain uniform draws) and is the honest
tool for bursty loss at a chosen mean rate.

Documented in the packet-filters correlation-bias bullet, and surfaced in the
two machine-facing descriptions (MCP link_update packet_loss note, controller
filter schema) so agents and clients stop walking into the trap.
2026-10-08 19:42:18 +08:00
Jeremy Grossmann 48b6257410 Merge pull request #2952 from markparonyan/api-issue-02-rp8mx3
feat(api): return node and add wait option on node lifecycle calls
2026-10-08 11:05:28 +02:00
Jeremy Grossmann 5055664456 Merge pull request #2957 from markparonyan/api-issue-08-67pip0
feat(api): add machine-readable error codes and align OpenAPI error schemas
2026-10-08 09:30:13 +02:00
Jeremy Grossmann ed8b0c3e20 Merge pull request #2958 from markparonyan/api-issue-09-aef9as
feat(api): return token lifetimes and document API keys as bearer tokens
2026-10-08 04:35:19 +02:00
Jeremy Grossmann dc57c95f1c Merge pull request #2963 from markparonyan/api-issue-16-0gmylm
feat(api): add Snapshot.created and type NodeFile timestamps as date-time
2026-10-08 04:15:01 +02:00
Jeremy Grossmann d797069921 Merge pull request #2964 from markparonyan/api-issue-17-asr039
feat: add optional ETag/If-Match concurrency for projects, nodes and links
2026-10-08 04:14:04 +02:00
Jeremy Grossmann 0a78a2bf12 Merge pull request #2961 from markparonyan/api-issue-13-bfbm9z
feat(api): add Notification schema and document notification streams
2026-10-08 04:11:14 +02:00
Jeremy Grossmann bcf38d74f8 Merge pull request #2951 from markparonyan/api-issue-11-gqdty1
feat(api): type link filters and available_filters response
2026-10-07 18:25:30 +02:00
Guobin Yue 5238bd3b39 Merge branch '3.1' into fix/duplicate-device-configs-merge 2026-10-07 23:59:30 +08:00
YueGuobin 5be4f52a2f docs(features): describe how the 13 filter types combine
A "Combining filters" section for packet-filters.md: deterministic drops
are an OR-gate (first kill wins — a clsact-dropped frame consumes no rate
serialization, no limit capacity and no netem counter), netem draws are
independent probabilities that multiply in one qdisc pass, and a round
trip squares everything. The couplings that do exist: quota's byte count
sees only frequency_drop survivors (ordered evaluation slows the burn),
delay/reorder/rate fold into one time_to_send, limit x rate x delay is
the tail-drop triangle to watch, and seed pins netem's draws but not the
eBPF program's own PRNG. Closes with a fully-loaded 12-filter walkthrough
of one frame through the gauntlet.
2026-10-07 22:47:15 +08:00
YueGuobin 96006dcf58 docs(features): give packet filters their own doc with the evaluation-order diagram
The Packet filters section of docker-kernel-datapath.md was the de-facto
filter documentation every other datapath doc pointed at; move it to
features/packet-filters.md as the node-type-neutral home (veth or TAP
anchor), centered on a mermaid walkthrough of all 13 types through the
anchor's egress chain: clsact first (the eBPF stateful classifier's nth /
quota / window modes at prio 1, then the bpf expression lines at 10-99,
first drop wins), the single netem qdisc behind it (enqueue draws, one
time_to_send drained by the delay queue).

Clarify a naming trap the table verbs invite: uBridge's tc module only
borrows the iproute2 vocabulary — the tc ... tokens are its own hypervisor
command names over hand-built netlink messages (RTM_NEWQDISC /
RTM_NEWTFILTER), raw bpf() syscalls, embedded distribution tables and
instruction array, libpcap as a library only; the tc binary is never
invoked outside the test suite's oracles. Verified against the uBridge
sources (hypervisor_tc.c, tc_impair.bpf.c, tc_ebpf.c), not just the
commands gns3-server sends.

docker-kernel-datapath.md keeps a pointer section; the iol doc's filter
reference and docs/README.md's tree and catalog point at the new doc.
2026-10-07 22:39:39 +08:00
Mark Paronyan 241c2b65e7 feat: add optional ETag/If-Match concurrency for projects, nodes and links 2026-10-07 16:53:11 +03:00
Mark Paronyan db031416a1 feat: add response models for endpoints returning untyped objects 2026-10-07 16:49:31 +03:00
Mark Paronyan 6ed9e44f00 feat(api): generate unique readable OpenAPI operationIds 2026-10-07 15:53:00 +03:00
Mark Paronyan 11a310dd9b feat(api): type link filters and available_filters response 2026-10-07 15:48:52 +03:00
Mark Paronyan a9e87df644 fix(links): reserve ports on add, accept port name and auto, add port_in_use code 2026-10-07 15:41:04 +03:00
Mark Paronyan e1a27dadcf feat(api): add strict_names and batch node and link creation 2026-10-07 15:35:45 +03:00
Mark Paronyan 6a416d1a2a feat(api): return node and add wait option on node lifecycle calls 2026-10-07 15:35:11 +03:00
Mark Paronyan ead44787f3 feat(api): add Snapshot.created and type NodeFile timestamps as date-time 2026-10-07 15:25:15 +03:00
Mark Paronyan 8cb92e7685 fix(api): derive OpenAPI version from package, add servers, hide AI stub routes 2026-10-07 15:21:30 +03:00
Mark Paronyan 86a279330d feat(api): add Notification schema and document notification streams 2026-10-07 15:14:50 +03:00
Jeremy Grossmann 0836e01525 Merge pull request #2950 from markparonyan/api-issue-14-yywwso
fix(api): return 200 instead of 201 for ACL endpoints, IOU license up…
2026-10-07 13:50:53 +02:00
Jeremy Grossmann 4eebe5c056 Merge pull request #2949 from markparonyan/api-issue-03-85fcdr
feat(api): add exact-match name filter to list endpoints
2026-10-07 13:41:59 +02:00
Mark Paronyan a4f20e0966 feat(api): add discriminators to link iface, appliance version and template settings schemas 2026-10-07 14:22:18 +03:00
Mark Paronyan fcfa968cc5 feat(api): return token lifetimes and document API keys as bearer tokens 2026-10-07 14:18:18 +03:00
Mark Paronyan 289f9394b6 feat(api): add machine-readable error codes and align OpenAPI error schemas 2026-10-07 14:15:41 +03:00
Mark Paronyan ba0465f191 fix(api): declare binary and streaming bodies in OpenAPI 2026-10-07 14:09:02 +03:00
Mark Paronyan 97d5480241 fix(api): return 200 instead of 201 for ACL endpoints, IOU license update 2026-10-07 13:56:08 +03:00
Mark Paronyan 852dc5be0f feat(api): add exact-match name filter to list endpoints 2026-10-07 13:40:34 +03:00
YueGuobin 980254b9e6 Merge branch 'feat/e2e-ipv6-dualstack' into fix/duplicate-device-configs-merge 2026-10-07 13:20:22 +08:00
YueGuobin 6459122113 test(e2e): run every traffic checkpoint dual-stack (IPv6)
The live suite asserted the datapath over IPv4 only. Give every guest a
ULA IPv6 address next to its v4 one and twin every v4 assertion point,
sharing the impairment window (one filter application, both families
asserted) so the runtime grows by minutes, not double.

- harness: configure_ios(eth_ipv6=), ping() dispatches to `ping ipv6`,
  docker_bring_up_ipv6 (the Docker daemon leaves eth0 with
  disable_ipv6=1 on v6-less bridge networks, so the interfaces-file
  route cannot work), family-aware docker_wait_address, pcap_records
  scans every record (a leading DAD/MLD frame must not mask the
  sampled ethertype), and pcap_icmp_rtt measures the wire round trip
  from capture timestamps;
- scenarios: connectivity/delay/suspend/isolation/churn checks in both
  families, captures assert 86dd next to 0800, the libpcap bpf drops
  are asserted family-selective (icmp vs icmp6, each killing its own
  family and leaving the other alive), the eBPF classifier modes on
  both families, marker v6 twins with an echo-specific expression
  (bare icmp6 also matches DAD/MLD and would break the exact counts),
  the v6 sharkd replay, and the link-local matrix gains the 86dd
  all-nodes row; serial (HDLC) legs stay v4-only;
- the dynamips-emulated classic IOS under-reports its `ping ipv6` RTT
  by ~40 % of a delayed round trip (pcap-verified: the wire carries the
  v6 echo exchange in the same ~230 ms as v4 while the console reports
  ~130 ms), so the dynamips-family scenarios assert the v6 delay from
  the capture's own timestamps — recorded in tests/e2e/README.md.

Full suite: 17 passed in 58m50s.
2026-10-07 13:19:38 +08:00
Jeremy Grossmann 2fb7056cb9 Merge pull request #2948 from cristian-ciobanu/ssh-web-console-crash
fix(console): keep SSH web console open after terminal resize
2026-10-07 04:58:08 +02:00
Cristi 51f7d06fae fix(console): keep SSH web console open after terminal resize 2026-10-07 00:21:03 +03:00
Jeremy Grossmann 49f047d07a Merge branch '3.1' into fix/duplicate-device-configs-merge 2026-10-06 17:09:32 +02:00
Jeremy Grossmann f051bf2505 Merge pull request #2945 from cristian-ciobanu/images-nested-folders-support
Support uploading images into nested subfolders inside predefined image directories, and check whether templates can be created for uploaded images based on  existing appliance definitions.
2026-10-06 17:07:28 +02:00
Jeremy Grossmann f184883aa7 Merge branch '3.1' into images-nested-folders-support 2026-10-06 16:50:40 +02:00
YueGuobin 96be37baa1 test: cover the namespace-failure veth cleanup and BridgeNIO field validation
Both fixes from the code-review pass were carried by other tests'
side effects: the move_to_ns failure path (the branch that used to skip
the delete_veth) and the required-but-nullable bridge field on the NIO
create routes.
2026-10-06 22:42:31 +08:00
Jeremy Grossmann 2d8ddb5ed7 Merge branch '3.1' into fix/duplicate-device-configs-merge 2026-10-06 16:34:48 +02:00
Jeremy Grossmann 37bcd9171e Merge pull request #2943 from markparonyan/fix-api
refactor: discriminate appliance settings by template_type
2026-10-06 16:21:31 +02:00
Jeremy Grossmann e2161fb66c Merge branch '3.1' into fix-api 2026-10-06 16:12:18 +02:00
Jeremy Grossmann 0170d2c8ce Merge branch '3.1' into fix/duplicate-device-configs-merge 2026-10-06 16:10:23 +02:00
Jeremy Grossmann 01425eb75d Merge pull request #2947 from markparonyan/fix-apii
refactor: derive update schemas with PartialUpdateModel
2026-10-06 16:07:19 +02:00
Mark Paronyan d9678ce98c refactor: derive update schemas with PartialUpdateModel 2026-10-06 16:46:22 +03:00
YueGuobin 1542a222f4 refactor: share the anchor-TAP lifecycle in the kernel-datapath mixin
The persistent-TAP lifecycle — probe, sweep, create, register, delete —
was implemented four times, once per node type, and the copies had drifted
(probe mechanism, _tap_datapath reset, keep-vs-recreate policy). The
mechanical half moves into KernelDatapathMixin:

- _probe_persistent_taps(probe_name): the scratch-TAP probe, returning the
  refusal for the caller's own warning (QEMU, Dynamips);
- _create_anchor_taps(ports, set_owner, keep_existing): sweep + create +
  optional ownership handover + carrier down + registry, with the ports
  enumerated by the node type and named through the new _tap_name hook;
- _delete_anchor_taps(): the suppressed tap sweep + per-link bridge
  cleanup + registry clear.

Each node type keeps what its fd holder dictates: the release step before
the tap sweep (the QEMU process, the IOL bridge, the hypervisor's NIO
bindings, the container port bridges), its probe policy, and its registry
lifetime. QEMU's now-unconditional registry clear aligns it with the other
three; everything else is behavior-preserving.
2026-10-06 21:17:50 +08:00
YueGuobin 35cf964882 test: cover the kernel-datapath review fixes
Regression coverage added with the fixes:
- capture-slot semantics: second-port refusal, failed-start rollback, and
  a non-owner port's stop not reaching `capture stop_kernel`;
- QEMU stop/start teardown on a mid-body or pre-launch failure, IOU start
  cleanup and filter guards, Dynamips half-attach undo plus retry;
- switch VLAN reconcile skipping a deferred anchor and rolling the
  ports_mapping back on failure;
- Docker/QEMU occupied-port refusal, probe ctime invalidation, probe
  survival of a failing uBridge start;
- env-marker dialects (mid-line mentions, falsy values) and the agent
  merge rejecting entries without a device_name.

Test-body imports of product modules move to the shared header.
2026-10-06 19:55:31 +08:00
YueGuobin c3c025ab2a fix: resolve the code-review findings on the kernel datapath
Compute:
- Track the anchor that owns uBridge's single AF_PACKET capture slot: a
  second kernel port's capture is refused with a clear error (its flag
  rolled back), a failed start no longer wedges the port, and only the
  owning port's stop issues the process-wide `capture stop_kernel`
  (docker/qemu/iou/dynamips/switch, via the mixin's slot helpers).
- Unwind failed starts instead of leaking uBridge and the anchor TAPs:
  QEMU's stop body runs under try/finally, QEMU and IOU start the datapath
  inside the launch try, Dynamips undoes a half-attached port (the retry
  used to be short-circuited into a silent black hole), and Docker deletes
  the veth pair when the namespace move fails.
- Restore the relay filter guard on IOU (kernel-only filters raise
  NodeError, an uncompilable BPF line degrades to a warning), validate the
  eBPF/quota/window/bpf filter shapes before touching the bridge (short or
  non-numeric values surfaced as 500s after partial state), and refuse a
  second NIO on an occupied Docker/QEMU port (the guard IOU and Dynamips
  already had).
- Probe fixes: `_probe_bridge_tap` survives a failing uBridge start, and
  the probe caches key on ctime too, so a chmod/setcap remedy re-probes.

Controller:
- Parse GNS3_UNIX_SOCKET_NIO like the compute does (line-anchored, truthy
  value) and mirror the compute's class selection in kernel_anchor_type.
- Read partial capability reports defensively; make BridgeNIO.bridge
  required-but-nullable so an omitted key is a 422 rather than a KeyError.
- Strip the packet_loss correlation slot even when it is zero: the relay
  filter takes exactly one argument and rejected `packet_loss 10 0`.

Ethernet switch: skip ports whose absorbed anchor does not exist yet (the
join is deferred by design) and roll the ports_mapping back when the VLAN
reconcile fails, so a retry still diffs against the old mapping.

Agent: reject device config entries without a device_name instead of
silently dropping them (a malformed batch used to execute partially while
reporting success).

Also split the netem builder to clear C901 and drop the two per-file ruff
ignores the PR had added, keeping the remove-only policy.
2026-10-06 19:55:21 +08:00
Cristi 5492105e58 fix(image-manager): Fix type-check errors in image uploads and appliance installation 2026-10-06 00:13:53 +03:00
Cristi a7f0c7174b fix(templates): Fixed template test formatting to pass CI 2026-10-06 00:04:26 +03:00
Mark Paronyan cbd4f457be Merge branch '3.1' into fix-api 2026-10-05 21:23:03 +03:00
Mark Paronyan b8e552ee9d refactor: ruff fixes 2026-10-05 21:05:24 +03:00
YueGuobin 87ca2138e3 chore(lint): apply the 3.1 f-string wave to the kernel-datapath code
The rebase onto 65c858d45 brought upstream's UP032 enforcement; the
conflict resolution kept this branch's semantics on the overlapping
lines, so their .format() calls needed the conversion afterwards
(ruff check --fix, 41 sites) plus the formatter's rewrap (7 files).

Replicates the CI recipe locally: pip check, ruff check/format, mypy
2.3.1 (clean, 434 files), unit suite 2216 passed.
2026-10-06 00:28:06 +08:00
YueGuobin 5841138cef docs(e2e): complete the README — requirements, image matrix, host notes
Adds what running the suite on a real machine actually requires (uBridge
with caps, tc for the filter assertions, a Docker daemon, cc -static for
the raw-frame probe), the full image-selection matrix (preferred
filenames, fallback patterns, per-folder layout, the alpine digest
ladder; missing images skip, never false-fail), the NetworkManager host
hazard and its record, timing/load sensitivity notes, the complete
GNS3_E2E_* environment-variable list — and the link-local scenario,
which the scenario list was missing.
2026-10-06 00:21:11 +08:00
YueGuobin f688e654e1 test(e2e): widen the fast-path RTT bound to 100 ms via harness.FAST_RTT_MS
The 'impairment cleared' asserts used avg < 50 on three-packet IOS pings;
the unimpaired baseline is 20-45 ms with 4 ms quantization, and host
scheduling jitter pushed averages to 54/56 in two full-suite runs
(esw, dynamips) — a margin, not an impairment (the qdisc asserts pass,
success is 100 %). The contrasted delayed regime is >= 150 ms, so a
100 ms bound still separates the two cleanly. Docker's sub-millisecond
veth asserts keep their 50 ms bound (three orders of magnitude of
headroom, never observed to flake).
2026-10-06 00:21:11 +08:00
YueGuobin f21d7be99c test(e2e): derive busybox ping loss from replies when the summary is lost
The exec stream can truncate after busybox's 4294967 ms RTT timer-wrap
artifact, dropping the summary line — docker_ping then reported a
phantom 100 % loss and made the corrupt-filter scenario fail spuriously.
Factor the parsing into _busybox_ping_parse: the summary stays
authoritative when present; otherwise the loss is derived from the
seq= replies actually seen (no replies at all still reports 100 %).
2026-10-06 00:21:11 +08:00
YueGuobin 15fbef93fb test(e2e): unmanage the TAP anchors in the remaining kernel scenarios
Same guard the ethernet-switch scenario already carries: NetworkManager
can release an NM-managed TAP from its bridge shortly after
(re-)enslavement (docs/bugs/networkmanager-tap-release.md). Applied to
the Dynamips, QEMU, IOU, IOL-runner and switch-cascade scenarios after
their nodes have booted (no-op where nmcli/NetworkManager is absent).
This keeps those tests deterministic on un-declared hosts.
2026-10-06 00:21:11 +08:00
YueGuobin 28e9b82a5f docs(bugs): managed-yes cannot re-arm the baseline once the conf matches 2026-10-06 00:21:11 +08:00
YueGuobin 20b7968e33 docs(bugs): note how to re-observe the baseline on an already-declared host 2026-10-06 00:21:11 +08:00
YueGuobin 6c73bb15f0 docs(bugs): embed the runnable TAP-release reproducer and the measurement method
The reproduction section described the harness only in prose; the actual
driver scripts were throwaway lab files. Embed the distilled, runnable
reproducer (drives uBridge's control socket through the repo's own client,
kept tap for the single-variable A/B), the exact measurement semantics
(40 re-enslavements, ~1 kHz / 200 ms membership sampling, a release = the
brif entry vanishing, latency print) and the flip protocol, so a reader
can reproduce the 19-20/40 vs 0/40 numbers on an affected host. Also point
the host-fix layer at the reproducer for re-verification.
2026-10-06 00:21:11 +08:00
YueGuobin 3018d3aecc docs(bugs): record the NetworkManager TAP-release root cause, repro and fix
A kernel-datapath link could die silently after a delete/recreate: on
NetworkManager hosts, NM's state machine releases an NM-managed TAP from
its bridge 58-87 ms after (re)enslavement (~50% while the tap has not
been assumed yet; the port stays up, no GNS3 process logs anything).
Root-caused with a server-free minimal harness (one uBridge, one tap,
one bridge, an addif/delif loop) and a single-variable NM A/B; the
NetworkManager side is explained by three of its commits (assumption
recheck on external enslavement, master removal during activation,
external changes not touching assumed slaves).

Records: forensic signatures (ifindex unchanged, flags 0x300 cleared,
heal-on-next-update), the reproducer, the verified host fix
(unmanaged-devices conf.d snippet: 19-20/40 -> 0/40, and the e2e
scenario green with test-side workarounds disabled), scope and history
(2016 issue #440 veth incident; the 2026-10-01 ethernet-switch
incident previously misattributed). Cross-linked from the L2-anchor
spec and the switch feature doc.
2026-10-06 00:21:11 +08:00
YueGuobin 1c85befbab test(e2e): take the switch anchors out of NetworkManager's reach
The esw kernel fast-path scenario deletes and re-creates a link, which
re-enslaves the peer anchor — and on NetworkManager hosts NM's netdev
state machine can release an NM-managed TAP from its bridge some 60-70 ms
after enslavement, ~50% of re-enslavements, while the tap is in NM's
not-yet-assumed state. The freed port stays administratively up and no
GNS3 process logs anything: the membership assert sees the join, then the
ping measures a silent blackhole (this was the line-277 e2e failure).

Root-caused with a server-free harness (one uBridge, one fresh tap, one
bridge, an addif/delif loop): the same tap frees 20/40 while NM-managed,
0/40 after `nmcli device set <tap> managed no`, 20/40 again when
re-managed. Docker's veth host ends are not NM-managed, which is why only
TAP anchors ever showed it — including the "anchor lost its bridge
membership after a ports_mapping update (TAP peers only)" incident from
the switch's development, whose conclusion is corrected in the docs.

Unmanage the anchors once the routers have booted, before the scenario
re-enslaves them; document the failure signature and the host-side remedy
(per-device nmcli call, or NM unmanaged-devices configuration) in the
L2-anchor spec and the switch feature doc.
2026-10-06 00:21:11 +08:00
YueGuobin dc5e2d90ba fix(iou): keep BridgeNIO filters across the NIO update route
Upstream's mypy pass narrowed the filter copy to UDPNIO only (the
Ethernet/TAP members of the union have no filters field). BridgeNIO —
the kernel-datapath NIO — carries filters too, so on an IOU kernel link
every PUT of a link's filters cleared them and applied nothing: netem
never landed on the anchor (e2e test_iou_kernel_datapath caught it).

Narrow to (UDPNIO, BridgeNIO): still avoids attribute access on the
models without the field, keeps both filter-carrying types.
2026-10-06 00:21:11 +08:00
YueGuobin 7d04d08dba fix: repair imports lost in the 3.1 rebase and meet the new lint baseline
The rebase onto upstream 3.1 (mypy + ruff I001/F401 waves) left the tree
short of the newly enforced baselines in three ways:

* contextlib / UbridgeError imports dropped as false duplicates during
  conflict resolution left NameErrors in iou_vm and qemu_vm (F821);
  the Dynamips router grabbed the compute-level NIOTAP instead of the
  hypervisor one, breaking TAP anchoring (test failure).
* unused imports (KERNEL_UNSUPPORTED_FILTERS, UbridgeError, List) and
  unsorted blocks left behind where the stack's later commits moved the
  last usage elsewhere — ruff I001/F401/RUF022 now enforce these.
* mypy, now baseline-free: cache dict annotations in tc_probe, the
  locators candidate list, the resolved-params None branch in the MCP
  runner, and validate_bpf_syntax keeps the upstream Dict[str, Any]
  return (the strict Optional[str] was wrong for the "valid" bool entry).

The e2e raw-frame probe resolves its compiler via shutil.which (S607)
and zips with strict= (B905); the remaining subprocess call is S603 by
nature and gets a per-file ignore like other test files.

ruff check/format clean, mypy at upstream parity (no new errors),
full unit suite 2167 passed.
2026-10-06 00:21:11 +08:00
YueGuobin e13e5f3804 fix(tools): merge same-device entries before device command execution
A batch carrying the same device twice lost all but the last entry's
commands: the per-device command map kept only the last entry while
result processing iterated every original entry, so each row reported
the last entry's output under its own command list.

c3c78f99a consolidated the merge into the MCP template renderer, but
that only runs when a template is passed — the MCP direct-commands
path and gns3-copilot's direct _run path were left uncovered.
Normalize once in each tool's _run (single point covering all entry
paths, restoring the c42b3a59b coverage) and keep the renderer merge
as boundary normalization. Blocked-command info now also accumulates
across same-device entries instead of last-winning in the per-device
map.
2026-10-06 00:21:11 +08:00
YueGuobin d0b0cdbd38 fix(compute): a passive absorbed anchor no longer resets the switch's tc state
The peer end of an Ethernet switch fast-path link is a NIOBridge with no
bridge of its own (the switch absorbed its anchor into the switch bridge).
Its update reconcile still ran the impairment pass with the empty filter
set the controller routes to that end — and an empty set is a plain
`tc reset` on the shared anchor, silently wiping the netem/cls_bpf/eBPF
the switch had just applied. Any link update did it (filters, markers,
suspend, capture start/stop), and the outcome depended on the link's
endpoint order: UdpLink.update() PUTs node1 then node2, so with the
switch first its apply ran first and the peer's reset ran last (API
green, data plane unimpaired), while with the peer first the reset ran
first and the filter survived. That order dependence is also why the
shipped e2e never caught it — it only created peer-first links.

Ownership is now explicit: only the end that owns the anchor's tc state
applies the impairment reconcile (_owns_anchor_impairments — a NIOBridge
with `bridge is None` is a passive carrier, the same idiom the
bridge-delete path already used). Markers, capture and the suspend
carrier still apply on both ends: markers reconcile per process, so
neither end can strip the other's, and the carrier converges by
agreement.

Red/green: two new docker unit tests fail on the unfixed tree with
`tc reset "<anchor>"` and pass after; the switch e2e also creates one
link switch-first and asserts the netem qdisc and the RTT hold under
that order (failed with the wipe, passes with the fix). Full unit suite
2110 passed; the switch e2e file passed end to end (378s).
2026-10-06 00:21:11 +08:00
YueGuobin 7a9a514ea3 docs: kernel-datapath family review pass — accuracy fixes and pinned claims
A correctness read-through of the five delivered datapath documents, plus
the two code comments that carried the same stale vocabulary.

Datapath selection: the VendorDockerVM selector is `console_type=docker_exec`
alone (`GNS3_SKIP_INIT` and friends are behavior knobs of the chosen class);
the cross-compute and anchor-less fallbacks are named for what they are; the
Ethernet-switch endpoint is the documented exception to the anchoring rule,
and the IOL runner container is called out as the Docker node that does not
anchor on a veth.

Filter vocabulary: the stateful eBPF program evaluates four modes
(nth → quota → window → flow), GNS3 exposes three of them, and window_drop
joins the kernel-only list; the correl suffixes gate on the `rate` token as
the extension-build marker.

group_fwd_mask: the 0xfffd port mask is applied inside uBridge's `brctl addif`
itself, not as a separate command — the link-creation sequences and the
operation tables no longer show an arrow the server never sends. Same class
of fix for `link set up` on the IOL anchor (addif already brought it up; the
command only pushes a suspended anchor back down) and for the QEMU carrier
replication (QMP `set_link`, gated by `replicate_network_connection_state`).

Lifecycles and stop orders re-worded around the invariant rather than the
node type: the fd holder must release before the devices are deleted, which
is QEMU's process-first order, IOU's uBridge-first order and Dynamips'
hypervisor-NIO-first order. Deferred wiring for a stopped endpoint is
documented as the common path it is, and the Dynamips "stop is not a close"
note now says what recovery from a dead hypervisor actually requires.

Dynamips specifics: a c7200 needs an adapter in slot 1 (slot 0 is the fixed
I/O slot), the tap-fd direction is stated correctly (writes inject into the
kernel, reads return what the kernel transmits), and the anchor registry is
name-keyed against the controller's port matrix by convention, not derivation.

IOL port bridge naming: `bridge{bay}` on unit 0, `bridge{bay}_{unit}`
elsewhere; the leg swap happens on link delete/re-create or a datapath
switch, while suspend is an in-place NIO update and a project reopen is a
fresh build.

Verified and Roadmap sections: the in-repo e2e suite is distinguished from
the isolated-instance development harness (IOU), assertions are stated with
their bounds and capability gates, and the roadmap entries collapse into the
one remaining project — VXLAN/GENEVE for cross-compute links.

Code comments: `flow` added to the documented mode order in the eBPF apply
path, and the `nio_bridge` module docstring corrected on which filter types
run on the kernel datapath (bpf via cls_bpf, frequency_drop/quota/window_drop
via the eBPF classifier — neither is relay-only any more).
2026-10-06 00:21:10 +08:00
YueGuobin 74010b9abd docs: dynamips kernel-datapath diagram suite, unified frame-path form across the family
The dynamips doc gets the full suite: anatomy (anchors reached by the
hypervisors' TAP fds, uBridge's AF_PACKET-tap / tc-qdisc sidebands), a
one-way copy-numbered relay comparison (six kernel/user crossings per
way against the kernel datapath's two TAP-fd legs), a staged walkthrough
(reserved-range diamond, egress clsact chain, capture/markers observation
sideband, copies 1-2) and a control sequence of real commands in real
order (hypervisor fd first, capture before markers, carrier last; router
handlers, not computes, as the per-node participants).

The four sibling frame paths are unified on the same form: netem qdisc
node labels, one capture/markers node outside the stages with AF_PACKET
tap edges anchored at ingress and post-chain egress, copy numbering
wherever the trace crosses the kernel/user boundary (qemu's two TAP-fd
legs, iol-docker's six socket/TAP legs), stage subgraphs with role-noted
titles everywhere (iol-docker restructured from its flat chain, iou's
chA/tapA variants folded into the canonical shapes).

The documentation skill records the rules as v3.1.0: four diagram kinds
(anatomy / comparison / control sequence / walkthrough), one step per
node, dashed sidebands per role with meaningful direction, numbered
crossings when copies are the point, glossary before the first diagram.
2026-10-06 00:21:10 +08:00
YueGuobin d0773aabea docs(iou): align the kernel-datapath doc with the delivered implementation
Sequence diagram: drop the phantom "port fwd_mask 0xfffd" step — uBridge
sets the per-port mask inside brctl addif and gns3-server never sends it.
Frame path: explain the ingress/egress mechanism in prose (the TAP-fd
write lands at the sender's anchor ingress, where nothing is installed;
the bridge's forward out the far anchor is the egress transmission the
tc chain sits on), and group the netio mailboxes into a kernel subgraph
matching the relay diagram. Suspend: a down anchor answers EIO on the
TAP fd in both directions (the section B hardening), not reads-block.
Term table: the anchor shape is per Ethernet bay (4 units per bay), not
the default 2x4. Link operations: carrier up is applied last, matching
_attach_kernel_nio. Link-local: note the verification matrix runs on the
Docker datapath. Reflow paragraphs to the soft-wrap convention.
2026-10-06 00:21:10 +08:00
YueGuobin 8bca2c70f8 docs: qemu kernel datapath doc in the family diagram style
Term table, QEMU↔QEMU topology with role-suffixed anchors and
frame-copies/qdisc-install dashed edges, relay copy-count diagram,
boxed frame path, link creation sequence; prose reflowed one
paragraph per line.
2026-10-06 00:21:10 +08:00
YueGuobin e04552cdb0 docs(iol): IOL runner kernel datapath — diagram suite and glossary
Replace the ASCII overview with mermaid diagrams per the documentation
standard: a glossary table first, then the two-container architecture
(port bridges inside their uBridge process blocks, the per-link Linux
bridge circled, dashed sidebands split by direction — frame copies flow
to uBridge, qdisc installs to the anchor), a copy-counted relay diagram
(six kernel/user crossings each way, datapath-invariant — swapping
datapaths only changes the middle two), the frame path with the
reserved-range diamond, and the link creation sequence. Details moved
from the old bullets into per-diagram prose; paragraphs reflowed to one
per line.
2026-10-06 00:21:10 +08:00
YueGuobin 2e29d053cf docs: docker kernel datapath — diagram suite, glossary and refreshed configuration
Replace the ASCII art with a mermaid suite (steady-state topology with
namespace boxes and sideband edge semantics, one-way frame path with
per-object boxes, link-creation sequence, full relay path with the four
kernel/user copies), add a term glossary ahead of the diagrams, reflow the
prose to soft-wrap, and refresh the stale parts: the configuration section
now describes enable_kernel_datapath as the global switch it already is,
with every anchorable node type landed and linked to its feature doc.
2026-10-06 00:21:10 +08:00
YueGuobin df79773bc0 test(e2e): live link-local matrix on the kernel datapath
Two Alpine containers on a kernel link, a static raw-Ethernet probe built
at run time and docker-cp'd in (the image has no raw-frame tool; DockerDaemon
gains the cp), injecting per-destination-MAC frames from guest 1 while
guest 2 counts arrivals: ordinary multicast, STP, LACP, 802.1X and LLDP must
cross, PAUSE must not (the documented kernel limit). Asserts the anchors'
sysfs brport group_fwd_mask reads 0xfffd through the server's own wiring
(int-parsed: newer kernels print it hex), that the bridge level stays 0, and
that a container stop/start replays the mask with LACP surviving. Negative
control is the uBridge suite's setportgroupfwd 0 case.
2026-10-06 00:21:10 +08:00
YueGuobin f03c94db6d docs: link-local frame transparency on kernel links — spec and per-datapath sections
A Linux bridge standing in for a cable does not forward the IEEE 802.1D
reserved range (01:80:c2:00:00:00-0f) by default, so LACP/LLDP/802.1X never
crossed a kernel-datapath link while the UDP relay carried them fine. uBridge
now opens every enslave'd port's IFLA_BRPORT_GROUP_FWD_MASK to 0xfffd at
brctl addif time (branch feature/bridge-tap-l2only, commits 0284500/03a18f1/
cf4e494), which the six kernel-datapath feature docs now document as a
section: STP, LACP, 802.1X and LLDP/DCBX cross; 802.3x PAUSE / PFC stays
dropped — br_handle_frame()'s case 0x01 discards it unconditionally, no mask
can enable it, and PFC labs must use a relay link. The full contract, kernel
references and requirements live in the new design spec, marked landed.
2026-10-06 00:21:10 +08:00
YueGuobin 86651604c4 test(e2e): relay capture and markers on both relay engines
The relay engines' observable paths had no live coverage: every
capture/start call in the suite sat on a kernel anchor (AF_PACKET
capture start_kernel) and markers were only asserted on marker
add_kernel. The two relay engines' own command shapes were unit-tested
only:
  * bridge engine  - bridge start_capture / bridge add_packet_filter ... mark
  * iol_bridge engine - iol_bridge start_capture / iol_bridge add_packet_filter ... mark

Docker relay control (bridge engine, 1 passed 33s): the capture start
REST call writes the ICMP exchange to a pcap off the relay bridge; a
mark filter attached with capture_node_id n1 signals exactly 10
marker.match events over the dedicated marker WS for 5 pings (5
requests + 5 replies, both directions), carrying node_id/link_id/tag and
the busybox frame length, writes exactly those 10 frames to the marker
pcap, and deleting the marker takes the pcap with it.

IOU relay control (iol_bridge engine, 1 passed 173s): the same two
checks on iol_bridge start_capture and the port's mark filter, driven
by the real IOS ping through the fabric socket relay.

Not duplicated in the ESW/VPCS/cloud relay controls: they issue the same
uBridge bridge commands through their own call sites, which stay covered
by unit tests; the IOL container relay goes through the same iol_bridge
engine already exercised here.
2026-10-06 00:21:10 +08:00
YueGuobin ff41a54364 test(e2e): assert the §E.2 idle-silence window in every kernel scenario
The L2-anchor spec's behavioral guarantee — an idle link stays silent for
5 s once the enslavement burst settles — only ran in the Dynamips and
Docker suites. It now also runs in QEMU, IOU, the IOL container, the
switch fast path and the switch cascade, which covers every host-device
creation path:

* tap create (Dynamips/QEMU/IOU anchors), docker create_veth (Docker host
  ends; the cascade's race-loser end is hardened after create by the
  server), bridge add_nio_tap (the IOL container anchor, the fifth
  creator), and the brctl switch bridges, whose multicast snooping is off
  precisely so the bridge role can reach silence;
* each scenario silences its guests first (IOS interfaces shut through
  the console; Docker guests' links down) and re-verifies the ping after;
* the cascade measures 8 devices at once (four absorbed router anchors,
  both cascade ends, both switch bridges).

IOL 158 s, cascade 293 s, ESW fast path 378 s, QEMU 428 s, IOU 308 s —
all green.
2026-10-06 00:21:10 +08:00
YueGuobin 1f544c96a5 test(e2e): classifier spot check and filter persistence on TAP anchors
The filter matrix (cls_bpf, the eBPF classifier) only ran on Docker veth
host ends; the IOU and IOL-container scenarios now spot-check it on their
TAP anchors and prove a filter survives a node restart:

* bpf "icmp" drops everything with clsact on the anchor, both ends, and
  clears back to an empty qdisc;
* frequency_drop 3 (the eBPF every-nth mode) measured 56 % round-trip
  loss (1 - (2/3)^2 = 55.6 % expected) in both scenarios;
* the IOU test applies delay 100 before a router stop/start: the fresh
  anchor gets netem back (tc level) and the restarted router's pings
  measure RTT >= 150 ms until the filter is cleared (a re-attach that
  dropped the filter would show ~100 ms).

IOU file 492 s, IOL file 182 s, both green.
2026-10-06 00:21:10 +08:00
YueGuobin 9d937802d5 test(e2e): relay filters shape real traffic on both relay engines
Extend the docker and IOU relay negative controls with the filters the
relay itself supports (delay, frequency_drop, bpf), asserted through real
ICMP — the first live coverage of the relay filter path:

* bridge engine (docker): delay 100 grows the RTT by ~200 ms and comes
  back on clear; frequency_drop 2 kills the round trips (the filter counts
  every packet crossing the bridge, both directions sharing one counter,
  so on an alternating ping stream one whole direction dies; verified
  against uBridge directly), frequency_drop -1 blackholes, and bpf drops
  by libpcap expression ('icmp', then 'greater 150' discriminating by
  frame size).
* iol_bridge engine (IOU): the same delay and frequency_drop effects
  through the port's iol_bridge filter list, plus the available_filters
  spot check.

Docker 33 s, IOU 168 s, both green.
2026-10-06 00:21:10 +08:00
YueGuobin 4fc0398423 test(e2e): live coverage for markers on the kernel datapath
Two Alpine containers on a kernel-only link with traffic-insight markers
attached to a veth anchor (marker add_kernel), observed on the dedicated
marker WebSocket via a new harness piece (WebSocketCollector, a sync
facade over websockets' sync client). Real ICMP proves: the marker.match
identity is complete (filter/tag/link_id/capture node/ts/len and the
tx/rx direction set of a ping), the main project channel carries no
matches, the BPF and direction are enforced (a non-matching sibling and
a tx-only marker each see exactly their traffic), the host pcap holds
exactly the matched frames, pausing silences one marker while a sibling
keeps counting (silence is never a dead channel), tag replay serves the
paused tag's timeline with display-filter/link/window narrowing and
refuses with 409 while capturing, and deleting a marker takes its pcap
and signals with it.
2026-10-06 00:21:10 +08:00
YueGuobin ad39b22ab4 test(e2e): live coverage for the switch cascade kernel datapath
Two switches cascaded through the link-owned veth pair, two c7200
routers per switch, real ICMP crossing both bridges: the pair is born
UP with exactly one end per switch bridge, a dot1q trunk cascade
carries two VLANs at once, the symmetric access/trunk mode flip on the
cascade ends isolates and revives a VLAN in place (asymmetric flips are
semantically broken — the access side egresses untagged into the far
trunk's native PVID), a delay filter lands as netem on both ends (one
per direction, RTT ~= 2x delay), suspend admin-downs both ends, and a
link delete/re-create retires the whole pair and mints a new one under
the new link id — zero host residue after the project goes.
2026-10-06 00:21:10 +08:00
YueGuobin cb7f74c77b fix(esw): harden the cascade end the create race leaves unhardened
docker create_veth hardens only its FIRST end (the Docker shape: host
anchor plus a container leg that keeps its L3 life). A cascade end is
that second, unhardened end whenever the peer switch's create won the
race, and the kernel gives it an IPv6 link-local — a silent L3 identity
on the switch fabric (ubridge-l2-anchor-spec §E). Each switch now
hardens its OWN end with 'link l2only <end> on' once the pair exists,
whatever branch brought it there (fresh create, lost race, reuse);
idempotent, and best-effort with a warning on a uBridge without the
command.
2026-10-06 00:21:10 +08:00
YueGuobin 6e36b58a5d fix(compute): refuse a duplicate port NIO and wire before bookkeeping
The compute-side backstop of the controller's duplicate-port guard
(keep-port-links + live-port bind made the controller guard reliable;
this is the layer under it). IOU and Dynamips bound the adapter NIO
before the uBridge/hypervisor attach: a failed attach left the port's
binding replaced — the link that still owned the port lost its handle
and its host state leaked (the IOU EBUSY incident's 8 orphan TAPs).
Dynamips was worse: its wiring idempotence check silently skipped the
attach on a second binding and rebound only the bookkeeping. A port
that already carries an NIO is now refused, and both types bind the
NIO only after the wiring succeeded.
2026-10-06 00:21:10 +08:00
YueGuobin 6839b279be docs(qemu): record the in-repo e2e coverage 2026-10-06 00:21:10 +08:00
YueGuobin 4fd7e1aa07 test(e2e): live coverage for the QEMU node kernel datapath 2026-10-06 00:21:10 +08:00
YueGuobin 928757542e fix(controller): bind and release link members on their live ports
Link.delete cleared the port link through the port object stored at
add_node time; a node update since then rebuilt the port list, so that
object was stale and the live port kept its link — the next link on the
port was refused with "Port is already used". Masked until now by the
older rebuild bug (c2d68a65d): links never survived a rebuild, so the
guard never fired and the stale clear never mattered.
2026-10-06 00:21:10 +08:00
YueGuobin 1e999d916d fix(controller): keep port links across a port-list rebuild
Node._list_ports() rebuilds every Port object, and it runs on each node
update — including every compute node.updated notification (a node
reporting started is one). The links are unaffected by that rebuild, but
the fresh port objects started out with link=None, so after any node
update the "Port is already used" guard in Link.add_node stopped matching:
a second link on an occupied port reached the compute, where the port's
NIO was replaced before the attach failed on the already-bound anchor,
leaving the link half-torn-down (on IOU, deleting the project afterwards
left the node's anchor TAPs and a per-link bridge on the host).

Carry the link back-references over by (adapter_number, port_number),
first match wins, mirroring get_port; a port that still exists keeps its
link. Regression tests pin both the reference (test_node) and the guard
(test_link: the duplicate link is refused after a node update).
2026-10-06 00:21:10 +08:00
YueGuobin a0d76b30c0 docs(iou): record the in-repo e2e coverage
The Verified section only described the /tmp driver with a fake IOU
image; the repository suite now carries the same scenario with real
routers on a real L3 image.
2026-10-06 00:21:10 +08:00
YueGuobin aaabf0409d test(e2e): live coverage for the IOU node kernel datapath
Two real IOU routers on a real L3 image (the image's own IOL fabric, the
real IOS CLI on the server's telnet console), driving the anchor TAPs the
kernel datapath builds on: anchors born with the node (one per Ethernet
bay/unit), real ICMP through the [fabric <-> TAP] port bridge, netem
delay, suspend, capture, link delete/re-create, node stop/start rewiring,
the serial link staying on the relay (serial bays never anchor) and a
relay negative control on an isolated instance. Every scenario ends with
no anchors, bridges or tmpdirs left behind.

harness: create_iou_node/iou_images/iou_anchor_name, and the IOS console
helper is now ios_console (dynamips, IOU and the IOL containers share it).
2026-10-06 00:21:10 +08:00
YueGuobin 765d706ec4 docs(docker): record the in-repo e2e coverage
The feature doc's Verification section now points at
tests/e2e/test_docker_kernel_datapath.py and what the suite pins down
(anchors/bridges, the filter matrix through real traffic, suspend,
capture, the stop/start and delete/re-create beats, the relay control and
the relay->kernel reopen upgrade), including the digest-pinned image the
scenarios share.
2026-10-06 00:21:10 +08:00
YueGuobin 897f50e430 test(e2e): live coverage for the standard Docker node kernel datapath
Two real Alpine containers on an isolated instance, addressed the way a
GNS3 user does it (the node's persistent /etc/network/interfaces, applied
by init.sh) and driven through the Docker daemon socket the server itself
uses. Four scenarios:

* fast path: the per-link kernel bridge enslaves exactly the two veth host
  ends, real ICMP crosses, the L2-anchor spec E.1/E.2 assertions hold
  (idle silence measured with the guests' links down -- a container's own
  boot-time IGMP report re-fires ~10 s later, so silencing is not just
  IPv6), netem delay, suspend/resume, capture, link delete/re-create,
  container stop/start (the veth host ends die with the adapter and are
  rebuilt from the NIO), zero residue on project delete;
* filter matrix, one type at a time, each asserted through real traffic
  and its tc state: netem core (delay, jitter+distribution, loss, corrupt,
  duplicate), the extensions (reorder+correl+gap, seed+limit, gemodel,
  rate), cls_bpf match-drop including a byte-size discriminator, the eBPF
  classifier (frequency_drop every-Nth and -1, quota byte-cap cutoff,
  window_drop single outage with per-seq pass/drop/pass evidence), plus
  available_filters offering the kernel-only types;
* relay control: no per-link bridge, the kernel-only types hidden;
* relay->kernel reopen upgrade: the datapath choice is flipped across a
  server restart and the project reopened -- the link is rebuilt on the
  kernel datapath and forwards.

The harness gains a Docker guest driver (a stdlib Engine API client over
the daemon socket: exec with stream demux, container id by deterministic
name -- the controller's node payload does not carry it, image inspect),
a digest-pinned image helper (cache hit = no network, miss = pull through
the server's own route, neither = skip) and Server.restart() for the
reopen scenario (which also needs the local compute's capabilities to be
up before a project open is accepted).

Live: 4/4 scenarios, 142 s for the file; full e2e suite 10/10 (1503 s);
unit suite 2149 passed; ruff clean. The matrix measures loss with 20
packets at 0.2 s spacing (143 s -> 58 s) and the jitter RTT assertion
keeps statistical margin (per-direction N(50,20); 10 packets, >= 65 ms).
2026-10-06 00:21:10 +08:00
YueGuobin e0329ceee6 test(e2e): give the dynamips routers a detected idle-PC
Without one every c7200 busy-waits a full CPU core for the whole scenario
-- the tests create raw nodes and no template supplies a value (measured:
constant ~100 % per router, up to ~6 minutes per dynamips scenario).

harness.dynamips_idlepc() detects a value through the controller's
auto_idlepc endpoint (the GUI idle-PC finder path: a throwaway project
boots the image, candidate values are validated by measuring actual CPU
usage) and caches it in ~/.cache/gns3-e2e/idlepc.json keyed by the image
checksum, so the cost (~100 s here) is paid once per image, not per run.
GNS3_E2E_IDLEPC overrides detection; any failure returns None and the
scenarios run without one rather than fail on a CPU optimisation.

All four scenarios that boot c7200 routers (dynamips kernel/relay,
ethernet switch kernel/relay) pass the value at creation. Live: detected
0x60189234 for the M11 image (238 s first run including detection); the
routers drop from ~100 % during boot to 3-8 % steady (sampled per
process), and a re-run reports the cached value with no detection.
2026-10-06 00:21:10 +08:00
YueGuobin f13da59f23 docs(ubridge): the fifth L2-only creator, and the call site that used it
The spec's B table grows its fifth row: bridge add_nio_tap mints a
transient TAP when the name is free and hardens it at creation, while an
attach to an existing device (possibly a user-owned TAP with addresses)
is left untouched. The rule paragraph spells out attach-is-not-a-creation.
Delivery: uBridge fb72758, closing the gap the new e2e assertions found
(live: the switch's gns3*-0 relay TAP carried fe80::). The server issues
no link l2only of its own -- the switch call site now documents that the
TAP is minted-and-hardened by add_nio_tap, and the ESW feature doc
describes the uBridge-side close instead of a server workaround.
2026-10-06 00:21:10 +08:00
YueGuobin 30cb7119e5 test(e2e): assert the L2-anchor spec's server-side guarantees
The spec's gns3-server alignment section promised three assertions the
suites never carried; they land in harness.py and run in every kernel
scenario (plus the relay controls' anchor checks):

- E.1 assert_pure_l2: anchors and bridges carry no L3 identity (addrgenmode
  none, no address in /proc/net/if_inet6, no ip -o -4 addr) -- the kernel
  scenarios' anchors and per-link/switch bridges, relay-mode anchors and
  the switch's relay TAPs alike (hardening is a creation-time property,
  not a datapath one);
- E.2 assert_idle_silence (Dynamips suite): guest interfaces shut to
  silence IOS's own CDP/keepalives, settle 2.5 s, then a 5 s window of
  zero traffic over both anchors and the per-link bridge;
- assert_forwarding: every attached port reports brport/state == 3 -- a
  bridge left DOWN keeps its ports disabled and forwards nothing, with no
  error anywhere; the assertion is the only signal.

harness.l2only_supported() probes a throwaway uBridge once (link l2only
against a nonexistent device: 208 = command present, 202-Unknown command
= old build); without the command the assertions skip -- the spec's
degradation contract, mirroring the tc-capability skip.

The first live run caught a fifth-creator gap: the switch's relay port
TAPs (minted implicitly by bridge add_nio_tap) carried a live fe80::.
Delivered uBridge-side per the spec (fb72758: the transient TAP is
hardened at creation, attaches untouched); the server needed no change,
and the relay-control E.1 check is that creator's end-to-end coverage.
2026-10-06 00:21:10 +08:00
YueGuobin 02340f2ed3 docs(iol): record the IOL runner container kernel datapath
The feature doc covers the architecture (one irreducible userspace hop
on the unix-socket leg; the link segment kernelized through the port
bridge's swappable TAP leg), the capability gate, the anchor lifecycle,
the swap flow, the inherited capture/markers/filters, the relay
fallback and the live verification — including the ensure-then-add
lesson (tap create is strictly create-only).

The other datapath docs' roadmaps catch up: the IOL runner container
has landed (and the ethernet-switch doc's stale 'cascade deferred'
exclusion from d2f8aba58 is corrected while there); the docker doc's
adapter table no longer rejects IOLDockerVM.
2026-10-06 00:21:09 +08:00
YueGuobin 72aa379e87 test(e2e): live IOL runner container kernel datapath suite
Two real iol-xe containers (Cisco CML iol-runner images, real IOS-XE on
the telnet console) against an isolated instance, the real uBridge with
the swappable bridge TAP leg:

* kernel link reports kernel_datapath; anchors exist from node start
  and the per-link bridge enslaves exactly the two of them;
* real ICMP crosses the [unix <-> tap] port-bridge relay; delay 100
  lands as netem on both anchors with the measured RTT growing >= 150 ms
  and returning < 50 ms when cleared;
* suspend admin-downs the anchor and kills the traffic; resume
  restores; AF_PACKET capture writes a real pcap;
* link delete/re-create swaps the port leg out and back in with the
  ping returning; node stop leaves no gx devices and a start recreates
  the whole wiring from the NIO; project delete cleans everything;
* the relay control on a relay-configured instance keeps the link off
  the kernel and still pings (anchors may exist idle — the same
  semantics as QEMU's and Dynamips' anchors: the server flag decides
  attachment, not anchor birth).

Harness: create_iol_router (the appliance's template properties),
docker_images, iol_anchor_name, stage_iol_base_config (the shipped
iol-xe-base.txt copied into the isolated instance's configs dir — the
GNS3_IOL_STARTUP_CONFIG lookup path), boot_wait(straight_prompt=True)
for images that boot from NVRAM straight into the CLI with no 'Press
RETURN' sentinel, and GNS3_E2E_DEBUG=1 to run the isolated instance
with debug logging (the uBridge command stream lands in server.log —
how the ensure-anchor EBUSY was pinned down).
2026-10-06 00:21:09 +08:00
YueGuobin 13c1ffb951 feat(controller): let IOL runner containers take the kernel datapath
_is_unix_socket_docker no longer excludes the IOL runner marker: those
containers anchor on persistent TAPs now (compute side), so they
graduate through _kernel_endpoint_ready's gate instead — both
ubridge_bridge_tap (the swappable leg) and ubridge_tap (the tap module)
strict True, an unreported capability keeping the link on the relay
where it always works. The generic GNS3_UNIX_SOCKET_NIO exclusion keeps
its shape (an IOL runner environment wins the compute's class
selection, so the exclusion must not fire when both markers are set).

The switch fast path names an IOL runner peer's anchor through
kernel_anchor_type — the iol_docker key, never the gv veth namespace.

The 307d676cb regression tests move with the semantics: the capability
matrix replaces the unconditional relay, and the switch-path test also
asserts the gx naming. Its original concern stands — a compute that
cannot serve the anchor lifecycle must never be handed a kernel link
(the switch's deferred join would make it a silent dead cable).
2026-10-06 00:21:09 +08:00
YueGuobin 4b4a0fc35f feat(iol): anchor IOL runner containers on persistent TAPs
IOL runner containers (IOLDockerVM, GNS3_IOL_RUNNER) had no kernel
datapath: their guest leg is the runner's AF_UNIX socket pairs, so every
link rode the uBridge relay. Their Ethernet bays now own persistent TAP
anchors (gx names, the iol_docker key of the shared naming contract —
born at node start like IOU's, before any link, so the switch fast
path's deferred join can never miss them), and the per-port bridge's
topology leg swaps between UDP (relay) and the anchor (kernel link)
through the frozen stop -> delete -> add -> start contract — the unix
binding never re-binds across a swap.

- iol_docker_vm: KernelDatapathMixin hooks, the anchor lifecycle
  (_prepare_tap_datapath at _start_ubridge: probe ubridge_bridge_tap +
  ubridge_tap, sweep leftover, tap create born down), the kernel attach
  (ensure-then-add — tap create is strictly create-only, IFF_TUN_EXCL,
  so the ensure checks /sys/class/net first: an unconditional create
  answers EBUSY on the device the start loop just made), the release
  (port bridge stop + delete_nio_tap before the shared teardown) and the
  stop order the fd holders dictate (port bridges first, then tap
  delete, then the per-link bridges — all before the hypervisor stops).
- vendor_docker_vm: the port-bridge creation factored into
  _ensure_unix_port_bridge (idempotent on the registered name), keeping
  the NIOBridge rejection for the generic unix-socket containers.
- docker_vm: the three _kernel_veths lookups go through the
  _kernel_host_ifc hook — behavior-identical for DockerVM, and it is
  what lets the subclass route without overriding the binding methods.
- kernel_anchor: the iol_docker key (gx) and kernel_anchor_type, the
  controller-side mapping for naming an IOL runner's anchor on the
  switch fast path (the marker check stays inline: this module sits
  below everything and must not import the controller package).
2026-10-06 00:21:09 +08:00
YueGuobin c20125c180 feat(compute): probe uBridge's swappable bridge TAP leg
The bridge module gained delete_nio_tap (uBridge's gns3server-integration
contract, section 'bridge — generic NIO relay with a swappable TAP leg'):
a per-port bridge can swap its topology leg between UDP and a persistent
TAP through stop -> delete -> add -> start, which is what lets an IOL
runner container's port bridge carry a kernel-link anchor.

The probe needs no scratch objects and no capabilities: one command
against a bridge that cannot exist — 202 (unknown command) is an old
build, 214 (bridge doesn't exist) is a new one. Cached by binary identity
like every other probe; any failure reports unknown.

GET /v3/compute/capabilities gains ubridge_bridge_tap; the controller's
default capability dict carries it too (the single schema definition, per
the 1e67fbf12 lesson).
2026-10-06 00:21:09 +08:00
YueGuobin d6851695cc test: give the argument-less pytest run the e2e-excluding configuration
CI runs the suite through `just test` -> `just unit`, i.e. `pytest` with
no path argument and the repository root as rootdir — which does not load
tests/pytest.ini, so its `addopts = -m "not e2e"` never applied there. The
e2e tests were collected and executed on every CI run and only stayed
green because a runner has no ~/GNS3/images directory: the harness skips
itself. A local run on a machine that does have images went ahead and
booted real servers for twelve minutes instead.

Declare the same policy in pyproject.toml, the file that argument-less
run does resolve, and add testpaths so the package-internal tests
(gns3server/agent/.../tests/) stay collected — `pytest tests` never
reached them either. That shape keeps resolving tests/pytest.ini and is
unchanged.
2026-10-06 00:21:09 +08:00
YueGuobin 90bcb32473 feat(esw): cascade two switches through a veth pair
Switch-to-switch links were the last shape left on the relay: the switch
fast path works by absorbing the *peer's* anchor, and a switch has none —
its ports are its own bridge, and a kernel interface belongs to exactly
one bridge, so two bridges cannot be joined by enslaving anything.

Join them with a veth pair instead: one end per bridge, each side
enslaving its own end and applying its own port mode to it — an access
port on one side and a trunk on the other behaves like the real cable it
models. uBridge's docker create_veth/delete_veth (the primitive every
Docker adapter is already born from) creates and destroys the pair; the
names derive from the link id (utils.kernel_anchor.kernel_cascade_names),
so each side computes its own end and the names survive a restart.

The pair belongs to the link, and the two ends are wired by two
independent uBridge processes — the project-open batch drives different
nodes concurrently — so the protocol is order-free: both sides create the
pair when their own end is missing (one create wins; the loser's failure
is re-checked against the kernel and "the pair is there" is not an
error), and either side's teardown destroys it (deleting one veth end
takes the other with it, so both converge on the same gone pair and the
second delif answers ENOENT). A pre-existing end — this switch restarted,
or a leftover from a previous life of the link id — is reused rather than
recreated, because the other end may still be a live port of the peer
switch; a stale tc qdisc is all a reused end can carry.

No new wire format was needed: a cascade is an anchor NIO on both ends,
the absorbed-anchor case plus the peer end's name. That also corrects the
filter routing — the single-sided rule exists because an absorbed anchor
is one interface, while a cascade has one per switch, so impairments go
to both ends like any other kernel link.

Tests: the wire format, the eligibility flip and the both-ends re-push on
node start (controller); the naming contract (utils); the switch-side
lifecycle — create, reuse, lost create race, delete destroys the pair
(compute routes).

Drive-by: the relay filter test's compute mock carried no awaitable
`put`, so tests/controller/test_kernel_datapath_link.py failed when run
alone while an argument-less full run passed; callers now get one.
2026-10-06 00:21:09 +08:00
YueGuobin caa054986f fix(controller): keep IOL runner containers off the kernel datapath
The unix-socket container gate matched GNS3_UNIX_SOCKET_NIO in the node
environment only, but the IOL runner reaches the same wiring through the
GNS3_IOL_RUNNER marker: the compute selects IOLDockerVM on it, and that
class forces the AF_UNIX socket pairs whatever the generic knob says —
and the documented environment for those nodes carries only the marker.
Such a container was therefore handed a kernel link its compute cannot
serve. The plain case failed at link creation (no veth end to enslave);
on the switch fast path it was worse — the switch defers a join against a
missing anchor by design (a link to a stopped node must not fail), so the
cable was silently dead instead of merely slow.

Match both markers, through the shared is_iol_runner_environment helper so
the controller and the compute select the same way. Verified live on a
real server: docker↔IOL-XE and switch↔IOL-XE links stay relay while the
docker↔switch control link still takes the kernel datapath.
2026-10-06 00:21:09 +08:00
YueGuobin a40503e44b fix(qemu): release the datapath under the execution lock
QEMU's process monitor calls stop() by itself when the process dies, so an
API stop and a process-death stop run concurrently in the normal case — and
the datapath release sat outside _execute_lock, letting both stops sweep the
adapter TAP map at the same time. Whichever finished first cleared
_kernel_taps under the other's iterator, which died with "dictionary changed
size during iteration" (the monitor's task, so it surfaced as "Task exception
was never retrieved") with the rest of its sweep, the orphan-bridge removal
and uBridge's shutdown skipped.

Keep the previous fix's ordering (process side first, then the devices) and
hold the lock across the release: serialized, the second stop finds uBridge
gone and sweeps nothing. Reproduced deterministically with two concurrent
stop() calls, the first parked mid-sweep — it raised at qemu_vm.py:1659
before the change, and every TAP is swept exactly once after it.
2026-10-06 00:21:09 +08:00
YueGuobin 0b78d313eb fix(qemu): release the datapath after the process is gone
QEMU is the guest side of every adapter TAP, and uBridge's tap delete
refuses a device another process holds open ('Device or resource busy') —
a best-effort delete whose failure is suppressed. QEMU's stop did the
delete first and stopped the process after, so every node stop or project
delete leaked the persistent TAPs: found by inspecting the host after a
project delete (16 taps left behind, carrier down, no holder), and the
held-tap behaviour reproduced against uBridge directly.

Stop the QEMU process first, then remove the TAPs and the per-link kernel
bridges — process side first, then the devices, the same lesson as IOU's
reverse stop order. Verified live: node stop and project delete now leave
no taps and no processes behind, while a restart recreates the TAPs.

The adapter anchor naming also goes through the shared
utils.kernel_anchor helper, like the other node types.
2026-10-06 00:21:09 +08:00
YueGuobin c343ce0b8f feat(esw): wire peer anchors straight into the switch bridge
The Ethernet switch's kernel fast path: instead of a link crossing the
switch's per-port uBridge relay, the switch absorbs the peer's anchor into
its own kernel bridge. The peer's interface (Docker veth host end, QEMU
TAP, IOU port TAP, Dynamips port TAP) becomes the switch port, and frames
cross anchor -> switch bridge -> switch ports entirely in the kernel.

Wire format: the switch end receives nio_anchor ('join this interface to
my own bridge' — the mirror of nio_bridge), the peer end nio_bridge with a
null bridge ('your anchor is bridged elsewhere': carrier, markers and
impairments only — never bridge membership, and never a bridge delete, on
an interface this node does not own). Anchor names come from the shared
naming contract (utils.kernel_anchor), a pure function of node type, id,
adapter and port — the controller computes the peer's anchor while the
node may be stopped, which is what makes links to stopped nodes wireable.

Stopped peers defer the join; after any node of a link starts
(UDPLink.node_started) the controller re-pushes the switch NIO, and the
switch completes — or repairs, when a peer restart replaced its interface
under the same name — the join against the kernel's actual membership
instead of assuming it.

VLAN changes now edit membership in place: only the ports whose mode/VLAN
actually changed are touched, each losing exactly the previous mode's
entries the new mode does not want (the dot1q admits-all entry is one
range operation in both directions), and no port ever leaves the bridge to
change its VLANs. This replaces the old 'reset by re-enslaving' shortcut
(delif+addif on every wired port, added when the ports were the switch's
own TAPs): on absorbed anchors, re-enslaving an interface owned by another
node is where live testing watched links die — anchors occasionally lost
their bridge membership right after a ports_mapping update (later updates
then failed with delif EINVAL), reproducibly with qemu, IOU and Dynamips
peers and never with Docker's veths.

Eligibility: the switch side needs no capability of its own (its bridge
exists by construction); the peer must be able to anchor. Switch-to-switch
cascades stay on the relay — a kernel interface belongs to one bridge, and
joining two bridges needs a veth pair, deferred.

Verified live on a real server: qemu peers through four VLAN cycles with
both anchors enslaved throughout; a mixed switch (2 IOU + 2 Dynamips, four
kernel ports); Docker peers with real ICMP isolating and recovering (with
both anchors still enslaved); VPCS relay ports likewise in place.
2026-10-06 00:21:09 +08:00
YueGuobin 3910a6b585 docs(dynamips): record the kernel datapath and its live verification
New features/dynamips-kernel-datapath.md: the anchor model (persistent TAP
per Ethernet port, the hypervisor opens it with nio create_tap), port
selection via the adapter registry, the anchor lifecycle with QEMU's stop
order and the stop-is-not-close semantics, link operations, capture/
markers/filters, the relay fallback, the live e2e results, configuration
and the roadmap (Ethernet switch next). The IOU and QEMU roadmaps note
that Dynamips has landed.
2026-10-06 00:21:09 +08:00
YueGuobin 5c2c8cdb0c test(e2e): a live end-to-end suite, Dynamips as the first scenario
Live e2e verification moves into the repository instead of being rewritten
as a throwaway script every time: tests/e2e/ carries a shared harness (REST
client, isolated-instance lifecycle, a deliberately dumb IOS console
driver, host-side kernel inspection: bridge membership, tap admin state,
tc qdiscs) and each node type adds only its scenario module. The e2e marker
plus 'addopts = -m "not e2e"' keeps these privileged, image-dependent
tests out of normal runs; they are opt-in: pytest -m e2e tests/e2e -s.

The harness targets an existing server via GNS3_E2E_URL or starts an
isolated instance (own config dir — DB and paths follow it — on a free
port) and deletes its project afterwards (GNS3_E2E_KEEP=1 keeps it on
failure).

The first scenario drives two real c7200 routers on a real IOS image
through the REST API and the consoles: the kernel link is created while the
routers are stopped (deferred wiring), the per-link kernel bridge enslaves
exactly the two anchors, real ICMP crosses it, delay 100 shows netem on
both anchors and grows the RTT (~200 ms), suspend kills the traffic on an
admin-down anchor, capture writes a pcap of ICMP records, a serial link
between the same routers stays on the relay and still pings, delete/
re-create and stop/start leave the wiring consistent, and deleting the
project removes every anchor and bridge. A negative control runs the same
topology on an isolated relay-configured instance (no per-link bridge,
nothing enslaved, still pings).
2026-10-06 00:21:09 +08:00
YueGuobin e5f65a510a feat(controller): offer Dynamips the kernel datapath
A Dynamips Ethernet port can anchor a kernel link whenever its compute's
uBridge has the tap module — the anchors are uBridge-created TAPs the
hypervisor merely opens, the same capability QEMU gates on, so no
Dynamips-specific capability is needed. Serial, ATM and POS ports are
excluded per port by the existing link-type check (the controller's port
matrix decides), keeping them on the relay whatever the capabilities.

Eligibility tests cover the mixed pairs (docker/qemu/iou endpoints on the
same compute), the strict tap-capability requirement, and the serial
exclusion.
2026-10-06 00:21:09 +08:00
YueGuobin 7201a870da feat(dynamips): anchor every Ethernet port on a persistent TAP
Dynamips links can now ride the kernel datapath like Docker, QEMU and IOU:
each Ethernet slot/port gets a persistent TAP anchor (gd{id}e{slot}p{port}),
created through uBridge's tap module, and the Dynamips hypervisor opens it
with nio create_tap — the hypervisor holds the fd, exactly QEMU's shape.
Links attach the anchor to their per-link kernel bridge; the legacy UDP
tunnel remains the relay datapath for every other port.

Anchor lifecycle: born at node start (tap module probed with one
create/delete cycle, sweep of stale devices, ownership handed to the server
user, born down); a kernel link opens the anchor in the hypervisor, binds
the slot/port and enslaves it; removing the link releases the fd again
(nio delete) and detaches. A link bound while the router is stopped is
wired by the next start (deferred wiring). Node close follows QEMU's stop
order — the hypervisor's TAP NIOs go before tap delete, since it is
Dynamips, not uBridge, that holds the fds.

Stop is not close: vm stop only halts the emulated router, so the
hypervisor, the TAP fds, the bindings and the per-link bridges all survive
a stop/start untouched (attach skips ports that still hold their TAP NIO).

Port selection follows the adapter registry: ETHERNET_ADAPTERS and
ETHERNET_WICS name the models whose ports carry Ethernet frames (WIC-1ENET
included, at its Dynamips port number); serial, ATM and POS ports never
anchor, and a kernel link there errors with the relay-datapath message
instead of half-wiring. Adapters hot-added to a running router (OIR) get
their anchors at once.

The compute NIO routes accept nio_bridge alongside nio_udp (the same
widening QEMU needed), carry the endpoint's suspend flag on update (it is
the anchor's admin state on a kernel link), skip the hypervisor delete for
a kernel NIO (its TAP NIO was already released by the slot removal), and
the close path leaves NIOBridge instances to _stop_ubridge.
2026-10-06 00:21:09 +08:00
YueGuobin 6633304e97 fix(mcp): let link_list return kernel_datapath
The tool descriptions have always advertised kernel_datapath as a
requestable field, but the handler's whitelist did not contain it: asking
for it was rejected as an invalid field, so the MCP clients could not see
which links run on kernel interfaces at all.

Also record what seeding a netem experiment on IOU costs: IOL emits its own
CDP/keepalive frames and they draw from the netem RNG stream, so a
seeded run only reproduces after `no cdp run` (verified bit-identical pcaps).
2026-10-06 00:21:09 +08:00
YueGuobin 4fa7f158fd fix(schemas): one definition of the capabilities payload
GET /computes/{id} answered with only part of the capabilities the compute
reports: the response schema kept a second, private Capabilities class of
its own (it knew ubridge_tc and nothing else), and FastAPI's response model
silently drops fields it does not define — so ubridge_tap and
ubridge_iol_tap never reached clients even though the compute had sent
them and links were already being built on those datapaths.

Import the one definition instead of duplicating it, so the next capability
cannot drift the same way.
2026-10-06 00:21:09 +08:00
YueGuobin 3b8172cbc8 docs(iou): record the IOU kernel datapath and its spec
* docs/features/iou-kernel-datapath.md: architecture (one irreducible
  userspace hop on the fabric leg, kernel link segment), datapath
  selection, the anchor lifecycle with the reverse-of-QEMU stop order,
  capture/markers/filters, relay fallback, and the verified numbers (an
  isolated server with two IOU nodes behind a fake ELF image, the test
  playing the IOL fabric: 64/64 kernel, 62/62 relay).
* docs/design/ubridge-iol-tap-anchor-spec.md: delivered — implemented on
  the ubridge fork's feature/iol-tap-anchor branch (both commands, the
  listener hardening, plus releasing every port NIO on iol_bridge delete
  even when the bridge was not running), with the implementation notes
  that came back (208 vs the older 214 for a missing bridge; one perror
  line per frame dropped on a down anchor).
* The Docker/QEMU feature docs point at it from their roadmaps.
2026-10-06 00:21:09 +08:00
YueGuobin f23c3bb6e6 fix(iou): carry suspend from the NIO update body
The IOU NIO update route never copied the body's suspend flag onto the
NIO; the Docker and QEMU routes always did. Harmless on the relay, where
suspend is emulated by the synthetic frequency_drop filter the controller
injects, but fatal on a kernel link, whose suspend *is* the anchor's
admin state: a suspended link kept forwarding traffic, and the resume
looked like it worked because nothing had ever stopped.
2026-10-06 00:21:09 +08:00
YueGuobin 806afec0d8 feat(controller): offer IOU the kernel datapath
Eligibility gains an IOU branch gated on the compute's ubridge_iol_tap
(strict True: an unreported capability keeps the link on the relay), and
a port-level rule: a kernel link is an Ethernet segment, so any endpoint
whose port is not Ethernet (IOU serial) disqualifies the link before it
is dispatched. Without that, a serial link between two capable IOU nodes
would be sent as nio_bridge and fail at the compute.

The IOU NIO routes accept nio_bridge alongside the UDP/TAP/Ethernet NIOs
— without the widening the controller's POST is 422'd before the node
ever sees it, the same trap the QEMU routes hit.
2026-10-06 00:21:09 +08:00
YueGuobin 200c946eef feat(ubridge): probe iol_bridge's TAP-port support
Whether an IOU port can terminate on a persistent TAP (iol_bridge
add_nio_tap) is a capability of its own: the tap module and that command
land independently, so a build may have one without the other. Probed on
a scratch IOL bridge with a scratch TAP — one add/delete cycle, no
iol_bridge start needed (attaching a NIO works on a stopped bridge) —
cached by binary identity, with the scratch bridge id above the per-node
id space the fabric locks (513..1024) so a probe cannot collide with a
running node. Any failure, including an old build's "Unknown command",
means unknown: IOU stays on the relay datapath.

Reported through /capabilities as ubridge_iol_tap, next to ubridge_tap.
2026-10-06 00:21:09 +08:00
YueGuobin 9a14a91293 feat(iou): anchor every Ethernet bay/unit on a persistent TAP
IOU's only wire is the IOL fabric (Unix datagrams, 8-byte headers,
NETMAP), so it has no host netdev to enslave — the kernel datapath gives
each Ethernet bay/unit a persistent TAP anchor the uBridge IOL bridge
binds the port to (iol_bridge add_nio_tap), which links then enslave into
their per-link kernel bridge exactly like Docker's veth and QEMU's TAP.

* IOUVM joins KernelDatapathMixin: one TAP per Ethernet bay/unit
  (gi{id8}e{bay}p{unit}), created at start after a capability probe and a
  stale sweep, born down and address-free; serial bays never anchor.
* _networking dispatches per NIO type: a relay link keeps iol_bridge
  add_nio_udp, a kernel link binds the anchor then runs _kernel_attach.
* Stop order is QEMU's reverse, because uBridge holds the anchor fds:
  iol_bridge delete (releases every port NIO) -> tap delete (a held TAP
  answers EBADFD) -> brctl delete -> hypervisor stop. Removing a single
  link releases its fd the same way (delete_nio_tap).
* The IOU-specific marker reconcile override is gone: marker primitives
  are polymorphic on the anchor (marker *_kernel on a TAP, iol_bridge
  commands on an IOL location), so the base reconcile serves both.

Capture on a kernel link anchors on the TAP (capture start_kernel);
filters are tc on the anchor, never combined with the userspace
iol_bridge filters a relay link uses.
2026-10-06 00:21:09 +08:00
YueGuobin 81ad9b837f docs(spec): record the delivered L2-only anchors and their residual
uBridge delivered `link l2only` (e2e3155) and the brctl delete refusal
(83a84fb); verified from the server side -- anchors and per-link bridges
report addrgenmode none, carry no addresses, and an idle anchor is silent
once the one-shot membership burst has settled.

That burst is the one thing the command cannot remove, so it is now recorded
where the acceptance criteria live, with the measurement: enslaving a port
makes the kernel announce the bridge's multicast memberships (90 B MLDv2 at
+0.00 s, 54 B IGMPv3 at +0.09 s, 90 B MLDv2 at +0.73 s, then silence; no
addresses involved, and IPv4 has no per-device IGMP switch). Decision:
accepted and documented, not suppressed -- §E.2 measures idle silence after a
settle window instead.

Pins the other delivered behaviour with a test: a bridge now survives a
single-sided node stop, so brctl create answers EEXIST on the common path
rather than only in a create race -- the attach must not short-circuit there,
because the restarted side has a brand-new anchor whose filters and markers
still have to be re-applied.
2026-10-06 00:21:08 +08:00
YueGuobin a1fcd29bce fix(qemu): build a command line for a headless node
_console_options() fell through the "none" branch and returned None, so
_build_command() blew up on `command.extend(None)`: a QEMU node with
console_type "none" -- offered by the GUI, and what API/MCP-driven labs use
to skip the console entirely -- failed to start with a 500 and a traceback.

Return an empty list, exactly like _aux_options() already does, and cover it
with a test that builds the command line for a headless node. Verified on a
live instance: such a node now starts (204) with `console: null` and no
-serial device in the QEMU command line.
2026-10-06 00:21:08 +08:00
YueGuobin 187201a08c feat(controller): offer QEMU the kernel datapath, gated per compute
Kernel eligibility becomes "both endpoints on one compute, each able to
anchor": Docker always (adapters are born as veth pairs), QEMU when that
compute's uBridge can create the persistent TAPs its adapters anchor on. The
question is asked per compute, because the link needs both ends anchored --
so a mixed or half-upgraded deployment degrades to the relay instead of
failing an attach.

probe_tap_support() creates and deletes one throwaway persistent TAP through a
scratch uBridge, cached by binary identity like the tc report; /capabilities
exposes `ubridge_tap` (absent = unknown, which keeps links on the relay).

The compute route for a QEMU adapter NIO took UDPNIO only, so a kernel link
was rejected with 422: its body and response now accept
Union[UDPNIO, BridgeNIO] exactly like Docker's.

Stale "Docker-to-Docker" wording in the config, link and MCP descriptions now
talks about anchors, and docs/features/qemu-kernel-datapath.md documents the
datapath -- verified end-to-end on a real instance: 32/32 kernel-datapath
checks and 29/29 on the relay variant.
2026-10-06 00:21:08 +08:00
YueGuobin 7d2d8c6747 feat(qemu): anchor QEMU adapters on a persistent TAP
QEMU had no host-side interface at all: every adapter was a local UDP tunnel
into uBridge (-netdev socket plus two UDP ports per adapter), so a link could
only ever be a userspace relay. Each adapter now owns a persistent TAP
(gq{node_id[:8]}e{adapter}p{port}), created by uBridge before QEMU is launched
and handed to this user, and the netdev is that TAP -- the anchor role Docker's
veth host end plays. Links attach to it:

* kernel link (NIOBridge): brctl create/up/addif enslaves the TAP into the
  per-link bridge and capture, markers and tc filters are installed on it,
  verbatim through the shared KernelDatapathMixin -- a TAP and a veth host end
  are interchangeable there (an egress qdisc on either impairs traffic entering
  the node, and PACKET_OUTGOING on either is the node receiving);
* relay link: bridge add_nio_ethernet plus add_nio_udp -- AF_PACKET, never the
  TAP NIO, which would take the fd QEMU itself holds.

The netdev type is fixed at launch, so this is all-or-nothing per VM: on the
TAP datapath every link type attaches to (or detaches from) a running VM,
including switching a link between the two datapaths. Stop un-persists the
TAPs (QEMU's open fd keeps each device alive until it exits) and removes the
per-link bridges; start sweeps leftovers first. A uBridge without the tap
module keeps the previous socket-netdev datapath, so an unupgraded install is
unaffected -- such a node simply cannot carry kernel links.
2026-10-06 00:21:08 +08:00
YueGuobin 12d8abce45 refactor(compute): share the kernel-datapath machinery across node types
Move the datapath-agnostic half of DockerKernelDatapathMixin into a new
KernelDatapathMixin (compute/kernel_datapath.py) so a second node type can
reuse it verbatim: the three marker primitives, the tc netem / cls_bpf / eBPF
appliers, the uBridge tc-capability probe, kernel marker teardown, link
detach, the per-link bridge cleanup and the adapter carrier -- plus
_kernel_attach(), lifted from DockerVM._connect_nio's kernel branch.

The mixin talks about "the anchor" (the host-side interface an adapter owns in
the root namespace) instead of "the veth host end": a node type provides
_kernel_host_ifc(), _kernel_anchors() and, when needed, _relay_carrier_bridge()
and _kernel_error(). Docker keeps only the veth lifecycle and those hooks;
behaviour is unchanged.

The C901 baseline entry moves with _netem_command_parts (the docker module is
no longer over the limit) and the bpf-compile-failure test patches the logger
of the module that now owns the code -- net zero new ignores.
2026-10-06 00:21:08 +08:00
YueGuobin 0b507773b9 docs(spec): require L2-only host anchors in uBridge
Every host-side device uBridge creates for the data plane (persistent TAP
anchors, veth host ends, per-link kernel bridges) must be pure L2: no IPv4
address, no IPv6 address and no IPv6 stack activity on that device.

Measured today: an idle TAP emits ~6 frames / 2 s of the host's own MLD/DAD
from its own link-local, the production Docker veth host end carries
fe80::5c30:e8ff:fe00:5d8d/64 and the per-link bridge fe80::f0d9:94ff:feac:e42b/64.
On a kernel link the bridge floods those frames into the emulated segment, on a
relay link uBridge relays them to the peer, and the host answers neighbor
solicitations for its own address (a phantom IPv6 neighbour for the emulated
nodes). IPv4 needs no equivalent knob: nothing self-provisions it, and the
anchors hold no IPv4 address.

The spec adds one command (link l2only <iface> [on|off], netlink addr-gen-mode
none -- never a /proc sysctl write, which fails the DAC check for a non-root
setcap'd uBridge), applied by the four creators themselves, with an
idle-silence acceptance test and a known-noise note in the Docker kernel
datapath document. No change to existing command grammar.
2026-10-06 00:21:08 +08:00
YueGuobin c1d0e6ee21 docs(spec): define the gemodel acceptance target
The F section asked for "gemodel loss within +/-5% of target" without
saying what the target is, and the A.1 table gave ranges only. Spell out
the semantics the kernel implements (and that the veth calibration
confirmed): p is the good-to-bad transition, r the bad-to-good
transition, 1-h the loss chance inside the bad state (the good state
loses nothing), mean loss p/(p+r)*(1-h) per direction. The functional
bullet now names that target and how to measure it (per-direction
counters, round-trip reads 1-(1-L)^2, pre-warm ARP when 1-h=100).

No wire-format or grammar change.
2026-10-06 00:21:08 +08:00
YueGuobin 1db9f171ca fix(controller): re-arm window_drop and expose kernel_datapath
Three fixes from live-calibrating the kernel impairment filters on an
isolated instance (Docker-to-Docker veth link, per-sequence evidence):

- update_filters skipped an unchanged filters dict as a no-op, so a
  one-shot window_drop outage that had already passed could never be
  re-armed: re-applying the same values produced no datapath command at
  all. A PUT still carrying window_drop now reconciles, restarting the
  schedule from the apply as documented. Measured: identical re-apply
  moves the outage window from seq 50-70 to 70-91 (arm at +8s of the
  new apply).

- gemodel parameter semantics were documented backwards in the
  validation rules, available_filters, the MCP/copilot descriptions and
  the feature docs. Measured against the kernel (per-direction counters,
  offered = sent + dropped): p is the good-to-bad transition chance, r
  the bad-to-good transition, 1-h the loss chance in the bad state (the
  good state loses nothing) - mean one-way loss p/(p+r)*(1-h), e.g.
  [10,30,100] -> 24.8%/25.7% measured vs 25% predicted, [5,45,100] ->
  10.8% both ways vs 10%.

- kernel_datapath was silently stripped from every REST/MCP link payload
  by the response model (LinkBase carried no such field), so clients
  could not tell a kernel link from a relay one.

Also verified on the same setup: the 3-argument window_drop form works
exactly as specified ([3000,5000,100] -> a single seq 31-55 outage,
[20000,6000,100] -> seq 115-144), and both generations of the command
builder emit the parameters unpadded.

Adds an API test for the field and controller tests for the no-op skip
and the window_drop re-arm exemption.
2026-10-06 00:21:08 +08:00
YueGuobin 5ac1521217 feat(mcp): accept project/node names as tool locators
LLM agents transcribe UUIDs unreliably — a 2-character slip invents an
id that never existed and is invisible to the eye. Tool parameters now
accept names wherever the server guarantees uniqueness: project names
among live projects, node names within a project. Links, drawings,
appliances and snapshots have no names and stay UUID-only.

Resolution sits in the single dispatch choke point (_run_handler_sync):
UUID-shaped values pass through untouched, names resolve with one list
call, and an unknown name fails fast listing the known names instead of
a confusing downstream 404. As a backstop for residual UUID typos,
error replies carrying "<UUID> doesn't exist" are matched against the
in-scope ids; a single candidate within edit distance 2 earns a
"Did you mean ...?" hint.
2026-10-06 00:21:08 +08:00
YueGuobin 935c00802f docs(mcp): refresh filter vocabulary in the MCP/copilot tool descriptions
link_update, link_available_filters and the copilot packet-filter tool
still advertised the pre-kernel-datapath five types. List the full
thirteen with positional parameter formats, ranges and kernel-only
marking, point at link_available_filters as the per-link authority
(topology + compute capability gated), and document window_drop's
apply-relative schedule restart. Also add kernel_datapath to the link
field lists.

Description-only: handlers pass filters through unchanged.
2026-10-06 00:21:08 +08:00
YueGuobin cecaf298bb feat(controller): expose kernel_datapath on the link payload
Runtime fact recomputed from the NIO wiring on every load (not
persisted). Without it clients cannot tell a relay link from a kernel
link whose compute lacks a filter capability — both show up as
kernel-only types missing from available_filters.
2026-10-06 00:21:08 +08:00
YueGuobin b4e4739d52 feat(compute): report uBridge tc capabilities and gate filters on them
Consume uBridge's ebpf_modes contract (feature/tc-window 40c36ae): a
stateful mode is usable iff ebpf=1 and its token is listed; builds
predating the field keep their shipped modes (nth/quota/flow), so the
pre-correction window semantics can never be installed silently.

- gns3server/utils/tc_capabilities.py: shared reply parser, mode
  policy and filter-type mappings (compute and controller gate on the
  same rules)
- gns3server/compute/ubridge/tc_probe.py: standalone probe spawning a
  throwaway uBridge as the server's own user, cached by binary
  identity (path/mtime/size - the version string cannot distinguish
  rebuilds); failures cache as unknown
- GET /v3/compute/capabilities gains ubridge_tc {netem, ebpf,
  ebpf_modes, cbpf}; the controller forwards it (Compute.capabilities)
  and available_filters hides kernel-datapath filter types an endpoint
  compute cannot run (both ends apply their own filters, so one
  incapable compute hides the type); computes without a report keep
  the full list and apply-time 409 stays the guard
- docker: _ubridge_apply_ebpf_drops gates per mode token; the cleanup
  path only sends "off" for modes the build declares
- split DockerVM's kernel-datapath machinery (veth lifecycle, carrier,
  marker primitives, tc filter translation, kernel NIO teardown) into
  compute/docker/docker_kernel_datapath.py (DockerKernelDatapathMixin)
2026-10-06 00:21:08 +08:00
YueGuobin 48dbdbe4a9 fix(docker): delete the per-link kernel bridge when a node stops
The bridge teardown only hung off the link-removal path, but deleting a
node or closing a project never issues a per-link delete — the veths
disappeared with their containers and left the bridge behind as an empty
orphan (reproduced: create a kernel link, DELETE the project, the
gns3{link_id} bridge survives). `_remove_kernel_veths` now deletes the
node's kernel-NIO bridges alongside the veth host ends: both endpoints do
it, the peer's still-enslaved port answers EBUSY (suppressed, last one
wins) exactly like link deletion, a relay NIO's uBridge bridge is left
alone (it dies with the process), and a node restart rebuilds the bridge
from the NIO in _connect_nio.

Found while cleaning up the window_drop e2e: seven such bridges had
accumulated on this host. Re-verified live: the bridge is gone after the
project delete, and the window_drop e2e (which includes a node restart
with the kernel link attached) still passes 15/15.
2026-10-06 00:21:08 +08:00
YueGuobin 316e7002c1 feat(docker): expose the eBPF time-window filter on kernel links
uBridge's window mode gained the semantics the B.2 spec asked for —
`tc window_drop <if> <start> <outage> <pct> [<period> [<jitter>]]`: a
single outage that traffic passes before *and* after, recurring flaps
with period >= outage, and a per-cycle jitter — so the kernel-only
`window_drop` filter type is now exposed:

- validation mirrors the tc grammar (3-5 params, ranges, period >=
  outage, jitter cap) and adds window_drop to KERNEL_ONLY_FILTERS;
  filter_inactive_filters keeps start=0 — unlike every other filter a
  zero first parameter means "the outage starts now", not "disabled".
- `_ubridge_apply_ebpf_drops` sends `tc window_drop` (positional
  pass-through) and turns the mode off explicitly when absent, under the
  same ebpf=1 gate.
- FILTERS entry (Start/Outage/Chance/Period/Jitter) + available_filters.

The schedule is relative to the apply: reconcile re-sets the classifier
on every apply, so any filter change, node restart or link reset restarts
the window.

Verified on a two-container kernel link, 15/15: a single outage
[1000, 1500, 100] arrives per-seq as [0..4, 13..19] (passing before the
window, dropped inside, passing after); recurring 1000/2000 ms = 52 %
round trip (duty cycle); period == outage = permanent outage; period <
outage = 409 before uBridge; jittered flap keeps the ~50 % duty cycle;
30 % chance on a permanent window = 53 % round trip against the
per-direction theory 1-0.7^2 = 51 %; coexist with netem; node restart
restores; available_filters kernel vs relay (409 + hidden); teardown
clean. P6b re-run as a regression on the same uBridge build: 13/13.

Worth recording for the next rebuild: the first delivered window program
loaded as root but reported ebpf=0 through gns3-server — the verifier's
non-root path loses the loop counter's bound, treats the catch-up loop as
unbounded and rejects the *whole* program (E2BIG, 8193 pending states),
which also took frequency_drop and quota down, with ebpf=0 as the only
symptom. Smaller trip caps did not help; the loop had to go (uBridge
572ca0c), on top of a Makefile header-dependency fix (53e34bb) that had
been shipping a stale program object.
2026-10-06 00:21:08 +08:00
YueGuobin 0c4ec8c38c feat(docker): eBPF stateful packet filters on kernel links
Consume the eBPF impairment classifier delivered in uBridge
feature/tc-precision: frequency_drop becomes the exact every-Nth mode
(tc nth_drop; -1 = drop everything maps to every 1st) and the new
kernel-only quota type is the byte-cap mode (tc quota_drop, 100 = hard
cutoff). KERNEL_UNSUPPORTED_FILTERS is gone entirely — kernel/relay
eligibility is now purely topological. Both modes gate on ebpf=1 from
the per-process tc capabilities probe (error names the setcap fix); the
cleanup path (modes off) only talks to the eBPF commands when the probe
reported them. Reconcile is a plain re-set: the netem reset-before-set
already detaches the program and clears uBridge's per-interface
registry, so a mode set after it is a fresh load+attach.

Documented semantic difference: the relay counts both directions
through one bridge counter, the kernel counts per direction — N=3
round-trip loss is 1-(2/3)^2 = 55.6% on kernel vs ~1/N on relay
(measured 57%). window_drop is NOT exposed: the delivered
implementation advances the window with no gap, making 'outside the
window packets pass' unreachable (needs outage/period fields —
recorded in the spec); flow_drop awaits a parameter-shape decision.

Also fixes a pre-existing restart bug the e2e exposed: _bridges (relay
bridge names) was never cleared on stop, so restarting a node with a
relay link skipped 'bridge create' and failed on add_nio_udp.

e2e (isolated instance): 13/13 — pref-1 tc_impair classifier on both
veths, 57% round-trip for N=3, -1 = exact 100%, quota hard cutoff,
delay coexistence, clean teardown, suspend/resume, node restart,
relay-leg frequency_drop regression through an Ethernet switch. Full
suite: 1925 passed.
2026-10-06 00:21:08 +08:00
YueGuobin d4b57d49fb feat(docker): expose netem-extension packet filters on kernel links
Surface the netem extensions delivered in uBridge feature/tc-netem-ext
as GNS3 filter types: rate (tc-style bandwidth string), reorder (needs
delay), gemodel (Gilbert-Elliot bursty loss, exclusive with
packet_loss), duplicate, seed and limit, plus the delay jitter
distribution and the loss/dup correlation parameters. All are
kernel-datapath only — the relay's packet-filter registry has no
equivalent, so available_filters hides them on relay links, setting one
on a created relay link returns 409, and the project-load path drops
them with a warning (update_filters runs before the datapath is
decided, so it cannot reject there). Validation mirrors the tc grammar:
reorder requires delay, gemodel and packet_loss are mutually exclusive,
a distribution requires jitter > 0, rate is integer+unit capped at
100gbit.

The translation in DockerVM._netem_command_parts emits the frozen
grammar order and gates extension keywords on the 'tc capabilities'
netem token list (probed once per uBridge process; a plain
delay/loss/corrupt/dup filter never probes, keeping old uBridge builds
untouched; the correl suffix has no token and gates on 'rate' as the
extension-build marker).

Reconcile became reset-before-set: the kernel's netem change merges
optional attributes (rate, correlation, reorder, corrupt, gemodel,
distribution, seed keep their previous value when the new message omits
them), so removing a parameter needs an explicit 'tc reset' — the
bpf_drop filters are re-added right after in the same flow, so the
clsact churn is invisible. The capability check runs before the reset
so a failed update leaves the previous qdisc in place.

e2e (isolated instance, kernel link): 24/24 — rate 512kbit adds exactly
2x the per-packet serialization to the RTT (45.5 ms for 1400-byte
pings), paretonormal jitter + rate-cleared leak check, reorder gap 5,
gemodel 50% bursty loss, duplicate, loss 30% correl 50%, seed 42 +
limit 5000 visible in the qdisc dump, suspend/resume and node restart
keep the filters, relay link rejects rate with 409, teardown leaves no
netem. Full unit suite: 1916 passed.
2026-10-06 00:21:08 +08:00
YueGuobin b1eb0984bc fix(docker): bring the veth host end up before a relay attach
The unified veth host end is born admin-down (carrier off until a link
attaches), and libpcap cannot open a packet socket on an admin-down
interface — its netlink promiscuous-mode transaction returns ENOENT, so
'bridge add_nio_ethernet' failed on every runtime relay link (and would
on any relay link at container start). Bring the interface up for the
attach; the carrier pass in the caller refines the state afterwards (a
suspended NIO sets it back down). Verified live with a direct uBridge
probe: attach on a down veth -> ENOENT, after 'link set up' -> OK.
2026-10-06 00:21:08 +08:00
YueGuobin 2b45f29b2c feat(docker): bpf packet filter on kernel links via cls_bpf match-drop
The GNS3 bpf filter (one expression per line, any line matching drops the
packet) now runs on the kernel datapath: uBridge's tc bpf_drop compiles
each line with libpcap (same compiler as the relay filter) into classic
BPF, attaches it to the veth host end's clsact egress as a cls_bpf
classifier with a gact TC_ACT_SHOT action, and the kernel migrates the
cBPF to eBPF internally -- no CAP_BPF needed.

- reconcile is flush + one add per line at priorities 10, 11, ... (OR
  semantics, same as the relay's per-line filters); tc reset (link
  delete / clear) is the full restore in uBridge and clears them
- capability-gated: the compute probes "tc capabilities" once per uBridge
  process (cached, invalidated on stop); without cbpf=1 the filter apply
  fails with an actionable upgrade error, and old uBridge builds without
  the tc module are never touched when no bpf filter is present
- a line that compiled for the controller's tcpdump but not for the
  compute's uBridge libpcap is skipped with a warning, mirroring the
  relay path
- KERNEL_UNSUPPORTED_FILTERS shrinks to frequency_drop (its eBPF stateful
  classifier is still pending, spec part B)

e2e (22/22): bpf "icmp" = 100% loss; size-discriminating expression
("greater 150") passes 98-byte and drops 300-byte pings (real byte-level
match); two-line OR; coexistence with netem (delay 50 -> small pings
100.2 ms while big dropped); clear removes clsact; suspend/resume keeps
the drops; link delete + recreate leaves no residual filters.
2026-10-06 00:21:08 +08:00
YueGuobin bd1c205651 docs: frozen uBridge spec for kernel impairment (netem extensions, eBPF/cBPF classifiers) 2026-10-06 00:21:08 +08:00
YueGuobin 0a8d430d50 feat(docker): packet filters on kernel-datapath links via tc netem
Impairment filters with a netem equivalent (delay, packet_loss, corrupt)
now run on the kernel datapath as one tc netem qdisc per veth host end,
pushed through uBridge's netlink tc module (tc netem set / tc reset).
This removes the relay delay filter's nanosleep bottleneck (upstream

Both link endpoints carry the filters: each end's qdisc egress covers
the traffic entering that container, so every direction is impaired
exactly once -- the same net effect as the relay, where both directions
cross the single filtered bridge.

- controller: eligibility keys on relay-only types (frequency_drop, bpf)
  instead of any filter; kernel links push the real filters (the
  synthetic suspend frequency_drop no longer flips a suspended link to
  relay on reopen/reset); update_filters 409s only relay-only types;
  available_filters hides them on kernel links
- compute: create_nio whitelists netem-capable filter types; the NIO
  update path keeps its own guard (PUT mutates the NIO in place);
  _ubridge_apply_netem translates the filter dict into one atomic
  netem-set (full re-apply IS the reconcile); node restart restores the
  qdisc, link deletion detaches it (the veth survives the link)
- e2e (27/27): delay 100 -> 200.2 ms RTT, atomic replace 50 -> 100.2 ms,
  clear -> baseline, packet_loss 30 -> 48 % round-trip (expected 51 %),
  suspend/resume and node restart keep the qdisc, link delete leaves no
  residual impairment
2026-10-06 00:21:08 +08:00
YueGuobin 94b5495683 docs: Docker kernel datapath implementation document
Cover the four-stage stack (kernel datapath, AF_PACKET capture, markers,
veth-everywhere): adapter interface types per node class, datapath
selection, veth lifecycle, link operations, suspend/capture/markers
semantics, uBridge command surface and the tc netem filters roadmap.
Cross-link from the traffic-insight marker doc for the kernel variant.
2026-10-06 00:21:08 +08:00
YueGuobin 672efda592 feat(docker): unify adapter interfaces on veth, allow kernel links at runtime
Every Docker adapter is now born as a veth pair at container start
(unified interface) regardless of NIO type: guest end in the container
namespace, host end in the root namespace. Kernel links enslave the host
end into the per-link Linux bridge; relay links attach it to the uBridge
relay via AF_PACKET (bridge add_nio_ethernet) — the TAP path is gone.

This makes the datapath a runtime decision:
- links can be created on running containers (kernel or relay) without
  touching container interfaces — the controller stopped-node
  eligibility check is removed
- project reopen re-prepares relay links and upgrades eligible ones to
  the kernel datapath
- packet capture start/stop now key on the NIO type (not veth presence)
  so relay-over-veth captures use the relay capture, kernel ones the
  AF_PACKET module
- vendor unix-socket containers keep their wiring: no veth is required
  on the relay path
2026-10-06 00:21:08 +08:00
YueGuobin 61020d3bbc feat(docker): traffic-insight markers on kernel-datapath links via AF_PACKET
Markers no longer disqualify the kernel datapath. They ride the NIO like
on the relay path and attach to the veth host end through uBridge's
marker add_kernel/delete_kernel/enable_kernel commands (AF_PACKET taps,
same BPF/direction/signal semantics as the relay mark filter).

- base_node: marker anchors are now polymorphic (relay bridge name or
  kernel veth host interface); the reconcile loop is datapath-agnostic
  and DockerVM overrides the add/delete/enable primitives to translate
  the commands. Marker-name validation extracted for both add paths.
- docker_vm: kernel NIO connect/update apply markers on the veth anchor;
  link deletion tears markers down explicitly (the veth survives the
  link, unlike a relay bridge whose death drops its filters).
- controller: eligibility and start_marker no longer exclude markers or
  project-level marker definitions; the kernel NIO carries the capture
  node's marker specs.
- NIO creation accepts markers on kernel NIOs (filters still rejected).
2026-10-06 00:21:07 +08:00
YueGuobin f6b869be63 feat(docker): packet capture on kernel-datapath links via AF_PACKET
Replace the capture rejection with wiring to uBridge's capture module:
an AF_PACKET socket bound to the veth host end writes into the same pcap
file the relay path uses (capture start_kernel <if> "<pcap>" /
capture stop_kernel), so the pcap streaming to clients is unchanged.

- capture survives node restarts: _connect_nio re-arms it when the NIO
  is already capturing, mirroring the relay path
- uBridge's kernel capture is a singleton per process: a concurrent
  second capture on the same node surfaces uBridge's EALREADY error
- update the datapath docs: filters and markers remain relay-only,
  capture is now served on both datapaths
2026-10-06 00:21:07 +08:00
YueGuobin 58b97b4ce5 fix(controller): don't push the synthetic suspend filter to kernel links
update_suspend() piggybacks on the filter system: get_active_filters()
returns {"frequency_drop": [-1]} while a link is suspended so relay-based
node types drop all traffic at the uBridge filter. Kernel-datapath links
implement suspend natively via interface carrier, and pushing the
synthetic filter tripped the compute-side guard, making suspend fail
with 409 on every kernel link (and leaving controller/kernel state torn).
_get_node_filters() now returns empty filters for kernel links.
2026-10-06 00:21:07 +08:00
YueGuobin 37d7b9121e feat(docker): wire Docker-to-Docker links through a kernel bridge
Eligible links (both endpoints Docker, same compute, no filters/markers,
stopped nodes, no unix-socket NIO containers) are wired as veth pairs
enslaved into a per-link Linux kernel bridge (gns3 + 11 hex of the link
id, filling IFNAMSIZ) instead of the uBridge UDP relay, so frames flow
entirely in the kernel.

- NIOBridge NIO type: the controller decides the datapath in
  UDPLink._prepare and both computes enslave their deterministic gv*/gc*
  veth pair via uBridge's docker/brctl modules
- carrier/suspend = host-end admin state; both endpoints race-safely
  create/delete the bridge (EEXIST/EBUSY/ENOENT tolerated)
- veth adapters can still attach relay (UDP) links on a running node:
  lazy relay bridge over AF_PACKET on the host end (add_nio_ethernet)
- filters/markers/capture are rejected with explicit errors on this
  datapath (they live in the uBridge relay); vendor unix-socket
  containers are excluded; Server.enable_kernel_datapath is the
  kill-switch (default on)
- host-end veths survive container death and are removed on stop plus
  swept by name on the next start (crash/stale recovery)
2026-10-06 00:21:07 +08:00
Cristi 207db770c6 feat(image-manager): Add support for nested image folders and appliance compatibility checks 2026-10-05 18:49:21 +03:00
Jeremy Grossmann 65c858d455 Merge pull request #2942 from markparonyan/ruff/pr03-fstrings
refactor: use f-strings
2026-10-05 14:35:56 +02:00
Mark Paronyan be52a0d0d4 refactor: discriminate appliance settings by template_type 2026-10-05 15:00:35 +03:00
Mark Paronyan b3b1ba0d4e Merge branch '3.1' into ruff/pr03-fstrings 2026-10-04 20:56:13 +03:00
Jeremy Grossmann 9f9be983cd Merge pull request #2939 from markparonyan/patch-1
fix: bump asyncssh - at least 2.24.1 for CVE-2026-62949 fixes
2026-10-04 18:15:03 +02:00
Mark Paronyan 1c5c3d1f76 fix: bump asyncssh - at least 2.24.1 for CVE-2026-62949 fixes
Updated asyncssh version to 2.24.1 in requirements.
2026-10-04 19:01:30 +03:00
Jeremy Grossmann 38cc7cc0a0 Merge pull request #2938 from markparonyan/ruff/pr02-unused-imports
Ruff/pr02 unused imports
2026-10-03 19:33:45 +02:00
Mark Paronyan 7e1bc67be2 chore(ruff): drop UP032 from the ignore baseline 2026-10-03 19:44:02 +03:00
Mark Paronyan 3135c8b7e3 refactor: use f-strings in remaining modules, scripts and tests 2026-10-03 19:44:02 +03:00
Mark Paronyan be943fcdf3 refactor: use f-strings in controller tests 2026-10-03 19:44:02 +03:00
Mark Paronyan bee6b3f8b1 refactor: use f-strings in compute tests 2026-10-03 19:44:01 +03:00
Mark Paronyan 7a9c600f54 refactor: use f-strings in controller modules 2026-10-03 19:44:01 +03:00
Mark Paronyan 552c0ca3e0 refactor: use f-strings in remaining compute modules 2026-10-03 19:44:01 +03:00
Mark Paronyan bbebf20825 refactor: use f-strings in dynamips manager 2026-10-03 19:44:01 +03:00
Mark Paronyan c458459626 refactor: use f-strings in dynamips NIO modules 2026-10-03 19:44:01 +03:00
Mark Paronyan fba3ecc5fc refactor: use f-strings in dynamips nodes 2026-10-03 19:44:00 +03:00
Mark Paronyan a5d2bca921 refactor: use f-strings in dynamips router node 2026-10-03 19:44:00 +03:00
Mark Paronyan 97f6805d0a refactor: use f-strings in iou compute modules 2026-10-03 19:44:00 +03:00
Mark Paronyan d5ad4c67c6 refactor: use f-strings in qemu compute modules 2026-10-03 19:44:00 +03:00
Mark Paronyan 7f2c0c7e9c refactor: use f-strings in docker compute modules 2026-10-03 19:44:00 +03:00
Mark Paronyan 72fae7a1ce refactor: declare new image sync models in the public API 2026-10-03 19:43:59 +03:00
Mark Paronyan d5e2832649 chore(ruff): drop F401 from the ignore baseline 2026-10-03 19:43:59 +03:00
Mark Paronyan b622ccae7b refactor: declare explicit public API in package __init__ modules 2026-10-03 19:43:59 +03:00
Mark Paronyan 01d890bc40 style: tidy import block after unused-import removal 2026-10-03 19:43:59 +03:00
Mark Paronyan 306d8fbde4 refactor: remove unused imports 2026-10-03 19:43:58 +03:00
Jeremy Grossmann 084004586c Merge pull request #2934 from markparonyan/ruff/pr01-imports
refactor: ruff fixes
2026-10-03 17:20:41 +02:00
Mark Paronyan 1ed8320e31 Merge branch '3.1' into ruff/pr01-imports 2026-10-03 14:21:22 +03:00
grossmj 64e2a62a04 fix: improve warning message for missing mtools in config disk creation. Ref #2778 2026-10-02 16:08:38 +02:00
Mark Paronyan b78672a8ca style: sort imports in the new image management modules 2026-10-02 12:43:26 +03:00
Mark Paronyan a64379cb78 chore(ruff): drop I001 from the ignore baseline 2026-10-02 12:43:26 +03:00
Mark Paronyan 83e7fbe63b style: sort imports in remaining tests and scripts 2026-10-02 12:43:26 +03:00
Mark Paronyan 6d16d923c7 style: sort imports in compute and controller tests 2026-10-02 12:43:26 +03:00
Mark Paronyan b46b9a1d26 style: sort imports in api tests 2026-10-02 12:43:26 +03:00
Mark Paronyan 55df230864 style: sort imports in controller 2026-10-02 12:43:26 +03:00
Mark Paronyan 61caa20524 style: sort imports in agent and remaining compute modules 2026-10-02 12:43:26 +03:00
Mark Paronyan 3b993b464f style: sort imports in schemas 2026-10-02 12:43:26 +03:00
Mark Paronyan 634189d443 style: sort imports in api and utils modules 2026-10-02 12:43:26 +03:00
Mark Paronyan 4ebc941951 style: sort imports in controller API routes 2026-10-02 12:43:26 +03:00
Mark Paronyan b9cdac487c style: sort imports in compute, db and services modules 2026-10-02 12:43:26 +03:00
Mark Paronyan 38e9ddca09 style: sort imports in compute node modules 2026-10-02 12:43:26 +03:00
Jeremy Grossmann 7f8d9c2f54 Merge pull request #2933 from markparonyan/ruff/trivia-fixups
refactor: ruff fixes
2026-10-01 23:18:29 +02:00
Mark Paronyan a77e06b907 Merge branch '3.1' into ruff/trivia-fixups 2026-10-01 19:58:02 +03:00
Mark Paronyan 269e7aaa67 chore(ruff): drop resolved trivia rules from the ignore baseline 2026-10-01 19:57:47 +03:00
Mark Paronyan 74943b4c74 refactor: convert remaining percent formatting in log messages 2026-10-01 19:57:47 +03:00
Mark Paronyan 95ada23395 refactor: replace percent formatting with format specifiers 2026-10-01 19:57:47 +03:00
Mark Paronyan 06899c92fc refactor: use iterable unpacking instead of concatenation 2026-10-01 19:57:46 +03:00
Mark Paronyan 2dc7479d11 style: remove f-strings without placeholders 2026-10-01 19:57:46 +03:00
Mark Paronyan c9416d2569 style: remove quotes from type annotations 2026-10-01 19:57:45 +03:00
Mark Paronyan fdb8d87a64 style: drop useless object inheritance 2026-10-01 19:57:45 +03:00
Mark Paronyan 396407827e style: drop redundant open mode arguments 2026-10-01 19:57:44 +03:00
Mark Paronyan d356a68987 refactor: replace aliased OSError subclasses 2026-10-01 19:57:44 +03:00
Mark Paronyan 7d0be62da8 style: drop redundant utf-8 encode arguments 2026-10-01 19:57:44 +03:00
Mark Paronyan 06ef803ee9 style: use not-in membership tests 2026-10-01 19:57:43 +03:00
Mark Paronyan 7a1e79a8a0 style: parenthesize chained boolean operators 2026-10-01 19:57:43 +03:00
Mark Paronyan 1a495ab318 refactor: replace getattr with attribute access 2026-10-01 19:57:42 +03:00
Mark Paronyan 0416ad8228 style: sort __all__ declarations 2026-10-01 19:57:42 +03:00
Mark Paronyan c5b5091f5e refactor: use explicit conversion in f-strings 2026-10-01 19:57:41 +03:00
Mark Paronyan 0f66fd6c2b style: remove trailing whitespace 2026-10-01 19:57:41 +03:00
Mark Paronyan 06e98f8b55 style: drop redundant utf-8 coding declarations 2026-10-01 19:57:40 +03:00
Mark Paronyan 9e5ab02147 style: remove unused noqa directives 2026-10-01 19:57:40 +03:00
grossmj be3da6f372 fix: require Python >= 3.10 in remote-install.sh when installing v3 2026-10-01 16:28:26 +02:00
Jeremy Grossmann 7be135f0ae Merge pull request #2903 from cristian-ciobanu/image-manager-out-of-sync
fix(image-manager): Reconcile the image inventory with filesystem changes
2026-10-01 15:42:14 +02:00
grossmj 1456d36bf0 chore(tests): fix mypy errors 2026-10-01 15:22:17 +02:00
grossmj 285af128f2 fix: ignore S324 error in tests 2026-10-01 14:53:54 +02:00
Jeremy Grossmann a2cdc14a25 Merge branch '3.1' into image-manager-out-of-sync 2026-10-01 14:44:24 +02:00
Jeremy Grossmann eb3ce3804d Merge pull request #2931 from markparonyan/mypy-api-controller-misc
chore: drop the mypy baseline ignore list
2026-09-29 21:37:31 +02:00
Jeremy Grossmann e90be1ebac Merge pull request #2930 from markparonyan/mypy-db-templates-images
fix(typing): resolve the remaining mypy errors (18 modules)
2026-09-29 21:37:14 +02:00
Mark Paronyan 98097a7f8f chore: drop the mypy baseline ignore list (no modules left) 2026-09-29 22:02:24 +03:00
Mark Paronyan eae69bd5c5 fix(typing): resolve mypy errors in compute.virtualbox.virtualbox_vm 2026-09-29 22:02:23 +03:00
Mark Paronyan 472c1b61fd fix(typing): resolve mypy errors in controller.project 2026-09-29 22:02:23 +03:00
Mark Paronyan 783f243230 fix(typing): resolve mypy errors in controller.appliance_manager 2026-09-29 22:02:23 +03:00
Mark Paronyan 0954723ebd fix(typing): resolve mypy errors in schemas.controller.computes 2026-09-29 22:02:22 +03:00
Mark Paronyan 36945daa83 fix(typing): resolve mypy errors in db.repositories.computes 2026-09-29 22:02:22 +03:00
Mark Paronyan 2fe4e39715 fix(typing): resolve mypy errors in db.repositories.api_keys 2026-09-29 22:02:22 +03:00
Mark Paronyan bacfab8465 fix(typing): resolve mypy errors in api.routes.controller.pools 2026-09-29 22:02:21 +03:00
Mark Paronyan adf9c15e21 fix(typing): resolve mypy errors in api.routes.controller.projects 2026-09-29 22:02:21 +03:00
Mark Paronyan 8f7b895cf4 fix(typing): resolve mypy errors in db.repositories.pools 2026-09-29 22:02:21 +03:00
Mark Paronyan fa9d1cde80 fix(typing): resolve mypy errors in db.repositories.rbac 2026-09-29 22:02:20 +03:00
Mark Paronyan 323055c486 fix(typing): resolve mypy errors in api.routes.controller.templates 2026-09-29 22:02:20 +03:00
Mark Paronyan bbf4e6aa2c fix(typing): resolve mypy errors in api.routes.controller.images 2026-09-29 22:02:20 +03:00
Mark Paronyan 81474b4651 fix(typing): resolve mypy errors in db.repositories.images 2026-09-29 22:02:19 +03:00
Mark Paronyan 4361598df0 fix(typing): resolve mypy errors in api.routes.controller.llm_model_configs 2026-09-29 22:02:19 +03:00
Mark Paronyan c048124c21 fix(typing): resolve mypy errors in db.repositories.llm_model_configs 2026-09-29 22:02:19 +03:00
Mark Paronyan b1d13edd2d fix(typing): resolve mypy errors in api.routes.controller.users 2026-09-29 22:02:18 +03:00
Mark Paronyan 8e96f18429 fix(typing): resolve mypy errors in db.repositories.users 2026-09-29 22:02:18 +03:00
Mark Paronyan 1aaf36fc80 fix(typing): resolve mypy errors in db.tasks 2026-09-29 22:02:18 +03:00
Jeremy Grossmann 5feebbc1d9 Merge pull request #2929 from markparonyan/mypy-restore-type-check
fix(typing): resolve mypy errors in services.templates and api.routes.controller.dependencies.authentication
2026-09-29 20:57:47 +02:00
Mark Paronyan a3cb73da3d fix(typing): resolve mypy errors in api.routes.controller.dependencies.authentication 2026-09-29 21:48:33 +03:00
Mark Paronyan dfea615248 fix(typing): resolve mypy errors in services.templates 2026-09-29 21:48:32 +03:00
Cristi 87df09c00c fix(images): Fix symlinked image imports and add regression tests 2026-09-29 20:16:22 +03:00
Cristi 2e12775911 fix(images): Fix symlink support in image inventory 2026-09-29 15:42:49 +03:00
Jeremy Grossmann 5f9fd6e595 Merge pull request #2928 from markparonyan/mypy-utils
fix(typing): resolve mypy errors in gns3server.utils
2026-09-29 13:42:11 +02:00
Jeremy Grossmann 5c87c0e1a4 Merge branch '3.1' into mypy-utils 2026-09-29 13:41:58 +02:00
Jeremy Grossmann b812ed75c0 Merge pull request #2927 from markparonyan/mypy-schemas-plus
fix(typing): resolve mypy errors in schemas + schemas.controller + services + utils.asyncio
2026-09-29 13:41:22 +02:00
Jeremy Grossmann 1838ad7f05 Merge branch '3.1' into mypy-schemas-plus 2026-09-29 13:41:11 +02:00
Jeremy Grossmann 053cd9479e Merge pull request #2926 from markparonyan/mypy-schemas
fix(typing): resolve mypy errors in gns3server.schemas
2026-09-29 13:40:10 +02:00
Jeremy Grossmann eace280c5f Merge branch '3.1' into mypy-schemas 2026-09-29 13:40:00 +02:00
Jeremy Grossmann 482e3faecb Merge pull request #2925 from markparonyan/mypy-schemas-compute
fix(typing): resolve mypy errors in gns3server.schemas.compute
2026-09-29 13:39:14 +02:00
Jeremy Grossmann e6410ed729 Merge branch '3.1' into mypy-schemas-compute 2026-09-29 13:39:01 +02:00
Jeremy Grossmann 76411f1eb0 Merge pull request #2924 from markparonyan/mypy-api-plus
fix(typing): resolve mypy errors in api + compute.dynamips + compute.iou + compute.vpcs + controller
2026-09-29 13:29:08 +02:00
Jeremy Grossmann 2f8277aeb7 Merge pull request #2922 from markparonyan/mypy-api-routes-controller-1
fix(typing): resolve mypy errors in gns3server.api.routes.controller
2026-09-29 13:28:43 +02:00
Jeremy Grossmann e8f49877fc Merge branch '3.1' into mypy-api-routes-controller-1 2026-09-29 13:28:33 +02:00
Jeremy Grossmann 7e5f5486eb Merge pull request #2921 from markparonyan/mypy-api-routes
fix(typing): resolve mypy errors in gns3server.api.routes
2026-09-29 13:25:46 +02:00
Jeremy Grossmann 7f4f9eb2d0 Merge branch '3.1' into mypy-api-routes 2026-09-29 13:25:35 +02:00
Jeremy Grossmann fd43f39a8d Merge pull request #2920 from markparonyan/mypy-api-routes-compute-4
fix(typing): resolve mypy errors in gns3server.api.routes.compute
2026-09-29 13:24:00 +02:00
Jeremy Grossmann 49f1af0962 Merge branch '3.1' into mypy-api-routes-compute-4 2026-09-29 13:23:50 +02:00
Jeremy Grossmann 87f469b299 Merge pull request #2919 from markparonyan/mypy-api-routes-compute-3
fix(typing): resolve mypy errors in gns3server.api.routes.compute
2026-09-29 13:23:15 +02:00
Jeremy Grossmann 1f7048d49d Merge branch '3.1' into mypy-api-routes-compute-3 2026-09-29 13:23:05 +02:00
Jeremy Grossmann 3be6da2476 Merge pull request #2918 from markparonyan/mypy-api-routes-compute-2
fix(typing): resolve mypy errors in gns3server.api.routes.compute
2026-09-29 13:22:22 +02:00
Jeremy Grossmann cbd29ece37 Merge branch '3.1' into mypy-api-routes-compute-2 2026-09-29 13:21:10 +02:00
Jeremy Grossmann 58c928759c Merge pull request #2916 from markparonyan/mypy-agent-gns3_copilot-plus
fix(typing): resolve mypy errors in agent.gns3_copilot + agent.mcp + agent.web_wireshark + api.routes
2026-09-29 13:20:39 +02:00
Jeremy Grossmann 726da8383a Merge branch '3.1' into mypy-agent-gns3_copilot-plus 2026-09-29 13:20:27 +02:00
Jeremy Grossmann 8493ddd2b4 Merge pull request #2915 from markparonyan/mypy-agent
fix(typing): resolve mypy errors in gns3server.agent
2026-09-29 13:19:43 +02:00
Jeremy Grossmann 468ad4e85f Merge branch '3.1' into mypy-agent 2026-09-29 13:19:30 +02:00
Jeremy Grossmann 2866dbc51b Merge pull request #2917 from markparonyan/mypy-api-routes-compute-1
fix(typing): resolve mypy errors in gns3server.api.routes.compute
2026-09-29 13:16:31 +02:00
Jeremy Grossmann 4efc22b7ab Merge branch '3.1' into mypy-api-routes-compute-1 2026-09-29 13:15:30 +02:00
Jeremy Grossmann 563b6080f0 Merge pull request #2923 from markparonyan/mypy-api-routes-controller-2
fix(typing): resolve mypy errors in gns3server.api.routes.controller
2026-09-29 13:13:58 +02:00
Jeremy Grossmann ec4b04ba54 Merge pull request #2914 from markparonyan/mypy-utils-misc
fix(typing): resolve mypy errors in utils
2026-09-29 13:01:12 +02:00
Jeremy Grossmann a6ae3984d4 Merge pull request #2913 from markparonyan/mypy-schemas-compute-nodes
fix(typing): resolve mypy errors in schemas.compute node schemas
2026-09-29 12:53:39 +02:00
Jeremy Grossmann 9e9a778f8b Merge pull request #2912 from markparonyan/mypy-api-controller-routes
fix(typing): resolve mypy errors in api.routes.controller
2026-09-29 12:50:06 +02:00
Jeremy Grossmann ce3911be71 Merge pull request #2911 from markparonyan/mypy-api-compute-routes
fix(typing): resolve mypy errors in api.routes.compute
2026-09-29 12:48:36 +02:00
Jeremy Grossmann 4bcaf596df Merge pull request #2910 from markparonyan/mypy-agent-copilot-utils
fix(typing): resolve mypy errors in agent.gns3_copilot.utils
2026-09-29 12:48:03 +02:00
Jeremy Grossmann f37a4c1bd3 Merge pull request #2909 from markparonyan/mypy-agent-copilot-tools-analysis
fix(typing): resolve mypy errors in agent.gns3_copilot.tools_v2 (packet analysis)
2026-09-29 12:47:41 +02:00
Jeremy Grossmann b73128d791 Merge branch '3.1' into mypy-agent-copilot-tools-analysis 2026-09-29 12:45:07 +02:00
Jeremy Grossmann 4337f8ccf6 Merge pull request #2908 from markparonyan/mypy-agent-copilot-tools-nornir
fix(typing): resolve mypy errors in agent.gns3_copilot.tools_v2 (nornir + packet filter)
2026-09-29 12:39:19 +02:00
Jeremy Grossmann 77a323e1e8 Merge branch '3.1' into mypy-agent-copilot-tools-nornir 2026-09-29 12:38:40 +02:00
Jeremy Grossmann f23302f52a Merge pull request #2907 from markparonyan/mypy-agent-copilot-skills
fix(typing): resolve mypy errors in agent.gns3_copilot.skills
2026-09-29 12:35:51 +02:00
Jeremy Grossmann a51af4a32e Fix module list after merging
Removed unused modules from the project configuration.
2026-09-29 12:35:33 +02:00
Jeremy Grossmann 7b40064658 Merge branch '3.1' into mypy-agent-copilot-skills 2026-09-29 12:30:40 +02:00
Jeremy Grossmann 080c907139 Merge pull request #2901 from markparonyan/mypy-controller-topology
fix(typing): resolve mypy errors in controller.topology
2026-09-29 12:28:01 +02:00
Jeremy Grossmann eb9a9ae19a Merge pull request #2904 from markparonyan/mypy-agent-web-wireshark
fix(typing): resolve mypy errors in agent.web_wireshark
2026-09-29 12:27:28 +02:00
Jeremy Grossmann 6aac6c8e34 Merge pull request #2906 from markparonyan/mypy-agent-copilot-client
fix(typing): resolve mypy errors in agent.gns3_copilot.gns3_client
2026-09-29 12:21:33 +02:00
Jeremy Grossmann 0ef6e80d94 Merge pull request #2905 from markparonyan/mypy-agent-copilot-agent
fix(typing): resolve mypy errors in agent.gns3_copilot.agent
2026-09-29 11:15:24 +02:00
Mark Paronyan 780b7f2ab6 fix(typing): resolve mypy errors in agent node lifecycle tools 2026-09-29 09:46:32 +03:00
Mark Paronyan bc27c4814f fix(typing): resolve mypy errors in agent.gns3_copilot.gns3_client.api_handlers 2026-09-29 09:46:31 +03:00
Mark Paronyan 9882eba088 fix(typing): resolve mypy errors in agent.gns3_copilot.chat_sessions_repository 2026-09-29 09:46:31 +03:00
Mark Paronyan 07560b0026 fix(typing): resolve mypy errors in agent 2026-09-29 09:46:31 +03:00
Mark Paronyan d783ccfc0d fix(typing): resolve mypy errors in controller.topology 2026-09-29 09:45:36 +03:00
Mark Paronyan a7b32ca6df fix(typing): resolve mypy errors in controller.appliance 2026-09-29 09:38:24 +03:00
Mark Paronyan 2542ad4647 fix(typing): resolve mypy errors in compute.vpcs.vpcs_vm 2026-09-29 09:38:24 +03:00
Mark Paronyan a7350ae0c8 fix(typing): resolve mypy errors in compute.iou.utils 2026-09-29 09:38:24 +03:00
Mark Paronyan 1babf7bcce fix(typing): resolve mypy errors in compute.dynamips.nodes.router 2026-09-29 09:38:24 +03:00
Mark Paronyan 68368220f2 fix(typing): resolve mypy errors in api.server 2026-09-29 09:38:17 +03:00
Mark Paronyan 1284701253 fix(typing): resolve mypy errors in utils.zipfile_zstd._patcher 2026-09-29 09:23:15 +03:00
Mark Paronyan df8b3c2903 fix(typing): resolve mypy errors in utils.asyncio.aiozipstream 2026-09-29 09:23:15 +03:00
Mark Paronyan 1772c7380e fix(typing): resolve mypy errors in utils.websocket_to_websocket 2026-09-29 09:23:15 +03:00
Mark Paronyan 5bf3c8d203 fix(typing): resolve mypy errors in utils.http_client 2026-09-29 09:23:15 +03:00
Mark Paronyan e6053dd0a8 fix(typing): resolve mypy errors in services.computes 2026-09-29 09:23:14 +03:00
Mark Paronyan 9bad1d92f8 fix(typing): resolve mypy errors in schemas.qemu_disk_image 2026-09-29 09:23:14 +03:00
Mark Paronyan 79862d900a fix(typing): resolve mypy errors in schemas.controller.templates.vmware_templates 2026-09-29 09:23:14 +03:00
Mark Paronyan 3abed40707 fix(typing): resolve mypy errors in schemas.controller.templates.docker_templates 2026-09-29 09:23:13 +03:00
Mark Paronyan edaf9a4377 fix(typing): resolve mypy errors in schemas.controller.templates.virtualbox_templates 2026-09-29 09:23:13 +03:00
Mark Paronyan 94a0f462bf fix(typing): resolve mypy errors in schemas.controller.templates.iou_templates 2026-09-29 09:23:13 +03:00
Mark Paronyan 07dc9b4d7d fix(typing): resolve mypy errors in schemas.controller.settings 2026-09-29 09:23:12 +03:00
Mark Paronyan 01dd09495c fix(typing): resolve mypy errors in schemas.controller.projects 2026-09-29 09:23:12 +03:00
Mark Paronyan a68e57dd2e fix(typing): resolve mypy errors in schemas.controller.nodes 2026-09-29 09:23:12 +03:00
Mark Paronyan 7439e91f5a fix(typing): resolve mypy errors in schemas.controller.appliances 2026-09-29 09:23:12 +03:00
Mark Paronyan 515ae8dcfb fix(typing): resolve mypy errors in schemas.compute.virtualbox_nodes 2026-09-29 09:23:11 +03:00
Mark Paronyan d027146fb9 fix(typing): resolve mypy errors in schemas.compute.vpcs_nodes 2026-09-29 09:23:11 +03:00
Mark Paronyan 87f209f548 fix(typing): resolve mypy errors in schemas.compute.qemu_nodes 2026-09-29 09:23:11 +03:00
Mark Paronyan 898205a33b fix(typing): resolve mypy errors in schemas.compute.vmware_nodes 2026-09-29 09:23:11 +03:00
Mark Paronyan aa7941411f fix(typing): resolve mypy errors in schemas.compute.iou_nodes 2026-09-29 09:23:10 +03:00
Mark Paronyan abb564a2fa fix(typing): resolve mypy errors in schemas.compute.frame_relay_switch_nodes 2026-09-29 09:23:10 +03:00
Mark Paronyan 2b704025e3 fix(typing): resolve mypy errors in schemas.compute.docker_nodes 2026-09-29 09:23:10 +03:00
Mark Paronyan 908a1eb3e6 fix(typing): resolve mypy errors in schemas.compute.cloud_nodes 2026-09-29 09:23:10 +03:00
Mark Paronyan ebe6dee916 fix(typing): resolve mypy errors in api.routes.controller.snapshots 2026-09-29 09:23:08 +03:00
Mark Paronyan 68d96193ec fix(typing): resolve mypy errors in api.routes.controller.groups 2026-09-29 09:23:07 +03:00
Mark Paronyan c340b18ba2 fix(typing): resolve mypy errors in api.routes.controller.roles 2026-09-29 09:23:07 +03:00
Mark Paronyan 2cf90dfce6 fix(typing): resolve mypy errors in api.routes.controller.privileges 2026-09-29 09:23:07 +03:00
Mark Paronyan 93419fc33a fix(typing): resolve mypy errors in api.routes.controller.nodes 2026-09-29 09:23:07 +03:00
Mark Paronyan 0872576b46 fix(typing): resolve mypy errors in api.routes.controller.acl 2026-09-29 09:23:06 +03:00
Mark Paronyan a648bf3780 fix(typing): resolve mypy errors in api.routes.controller.dependencies.database 2026-09-29 09:23:06 +03:00
Mark Paronyan 58609bae7b fix(typing): resolve mypy errors in api.routes.controller.controller 2026-09-29 09:23:06 +03:00
Mark Paronyan d826285748 fix(typing): resolve mypy errors in api.routes.controller.computes 2026-09-29 09:23:06 +03:00
Mark Paronyan 83b80b8c52 fix(typing): resolve mypy errors in api.routes.compute.virtualbox_nodes 2026-09-29 09:23:05 +03:00
Mark Paronyan a86cae541e fix(typing): resolve mypy errors in api.routes.compute.vpcs_nodes 2026-09-29 09:23:05 +03:00
Mark Paronyan e0c4cb8122 fix(typing): resolve mypy errors in api.routes.compute.vmware_nodes 2026-09-29 09:23:05 +03:00
Mark Paronyan 0ff63bfd90 fix(typing): resolve mypy errors in api.routes.compute.nat_nodes 2026-09-29 09:23:04 +03:00
Mark Paronyan 04ca7ffd9b fix(typing): resolve mypy errors in api.routes.compute.frame_relay_switch_nodes 2026-09-29 09:23:04 +03:00
Mark Paronyan fed8aab86c fix(typing): resolve mypy errors in api.routes.compute.projects 2026-09-29 09:23:04 +03:00
Mark Paronyan 9218f3fc72 fix(typing): resolve mypy errors in api.routes.compute.iou_nodes 2026-09-29 09:23:04 +03:00
Mark Paronyan cacbc18ad1 fix(typing): resolve mypy errors in api.routes.compute.ethernet_hub_nodes 2026-09-29 09:23:03 +03:00
Mark Paronyan 5ed85340af fix(typing): resolve mypy errors in api.routes.compute.ethernet_switch_nodes 2026-09-29 09:23:03 +03:00
Mark Paronyan 904672559e fix(typing): resolve mypy errors in api.routes.compute.dynamips_nodes 2026-09-29 09:23:03 +03:00
Mark Paronyan 50a749af36 fix(typing): resolve mypy errors in api.routes.compute.cloud_nodes 2026-09-29 09:23:02 +03:00
Mark Paronyan bb0f29b8e6 fix(typing): resolve mypy errors in api.routes.compute.docker_nodes 2026-09-29 09:23:02 +03:00
Mark Paronyan 8aa07a8c25 fix(typing): resolve mypy errors in api.routes.compute.atm_switch_nodes 2026-09-29 09:23:02 +03:00
Mark Paronyan 10edb109df fix(typing): resolve mypy errors in api.routes.compute.dependencies.authentication 2026-09-29 09:23:02 +03:00
Mark Paronyan c154d1c41e fix(typing): resolve mypy errors in agent.web_wireshark.docker_client 2026-09-29 09:23:01 +03:00
Mark Paronyan d25cb5cdca fix(typing): resolve mypy errors in agent.mcp.appliances 2026-09-29 09:23:01 +03:00
Mark Paronyan 2d712e0a90 fix(typing): resolve mypy errors in agent.gns3_copilot.utils.custom_netmiko.scripts.list_netmiko_telnet_devices 2026-09-29 09:23:01 +03:00
Mark Paronyan a3c4c95431 fix(typing): resolve mypy errors in schemas.compute.nat_nodes 2026-09-29 08:52:44 +03:00
Mark Paronyan 672ef2e3ce fix(typing): resolve mypy errors in schemas.compute.dynamips_nodes 2026-09-29 08:52:43 +03:00
Mark Paronyan 094fcf2747 fix(typing): resolve mypy errors in schemas.compute.atm_switch_nodes 2026-09-29 08:52:43 +03:00
Mark Paronyan 4ae6b5338d fix(typing): resolve mypy errors in agent.gns3_copilot.utils.parse_tool_content 2026-09-29 08:52:38 +03:00
Mark Paronyan 5cb1b8e3d2 fix(typing): resolve mypy errors in agent.gns3_copilot.utils.message_converters 2026-09-29 08:52:37 +03:00
Mark Paronyan cd7f5ab8e9 fix(typing): resolve mypy errors in agent.gns3_copilot.agent.model_factory 2026-09-29 08:52:33 +03:00
Mark Paronyan a251ca73ac fix(typing): resolve mypy errors in agent.gns3_copilot.agent.context_manager 2026-09-29 08:52:33 +03:00
Mark Paronyan 94bf56040b fix(typing): resolve mypy errors in utils.packet_filter_validation 2026-09-29 08:48:06 +03:00
Mark Paronyan ab5572a0c1 fix(typing): resolve mypy errors in utils.images 2026-09-29 08:48:06 +03:00
Mark Paronyan 943bd6732c fix(typing): resolve mypy errors in utils.encryption 2026-09-29 08:48:06 +03:00
Mark Paronyan bbdd9bf861 fix(typing): resolve mypy errors in api.routes.controller.drawings 2026-09-29 08:48:04 +03:00
Mark Paronyan 5fb2c277a9 fix(typing): resolve mypy errors in api.routes.compute.notifications 2026-09-29 08:48:04 +03:00
Mark Paronyan 6526beeb3d fix(typing): resolve mypy errors in api.routes.controller.chat 2026-09-29 08:48:04 +03:00
Mark Paronyan 777258ff68 fix(typing): resolve mypy errors in api.routes.controller.api_keys 2026-09-29 08:48:04 +03:00
Mark Paronyan f94a0cae0d fix(typing): resolve mypy errors in api.routes.compute.compute 2026-09-29 08:48:03 +03:00
Mark Paronyan 5bb7896242 fix(typing): resolve mypy errors in api.routes.compute.capabilities 2026-09-29 08:48:03 +03:00
Mark Paronyan f8144494f6 fix(typing): resolve mypy errors in agent.gns3_copilot.tools_v2.vpcs_tools_netmiko 2026-09-29 08:48:02 +03:00
Mark Paronyan d2fd238383 fix(typing): resolve mypy errors in agent.gns3_copilot.tools_v2.gns3_packet_filter 2026-09-29 08:48:02 +03:00
Mark Paronyan 67f68c9676 fix(typing): resolve mypy errors in agent.gns3_copilot.tools_v2.packet_analysis_tool 2026-09-29 08:48:02 +03:00
Mark Paronyan d6ae597f36 fix(typing): resolve mypy errors in agent.gns3_copilot.skills.manager 2026-09-29 08:48:01 +03:00
Mark Paronyan 35b360ca75 fix(typing): resolve mypy errors in agent.gns3_copilot.tools_v2.display_tools_nornir 2026-09-29 08:48:01 +03:00
Mark Paronyan c7c7e3b583 fix(typing): resolve mypy errors in agent.gns3_copilot.skills.loader 2026-09-29 08:48:01 +03:00
Mark Paronyan e8bff79370 fix(typing): resolve mypy errors in agent.gns3_copilot.tools_v2.config_tools_nornir 2026-09-29 08:48:01 +03:00
Mark Paronyan 97f71269d3 fix(typing): resolve mypy errors in agent.gns3_copilot.gns3_client.project_inventory 2026-09-29 08:48:00 +03:00
Mark Paronyan 890093de01 fix(typing): resolve mypy errors in agent.gns3_copilot.gns3_client.connector_factory 2026-09-29 08:48:00 +03:00
Mark Paronyan 7f2d1bc789 fix(typing): resolve mypy errors in agent.web_wireshark.manager 2026-09-29 08:41:57 +03:00
Mark Paronyan 81d77bb689 fix(typing): resolve mypy errors in agent.web_wireshark.stats 2026-09-29 08:41:57 +03:00
Mark Paronyan 755556c146 fix(typing): resolve mypy errors in agent.web_wireshark.manage_wireshark 2026-09-29 08:41:57 +03:00
Jeremy Grossmann b9192438c9 Merge pull request #2902 from markparonyan/mypy-services-authentication
fix(typing): resolve mypy errors in services.authentication
2026-09-28 23:34:47 +02:00
Jeremy Grossmann 884526c3be Merge pull request #2900 from markparonyan/mypy-compute-iou-vm
fix(typing): resolve mypy errors in compute.iou.iou_vm
2026-09-28 23:33:41 +02:00
Jeremy Grossmann f19274891c Merge pull request #2898 from markparonyan/mypy-schemas-dynamips-templates
fix(typing): resolve mypy errors in schemas.controller.templates.dynamips_templates
2026-09-28 23:33:22 +02:00
Jeremy Grossmann 7864a4e567 Merge pull request #2897 from markparonyan/mypy-api-controller-links
fix(typing): resolve mypy errors in api.routes.controller.links
2026-09-28 23:26:48 +02:00
Jeremy Grossmann f6ee1ee01a Merge pull request #2896 from markparonyan/mypy-api-compute-qemu-nodes
fix(typing): resolve mypy errors in api.routes.compute.qemu_nodes
2026-09-28 23:25:55 +02:00
Cristi 42d30651da Merge origin/3.1 into image-manager-out-of-sync
Preserve image reconciliation, locking, and regression coverage while integrating upstream release, dependency, typing, and formatting updates. Align feature code with the new Ruff checks.
2026-09-28 23:16:24 +03:00
Jeremy Grossmann 35e1abcaf2 Merge pull request #2895 from markparonyan/mypy-agent-agent-service
fix(typing): resolve mypy errors in agent.gns3_copilot.agent_service
2026-09-28 20:56:12 +02:00
Jeremy Grossmann 02d02cceca Merge pull request #2899 from markparonyan/mypy-db-models-base
fix(typing): resolve mypy errors in db models
2026-09-28 20:52:55 +02:00
Jeremy Grossmann 71965e0e81 Merge pull request #2894 from markparonyan/mypy-utils-zipfile-zstd
fix(typing): resolve mypy errors in utils.zipfile_zstd
2026-09-28 20:50:20 +02:00
Jeremy Grossmann 4ea31f98b7 Merge pull request #2893 from markparonyan/mypy-agent-mcp
fix(typing): resolve mypy errors in agent.mcp
2026-09-28 20:49:10 +02:00
Mark Paronyan 9f36fb4500 fix(typing): resolve mypy errors in services.authentication 2026-09-28 21:48:40 +03:00
Mark Paronyan 4802c865fc fix(typing): resolve mypy errors in compute.iou.iou_vm 2026-09-28 21:48:18 +03:00
Mark Paronyan db265f9524 fix(typing): resolve mypy errors in db models 2026-09-28 21:48:06 +03:00
Mark Paronyan 6f3e5cfc2b fix(typing): resolve mypy errors in schemas.controller.templates.dynamips_templates 2026-09-28 21:47:56 +03:00
Mark Paronyan ecff4beb65 fix(typing): resolve mypy errors in api.routes.controller.links 2026-09-28 21:47:46 +03:00
Mark Paronyan b8a51fdefc fix(typing): resolve mypy errors in api.routes.compute.qemu_nodes 2026-09-28 21:47:36 +03:00
Mark Paronyan 644ed63334 fix(typing): resolve mypy errors in agent.gns3_copilot.agent_service 2026-09-28 21:47:26 +03:00
Mark Paronyan 3fc1d27937 fix(typing): resolve mypy errors in utils.zipfile_zstd 2026-09-28 21:47:05 +03:00
Mark Paronyan 6ffa39642f fix(typing): resolve mypy errors in agent.mcp 2026-09-28 21:41:58 +03:00
Cristi 046dff4d08 fix(images): reconcile the image inventory with filesystem changes 2026-09-28 16:01:36 +03:00
Jeremy Grossmann 0c9f6aa9e3 Merge pull request #2892 from markparonyan/mypy-compute-qemu-vm
fix(typing): resolve mypy errors in compute.qemu.qemu_vm
2026-09-28 12:00:10 +02:00
Mark Paronyan 6bff55d3c7 Remove gns3server.compute.project from pyproject.toml
Removed 'gns3server.compute.project' from the list.
2026-09-28 12:41:51 +03:00
Mark Paronyan 798edca81d Remove qemu_vm typing ignore from pyproject.toml 2026-09-28 12:40:51 +03:00
Mark Paronyan 8c0a5404ac Merge branch '3.1' into mypy-compute-qemu-vm 2026-09-28 12:39:38 +03:00
Mark Paronyan 525ef8ca57 fix(typing): resolve mypy errors in compute.qemu.qemu_vm 2026-09-28 12:37:28 +03:00
Jeremy Grossmann 79ecb15164 Merge pull request #2888 from markparonyan/mypy-compute-vmware-vm
fix(typing): resolve mypy errors in compute.vmware.vmware_vm
2026-09-28 11:06:12 +02:00
Jeremy Grossmann 310bb193a5 Merge pull request #2887 from markparonyan/mypy-compute-docker-vm
fix(typing): resolve mypy errors in compute.docker vm modules
2026-09-28 11:03:44 +02:00
Jeremy Grossmann ccee503b74 Merge pull request #2891 from markparonyan/mypy-controller-compute
fix(typing): resolve mypy errors in controller.compute
2026-09-28 11:01:30 +02:00
Jeremy Grossmann 378751070c Merge pull request #2885 from markparonyan/mypy-compute-project
fix(typing): resolve mypy errors in compute.project
2026-09-28 10:55:33 +02:00
Jeremy Grossmann 10b5c1bb6b Merge branch '3.1' into mypy-compute-project 2026-09-28 10:55:25 +02:00
Jeremy Grossmann 0bd1204d15 Merge pull request #2884 from markparonyan/mypy-config
fix(typing): resolve mypy errors in config
2026-09-28 10:54:17 +02:00
Jeremy Grossmann 0718e038f7 Merge pull request #2883 from markparonyan/mypy-utils-embed-shell
fix(typing): resolve mypy errors in utils.asyncio.embed_shell
2026-09-28 10:47:23 +02:00
Jeremy Grossmann f2b8b32d59 Merge pull request #2882 from markparonyan/mypy-api-index
Fix mypy errors in api.routes.index
2026-09-28 10:39:46 +02:00
Mark Paronyan 21643fe89d fix(typing): resolve mypy errors in controller.compute 2026-09-28 04:56:59 +00:00
Mark Paronyan d1df96e0a6 fix(typing): resolve mypy errors in utils.asyncio.embed_shell 2026-09-28 04:56:18 +00:00
Mark Paronyan fdfb2d5591 fix(typing): resolve mypy errors in compute.vmware.vmware_vm 2026-09-28 04:55:44 +00:00
Mark Paronyan 667b0531f6 fix(typing): resolve mypy errors in compute.project 2026-09-28 04:55:38 +00:00
Mark Paronyan b8ae84031e fix(typing): resolve mypy errors in compute.docker vm modules 2026-09-28 04:55:32 +00:00
Mark Paronyan f858ae23a6 fix(typing): resolve mypy errors in api.routes.index 2026-09-28 04:55:30 +00:00
Mark Paronyan 2512556770 fix(typing): resolve mypy errors in config 2026-09-28 04:55:20 +00:00
grossmj 8df25dec32 Development on 3.1.0.dev7 2026-09-27 20:21:12 +02:00
grossmj 4fa4ef7c2f Release v3.1.0a6 2026-09-27 19:18:25 +02:00
grossmj 3f2afb0e4a Bundle web-ui v3.1.0a6 2026-09-27 19:10:11 +02:00
Jeremy Grossmann 902b1f8ea1 Merge pull request #2881 from GNS3/update-dependencies
Update dependencies
2026-09-27 19:07:55 +02:00
grossmj 1f3d00dd1a Merge remote-tracking branch 'origin/update-dependencies' into update-dependencies 2026-09-27 19:01:56 +02:00
Jeremy Grossmann 539d9f94f9 Merge branch '3.1' into update-dependencies 2026-09-27 19:01:34 +02:00
grossmj b96774d1f7 Sync appliances 2026-09-27 18:59:42 +02:00
grossmj 52f2774c05 sqlalchemy v2.0.54 is the last version that supports Python 3.10 2026-09-27 18:55:33 +02:00
Jeremy Grossmann d99b89f1e9 Merge pull request #2880 from markparonyan/harden-ci
ci: mypy, ruff, pytest
2026-09-27 18:52:08 +02:00
grossmj 76e85b552a chore(deps): update dependencies 2026-09-27 18:51:14 +02:00
Mark Paronyan 544890c6b4 chore: delete mac and win reqs 2026-09-27 19:09:25 +03:00
grossmj 45a0f596c8 Ignore Markdown files 2026-09-27 17:52:40 +02:00
grossmj 5c686b0c20 Revert changes to rbac-user-isolation-roadmap.md 2026-09-27 17:13:34 +02:00
Mark Paronyan ef579dfa8f ci: no flake8 checks for now, ruff covers them 2026-09-27 16:07:44 +03:00
Mark Paronyan a0450b6bce refactor: ruff autofixes 2026-09-27 15:55:10 +03:00
Mark Paronyan 2ac637c662 ci: run just test 2026-09-27 15:43:49 +03:00
Mark Paronyan 8dfe05df3d chore: justfile with mypy, ruff, pytest checks 2026-09-27 15:43:18 +03:00
Jeremy Grossmann efd6bb77fe Merge pull request #2878 from cristian-ciobanu/project-missing-images
Allow projects containing unavailable images to open in a degraded state instead of failing to load
2026-09-22 15:34:36 +02:00
grossmj 34923e46e0 chore(docs): update gns3_server.conf sample about the default NAT interface 2026-09-22 14:56:58 +02:00
Cristi da16dc9874 fix(qemu): Fixed missing image replacement for linked-clone nodes 2026-09-18 23:58:49 +03:00
Cristi 59a367b88d Allow projects containing missing images to open in a degraded state instead of failing to load 2026-09-18 15:06:17 +03:00
Jeremy Grossmann de8e1039a9 Merge pull request #2876 from yueguobin/fix/node-delete-rmtree-race
Make node working directory deletion robust against races and mode mangling
2026-09-15 17:49:19 +02:00
YueGuobin 84e7ead465 fix: make node working directory deletion robust
The rmtree error handler in BaseNode.delete() was chmod'ing the failed
path to S_IWRITE (0o200). On POSIX this strips the search permission
from directories, turning a transient deletion failure into a directory
that can no longer be traversed or deleted. The node deletion itself
silently "succeeds" (rmtree gives up once its error handler returns)
and a later project deletion then fails with EACCES. The handler also
never retried the failed operation, so it did not help on Windows
either (the platform it was written for).

The transient failure exists in practice: a concurrent MD5 checksum
computation caching its result in the node directory (e.g. a properties
request racing the deletion) can recreate a file after rmtree has
listed the directory, making the final rmdir fail with ENOTEMPTY.

- add the missing user permissions instead of replacing the whole mode,
  and retry the failed unlink/rmdir
- retry the whole deletion a few times to absorb files recreated while
  the directory is being deleted
- raise a ComputeError when the directory cannot be fully deleted
  instead of failing silently
2026-09-15 01:23:31 +08:00
Jeremy Grossmann 1c57bd7dca Merge pull request #2875 from yueguobin/feat/docker-image-sync
Sync Docker images from the controller to remote computes
2026-09-13 20:11:03 +02:00
YueGuobin be62e8c022 feat: keep Docker images on computes consistent with the controller host
Only relying on the image name lets a moved tag (e.g. a newer :latest)
silently serve stale content from a compute that already has an image
under the same name. When creating a Docker node, the controller now
pins the image id (Id from the Docker daemon on the controller host)
into the create payload. A compute holding a different image under the
same tag reports the image as missing, which routes it through the
image sync added by the previous commit and re-aligns the tag.

No new template fields or database changes: the controller host daemon
remains the source of truth and the pin is resolved per creation. When
the image is not available on the controller host the pin is omitted
and behavior is unchanged (the compute pulls from the repository).
2026-09-14 00:55:18 +08:00
YueGuobin c477812332 feat: sync Docker images from the controller to remote computes
When a Docker node is created on a remote compute whose Docker daemon
does not have the image, the compute now raises ImageMissingError
instead of blindly pulling from the Docker repository. The controller
exports the image from the Docker daemon on its host (docker save
stream) and streams it to the compute which loads it, so locally built
or docker-loaded images work across computes. When the image is not
available on the controller host either, the compute is asked to pull
it from the Docker repository as a fallback.

- add a POST /docker/images/load compute endpoint that streams a
  docker save tar into the Docker daemon
- let Docker.http_query pass raw (non-dict) request bodies through so
  the tar can be streamed to the daemon
- drop the inline pull from DockerVM.create() and the now unused
  DockerVM.pull_image wrapper
2026-09-14 00:36:54 +08:00
Jeremy Grossmann 2a3626824f Merge pull request #2874 from yueguobin/fix/docker-root-owned-file-reclaim
fix: reclaim root-owned container files so docker nodes and projects can be deleted
2026-09-13 17:19:09 +02:00
YueGuobin 4b239cc11a fix: run the reclaim helper as root regardless of the image's default USER
The one-shot reclaim container inherited the image's baked-in USER:
ghcr.io/nokia/srlinux runs as "user:user", so the "privileged" helper
was exactly as unprivileged as the server itself — chmod/chown on files
written by other uids (srlinux writes as a large internal uid) failed
with EPERM and node/project deletion still broke, just with a different
error. Pass --user 0:0 explicitly so the helper is root no matter what
the image declares, and fix the manual reclaim hint the same way.

Validated live on two stuck srlinux node directories (257/258
foreign-owned entries reclaimed to 0 in ~0.5 s each).
2026-09-12 23:15:52 +08:00
YueGuobin 54d9d7c08f fix: reclaim root-owned container files so docker nodes and projects can be deleted
The stop-time permission pass necessarily runs before the container's
processes exit, so files written during the shutdown window (syslog
archives, trace flushes) and after any SIGKILL path stay owned by root
on the host. An unprivileged server can neither chown nor delete them,
which broke node deletion and project deletion.

Reclaim them through the only privilege door a non-root server has:
a one-shot throwaway container of the node's own image, entrypoint
overridden to the GNS3 busybox (nothing of the guest boots), chowning
the node directory back to the server user. It runs at the end of
close() — project deletion rmtrees the directory right after the nodes
close, so close must leave a clean tree — and as a retry fallback in
delete(). The helper resolves the image by its create-time ID with
--pull=never, so a stale or retagged image name cannot turn into a
registry pull attempt.
2026-09-12 23:04:28 +08:00
Jeremy Grossmann 100cb327bd Merge pull request #2873 from yueguobin/fix/marker-replay-hardening
Marker tag aggregate replay driven by resident sharkd sessions
2026-09-11 19:33:32 +02:00
YueGuobin 673253d848 ci: install sharkd in the test workflow and make manager tests hermetic
The replay tests marked sharkd_present skip gracefully without the
binary, but four manager-level tests (cap eviction, in-use protection,
single spawn under concurrency, filter-error mapping) run entirely
against fakes and died on the acquire-time PATH check instead - install
wireshark-common (which ships /usr/bin/sharkd on the Ubuntu runner) so
the real-engine tests actually run in CI, and patch the which() check in
the fake-session tests so the suite stays green on machines without
sharkd.
2026-09-11 23:49:51 +08:00
YueGuobin 5d91ca0efc fix: harden sharkd replay sessions and serve the uncapped frame list
Review-driven session/transport fixes (each reproduced live against
sharkd 4.6.7 before fixing):

- raise the RPC stream limit to 16 MB: a full 1000-row frames page
  measures ~190 KB against the 64 KB StreamReader default, which failed
  the request with a 500 and desynchronized the resident session; a
  line-over-limit ValueError is now treated as a transport failure
- verify JSON-RPC reply ids: a timed-out request's late reply was
  served as the next request's answer; timeouts, dead pipes, malformed
  and stale replies now kill the session for good instead
- make check-spawn atomic under one manager lock: concurrent requests
  for the same pcap double-spawned sharkd and leaked the loser (process
  plus /tmp scratch copy) forever
- refcount sessions and evict idle only (LRU, cap raised 8 -> 16): a
  tag with more sources than the cap respawned every source on every
  request, and concurrent requests could get their session killed
  mid-RPC (spurious 502)
- map FilterError to sharkd's filter rejection (-13002) only; other
  engine failures with a filter set are 502, not a client 400
- detail: accept an optional frame_number to disambiguate
  same-microsecond frames (ts is not unique within a pcap); drop the
  -8003 -> 404 mapping (the range is validated locally, engine errors
  are real faults); a failed hex read is a 404 instead of "hex": null
- a pcap deleted mid-request is a 404, not a 500; the pcap-sized
  scratch copy runs off the event loop; server shutdown kills every
  resident session and drops its scratch directory
- pin the packet-list layout through scratch-HOME Wireshark
  preferences: the column indexes are a contract the server owns
  (protocol-level column negotiation is rejected by sharkd 4.6.x)

Range contract change (WebUI moved to an always-flat list): the merged
frame list is returned in full, deliberately uncapped - truncated and
per-second buckets are removed, frame_count always equals
len(frames), and rendering cost is the client's concern (the window
endpoint remains the incremental path).
2026-09-11 00:55:18 +08:00
YueGuobin ef5d81498a feat: accept link=<link_id> on the replay range and frames endpoints
Narrows the merged frame stream to one capture source BEFORE counting,
slicing and bucketing (frame_count / frames | buckets all recomputed on
the narrowed set), AND-composing with the display filter. A pure
identity filter applied before any engine work — only the selected
link's pcap gets a sharkd pass, so link+filter is cheaper than filter
alone.

Two boundaries by contract with the Web UI:
- sources[] stays the tag's stable inventory: every capture source
  listed with engine-free TOTAL counts, unaffected by link/filter — a
  source dropdown must not shrink when the view narrows (this also
  settles sources[].count on total counts rather than post-filter
  matches, which no spec ever required)
- an unknown link_id matches nothing: frame_count 0, start null, empty
  frames/buckets — the same shape as a zero-match display filter,
  deliberately not a 404; an empty link param is treated as absent
2026-09-09 00:53:06 +08:00
YueGuobin 31ba82b8d3 docs: record live validation of the sharkd replay endpoints
Real-data examples from a 9-link OSPF project (29 frames): range with
full columns and Wireshark coloring, filter verified in all four regimes
(match / zero-match / invalid 400 with sharkd's text / oversized), window
hit and miss, and a frame detail whose filter_expr carries OSPF's
multicast TTL (ip.ttl == 1) with byte ranges for hex highlighting.

Three precision fixes found by auditing the doc against the code: the
501 applies when the engine is consulted (an empty-capture tag answers
200 without sharkd), sources[].count is post-filter like every other
figure, and the unified {"message": …} error body is now stated.
2026-09-08 22:00:00 +08:00
YueGuobin 790c423c26 feat: drive marker replay with resident sharkd sessions
sharkd (the Wireshark daemon) is now the single decode engine — the
tshark/PDML path is gone, and without sharkd every replay endpoint
returns 501 (no degraded mode: one engine, one rendering shape for the
Web UI).

- Frame entries gain packet-list columns from sharkd's frames RPC:
  src/dst/proto/info plus the Wireshark coloring hints bg/fg
- range and frames accept ?filter=<display filter>, applied before
  counting and slicing; invalid expressions are 400 carrying sharkd's
  original text; filters travel as single argv-style elements, capped
  at 2000 chars; filtered frames keep their original pcap frame numbers
- frame detail returns sharkd's protocol tree with keys renamed into
  the REST contract (element/label/name/filter_expr/pos+size/expert/
  generated/children): a census-verified closed key set, values
  untouched, unknown keys passed through verbatim, Wireshark-internal
  hf ids dropped. filter_expr gives the UI click-to-filter; pos/size
  drives hex highlighting (hex still read straight from the pcap)
- one resident 'sharkd -' session per source pcap: lazy spawn, /tmp
  scratch copy + scratch HOME (hardened profiles), per-request
  (mtime,size) validation with respawn, LRU bound, per-session lock,
  per-RPC timeout, bounded close

Timeline backbone (gate, record-header scan, merge ordering, canonical
ts strings, hex reads) stays plain Python — identity and ordering never
depend on the engine.
2026-09-08 00:04:04 +08:00
YueGuobin 0c540abbf2 fix: stop leaking a global os.kill mock from the shutdown route test
The bare 'os.kill = MagicMock()' was never restored, so every later test
in the same process ran with a no-op kill. Any test that kills a child
process and waits for it then hangs forever (resident sharkd sessions
waiting on an immortal process). Use monkeypatch so the patch is undone.
2026-09-08 00:04:04 +08:00
Jeremy Grossmann fa282e0f82 Merge pull request #2872 from yueguobin/pr/3.1-20260906
feat: iol-runner Docker nodes, marker tag replay and copilot start-node rework
2026-09-05 20:45:03 +02:00
YueGuobin a8c96dd3f7 fix: keep port_number in Docker NIO dispatch of the batch endpoints
The project-open bulk path (_add_nio_binding / _get_existing_nio /
_update_nio_binding in routes/compute/projects.py) dropped port_number
for Docker nodes, unlike the per-node routes and the IOU branch. With
multi-port docker adapters (iol-runner nodes model 4 ports per adapter,
0ca9ccc63) every batched NIO landed on port 0 where Adapter.add_nio()
silently overwrites — the last entry per node won — so reopening a
project clobbered the port-0 links with the port-1 NIOs: links ended up
cross-wired between the wrong node pairs and the real links died
(IOL direct-link ping failures after close/reopen, EXCESSCOLL storms
from the phantom loops).
2026-09-06 00:15:43 +08:00
YueGuobin a8bec35ef0 Merge branch 'feat/copilot-start-quick-wait' into local-test 2026-09-05 22:52:05 +08:00
YueGuobin a841175fbf feat(copilot): make start_gns3_node immediate-return, add wait_seconds tool
The waiting variant blocked on a fixed progress bar (up to 120s) even
when every start command had already failed (e.g. the uBridge >= 1.2.3
409), burying the error behind two minutes of silence. Drop it: the
single start_gns3_node now sends the commands and returns per-node
results immediately (GNS3StartNodeQuickTool kept as an alias). Boot
waiting moves to a dedicated wait_seconds tool the agent calls
explicitly between start and status checks, with a 600s ceiling and
liveness logging every 5s.
2026-09-05 22:52:02 +08:00
YueGuobin 27b55b72f9 fix: keep upstream link-carrier commands off unix-socket NIO bridges
Upstream #2870 added TAP carrier control (set_nio_tap_carrier) and a
busybox interface-status monitor to the Docker base class. Both assume
TAP wiring: unix-socket NIO bridges carry no TAP NIO, so uBridge rejects
the carrier command ('bridge has no TAP NIO') and every link create,
update or delete on a running iol-runner node would fail; the monitor
polls eth{adapter} interfaces that do not exist in the container's
network namespace (or misreports the Docker default eth0 as adapter 0).

VendorDockerVM now short-circuits _set_adapter_carrier and the interface
monitor under GNS3_UNIX_SOCKET_NIO; TAP-wired vendor nodes keep the base
behavior.
2026-09-05 22:21:18 +08:00
YueGuobin e12ef7f272 tests: expect port_number in adapter carrier calls
Upstream #2870's carrier tests assert the two-argument
_set_adapter_carrier call; the 4-port-unit commit threads port_number
through every carrier call site, so single-port adapters now pass 0.
2026-09-05 21:58:45 +08:00
YueGuobin 1adc1b47b7 Merge branch 'feat/iol-docker-startup-config' into local-test 2026-09-05 21:55:51 +08:00
YueGuobin efed973107 Merge branch 'feat/marker-tag-replay' into local-test 2026-09-05 21:55:51 +08:00
YueGuobin 51cb85090d Merge branch 'fix/test-order-freeze-pollution' into local-test 2026-09-05 21:55:51 +08:00
YueGuobin 8892f9dc91 docs: record IOL console typing latency characteristics 2026-09-05 21:54:52 +08:00
YueGuobin e365427d1b docs: spell out IOL startup-config knob consumption in the node environment 2026-09-05 21:54:52 +08:00
YueGuobin 1ccea916c3 docs: roadmap for docker image types (vendor profiles)
Design proposal for an image_type discriminator on Docker templates plus
a compute-side profile registry: vendor parameters graduate from
environment markers into schema-gated fields, generic-feature
applicability becomes declared capability data, existing markers stay as
a compatibility fallback. Explicitly not a new node type.

Four profiles already exist to shape it (iol-runner, XRd, SR Linux
prototype, FRR appliance); implementation follows the current PR series.
2026-09-05 21:54:52 +08:00
YueGuobin e318afef86 feat: ship an iol-xe-base.txt base config for IOL Docker nodes
Follows the IOU pattern: the file lives in gns3server/configs/ and the
controller installs it into the user's configs directory on startup
(never overwriting a customized copy). Referenced by the documented
GNS3_IOL_STARTUP_CONFIG=iol-xe-base.txt template knob — without it a
fresh install had no file for the knob to resolve and nodes booted to
the initial configuration dialog.

Also fixes the configs directory named in the docs (~/GNS3/configs,
the configs_path server setting default — not ~/.config/GNS3/...).
2026-09-05 21:54:52 +08:00
YueGuobin 5685f40dd6 fix: keep payload-delivered state across container (re)creation
create() re-runs _parse_vendor_environment on every (re)create — and a
stop removes the container, so every start recreates it. Resetting the
controller-allocated application id there silently flipped nodes to the
hash fallback after their first stop/start (MAC change, plus collision
risk with the allocation pool), and dropped any pending startup-config
delivered by a PUT.

The application id and startup-config state now default via class
attributes instead of being re-initialized by the parser, and the hash
fallback is removed outright: starting an IOL node without a coordinated
allocation raises an actionable error — an uncoordinated id could
collide with the pool and blackhole traffic as a MAC loop.

Found in the E2E run: node booted app id 512, came back as 566 (hash
fallback) after one stop/start; the PUT-ed config edit vanished the same
way.
2026-09-05 21:54:52 +08:00
YueGuobin 8b3aafbbdc feat: IOU-style startup-config for IOL Docker nodes
Templates reference a config file with the GNS3_IOL_STARTUP_CONFIG
environment knob; the controller materializes the file content into
startup_config_content on node creation (sent once, knob consumed —
the same pattern as the IOU startup_config mapping). The compute builds
the content into the node's nvram_<app id> at the next start using the
IOU nvram_import utility (IOL and IOU share the nvram container format,
verified against iol-xe 17.18.02): valid config at boot, no setup
dialog, %h hostname substitution, hostname rewrite on rename.

Semantics verified against the runner: IOL boots from NVRAM whenever it
holds a config, so a plain stop/start never re-applies the startup
config and 'write memory' survives restarts; an explicit content edit
(PUT) is re-applied on the next start and wins over the saved config,
like IOU.
2026-09-05 21:54:52 +08:00
YueGuobin 9147deccaa docs: document that restarting capture nodes truncates marker pcaps
A marker pcap's lifetime equals its uBridge's lifetime: a fresh uBridge
reinstalls every desired marker (paused ones too — install first, then
turn the filter off) and pcap_dump_open truncates. Server restart +
project reopen without starting nodes is safe until a uBridge comes up
(verified live); Docker nodes restart effectively on server restart via
stale-container cleanup. Recorded in the tag-gate table, a lifecycle
note, and a pcap_dump_open_append follow-up.
2026-09-05 21:54:52 +08:00
YueGuobin a8fa529252 feat: add tag-keyed aggregate replay over paused markers' pcaps
Markers on different links sharing a tag form one distributed capture
session. Once every marker under the tag is paused (409 otherwise), three
read-only endpoints replay it:

- GET .../markers/tags/{tag}/replay/range merges the per-marker pcaps by
  scanning 16-byte record headers only (no tshark) into a timestamp-
  ordered frame list (per-second buckets above a 5000-frame cap)
- GET .../replay/frames?ts=&window_ms= returns frames in [T, T+window];
  an empty window is a normal empty array
- GET .../replay/frame/detail lazily decodes one frame the user opened:
  raw bytes for the hex view read straight from the pcap, protocol tree
  from 'tshark -T pdml' mapped isomorphically to JSON (every attribute
  survives, values stay strings). tshark reads a /tmp scratch copy with a
  scratch HOME — hardened profiles deny it the project directory.

Sort key is (ts, source file, frame number): ts is not unique across a
merge. The ts parameter round-trips as the exact string from the frame
list. Round-trip tests pin the PDML→JSON fidelity (element count and
attribute coverage).
2026-09-05 21:54:52 +08:00
YueGuobin 5c285f631b fix: normalize marker.match event tag to int to match the REST schema
The WS event carried the tag as str (verbatim from the MARK signal) when
present and as int when falling back to the registry, so one tag reached
consumers as two different values. Parse the signal's decimal (the exact
value we installed via 'mark <bpf> tag <id>') and keep the registered int
on malformed input; None only when neither side carries one.
2026-09-05 21:54:52 +08:00
YueGuobin 51b3c81859 fix: make the patched get_default_project_directory order-safe in tests
A product module first-imported while run_around_tests' autouse
monkeypatch of gns3server.utils.path.get_default_project_directory is
active (e.g. 'from gns3server.api.server import app' inside a test body)
binds the patched lambda into its own namespace forever: module-level
from-imports capture the object by value. Once the patch is reverted,
that module keeps calling the stale lambda, which closed over the very
test's tmppath — a directory deleted at that test's teardown. Every
later test hitting psutil.disk_usage(get_default_project_directory())
then fails with FileNotFoundError, but only when the importing test runs
before the API test files (full-suite collection order hides it).

The replacement now resolves Config.instance().settings at call time
instead of closing over the tmppath, so a frozen reference stays
correct; the test that triggered this imports gns3_app at module top
so no product import ever happens inside a patched window.

Also pins pytest-random-order (inert without --random-order) and
documents the order-independence rules for new tests in the
gns3-api-test-writing skill, including the known-red legacy files
whose tests share rows sequentially.
2026-09-05 21:54:52 +08:00
YueGuobin 0119373690 feat: allocate IOL Docker application IDs from a pool disjoint from IOU
IOL interface MACs derive from the application ID (aabb.cc{app}{iface}),
so ids must be unique across opened projects sharing computes — the same
reason IOU has its allocator. IOL Docker nodes draw from the upper half
(512-1022, netiomux's fixed peer is 1023) so the two node types can
neither collide nor starve each other; IOU behavior is unchanged.

The controller sniffs the same GNS3_IOL_RUNNER environment marker the
compute uses to select IOLDockerVM (both the nested-properties and
template/top-level-kwarg shapes), stores the id in node properties like
IOU does, and passes it through the Docker create payload. Without an
allocation the compute falls back to a stable node-derived id in the
same upper range.
2026-09-05 21:54:52 +08:00
YueGuobin b17d021bf6 fix: derive per-node IOL app id so linked routers get distinct MACs
IOL derives interface MACs from its application ID. With a constant
local-app every node shared the same MACs, and linked routers dropped
each other's frames as MAC loops — ARP never resolved and pings were
100% lost even though the whole uBridge datapath was forwarding.

Derive local-app from the node UUID (stable across restarts, kept in
1..1022) and align remote-app with the netiomux convention CML uses
(1023). Verified end to end: two iol-xe nodes, Ethernet0/0 link,
ARP resolves both ways, ping 4/5 (first loss = ARP), graceful
stop/start keeps the NVRAM config.
2026-09-05 21:54:51 +08:00
YueGuobin 0ca9ccc637 feat: model IOL adapters as 4-port units like the IOU node type
IOL interfaces come in 4-port units (Ethernet0/0-3, Ethernet1/0-3, ...),
addressed like IOU as (adapter_number, port_number 0-3):

- IOLDockerVM builds EthernetAdapter(interfaces=4) per adapter and asks
  the runner for adapters x 4 interfaces (num-eth).
- DockerVM threads port_number through the NIO/capture API (the compute
  routes parsed it from the URL but dropped it); single-port adapters
  keep the historical bridge{N} names and command sequence, multi-port
  adapters get one bridge per port (bridge{a}_{p}).
- The unix-socket NIO wiring addresses sockets flat across adapters:
  adapter x ports-per-adapter + port, so single-port images keep their
  exact socket layout.
- The controller port list for GNS3_IOL_RUNNER docker nodes is generated
  by StandardPortFactory with the IOU naming (Ethernet{segment0}/{port0},
  segment size 4); plain docker nodes keep eth{N}.
2026-09-05 21:54:51 +08:00
YueGuobin 9b55164064 revert IOL port-name override; document custom_adapters instead
_get_container_ifname only names the kernel interface inside the
container's network namespace (single call site: docker move_to_ns) -
IOL never uses that path, and the controller port list never reads it.
Name the ports through the template's custom_adapters instead (the
mechanism SR Linux appliances use for mgmt0/e1-1): adapter N shows as
Ethernet{N/4}/{N%4}, matching the IOS CLI, with no server-side changes.
2026-09-05 21:54:12 +08:00
YueGuobin 4c818c6b37 feat: show IOL-style interface names on iol-runner ports
Name ports after the IOL interface they map to (Ethernet0/0, one 4-port
unit per adapter range) via the _get_container_ifname override point, so
the GNS3 UI matches the IOS CLI. Display only — the flat adapter number
remains the socket index.
2026-09-05 21:54:12 +08:00
YueGuobin cd17306372 docs: docker memory is optional for iol-runner nodes
0 (the default) passes through as Docker's no-limit; the IOL-memory+512
guidance only applies when a cap is set.
2026-09-05 21:54:12 +08:00
YueGuobin 28f8f665f7 docs: template creation how-to for iol-runner nodes
API/Web-UI creation steps, a field table with the extra_volumes=/tmp
footgun, and a 3-step verification checklist.
2026-09-05 21:54:12 +08:00
YueGuobin d04a99f934 refactor: wire unix-socket NIOs through a per-node runtime directory
uBridge cannot reach sockets bind-mounted from the node's projects
directory: the path exceeds AF_UNIX's 107-byte sun_path cap. The /proc
detour from the previous commit is a dead end too - the runner drops
from root to the server uid, which makes the process non-dumpable and
its /proc/<pid>/root unreadable for the unprivileged server.

Instead, mirror how CML itself runs the image (source=<scratch>/tmp,
target=/tmp in its node definition): bind a per-node directory from the
runtime directory (<XDG_RUNTIME_DIR>/gns3/unixio/<node-id>, next to the
uBridge control sockets) at the image's socket directory. The path is
short, the directory is owned by the server user (whom the agent drops
its privileges to), and it is removed with the node. A socket directory
covered by a persisted volume keeps working as before.

IOLDockerVM persists only /tmp/run (nested bind at /tmp/run) and cleans
stale sockets/netio dirs from the socket directory on start, skipping
the cleanup when the container is already running. A failed wiring now
stops uBridge so the next start does not hit 'bridge already exist'.
2026-09-05 21:54:12 +08:00
YueGuobin 165f271bb8 refactor: reach unix-socket NIOs through the container root in /proc
The unix-socket NIO no longer requires the socket directory to be a
persisted volume: uBridge references the sockets through
/proc/<container-pid>/root<dir>/..., which is always well under the
107-byte sun_path cap (a project directory path alone exceeds it) and
leaves the sockets ephemeral in the container's own filesystem.

This replaces the runtime-dir symlink alias and its cleanup, and the
mount-time volume enforcement. IOLDockerVM now persists only /tmp/run
(the IOL working directory: startup-config + NVRAM) as a nested bind
instead of the whole /tmp; stale socket cleanup is gone with it, as
containers are recreated on every start.
2026-09-05 21:54:12 +08:00
YueGuobin 42e26717e6 fix: alias long unix-socket NIO paths through the runtime dir
AF_UNIX sun_path caps at 107 bytes and node volume directories
(projects/<uuid>/project-files/docker/<uuid>/tmp) exceed it — uBridge
rejects the NIO with 'invalid file path size'. When the wiring path is
too long, create <XDG_RUNTIME_DIR>/gns3/unixio-<node-id> as a symlink
to the real volume directory (same trick as the uBridge control
socket) and reference the alias in the uBridge commands; the symlink is
removed when uBridge stops. Found during E2E with iol-xe:17-18-02.
2026-09-05 21:54:12 +08:00
YueGuobin e272ad915b feat: add IOL (iol-runner) Docker node support
Run Cisco CML containerized IOL images (e.g. iol-xe/iol-xe:17-18-02,
driven by virl.lab/cmd/iol-runner) as GNS3 Docker router nodes:

- VendorDockerVM: generic GNS3_UNIX_SOCKET_NIO/GNS3_UNIX_SOCKET_DIR knobs
  wiring adapters through AF_UNIX datagram socket pairs
  (add_nio_unix cNN.sock sNN.sock) instead of TAP + move_to_ns; node
  creation fails if the socket dir is not a persisted volume.
- IOLDockerVM (GNS3_IOL_RUNNER=1): forces skip-init + unix-socket NIO +
  /config,/tmp volumes, writes iol-config.json on every start (num-eth
  tracks adapters, runner drops to the server uid/gid so the sockets are
  reachable), pre-creates tmp/run, cleans stale sockets after unclean
  kills, and makes reload a graceful stop + full start (NVRAM flush +
  rewiring). Console stays telnet on PID 1 stdio.
- Manager selects the node class from console_type or GNS3_* environment
  markers (create-time, like console_type).
- Image-free tests (25) and feature documentation.
2026-09-05 21:54:12 +08:00
YueGuobin d4f2a429f4 docs: document that restarting capture nodes truncates marker pcaps
A marker pcap's lifetime equals its uBridge's lifetime: a fresh uBridge
reinstalls every desired marker (paused ones too — install first, then
turn the filter off) and pcap_dump_open truncates. Server restart +
project reopen without starting nodes is safe until a uBridge comes up
(verified live); Docker nodes restart effectively on server restart via
stale-container cleanup. Recorded in the tag-gate table, a lifecycle
note, and a pcap_dump_open_append follow-up.
2026-09-05 21:49:24 +08:00
YueGuobin 49c8a72103 fix: make the patched get_default_project_directory order-safe in tests
A product module first-imported while run_around_tests' autouse
monkeypatch of gns3server.utils.path.get_default_project_directory is
active (e.g. 'from gns3server.api.server import app' inside a test body)
binds the patched lambda into its own namespace forever: module-level
from-imports capture the object by value. Once the patch is reverted,
that module keeps calling the stale lambda, which closed over the very
test's tmppath — a directory deleted at that test's teardown. Every
later test hitting psutil.disk_usage(get_default_project_directory())
then fails with FileNotFoundError, but only when the importing test runs
before the API test files (full-suite collection order hides it).

The replacement now resolves Config.instance().settings at call time
instead of closing over the tmppath, so a frozen reference stays
correct; the test that triggered this imports gns3_app at module top
so no product import ever happens inside a patched window.

Also pins pytest-random-order (inert without --random-order) and
documents the order-independence rules for new tests in the
gns3-api-test-writing skill, including the known-red legacy files
whose tests share rows sequentially.
2026-09-05 21:49:24 +08:00
YueGuobin c646d6df5a feat: add tag-keyed aggregate replay over paused markers' pcaps
Markers on different links sharing a tag form one distributed capture
session. Once every marker under the tag is paused (409 otherwise), three
read-only endpoints replay it:

- GET .../markers/tags/{tag}/replay/range merges the per-marker pcaps by
  scanning 16-byte record headers only (no tshark) into a timestamp-
  ordered frame list (per-second buckets above a 5000-frame cap)
- GET .../replay/frames?ts=&window_ms= returns frames in [T, T+window];
  an empty window is a normal empty array
- GET .../replay/frame/detail lazily decodes one frame the user opened:
  raw bytes for the hex view read straight from the pcap, protocol tree
  from 'tshark -T pdml' mapped isomorphically to JSON (every attribute
  survives, values stay strings). tshark reads a /tmp scratch copy with a
  scratch HOME — hardened profiles deny it the project directory.

Sort key is (ts, source file, frame number): ts is not unique across a
merge. The ts parameter round-trips as the exact string from the frame
list. Round-trip tests pin the PDML→JSON fidelity (element count and
attribute coverage).
2026-09-05 21:49:24 +08:00
YueGuobin 9262dcfaef fix: normalize marker.match event tag to int to match the REST schema
The WS event carried the tag as str (verbatim from the MARK signal) when
present and as int when falling back to the registry, so one tag reached
consumers as two different values. Parse the signal's decimal (the exact
value we installed via 'mark <bpf> tag <id>') and keep the registered int
on malformed input; None only when neither side carries one.
2026-09-05 21:49:24 +08:00
Jeremy Grossmann b72b8b44b4 Merge pull request #2870 from cristian-ciobanu/docker-link-status
feat: Add Docker link carrier and interface status support
2026-09-04 20:52:13 +02:00
Cristi 5d08cc92a4 fix: Fix failing tests and adress the MCP 2.x incompatibility failures 2026-09-04 17:37:36 +03:00
Cristi 28f0d9c009 feat: Add Docker link carrier and interface status support 2026-09-04 09:45:41 +03:00
Jeremy Grossmann d1b4de6b8f Merge pull request #2868 from yueguobin/feat/template-delete-usage-guard
feat: forbid deleting templates and images still used by projects
2026-08-31 19:03:28 +02:00
Jeremy Grossmann 20819f35ae Merge pull request #2867 from yueguobin/fix/controller-console-ws-disconnect-traceback
fix: tear down controller console WebSocket forwarding cleanly on client disconnect
2026-08-31 19:02:02 +02:00
YueGuobin 823cf37287 fix: list every project in template/image in-use refusal, not just the first
The usage scans broke out of the whole (project, node) iteration at the
first matching node, so deleting a template or image used by several
projects reported only one project name while the error message says
'one or more projects'. Keep scanning and list each project once.

Caught on a live server: an IOU L3 template used by two projects
(one of them closed) was refused citing only one of them.
2026-08-31 23:04:00 +08:00
YueGuobin eed981fee3 fix: tear down controller console WebSocket forwarding cleanly on client disconnect
Closing a web console while the node kept streaming output crashed the
ws_console/vnc_console handlers with an uncaught WebSocketDisconnect from
the compute-to-client send path (only the opposite direction was guarded),
producing a full ASGI traceback on every console close.

Restructure both endpoints as symmetric forwarding tasks managed with
asyncio.wait(FIRST_COMPLETED): exceptions from either direction are
collected as task exceptions, the peer task is cancelled, the compute
WebSocket is closed, and the client is notified. The receive loops now
close and log on every exit path instead of only in the exception branch.

Tests patch the in-memory ASGI transport to deliver a conformant
websocket.disconnect on client close (it sends a non-conformant
websocket.close that starlette receive() rejects).
2026-08-31 22:43:41 +08:00
YueGuobin 13548deae8 feat: forbid deleting templates and images still used by projects
Deleting a template with prune_images, deleting an image, or pruning
orphan images only checked template references — a project node still
pointing at the image (e.g. via hda_disk_image_backing_file) was left
with a dangling reference and the project could no longer be opened.

- Add controller helpers scanning every known project (opened projects
  via in-memory nodes, closed projects via their .gns3 file) for
  template and image usage; unreadable topologies are skipped
- Guard DELETE /templates/{id}, DELETE /templates/{id}?prune_images,
  DELETE /images/{path} and /images/prune with a 409 listing the
  project names
- Run all template-delete checks before any mutation so a refused
  deletion cannot leave the template gone while its images survive
2026-08-31 22:30:42 +08:00
grossmj 861b7e86ff fix: publish-api-documentation.yml 2026-08-31 12:28:03 +02:00
grossmj ed20118f86 Development on 3.1.0.dev6 2026-08-31 11:45:34 +02:00
Jeremy Grossmann 375fc8af81 Merge pull request #2864 from yueguobin/fix/console-ws-ticket
fix: issue short-lived access tickets instead of JWTs in MCP tools
2026-08-29 21:07:12 +02:00
YueGuobin 3cf9dbff5b fix: handle client disconnect in compute console WebSocket forwarding
The compute-side telnet_forward (and vnc_forward) let the
WebSocketDisconnect that starlette raises from send_bytes once the peer
is gone escape to the generic task-exception handler. Its str() is
empty, so every client disconnect during active node output logged a
message-less warning:

  WARNING gns3server.compute.base_node:658 Exception while forwarding
  WebSocket data to TELNET server:

Catch WebSocketDisconnect in both forwarders and log it at INFO as the
normal end of a session, and format the remaining task exceptions with
!r so their type stays visible. Mirrors the controller-side fix for
the same scenario (2324dcd74).
2026-08-29 10:09:05 +08:00
Jeremy Grossmann cf00a4e863 Merge pull request #2863 from yueguobin/docs/busybox-ifup-cidr-trap
docs: document the BusyBox ifup CIDR trap in the docker init path
2026-08-28 22:02:58 +02:00
Jeremy Grossmann c42ac6e559 Merge pull request #2862 from yueguobin/fix/console-ws-client-disconnect
fix: handle client disconnect in console WebSocket forwarding
2026-08-28 22:00:59 +02:00
YueGuobin f95d4c7a4e fix: update link_capture_download and symbol_get tool descriptions for tickets
The tool descriptions still advertised the removed "short-lived JWT"
and gave no guidance against URL reconstruction. Align them with
node_console's wording: run the returned curl_command verbatim, never
rebuild the URL or copy the ticket by hand, re-call the tool once the
10-minute ticket has expired.
2026-08-29 01:13:33 +08:00
YueGuobin d1edfbe5e8 fix: replace Bearer JWTs with path-bound access tickets in MCP download tools
link_capture_download and get_symbol embedded a 10-min JWT in the
Authorization header of the curl command they return; LLM clients
retyping that command corrupted the long token — the same failure
class as the console WebSocket URLs fixed in the previous commit.

Generalize the ticket store (console_tickets.py -> access_tickets.py,
ConsoleTicketService -> AccessTicketService): a ticket now binds to
either a node's console endpoints (WebSocket, matched against route
path params) or one exact REST resource path (capture file, symbol
image). The two binding modes are isolated — a node-bound ticket
cannot authenticate a REST resource and vice versa.

get_user_from_token redeems path-bound tickets through the existing
token parameter / Bearer header, matched exactly against
request.url.path, then reuses the shared user lookup and token_version
revocation checks. Download URLs embed ?token=<ticket> and the curl
commands no longer carry a Bearer header.
2026-08-29 01:10:19 +08:00
YueGuobin 6d6b5351fa fix: issue short-lived console tickets instead of JWTs in node_console MCP tool
LLM clients transcribing the console WebSocket URL into shell commands
reliably corrupted the ~200-char JWT embedded in it (dropped header
segment -> "MissingAlgorithmError: Missing 'alg' value in header" on
every connection attempt). The node_console tool now mints a short
random ticket ("gns3t_" + 16 urlsafe chars, 10 min TTL, multi-use)
stored server-side and bound to the node's console endpoints:

- new ConsoleTicketService (gns3server/services/console_tickets.py),
  in-memory store with lazy expiry sweeps
- get_current_active_user_from_websocket redeems tickets through the
  existing "token" query parameter, gated on websocket.path_params so a
  ticket only authenticates the console/ws and console/vnc routes of
  the node it was minted for; the JWT path is unchanged
- redemption reuses the existing user lookup, token_version revocation
  and is_active checks, so logging out invalidates outstanding tickets
- vnc_url no longer embeds the full session JWT
- the tool docstring now tells clients to run the returned command
  verbatim instead of reconstructing the URL
2026-08-29 01:00:12 +08:00
YueGuobin 2324dcd744 fix: handle client disconnect in console WebSocket forwarding
The compute-to-client forwarding loops in ws_console and vnc_console had
no WebSocketDisconnect handling: when a client (WebUI, or an MCP-driven
websocat session killed by timeout) disconnected while the compute was
still streaming console output, the next send raised WebSocketDisconnect
that leaked all the way up to uvicorn as an ERROR-level ASGI traceback.

Catch it and log at info level, symmetric with the receive-side handlers.
2026-08-28 23:35:33 +08:00
YueGuobin c3cc067eea docs: document the BusyBox ifup CIDR trap in the docker init path
BusyBox ifup — what runs in /gns3/init.sh unless the image ships its
own ifupdown — only brings up 'auto' stanzas and rejects CIDR notation
in the address line ("don't have all variables for <iface>/inet"),
leaving the interface unconfigured after a container restart.

Document the constraint next to the ifup call and in the generated
/etc/network/interfaces sample, where addressing gets written.
2026-08-28 23:26:24 +08:00
Jeremy Grossmann ae317608e8 Merge pull request #2861 from yueguobin/refactor/gns3-client-and-mcp-fixes
refactor: sink shared REST handlers into gns3_client + MCP regression fixes
2026-08-25 19:28:43 +02:00
YueGuobin df25e037ea fix: accept the 'local' compute id in compute tools
The compute_get/compute_images MCP tools typed compute_id as a UUID, so
passing 'local' (the actual id of the built-in compute, which the
compute_images description itself pointed to) was rejected by schema
validation. Both tools now take a string defaulting to 'local', and the
compute_get REST route resolves 'local' through the controller since the
local compute has no database entry.
2026-08-26 00:44:57 +08:00
YueGuobin 6703e50487 fix: unify the device tool error contract
The device tools reported failures in three shapes: topology-level
entries with only an error key, per-device entries with status 'error'
plus the reason under output (VPCS tool only), and raw exceptions
leaking out of template rendering. Every in-band error entry now
carries status 'failed' and an error message, and invalid Jinja2
templates are reported in-band instead of escaping the handler.
2026-08-26 00:39:38 +08:00
YueGuobin 2951af6eab fix: reject non-VPCS nodes in the VPCS config tool
VPCS syntax typed into another node's console is silently discarded
(IOS answers % Invalid input) while the tool still reports success.
get_device_ports_from_topology now carries the GNS3 node type through
to callers, and VPCSCommands fails device preparation with a per-device
error unless the node type is vpcs.
2026-08-26 00:36:47 +08:00
YueGuobin 8a8314ab29 fix: dedupe and report automatic template creation from images
install_appliances_from_image relied on the name+version pair check in
TemplatesService, so the same appliance reached through a second image
(the CSR1000v case) created a second template sharing the name. The auto
path now skips when any template with the same name exists, whatever the
version, and returns a manifest of created and skipped candidates;
POST /images/install replies 200 with that manifest instead of an empty
204, and the image_install MCP tool surfaces it.
2026-08-26 00:04:57 +08:00
YueGuobin 888afdccbd fix: return the created template from appliance install
POST /appliances/{id}/install replied 204 with an empty body, so the MCP
appliance_install tool crashed with 'Expecting value: line 1 column 1'
while the template had actually been created. The route now returns the
created template (201, response_model=schemas.Template), _create_template
propagates it, and the MCP handler parses the body defensively so an
empty reply degrades to a plain success message.
2026-08-25 23:39:38 +08:00
YueGuobin 73e5e27c7b fix: keep default node naming aligned with batch submission order
The controller assigns default names (R-1, R-2, ...) and console ports
in request arrival order. A parallel batch fan-out lets thread scheduling
decide that order, so the first submitted node could end up as R-2.
Batches that rely on default naming (any node without a name) are now
created sequentially; batches with explicit names stay parallel. The
node_create tool description documents the ordering semantics and tells
callers to correlate nodes by node_id.
2026-08-25 22:22:08 +08:00
YueGuobin 636abde16c fix: keep node file content byte-faithful in node_file_get
Splitting the file with keepends=False and rejoining with newlines
dropped the trailing newline of the last line (and every \r of CRLF
files), so returned content was shorter than the file on disk and did
not round-trip. Split with keepends=True and join the selected lines
verbatim; pagination semantics are unchanged.
2026-08-25 21:33:21 +08:00
YueGuobin 57b5baed7f fix: keep submission order and unify status in MCP batch handlers
Batch node/link creation collected results with as_completed, so the
response order followed completion rather than the submitted array and
callers could not correlate entries. Collect in submission order via
pool.map, and report batch deletes as status=success like every other
batch action (the message still says what was deleted).
2026-08-25 21:32:09 +08:00
YueGuobin c9bc635996 fix: propagate 405 when suspending a node without suspend support
Suspending a single VPCS/IOU node returned a fake 204: the controller
route swallowed the compute 405 that the node types honestly raise, so
callers saw success while the node stayed started. Surface the 405
instead. The best-effort swallow on suspend_all is kept (and now covered
by a test) since mixed projects legitimately contain always-running node
types.
2026-08-25 21:29:53 +08:00
YueGuobin 97e7a79117 fix: report empty projects as not locked
GET /projects/{id}/locked returned True for a project with no drawings
or nodes: both loops ran zero times and the fallback return won. Locking
and unlocking such a project always succeeded while the state stayed
"locked", so it could never be unlocked.

Report a project with nothing to lock as not locked, and re-check the
state after unlock in the route tests.
2026-08-25 13:45:36 +08:00
YueGuobin f31bfffefc feat: expose data_link_type on the link_marker MCP tool (create-only)
Per-link markers on serial links need the WAN encapsulation (e.g.
DLT_C_HDLC) so the BPF compiles against the right link layer — the
REST API already accepts it, but the MCP tool never forwarded it.
Create passes it through; update ignores it (changing it would
invalidate the capture file), matching the REST schema semantics.
2026-08-25 13:29:39 +08:00
YueGuobin 9e4edc8a8a chore: disable symbol MCP tools for now
Symbol tools (symbol_list/get/dimensions/defaults/upload/delete) require
a vision-capable model to be genuinely useful — they shuttle SVG
content, which a text-only LLM cannot inspect or produce. The tool
registrations and imports are commented out (handlers stay in
symbols.py); revisit when multimodal support is worked out.
2026-08-25 13:22:59 +08:00
YueGuobin 702fc1f6d9 fix: never allow the projects directory to become a project directory
Loading a .gns3 placed directly in the projects root registered the
shared projects directory as the project path (load_project derives
the path from the file's parent directory). Deleting such an entry ran
rmtree on the projects directory itself, wiping every project until a
root-owned file stopped it, and left a zombie entry in the controller.

Three layers of protection:

- Controller.load_project() refuses a .gns3 whose parent directory is
  the projects directory; the normal subdirectory layout is unaffected
- the Project.path setter rejects the projects directory itself and
  its ancestors, closing the same hole for POST/PUT with an explicit
  path
- Project.delete() uses realpath + commonpath instead of commonprefix:
  entries whose path is the projects root are refused, and sibling
  directories sharing a string prefix (/srv/projects-evil vs
  /srv/projects) are no longer treated as inside the projects dir

Also removes the project_load MCP tool: loading by raw server
filesystem path is a footgun for automated clients; projects can still
be opened by project_id via the remaining tools.
2026-08-25 13:17:37 +08:00
YueGuobin 629bb9194f refactor: sink shared REST handlers into gns3_client, drop gns3fy wrappers
- Slim custom_gns3fy.py to connector-only Gns3Connector and rename to
  connector.py; delete the unused Node/Link/Project dataclasses and
  endpoint wrapper methods (~3000 lines)
- Move the MCP node/link handler implementations into
  gns3_client/api_handlers.py as the shared REST client layer consumed
  by both the MCP service and copilot tools; add available_filters
  handler (exposed as link_available_filters MCP tool) and
  build_gns3_ctx() for copilot callers
- Rewrite the tools_v2 node/link tools on top of the handlers: batch
  lifecycle actions now run in parallel, node creation is a single
  POST, project-wide status reads replace per-node GETs
- Port Project.nodes_inventory/links_summary aggregation into
  project_inventory.py (output shape preserved) and rewrite the
  topology reader / project info tools on it, dropping the unused
  stats/snapshots/drawings calls
- Delete the dead mcp/nodes.py and mcp/links.py (NODE_TOOLS/LINK_TOOLS
  had no consumers; __init__ imports handlers from api_handlers)
- Retarget mcp handler tests to patch api_handlers._get_connector and
  replace test_custom_gns3fy.py with inventory contract tests
2026-08-25 09:15:32 +08:00
Jeremy Grossmann 006102c1af Merge pull request #2860 from yueguobin/feat/project-gns3file-endpoint
api: serve the project .gns3 topology file
2026-08-24 20:07:12 +02:00
YueGuobin 1649fb7b7a api: add endpoint serving the project .gns3 topology file
GET /v3/projects/{project_id}/gns3file returns the raw .gns3 file as
application/json so the WebUI can render topology thumbnails without
opening the project. Adds a public Project.topology_file property.
2026-08-24 22:19:09 +08:00
Jeremy Grossmann 9a0501936c Merge pull request #2859 from yueguobin/feat/config-study
feat: add server settings API (GET/PUT /v3/settings)
2026-08-24 14:53:58 +02:00
Jeremy Grossmann 87e23a6819 Merge branch '3.1' into feat/config-study 2026-08-24 14:36:06 +02:00
YueGuobin 317f4d2406 docs: clarify the default admin credentials only seed the database
The default_admin_username/password descriptions now state that the
values are applied when the controller database is created and only
take effect again after it is re-created (resetting the account).
2026-08-24 01:12:48 +08:00
YueGuobin 4dcde5df59 docs: document settings schema metadata in the settings API doc
Field descriptions, defaults and validation bounds are exposed
via the OpenAPI schema, letting clients render the settings form
without a hand-maintained field table; the annotated config
sample is the human-readable reference.
2026-08-24 00:45:29 +08:00
YueGuobin 27ffc1e7a6 fix: type optional configuration fields as Optional
secrets_dir, certfile and certkey were typed FilePath/DirectoryPath
with a None default, and several str fields (jwt_secret_key,
iourc_path, resources_path, default_nat_interface, vboxmanage_path,
vmrun_path) had the same mismatch. Serializing the unset values
emitted PydanticSerializationUnexpectedValue warnings on every
GET /v3/settings (two lines per request with SSL disabled).
2026-08-24 00:42:48 +08:00
YueGuobin b7dbf45a90 docs: add field descriptions to the settings schemas
Document all 70 configuration fields with pydantic Field
descriptions, ported from the config sample comments and verified
against the actual consumers (allow_remote_console and local had
no documentation anywhere). The descriptions flow into the
OpenAPI schema of GET /v3/settings, giving the Web UI tooltips,
defaults and validation bounds from a single source. Response
models re-declare six path fields as plain strings, which drops
the inherited description — restore them explicitly.

Sync the config sample: document local and allow_remote_console,
drop hardware_virtualization_check which no longer exists in the
schema.
2026-08-24 00:35:26 +08:00
Jeremy Grossmann d7a1bf9b7b Merge pull request #2858 from yueguobin/refactor/mcp-to-agent-dir
Move MCP service to agent package + fix auto_close forwarding
2026-08-23 18:00:11 +02:00
YueGuobin 05fa4ec376 docs: document server settings API and add API test writing skill
Move the server settings roadmap to implemented/ rewritten per
the documentation standard (architecture and PUT flow diagrams,
endpoint table, design notes). Add a skill covering the pytest
conftest fixture model and the shared-client order-dependency
trap hit while writing the settings tests.
2026-08-23 18:54:38 +08:00
YueGuobin e0962a59ed feat: add GET/PUT /v3/settings server settings API
GET returns all settings sections except the deprecated
VirtualBox/VMware ones (Server.Audit privilege); secrets are
masked and Controller.jwt_secret_key is excluded entirely.
PUT applies a partial update (Server.Modify privilege): masked
or empty secrets mean unchanged, null removes the option, the
response carries the new values plus restart_required, and a
settings.updated notification is emitted. New
Server.Audit/Server.Modify privileges are seeded into the
Administrator role at table creation.
2026-08-23 18:54:31 +08:00
YueGuobin 7d3cbf1023 feat: add config read-modify-write update and harden file watcher
Config.update_config() applies submitted options to the main
configuration file via configparser read-modify-write: unknown
options are preserved, null removes an option, the merged view
of all files is validated as ServerConfig before anything is
written (a bad file would kill the FileWatcher polling loop),
and the write is atomic (.tmp + os.replace, mode 0600). Options
whose effective value is owned by a later configuration file
raise ConfigConflictError instead of writing a no-op. The
reload logic is factored into reload_and_notify() and the file
watcher callback is exception-guarded so polling never dies.
2026-08-23 18:54:23 +08:00
YueGuobin d3ceb453a6 fix: forward auto_close in create_project_handler
The MCP project_create tool has passed auto_close=False since 8f8abe410
(2026-06-13), but create_project_handler only forwarded {"name": name}
to the REST API — auto_close was silently dropped and the controller's
Project.__init__ default (True, unchanged since 2016) won. Every project
created via MCP since June has auto_close=true on disk and closes when
the last client disconnects.

- projects.py: forward auto_close when present in params
- test_handlers.py: assert the forwarded json_data (with and without
  auto_close)
- test_tool_params.py: the tool/handler param consistency test never
  actually checked anything — three blind spots now fixed:
  1. dispatch is asyncio.to_thread(_run_handler_sync, ...) whose
     node.func is an Attribute, not a Name — no call ever matched
  2. tools that build 'params' as a variable before passing it were
     skipped; now the initial dict literal is resolved (extra-passed
     direction only)
  3. tool functions are async defs (ast.AsyncFunctionDef) but the
  enclosing-function lookup only matched ast.FunctionDef, so tool_name
  was always None
  Also: map the two marker handlers missing from HANDLER_FILES, skip
  handlers that forward params.items() generically (wildcard), union
  passed keys across multi-branch dispatches (node_create single/batch),
  and drop two dead helpers.

Verified: full suite 1568 passed; reverting the handler fix turns both
test_tool_handler_param_consistency and test_create red.
2026-08-23 08:57:39 +08:00
YueGuobin 641d10177a refactor: move MCP service from api/routes to agent package
MCP is an optional AI feature that already depends on
agent.gns3_copilot (Gns3Connector, nornir/netmiko tools) and whose
MCP_AVAILABLE feature flag lives in gns3server/agent. Moving it there
collocates all AI features under one tree and removes AI code from the
core REST routes.

- git mv gns3server/api/routes/mcp -> gns3server/agent/mcp (no content changes)
- api/server.py, core/tasks.py: update import paths
- tests: tests/api/routes/mcp -> tests/agent/mcp, rewrite patch BASE and
  handler imports; fix MCP_DIR depth in test_tool_params.py
- agent/__init__.py: probe the SDK via importlib.import_module so the
  top-level name "mcp" is not bound in the agent namespace (it would
  shadow the new gns3server.agent.mcp subpackage and break
  'from gns3server.agent import mcp')
- docs: update source file paths

Verified: full suite 1567 passed; 82 MCP tools registered, SSE mounted
at /v3/mcp/transport.
2026-08-22 19:32:13 +08:00
Jeremy Grossmann 770c898ec1 Merge pull request #2857 from yueguobin/feat/skills-device-topics
feat: appliance v8 install, copilot device integration, console terminal size and misc fixes
2026-08-21 20:53:28 +02:00
YueGuobin e98c51889e fix: notification ping starved under sustained event load
NotificationQueue.get only generated a synthetic ping when the queue
was idle for the full timeout. Under sustained event load (e.g. a
project with markers matching at 15-260 events/s) the queue never
idled, so compute notification streams never carried a ping and the
controller stopped emitting compute.updated: clients lost compute
statistics until the event flow paused or the server restarted.

A ping is now guaranteed at least every timeout seconds regardless of
event flow: when the ping deadline is reached the next get() returns a
ping ahead of queued events (pings only carry statistics, so skipping
ahead of real events is harmless). Both the compute stream (compute
CPU/memory/disk stats -> compute.updated) and the controller stream
(idle keepalive) benefit.
2026-08-22 00:50:49 +08:00
YueGuobin c709d74826 fix: compute notification stream silently died on uncaught exceptions
Two exception paths could permanently kill the compute notification
chain (no more compute.updated events, no reconnection until a server
restart):

- connect() only caught ComputeError, but _run_http_query translates
  HTTP status errors (401/403/404/...) into sibling ControllerError
  subclasses (and a raw fastapi HTTPException for unexpected statuses).
  Those escaped the fire-and-forget connect() task started at controller
  startup and died silently. Now they notify clients, schedule an
  exponential-backoff retry, and still re-raise for explicit callers.
  The dead web.HTTP* except branches (never reached since
  _run_http_query converts HTTP errors itself) are removed.

- _connect_notification() only caught aiohttp.ClientError. A malformed
  frame (e.g. missing 'action') or any error raised while dispatching a
  compute event (e.g. a pydantic ValidationError in
  node.parse_node_response) escaped the task, skipped the reconnect
  scheduling placed after the try block, and killed the stream forever.
  Now any exception is logged with its traceback (the gather() future
  holding it was never retrieved, so nothing was ever printed) and the
  reconnect scheduling + final compute.updated emit live in the finally
  block so every exit path recovers.

Also moves the usage-stats reset before the disconnect log line so the
emitted compute.updated snapshot is consistent.
2026-08-22 00:36:24 +08:00
YueGuobin 89d7f866cb docker: replace vendor SKIP_INIT exec volume bridge with create-time direct binds
The SKIP_INIT volume bridge replicated init.sh's seed + mount --bind script
via docker exec *after* the container started. That copied the mechanism but
not the invariant that makes init.sh safe — the entrypoint position, which
guarantees the volume is in place before the application runs. The exec runs
concurrently with the NOS boot, so whether the NOS loaded its persisted
config or the overlay's factory copy was a timing race:

- single node stop/start on an idle system won it (exec ~1s, SR Linux reads
  its startup config at ~2-4s) — the save/stop/start round-trip passed;
- a server restart + project reload lost it (concurrent node starts queue on
  the Docker API, delaying the exec by seconds) — SR Linux booted factory
  while the persisted config.json sat intact on the host;
- XRd was immune (systemd boots tens of seconds before XR touches
  /xr-storage), which is why the race was never observed on it.

Replace the bridge entirely:

- new DockerVM._prepare_volumes hook (no-op in the base class) runs in
  create() after the image is present, before the container is created;
  VendorDockerVM overrides it to seed each volume's host directory from the
  image (throwaway docker create container + docker cp -a, nothing
  executes). The .gns3_perms marker gates the seeding: a volume that ever
  started is never re-seeded, so saved configuration is never overwritten
  with factory content (also the upgrade path for existing nodes).
- VendorDockerVM._mount_binds now binds the volumes directly at their real
  in-container paths (/etc/opt/srlinux) instead of /gns3volumes aliases, so
  the persisted config is visible to the NOS from the very first process.
- _setup_skip_init_volumes and its start() call are gone; the container-side
  _fix_permissions targets the volume paths directly (the direct binds
  exist for the whole container lifetime, unlike the old bridge).

The volume-list computation (validation + overlap de-duplication) moves
into DockerVM._persistent_volume_list so create-time seeding and _mount_binds
cannot drift apart.
2026-08-22 00:09:13 +08:00
YueGuobin 6aeb5dbda5 feat(copilot): device skills per-topic split layout and topic retrieval
SkillsLoader.load_device_skills() now supports two device layouts: the
existing single file and a split directory (device/<device>/_base.yaml +
one YAML per protocol topic). Topic files are merged into the device
skill under 'topics', keyed by their 'topic' field; mismatched
device_type, missing _base.yaml and duplicate topics are handled with
explicit log-and-skip.

get_skill() and DeviceSkillsTool gain a 'topic' parameter following the
injection list -> index -> issue pattern. Topic bodies are never
returned without an explicit topic request - index/summary/full all
serve a topic index instead - so growing a device with new protocol
topics no longer grows the token cost of device-level lookups.

Also fix reload_skills() to actually drop injection skills that fail
validate_skill_format() instead of logging 'skipping' and merging them
anyway.
2026-08-21 21:41:51 +08:00
YueGuobin 8d8b2c9692 docs: terminal geometry, WS size forwarding, GNS3_CONSOLE_RESIZE
docker-exec-console.md gains a "Terminal geometry and size forwarding"
section: the WS binary control-frame protocol ({"cols","rows"} -> NAWS /
asyncssh resize), the tall 511x10000 default and when it is applied or
restored, the exec-creation race handling, the GNS3_CONSOLE_RESIZE=0
knob for paging CLIs, and the SR Linux flicker root cause with the
measured numbers (rows-driven ~2.4x output inflation on CPR-answering
clients; width-independent; sr_cli's scroll-append re-rendering is
inherent and identical outside GNS3).

vendor-nos-xrd.md: the appliance recipe now includes
GNS3_CONSOLE_RESIZE=0 with the rationale (shared exec + XR pager vs
browser resizes). New troubleshooting entry for the flicker symptom.
2026-08-21 21:41:51 +08:00
YueGuobin 65e8eb9e28 docker: don't lose a client size that races the exec creation
A browser's terminal-size control frame (NAWS through the console telnet
server) can arrive while client_connected_hook is still creating the
exec; the resize is a no-op then, and the tall default applied after
creation would overwrite it, leaving the session at 511x10000 until the
user resizes.

Record sizes received before the exec exists and prefer them over the
tall default once creation finishes. The recorded size is cleared when
the last client disconnects, together with the restore-to-default.
2026-08-21 21:41:51 +08:00
YueGuobin 5741e85b65 docker: add GNS3_CONSOLE_RESIZE knob for paging CLIs
The exec behind a docker_exec console is shared by every console client,
so a browser's terminal-size resize (WS control frames -> NAWS) also
changes the geometry concurrent netmiko sessions see. SR Linux doesn't
care (no pager, no hard wrapping), but CLIs that page on the PTY window
size (IOS-XR) would park at --More-- again the moment a browser is
connected.

Split the client-driven NAWS path (_on_naws) from the internal resize
(_resize_exec): GNS3_CONSOLE_RESIZE=0 makes the console ignore client
resizes entirely and keep the tall 511x10000 no-paging default, while
the creation-time default and the restore-on-last-disconnect still go
through the internal path. XRd appliance templates should set it.
2026-08-21 21:41:51 +08:00
YueGuobin abd0b8e274 console: forward client terminal size over the console WebSocket
The docker_exec console defaults its exec PTY to 511x10000 (the no-NAWS
default that keeps the IOS-XR pager quiet for netmiko). A CPR-answering
client (xterm.js) on top of that tall canvas makes prompt_toolkit-based
CLIs (SR Linux sr_cli) re-emit their accumulated output on every
incremental render: ~145 KB instead of ~60 KB per command, visible in
the WebUI as full-screen clear/redraw flicker.

Let WebSocket console clients propagate their real terminal geometry:
binary frames {"cols": N, "rows": M} alongside text frames carrying
terminal data. The controller forwards binary frames (previously only
text was forwarded), and the compute side turns them into a NAWS
subnegotiation for telnet-based consoles (docker_exec included) or an
asyncssh pty size change for SSH consoles.

The docker_exec console restores the tall 511x10000 default when its
last client disconnects, so a later non-NAWS client (netmiko, bare
telnet) connecting to the still-live exec doesn't inherit a browser
geometry and hit PTY-window paging again.
2026-08-21 21:41:51 +08:00
YueGuobin 5188ae625a tests: pick a free console port instead of hardcoding 5011
A dev machine running a real gns3server (or qemu) can already listen on
5011; reserve_tcp_port then silently replaces it with the next free port
and test_console fails on the exact-echo assertion. Pick a port that is
actually free on the host first, like test_change_console_port does.
2026-08-21 21:41:51 +08:00
YueGuobin 72dc10a669 controller: allow markers and packet filters on Ethernet switch links
The brctl Ethernet switch runs a per-port uBridge relay, so it can host
the mark filter and packet filters like any uBridge-backed node. Add
ethernet_switch to _MARKER_CAPABLE_TYPES and _get_filter_node, narrow the
UDPLink.update() NIO-PUT skip down to the Dynamips-hosted ethernet_hub,
and expose the matching compute endpoints: PUT nio (filter/marker
reapply) plus the per-marker toggle/pause/resume/delete/rebuild routes.

The ethernet_hub keeps its exclusion: its routes still wire into the
Dynamips hub, which has no uBridge of its own.
2026-08-21 21:41:51 +08:00
YueGuobin 210103058f docker: don't recreate containers on empty-string property PUTs
Web clients serialize empty form fields as "" while unset values are
stored as None on the node. The bare != diff in the update handler then
sees a phantom change on every full PUT and recreates the container for
nothing -- even when the user only changed a controller-only field such
as netmiko_device_type.

Normalize at the schema boundary ("" -> None for start_command,
environment and extra_hosts; "" -> "/" for console_http_path), make
the setters apply the same canonicalization, and create nodes through
the setters instead of bypassing them in __init__ so both paths store
identical values.
2026-08-21 21:41:47 +08:00
YueGuobin c3145a9f65 mcp: don't run API keys through JWT validation
_resolve_token tried the JWT path before checking for the gns3_ prefix,
so every API-key connection logged a spurious "JWT rejected" ERROR from
get_token_data. Check the prefix first, and downgrade the JWT-rejected
log to WARNING — a rejected token is a client problem, not a server one.
2026-08-21 21:41:47 +08:00
YueGuobin 200ccf0dfe mcp: fingerprint short-lived console tokens for copy-corruption checks
node_console_info now returns token_sha256_prefix (sha256, first 8 hex
chars) and token_ttl_seconds alongside the console WebSocket URL, and
controller WebSocket auth rejections include the sha256 prefix of the
token as received. Comparing the two immediately distinguishes a token
corrupted in transfer from server-side rejection causes (expired,
revoked, bad signature).
2026-08-21 21:41:47 +08:00
YueGuobin 704b5d80c2 auth: split JWT validation errors by failure cause
get_token_data used to raise the same "Could not validate credentials"
for every JWT-level failure (bad signature, expired, malformed), which
made console WebSocket auth failures impossible to tell apart. Return a
distinct detail per cause and log the underlying exception plus the
unverified header alg value on rejection.
2026-08-21 21:41:47 +08:00
YueGuobin fd7594f62e docker: give the docker_exec console a tall default PTY geometry
The docker_exec console resized its exec PTY to 80x24 until a client
sent NAWS. CLIs that page on the PTY window size instead of the
terminal length (the IOS-XR pager) therefore parked long output at
--More-- for clients that never negotiate NAWS — netmiko, bare telnet —
making copilot device commands time out on XRd.

Default the exec to 511x10000 instead (511 matches netmiko's own
'terminal width 511' convention): no paging and no hard wrapping for
non-NAWS clients, while real NAWS clients keep resizing to their actual
geometry as before.

Also updates the project memory record with the confirmed root cause
and the fix.
2026-08-21 21:41:46 +08:00
YueGuobin 2b81160570 docs: record the XRd console --More-- pager bug in project memory
Root cause (confirmed live): the XRd console reaches the container CLI
via docker exec, and the XR pager reads the exec PTY's 24-row window
(TIOCGWINSZ) instead of the CLI-level terminal length — so
'terminal length 0' shows in 'show terminal' yet long-output commands
page after exactly 24 lines and park at --More--, making netmiko time
out. '| no-more' does not exist on IOS-XR.

Also documents the agreed copilot-side fix design (tail-anchored
--More-- detection with quiet double-confirmation, reconnect before
retry, session_log), for the upcoming feat/copilot-xrd-more-handling
branch.
2026-08-21 21:41:42 +08:00
YueGuobin 19f20e8d75 copilot: log into devices using the node default credentials
The vendored gns3fy Node model dropped default_username/default_password
from the API response, and the nornir groups hardcoded empty
credentials, so drivers that require authentication (gns3_ruijie_telnet,
stock netmiko SSH/telnet) could not log in.

Carry the per-node credentials through nodes_inventory() into the
nornir hosts data at host level, where they override the group's empty
fallback. Missing or cleared ("") values keep inheriting from the
group, so no-auth drivers are unaffected.
2026-08-21 21:41:42 +08:00
YueGuobin 38742ad4b6 tests: sign class-scoped client tokens with the default JWT secret
Since aef337e86 the config loader generates a random JWT secret even
without a main config file, so the class-scoped client/authorized_client
fixtures signed their tokens with a key that the autouse
run_around_tests fixture would immediately replace with the default
one for every test function. Every controller API test using those
fixtures was failing with 401 (BadSignature).

Sign both fixtures explicitly with DEFAULT_JWT_SECRET_KEY to match
the secret enforced at request time.
2026-08-21 21:41:42 +08:00
YueGuobin 7e8c515a3c api: expose installed netmiko device types for the web UI
New GET /v3/netmiko/device_types endpoint returns the device types
supported by the netmiko library installed on the server, including
the gns3-copilot custom drivers, so the web UI can populate the
netmiko_device_type dropdown on templates and nodes.

The list is read at runtime from netmiko's ssh_dispatcher.CLASS_MAPPER
registry (the same table ConnectHandler dispatches on), filtered to
drop the '_ssh' aliases and the 'autodetect' pseudo type, and cached
for the process lifetime. Returns 501 when netmiko is not installed
(ai-features extra).
2026-08-21 21:41:42 +08:00
YueGuobin 92d4e3d378 nodes: per-node default credentials seeded from the template
Add default_username/default_password as controller-only node properties
(the netmiko_device_type pattern): they are not sent to the compute,
persist with the project topology and can be updated or cleared per
node. Creating a node from a template seeds them from the template
appliance metadata, and the metadata itself is dropped there so it
never leaks into the node properties.
2026-08-21 21:41:42 +08:00
YueGuobin 300c53e6fb templates: persist appliance metadata on install
Appliance fields that describe the appliance (vendor information, default
credentials, installation instructions...) were dropped when installing a
template. Keep them in a new appliance_metadata JSON column on the
templates table, filled by the appliance-to-template conversion for both
registry v1-6 and v8 (version level values override the appliance level
ones). The nested schema allows extra fields so future registry fields
persist without a migration.
2026-08-21 21:41:42 +08:00
YueGuobin 1c68a52856 fix: address appliance v8 install review findings
- install: resolve the image directory from the version's settings type and
  skip image handling for docker appliances; guard appliance.images
- appliance schema: validate template_properties against template_type,
  align cpu_throttling with the qemu template, add kvm and version idlepc
- conversion: map IOU image to path, kvm disable to accel=tcg, inherit only
  same-type default settings, symbol fallback from the effective category,
  template_properties cannot override structural fields
- allow clearing netmiko_device_type with an empty string
- download the template symbol regardless of the level it is defined at and
  give qemu guests a default symbol
2026-08-21 21:41:42 +08:00
YueGuobin 435aa4c257 copilot: prefer netmiko_device_type over the device_type:<type> tag
The vendored gns3fy Node model and its nodes_inventory() now carry the
node's netmiko_device_type field, and get_device_ports_from_topology()
resolves the Netmiko device type from it first, falling back to the
device_type:<type> tag. Nodes created from a template inherit the value
from the template automatically, so automation tooling gets the correct
Netmiko driver without tags.
2026-08-21 21:41:35 +08:00
YueGuobin f524e9a713 appliance: seed netmiko_device_type from the appliance file
Both the v1-6 and v8 appliance models accept an optional top-level
netmiko_device_type, and ApplianceToTemplate copies it into the created
template so installed appliances carry the automation hint end to end.
2026-08-21 21:41:35 +08:00
YueGuobin d64f47afa4 nodes: per-node netmiko_device_type (controller-only)
netmiko_device_type follows the CONTROLLER_ONLY_PROPERTIES pattern
(like console_auto_start): a node created from a template inherits the
template value, PUT /nodes can override it inside a topology, updates
never round-trip to the compute, and the value persists in the project
topology file.
2026-08-21 21:41:35 +08:00
YueGuobin 9260108f53 templates: add netmiko_device_type for automation tools
Common template field (schema + templates table column + Alembic
migration) holding the Netmiko device type (e.g. 'cisco_xr', 'nokia_srl')
so Netmiko/Nornir based tooling can look up how to reach a node's CLI
without hard-coded vendor mappings. Free-form lowercase string on
purpose: Netmiko's platform list evolves independently of GNS3.
2026-08-21 21:41:35 +08:00
YueGuobin 254721dbda appliance: close the v8 gaps for Docker vendor appliances
DockerPropertiesV8 now accepts custom_adapters (already available to
v1-6 top-level appliances and to Qemu v8 properties), so port-named
Docker appliances (XRd, SR Linux) can move to the v8 format without
losing their interface naming.

Appliance.type resolves the node type from the v8 settings template_type
(default set first) instead of misclassifying every v8 appliance as
qemu, and _get_default_symbol applies the docker guest symbol to v8
Docker guest appliances.
2026-08-21 21:41:35 +08:00
YueGuobin 57fe549773 appliance: implement install support for registry version 8
new_template() now converts the v8 settings[] format per the spec in
gns3-registry#734: settings selection (version name reference, then the
default set, then a single set), inherit_default_properties merging, and
template_properties expansion with category/usage/symbol resolved from
template_properties > version > appliance levels. Undefined properties
are left out so controller template defaults apply.

Registry versions 1-6 keep the existing top-level emulator block path.
2026-08-21 21:41:35 +08:00
grossmj 582412bac3 Release v3.1.0a5 2026-08-19 18:06:12 +02:00
grossmj 51c6440403 Bundle web-ui v3.1.0a5 2026-08-19 17:57:42 +02:00
grossmj 08d7ba6bd0 chore: upgrade dependencies 2026-08-19 17:44:38 +02:00
grossmj 52de01523f Merge branch '2.2' into 3.1
# Conflicts:
#	gns3server/compute/builtin/nodes/cloud.py
#	gns3server/utils/interfaces.py
2026-08-18 18:05:56 +02:00
grossmj 9db55cafec Merge branch 'master' into 2.2 2026-08-18 18:03:56 +02:00
grossmj c85551ec09 Sync appliances 2026-08-18 18:02:53 +02:00
Jeremy Grossmann a3e85b7041 Merge pull request #2853 from hjicks/master
add support basic support for OpenBSD.
2026-08-18 18:01:15 +02:00
Jeremy Grossmann 80a69814b3 Merge pull request #2854 from yueguobin/code-review-fixes
docker: vendor NOS containers (XRd, SR Linux) as first-class nodes; UDP port race fix
2026-08-15 18:24:13 +02:00
YueGuobin f43a717b20 copilot: sync CONSOLE_TYPES with the server ConsoleType enum
The vendored gns3fy copy keeps its type lists as literals (the module is
shared with the standalone MCP service and cannot import server enums),
and CONSOLE_TYPES had drifted: 'ssh' and 'docker_exec' were missing while
both are valid server-side. Impact: the copilot topology reader validates
the whole node list in one pydantic pass, so a single vendor NOS node
(console_type 'docker_exec') made it drop the entire project and return
zero devices to every copilot device tool.

Add the missing values plus drift tests asserting the vendored lists
cover the server enums (skipped when ai-features extras are absent).
2026-08-15 23:32:24 +08:00
Guobin Yue 74a51a1f9f Merge branch '3.1' into code-review-fixes 2026-08-15 22:39:42 +08:00
Jeremy Grossmann 74191e7a8c Merge pull request #2855 from cristian-ciobanu/3.1
feat: Enhance information displayed on the system status dashboard
2026-08-14 23:33:47 +02:00
Cristi a35df76384 feat: Enhance information displayed on the system status dashboard 2026-08-14 23:36:03 +03:00
YueGuobin 110e041e56 docker: cap GNS3_STOP_TIMEOUT at 210 s (controller stop budget)
The 600 s clamp was unreachable in practice: the controller's stop
request times out at 240 s (controller/node.py) and the Docker stop
query gets the value +30 s as its HTTP timeout, so anything above 210
would abort upstream first and surface an error while the stop keeps
running server-side. Cap at the derived ceiling and document the chain
in the clamp and the docstring.
2026-08-15 01:25:50 +08:00
YueGuobin 9604c85fda docker: harden the shm/devices/extra_configs/masking work (code review)
Nine fixes from a review of the docker-shm-devices diff:

* GNS3_STOP_TIMEOUT >300 s aborted at the manager's default HTTP timeout
  before Docker finished the stop — the stop query now gets a timeout
  with a margin over the grace period.
* Overlapping bind targets (GNS3_MASK_UDEV + GNS3_MASK_SYSTEMD on the
  same unit, a unit named twice, an extra_configs target equal to a
  masked unit) made Docker reject the create with 'Duplicate mount
  point' — Mounts are deduplicated by target.
* ExtraConfig.target now carries a pydantic validator (absolute file
  path, no '..'), so bad targets 422 at template-save time instead of
  failing at node-create time after a multi-GB image pull; directory
  forms ('/', '/etc/') are also rejected by the runtime guard instead
  of raising IsADirectoryError (raw 500).
* _check_host_readiness skipped every remaining check when one
  /proc/sys key was unreadable (mid-loop return) — now continues.
* The base-class GNS3_* env parser strips trailing commas like the
  vendor parser, so 'GNS3_MASK_UDEV=1,' composed from a list still
  activates.
* Vendor env knobs are re-parsed on every create(), so a PUT to the
  node's environment takes effect on the next (re)create.
* The graceful SIGTERM stop is now limited to the explicit user stop
  route; delete/update/close/crash-cleanup keep the immediate kill
  (those paths force-delete or recreate the container right after).
* An extra_configs target beneath a persisted volume is shadowed by the
  volume bind — warn at create time.
2026-08-15 00:52:55 +08:00
YueGuobin 1124d7a539 docs: XRd appliance tunes GNS3_STOP_TIMEOUT to 40 s; note version-agnostic template image 2026-08-15 00:09:53 +08:00
YueGuobin 62076c1727 docker: make the vendor graceful-stop grace period configurable (GNS3_STOP_TIMEOUT)
The 60 s SIGTERM grace was hardcoded, unlike every other vendor knob
(GNS3_SHM_SIZE, GNS3_DEVICES, GNS3_MASK_UDEV, ...) which rides the
environment line. Parse GNS3_STOP_TIMEOUT=<seconds> (default 60,
clamped to 1-600, invalid values keep the default) and use it in
VendorDockerVM._terminate_container().
2026-08-14 22:11:34 +08:00
YueGuobin e9339faaa7 docker: graceful stop for vendor NOS containers (SIGTERM + 60s grace)
DockerVM.stop() terminated containers with an immediate SIGKILL — fine
for init.sh-based containers whose state is persisted beforehand, but a
systemd NOS (Cisco XRd, SR Linux) needs a graceful shutdown and treats
the abrupt kill as an unclean shutdown (exit 137 on every stop).

Extract the final termination into _terminate_container() and override
it in VendorDockerVM: POST /containers/{id}/stop?t=60 sends SIGTERM and
waits for systemd to stop services; Docker itself SIGKILLs the
container once the grace period expires, so no fallback is needed.
Docker's 304 (already stopped) is swallowed.
2026-08-14 22:02:58 +08:00
YueGuobin 350f2b24e7 fix: UDP port allocation race causing link self-loop (one-way links)
PortManager.get_free_udp_port had an unguarded find-then-add sequence.
A link allocates both ends concurrently (asyncio.gather in
UDPLink._prepare -> two POST /ports/udp) and FastAPI runs the sync
route handler in a threadpool, so both threads could probe the same
'free' port before either recorded it — handing lport == rport to both
ends. uBridge sets SO_REUSEADDR on UDP NIO sockets, so the double bind
succeeds silently and the kernel delivers everything to the last-bound
socket: one node starves, the other echoes to itself.

Make every TCP/UDP allocate/reserve/release path atomic with an RLock,
and rebuild _link_data in UDPLink._prepare so reset() commits the fresh
port pair instead of re-sending the stale, already-released one.

Regression tests: threaded barrier allocation never returns duplicates
(red on the old code, UDP and TCP); reset() leaves exactly one mirrored
NIO pair per side with lport != rport (red on the old code).
2026-08-14 21:31:58 +08:00
YueGuobin 1cddeb8c3f docs: record the link UDP self-loop bug; mark XRd datapath validated
Add bugs/link-udp-self-loop.md: the intermittent one-way docker link
observed during XRd validation (one end's nio_udp rport pointing at its
own lport after a uBridge restart), with the evidence table, the uBridge
console capture diagnostics, the delete/recreate workaround, and the
narrowed suspects (batch port preallocation / link re-creation race).
Also note that a docker node's in-container ethN is a TAP device held by
uBridge (no veth host end exists).

Update the XRd feature doc: datapath validated end-to-end (XRd brings
its own interfaces up, ARP/ICMP bidirectional), add a troubleshooting
row pointing at the bug doc. Index the bug in docs/README.md.
2026-08-14 19:50:58 +08:00
YueGuobin 0f12786885 docs: document the XRd control-plane adaptation
New feature doc covering why XRd takes the vendor docker_exec/SKIP_INIT
path (init.sh wrapper crashes its glibc loader), the four generic
mechanisms added for it (GNS3_SHM_SIZE/GNS3_DEVICES HostConfig injection,
extra_configs file injection, GNS3_MASK_UDEV + udevadm null-binding,
host-readiness check), the three host-disturbance root causes isolated by
plain docker-run A/B/C testing, the appliance recipe with XRd-specific
gotchas (Mg0/RP0/CPU0/0, /xr-storage-shadow persistence, first-boot
semantics), and troubleshooting. Indexed in docs/README.md alongside the
docker-exec-console base doc.
2026-08-14 19:14:59 +08:00
YueGuobin e8b51aa12c docker: also null-bind udevadm in GNS3_MASK_UDEV
Masking the udev systemd units stopped the daemon's coldplug (host audio
resets), but host USB devices still reconnected on every XRd start. A/B
testing with plain `docker run` isolated the trigger: XRd's own
xr_startup.sh calls udevadm directly (USB license-dongle probing, e.g.
`udevadm trigger --action=add --parent-match=<usb device>`), which
synthesizes uevents into the host kernel from the privileged container --
no udevd required.

GNS3_MASK_UDEV=1 now also binds /dev/null over the udevadm binary
(/bin, /sbin, /usr/bin). Verified with a plain-run experiment: with the
bind, host udev monitor shows zero usb/input/hid/sound events during XRd
boot (only normal docker veth traffic), and XRd itself boots to running
state -- it does not need udevadm under GNS3 (interfaces are pre-created
veths).
2026-08-14 19:09:48 +08:00
chara 80da7da515 add support basic support for OpenBSD.
there remains some work on ubridge, but this seems to work so far.
2026-08-13 22:24:58 +03:30
YueGuobin b928a2f48a docker: use the container's chown (not busybox) in vendor volume/perms path
The vendor skip-init path (_setup_skip_init_volumes, _fix_permissions) runs
`/gns3/bin/busybox chown` inside the container via docker exec. busybox is
statically linked, and its chown dlopens NSS modules (libnss_*) from the
container; on NOS images whose glibc differs from the host's (e.g. Cisco
XRd) that mismatches and aborts with the glibc assertion
`_dl_call_libc_early_init: sym != NULL` (SIGABRT). The per-file chown loop
then crash-loops, and the resulting core-dump storm -- processed by the
host's systemd-coredump -- cascades into host device rescans, reconnecting
USB / resetting audio / corrupting the journal on every XRd start.

cp/chmod/find/stat don't touch NSS and work fine on busybox, so only chown
is affected. Prefer the container's own coreutils chown
(`command -v chown && chown ...`), falling back to busybox chown only when
the container ships no chown (minimal images, where the glibc matches and
busybox is safe).
2026-08-14 01:27:18 +08:00
YueGuobin 347537f1b3 docker: mask systemd-udevd in privileged containers (GNS3_MASK_UDEV)
A privileged systemd-based NOS container (Cisco XRd boots /usr/sbin/init)
runs systemd-udevd, which on startup coldplugs every device it can reach.
In privileged mode that includes the HOST's USB/input/audio/disk devices,
so every XRd start reconnects USB, mutes audio, and disrupts the host
journal -- highly disruptive on Linux desktops (caught in the act: the
container's udevd was even rescanning the host BTRFS root device).

XRd doesn't need udev (its interfaces are pre-created by GNS3 veth and
mapped via XR_INTERFACES). Add two opt-in env vars, consumed host-side at
container create time in the inherited DockerVM.create (so VendorDockerVM
nodes get it too):

  GNS3_MASK_UDEV=1        -> bind /dev/null over the udevd unit, its two
                             activation sockets, and the coldplug/settle
                             trigger services
  GNS3_MASK_SYSTEMD=u1,u2 -> bind /dev/null over arbitrary units in
                             /etc/systemd/system/ (comma/semicolon list)

Only injected when set, so ordinary nodes are unaffected.
2026-08-14 01:12:21 +08:00
YueGuobin 088f1da77a docker: persist extra_configs in the template DB table
The extra_configs schema field needs a column on the docker_templates table
to actually round-trip through the controller DB (the schema alone is
accepted but dropped by the SQLAlchemy model mapping). Add the JSON column
and an Alembic migration so existing databases get it on upgrade.
2026-08-14 00:20:08 +08:00
YueGuobin 08e37a4509 docker: inject config files into containers via extra_configs
Add an `extra_configs` field (list of {target, content}) to the docker
node/template/appliance schemas. For each entry GNS3 writes `content` to a
file in the node working directory and bind-mounts it read-only at `target`
inside the container.

This lets a NOS appliance seed its startup config without rebuilding the
image: XRd points XR_FIRST_BOOT_CONFIG at an injected /firstboot.cfg, FRR at
/etc/frr/frr.conf, etc. The bind is a single-file mount applied at create
time, so it works for both the generic init.sh path and vendor nodes that
skip init.sh (console_type=docker_exec). Entries are only injected when
present, so ordinary nodes are unaffected.

The content can't go through `environment` (it is line-delimited, one var per
line), hence a dedicated field -- the same plumbing shape as extra_volumes.
2026-08-13 23:33:34 +08:00
YueGuobin 2bee34031c docker: warn about low inotify/file-max and missing FUSE at connect
Add a read-only _check_host_readiness() that runs once after the Docker
daemon connection is established. It reads /proc/sys inotify/file-max
limits and /proc/filesystems (for FUSE), and logs a warning with the exact
commands to fix when they are too low for heavy containers -- XRd wants
~4000 inotify instances per node against a stock default of 128.

The server runs unprivileged (only the setuid ubridge helper has root), so
it can only check, not set; the warning tells the admin exactly what to
raise once. Stays silent when the limits are already sufficient.
2026-08-13 22:39:48 +08:00
YueGuobin 86d30f34b4 docker: inject /dev/shm size and host devices via HostConfig from env
Heavy NOS containers (e.g. Cisco XRd) need /dev/shm larger than Docker's
64 MB default and host device nodes such as /dev/fuse. Add two opt-in
environment variables, consumed host-side and applied as native Docker
HostConfig keys at create time:

  GNS3_SHM_SIZE (MB)  -> HostConfig.ShmSize (bytes)
  GNS3_DEVICES        -> HostConfig.Devices in `docker run --device` syntax
                         (host[:container[:perm]]; Docker resolves major/minor
                         from the host node itself)

Native HostConfig (rather than remount/mknod inside init.sh) is used so this
works for vendor NOS nodes that skip init.sh (console_type=docker_exec) --
the path XRd must take, since GNS3's init.sh wrapper crashes XRd's glibc
loader. It applies whether or not init.sh runs, needs no schema/API/UI
change (reuses the `environment` field), and only takes effect when the vars
are set, so ordinary nodes keep default Docker behaviour.

GNS3_-prefixed user env vars stay dropped from the container environment
(only consumed here host-side), keeping GNS3-injected vars safe.
2026-08-13 22:39:48 +08:00
Jeremy Grossmann f65d9b17c6 Merge pull request #2851 from yueguobin/fix/docker-node-create-setattr-noise
fix: suppress redundant console port setter log during Docker node create
2026-08-12 23:02:49 +02:00
Jeremy Grossmann c588652768 Merge pull request #2852 from yueguobin/docker-srlinux-support
Support vendor NOS Docker containers: docker_exec console + SR Linux integration
2026-08-12 22:49:05 +02:00
YueGuobin 64657918b5 docs: appliance packaging section + symbol theme caveat
Document the SR Linux gns3a (35-adapter full chassis, matching
GNS3_INTERFACE_NAMES + custom_adapters), the three server-side schema fixes
needed for it to load (DockerConsoleType.docker_exec,
ApplianceV1_6.custom_adapters, extra_volumes docker-block passthrough), and
the symbol-theme behaviour that rewrites any :/symbols/-prefixed symbol to
the category default at load time (so router_cloud.svg cannot be used from
an appliance; use a custom symbol under symbols_path instead).
2026-08-13 02:05:17 +08:00
YueGuobin 9e830f7883 appliance: expose custom_adapters on the v1-6 appliance model
The top-level ApplianceV1_6 model declared first_port_name /
port_name_format / port_segment_size but not custom_adapters, so the
GET /appliances endpoint (response_model=schemas.Appliance) stripped
custom_adapters from the response — the frontend never saw per-adapter
port names even though the appliance file and the server-side template
conversion (appliance_to_template reads it from the raw dict) handled it.

Add custom_adapters: Optional[List[CustomAdapterItem]] to ApplianceV1_6
so the field round-trips through the API. (ApplianceV8 already models it
inside its TemplateSetting.)
2026-08-13 02:05:17 +08:00
YueGuobin 141b3d8701 appliance: accept docker_exec console type in Docker appliances
The Docker appliance Pydantic model (DockerConsoleType) rejected
console_type='docker_exec', so an appliance file using the vendor NOS
docker_exec console could not be loaded (validation error at import).
Add docker_exec to the enum — it is already a valid ConsoleType
(schemas/common.py) and is handled by VendorDockerVM.
2026-08-13 02:05:17 +08:00
YueGuobin 8889cea38b fix: recreate docker_exec console on reconnect after CLI exit
The reconnect-blank-screen bug: when sr_cli exited (quit / idle timeout /
crash) the while-true wrapper restarted it mid-session with no client
attached, so its startup CPR probe (\e[6n) went unanswered and the TUI
degraded/blocked. On reconnect lazy_started=True skipped recreation, so the
client saw a blank screen.

Fix: drop the while-true wrapper. Now when the CLI exits, the exec pty
closes (EOF), the broadcast task ends, and the next client connection
detects the dead upstream via _upstream_alive() and recreates the exec —
with a terminal attached, so CPR is answered. A live exec is reused
(just a Ctrl-L redraw).

_LazyExecTelnetServer is extracted from a closure to module level so the
reconnect/recreate logic is unit-testable. Add 9 tests covering
_upstream_alive states and the recreate-on-death / reuse-if-live /
close-half-dead-writer / no-while-true behaviors.

Full Docker suite (120) passes.
2026-08-13 02:05:17 +08:00
YueGuobin 1e154ac85f test: add tests for VendorDockerVM and the docker_exec factory
25 tests covering:
- Docker.create_node factory: selects VendorDockerVM iff console_type ==
  docker_exec, DockerVM otherwise (including telnet/ssh/vnc/http/none/spice)
- GNS3_* env parsing: SKIP_INIT, INTERFACE_NAMES, CONSOLE_CMD (single and
  multiline), defaults
- create(): init.sh skipped under GNS3_SKIP_INIT, prepended otherwise;
  GNS3_MAX_ETHERNET follows the interface rename; /etc/network mount dropped
  under SKIP_INIT (and host skeleton dir removed) but kept without it
- _add_ubridge_connection: move_to_ns targets the renamed interface
  (mgmt0) or falls back to eth{N}
- start(): docker_exec console dispatch + SKIP_INIT volume bridge + permission
  fix; without SKIP_INIT the vendor passes are skipped
- _fix_permissions: skips dead/missing containers (no restart), targets
  /gns3volumes bind-mount paths
- _setup_skip_init_volumes: runs the docker exec bridge script
- _cleanup_console_resources: closes the exec pty writer

Full Docker suite (111) and compute suite (395) pass — the four hook
extractions in DockerVM introduce no regressions.
2026-08-13 02:05:17 +08:00
YueGuobin f5554d816a vendor: drop the hardcoded /etc/network mount for SKIP_INIT containers
Override _mount_binds in VendorDockerVM: for GNS3_SKIP_INIT containers the
/etc/network volume (GNS3's own network config consumed by init.sh's ifup)
is dead weight — init.sh never runs and the NOS manages its own
interfaces. The override removes the bind, filters /etc/network out of
self._volumes (keeping GNS3_VOLUMES and the bridge/fix passes consistent)
and deletes the host-side skeleton directory created by the base class.
Without GNS3_SKIP_INIT the mount is kept, matching base behaviour.
_persistent_volumes() is removed — the mount override is now the single
filter point.
2026-08-13 02:05:17 +08:00
YueGuobin 46e863b975 vendor: skip /etc/network in volume bridge and permission passes
GNS3_SKIP_INIT containers never run init.sh, so /etc/network (GNS3's own
network config consumed by init.sh's ifup) has no consumer — the NOS
manages its own interfaces. VendorDockerVM._persistent_volumes() filters it
out for both _setup_skip_init_volumes and _fix_permissions, saving one
docker exec per pass. The shared _mount_binds is untouched, and without
GNS3_SKIP_INIT the full volume list is returned so behaviour matches the
base class.
2026-08-13 02:05:17 +08:00
YueGuobin 486c5cc1cb docs: runtime ownership safety and boot-ordering caveat
Document why host-user ownership of volume files during runtime is
harmless for SR Linux (root processes, self-healing daemons like aaamgr
rewriting its managed files, ACL-based access) and the deviation from the
standard init.sh model, with the escape hatch of dropping the start-time
fix pass for strict-ownership NOS images.

Also document the boot-ordering caveat: the volume bridge comes up after
the NOS boots, so early boot reads overlay defaults — verify the
save/stop/start closed loop, and add troubleshooting entry #10 for config
present on the host but not applied after restart.
2026-08-13 02:05:17 +08:00
YueGuobin 6f852c83fd docs: explain mid-run Permission denied warning for boot-written NOS files
Document the aaamgr_local_user.json case: SR Linux's aaamgr daemon rewrites
the file during boot as the image's srlinux user (uid 1002) after the
start-time permission pass, leaving it unreadable until the stop-time pass.
Trace the warning to the file-browser API chain (Show in file manager ->
list_node_files -> magic.from_file) and note the impact is limited to the
file_type field.
2026-08-13 02:05:17 +08:00
YueGuobin 3455da7da3 fix: run _fix_permissions container-side on /gns3volumes mount targets
The host-side pass could not work for unprivileged GNS3 processes: the
.gns3_perms marker is created root-owned by the container-side touch, and
chowning root-owned files from the host requires root.

Rewrite VendorDockerVM._fix_permissions to run the busybox
record/chmod/chown script inside the container (as root) on the
/gns3volumes bind-mount targets — they exist for the container's whole
lifetime and do not depend on the mount --bind bridge, so a container
restart can no longer make the fix hit the overlay copy. A
stopped/exited container is skipped (logged) instead of restarted; the
next start's pass fixes ownership.
2026-08-13 02:05:17 +08:00
YueGuobin 2f36471a55 fix: host-side permission fix + SKIP_INIT volume persistence docs
Replace the container-side _fix_permissions for vendor NOS containers with a
host-side pass that walks the node's project directories directly (they are
the Docker bind-mount sources): records mode:uid:gid into .gns3_perms and
chowns to the GNS3 user. No docker exec, no container restart — the base
implementation restarts an exited container just to chown, and after the
restart the mount --bind bridge is gone so it would fix the overlay copy
instead of the host files.

The pass runs at start (after _setup_skip_init_volumes seeds and bridges the
volumes) so the controller can read project files while the node runs, and
again at stop for files written during runtime.

Update docker-exec-console.md: VendorDockerVM architecture, hook points,
class-selection factory, volume-persistence lifecycle, and new
troubleshooting entries.
2026-08-13 02:05:17 +08:00
YueGuobin 5388fd3796 refactor: move vendor NOS Docker support into VendorDockerVM subclass
Extract the docker_exec console and GNS3_* prototype knobs (SKIP_INIT,
INTERFACE_NAMES, CONSOLE_CMD) from DockerVM into a VendorDockerVM subclass.
DockerVM is restored to its 3.1 baseline plus four small extension hooks
(_prepare_init_and_interface_env, _start_console_server,
_get_container_ifname, _cleanup_console_resources) that are pure
refactorings with zero behaviour change for existing nodes.

VendorDockerVM additionally replicates init.sh's volume persistence
(bind-mount /gns3volumes over the in-container path) via docker exec for
containers that skip init.sh, so vendor NOS config (e.g. /etc/opt/srlinux)
survives node stop/start.

The Docker manager selects VendorDockerVM when console_type == docker_exec;
all other nodes keep using DockerVM unchanged.
2026-08-13 02:05:17 +08:00
YueGuobin 511c52330b docker_exec console: wrap exec command in while-true loop so sr_cli restarts on quit 2026-08-13 02:05:17 +08:00
YueGuobin 486178d05c docs: document the docker_exec console and vendor NOS Docker knobs 2026-08-13 02:05:17 +08:00
YueGuobin 474dc1db64 Prototype: vendor NOS Docker node support (SR Linux etc.) — docker_exec console via Docker exec API (pty + hijacked HTTP + NAWS resize) 2026-08-13 02:05:17 +08:00
Guobin Yue abaddec6df Merge branch '3.1' into fix/docker-node-create-setattr-noise 2026-08-12 12:44:39 +08:00
grossmj 1988768d32 fix: update CI configuration to use a single OS and remove Windows-specific dependencies 2026-08-11 19:23:18 +02:00
Jeremy Grossmann 0763ec3bd4 Merge pull request #2804 from GNS3/update-dependencies
Update dependencies
2026-08-11 19:03:41 +02:00
grossmj 78f175d827 Merge remote-tracking branch 'origin/update-dependencies' into update-dependencies 2026-08-11 18:52:20 +02:00
grossmj 386c88f230 Downgrade websockets version 2026-08-11 18:52:09 +02:00
Jeremy Grossmann 913ff3823a Merge branch '3.1' into update-dependencies 2026-08-11 18:48:54 +02:00
grossmj 9e1c533847 Finish to upgrade other dependencies 2026-08-11 18:47:35 +02:00
grossmj 0219914103 fix: breaking change with dependency FastAPI v0.137.0
https://fastapi.tiangolo.com/release-notes/#specific-breaking-changes
2026-08-11 18:47:02 +02:00
YueGuobin 72917596ab fix: suppress redundant console port setter log during Docker node create
create_docker_node() passes console, aux etc. to create_node() via
.get() so those keys remain in node_data.  The setattr fallback loop
then re-applies them — if reserve_tcp_port returned a different port
in __init__, the setter fires an INFO log and performs a wasted
release→reserve round-trip.

Pop the 15 keys already consumed by create_node() before the loop so
it only handles truly extra keys.
2026-08-12 00:10:01 +08:00
Jeremy Grossmann f69098f441 Merge pull request #2850 from yueguobin/fix/marker-batch-reconcile
fix: marker reconcile scope, batch NIO parallelism, aiohttp WS upgrade
2026-08-11 18:04:45 +02:00
YueGuobin fdcc7058cb revert: restore force_close=True in compute._session()
The per-commit force_close=not _local optimisation reused TCP connections
for the loopback compute, but _session() is also used for the controller's
WebSocket heartbeat connection (_connect_notification -> ws_connect).
The different connector behaviour prevented the compute from receiving
pings, so no compute.updated events reached the WebUI and the compute
cache stayed empty.
2026-08-11 23:27:30 +08:00
YueGuobin 1dd334caff perf: parallelize batch NIO creation across nodes
create_batch_nios bound NIOs in a serial for-loop, so during project open
every builtin L2 node (ethernet_switch/hub/cloud/nat) started its uBridge
one at a time (~0.5s each for fork + AF_UNIX connect). Group entries by
node and bind in parallel with asyncio.gather — mirroring update_batch_nios
— so independent uBridge processes start concurrently. Within a node,
entries stay serial to respect the per-node uBridge command lock.
2026-08-11 22:11:44 +08:00
YueGuobin 958aa59d7e fix: scope marker reconcile to the current bridge/NIO
The reconcile pass in _ubridge_apply_markers walked the node-wide
_marker_filter_bridges map but compared against `desired`, which only
carries the markers of the NIO being updated. Updating any one link
therefore deleted every other link's markers (and their pcaps) on that
node — a regression from the add-only→reconcile switch. IOU's override
had the same flaw across its ports.

Guard the delete pass with the current bridge (base_node) / IOL location
(IOU) so only markers on the NIO being reconciled can be removed. Added
a regression test that fails without the guard.
2026-08-11 22:11:44 +08:00
YueGuobin 5de902c8b1 cleanup: remove stray debug print in Dynamips node creation
The print(node_data.chassis, platform in DEFAULT_CHASSIS) at
dynamips_nodes.py:67 (added in 8ad7b3f6, 2022) emitted "None False"
to stdout on every Dynamips router creation. Pure debug leftover;
the very next line tests the same condition.
2026-08-11 21:46:38 +08:00
YueGuobin 958c45b6fc fix: reconcile marker filters in _ubridge_apply_markers (delete/update)
The batch marker-def fan-out (PR #2848) routed create/update/delete
marker_definition through memory_only + a batch PUT /nios/batch that
re-applies markers via _ubridge_apply_markers. But _ubridge_apply_markers
was strictly add-only: it skipped any (name, link_id) already in
_marker_filter_bridges, and reset_packet_filters preserves mark filters
(contract). So:

  * delete_marker_definition left the deleted marker's filter alive in
    uBridge (still matching / signalling / writing pcap) until node restart.
  * update_marker_definition (bpf/tag/direction change) never reached
    uBridge — the live filter kept the old expression until node restart.

Make _ubridge_apply_markers a real reconcile against the desired
nio.markers:
  - installed but no longer desired  → delete_packet_filter + unlink pcap
                                       + unregister
  - desired with changed filter field → rebuild (delete + re-add)
  - desired with only enabled changed  → instant toggle (pcap preserved)
  - desired and unchanged              → skip
  - desired and new                    → add

Track installed specs in a parallel _marker_specs dict so changes can be
detected. Both base_node and the IOU iol_bridge override are updated.
Added tests for the delete-removed and rebuild-changed-bpf paths.
2026-08-11 21:00:03 +08:00
Jeremy Grossmann f045cde0da Merge pull request #2848 from yueguobin/perf/link-create-parallel
perf: link creation & marker fan-out batch optimization
2026-08-11 09:35:08 +02:00
YueGuobin 04592a1107 log: suppress marker sink stats when no matches received 2026-08-11 11:43:43 +08:00
YueGuobin 11461982b6 log: add periodic marker.match throughput statistics
MarkerManager now logs every 10s how many marker datagrams the UDP sink
processed and the current throughput rate (match/s), so operators can
tell at a glance whether the single sink keeps up with the aggregated
uBridge traffic. Error count is also logged.
2026-08-11 11:40:22 +08:00
YueGuobin 2ac0bb7d25 marker: route marker.match to a dedicated project WS channel
High-frequency marker.matches shared the single project notification queue with topology events (node.*/link.*), causing head-of-line blocking. Add a separate marker channel: Notification.project_marker_queue/marker_emit, dispatch routes marker.* off the main project queue, plus a new WS /{project_id}/notifications/markers/ws endpoint. Fully migrated (the main project WS no longer carries marker.match); marker listeners are independent of project auto_close. Compute side unchanged.
2026-08-11 11:19:56 +08:00
YueGuobin a699383933 perf: raise marker UDP receive buffer from ~208KB to 8MB
1000+ uBridge processes share a single UDP marker.sink endpoint. The
default kernel receive buffer (~208 KB) holds ~1000 datagrams — a
traffic burst can overflow it before the event loop drains them. Grow
it to 8 MB via setsockopt(SO_RCVBUF) so the kernel absorbs bursts
without silent packet loss.  UDP is unordered — buffer size does not
affect per-datagram latency, only burst-loss resilience.
2026-08-11 10:44:16 +08:00
YueGuobin 6c0ec30d5d perf: move project-open marker inheritance to prepare phase
Previously apply_defs_to_new_link ran during finalize (after
link._created=True), issuing one PUT /nio round-trip per link end for
each inherited marker — 5000+ HTTP round-trips even for a single def.
Move it into _prepare_link_from_topology (memory_only) so the inherited
markers are already in _link_data when _prepare() constructs the NIO
specs, and create_batch_nios carries them in the single batch dispatch.

Finalize no longer calls apply_defs_to_new_link.  Interactive link
creation (dragging a cable in the UI) still goes through the per-link
create() → apply_defs_to_new_link path — a single link is fast.
2026-08-11 09:13:14 +08:00
YueGuobin e4d4282026 perf: parallelise compute-side batch NIO update per node
The update_batch_nios handler looped serially across all entries (5010
for a 2505-link topology). On started nodes each entry does uBridge I/O,
so the serial loop added orders of magnitude to the fan-out wall time.

Group entries by node_id before dispatching.  Different nodes talk to
their own uBridge process (AF_UNIX socket) and are fully independent, so
their updates run in parallel via asyncio.gather.  Per-node entries are
still serial (respecting the per-node uBridge command lock).
2026-08-11 09:02:46 +08:00
YueGuobin 57558508bf perf: batch update/delete marker-def fan-out too (full project-level)
per-def operations are project-level — create, update AND delete all
modify the marker policy on every link — so all three must batch, not
just create.

Extend memory_only to update_marker and stop_marker (merge/delete into
_markers + refresh _link_data, no per-link HTTP), and route
update_marker_definition and delete_marker_definition through the same
two-phase path as create: memory-only per link, then one
PUT /projects/{id}/nios/batch per compute.

Trade-off: a full reapply resets every marker's pcap on the link (the
old precise update_marker/stop_marker preserved sibling pcaps). For
project-level policy changes this is acceptable — real-time insight
matters more than pcap continuity, and batching turns 5000+ round-trips
into one per compute.
2026-08-11 08:54:16 +08:00
YueGuobin 48991f2d29 perf: batch marker-def fan-out to one PUT /nios/batch per compute
When a marker definition is created (or re-applied on data_link_type
change), the fan-out used to call inherit_marker -> update() on every
link, issuing one PUT /nio per link end (5000+ round-trips on a 2500-link
project). On started nodes each round-trip also reconfigured uBridge.

Two-phase fan-out:
- inherit_marker/start_marker gain memory_only: writes the marker into
  link._markers and refreshes _link_data without any HTTP/emit/dump.
- _apply_def_to_all_links applies memory-only to every link, then
  _batch_update_link_nios groups the updated NIO specs by compute and
  sends a single PUT /projects/{id}/nios/batch per compute.

compute: new PUT /projects/{id}/nios/batch endpoint with _get_existing_nio
+ _update_nio_binding dispatch (mirrors create_batch_nios), re-applies
filters+markers to uBridge on started nodes.

Precise per-marker operations (update_marker bpf change, stop_marker on
def delete) are untouched — they deliberately avoid a full reapply to
preserve sibling marker pcaps.
2026-08-11 08:44:57 +08:00
YueGuobin c877ed87a6 log: add marker fan-out timing for project-open and interactive def-change
Distinguish the two marker-policy fan-out paths in the log so we can tell
which is slow:
- apply_defs_to_new_link (project-open finalize): logs def count + link
  count + elapsed, only when marker_definitions is non-empty.
- _marker_apply_concurrently (interactive create/update/delete def): logs
  link count + elapsed per fan-out.
2026-08-11 08:29:39 +08:00
YueGuobin d84e756228 tune: raise start_all concurrency from 3 to 10
3 is too conservative for modern hardware; 10 provides a moderate boost
without the risk of overwhelming the host (start is the heaviest
operation: ubridge process + docker start + network config for each
node).
2026-08-11 01:20:14 +08:00
YueGuobin 2f70bd6daa revert: drop _connect_nio thread-pool executor, restore async _ubridge_send
The _connect_nio thread-pool optimisation (send_batch_sync) targeted
node-start performance, but start_all already runs at concurrency=3
(by design, to avoid overwhelming the host).  It also introduced a
Python 3.13 incompatibility (trsock.setblocking forbidden) that
prevented docker nodes from starting.  Since node-start is not the
target of this branch (project-open link creation is), revert to the
simple per-command async _ubridge_send.

The project-open batch NIO dispatch (create_batch_nios) is unaffected —
it never called _connect_nio (nodes aren't started during open).
2026-08-11 01:16:13 +08:00
YueGuobin 46bad0b639 fix: use socket.fromfd in send_batch_sync for Python 3.13 compat
Python 3.13's asyncio TransportSocket wrapper rejects setblocking(). Dup
the underlying fd via socket.fromfd() into a plain socket that the
executor thread can drive in blocking mode, then detach() after the
batch to avoid closing the transport's fd.
2026-08-11 01:10:18 +08:00
YueGuobin f9f1a4d4d8 log: demote all per-node lifecycle INFO logs to DEBUG
Extend the docker_vm / base_node demotion to the remaining node types
and supporting layers:

  qemu_vm: MAC, adapters, disk image, RAM, priority, NIO added, created
  iou_vm:  application ID, adapters, serial, image, RAM, NIO added
  dynamips router: created, adapter, RAM, NVRAM, IOS, idle-PC, disk,
    MAC, NIO bound; hypervisor create/start/connect; nio_udp created
  builtin: ethernet_switch/hub, cloud, nat — created, NIO bound
  ubridge: hypervisor start/connect

At multi-node scale these per-node lines flood the log. Only the
project-open progress summary (loaded N nodes / creating N links)
now remains at INFO alongside genuinely exceptional events.
2026-08-11 01:05:53 +08:00
YueGuobin 4e30b6905a fix: await Dynamips.create_nio (it is async, unlike sync base)
Dynamips.create_nio is async def while BaseManager.create_nio is a sync
def.  The previous fix only added the extra 'node' argument but did not
await the resulting coroutine, causing 'was never awaited' warnings and
passing a coroutine object instead of an NIO instance to the binding
dispatch.  Add 'await' on the Dynamips branch.  Test updated to verify
both the async nature and the parameter count.
2026-08-11 01:00:01 +08:00
YueGuobin 09a9555d02 fix: use bound-method param count for Dynamips create_nio detection
The inspect check tested unbound function signatures (3 params unbound vs
2 unbound) but node.manager.create_nio is a bound method — inspect
excludes 'self'.  Dynamips bound = 2 (node + nio_settings), standard
bound = 1 (nio_settings).  The old '== 3' never matched, so the extra
'node' arg was never passed.  Switch to '>= 2' and rewrite the test to
exercise the actual bound-method scenario.
2026-08-11 00:58:08 +08:00
YueGuobin e56488c2f7 test: add _add_nio_binding dispatch tests for Qemu, IOU, VPCS, Builtin
Cover every dispatch branch in the batch NIO endpoint so that future
additions of node types with unusual NIO-binding signatures are caught
at test time.
2026-08-11 00:55:54 +08:00
YueGuobin ed0f1bb4de fix: Dynamips create_nio(node, nio_settings) takes extra arg + add tests
Dynamips.create_nio requires the node as first positional argument
(unlike every other manager which takes only nio_settings). The batch
handler now detects this via parameter-count inspection (3 vs 2) and
passes node when needed.

Also add Dynamips to _add_nio_binding dispatch: routers use
slot_add_nio_binding(slot, port, nio), switches/hubs fall back to
add_nio(nio, port_number).

Add tests covering Dynamips router dispatch, switch dispatch, and the
create_nio signature detection to prevent regression.
2026-08-11 00:54:53 +08:00
YueGuobin c366f20340 log: add start/stop/close progress lines; revert start concurrency to 3
- start_all, stop_all: emit 'starting/stopping N nodes...' and complete
  lines with project name+id, matching the open-node/link log style.
- close: emit 'project closing.../closed' bracketing the whole teardown.
- Revert start_all concurrency 20->3 and reset_console 20->3: start
  (ubridge process + docker start + network) is heavy enough that high
  concurrency risks overwhelming the server. stop remains 100 (kill is
  light) and suspend remains 50 (pause is light).
2026-08-11 00:48:13 +08:00
YueGuobin ec2a0ffff3 log: lower per-node lifecycle logs in base_node to DEBUG
The per-node created / is-closing / Starting-uBridge / Stopping-uBridge
INFO lines flood the log at 1000+ node scale during project open, close,
start-all and stop-all. Demote them to DEBUG (consistent with the
docker_vm lifecycle-log demotion).
2026-08-11 00:39:49 +08:00
YueGuobin 3aa39a2da3 perf: raise start/stop/suspend/reset-console concurrency from 3
The historic concurrency=3 was far too conservative for 1000+ node
topologies. Raise them based on operation weight:

  stop_all:      3 -> 100  (docker kill + permissions cleanup, light)
  suspend_all:   3 ->  50  (docker pause/unpause, light)
  start_all:     3 ->  20  (ubridge startup + docker start + network, heavy)
  reset_console: 3 ->  20  (terminal reset, light)

Node creation (open) already uses concurrency=100 and approaches the
container-create daemon limit (~20/s); stop/kill is substantially faster
than create, so 100 is safe.
2026-08-11 00:33:49 +08:00
YueGuobin 7dc66d4836 fix: race in concurrent node creation sending duplicate POST /projects
When opening a project, nodes are created with Pool(concurrency=100).
Each _create_node did an unlocked check-then-act: 'if compute not in
_project_created_on_compute' -> await POST /projects -> add(compute).
The await let dozens of concurrent node creations race past the check
before any registered, each firing a redundant POST /projects at the
same compute. The compute-side sync handler then ran in a thread pool
and instantiated the Project N times (the repeated 'Project ... created'
INFO logs, ~16x).

Guard the check+POST+register with a project-level asyncio.Lock. The
first creation holds it for one POST; the rest acquire, see the compute
already registered, and return immediately — negligible serialization.

Also annotate the node/link progress logs with project name+id and add
completion lines, so the log clearly shows which project is loading and
when each phase finishes.
2026-08-11 00:30:33 +08:00
YueGuobin df3ca6e26b log: lower per-node docker lifecycle logs to DEBUG
At 1000+ nodes the per-node INFO lines flood the log during open /
start-all / stop-all: MAC changed, adapters changed, created, started,
console listen, fix ownership, stopped, paused, removed, adapter created,
NIO removed, capture start/stop, CPU/memory limits, mount resources.

Demote all of these routine per-node/per-adapter lines to DEBUG. Keep
INFO only for genuinely rare/important events: image pull (missing image)
and stale-container cleanup. Warnings unchanged.
2026-08-11 00:22:26 +08:00
YueGuobin 4c6ef7752a log: emit progress lines for node and link loading on project open
A large topology takes ~50s to open (dominated by docker daemon node
creation). Without any start marker the user sees no feedback that work
is in progress. Add two INFO lines: 'Loading N nodes...' before the node
pool and 'Creating N links...' before the bulk link prepare/dispatch.
2026-08-11 00:16:32 +08:00
YueGuobin e2fd922922 cleanup: remove project-open stage timing logs, lower NIO-added log to debug
- Drop the diagnostic stage-timing logs added during link-create perf
  work (nodes / preallocate / prepare / dispatch) now that bottlenecks
  are resolved and verified.
- Lower the per-NIO 'added to adapter' log in docker_vm from INFO to
  DEBUG — at 5000+ NIOs per project open it floods the log at INFO.
2026-08-11 00:14:58 +08:00
YueGuobin c9a93c0aeb perf: skip per-link topology dump during project-open prepare
Stage timing showed prepare taking 96s for 1275 links (vs 0.31s for the
batch dispatch itself). Root cause: _prepare_link_from_topology called
add_link (dump=True default) and update_link_style/update_show_filters_icon
(each unconditionally dump the full topology). 1275 links x serialize-
and-write-the-whole-topology = the entire 96s.

- add_link(..., dump=False): the project is dumped once at the end of open
- set link._link_style / _show_filters_icon directly instead of the
  update_* helpers, which also avoids spurious 'link.updated' notifications
  before the link is finalised

The final self.dump() at the end of project.open already persists everything.
2026-08-10 23:54:26 +08:00
YueGuobin 38c49a655c perf: batch NIO dispatch on project open (one HTTP per compute)
Project open used to create each link by issuing two NIO POSTs from the
controller to the compute — ~5000 HTTP round-trips for a 2500-link
topology, all funnelling through the single shared controller/compute
event loop and capping throughput near 12 links/s.

Replace it with a bulk path:
- UDPLink split into _prepare() (local: ports, peer addrs, link_data)
  and _commit_nios() (dispatch). create() = prepare + commit (interactive).
- Link.add_node gains batch=True: attach both nodes without triggering
  per-link NIO HTTP.
- compute: new POST /projects/{id}/nios/batch endpoint with a unified
  _add_nio_binding dispatch across node types (docker/qemu/iou/vpcs/
  builtin differ in signature).
- project.open: prepare all links locally, group NIO entries by compute,
  send each compute a single /nios/batch, then finalise (wire node/port
  refs, mark created, notify, apply marker defs) in parallel.

Cuts controller->compute HTTP from O(links) to O(computes). Test added
for the batch endpoint.
2026-08-10 23:42:50 +08:00
YueGuobin 96d4d82716 perf: cache compute.host_ip + add UDPLink.create timing log
host_ip resolved socket.gethostbyname on every access with no cache.
get_ip_on_same_subnet touches host_ip 2-4 times per link, so opening a
2500-link project issued thousands of blocking DNS calls inline on the
event loop — freezing all concurrent link coroutines each time. This is
the most likely cause of the 12-link/s throughput (1000x below what
Pool(concurrency=100) should deliver) and the burst+pause pattern.

- compute.host_ip: cache the resolution in _host_ip_cache, invalidate
  on host setter change
- UDPLink.create: timing log splitting get_ip / ports / nio so the next
  project-open confirms where time actually goes
2026-08-10 23:20:40 +08:00
YueGuobin b155980402 perf: dedicated 500-worker thread pool for ubridge batch I/O
Replace the default asyncio executor (capped at ~32 threads) with a
dedicated ThreadPoolExecutor sized for large-topology parallelism.
When 500 nodes each call _connect_nio, up to 500 OS threads can now
send blocking ubridge commands in parallel — no longer serialised by
either the event loop or a small thread pool.

- ubridge_hypervisor: module-level _ubridge_sync_pool (max_workers=500)
- docker_vm._connect_nio: dispatches to the dedicated pool instead of
  the default executor
2026-08-10 23:11:23 +08:00
YueGuobin 05934fa8e8 perf: offload per-NIO ubridge commands to thread-pool executor
Replace the 3-5 sequential await _ubridge_send calls in _connect_nio
with a single run_in_executor batch.  The batch holds the node-level
asyncio Lock to prevent interleaving with async sends, then uses the
hypervisor's new send_batch_sync method which does blocking socket
sendall/recv inside the thread pool.  Different nodes' batches now
run in true OS-thread parallelism rather than serialising through
the asyncio event loop between every command.

- ubridge_hypervisor.send_batch_sync: blocking batch send using
  the underlying socket from the asyncio transport, protected by
  threading.Lock.
- _connect_nio: builds command list (add_nio_udp, start_capture,
  bridge start, reset_packet_filters, add_packet_filter) and
  dispatches to the default executor.
2026-08-10 23:06:54 +08:00
YueGuobin 506b0b9f4a perf: enable TCP keep-alive for local compute HTTP requests
When controller and compute share the same process, every HTTP request
to localhost was paying a full TCP handshake (force_close=True forced
connection teardown after each request).  With 2500+ links each sending
two NIO POSTs, that's 5000 SYN->SYN-ACK->ACK cycles even for sub-ms
in-memory handlers.  Switch to keep-alive for loopback compute
(127.0.0.1 / ::1 / localhost) while keeping force_close for remote
computes that may sit behind NAT/firewalls that drop idle connections.
2026-08-10 23:00:59 +08:00
YueGuobin 82fc7f2bd1 debug: add per-command timing to _connect_nio ubridge calls
Temporary diagnostic instrumentation to measure the wall-clock time of
each ubridge command during NIO addition (add_nio_udp, bridge start,
filters, markers).  The logs will reveal whether the 12-NIO/s
throughput stems from ubridge command latency itself or from lock
contention / HTTP overhead outside _connect_nio.
2026-08-10 22:45:32 +08:00
YueGuobin acc9e670af perf: parallelize UDP port allocation and NIO creation in UDPLink.create
Previously the two sides' UDP port reservations and NIO tunnel
POSTs were issued sequentially, even though they are independent
once the peer addresses are known — each node talks to its own
compute/uBridge with no shared lock, so the HTTP round-trips can
overlap.

- Port allocation: gather _allocate_port for both computes
- NIO creation: gather both node.post calls together
- Error handling: if either side fails, roll back whichever side
  succeeded (previously only node2-fails→cleanup-node1) before
  re-raising the first error

Batch loading (open/import project) benefits most because links
are created at high concurrency and the per-link wall-clock
time is dominated by the sum of its two sequential NIO POSTs.
2026-08-10 22:36:41 +08:00
Jeremy Grossmann 372874c7d5 Merge pull request #2847 from yueguobin/fix/docker-pid1-signal-chain
fix: SIGKILL docker container on stop instead of 5s grace period
2026-08-10 16:03:22 +02:00
YueGuobin e7dfe9c7c4 fix: SIGKILL docker container on stop instead of 5s grace period
Docker node stop took ~5s every time. The stop API grace period
(params t=5, unchanged since 2015) was always exhausted: the business
process (often an interactive shell) ignores SIGTERM, and GNS3 doesn't
depend on graceful shutdown — _fix_permissions and /gns3volumes already
persist container state before stop() is called.

Use POST /containers/{id}/kill (SIGKILL, zero delay) instead of stop.
The 409 (container already stopped) replaces the previous 304 handling
for the race where the container exits between the state check and the call.

t=5 traced to commit 33edbefa3 (2015-10-14) "Docker cleanup and
improvements" — introduced with no recorded rationale.
2026-08-10 21:48:26 +08:00
Jeremy Grossmann 3689e2bb87 Merge branch '3.1' into update-dependencies 2026-08-08 22:18:17 +02:00
Jeremy Grossmann cf072c7922 Merge pull request #2752 from Volo6uev/base-configs-3.0
Api endpoints to manage base configuration files for templates
2026-08-08 22:16:36 +02:00
Jeremy Grossmann 909ccf8fcd Merge branch '3.1' into base-configs-3.0 2026-08-08 22:11:39 +02:00
Jeremy Grossmann 1d6218a3f1 Merge pull request #2846 from GNS3/bugfix/2773
Handle manual project deletion
2026-08-08 22:10:46 +02:00
grossmj bc8e43dfca fix: add event handling for deleted projects 2026-08-08 17:27:52 +02:00
grossmj 544d15c87e fix: tests after merging 2026-08-08 16:50:19 +02:00
grossmj dff79f65d3 Merge branch '2.2' into 3.1
# Conflicts:
#	gns3server/compute/qemu/qemu_vm.py
#	gns3server/controller/import_project.py
#	gns3server/controller/project.py
#	gns3server/crash_report.py
#	gns3server/version.py
#	tests/compute/docker/test_docker_vm.py
#	tests/controller/test_import_project.py
#	tests/controller/test_project.py
2026-08-08 16:27:14 +02:00
Jeremy Grossmann 955d545cf2 Merge pull request #2844 from yueguobin/marker-enabled-pause-resume
marker: direction, real-time control, serial-link (WAN) support; uBridge AF_UNIX control channel
2026-08-07 22:00:13 +02:00
Guobin Yue 183739e630 Merge branch '3.1' into marker-enabled-pause-resume 2026-08-08 01:18:39 +08:00
YueGuobin 82945cd81e server: raise the open-files (RLIMIT_NOFILE) limit at startup
Every started node holds ~3 file descriptors in the server's table (pidfd + stdout/stderr pipes per child process), so a few hundred started nodes exhaust the default 1024 soft limit and the uBridge version-check subprocess fails with EMFILE ('Too many open files: /dev/null').

At startup, best-effort raise RLIMIT_NOFILE to 65535 (capped by the hard limit); failures are logged, never fatal. Runs before daemonize() so the daemon inherits the raised limit. Linux-only, matching the platform target.
2026-08-08 00:26:00 +08:00
YueGuobin ad8bac8328 marker: batch topology dumps in bulk fan-out (per-def on 500+ links was ~1 minute)
Every per-link marker operation (start_marker / stop_marker / update_marker) called Project.dump() -- a full topology serialization + file write. A definition fan-out over 500 links therefore wrote the whole topology 500+ times (each blocking the event loop), which dominated the observed ~1 minute; the NIO round-trips themselves were negligible.

Add a dump: bool = True parameter to the three per-link operations and inherit_marker (matching the existing dump param on Link.add_node). The bulk paths -- definition create fan-out, definition-update sync and re-fan-out, definition-delete cleanup, pause/resume, new-link inheritance -- pass dump=False and their caller dumps once after. apply_defs_to_new_link suppresses per-def dumps too: link create / project open dump once after, so opening a 500-link project with N definitions no longer does 500xN topology writes.
2026-08-08 00:03:30 +08:00
YueGuobin 078cf92aef marker: concurrent (bounded) definition fan-out
The per-definition fan-out applied markers to links in a serial loop -- one compute round-trip per link. On a 1000-link project that serializes N HTTP round-trips (minutes on remote computes). Fan out with asyncio.gather + Semaphore(32): links are independent (own _markers/_link_data), per-link ControllerError stays isolated, and Project.dump is synchronous + atomic (tmp + rename) so concurrent dumps cannot corrupt the topology file.

Converts the definition-create fan-out, the definition-update sync and re-fan-out loops, and the definition-delete cleanup to the shared _marker_apply_concurrently helper. apply_defs_to_new_link stays serial deliberately: all definitions share one link and each push carries the link's full marker set, so concurrent pushes would race and lose markers.
2026-08-07 23:50:41 +08:00
YueGuobin 0f86dabfa3 marker: forward data_link_type on per-link marker create
The per-link create_marker route (links.py) called start_marker without the data_link_type from the body, so it always defaulted to DLT_EN10MB and a serial encapsulation chosen by the caller was silently dropped. Same oversight the IOU capture and definition routes had; one-arg fix.
2026-08-07 13:38:33 +08:00
YueGuobin ba318150fa iou: skip already-installed markers in _ubridge_apply_markers (NIO update idempotency)
The IOU override of _ubridge_apply_markers lacked the incremental guard the generic path has, so on an NIO update it re-added every marker the port already carried. uBridge's add_packet_filter rejects a duplicate filter name (packet_filter.c find_packet_filter), so adding a private marker to an IOU link that already hosted an inherited global-* copy failed with 'Failed to add filter global-...' -- the NIO update re-sends ALL markers on the port (inherited + new private), and the pre-existing one collided.

Add the same (name, link_id) in self._marker_filter_bridges skip as the generic base_node path, so an update only installs markers not already on the port. Mirrors how Dynamips/vpcs/etc. stay idempotent across add + update.
2026-08-07 13:30:12 +08:00
YueGuobin 3322233658 marker: serial-link (WAN) support via data_link_type -> uBridge linktype
Markers now work on serial links (Cisco HDLC / PPP / Frame Relay / ATM), not just Ethernet. A marker carries a data_link_type (default DLT_EN10MB); at the uBridge boundary it becomes the 'mark ... linktype <dlt>' keyword so the BPF compiles and the pcap is written with the matching link-layer.

- MarkerCreate / MarkerDefinitionCreate gain data_link_type (default DLT_EN10MB). Per-link it is create-only; definitions are updatable (a change re-fans-out).
- base_node._marker_linktype() normalizes the GNS3 DLT name (strip DLT_, uppercase, None for EN10MB). Single source is SerialPort.data_link_types, so Cisco PPP -> PPP_SERIAL (50), matching the capture path -- no second mapping table.
- _ubridge_add_marker_filter (generic) and the IOU marker loop append 'linktype <dlt>'.
- Definition fan-out branches on link_type in inherit_marker: Ethernet is always EN10MB; a serial link uses the definition's WAN encapsulation, or is SKIPPED when none was chosen (an EN10MB pcap on serial is undecodable). One definition covers a mixed topology.
- MCP marker_definition exposes data_link_type (None = not forwarded).
- No uBridge rebuild on a data_link_type change -- only that one marker's filter is swapped (delete + re-add), mirroring a BPF change; reset_packet_filters preserves sibling mark filters.

Requires the uBridge build with 'mark ... linktype' support.
2026-08-07 01:53:33 +08:00
Jeremy Grossmann 555c3ecab5 Merge pull request #2845 from yueguobin/fix/iou-serial-capture-linktype
Fix IOU serial-link captures always written as Ethernet (DLT_EN10MB)
2026-08-06 19:07:22 +02:00
YueGuobin 117f580cfd Merge fix/iou-serial-capture-linktype: IOU serial capture data_link_type 2026-08-07 00:36:25 +08:00
YueGuobin 17020b7f7b iou: forward data_link_type on capture start so serial pcaps use the correct linktype
The IOU compute capture/start route received data_link_type in the NodeCapture body but dropped it when calling node.start_capture(), so iou_vm.start_capture always defaulted to DLT_EN10MB -- every IOU serial capture (Cisco HDLC / PPP / Frame Relay) was written as an Ethernet pcap. Dynamips, cloud and the L2 switches already forward this value; IOU was the only serial-capable node that omitted it. One-argument fix: the node method already accepts and forwards data_link_type to 'iol_bridge start_capture', so only the route was missing it.

Verified: IOU serial captures now produce the expected linktype (C_HDLC / PPP_SERIAL / FRELAY) instead of Ethernet.
2026-08-07 00:35:39 +08:00
YueGuobin 5f4ac38434 ubridge: default the control transport to unix
Switch ubridge_control_transport from tcp (-H) to unix (-U), the
AF_UNIX + SO_PEERCRED channel recommended on Linux for kernel-level
peer authentication. tcp is retained as an opt-in for backward
compatibility. Existing deployments that set the key explicitly are
unaffected; only fresh installs / unset keys pick up the new default.
2026-08-06 21:35:09 +08:00
YueGuobin b8ac76f047 ubridge: require version >= 1.2.0
Drop the platform-specific floor (0.9.12 darwin / 0.9.14 others) in
favour of a single 1.2.0 minimum. This server now relies on features
only present in recent uBridge builds: the AF_UNIX control channel
(-U / SO_PEERCRED), the marker (mark) filter, and the brctl-backed
builtin Ethernet Switch. Removes the now-unused sys import left behind
by the dropped darwin branch (target is Linux-only).
2026-08-06 21:35:09 +08:00
grossmj 29c1b04078 fix: add missing HTTPException import 2026-08-05 21:55:23 +02:00
YueGuobin 7ed4eeab29 mcp: drop direction from marker_definition tool
A marker definition fans out to every link and auto-selects its capture node
on each, so tx/rx is relative to a node that varies per link — the controller
already rejects it (409). Exposing direction on the MCP definition tool let an
agent ask for something that could only fail. Remove the parameter and the
handler's direction handling; the docstring now points to encoding direction in
the BPF (e.g. 'icmp and icmp[icmptype]==8'). Per-link link_marker keeps
direction, where the capture node is fixed.
2026-08-05 01:40:22 +08:00
YueGuobin f7b19dae99 marker: tighten marker name max length from 128 to 32
128 characters was far beyond any realistic marker label (icmp, arp, tcp-syn)
and would have collided with the pcap filename budget once a tag prefix is
added later. Cap the user-facing name at 32 in both MarkerCreate and
MarkerDefinitionCreate; the compute-side name guard now also rejects names
longer than 48, which covers the `global-{def_name}` inherited form (≤ 39).
2026-08-05 00:49:37 +08:00
YueGuobin 75f278228b marker: drop deleted marker from port NIO cache to stop empty pcap on restart
Deleting a marker while its node was stopped, then starting the node, recreated
an empty pcap. Root cause: delete_marker_capture removed the uBridge filter and
the pcap file but not the marker spec cached on the port NIO (nio.markers) —
the data source _ubridge_apply_markers reads on node start. The stale spec
reinstalled the marker when uBridge came up.

This was a regression from switching stop_marker off update() (which re-sent
the NIO and implicitly refreshed nio.markers) to the fine-grained
node.delete(/markers/{name}) path.

Fix: make the delete port-aware so the compute can locate the NIO. The DELETE
marker route becomes /adapters/{a}/ports/{p}/markers/{name} across all six
node types; the handler resolves the NIO via get_nio and passes it to
delete_marker_capture, which now pops the marker from nio.markers. get_nio
works regardless of uBridge state, so the stopped-node case is covered. The
controller's stop_marker targets the capture side's adapter/port.
2026-08-05 00:08:12 +08:00
YueGuobin 1a0ce51f38 marker: validate def BPF once, skip re-validation on inherited fan-out
A marker definition validated its BPF N times — once per link in the fan-out
(start_marker runs validate_bpf_syntax on every copy), spawning one tcpdump -d
subprocess per link for the same expression. Definitions did not validate BPF
at all; only direction was checked.

Move the single validation point to the definition layer (create/update), and
validate each definition's BPF on project load (dropping any that have gone
invalid, like private markers). The inherited fan-out (start_marker) and def
sync (update_marker) now skip validate_bpf_syntax for inherited copies, since
the BPF comes from an already-validated definition. Private per-link markers
still validate inline as before. uBridge still runs pcap_compile at install, so
an invalid expression can never slip through.

Creating a definition over N links now runs one tcpdump instead of N.
2026-08-04 23:20:58 +08:00
YueGuobin 60e2bbbbbb marker: point directional defs at BPF, refresh implementation doc
The 409 on a tx/rx definition now recommends encoding direction in the BPF
(e.g. icmp[icmptype]==8) as the primary fix, with per-link markers as the
single-link fallback. Doc updated: per-def rejects tx/rx (why + BPF), the
pause section no longer claims bpf changes reset+reapply (they rebuild one
filter), and a new Capture files section covers pcap cleanup + reset-preserves-mark.
2026-08-04 22:59:12 +08:00
YueGuobin 95824b1861 marker: incremental apply, clear bridge map on uBridge stop
_ubridge_apply_markers now installs only markers not already on the bridge
(uBridge's reset_packet_filters preserves mark filters), so an NIO update no
longer re-adds — and reopens — sibling markers' pcaps. _stop_ubridge clears
_marker_filter_bridges so a node restart re-installs everything (the map would
otherwise keep stale entries pointing at a fresh, empty uBridge).
2026-08-04 22:19:43 +08:00
YueGuobin caec71aa71 marker: fine-grained filter ops, clean pcap on remove
Deleting or updating a marker no longer triggers a full NIO reapply
(reset_packet_filters + re-add), which closed/reopened every sibling
marker's pcap via uBridge. Instead operate on single filters:

- stop_marker: bridge delete_packet_filter + unlink the pcap (works with
  the node stopped; filter removal is skipped, the file is still deleted).
- update_marker: bpf/tag/direction → rebuild just that filter (delete + add);
  enabled → instant toggle; color/highlight_duration → stored only.
- compute delete_marker_capture / rebuild_marker_filter + per-node routes
  (DELETE /markers/{name}, PUT /markers/{name}/rebuild) + MarkerRebuild schema.

IOU overrides _ubridge_delete_marker_filter for iol_bridge; rebuild reuses
the already-overridden add/delete/set, so IOU needs no rebuild override.
2026-08-04 21:35:31 +08:00
YueGuobin 19815f7a37 marker: restore direction on project load, reject tx/rx on definitions
Restore a private marker's direction (and highlight_duration) when a
project is reopened — _create_link_from_topology_data previously dropped
them, silently reverting rx/tx markers to "both".

Reject tx/rx direction on marker definitions with HTTP 409: a definition
auto-selects its capture node per link and direction is relative to that
node, so a fixed tx/rx has no stable project-wide meaning. Per-link
markers still support tx/rx; only the project-wide definition is restricted
to "both" (the default).
2026-08-04 10:14:02 +08:00
YueGuobin 9323ea4cec schema: accept direction='both' in marker schemas, normalize to None 2026-08-03 00:31:45 +08:00
YueGuobin b6959f8214 qemu: demote QEMU monitor connect and set_link logs to DEBUG 2026-08-03 00:17:34 +08:00
YueGuobin e3ce234a09 docs: add log-interpretation note across node types for marker operations 2026-08-03 00:05:08 +08:00
YueGuobin ff907da5f6 marker: key _marker_filter_bridges by (name, link_id) so multi-link nodes toggle every copy
The _marker_filter_bridges dict was keyed by marker name alone, so when one
node hosted the same filter name on several links (IUOL-BRIDGE per node with
many bays/units, or a multi-interface router), successive apply calls
overwrote earlier entries. pause_marker_definition then toggled only the last
recorded bridge/location — other copies stayed active and kept emitting.

Key by (name, link_id) so each copy is independent, and iterate all matching
entries in _ubridge_set_marker_filter_state (both generic bridge and IOU
iol_bridge override). Toggle route existence checks also iterate matching
names. Tests updated.
2026-08-02 23:48:24 +08:00
YueGuobin 34b644a548 marker: make per-filter toggle fall back to NIO rebuild when the marker isn't installed
Toggle routes silently no-opped when _marker_filter_bridges lacked the filter
name, so update_marker's enabled-only short-circuit succeeded without toggling
uBridge — the controller-layer enabled was set but the uBridge filter stayed on
and kept emitting signals. Now the toggle routes raise HTTPException 404
(FastAPI handles it directly, no ERROR log); the controller's except catches it
and falls back to self.update() (NIO rebuild, which applies the marker + off).
2026-08-02 23:41:43 +08:00
YueGuobin 0afbb897a5 marker: make per-filter toggle a no-op when the marker isn't installed
_ubridge_set_marker_filter_state raised "Marker X is not installed on this
node" when the capture node wasn't running — the name->bridge map is only
populated during _ubridge_apply_markers, which runs when the node is up. The
error was noise: the controller's enabled-only short-circuit catches it and
falls back, and the controller-layer enabled is authoritative (honoured when
the node starts and applies the marker). Treat a missing entry as a no-op
instead of raising.
2026-08-02 23:23:53 +08:00
YueGuobin 1eeee024bd marker: rework pause/resume from project-wide to per-definition
The project-wide mute (POST /markers/pause|resume + _markers_paused) paused
every marker with one button. The actual need is per-rule control: pause one
definition and toggle only its inherited global-{name} copies across all links.

- Drop project-level: _markers_paused (init/asdict/load/start_all), the
  pause_all/resume_all_markers methods, and the /markers/pause|resume routes.
- Add per-definition: a persisted `paused` flag on each definition;
  pause/resume_marker_definition fan out update_marker(enabled) to every
  global-{name} copy — instant, via the existing enable_packet_filter toggle
  (no NIO rebuild, pcap/emitted preserved). New links inherit a paused
  definition already off (inherit_marker passes enabled=not paused).
- start_marker takes an enabled kwarg; update_marker's enabled-only short-circuit
  now also covers inherited copies so def pause/resume is instant.
- Routes: POST /marker-definitions/{name}/pause|resume.
- Docs + tests updated.
2026-08-02 22:46:33 +08:00
YueGuobin e97df86d96 marker: fix PUT marker with an enabled-only body (bpf no longer required)
update_marker reused MarkerCreate, whose bpf is required, so a partial PUT like
{"enabled": false} was rejected with 422 "bpf field required". Add a MarkerUpdate
schema with every field optional (bpf included; capture_node_id and name are
create-only/path-driven and omitted) and use it for the PUT route — partial
updates now validate cleanly.
2026-08-02 22:32:04 +08:00
YueGuobin f7d7ba165a marker: persist project-wide markers_paused to the .gns3 file
pause/resume was fire-and-forget: the controller sent marker pause/resume but
stored nothing, so the Web UI could only keep a local optimistic flag that was
lost on panel reopen. Treat the mute as a project-level config (like per-marker
enabled): record _markers_paused, persist it in the topology (asdict + load),
and echo it on the project object so the UI renders from server truth.

Because marker pause is a uBridge runtime flag that resets on node restart,
start_all re-applies the mute to freshly started uBridges after a project
reopen — a paused project stays paused across close/reopen.
2026-08-02 22:21:05 +08:00
YueGuobin 8ba950fa29 marker: document pause/resume and instant enabled toggle 2026-08-02 16:22:31 +08:00
YueGuobin 84179c239c marker: test enabled/pause/resume and instant toggle
- compute (test_base_node.py): set_marker_filter_state on/off command,
  marker pause/resume command, and apply issues enable_packet_filter off
  for a disabled marker (+ records the name->bridge map).
- controller (test_marker.py): _markers_for_node keeps disabled markers
  and carries enabled; update_marker enabled-only hits the toggle route
  (not NIO rebuild) while a bpf change still rebuilds; pause/resume fan
  out to capture nodes.
2026-08-02 16:19:20 +08:00
YueGuobin 3d06c4e22f marker: drive uBridge enabled/pause/resume in real time
Wire gns3-server to uBridge's real-time marker controls (contract
../ubridge/doc/gns3server-integration.md §3.2), in three layers:

A. enabled reaches uBridge — _markers_for_node no longer drops disabled
   markers controller-side; it carries `enabled` in the NIO spec. apply
   installs every marker then issues `enable_packet_filter … off` for the
   disabled ones (base_node bridge / iou iol_bridge; old-ubridge errors
   downgrade to a warning so a toggle can't break link create).

B. instant per-filter toggle — apply records name→bridge so a new
   `_ubridge_set_marker_filter_state` can flip a running filter with
   `enable_packet_filter on|off` (iou overrides for iol_bridge + bay/unit).
   Each marker-capable node type gains PUT /markers/{name}; update_marker
   short-circuits to it when only `enabled` changes (no NIO rebuild, no pcap
   flush), falling back to reset+reapply if the route is unavailable.

C. global pause/resume — `_ubridge_marker_pause/resume` send `marker pause`
   / `marker resume` direct to the hypervisor (pause stops signal+pcap,
   resume instant, sink retained). Six node-type routes add POST
   /markers/pause|resume; project.pause_all/resume_all_markers fan out to
   each capture node (deduped, best-effort); REST exposes
   POST /projects/{id}/markers/pause|resume.

Toggling enabled and pause/resume are now both instant — only marker create
or a bpf change still go through reset+reapply.
2026-08-02 16:19:20 +08:00
YueGuobin 7368e4a65b marker: add direction-clear, routing, and ubridge transport tests
Close the test gaps surfaced in review:

- controller (test_marker.py): direction clear vs preserve, definition-sync
  clear propagation, pinned-marker NIO routing, _markers_for_node carrying
  direction, and non-capable capture-node rejection.
- ubridge (new tests/compute/ubridge/test_hypervisor.py): unix/tcp __init__
  branches + socket-dir perms, _build_command -U/-H/debug, endpoint, stop
  socket unlink, and start() immediate-exit fail-fast.
- mcp (test_handlers.py): TestLinkMarker / TestMarkerDefinition covering
  direction tri-state (both/tx/omitted) for create and update.
2026-08-02 11:37:49 +08:00
YueGuobin 37cb9f0a9c marker: support clearing direction via explicit null / "both"
direction was settable but not clearable: once a marker or project-level
definition had direction=tx/rx, no update path could return it to "both
directions", and the definition-sync fan-out silently kept stale values on
every inherited copy.

Introduce a _UNSET sentinel (link.py) distinct from None so updaters can
tell "caller omitted direction" (preserve) from "caller passed None"
(clear). Thread it through UDPLink.update_marker and
Project.update_marker_definition; the two REST routes use Pydantic v2
model_fields_set to translate an explicit JSON null into the sentinel.

MCP follows with a "both" token: link_marker / marker_definition handlers
map direction="both" to a null in the REST body (tri-state: omit=preserve,
tx/rx=set, both=clear), and the tool descriptions/docstrings document it.

Backward compatible: omitting direction or passing tx/rx behaves exactly
as before; only an explicit null / "both" clears.
2026-08-02 11:37:49 +08:00
YueGuobin 71fa778d50 marker: let callers pin the capture node via capture_node_id
A marker is single-sided — only the chosen capture node's uBridge installs the
mark filter — and dir=tx|rx is interpreted from that node's perspective. Until
now the observer was always auto-picked (_choose_marker_side), so dir=tx meant
"the auto-chosen endpoint is sending", which is unpredictable and makes the
direction filter hard to render meaningfully in the Web UI.

Add an optional create-only capture_node_id to MarkerCreate: when set, the
marker is pinned to that endpoint's uBridge (validated as a link endpoint and a
marker-capable type); when omitted, behavior is unchanged (auto-pick). The
chosen id is already echoed back as capture_node_id and in MARK signals, so the
UI can always render the observer regardless of who picked it.

capture_node_id is create-only (changing it would silently flip the meaning of
stored direction; recreate instead) and is not accepted on project-level
definitions — they are link-agnostic and have no endpoints, so inherited
markers keep auto-picking per link.

Plumbed through REST create_marker, the MCP link_marker tool, and base
Link.start_marker. update_marker does not forward it.
2026-08-01 22:24:47 +08:00
YueGuobin 6749b872fa marker: forward dir= from ubridge and add per-marker direction filter
Direction field in marker.match events
=======================================

Read ubridge dir=<tx|rx> from MARK signal datagrams and forward it
as a "dir" key in the marker.match notification event.  The field is
additive -- older ubridge builds omit it and the parser leaves it null,
so consumers fall back to undirected rendering with no version coupling.
Semantics are relative to the capture node (the signal's node=<id>):
tx = capture node is sending (ingressed device-side NIO), rx = it is
receiving (ingressed link-side NIO).

Per-marker direction filter (opt-in, server-side pipeline)
==========================================================

Add a direction field to MarkerCreate and MarkerDefinitionCreate
schemas ("tx" | "rx" | null).  Plumb it through the full pipeline:

  Schema -> controller (start_marker/update_marker, marker_entry,
  _markers_for_node, update_marker_definition sync)
  -> REST/MCP handlers -> compute _ubridge_add_marker_filter +
  IOU _ubridge_apply_markers -> bridge add_packet_filter dir <tx|rx>

When set, ubridge only fires the mark handler (signal + pcap) for
packets matching the chosen direction.  null (default/legacy) = both
directions -- zero behavioural change for existing markers.

Docs and tests
==============

- docs/features/marker-traffic-insight.md: signal format updated,
  new Direction section with NIO mapping, arrow mapping, and additive
  compatibility note.
- tests/compute/marker/test_marker_manager.py: 3 new parser tests
  (dir tx/rx/absent) plus existing test extended to assert dir=None.

13 files, +123/-22, 72 tests pass (zero breakage)
2026-08-01 14:52:07 +08:00
YueGuobin d729f76856 Name AF_UNIX sockets by node id for self-describing debuggability
Use the node id (UUID) instead of an incrementing counter for the unix
control socket name, so each socket identifies its owning node at a glance
(one ubridge per node => node_id is unique). Falls back to the counter only
when no node id is supplied. A single UUID fits sun_path's 107-byte cap
(~69 bytes), so no project_id is needed.
2026-07-31 23:48:07 +08:00
YueGuobin 2488c42cd4 Detect unsupported -U flag and fail fast with a clear error
start() now checks whether ubridge exited immediately after launch. An
old ubridge build that does not understand -U exits with a non-zero code
right away; surface the reason from ubridge.log instead of waiting for
connect() to time out 10s later with a confusing "couldn't connect" error.
2026-07-31 22:40:38 +08:00
YueGuobin 3d3e20f69e Add configurable uBridge control channel transport (tcp/unix)
Add ubridge_control_transport to [Server] config (default "tcp", fully
backward compatible). Selecting "unix" switches the uBridge hypervisor
control channel from the unauthenticated TCP listener (-H) to an AF_UNIX
socket (-U) authenticated in-kernel via SO_PEERCRED.

- UBridgeHypervisor: supports both socket_path (AF_UNIX) and host/port
  (TCP); a new `endpoint` property unifies log/error strings for both
- Hypervisor: unix mode allocates a short socket path under a 0700
  private runtime dir and unlinks it on stop; tcp mode restores the
  original getaddrinfo ephemeral-port allocation
- base_node: reads the transport from config and passes host through
- schemas/config.py + config_samples/gns3_server.conf: new option

Default deployments are unchanged. "unix" requires a ubridge build that
understands -U.
2026-07-31 22:27:16 +08:00
Jeremy Grossmann d2f73cae28 Merge pull request #2842 from GNS3/release/v2.2.61
Release v2.2.61
2026-07-30 19:15:25 +02:00
grossmj 8c0150cd62 Development on 2.2.62.dev1 2026-07-30 19:11:11 +02:00
grossmj da2942c139 Release v2.2.61 2026-07-30 12:53:08 +02:00
grossmj 5485eef3ad Sync appliances 2026-07-29 18:52:23 +02:00
Jeremy Grossmann ccf4b3f9db Merge pull request #2840 from GNS3/fix-unvalidated-symlink
Fix unvalidated symlink creation in import_project
2026-07-29 18:51:21 +02:00
grossmj b797981a65 test: add tests for unvalidated symlink creation in import_project 2026-07-29 18:48:31 +02:00
grossmj a225622a6e fix(import): unvalidated symlink creation in import_project 2026-07-29 18:10:52 +02:00
Jeremy Grossmann 3f19ede8d2 Merge pull request #2839 from GNS3/bugfix/2838
Fix addition of QEMU RNG device in 2.2.60 causes interface names to change
2026-07-29 18:00:16 +02:00
Jeremy Grossmann 668169d1cc Merge branch '2.2' into bugfix/2838 2026-07-29 17:55:53 +02:00
grossmj 66b39f0616 Merge remote-tracking branch 'origin/master' into 2.2 2026-07-29 17:54:18 +02:00
Jeremy Grossmann 7efef28d4f Merge branch '2.2' into bugfix/2838 2026-07-29 17:50:01 +02:00
grossmj d9140d2f8c fix(qemu): move the bios options after the network ones 2026-07-29 17:47:03 +02:00
grossmj e2657febf0 fix(qemu): fix addition of QEMU RNG device causes interface names to change 2026-07-29 17:23:28 +02:00
Jeremy Grossmann d161f1997d Merge pull request #2837 from my-code-is-grey/ghcr_lowercase
fix: lowercase GHCR image name in docker-build workflow
2026-07-28 17:28:41 +02:00
my-code-is-grey 37490f2c74 bugfix: docker workflow needs lowercase name 2026-07-27 22:27:48 -04:00
Jeremy Grossmann 9b1d7d44bf Merge pull request #2836 from iskanred/bugfix/2835
fix(qemu): remove trailing space from RNG object argument
2026-07-27 20:42:29 +02:00
Iskander Nafikov 9562c9d828 fix(qemu): remove trailing space from RNG object argument 2026-07-28 00:27:55 +08:00
Jeremy Grossmann deba9f8409 Merge pull request #2834 from yueguobin/mcp-tool-descriptions-enhancement
Improve MCP tool descriptions and add traffic-insight marker tools
2026-07-26 19:09:05 +02:00
Jeremy Grossmann 6c2a980afc Merge pull request #2833 from Sanjays2402/fix/delete-project-does-not-start-nodes
Do not start nodes when deleting a project
2026-07-26 09:23:12 +02:00
YueGuobin 309d388b0b Add MCP tools for traffic-insight marker feature
Add 2 new MCP tools to expose the marker (traffic-insight) REST API:

- link_marker: per-link marker CRUD (create/update/delete)
  POST/PUT/DELETE /projects/{pid}/links/{lid}/markers
- marker_definition: project-level marker definition CRUD (create/update/delete/list)
  POST/PUT/DELETE/GET /projects/{pid}/marker-definitions
  Create auto-fans out global-{name} to every link

Read operations use existing link_get (returns markers dict).
2026-07-26 13:01:06 +08:00
YueGuobin a8c6546c44 Improve MCP tool descriptions for link_update, device_show_run, and link_reset
- link_update: add bidirectional filter effect note, packet loss formula
  (packet_loss [50] ≈ 75% observed), filter clearing syntax (filters: {}),
  and ARP-also-filtered warning with static ARP recommendation
- device_show_run: add prerequisite section — device_type:<type> tag
  required, Docker/Linux nodes unsupported (use node_console)
- link_reset: clarify that filter state machines (e.g. frequency_drop
  counters) restart while filter configuration is preserved
2026-07-26 12:50:14 +08:00
Sanjay Santhanam 00ac2c19bd Do not start nodes when deleting a project
Project.delete() calls open() to rebuild the internal data structures
needed for cleanup. open() schedules start_all() when the project has
auto_start enabled, so deleting an auto-start project actually launched
every node process, allocating ports and consuming resources, only for
close() to kill them moments later.

open() now takes an auto_start argument (default True, so normal opens
are unchanged) and delete() passes auto_start=False.

Fixes #2784
2026-07-25 20:00:43 -07:00
Jeremy Grossmann 6742d09a70 Merge pull request #2831 from Sanjays2402/fix/docker-stop-state-check
fix: correct always-true state check in DockerVM.stop()
2026-07-25 19:59:28 +02:00
Sanjay Santhanam 41e8777609 fix: correct always-true state check in DockerVM.stop()
The condition 'state != "stopped" or state != "exited"' is a tautology,
so the state check was a no-op and a stop request was sent even for a
container that had already exited.

_get_container_state() never returns "stopped" (only "running",
"paused" or "exited"), so the intended negation of the condition used in
_fix_permissions() requires 'and', not 'or' (De Morgan's law).

Added a regression test asserting no stop query is issued for an
already-exited container.
2026-07-25 10:30:16 -07:00
Jeremy Grossmann 20868aa233 Merge pull request #2830 from rafael-33/master
docs: add structured bug-report template
2026-07-24 22:55:36 +02:00
rafael-33 27c6535ad0 add bug report issue template 2026-07-24 22:51:44 +02:00
Jeremy Grossmann f1be5eae9b Merge pull request #2829 from cristian-ciobanu/docker-pull-image
Add controller and compute API support for explicitly pulling or updating Docker images
2026-07-24 20:14:55 +02:00
Cristi 2abc7e09a3 Adds controller and compute API support for explicitly pulling or updating Docker images. 2026-07-24 16:40:20 +03:00
Jeremy Grossmann 28f883b46a Merge pull request #2828 from GNS3/set-ulimit-pytest
feat(tests): increase maximum open file descriptors for test runs on Unix
2026-07-23 18:05:19 +02:00
grossmj c010be1a02 feat(tests): increase maximum open file descriptors for test runs on Unix 2026-07-23 18:00:11 +02:00
Jeremy Grossmann 2b949b1a77 Merge pull request #2826 from cristian-ciobanu/iol-l1-keepalive
(feat): Implement functional Layer 1 keepalive support for IOU/IOL nodes
2026-07-22 18:10:42 +02:00
Cristian Ciobanu ac003c0a71 Merge branch 'GNS3:master' into iol-l1-keepalive 2026-07-22 11:50:09 +03:00
Cristi dd497e4308 (feat): Implement functional Layer 1 keepalive support for IOU/IOL nodes 2026-07-22 10:47:09 +03:00
grossmj 7bc9ae4aa8 Fix typo with ovmf_firmware_dir 2026-07-21 17:34:05 +02:00
grossmj 1f6e00d29f Fix issues after merging 2026-07-21 17:20:46 +02:00
grossmj 0091f2c64a Merge remote-tracking branch 'origin/3.1' into 3.1 2026-07-21 17:04:35 +02:00
grossmj 7487ec14e0 Merge branch '2.2' into 3.1
# Conflicts:
#	CHANGELOG
#	conf/gns3_server.conf
#	gns3server/compute/docker/__init__.py
#	gns3server/compute/docker/docker_vm.py
#	gns3server/compute/qemu/qemu_vm.py
#	gns3server/controller/import_project.py
#	gns3server/crash_report.py
#	gns3server/version.py
2026-07-21 17:03:00 +02:00
Jeremy Grossmann e90f250294 Merge pull request #2823 from yueguobin/feature/cloud-node-interface-refresh
fix(controller): refresh cloud/nat node interfaces from compute on GET, plus NAT interface info
2026-07-19 12:49:07 +02:00
YueGuobin 977d9628e5 fix(builtin): hide GNS3 internal bridge interfaces from Cloud node
Filter out host interfaces whose name starts with 'gns3' (e.g.
EthernetSwitch kernel bridges) from Cloud.asdict() interfaces list.
Other special interfaces (virbr0, docker0, etc.) remain visible.
2026-07-19 18:21:22 +08:00
YueGuobin 4943567962 feat(builtin): NAT node returns its interface IP info in asdict()
NAT now includes an 'interfaces' field in its response, filtered to
contain only the mapped NAT interface (virbr0 on Linux, vmnet8 on
macOS/Windows). This lets connected nodes discover the NAT subnet
and gateway address without needing to list all host interfaces.

The field format mirrors Cloud.asdict(): name, type, special, and
ip_addresses list (both IPv4 and IPv6).
2026-07-19 18:10:51 +08:00
YueGuobin ddf7d4ca60 fix(controller): refresh cloud/nat node interfaces from compute on GET
Cloud and NAT nodes need live host network interface data. Previously,
GET /projects/{project_id}/nodes/{node_id} returned cached properties
from creation time, so newly added host interfaces (e.g. kernel bridges
created by EthernetSwitch nodes) were invisible until the node was
deleted and recreated.

Now the controller fetches fresh data from the compute node before
returning the response, so host interface changes are reflected
immediately. Falls back to cached data if compute is unreachable.
2026-07-19 17:41:37 +08:00
Jeremy Grossmann e1b09e683e Merge pull request #2822 from yueguobin/feature/ethernet-switch-ubridge-brctl
POC: migrate builtin EthernetSwitch from Dynamips ethsw to ubridge brctl
2026-07-17 23:49:01 +02:00
YueGuobin 7c320d6100 docs: add builtin Ethernet Switch uBridge brctl implementation document 2026-07-18 01:27:53 +08:00
YueGuobin 18a123e0b9 refactor(builtin): use deterministic bridge name from switch UUID
Replace psutil.net_if_addrs() scan with a deterministic name derived from
the switch's node UUID: gns3 + first 6 hex chars (10 chars, fits kernel
IFNAMSIZ limit of 15). Taps: <bridge>-<port> (12-13 chars).

Crash recovery: brctl delete the bridge first (best-effort), then create
fresh. Stale bridges from abnormal gns3server shutdown are automatically
reclaimed on the next start — no EEXIST or leaked interfaces.

Remove _free_iface helper and psutil import (no longer needed).
2026-07-18 01:18:32 +08:00
YueGuobin aabbee3a04 fix(builtin): bring kernel bridge UP after creation
brctl create leaves the bridge administratively DOWN. Add link set up
so the bridge actually forwards frames between enslaved ports.

Also record Docker iptables FORWARD DROP pitfall in project memory.
2026-07-18 01:11:25 +08:00
YueGuobin fd4ac4460d feat: migrate builtin EthernetSwitch from Dynamips ethsw to ubridge brctl
Replace the builtin EthernetSwitch stub with a Linux kernel bridge backed
by uBridge's brctl module. Each switch node creates one kernel bridge
(gns3br{N}) with VLAN filtering; each port is a persistent TAP enslaved to
the bridge, relayed by a per-port uBridge bridge (nio_tap <-> nio_udp).

- Access/dot1q/qinq port modes translated to brctl vlan primitives
- Compute router repointed from Dynamips to Builtin manager
- Tests updated: 21 router-level tests + 215 surrounding tests pass
- Real-kernel e2e verified: access 100 PVID untagged, dot1q trunk
  VIDs 1-4094 + native 1, qinq 802.1ad proto + 200 PVID

Ethertype 0x9100/0x9200 handling and port-count guard relaxation are
deferred pending resolution.
2026-07-18 00:21:19 +08:00
Jeremy Grossmann 22a1026633 Merge pull request #2821 from yueguobin/fix/mcp-remove-node-reload
fix(mcp): remove unreliable node_reload / node_reload_all tools
2026-07-16 12:51:29 +02:00
YueGuobin 37867a1e44 fix(mcp): remove unreliable node_reload / node_reload_all tools
For Docker nodes, reload bottoms out as a raw POST /containers/{id}/restart
to the Docker daemon, bypassing GNS3's start/stop lifecycle (uBridge
re-attach, console servers, NIC setup). The container restarts at the
Docker level but GNS3's plumbing goes out of sync, and the daemon call can
block up to the controller's 240s timeout — manifesting as "reload hangs /
no response". stop+start runs the full lifecycle and is reliable.

Remove the node_reload and node_reload_all MCP tools (tool functions,
handlers, NODE_TOOLS entry, tests, docs). The underlying REST endpoints
(POST /nodes/{id}/reload, POST /nodes/reload) are kept for native API
users. MCP callers should use node_stop + node_start (partial) or
close/open project (full restart) instead.
2026-07-16 13:27:21 +08:00
Jeremy Grossmann 013ca442f4 Merge pull request #2816 from yueguobin/feature/traffic-insight-markers
feat: add traffic-insight markers (ubridge mark filter integration)
2026-07-15 22:12:11 +02:00
grossmj c75e1ba0be Development on 2.2.61.dev1 2026-07-15 20:45:33 +02:00
Jeremy Grossmann c1e845cb22 Merge pull request #2819 from GNS3/release/v2.2.60
Release v2.2.60
2026-07-15 20:44:04 +02:00
Jeremy Grossmann 3954d6477a Merge pull request #2817 from yueguobin/fix/mcp-rbac-token-hardening
fix: thread token_version through MCP token minting and guard websocket auth failure
2026-07-15 19:20:44 +02:00
Guobin Yue 64da926d2f Merge branch '3.1' into fix/mcp-rbac-token-hardening 2026-07-16 01:03:11 +08:00
Guobin Yue 2e9073be39 Merge branch '3.1' into feature/traffic-insight-markers 2026-07-16 01:03:06 +08:00
Jeremy Grossmann 3e12ddf321 Merge pull request #2818 from yueguobin/docs/api-testing-skill
docs: add a Claude Code skill with curl patterns for testing the REST API
2026-07-15 18:57:19 +02:00
YueGuobin dc7f5d76f4 docs(api-testing): add curl-based GNS3 API testing skill 2026-07-16 00:54:33 +08:00
YueGuobin 884c40038c docs(mcp): note --no-close for node_console websocat usage
A heredoc (<<<) closes stdin at once, so websocat dropped the WebSocket
before the device's reply arrived. Add --no-close to the node_console usage
examples and the returned command field so the connection stays open while
output is read.
2026-07-16 00:51:45 +08:00
YueGuobin d4389b7068 fix(rbac): guard None current_user on websocket auth failure
get_current_active_user_from_websocket returns None after closing the socket
on an auth failure (revoked token, bad credentials, inactive user).
has_privilege_on_websocket dereferenced current_user.is_superadmin without a
None check, so any websocket auth failure surfaced as an AttributeError
traceback instead of a clean close. Bail out early when current_user is None,
mirroring the guard already present in ws_console.
2026-07-16 00:51:45 +08:00
YueGuobin 3d6d9a3396 fix(mcp): thread token_version into console/download token minting
Token revocation is a strict version check (token_data.token_version !=
user.token_version). create_access_token defaults token_version to 0, so the
short-lived JWTs minted for the console WebSocket URL (nodes) and the download
URLs (symbols, links) carried ver=0. Any user who had logged out at least once
(token_version >= 1, e.g. the default admin) got tokens rejected as "revoked"
on first use.

e433991cf fixed this in _resolve_token's API-key branch but missed these three
independent minting sites. Now resolve token_version during _resolve_token (the
JWT branch decodes it, the API-key branch reads user.token_version), carry it
through gns3_ctx, and pass it at every minting call.
2026-07-16 00:51:45 +08:00
YueGuobin 89e11d265f fix(mcp): pass user.token_version when generating temp JWT from API key
_resolve_token generated a temp JWT with a hardcoded ver=0 after
validating the API key. Users who had logged out at least once
(token_version >= 1) would hit "Token has been revoked" 401 on
every MCP tool call, because the REST auth chain rejects ver=0
when the user's token_version no longer matches.

Fix: pass the user's actual token_version to create_access_token
so the temp JWT carries the correct ver claim.
2026-07-16 00:51:45 +08:00
YueGuobin 45d18de8af fix(marker): avoid reentrant-lock deadlock when uBridge starts lazily
_start_ubridge configures the marker sink via _ubridge_configure_marker_sink, which used _ubridge_send. But _start_ubridge itself is reached THROUGH _ubridge_send when uBridge is started lazily — e.g. linking a stopped node. _ubridge_send's @locking lock (___ubridge_send_lock) is non-reentrant, so the nested _ubridge_send('marker sink') deadlocked forever, making the NIO create POST time out after 120s. Started nodes never hit this (uBridge already running, no _start_ubridge), so only stopped-node links (notably dynamips) hung.

_ubridge_configure_marker_sink now talks to self._ubridge_hypervisor.send directly: it runs inside _start_ubridge right after connect(), so uBridge is already up and the raw send is safe, with no reentrant lock acquisition.
2026-07-16 00:39:52 +08:00
YueGuobin 08f4b5ae0d docs(marker): document per-link attribution and IOU multi-interface
Add a Per-link attribution section (link field semantics, pcap path keyed on link) with an IOU subsection explaining the shared IOL-BRIDGE and per-port filter lists. Note that the marker.match link_id comes from the signal link= field, and call out shared capture-side node behavior in Notes.
2026-07-16 00:39:52 +08:00
YueGuobin 794bfef450 fix(marker): per-link attribution via link field in MARK signals
A uBridge MARK signal carries only node= and filter= (no bridge/link field), so when one node is the capture side for several links that share a marker name (always the case for global-{name} definitions on a multi-interface node) the signals were indistinguishable and the (node, filter) registry collapsed them to a single link.

The mark filter is now stamped with its link id (mark <bpf> ... link <link_id>); uBridge echoes it verbatim (link=<link_id>) and the listener uses the signal's link= as the authoritative link_id of the marker.match event, falling back to the registry only for legacy signals without it. base_node and iou apply paths pass link_id; covered by two new listener tests.
2026-07-16 00:39:52 +08:00
YueGuobin 27356da62d fix(marker): set nio.markers on iou/dynamips/cloud nio update
The PUT /nio (update) endpoints for iou, dynamips and cloud copied nio.filters from the request body but never copied nio.markers. So adding a marker (e.g. a project-level global definition) to an already-created link of these node types left nio.markers empty: no mark filter was installed on uBridge and no marker.match signal was emitted. vpcs/qemu/docker already set it; mirror them (getattr for the Union NIO types).
2026-07-16 00:39:52 +08:00
YueGuobin a732d8d521 test(marker): include marker_definitions in project-asdict expectations
project.asdict() and project_to_topology() gained a marker_definitions key.
Two tests that assert exact dict equality needed the new field.
2026-07-16 00:39:52 +08:00
YueGuobin 213738f0a5 test(marker): add controller + API route tests for traffic-insight
19 controller-layer tests covering start/stop/update_marker (storage,
inheritance guards + bypasses, partial-update preservation of render
hints), project-def CRUD (fan-out, sync, delete-cleanup regression),
apply_defs_to_new_link, persist_markers/asdict, and aggregation.

15 API-route tests covering per-link create/update/delete (201/200/204),
global-prefix rejection on create (409 regression), bad-format rejection
(422), PUT/DELETE-on-inherited guard (409 regression), project-def CRUD
endpoints, and the aggregation view.

All 34 tests pass when run as part of the full suite.
2026-07-16 00:39:52 +08:00
YueGuobin cbb4854d3d docs(marker): add traffic-insight feature documentation
Document the marker feature following the gns3-documentation standard:
overview, Mermaid architecture and business-process diagrams, API endpoint
tables, request/response and field reference, error responses, and notes
covering the key design points — immutable name (rename = delete + create),
global-prefix reservation, read-only inherited markers, render hints
(color / highlight_duration), supported node types, and persistence.

Indexed under Features in docs/README.md.
2026-07-16 00:39:52 +08:00
YueGuobin b21780605e fix(marker): reject reserved global-prefix names only on create
The global-prefix reservation belongs on the create path, where it keeps
user-chosen names disjoint from inherited global-{name} markers. It was
implemented as a field_validator on MarkerCreate / MarkerDefinitionCreate,
which also back the PUT update bodies — so updating an inherited marker
while echoing its name in the body tripped the validator with a generic
422 before the controller could return the actionable 409 ("inherited,
use the marker-definitions API").

Drop the schema validators and enforce the prefix in the two create routes
(ControllerError -> 409). PUT no longer validates the body name (ignored
anyway — the target is the {name} path param), so editing an inherited
marker now reaches the controller's inheritance guard and returns the
clear 409. The name-format regex stays on the schema (still 422).
2026-07-16 00:39:52 +08:00
YueGuobin cdc27c37a7 fix(marker): clean inherited markers on def delete
delete_marker_definition removed the def but left the inherited global-*
copies on every link: it called stop_marker(), which rejects inherited
markers (409), and the ControllerError was swallowed as a warning. The
orphaned copies were in-memory only (_persist_markers filters inherited
markers) so a restart hid the symptom, but during a running session they
were undeletable via either the per-link or project API.

Add the same inherited=True bypass that update_marker already has, and
pass it from the def-delete fan-out so the copies are removed for real.
2026-07-16 00:39:52 +08:00
YueGuobin 98bcd5eddd feat(marker): add highlight_duration render hint
Per-marker UI hint (milliseconds, ge=1) for how long the Web UI keeps a
marker highlighted after a match. Mirrors color: stored on the link,
persisted in the topology, inherited via project-level definitions, and
never sent to uBridge. Omitted = null = frontend uses its own default.

The default is intentionally NOT set in the schema: MarkerCreate also
backs PUT updates, so a schema default would make every partial update
silently reset the value. None means "not provided" (keep existing on
update / frontend decides on create).
2026-07-16 00:39:52 +08:00
YueGuobin 179f072c33 fix(marker): fix inheritance hook, topology load, update sync, and asdict
Bugs found via end-to-end testing of project-level marker definitions:

1. New links didn't inherit — apply_defs_to_new_link is async but was
   called without await in UDPLink.create().

2. Project load crashed — load_project passed marker_definitions to
   Project.__init__. Now popped in load_project and restored separately
   in Project.open() (it backs a read-only property).

3. PUT on a definition didn't sync to links — update_marker's guard
   rejected even the project-layer sync call. Added an `inherited`
   bypass flag used by update_marker_definition.

4. _ubridge_add_marker_filter raised re.PatternError — the name regex
   used (?i)(?!global) look-around, invalid in Python's re module.
   Dropped the prefix check there: "global-*" names are legitimate at
   the uBridge boundary (inherited definitions); forbidden only at the
   user-facing schema.

5. GET /links hid inherited markers — asdict()'s runtime branch used
   _persist_markers() (which filters inherited markers). Restored
   self._markers for the runtime branch; only the topology_dump branch
   filters (inherited markers are rebuilt from definitions on load).

6. Duplicate "already exists" warnings on project open — open() fanned
   out definitions to all links, but UDPLink.create() had already done
   so via its inheritance hook. Removed the redundant fan-out in open().
2026-07-16 00:39:52 +08:00
YueGuobin 84845f8504 fix(marker): export MarkerDefinitionCreate from schemas package 2026-07-16 00:39:52 +08:00
YueGuobin 686f96b748 fix(marker): replace pydantic lookahead pattern with field_validator
pydantic_core (Rust engine) does not support regex look-around.
Keep the character-class pattern for basic safety and enforce the
"global" prefix reservation via a field_validator instead.
2026-07-16 00:39:52 +08:00
YueGuobin 31991fe359 feat(marker): add project-level marker definition inheritance
Project-level marker definitions fan out to every link (existing and new).
A definition is stored once on Project._marker_definitions; when applied to
a link the marker is named "global-{def_name}" — the "global" prefix was
pre-reserved in the schema, so inherited and per-link markers can never
collide, nor will their registry keys.

Key behavior:
- POST /projects/{pid}/marker-definitions → fan out to all existing links
- PUT  /projects/{pid}/marker-definitions/{name} → sync all inherited copies
- DELETE → remove every inherited copy from every link
- New links auto-inherit all active defs (hook in UDPLink.create)
- Per-link DELETE/PUT of a "global-*" marker is rejected (409)
- Inherited markers are NOT persisted in the topology; they are re-created
  from _marker_definitions on project load
- Compute side is untouched — the marker reaches uBridge via the existing
  start_marker→update→NIO→ubridge pipeline

Files:
- controller/project.py — _marker_definitions + CRUD + fanout + topology load
- controller/link.py — Link.inherit_marker() + asdict() filter
- controller/udp_link.py — guards on stop/update + create() inheritance hook
- controller/topology.py — persist marker_definitions in project topology
- schemas/controller/links.py — MarkerDefinitionCreate schema
- api/routes/controller/projects.py — REST endpoints (marker-definitions)
2026-07-16 00:39:52 +08:00
YueGuobin 369badc6c2 fix(marker): reserve "global" name prefix for future marker inheritance 2026-07-16 00:39:51 +08:00
YueGuobin d3527c00de fix(marker): extend marker support to dynamips and cloud nodes
Dynamips needed its own NIO base class extended with a `_markers`
attribute and `markers` property (mirroring the existing `filters`
pattern), plus marker propagation from the controller-supplied NIO
settings through NIOUDP.create/update to the common destination
NIO that base_node._ubridge_apply_markers reads.

Cloud simply needed the missing _ubridge_apply_markers calls after
_ubridge_apply_filters in its two ubridge connection methods, same
pattern as the earlier docker fix.

Both types are now added back to _MARKER_CAPABLE_TYPES.
2026-07-16 00:39:51 +08:00
YueGuobin e4be98984c fix(marker): enable marker support for docker nodes
Docker's _connect_nio and adapter_update_nio_binding applied packet
filters but never called _ubridge_apply_markers, so markers silently
did nothing on Docker links despite docker being in the allowlist.
Add the missing calls (same pattern as the IOU fix).

Also narrow _MARKER_CAPABLE_TYPES to the four types that actually
implement marker support — vpcs, qemu, docker, iou — removing
dynamips, virtualbox, vmware, and cloud which have no marker pathway
and would silently fail when selected as the capture side.
2026-07-16 00:39:51 +08:00
YueGuobin f7fb43a4b9 fix(marker): tolerate port conflict on marker listener startup
When the configured marker_listen_port (default 3070) is already in
use, fall back to an OS-assigned port instead of crashing the server.
If even port 0 fails, log the error and continue without marker
signals — traffic insight degrades rather than taking down startup.
2026-07-16 00:39:51 +08:00
YueGuobin 7e4600b5a1 fix(marker): validate marker name and expose enabled via REST
Add a name pattern constraint to MarkerCreate schema (alphanumeric +
_.-) to prevent injection into uBridge commands, with a matching
defense-in-depth check in _ubridge_add_marker_filter for hand-edited
topology files. Also add the missing "enabled" field to MarkerCreate
and pass it through the PUT route so the documented toggle actually
works.
2026-07-16 00:39:51 +08:00
YueGuobin a495b5ddf2 fix(marker): uniquify auto-generated marker names per link
Auto-generating `marker-{link.id[:8]}` collided on the second anonymous
marker on the same link (start_marker rejects duplicate names). Append a
short uuid hex suffix so multiple anonymous markers coexist.
2026-07-16 00:39:51 +08:00
YueGuobin f2360f85fc feat(marker): add project-level marker aggregation endpoint
Add a read-only `markers` property on Project that flattens every link's
markers into a single dict keyed by "{link_id}/{name}", each entry
carrying the parent link_id and capture-side node_id. Expose it via
GET /projects/{pid}/markers (Project.Audit) so the frontend can fetch all
markers in one round-trip instead of enumerating links first.

Also surface a marker count in project.stats().
2026-07-16 00:39:51 +08:00
YueGuobin ab5b7444d4 feat(marker): add IOU node marker support via iol_bridge
IOU uses iol_bridge (not bridge) with extra bay/unit positional
arguments in add_packet_filter. Add _ubridge_apply_markers override
that mirrors the existing _ubridge_apply_filters pattern, called at
the same three sites: _networking, adapter_add_nio_binding, and
adapter_update_nio_binding.
2026-07-16 00:39:51 +08:00
YueGuobin c62b9b0283 refactor(marker): converge to filter single-path model, remove dual-apply endpoints
Markers now follow exactly the same apply pattern as packet filters:
state lives in Link._markers, application goes through NIO
(update() -> PUT /nio -> _ubridge_apply_markers). The former
immediate-apply REST endpoints (/markers/start, /markers/stop on
the compute side) and the per-node start_marker/stop_marker methods
are removed — they were a legacy of the original capture-inspired
design and have been superseded by the NIO flow.

Changes:
- controller/udp_link: start_marker/stop_marker/update_marker now
  set _markers state + call self.update() (mirrors update_filters).
  Removed _marker_capture_nodes runtime dict and its helpers.
- controller/project: _create_link_from_topology_data restores
  _markers directly from persisted data (with BPF validation,
  like filter reload). No long calls start_marker during load.
- compute: _ubridge_apply_markers swallows BPF compile errors
  (warn+skip), matching _ubridge_apply_filters behaviour so a
  single bad expression cannot break link creation / node restart.
- Removed: /markers/start,stop endpoints (6 handlers across
  vpcs/qemu/docker route files), node start_marker/stop_marker
  methods (3 VM files), _ubridge_delete_marker_filter,
  _marker_capture_nodes, MarkerDelete schema.

Net: ~280 lines of dead code removed; marker and packet filter now
share a single, unified apply path via the NIO.
2026-07-16 00:39:51 +08:00
YueGuobin 88c03d1431 fix(marker): restore markers from topology on project load
_create_link_from_topology_data now restores traffic-insight markers
(mirroring how filters are restored via update_filters), so markers —
including their color — survive project close/reopen and server restart.

Guard start_marker's uBridge POST with 'if self._created' (exactly as
update_filters guards its update() call): during project load the link
is not yet created, so only _markers state is recorded and the marker
is applied once via the NIO flow in create()/_ubridge_apply_markers —
no double application.
2026-07-16 00:39:51 +08:00
YueGuobin 3f15ac38f6 feat(marker): add optional color field to marker data model
Add a user-chosen hex color (e.g. '#ff5722') to each marker, stored in
Link._markers alongside bpf/tag/enabled. The color:

- Is serialized with the link (asdict) and persisted in the topology, so
  it survives project reload and is consistent across devices.
- Never reaches uBridge (compute ignores it) — it is purely a Web UI
  concern.
- Can be updated independently of the BPF (color-only changes skip the
  ubridge round-trip).

MarkerCreate schema gains color: Optional[str]; start_marker and
update_marker carry it through; REST create/update endpoints pass it.

The marker.match WebSocket event stays lean (no color) — the Web UI maps
filter -> color from the link state it already holds.
2026-07-16 00:39:51 +08:00
YueGuobin b8f49696cc fix(marker): use allowlist in _choose_marker_side, align with _get_filter_node
Replace the complex tier-based fallback (which leaked into unsupported
switch types on the final tiers) with a simple allowlist of
_MARKER_CAPABLE_TYPES, mirroring _get_filter_node in link.py.

Also accept stopped nodes — like packet filters, markers are stored on
the NIO and applied when the node starts via _ubridge_apply_markers.
2026-07-16 00:39:51 +08:00
YueGuobin 239f42f5aa fix(marker): stop auto-deleting markers on node stop in node_updated
Markers are persistent link-scoped features (like packet filters), not
transient runtime features (like capture).  Tearing them down on every
node stop breaks stop/start restore: the NIO-based re-application in
_ubridge_apply_markers works correctly on restart, but node_updated
was prematurely calling stop_marker which erased _markers state and
dumped an empty topology.

Now markers survive node stop transparently — the ubridge filter dies
with the process but is re-added from nio.markers in
add_ubridge_udp_connection when the node starts again, mirroring
exactly how packet filters behave.
2026-07-16 00:39:51 +08:00
YueGuobin 7c90fa9e64 fix(marker): ride markers on NIO so they survive node restart and project reload
Mirror the packet-filter lifecycle: marker specs now live on the NIO
(next to filters), ride in link_data from controller to compute on
every NIO create/update, and are reapplied by _ubridge_apply_markers
in add_ubridge_udp_connection (bridge creation / node restart) and
update_ubridge_udp_connection (NIO update — following the preceding
reset_packet_filters so markers survive filter changes).

Changes:
- NIO / NIOUDP: _markers property + asdict
- schemas/compute/nios.py: UDPNIO.markers field
- base_manager.create_nio: nio.markers from settings
- PUT /nio routes (vpcs/qemu/docker): nio.markers update
- base_node: _ubridge_apply_markers(bridge_name, nio) iterates
  nio.markers, computes pcap path, calls _ubridge_add_marker_filter
  + MarkerManager.register; called after _ubridge_apply_filters
- controller udp_link: _get_node_markers + _markers_for_node (route
  by capture_node_id); markers in create() and update() link_data
- /markers/start,stop endpoints: mirror spec onto nio.markers so
  the marker survives a subsequent node stop/start without a PUT
- tests: add markers field to NIO data expectations

This covers:
- Node restart: NIO persists, add_ubridge_udp_connection re-applies
- Filter update: reset wipes markers, _ubridge_apply_markers re-adds
- Project reload: create() carries markers in link_data → create_nio
- Immediate create: endpoint sets nio.markers immediately
2026-07-16 00:39:51 +08:00
YueGuobin 540e1c5678 config: set marker_listen_port default to 3070 and document in config templates
Change the marker UDP sink default from port=0 (OS-chosen) to 3070 for
predictable firewall/debugging/monitoring.

Add marker_listen_host and marker_listen_port with documentation to
config_samples/gns3_server.conf and scripts/gns3_server.conf.
2026-07-16 00:39:51 +08:00
YueGuobin 88465e872c fix(marker): add _choose_marker_side to exclude non-uBridge node types
_choose_capture_side prefers BUILTIN_NODE_TYPES which includes
ethernet_switch/ethernet_hub/NAT etc. — nodes that do not use uBridge
and therefore have no bridge for a marker filter to attach to.

Add _choose_marker_side with a _MARKER_UNSUPPORTED_TYPES blocklist
so marker capture-side selection skips NIO-only switches and picks
the uBridge-backed node (VPCS/QEMU/Docker/etc.) instead.

Verified end-to-end: PC1↔Switch↔PC2 links with arp markers correctly
pick VPCS nodes; MARK signals flow through to WebSocket and pcaps
are written.
2026-07-16 00:39:51 +08:00
YueGuobin d2e9823e6c feat: implement traffic insight marker backend (ubridge mark filter)
Add compute-side marker subsystem that receives ubridge UDP MARK signals
and forwards them as project-scoped notifications to the web UI for
real-time traffic coloring. Matched packets are always saved to per-link
pcaps for future replay.

Key components:
- gns3server/compute/marker/: MarkerManager (singleton, UDP listener +
  O(1) registry keyed by (node_id, filter_name)) + MarkerListener
  (DatagramProtocol parsing MARK lines per ubridge integration contract)
- gns3server/compute/base_node.py: marker sink/node config at ubridge
  startup; shared _ubridge_add_marker_filter / _ubridge_delete_marker_filter
- Per-node start_marker/stop_marker: VPCS (VPCS-{id}), QEMU
  (QEMU-{id}-{adapter}), Docker (bridge{adapter})
- Compute REST /markers/start + /markers/stop (vpcs/qemu/docker route files)
- Controller Link._markers state + UDPLink.start_marker/stop_marker/
  update_marker (mirror capture pattern: BPF validation, _choose_capture_side,
  node.post forwarding, topology persistence)
- Controller REST GET/POST/DELETE/PUT /v3/projects/{p}/links/{l}/markers
- Config: marker_listen_host / marker_listen_port in ServerSettings
- Signal routing: creation-time registry O(1) lookup, no node-table scan;
  project-scoped WS stream (not global); event payload always carries
  project_id for frontend scoping

Tests: 14 unit tests (registry, listener parsing, UDP round-trip);
562 existing tests pass with zero regressions.
2026-07-16 00:39:51 +08:00
grossmj 803cc17410 Release v2.2.60 2026-07-15 18:36:26 +02:00
grossmj f088c55cfe Sync appliances 2026-07-15 18:32:12 +02:00
Jeremy Grossmann 8a8864c90b Merge pull request #2814 from GNS3/bugfix/2783
fix(import): project import does not move images symlinks into place
2026-07-15 09:53:15 +02:00
grossmj 1986bce538 Only set IOU images to be executable when importing images 2026-07-15 09:43:34 +02:00
grossmj c528d2cd95 fix(import): project import does not move images symlinks into place 2026-07-13 18:19:52 +02:00
Jeremy Grossmann 7529ee4168 Merge pull request #2813 from GNS3/uefi-improvements
UEFI improvements for Qemu VMs
2026-07-13 12:05:07 +02:00
grossmj 61c7f4469d Search for system UEFI that is compatible with Python < 3.12 2026-07-13 11:34:29 +02:00
grossmj 896b4fc56a UEFI improvements for Qemu VMs
* Add OVMF firmware directory configuration
* Automatically add a Random Number Generator (RNG) device when using uefi option is enabled
2026-07-13 11:08:17 +02:00
grossmj a58fa8602b remove wrongly merged code 2026-07-13 10:05:01 +02:00
YueGuobin d8f8b6ec70 fix(docker): handle container name conflict automatically
When a Docker container with the same name already exists (e.g., from a
   previous crashed GNS3 session), Docker returns a 409 Conflict error
   when trying to create a new container with that name. This causes the
   project open operation to fail.

   This fix adds automatic cleanup of stale containers when encountering
   a name conflict:
   - Added DockerHttp409Error exception class
   - Updated http_query to detect 409 status codes
   - Modified create() to remove conflicting containers and retry

   Fixes the issue where opening a project fails with:
   "Docker has returned an error: 409 Conflict. The container name
   '/GNS3.xxx' is already in use by container 'xxx'"
2026-07-13 09:57:55 +02:00
grossmj 01d72aed9a Merge branch '2.2' into 3.1
# Conflicts:
#	gns3server/controller/__init__.py
#	gns3server/controller/project.py
2026-07-13 09:32:07 +02:00
Jeremy Grossmann b256d5a5f6 Merge pull request #2812 from GNS3/bugfix/2788
fix: gns3-server crashes on startup if "Open this project in the background" is active but there is a problem with that project
2026-07-12 13:50:11 +02:00
grossmj ea09cc2724 fix: gns3-server crashes on startup if "Open this project in the background" is active but there is a problem with that project 2026-07-12 13:46:12 +02:00
grossmj e3e0a511b6 Handle HTTPNotFound exception when retrieving compute status 2026-07-12 11:08:13 +02:00
grossmj 0ecaab4da0 Replace ControllerForbiddenError with aiohttp.web.HTTPForbidden for project deletion error handling 2026-07-12 11:05:15 +02:00
YueGuobinandClaude Opus 4.6 40644f33e6 Fix: Check compute connectivity before open() during project deletion
Previously the disconnected compute check ran after open(), which would
block for 120s trying to connect to unreachable remote computes before
rejecting the deletion. Now reads the topology file directly to extract
compute IDs and checks connectivity before calling open(), enabling
immediate rejection of deletions involving offline computes.

Also removes the redundant post-open() check since the early check
covers both opened and closed project states.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-07-12 10:57:56 +02:00
grossmj a9cce209d7 Development on 3.1.0.dev5 2026-07-10 10:01:35 +02:00
Jeremy Grossmann 94a131dab3 Merge pull request #2810 from yueguobin/feature/cloud-host-interface-ip-addresses
Expose full host interface IP addresses and link state in cloud node API
2026-07-10 09:19:54 +02:00
YueGuobin 0ed1715fe6 Use typed InterfaceStatus enum and simplify stats fallback in interfaces()
- Change `status: str` to `status: InterfaceStatus` (str Enum) in the
  HostInterface schema, matching the existing IPAddressFamily pattern.
- Use default-then-override pattern in interfaces() to eliminate the
  `else` branch and deduplicate defaults.
2026-07-10 14:55:21 +08:00
YueGuobin 9721660cc3 Expose full interface address list and link state in cloud node API
Each host interface surfaced by the cloud node now reports:
- ip_addresses: every IPv4 and IPv6 address (previously only a single
  IPv4 was collected internally and then dropped before the response)
- status / speed / mtu / flags: operational state and link attributes
  sourced from psutil.net_if_stats(), with flags normalized to a list

The legacy ip_address / netmask / mac_address fields are preserved so
existing callers (compute link detection, GNS3 VM, VMware, has_netmask)
keep working. The new fields travel through the existing interfaces
payload that the controller forwards verbatim, so no controller-side
change is required and the PUT / ports_mapping flow is unaffected.
2026-07-10 13:56:07 +08:00
grossmj a66740e154 Add script to create and push annotated git tags from version.py 2026-07-09 11:02:33 +02:00
grossmj 913d021705 Release v3.1.0a4 2026-07-09 10:40:38 +02:00
grossmj d64fdd71a9 Bundle web-ui v3.1.0a4 2026-07-09 08:40:05 +02:00
Jeremy Grossmann bdd73be6d6 Merge pull request #2808 from yueguobin/docs/jwt-refresh-token-config-example
Add jwt_refresh_token_expire_minutes to sample configuration
2026-07-09 08:34:25 +02:00
Guobin Yue 61ce59788b Merge branch '3.1' into docs/jwt-refresh-token-config-example 2026-07-09 14:19:14 +08:00
YueGuobin cccc3e5b77 Add jwt_refresh_token_expire_minutes to sample configuration
The sample gns3_server.conf documented jwt_access_token_expire_minutes but omitted jwt_refresh_token_expire_minutes (default 43200 minutes, 30 days) defined in ControllerSettings. Add it for parity with the schema.
2026-07-09 14:15:49 +08:00
grossmj 6fba497734 Remove deleted web-ui files from git 2026-07-08 22:40:27 +02:00
grossmj 54540e7ef7 Merge remote-tracking branch 'origin/3.1' into 3.1 2026-07-08 21:49:20 +02:00
grossmj 5992a284c9 Bundle web-ui v3.1.0a4 2026-07-08 21:48:48 +02:00
grossmj a2ee5389af Bundle web-ui v3.1.0a4 2026-07-08 20:11:59 +02:00
grossmj 4548d9053a Sync appliances 2026-07-08 18:45:07 +02:00
grossmj 2d3bb89e58 Merge remote-tracking branch 'origin/2.2' into 3.1 2026-07-08 10:33:00 +02:00
grossmj 809d4cc609 Merge branch 'master' into 2.2
# Conflicts:
#	.github/workflows/docker-build.yml
2026-07-08 10:30:53 +02:00
Jeremy Grossmann 89e4e836c9 Merge pull request #2806 from my-code-is-grey/2798-dockerhub
#2798 - DockerHub adjustments
2026-07-08 05:17:04 +02:00
my-code-is-grey 69ddcf553f .dockerignore ignore .dockerignore 2026-07-07 22:37:24 -04:00
my-code-is-grey 1e1ec5aae8 typo made me reconsider and move out to env 2026-07-07 21:58:49 -04:00
my-code-is-grey e30e6435ca defaulted DOCKERHUB_ORG repository variable 2026-07-07 21:48:13 -04:00
my-code-is-grey 77700f361c 2798 2026-07-07 01:30:58 -04:00
grossmj e3e3a7e729 Update fastapi to v0.139.0 2026-07-06 19:21:56 +02:00
grossmj 6415d2e56c Update dependencies 2026-07-06 19:06:25 +02:00
grossmj 424ae55c38 Revert "Update dependencies"
This reverts commit b6793a50f3.
2026-07-06 18:38:48 +02:00
grossmj b6793a50f3 Update dependencies 2026-07-06 18:31:52 +02:00
grossmj 562108748a Remove API docs from 2.2 after merging 2026-07-06 18:17:00 +02:00
grossmj d54b16df53 Merge branch '2.2' into 3.1
# Conflicts:
#	gns3server/handlers/api/controller/template_handler.py
#	tests/handlers/api/controller/test_template.py
2026-07-06 18:13:17 +02:00
Jeremy Grossmann ad4aa1d49b Merge pull request #2803 from GNS3/update-ga-workflows
Update GitHub Actions workflows
2026-07-06 18:10:17 +02:00
grossmj 8499ed3d65 Update GitHub Actions workflows 2026-07-06 18:05:28 +02:00
Jeremy Grossmann a0ca8761c0 Merge pull request #2802 from yueguobin/fix-web-wireshark-docker-xpra6.x
Fix web-wireshark docker build broken by xpra 6.5 release
2026-07-06 17:32:31 +02:00
Guobin Yue 277640a335 Merge branch '3.1' into fix-web-wireshark-docker-xpra6.x 2026-07-06 13:35:44 +08:00
YueGuobin f5a72532ac Fix web-wireshark docker build broken by xpra 6.5 release
Replace the `xpra=6.4*` version clamp on the apt-get install command
line with APT pinning via /etc/apt/preferences.d/pin-xpra.

The previous specifier stopped resolving once xpra 6.5 was released:
the xpra metapackage was pinned to 6.4 while its sub-packages
(xpra-client, xpra-server, xpra-codecs, ...) were unconstrained and
defaulted to 6.5, so apt could not satisfy the dependency graph and
the "Build Docker images" action failed.

Pinning all xpra* packages at the preferences level constrains the
whole set consistently (xpra-html5 is handled separately since it
follows a different version scheme, locked to v19). Blocking every
other version with priority -1 ensures that, if the pinned version
ever disappears from the repository, apt fails loudly instead of
silently upgrading to the latest release.

Fixes GNS3/gns3-registry#1044
2026-07-06 13:31:07 +08:00
Jeremy Grossmann 7650409ab6 Merge pull request #2797 from yueguobin/feature/optional-ai-support-2794
Make AI features (AI Copilot + MCP) optional via [ai-features] extra
2026-06-27 19:44:27 +02:00
YueGuobin e0ef63ebc1 Update CI to install [ai-features,dev] instead of [ai-copilot,dev]
The [ai-copilot] extra has been replaced by [ai-features] which
includes both AI Copilot and MCP dependencies.
2026-06-27 22:19:39 +08:00
YueGuobin 292b60efaa Make AI features (AI Copilot + MCP) optional via [ai-features] extra
- Move fastmcp from core requirements.txt to mcp-requirements.txt
- Add MCP_AVAILABLE feature flag in agent/__init__.py (graceful degradation)
- Guard MCP imports/registration in server.py and tasks.py
- Replace ai-copilot/mcp/ai-support extras with single ai-features extra
- Add stub MCP routes returning 501 when MCP is not installed
- Add gns3server-uninstall-ai-features CLI command
- Remove old gns3server-uninstall-ai-copilot command
- Update all error messages and docs to reference ai-features

Closes #2794
2026-06-27 10:14:43 +08:00
Jeremy Grossmann 58d3055dd3 Merge pull request #2792 from yueguobin/feature/refresh-token-mechanism-2786
Add stateless JWT refresh token mechanism
2026-06-24 00:26:07 +02:00
YueGuobin 0dd2fb4173 Add refresh token mechanism documentation under docs/features/ 2026-06-23 23:36:37 +08:00
YueGuobin c8c14af9f4 Add /refresh to allowed public endpoints list in route auth test 2026-06-23 23:19:07 +08:00
YueGuobin 0e8d0cb87b Add stateless JWT refresh token mechanism
- New config: Controller.jwt_refresh_token_expire_minutes (default 30 days)
- New endpoint: POST /v3/access/users/refresh (public, unauthenticated)
- Login/authenticate responses now include refresh_token
- AuthService: _create_token helper, create_refresh_token, get_token_data
  now parses type claim (token_use) for token classification
- Security: refresh tokens rejected on HTTP + WebSocket access paths;
  /refresh strictly requires type=='refresh'
- Logout works for free via existing token_version mechanism
- Tests: 9 new TestRefreshToken cases, all passing; 34 existing tests
  still pass (no regressions)
2026-06-23 22:39:11 +08:00
Jeremy Grossmann 4ffab7abee Merge pull request #2791 from yueguobin/fix/mcp-test-issues
Fix MCP testing issues: appliance_install version, handler unit tests, parameter validation
2026-06-17 21:07:59 +02:00
YueGuobin 471e65e48c Add project/node/link handler tests: 39 total, covering list/get/create/delete/start/stop/suspend/reload/console/update/fields 2026-06-18 00:07:14 +08:00
YueGuobin 5cc826baff Add MCP handler unit tests with mocked Gns3Connector
Tests cover:
- get_nodes_handler: fields filter, invalid fields rejection
- create_node_handler: name passthrough, fields filter, fields validation,
  batch mode inherited template_id, missing project_id
- create_link_handler: compact format, standard format, fields validation
- appliance_get, appliance_install with version
- list_templates: fields filter, invalid field error
2026-06-18 00:02:38 +08:00
YueGuobin dc3a386961 Add MCP tool parameter consistency tests 2026-06-17 23:59:40 +08:00
YueGuobin ead9747e1b Fix appliance_install: add version parameter 2026-06-17 23:03:28 +08:00
Jeremy Grossmann 2e75c9319b Merge pull request #2787 from yueguobin/optimize/project-open-speed
Performance: accelerate project opening with parallel link creation and batch UDP port allocation
2026-06-16 23:59:41 +02:00
YueGuobin f16eba183a Add coordinate system note to docs 2026-06-16 23:30:59 +08:00
YueGuobin 0d21f294f6 Document canvas coordinate system in node_create x/y params 2026-06-16 23:16:17 +08:00
YueGuobin 00647d092c Update docstring: batch concurrency from 10 to 100 2026-06-16 23:05:17 +08:00
YueGuobin da35eaa014 Remove unused import time 2026-06-16 23:04:05 +08:00
YueGuobin 10ff5b2283 Add list type check before nodes[0] access in _normalize_link_nodes 2026-06-16 23:00:47 +08:00
YueGuobin 0d45bfbae5 Add fields type validation in create handlers 2026-06-16 22:58:36 +08:00
YueGuobin 390a40ce80 Use pop() instead of pop(0) for O(1) port removal 2026-06-16 22:56:42 +08:00
YueGuobin 59e5f8dd2f Fix review issues: key_prefix length, count validation, WAL log, timeout comment, pointless temp var 2026-06-16 22:50:22 +08:00
YueGuobin 533d3d5b71 Fix: pass name from TemplateUsage to add_node_from_template
The controller endpoint received name via TemplateUsage but never
passed it to add_node_from_template, causing the name parameter to
be silently ignored. name is optional - if omitted the template's
default_name_format is used.
2026-06-16 22:43:46 +08:00
YueGuobin 68567118f1 Remove unused imports (logging, log, select) 2026-06-16 22:25:07 +08:00
YueGuobin af94c1729b Add warning for unconsumed pre-allocated UDP ports after link creation
Ports are properly released on project close (compute.post /close).
The warning alerts if any pre-allocated ports go unused within a session.
2026-06-16 22:22:46 +08:00
Jeremy Grossmann 7d5d4767bf Remove FIXME comment about middleware in server.py
Removed commented out FIXME note regarding middleware issues.
2026-06-16 12:20:55 +02:00
YueGuobin f7abb62603 Rename device_command_run_handler → device_show_run_handler to match tool name 2026-06-16 12:44:12 +08:00
YueGuobin fbb8924a8e Rename device_command_run → device_show_run for clarity
The name device_command_run was ambiguous and easily confused with
device_config_send. device_show_run makes the read-only intent explicit,
forming a clear pair: config_send (write) vs show_run (read).
2026-06-16 12:27:35 +08:00
YueGuobin e627481ec2 Fix device_command_run KeyError('commands'): tool desc said show_commands but backend expects commands
- Tool description and param schema now use 'commands' (matching ExecuteMultipleDeviceCommands)
- Updated error message in handler
- Clarified in docstring that this is read-only; use device_config_send for config changes
2026-06-16 12:23:15 +08:00
YueGuobin ec58bea24b Fix template_list return type annotation to match _run_handler_sync envelope
template_list was annotated as dict[str, Any] but _run_handler_sync always
returns a list envelope ([{"type":"text",...}]). Other tools use
list[dict[str, Any]] consistently. This caused a Pydantic dict_type
validation error on the client.
2026-06-16 12:08:07 +08:00
YueGuobin a126f910d4 Add performance optimization documentation 2026-06-16 01:14:12 +08:00
YueGuobin 48b7ea8bf0 Update MCP service docs: API key format, auth flow, tool parameters, concurrency 2026-06-16 01:13:01 +08:00
YueGuobin d407b29fe9 Increase HTTP connection pool to 500/1000 2026-06-16 00:58:12 +08:00
YueGuobin 74192f454f Increase BATCH_MAX_WORKERS and Pool concurrency from 20 to 100 2026-06-16 00:49:08 +08:00
YueGuobin 286b2407cd Remove final timing artifact in projects.py 2026-06-16 00:44:54 +08:00
YueGuobin bd15c8d019 Remove remaining dead timing variables and imports 2026-06-16 00:40:03 +08:00
YueGuobin a8cc01af46 Remove database warmup (proven ineffective - real bottleneck was bcrypt blocking event loop) 2026-06-16 00:35:42 +08:00
YueGuobin ccb629f48f Clean up all timing/debug logs
Remove all [MCP-TIMING] and [CTRL-TIMING] log lines, timing middleware,
and related import time statements across 11 files.
2026-06-16 00:34:11 +08:00
YueGuobin 8ef70d9fac Add memory: import validation best practice 2026-06-16 00:25:45 +08:00
YueGuobin 7d8ab399da Fix: add missing UUID imports 2026-06-16 00:24:37 +08:00
YueGuobin d6b337bc3a Generate fresh JWT on API key auth instead of returning raw key
When MCP client authenticates with API key, _resolve_token now
returns a newly generated JWT. This JWT is stored in the ContextVar
and used by all subsequent tool handler API calls - zero extra bcrypt.
2026-06-16 00:09:36 +08:00
YueGuobin f522c947bc Optimize API key auth: O(1) lookup via UUID-embedded key format
New format: gns3_<api_key_id>_<random_secret>
- Auth extracts api_key_id from token → single DB query by UUID → one bcrypt
- No more scanning all keys (was O(n) with bcrypt per key)
- bcrypt.checkpw offloaded to thread pool to prevent event loop blocking
- Legacy gns3_<random> format removed (compatibility break)
2026-06-15 23:56:36 +08:00
YueGuobin 796a2e6ca8 Fix: offload bcrypt.checkpw to thread pool to prevent blocking event loop
bcrypt.checkpw is CPU-bound (~1.3s per call) and was running
synchronously inside the async event loop, blocking ALL concurrent
requests. With 5 API keys and 10 concurrent requests, this caused
~13s delay before any handler could start.
2026-06-15 23:49:28 +08:00
YueGuobin 04f0657661 Add timing to API key auth path and log api_keys count 2026-06-15 23:45:26 +08:00
YueGuobin 3c41dea48f Replace SELECT 1 warmup with full database file read to warm OS page cache
Reading the entire DB file into OS page cache eliminates the 8-14s
cold-start penalty on the first ORM query (users/templates/api_keys).
Previous SELECT 1 only warmed the connection pool, not the file cache.
2026-06-15 23:43:41 +08:00
YueGuobin 5502b8f8e5 Add timing logs to auth dependency chain to identify 6s pre-handler delay 2026-06-15 23:35:12 +08:00
YueGuobin b3619a3c00 Add granular timing to get_template: separate execute vs fetch time 2026-06-15 23:33:19 +08:00
YueGuobin e90fb0774c Warm up database connection pool on startup to avoid 8s cold-start penalty on first API request 2026-06-15 23:26:28 +08:00
YueGuobin 6d3cfc7d1e Fix: register WAL PRAGMA on sync_engine instead of Engine class for async compat
- Move event listener from module-level @Engine to engine.sync_engine
- Add WAL mode verification log on startup
- Remove unused Engine class-level listener
2026-06-15 23:21:50 +08:00
YueGuobin 08e0dbc122 Add timing logs to get_template to identify DB query bottleneck 2026-06-15 23:18:00 +08:00
YueGuobin fa9aa5a9cc Add timing middleware to log slow requests (>1s) with [CTRL-TIMING] prefix 2026-06-15 23:13:36 +08:00
YueGuobin a855cb34f1 Fix: _time → time in compute.py timing log 2026-06-15 23:06:10 +08:00
YueGuobin ea4bb2c1fb Add [CTRL-TIMING] logs to controller create_node flow
Timing logs cover:
- create_node_from_template (entry, get_template, add_node, total)
- add_node_from_template (entry to done)
- _create_node (project_setup, node.create, total)
- Node.create (compute_post timing)
- compute._session.request (actual HTTP to compute)
2026-06-15 23:04:01 +08:00
YueGuobin e5797c3da0 Fix: pass template_id to batch mode handler so top-level template_id works as default 2026-06-15 22:57:40 +08:00
YueGuobin cef6dc6bd2 Add detailed timing logs to MCP node creation and HTTP client
Logs with [MCP-TIMING] prefix at:
- create_node_handler entry, setup, http_call start/end, total
- http_call entry, auth, response
- _authenticate_v3 entry, done, fail
2026-06-15 22:51:43 +08:00
YueGuobin 58ca6b1dd4 Add fields filter to template_list tool with description for AI 2026-06-15 22:11:14 +08:00
YueGuobin b79fb89866 Fix: add missing _filter_link_response function
Previously the function was referenced in create_link_handler
but never defined, causing NameError at runtime.
2026-06-15 21:51:17 +08:00
YueGuobin 1bb010d274 Pass name parameter through to controller API when creating node from template 2026-06-15 21:50:14 +08:00
YueGuobin eb3ac64016 Add validation to compact link format with clear error messages
- Validate array length (must be exactly 6)
- Validate node_id types at positions 0 and 3
- Return descriptive errors so AI can self-correct
2026-06-15 21:46:27 +08:00
YueGuobin a8a83051ff Add compact array format for link node entries to reduce token usage
Supports both standard and compact formats:
  Standard: [{"node_id": "uuid", "adapter_number": 0, "port_number": 0}]
  Compact:  ["uuid", 0, 0, "uuid", 0, 0] - 3x less tokens
2026-06-15 21:42:26 +08:00
YueGuobin 27a489a3fd Add fields filter to link_create tool
- Default response: link_id, link_type, nodes (3 fields vs full 13)
- Available fields listed in tool description for AI
2026-06-15 13:50:04 +08:00
YueGuobin 3465c39eaa Reduce md5sum cache write failure log level from error to warning
This is a non-fatal issue that occurs during concurrent project close
when multiple nodes try to write their md5sum cache while the project
directory is being cleaned up.
2026-06-15 13:27:14 +08:00
YueGuobin 11bf2d8cef Add fields filter to node_create tool description for AI
- Expose optional 'fields' parameter to AI via tool description
- List all available node fields in the parameter description
- Mention inherited template_id in batch mode
2026-06-15 13:22:32 +08:00
YueGuobin f4c8f9bf61 Optimize MCP create_node: support inherited template_id and default fields filter
- Batch mode now inherits top-level template_id as default per-node
- Both single and batch modes filter response to minimal fields by default
  (node_id, name, node_type, status, console)
- Optional 'fields' parameter overrides the default field set
2026-06-15 13:21:06 +08:00
YueGuobin 6cbe676b18 Increase MCP HTTP client timeout from 10s to 30s
Dynamips node creation (e.g., Cisco 7200 with multiple adapters)
can exceed the previous 10-second timeout, causing MCP tools to
fail with Read timed out errors.
2026-06-15 13:14:11 +08:00
YueGuobin 49d2c271ca Enable SQLite WAL mode to fix 'database is locked' errors under concurrent API requests 2026-06-15 13:02:17 +08:00
YueGuobin 650be3565f Cache IOU image default values per image path to avoid redundant subprocess calls
- Add class-level caches for loader and default RAM/NVRAM values
- When multiple IOU nodes use the same image, only the first one runs
  the ld-linux --verify and iou-image -h subprocesses
- Subsequent nodes reuse cached results, saving ~2 subprocess calls per node
- Cache is populated only on successful subprocess execution to avoid
  overwriting explicitly set ram/nvram values with stale cached defaults
2026-06-15 12:59:51 +08:00
YueGuobin 650f95af54 Increase node and link creation concurrency from 5 to 20 2026-06-15 12:50:59 +08:00
YueGuobin e29e02a8c6 Fix: revert IOU lock optimization, serialize IOU node creation for correct application_id assignment
The _iou_id_lock must cover _create_node() because get_next_application_id()
checks in-memory nodes (self._nodes), which are only registered after
_create_node() completes. Without this serialization, concurrent IOU
node creation produces duplicate application IDs.
2026-06-15 12:49:01 +08:00
YueGuobin 5d0284e7be Performance: accelerate project opening with parallel link creation and batch UDP port allocation
- Narrow IOU lock scope to only cover application_id allocation,
  allowing concurrent IOU node creation via Pool(concurrency=5)
- Parallelize link creation during project.open() using Pool(concurrency=5)
  instead of sequential processing
- Add batch UDP port allocation endpoint on compute to allocate N ports
  in a single HTTP call
- Pre-allocate UDP ports per compute before link creation during project
  loading, reducing HTTP round-trips
- UDPLink.create() falls back to individual port allocation if no
  pre-allocated port is available
2026-06-15 12:42:18 +08:00
Jeremy Grossmann b605d71a8a Merge pull request #2785 from yueguobin/mcp/batch-operations
MCP batch operations, field filtering, Jinja2 templates, download security, and WebSocket fixes
2026-06-15 00:47:17 +02:00
YueGuobin 97483310b1 docs: Update link tool descriptions for batch ops and fields filter 2026-06-14 22:51:06 +08:00
YueGuobin be69670333 feat: Add batch link_ids to link_delete/link_reset, fields filter to link_list 2026-06-14 22:43:44 +08:00
YueGuobin d6c362b3f0 feat: Add fields filter to link_list 2026-06-14 22:37:10 +08:00
YueGuobin 3b42eea112 feat: Add batch node_ids to node_delete 2026-06-14 22:28:28 +08:00
YueGuobin e17d298bc7 fix: Convert http to ws scheme in node_console WebSocket URL 2026-06-14 21:57:58 +08:00
YueGuobin 80d5ae91a4 docs: Update link capture batch ops and console short-lived JWT note 2026-06-14 21:47:25 +08:00
YueGuobin f14d30cb7e feat: Add batch link_ids to link_capture_download 2026-06-14 21:36:24 +08:00
YueGuobin 6df9374a4c feat: Add batch link_ids to link_capture_start/stop 2026-06-14 21:32:47 +08:00
YueGuobin e02f1a8cd0 fix: Store username in gns3_ctx during auth, use for short-lived download JWTs
_ jw t_username_var set in _resolve_token for both JWT and API key auth.
Passed to handlers via gns3_ctx['jwt_username']. No raw key exposure,
no fake-user fallback.
2026-06-14 14:00:41 +08:00
YueGuobin 678b1868f5 fix: Generate independent short-lived JWT for pcap download
No longer depends on the original token type (JWT or API key).
Always creates a fresh 10-min JWT for the download URL.
2026-06-14 13:49:24 +08:00
YueGuobin 754eab9609 docs: Clarify why nodes must be started for device config tools 2026-06-14 13:41:04 +08:00
YueGuobin 9f3a6a7e58 docs: Remove Claude Desktop section from MCP doc 2026-06-14 13:28:04 +08:00
YueGuobin f4b8de725c docs: Add device config workflow mermaid diagram 2026-06-14 13:20:25 +08:00
YueGuobin aabf54b6d1 docs: Add best practices section for device config — template usage, error checking, config backup 2026-06-14 13:11:15 +08:00
YueGuobin 647c5c0e65 docs: Add snapshot prerequisite and suppress telnetlib3 noise 2026-06-14 12:41:14 +08:00
YueGuobin b23f2181c4 docs: Update MCP doc with batch ops, field filtering, and Jinja2 template 2026-06-14 12:33:00 +08:00
YueGuobin c3c78f99a1 revert: Remove _configs_map changes in tools_v2 (handled by template renderer now) 2026-06-14 12:15:30 +08:00
YueGuobin c42b3a59bf fix: Merge commands for duplicate device_names in _configs_map
Dict comprehension overwrote earlier entries when the same device
appeared multiple times, causing all entries' outputs to collapse
into the last one. Now commands are appended for duplicate names.
2026-06-14 02:00:06 +08:00
YueGuobin fb032ade78 fix: Actually pass template param to device_config/command handlers
template was defined in the tool signature but omitted from
the params dict passed to the handler, making Jinja2 rendering
completely non-functional.
2026-06-14 01:40:48 +08:00
YueGuobin fed40c683e fix: Correct Jinja2 template commands_field per tool type
config_tools_nornir expects config_commands, while
display_tools_nornir and vpcs_tools_netmiko expect commands.
Render template now uses the correct field name.
2026-06-14 01:33:23 +08:00
YueGuobin 8aa7f2bde5 feat: Jinja2 template support in device_command_run 2026-06-14 00:27:49 +08:00
YueGuobin 06e1511773 feat: Jinja2 template support in device_config_send
- Add optional 'template' param with Jinja2 syntax
- Each device entry can use 'vars' dict instead of 'config_commands'
- Template rendered per device, merged with existing commands
- Rendering errors returned inline for AI self-correction
2026-06-14 00:27:13 +08:00
YueGuobin c647805cfb feat: Add batch node_ids support to node_start/stop/reload/suspend
- Each tool accepts either node_id (single) or node_ids (batch)
- Batch mode runs actions in parallel via ThreadPoolExecutor
- Useful for starting/stopping nodes by topology region
2026-06-14 00:14:34 +08:00
YueGuobin 3d3c0eb8db feat: Add fields filter to appliance_list
Appliances list can be very large (hundreds of entries). Use
fields=["name","category"] to return only what the AI needs.
2026-06-13 23:59:12 +08:00
YueGuobin cd8bb7cca2 feat: Add fields filter to node_list
- Matches same VALID_NODE_FIELDS as node_get
- Return only selected fields per node to save tokens
2026-06-13 23:54:24 +08:00
YueGuobin b9cc2d8bee feat: node_get fields filter — match controller Node schema fields 2026-06-13 23:26:41 +08:00
YueGuobin 8f8abe4106 fix: Set auto_close=False on project_create so projects stay open when clients disconnect 2026-06-13 23:13:31 +08:00
YueGuobin 2c1a83114d feat: Add batch mode to node_create and link_create (parallel, max 10 workers)
- node_create accepts nodes=[{template_id, x, y, name?}] for batch creation
- link_create accepts links=[{nodes, link_type?, filters?}] for batch creation
- Uses ThreadPoolExecutor for parallel REST API calls
- Max 10 concurrent workers per batch, backward compatible with single mode
2026-06-13 22:29:27 +08:00
Jeremy Grossmann 16d3f28cf5 Merge pull request #2782 from yueguobin/mcp/device-config
MCP (Model Context Protocol) integration — 82 tools with device config, API key auth, and bug fixes
2026-06-11 23:57:08 +02:00
YueGuobin a69485befa docs: Update MCP service documentation with 82 tools and API Key setup 2026-06-12 00:26:56 +08:00
YueGuobin f2e5d69a2c fix: Pass API key directly instead of generating short-lived JWT
REST API auth already supports gns3_ keys, so there's no need
to create a temporary 5-min JWT. The raw API key is passed
through as the Bearer token, eliminating token expiry issues.
2026-06-12 00:25:01 +08:00
Guobin Yue 47fa1bbe95 Merge branch '3.1' into mcp/device-config 2026-06-12 00:05:59 +08:00
YueGuobin a98707e91d chore: Remove redundant migration fixup
f0b0de2a9_add_api_keys_table already includes updated_at column,
so the fixup migration f0b0de2a9b is unnecessary.
2026-06-11 23:51:07 +08:00
YueGuobin 8ecc35193d feat: API key lifecycle — revoke/restore/delete
- POST /{id}/revoke: 吊销, revoked=True, 立即失效
- POST /{id}/restore: 恢复, revoked=False, 重新生效
- DELETE /{id}:       永久删除, 不可逆
- 列表接口显示所有 key 包括已吊销的
- 认证时过滤 revoked=False
2026-06-11 23:32:19 +08:00
YueGuobin 062e8dfbc4 chore: Remove unused revoke_api_key from repository 2026-06-11 23:28:43 +08:00
YueGuobin 700d71d675 fix: Rename revoke_api_key → delete_api_key 2026-06-11 23:28:05 +08:00
YueGuobin 9d441517fd fix: Hard-delete API keys instead of soft delete (revoked flag)
Removing the soft-delete approach — revoked keys are now deleted
from the database entirely via DELETE endpoint. This prevents the
api_keys table from accumulating stale records.
2026-06-11 23:27:43 +08:00
YueGuobin bfef0a36e3 feat: Support API keys in REST API authentication (reuse gns3_ prefix keys)
API keys can now be used in Authorization: Bearer header
for all REST API endpoints, not just MCP.
2026-06-11 23:21:49 +08:00
YueGuobin aed8830052 fix: Lazily access db engine for API key validation
_db_engine is not available when register_starlette_routes() is
called (it's set later during lifespan startup). Store the app
reference instead and access app.state._db_engine lazily.
2026-06-11 23:18:05 +08:00
YueGuobin d75746e029 fix: Add missing updated_at column to api_keys table
BaseTable base class includes updated_at, but the initial
migration didn't create the column. Added fixup migration.
2026-06-11 23:13:50 +08:00
YueGuobin f8340cb355 fix: Export ApiKeyCreate from schemas package 2026-06-11 22:56:44 +08:00
YueGuobin a79bc7dd20 feat: Add API Key support for MCP authentication
- New db model: api_keys table with bcrypt-hashed keys
- New API: POST/GET/DELETE /v3/access/api-keys endpoints
- MCP _resolve_token: validates API keys, resolves to 5-min JWT
- API keys inherit the creating user's RBAC permissions
- MCP auth supports both JWT (24h) and API key (permanent) tokens
2026-06-11 22:54:03 +08:00
YueGuobin 8e9afbcf92 fix: Validate JWT token exp claim — was silently ignored after migration to joserfc
joserfc.jwt.decode() does not validate the exp claim by default,
so expired tokens were accepted indefinitely. Added explicit check
after decoding. See issue #2781.
2026-06-11 22:32:12 +08:00
YueGuobin 0b2c784b81 docs: Fix appliance_install description - it does NOT download images 2026-06-11 12:13:31 +08:00
YueGuobin f0b0de2a91 docs: Add MCP sharing warnings to shared gns3_copilot modules 2026-06-11 12:11:13 +08:00
YueGuobin b69ff17850 docs: Fix image_install description - it auto-creates templates from uploaded images, not downloads 2026-06-11 12:00:36 +08:00
YueGuobin 05f12e1f15 docs: Clarify image_prune description - only removes unreferenced images 2026-06-11 01:42:27 +08:00
Jeremy Grossmann 5df385fabe Merge pull request #2780 from yueguobin/mcp/node-file-streaming
feat: Node file streaming, recursive listing, file type detection, file delete, and MCP file tools
2026-06-10 19:41:30 +02:00
YueGuobin d0960812aa docs: Clarify symbol_delete limitations (built-in vs custom symbols) 2026-06-11 01:35:14 +08:00
YueGuobin c2aae9529b fix: Add image field to template_create, document type-specific params in description 2026-06-11 01:34:34 +08:00
YueGuobin 828a770489 fix: Remove .json() calls on 204 responses for prune/install images 2026-06-11 01:28:19 +08:00
YueGuobin 9d7c482288 fix: Skip always-running nodes in start_all/stop_all
Always-running node types (Ethernet switch, Cloud, NAT, etc.)
return 405 when start/stop is called. is_always_running() already
tracks these types; start_all/stop_all now skip them.
2026-06-11 01:26:43 +08:00
YueGuobin 3db275b199 docs: Add GNS3 SVG rendering quirks to drawing_create description 2026-06-11 00:48:54 +08:00
YueGuobin 4b9572d565 docs: Add SVG shape examples to drawing_create tool description 2026-06-11 00:39:37 +08:00
YueGuobin 4266583922 fix: Add missing rotation parameter to drawing_update MCP tool
Parameter was defined in create_drawing but omitted from
update_drawing, causing rotation changes to be silently ignored.
2026-06-11 00:36:37 +08:00
YueGuobin 66975f54f7 fix: Map MCP device_command_run parameter to tool's expected field name
MCP sent 'device_commands' but the internal display_tools_nornir
expects 'device_configs'. Renamed parameter for consistency.
2026-06-11 00:14:00 +08:00
YueGuobin 571853599f docs: Update link_reset description with accurate UDP connection behavior 2026-06-10 23:59:45 +08:00
YueGuobin e7aa228ead fix: Update link_reset description to match actual behavior (delete + recreate) 2026-06-10 23:56:30 +08:00
YueGuobin 4ec80f8989 fix: Remove unsupported description param from project_create
GNS3 REST API ProjectCreate schema does not have a description field.
The parameter was silently ignored; now removed to avoid confusion.
2026-06-10 23:32:27 +08:00
YueGuobin 80e64ebbae fix: Fix symbol_get/upload/delete handlers for correct API paths
- get_symbol: URL was missing '/raw' suffix + tried .json() on binary SVG
  → now returns download URL + curl command (like download_capture_file)
- upload_symbol: URL was missing '/raw' suffix
  → now accepts SVG content string and POSTs to correct path
- delete_symbol: returns 204 No Content, .json() would fail
  → removed .json() call (just returns message)
2026-06-10 23:01:27 +08:00
YueGuobin d431ff6eaa feat: Log registered MCP tools at startup 2026-06-10 22:53:51 +08:00
YueGuobin 658a8d112b docs: Clarify compute tools descriptions about local compute vs database computes
compute_list and compute_get only return database-registered computes.
The built-in local compute is returned by server_statistics instead.
2026-06-10 22:44:54 +08:00
YueGuobin 8b014693a8 fix: Type compute_id as uuid.UUID to reject non-UUID values at MCP input layer
Previously compute_id was typed as str, so 'local' would pass MCP validation
and reach the controller API where it crashed. Now uuid.UUID type ensures
Pydantic rejects any non-UUID string before the handler runs.
2026-06-10 22:38:38 +08:00
YueGuobin 67fa65a9e0 fix: Require UUID for compute_get/images, remove 'local' string default
The end /v3/computes/{compute_id} expects the compute_id to be a
valid UUID. Previously the MCP tool defaulted to the string 'local',
which caused a ValueError in the database layer. Now compute_id is
required and callers must use compute_list first to resolve names to UUIDs.
2026-06-10 22:31:17 +08:00
YueGuobin e7038f1ae3 feat: Add device configuration MCP tools (config_send, command_run, vpcs_config_set)
- Add jwt_token/url parameters to get_device_ports_from_topology() and GNS3TopologyTool
  for MCP handler compatibility (backward compatible, auto-detection fallback)
- Add jwt_token/url pass-through to ExecuteMultipleDeviceConfigCommands,
  ExecuteMultipleDeviceCommands, and VPCSCommands _run() methods
- Create MCP handler device_config.py wrapping the 3 device config tools
- Register as device_config_send, device_command_run, vpcs_config_set
2026-06-10 14:34:35 +08:00
YueGuobin 87e14cc49e refactor: unify MCP tool naming to <module>_<action> convention
All 79 tools renamed for consistent alphabetical grouping:
- project_list, project_get, project_create, project_delete ...
- node_list, node_get, node_start, node_stop, node_file_list ...
- link_list, link_create, link_capture_start, link_capture_stop ...
- template_list, template_get ...
- snapshot_list, snapshot_create, snapshot_delete ...
- drawing_list, drawing_create, drawing_update ...
- symbol_list, symbol_get, symbol_upload ...
- appliance_list, appliance_get ...
- image_list, image_get, image_delete ...
- server_version, server_statistics ...
- compute_list, compute_get, compute_images ...
2026-06-10 14:07:34 +08:00
YueGuobin 41594faf43 feat: Add symbol upload/delete, project load, and locked check MCP tools 2026-06-10 13:59:39 +08:00
YueGuobin b786f0b7eb feat: Add image management MCP tools
- Image tools: get_images, get_image, delete_image, prune_images, install_images
2026-06-10 13:58:42 +08:00
YueGuobin e4d2faec37 feat: Add symbol and appliance MCP tools
- Symbol tools: get_symbols, get_symbol, get_symbol_dimensions, get_default_symbols
- Appliance tools: get_appliances, get_appliance, install_appliance
2026-06-10 13:57:52 +08:00
YueGuobin db9f645c98 feat: Add node bulk ops, project lock, and server info MCP tools
- Node bulk: start_all_nodes, stop_all_nodes, suspend_all_nodes, reload_all_nodes
- Node advanced: duplicate_node, isolate_node, unisolate_node, get_node_links
- Project: lock_project, unlock_project
- Server: get_version, get_statistics
2026-06-10 13:56:43 +08:00
YueGuobin e7fbb3ec10 feat: Add snapshot and drawing MCP tools
- Add snapshot tools: get_snapshots, create_snapshot, delete_snapshot, restore_snapshot
- Add drawing tools: get_drawings, create_drawing, get_drawing, update_drawing, delete_drawing
2026-06-10 13:55:13 +08:00
YueGuobin acce79d243 refactor: unify MCP handlers to use http_call directly, relocate node file ops to Node class
- Move node file operations (list_files, delete_file) from Gns3Connector to Node class
- Add link capture/reset operations (reset, start_capture, stop_capture) to Link class
- Convert all MCP handlers to use conn.http_call() directly instead of
  Gns3Connector/Node/Link abstraction methods
- Register 4 new MCP tools: reset_link, start_capture, stop_capture,
  download_capture_file
2026-06-10 13:47:10 +08:00
YueGuobin 28b06f37c4 feat: Add node file operations as MCP tools (list, get, write, delete)
- Add list_node_files, get_node_file, write_node_file, delete_node_file methods to Gns3Connector
- Add MCP handlers with offset/limit line-based reading for get_node_file
- Auto-truncate files >50KB with truncated flag in response
- Rich metadata returned (total_lines, total_bytes, has_more, etc.)
- Tool docstrings guide AI to check file sizes before reading chunked
2026-06-10 12:16:35 +08:00
YueGuobin 066b7076c0 Add comment about rootful Docker permissions at container start
Rootful Docker recreates volume mount points as root on start,
preventing the GNS3 process from writing files into node directories
while the container is running. self._fix_permissions() would resolve
this but is currently only called at container stop time.
2026-06-10 00:46:10 +08:00
YueGuobin ce95c89b64 Fix _fix_permissions test: set process.returncode=0 and update assertion
- Set returncode=0 on mock process to follow the success path
- Update assertion to include stderr=asyncio.subprocess.PIPE parameter
2026-06-10 00:44:12 +08:00
YueGuobin eb15c7138b Fix list_node_files PermissionError on os.scandir
Wrap os.scandir() in try-except to return empty list instead of
crashing when a node directory is not readable.
2026-06-10 00:15:26 +08:00
YueGuobin 1a307edbca Fix _fix_permissions error handling and list_node_files PermissionError
- _fix_permissions: capture stderr, check returncode, only set
  _permissions_fixed on success instead of silently marking as fixed
- list_node_files: wrap os.scandir in try-except to handle
  PermissionError gracefully
2026-06-10 00:14:40 +08:00
YueGuobin e659b64bf0 Add async_iterable_to_stream utility to avoid aiohttp compatibility issues
Create async_iterable_to_stream() in gns3server.utils.asyncio that
converts an async iterable to an aiohttp StreamReader via a background
feeder task. This bypasses aiohttp's AsyncIterablePayload which can
cause 'Connection reset by peer' with certain HTTP servers.

Use it in _run_http_query for the __aiter__ data path.
2026-06-09 23:55:59 +08:00
YueGuobin 8e340f0ce8 Add descriptive detail to 403 errors in compute file endpoints
Both is_safe_path rejection and PermissionError were returning 403
without a detail message, making them indistinguishable in logs.
Add specific detail strings to each:
- is_safe_path: 'Path is outside the project directory'
- PermissionError (write): 'Permission denied writing to ...'
- PermissionError (delete): 'Permission denied deleting ...'
2026-06-09 23:33:35 +08:00
YueGuobin 16a9064eb8 Fix silent file write failure in write_compute_project_file
The inner try-except caught OSError/UnicodeEncodeError with 'pass',
silently swallowing all write failures and returning HTTP 204 as if
the file was written successfully.

Remove the nested try-except and let errors propagate properly:
- OSError → 500 with error detail
- PermissionError → 403 (already handled)
- FileNotFoundError → 404 (already handled)
2026-06-09 23:27:45 +08:00
YueGuobin cbb21e8e40 feat: Node file streaming, recursive listing, file type detection, and file delete
- Stream file GET/POST through controller without buffering in memory
- Add recursive and subdirectory filtering to node file listing
- Replace file extension with magic-based file type detection
- Add DELETE endpoint for node and project files
- Include directories in listing response
- Add params and stream support to http_query
- Fix lambda closures, streamer exception scope, and delete error codes
2026-06-09 22:52:50 +08:00
Jeremy Grossmann c70a4660c1 Merge pull request #2777 from yueguobin/mcp/project-tools
Add MCP project tools: update, duplicate, and README operations
2026-06-07 18:11:16 +02:00
YueGuobin f91d7b18e9 Update README tool descriptions: .txt → .md
Only description strings changed to tell AI the content is Markdown
format (.md). The actual handler still reads/writes README.txt for
Web UI compatibility.
2026-06-07 23:32:26 +08:00
YueGuobin 4ca1a80adb Update README tool descriptions to mention Markdown format
Web UI supports rendering Markdown in README.txt, so note this in the
tool descriptions and content parameter.
2026-06-07 23:23:38 +08:00
YueGuobin 4921b98948 Add MCP project tools: update, duplicate, and README operations
- Add update_project and duplicate_project MCP tools
- Add get_project_readme and update_project_readme tools
- Add Gns3Connector methods: update_project, duplicate_project,
  get_project_file, write_project_file
2026-06-07 23:14:07 +08:00
grossmj 95b1a35300 Development on 3.1.0.dev4 2026-06-07 00:13:59 +02:00
grossmj aad66e8ede Release v3.1.0a3 2026-06-06 23:19:24 +02:00
grossmj 259b7824af Bundle web-ui v3.1.0a3 2026-06-06 23:11:04 +02:00
grossmj bd22911066 Sync appliances 2026-06-06 22:53:12 +02:00
Jeremy Grossmann c6a6cd9ad9 Merge pull request #2776 from yueguobin/fix/mcp-template-update-kwargs-handling
Fix MCP tool parameter handling for nested kwargs
2026-06-06 18:52:12 +02:00
Guobin Yue fbe6b280d5 Merge branch '3.1' into fix/mcp-template-update-kwargs-handling 2026-06-07 00:37:02 +08:00
YueGuobin 012df5af57 docs: add simplified MCP tool description guide to project memory
Added a focused, concise memory document about MCP tool description
location. Simplified from 180 lines to 45 lines to capture only the
essential information needed for future conversations.

Key points documented:
- MCP tool descriptions are defined in @mcp.tool() functions in __init__.py
- NOT in *_TOOLS arrays in individual module files
- Must restart GNS3 server to see description updates
- Description requirements: explicit formats, ranges, and examples

This replaces the verbose 180-line version with a practical 45-line
guide focused on answering: 'Where should I write tool descriptions so
the AI can see them?'
2026-06-07 00:32:39 +08:00
YueGuobin 1f985a2823 fix: update MCP link tools descriptions with detailed filter info
Updated the actual MCP tool definitions in __init__.py with detailed
filter parameter descriptions. The previous update to links.py was incorrect
because MCP tools are defined via @mcp.tool() decorators in __init__.py.

Changes:
- Updated update_link tool docstring with comprehensive filter information
- Updated create_link tool filters parameter description
- Added all 5 filter types with proper array format requirements
- Added parameter ranges and usage examples

Filters now properly documented:
- frequency_drop: [N] (N: -1 to 32767)
- packet_loss: [rate] (rate: 0 to 100)
- delay: [ms, jitter] (milliseconds)
- corrupt: [rate] (rate: 0 to 100)
- bpf: [expression] (BPF syntax)

This will prevent TypeError: 'int' object is not iterable errors and
help users understand the correct filter format.
2026-06-07 00:20:29 +08:00
YueGuobin eac6c9f17d docs: improve MCP link tools filter parameter descriptions
Updated the filters parameter description in create_link and update_link
MCP tools to specify the required array format and provide examples.

Changes:
- Updated create_link filters description with array format requirements
- Updated update_link filters description with array format and example
- Added specific filter types: frequency_drop, packet_loss, delay, corrupt, bpf

This helps users understand the correct format:
- frequency_drop: [N] (drop every Nth packet)
- packet_loss: [rate] (packet loss percentage)
- delay: [ms, jitter] (latency and jitter in milliseconds)
- corrupt: [rate] (packet corruption percentage)
- bpf: [expression] (Berkeley Packet Filter)

Prevents TypeError: 'int' object is not iterable errors.
2026-06-06 23:46:22 +08:00
YueGuobin 3ba11c8bff fix: correct MCP nodes and links tool parameter handling for nested kwargs
Extended the kwargs parameter handling fix to nodes and links MCP tools,
which had the same nested kwargs structure issue as templates.

Changes:
- Modified update_node_handler to extract params from nested kwargs
- Modified update_link_handler to extract params from nested kwargs

This ensures that node and link updates through MCP tools work correctly,
allowing proper modification of node and link properties.
2026-06-06 23:31:32 +08:00
YueGuobin 0d22d275fb fix: correct MCP template tool parameter handling for nested kwargs
Fixed an issue where MCP template tools (update_template, create_template)
were not correctly handling nested kwargs parameter structure from MCP clients.

The problem occurred when MCP clients passed parameters in the format:
  {'template_id': 'xxx', 'kwargs': {'adapters': 3}}

The original code was passing the entire kwargs dictionary as a parameter,
instead of extracting the actual update parameters from within it.

Changes:
- Modified update_template_handler to extract params from nested kwargs
- Modified create_template_handler to handle the same issue

This fix ensures that template updates through MCP tools now work correctly,
allowing proper modification of template properties like adapters count.
2026-06-06 23:26:21 +08:00
Jeremy Grossmann 93293a327d Merge pull request #2775 from yueguobin/fix/mcp-initialization-ready-check
Feature: add MCP server initialization check with ready state tracking
2026-06-06 16:56:18 +02:00
Guobin Yue 0a97e85a21 Merge branch '3.1' into fix/mcp-initialization-ready-check 2026-06-06 22:48:36 +08:00
Jeremy Grossmann 8e50d3f31b Merge pull request #2774 from cristian-ciobanu/3.1
fix(templates): Database error detected when saving a template with a disk image change
2026-06-06 16:40:52 +02:00
YueGuobin 3958279b8a feat: add client information logging to MCP connection rejection
Add reusable utility for extracting client information from ASGI scope:
- Create gns3server/utils/request_utils.py with extract_client_info()
- Extract client IP, port, path, method, and authenticated username
- Format comprehensive log messages with client context

Benefits:
- Better observability for connection rejection events
- Reusable utility for other modules
- Consistent client logging format across codebase
- Helps diagnose timing issues during server startup

Usage:
  from gns3server.utils.request_utils import extract_client_info
  client_info = extract_client_info(scope, auth_service)
  log.warning(f"Connection rejected - Client: {client_info['host']}:{client_info['port']} ({client_info['user_info']})")
2026-06-06 22:35:43 +08:00
YueGuobin 9e5b575d1c refactor: replace MCP ready state polling with asyncio.Event
Replace the global variable + lock + polling mechanism with asyncio.Event
pattern for MCP server ready state tracking.

Benefits:
- Eliminates race conditions (Event.set() is thread-safe)
- Event-driven notification instead of polling (no 50x sleep overhead)
- Fixes test contamination from global state
- Reduces code from 54 lines to 30 lines
- Uses standard asyncio primitive for this pattern
2026-06-06 22:24:10 +08:00
Cristi 03b3078271 fix: revert duplicate image check to fix failing tests 2026-06-06 15:04:06 +03:00
Cristi 1e40fa1b70 fix (templates): Add ordering to handle the duplicate cases gracefully 2026-06-06 14:46:27 +03:00
Cristi da3a34144b fix(templates): Database error detected when saving a template with a disk image change 2026-06-06 14:21:15 +03:00
YueGuobin 67a960fbce fix: return 503 error on MCP server ready timeout
Instead of allowing connections to proceed when server initialization
times out, return HTTP 503 Service Unavailable to prevent MCP
protocol initialization errors.

This prevents the original "Received request before initialization
was complete" errors when GNS3 server startup takes longer than
the 5-second timeout.
2026-06-06 15:23:52 +08:00
YueGuobin b1514edf88 fix: add MCP server ready check to prevent initialization errors
Add server ready state tracking for MCP service to prevent
"Received request before initialization was complete" errors
when clients connect before GNS3 server completes startup.

Changes:
- Add MCP server ready state management with wait/notify mechanism
- Modify auth wrapper to wait for server initialization before accepting connections
- Set MCP server ready flag after GNS3 startup completes

This ensures MCP protocol initialization handshake only occurs
after GNS3 server is fully initialized, preventing race
conditions during server startup.
2026-06-06 15:21:17 +08:00
Jeremy Grossmann 13d1563762 Merge pull request #2772 from yueguobin/feature/mcp-transport-security-config
feat: add configurable MCP transport security settings via gns3_server.conf
2026-06-05 19:05:23 +02:00
YueGuobin 1dcbd9199f docs: document MCP server URL host resolution behavior
Add documentation explaining how _server_url() resolves the host
when Server.host is 0.0.0.0 or :: — using the default route
interface IP instead of hardcoding 127.0.0.1.
2026-06-06 00:52:21 +08:00
YueGuobin db9772ca7a fix: resolve MCP server URL host via default route IP when bound to 0.0.0.0
When GNS3 server is configured to listen on 0.0.0.0 (all interfaces),
_server_url() was hardcoding 127.0.0.1, making the WebSocket console
URL unreachable from remote MCP clients.

Use the UDP connect trick (connect to 8.8.8.8:80 without sending data)
to discover the default route interface IP, which is the address remote
clients can actually reach.
2026-06-06 00:48:22 +08:00
YueGuobin 4d87b57f18 docs: add MCP transport security documentation
Added Transport Security section to MCP service documentation covering:
- Default behaviour (disabled, allow all hosts)
- How to enable protection via gns3_server.conf
- Protection mechanism (Host header validation)
- DNS rebinding attack prevention explanation
- Behaviour summary table
2026-06-05 23:40:01 +08:00
YueGuobin 0e6db9a7b6 fix: correct MCP transport security config to actually allow all hosts by default
The MCP library's TransportSecurityMiddleware only supports exact host
matches or "host:*" port wildcards. It does NOT support a standalone "*"
wildcard to mean "allow all hosts" — setting allowed_hosts=["*"] would
reject every connection because no Host header equals "*".

Worse, when transport_security=None was passed to FastMCP while its default
host is "127.0.0.1", FastMCP would auto-enable protection with strict
localhost-only rules, overriding GNS3's intent to allow all hosts.

Root cause analysis:
- FastMCP auto-enables DNS rebinding protection when host is localhost
  and no explicit TransportSecuritySettings is provided
- GNS3 was passing transport_security=None (indirectly via FastMCP's default)
  when protection was disabled, triggering the auto-enable
- The TransportSecuritySettings "allowed_hosts" list does NOT support "*"
  as a catch-all wildcard

This fix:
1. Always pass an explicit TransportSecuritySettings to FastMCP
   - Disabled: TransportSecuritySettings(enable_dns_rebinding_protection=False)
   - Enabled: TransportSecuritySettings(enable_dns_rebinding_protection=True, ...)
2. Restore mcp_allowed_hosts and mcp_allowed_origins config fields
3. Set mcp_enable_dns_rebinding_protection default to False (allow all hosts)

Behaviour:
- Default (no config change): all hosts can connect to MCP server
- With mcp_enable_dns_rebinding_protection=true: only configured hosts
- Aligns with GNS3 server's 0.0.0.0 binding policy
2026-06-05 23:20:57 +08:00
YueGuobin bb39238f02 feat: add configurable MCP transport security settings via gns3_server.conf
Add MCP transport security configuration to gns3_server.conf with permissive
defaults that align with GNS3's design philosophy and VM distribution requirements.

## Changes

### 1. Configuration Schema (gns3server/schemas/config.py)
- Added MCP transport security fields to ServerSettings class:
  - mcp_enable_dns_rebinding_protection (bool, default: True)
  - mcp_allowed_hosts (list[str], default: ["*"])
  - mcp_allowed_origins (list[str], default: ["*"])
- Added field validators to handle comma-separated string input

### 2. MCP Server Initialization (gns3server/api/routes/mcp/__init__.py)
- Import TransportSecuritySettings from mcp.server.transport_security
- Added _create_mcp_server() function to read configuration
- Updated FastMCP instantiation to use configured security settings

### 3. Configuration Sample (gns3server/config_samples/gns3_server.conf)
- Added MCP transport security settings section
- Documented default behavior and security options
- Provided examples for different use cases

## Design Philosophy

**Default: Allow All Hosts** (matches GNS3's 0.0.0.0 binding):
- VM distribution works out-of-the-box
- Users can access from any network location
- Security-conscious users can restrict when needed

**Security: Optional Restriction**:
Users can configure specific hosts for enhanced security:
``ini
mcp_allowed_hosts = 127.0.0.1:*,localhost:*,192.168.1.3:*
mcp_allowed_origins = http://127.0.0.1:*,http://localhost:*,http://192.168.1.3:*
```

## Benefits

- Flexible: Users can configure based on security requirements
- User-friendly: Default matches GNS3's 0.0.0.0 binding philosophy
- Maintainable: No code changes needed for different deployment scenarios
- Secure: DNS rebinding protection remains enabled with configurable hosts

## Related

- Issue #2771
- FastMCP DNS rebinding protection design
- Existing skills configuration in ServerSettings
2026-06-05 23:06:06 +08:00
Jeremy Grossmann 68f63597eb Merge pull request #2769 from yueguobin/fix/load-feature-skills
fix: add load_feature_skills() to properly load network planning features
2026-06-05 16:58:06 +02:00
YueGuobin e76f3970ca fix: add load_feature_skills() to properly load network planning features
The feature directory contains network planning and design functionalities
(e.g., topology_planner), not device-specific features. These were not being
loaded because load_device_skills() only scanned the device directory.

Changes:
- Added new load_feature_skills() method in SkillsLoader
- Modified reload_skills() to load both device and feature directories
- Device skills: device-specific configurations (e.g., VPCS)
- Feature skills: network planning functionalities (e.g., topology planner)
- Both are now properly loaded into SKILLS_REGISTRY

This ensures that network planning features like topology_planner are available
via the device_skills tool with proper category classification.
2026-06-05 22:25:17 +08:00
Jeremy Grossmann 6497db6f30 Merge pull request #2768 from yueguobin/feature/mcp-service
feat: MCP (Model Context Protocol) service with SSE transport
2026-06-05 10:25:58 +02:00
YueGuobin 24953c1712 refactor: convert all MCP tool parameter descriptions to Annotated+Field
- Replace Args: docstring blocks with Annotated[str, Field(description=...)]
  so parameter descriptions appear in inputSchema.properties.*.description
- mcp.server.fastmcp does not parse Args: blocks from docstrings;
  only Annotated with pydantic Field injects descriptions into the
  structured JSON Schema visible to AI clients via tools/list
- Remove redundant Args: blocks from docstrings (info moved to Field)
- Restore full 4-step websocat workflow in get_node_console_info docstring
  with connection, command sending, response receiving, and timeout
2026-06-05 14:02:58 +08:00
YueGuobin 62db5caf6a fix: remove platformdirs upper bound to resolve fastmcp-slim dependency conflict
- Remove platformdirs<3 constraint (was for Debian packaging only)
- fastmcp-slim>=3.4.0 requires platformdirs>=4.0.0
- Debian packaging is no longer a concern
2026-06-05 13:38:25 +08:00
YueGuobin 4c44a32db7 docs: update get_node_console_info description with websocat connection workflow 2026-06-05 13:17:23 +08:00
YueGuobin b415ae0af6 fix: add missing fastmcp dependency to resolve CI test failures
- Add fastmcp>=3.4.0 to requirements.txt
- Fixes ModuleNotFoundError: No module named 'mcp'
- Resolves CI test failures in compute routes tests
2026-06-05 12:32:27 +08:00
YueGuobin a056fa3450 refactor: move all imports to top of __init__.py 2026-06-05 01:16:17 +08:00
YueGuobin f1078a97e2 test: add /v3/mcp/ to allowed public endpoints 2026-06-05 01:07:20 +08:00
YueGuobin f9f7ba7a53 docs: update memory record to 30 tools 2026-06-05 00:20:34 +08:00
YueGuobin 25dc1e9009 docs: update MCP feature doc to cover all 30 tools and console WS 2026-06-05 00:20:13 +08:00
YueGuobin f34de4c075 fix: remove console_host/port from get_node_console_info
Return only ws_url + websocat command to avoid LLM misinterpreting
direct telnet connection.
2026-06-04 23:53:03 +08:00
YueGuobin 8775583b83 feat: add get_node_console_info tool
Returns console type, host, port and a suggested command (e.g. telnet,
vncviewer) for connecting to a node's console. Total: 30 tools.
2026-06-04 23:45:34 +08:00
YueGuobin 0c572f2e9c docs: add MCP service design memory record 2026-06-04 23:25:22 +08:00
YueGuobin e416ef8d5e feat: add 3 Compute MCP tools
- Add list_computes, get_compute, get_compute_images
- Total MCP tools: 29
2026-06-04 23:22:14 +08:00
YueGuobin 6889f51737 feat: add 5 Template MCP tools
Add list_templates, get_template, create_template, update_template,
delete_template. Total MCP tools: 26.
2026-06-04 23:21:01 +08:00
YueGuobin cad216705a feat: add Node and Link MCP tools, update copyright
- Add 9 node tools and 5 link tools
- Update copyright year to 2026, add author
2026-06-04 23:19:00 +08:00
YueGuobin 5b23ac81d0 docs: add MCP service feature documentation 2026-06-04 23:09:44 +08:00
YueGuobin ccdd307d54 docs: add MCP service feature documentation 2026-06-04 23:09:08 +08:00
YueGuobin 1e9b3d5879 feat: complete MCP SSE transport with JWT auth
- SSE endpoint at /v3/mcp/transport/sse with token auth
- Supports Authorization: Bearer header and ?token= query param
- JWT validated via GNS3 auth_service, stored in contextvars
- Tool handlers use GNS3 REST API via Gns3Connector with JWT token
- 7 project tools: list_projects, get_project, create_project,
  delete_project, open_project, close_project, get_project_stats
- Claude Code: claude mcp add --transport sse ... -H 'Authorization: Bearer <jwt>'
- Claude Desktop: SSE URL with ?token=<jwt>
2026-06-04 23:06:20 +08:00
YueGuobin 19e7533cd7 feat: support Authorization header and query param for MCP token
- SSE endpoint supports both Authorization: Bearer header and ?token= query param
- Claude Code can use headers (no URL exposure)
- Claude Desktop (EventSource) can use ?token= URL param
2026-06-04 22:38:49 +08:00
YueGuobin 55b3a7d622 feat: implement standard MCP protocol with SSE transport
- Use FastMCP (Anthropic MCP SDK) for tool registration and SSE transport
- Mount SSE app under /v3/mcp/transport with JWT token authentication
- Token passed via ?token=<jwt> query parameter on SSE connection
- Token validated against GNS3 auth_service and stored in contextvars
- Tool handlers create Gns3Connector with JWT token to call GNS3 REST API
- 7 project tools: list_projects, get_project, create_project, delete_project,
  open_project, close_project, get_project_stats
- Unauthenticated SSE connections return 401
2026-06-04 22:19:43 +08:00
YueGuobin 7086db4226 feat: add MCP (Model Context Protocol) service with project tools
- Add MCPTool/MCPToolRegistry system for centralized tool registration
- Add 7 project-related MCP tools: list_projects, get_project, create_project,
  delete_project, open_project, close_project, get_project_stats
- Tools use Gns3Connector (custom_gns3fy) to call GNS3 REST API via HTTP loopback,
  keeping the MCP layer decoupled from controller internals
- Handlers run in thread pool via asyncio.to_thread() to avoid blocking
  the event loop on synchronous requests calls
- Unified POST /v3/mcp/execute endpoint with JWT authentication
2026-06-04 13:53:05 +08:00
Jeremy Grossmann 6c7e8fb370 Merge pull request #2767 from yueguobin/fix/docker-container-status-detection
Add running project check for fast duplication
2026-06-03 18:44:22 +02:00
YueGuobin fb1a5a3385 Add project memory: Docker container stop delay analysis 2026-06-03 22:47:48 +08:00
YueGuobin e8e1930e0b Remove extra blank line from merge 2026-06-03 22:22:03 +08:00
YueGuobin 4adaba8e8c Revert container state detection in create()
The _get_container_state() call in create() has no practical effect:
Docker's POST /containers/create only creates the container without
starting it, so a newly created container can never be in 'running'
or 'paused' state.
2026-06-03 22:20:34 +08:00
YueGuobin 2adc09604c Fix Docker VM tests for container status detection on node creation
The create() method now calls _get_container_state() after creating the
container to detect if the container is already running. Mock this method
in all test_create_* tests so the new code path doesn't fail with
KeyError: 'State' when the Docker.query mock response lacks a State field.
2026-06-03 22:17:43 +08:00
Guobin Yue 9712e9328a Merge branch '3.1' into fix/docker-container-status-detection 2026-06-03 21:49:56 +08:00
Jeremy Grossmann 305f1cad21 Merge pull request #2766 from yueguobin/fix/web-ui-update-script-remote-check
Fix web-ui update script to handle custom GitHub URL changes
2026-06-03 09:30:01 +02:00
YueGuobin 7ab04a0f9a Add running project check for fast duplication 2026-06-03 12:20:26 +08:00
YueGuobin b6e1f84740 Move running project check before fast duplication
Move the is_running() check from _fast_duplication() to
duplicate() to avoid the error message being wrapped by
the except Exception handler. This ensures the error
message is clean and prevents wasted fast duplication
attempts on running projects.
2026-06-03 12:18:28 +08:00
YueGuobin c4440d882d Add running project check for fast duplication
Add is_running() check at the beginning of _fast_duplication()
to prevent duplicating a project while nodes are running.
Previously, only the export/import fallback path had this check,
which meant running nodes were not detected when fast duplication
succeeded. This aligns with the duplicate API behavior and
provides a consistent safeguard against data inconsistencies.
2026-06-03 12:15:27 +08:00
YueGuobin 45b5f8d7e2 Fix Docker container status detection on node creation
When a Docker container is created (e.g., when loading a project), the node
status should reflect the actual container state. Previously, the node status
was always set to 'stopped' even if the container was already running.

This fix checks the container state after creation and updates the node
status accordingly:
- If container is running: status = 'started'
- If container is paused: status = 'suspended'
- If container is exited: status = 'stopped' (default)

This ensures that project.is_running() correctly detects running Docker
containers when attempting to export/duplicate a project, fixing the issue
where running Docker nodes were not detected and prompted for shutdown.
2026-06-03 11:51:55 +08:00
YueGuobin d4fb45f862 Fix web-ui update script to handle custom GitHub URL changes
When using --url parameter with a different GitHub repository, the script
now checks if the existing clone's remote matches the provided URL. If they
don't match, it removes the old clone and re-clones from the new URL.

This prevents errors when switching between different forks or branches
of the gns3-web-ui repository.
2026-06-03 11:25:00 +08:00
Jeremy Grossmann 1d7feaf994 Merge pull request #2765 from GNS3/upgrade-dependencies
Upgrade dependencies
2026-06-02 18:11:51 +02:00
grossmj 5f3978c57c Upgrade pytest-asyncio to v1.4.0 2026-06-02 18:07:41 +02:00
grossmj 18e20f0918 Upgrade dependencies 2026-06-02 17:48:16 +02:00
Jeremy Grossmann 5ab05fb688 Merge pull request #2762 from yueguobin/fix/docker-container-rename
Fix unnecessary Docker container recreation when renaming a project
2026-06-02 09:34:11 +02:00
YueGuobin 0ba180ad1d Fix unnecessary Docker container recreation when renaming a project
When renaming a project that has running Docker containers, the containers
were unnecessarily stopped, removed, and recreated, even though the project
name change doesn't affect container configuration.

Root cause:
- Client sends complete project object including variables: [] during rename
- Controller unconditionally notified all computes about the update
- Docker nodes rebuild containers on any project update notification

Solution:
- Only notify compute nodes when variables field has actual content
- Treat None and [] as semantically equivalent (no variables)
- Empty variables don't affect running containers, so no need to update

Impact:
- Project rename operations no longer trigger ~7 second container rebuilds
- Only actual variable changes trigger container recreation
- Fixes issue #2760
2026-06-02 13:04:44 +08:00
grossmj 06b02981df Development on 3.1.0.dev3 2026-06-02 00:04:50 +02:00
Jeremy Grossmann 1f98d18ae7 Merge pull request #2761 from yueguobin/fix/project-rename-filename-sync
Fix project rename and duplicate issues (#2759)
2026-06-01 23:59:24 +02:00
YueGuobin b5d3556add Fix project rename and duplicate issues
Fixes #2759

When renaming a project:
- Update self._filename to match the new project name
- Rename the .gns3 file on disk to keep it in sync
- Add error handling for file rename failures

When duplicating a project:
- Use self._filename (actual filename) instead of self.name
- This handles the case where a project has been renamed
- Prevents 'No such file or directory' errors

The root cause was that project renaming only updated the project name
in memory and in the .gns3 file content, but did not update the actual
.gns3 filename. This caused duplicate operations to fail because they
tried to read a file with the new name that didn't exist.
2026-06-01 22:19:44 +08:00
Jeremy Grossmann 12347b24aa Merge branch '3.1' into base-configs-3.0 2026-06-01 11:39:40 +02:00
Jeremy Grossmann ed6273413e Merge pull request #2758 from yueguobin/verify-resource-pool-deletion
Fix: properly delete resource records when deleting resource pools
2026-06-01 10:55:26 +02:00
YueGuobin f3aaa902c6 Fix double deletion issue in remove_resource_from_pool
Remove duplicate delete_resource call from remove_resource_from_pool since
the API layer already handles resource deletion. This prevents conflicts
where the API layer tries to delete a resource that was already deleted by
the repository layer.

The complete fix is now:
- remove_resource_from_pool: Only removes resource from pool (API handles deletion)
- delete_resource_pool: Deletes all resource records before deleting pool
2026-06-01 12:46:15 +08:00
YueGuobin d2848a600e Complete fix: delete resource records when deleting resource pool
This completes the fix from PR #2315 by ensuring that when a resource
pool is deleted, all associated resource records are also deleted from
the resources table, preventing orphaned resource records.

Changes:
- Modified delete_resource_pool() to first delete all resource records
  in the pool before deleting the pool itself
- This complements the existing fix in remove_resource_from_pool() which
  handles single resource removal
2026-06-01 12:43:56 +08:00
YueGuobin fcb76a4b01 Apply fix from PR #2315: delete resource from resource table when removing from pool 2026-06-01 12:30:03 +08:00
grossmj bc15e3331b Add privilege dependencies for the new API endpoints 2026-05-31 19:26:47 +02:00
grossmj 87f5a4560a Remove test config files 2026-05-31 19:26:12 +02:00
Jeremy Grossmann db605120fa Merge pull request #2741 from Volo6uev/issue-2735/api-base-config
api endpoint implemented
2026-05-31 19:10:55 +02:00
grossmj 18eb3d9c48 Remove deprecated 'PermissionsStartOnly' setting for Systemd service. Ref #1830 2026-05-31 19:06:03 +02:00
Jeremy Grossmann b5536d61a1 Merge pull request #2756 from yueguobin/fix/ghost-docker-node-vnc-timeout
Fix Docker node management issues and optimize variable update performance
2026-05-31 18:59:00 +02:00
YueGuobin b4daddd1c7 Optimize project loading by implementing parallel node creation
This change significantly improves project loading performance, especially for
topologies with multiple Docker containers or other node types.

Changes:
- Modified project.open() method to use parallel node creation
- Replaced serial node creation loop with Pool-based parallel processing
- Set concurrency limit to 5 to avoid overwhelming the system
- Maintains backward compatibility with existing functionality

Performance improvements:
- Projects with 6 Docker containers: 60-70% faster loading time
- Reduced from ~4-5 seconds to ~1-2 seconds for typical multi-node topologies
- Better resource utilization through concurrent node creation

Technical details:
- Uses existing Pool utility class (concurrency=5)
- Preserves node creation order where required
- Maintains error handling and rollback capabilities
- No changes to node creation logic itself, only parallelization

Testing:
- Syntax validation passed
- Compatible with existing project.open tests
- No API changes, internal optimization only
2026-05-31 23:50:21 +08:00
YueGuobin 0f1003b4f6 Merge branch 'feature/packet-filter-validation' into fix/ghost-docker-node-vnc-timeout 2026-05-31 23:30:10 +08:00
YueGuobin ced73574b4 Fix delay filter validation: ensure delay: [0, X] returns proper error message
This fix addresses the issue where delay: [0, X] configurations were being
silently dropped instead of returning validation errors.

Changes:
- Created new utility function filter_inactive_filters() in packet_filter_validation.py
- Implemented smart filtering logic for delay filter that checks both latency and jitter:
  * delay: [0, 0] → User wants to disable delay, filter out silently
  * delay: [0, X] where X > 0 → Invalid config, keep for validation error
  * delay: [X, X] where X > 0 → Normal configuration, validate normally
- Simplified link.py update_filters() method to use the new utility function
- Added comprehensive tests for the new filtering logic

Before this fix:
- delay: [0, 100] would be silently dropped with no error message
- Users wouldn't know their configuration was invalid

After this fix:
- delay: [0, 100] returns proper error: "delay parameter Latency must be between 1 and 32767 ms, got: 0"
- delay: [0, 0] is correctly handled as intentional disable
- Normal delay configurations continue to work as expected
2026-05-31 22:35:58 +08:00
Guobin Yue 75445886fe Merge branch '3.1' into fix/ghost-docker-node-vnc-timeout 2026-05-31 22:18:28 +08:00
Jeremy Grossmann cc416f20d5 Merge pull request #2754 from yueguobin/feature/packet-filter-validation
Add packet filter parameter validation to prevent ubridge errors
2026-05-30 23:01:17 +02:00
YueGuobin 92a0fa6cd7 Fix packet filter validation tests: use correct ubridge filter type names 2026-05-31 00:38:03 +08:00
YueGuobin 5733705615 Update default web-ui branch from master-3.0 to 3.1 2026-05-31 00:25:09 +08:00
YueGuobin 2584d17067 Update tests to match show_interface_labels default change
The default value of show_interface_labels has been changed to True.
Update test expectations to match this new default.
2026-05-31 00:09:33 +08:00
YueGuobin 21bba7f4b2 Set default value of show_interface_labels to True
Change the default value of show_interface_labels from False to True for better user experience, as interface labels are commonly used in network topology visualization.
2026-05-30 22:49:42 +08:00
YueGuobin 598029face Optimize project variable updates to use parallel node processing
Performance improvement for project variable updates when multiple containers
are present. Previously, nodes were updated serially in a for loop, causing:
- 5 containers: ~35 seconds (7s per container)
- 10 containers: ~70 seconds
- 20 containers: ~140 seconds (2min 20sec)

Changed to parallel processing using asyncio.gather(), reducing total time
to the duration of the slowest single node update (~7 seconds regardless
of container count).

The change maintains error handling with return_exceptions=True to ensure
one node's update failure doesn't prevent others from completing.

This is particularly important for users with large topologies containing
many Docker containers that need to be recreated when project variables change.

Related to issue #2755 ghost node timeout fix.
2026-05-30 22:24:34 +08:00
YueGuobin 8c1dbdf079 Fix ghost Docker nodes causing 60-second VNC timeout on variable updates
When a Docker node is deleted, the compute node's DELETE endpoint only calls
node.delete() which removes the working directory but does not remove the node
object from the project's self._nodes collection. This causes ghost nodes to
remain in memory.

When project variables are updated, the code iterates through ALL nodes in
memory and calls update() on them. For ghost nodes with VNC configuration, this
triggers VNC startup attempts, resulting in 60-second timeouts waiting for X11
socket files that don't exist.

The fix adds await node.project.remove_node(node) to ensure the node object is
removed from the project's node collection when deleted, matching the behavior
of other node types that use manager.delete_node() which already calls
project.remove_node().

This resolves the issue where updating project variables after deleting a VNC
Docker container would timeout with: 'x11 socket file "/tmp/.X11-unix/X100"
does not exist'

Fixes issue #2755
2026-05-30 22:15:40 +08:00
YueGuobin c2dd480edd Fix Docker container variable compatibility with Pydantic models
When updating project variables while Docker containers are running, the
system now properly handles both dictionary-format variables and Pydantic
Variable objects. This prevents AttributeError when containers are recreated
after variable updates.

Changes:
- Modified DockerVM.create() to detect and handle Pydantic Variable objects
- Updated _format_env() method to support both variable formats
- Maintains backward compatibility with existing dictionary format

Fixes error: AttributeError: 'Variable' object has no attribute 'get'
2026-05-30 13:26:36 +08:00
YueGuobin 0aa0467b02 Fix delay latency minimum: ubridge rejects latency <= 0
Align validation rules with ubridge source: delay latency must be > 0
(packet_filter.c delay_setup line 182). Update FILTERS definition in
link.py and test cases accordingly.
2026-05-30 01:21:00 +08:00
Jeremy Grossmann 458eff6020 Merge branch '3.1' into feature/packet-filter-validation 2026-05-29 19:16:59 +02:00
YueGuobin 7bcb96a368 Improve packet filter validation: use tcpdump, handle multi-line BPF, safe project load
Changes:
- Replace tshark BPF validation with tcpdump -d (calls pcap_compile
  internally like ubridge, returns instantly without waiting for traffic)
- Support multi-line BPF expressions: split on newlines and validate
  each line individually
- Always validate, never save invalid filters on error
- Drop invalid filters during project load with warning (prevents
  old topologies with bad filters from failing to open)
- Simplify test cases (no longer depend on tshark availability)
2026-05-30 01:02:21 +08:00
Jeremy Grossmann 7d718e66c5 Merge pull request #2749 from yueguobin/feature/update-gns3-skills-repo
chore: update GNS3 skills repository to official organization
2026-05-29 17:57:14 +02:00
YueGuobin 87f38b1507 Add packet filter parameter validation to prevent ubridge errors
This commit implements comprehensive parameter validation for GNS3 packet
filters at the API layer, preventing invalid parameters from reaching
ubridge and causing technical errors.

## Changes

### New Features
- **Add packet filter validation module** (`gns3server/utils/packet_filter_validation.py`)
  - Validate parameter ranges for all filter types:
    - frequency_drop: -1 to 32767
    - packet_loss: 0 to 100%
    - delay: 0 to 32767ms (latency + jitter)
    - corrupt: 0 to 100%
  - **BPF syntax validation** using tshark (method from gns3_copilot)
  - Parameter count and type validation
  - User-friendly error messages with parameter details

### Integration
- **Integrate validation into Link.update_filters()** (`gns3server/controller/link.py`)
  - Validate parameters before applying filters
  - Raise ControllerError with clear error messages for invalid input
  - Prevent invalid parameters from reaching ubridge

### Testing
- **Add comprehensive test suite** (`tests/utils/test_packet_filter_validation.py`)
  - 15 test cases covering all validation scenarios
  - Tests for valid/invalid parameters, edge cases, and BPF syntax
  - All tests passing

## Benefits
- **Better UX**: Clear, actionable error messages instead of ubridge technical errors
- **Prevents crashes**: Validate parameters at API layer before reaching ubridge
- **Consistent validation**: Centralized validation logic for all filter types
- **BPF safety**: Syntax validation using tshark prevents invalid BPF expressions
2026-05-29 23:39:44 +08:00
YueGuobin 64471575f7 chore: update GNS3 skills repository to official organization
Update the default download repository address for GNS3 skills from
yueguobin/GNS3-Skills to gns3/gns3-skills to use the official
organization repository.

This affects:
- Default skills_repo_url in server configuration schema
- Skills manager default repository URL
- Skills configuration defaults
- All documentation references
2026-05-29 22:04:48 +08:00
Jeremy Grossmann 5d12c26836 Merge pull request #2750 from yueguobin/feature/simple-user-isolation
feat: implement simple user isolation based on project ownership
2026-05-29 11:50:13 +02:00
YueGuobin 06e31fad16 docs: update RBAC user isolation design doc to match actual implementation
Align the design document with the actual codebase:
- Correct pseudo-code to use get_accessible_project_ids() batch API
- Add super admin bypass section
- Clarify seen_project_ids is now a lightweight dedup set
- Add get_accessible_project_ids() implementation details
- Update base branch reference and add MEMORY.md index entry
2026-05-29 00:56:23 +08:00
YueGuobin 1a9a16552b docs: update skills repo URL in command-security.md 2026-05-28 14:22:04 +08:00
YueGuobin 5c8523f321 docs: remove Chinese overview docs, keep only English versions 2026-05-28 14:18:57 +08:00
YueGuobin 305eb58b1c docs: add overview docs for packet analysis, fault injection, and AI assistant 2026-05-28 14:18:24 +08:00
YueGuobin 27eca929cf feat: add mermaid-to-SVG conversion script with environment setup 2026-05-28 14:05:58 +08:00
YueGuobin 67c6f3c970 test: fix privilege count assertions after adding LLMConfig privileges
The LLMConfig.Audit and LLMConfig.Modify privileges added to the User
role increased the default privilege count from 25 to 27. Update test
assertions to match the new counts.
2026-05-28 01:24:22 +08:00
YueGuobin c66867e5ff docs: add user node limit roadmap 2026-05-28 00:02:52 +08:00
YueGuobin 9825a7b271 test: fix RBAC test to match implementation logic
- Update test_list_projects_in_resource_pool to use independent AsyncClient
- Fix test logic to match actual RBAC implementation:
  - Direct ACE + created_by match = accessible
  - Resource pool ACE = accessible (no created_by check)
  - Deduplication prevents duplicate projects
- Test now verifies: pool-only access → pool + /projects access → /projects-only access
- Add missing imports for ASGIWebSocketTransport and auth_service
2026-05-28 00:02:25 +08:00
Jeremy Grossmann 7dcb49fe45 Merge branch '3.1' into base-configs-3.0 2026-05-27 17:43:04 +02:00
YueGuobin adba0f17e5 test: add --prefix and --cleanup-only parameters to benchmark script
- Add --prefix parameter to specify custom project name prefix for testing/cleanup
- Add --cleanup-only parameter to clean up test projects without running benchmark
- Add timing statistics to cleanup showing total time and throughput
- Simplify cleanup output to single summary line instead of per-project printing
2026-05-27 23:37:34 +08:00
YueGuobin 2efcc619b1 perf: batch RBAC permission checking for GET /projects
Replace per-project check_user_has_privilege calls with a single
batch method that performs 3 fixed DB queries regardless of project
count. Reduces GET /projects response time for 10000 projects from
~12s to ~290ms (40x improvement).
2026-05-27 13:27:35 +08:00
YueGuobin 0022d1ad62 test: add benchmark script for GET /projects performance testing 2026-05-27 12:53:42 +08:00
YueGuobin 1eca8c5c94 fix: prevent duplicate projects when user projects are in resource pools
Fixed a bug where projects created by a user that are also in a resource pool
the user has access to would appear twice in the GET /projects response.

Changes:
- Add seen_project_ids set to track already added projects
- Check for duplicates before adding projects in Step 2 (user projects)
- Check for duplicates before adding projects in Step 3 (resource pool projects)

This ensures each project appears only once regardless of whether it's user-created
or shared via resource pool.
2026-05-27 10:47:36 +08:00
YueGuobin ca5db7567c fix: check both regular ACEs and resource pool ACEs for proper access control
This fix addresses a critical issue in the RBAC permission checking logic
introduced in PR #2750. When a project is shared through a resource pool,
both the project creator (with regular ACEs like "All endpoints") and the
shared user (with resource pool ACEs) should be able to see the project.

Changes:
- Modified `check_user_has_privilege` in `gns3server/db/repositories/rbac.py`
- Changed from if-elif (exclusive) to sequential (inclusive) checking
- Now checks regular ACEs first, then resource pool ACEs
- Both types of ACEs can grant access (OR logic instead of XOR)

This fixes the scenario where:
1. user100 has "All endpoints" ACE and creates a project
2. user100 shares the project via resource pool with user200
3. Both users should see the project (user100 via regular ACE, user200 via pool ACE)

Related to PR #2750 - RBAC user isolation implementation.
2026-05-27 00:17:52 +08:00
YueGuobin e6581dfe68 test: update RBAC test to use test_user.username for user isolation
Updated test_list_projects_in_resource_pool to:
- Add test_user fixture parameter
- Use test_user.username when creating projects to match created_by filtering
- Switch from authorized_client to client (admin user) for consistency

This aligns the test with the new user isolation architecture where
projects are filtered by created_by == current_user.username.

Note: This test currently fails with 401 due to test infrastructure
JWT authentication issues, but the core RBAC functionality is verified
by TestPrivileges (13 tests passing).
2026-05-26 23:46:28 +08:00
YueGuobin 5e5c464347 docs: add Phase 9 and 10 user self-registration and email service 2026-05-26 22:59:30 +08:00
YueGuobin 7bfb39dcc9 docs: add Phase 8 per-user project namespace to roadmap 2026-05-26 22:58:18 +08:00
YueGuobin a11a95330b docs: add Phase 7 resource pool renaming to roadmap 2026-05-26 22:56:25 +08:00
YueGuobin 2062136d12 feat: add alembic migration for LLMConfig privileges
Add migration to insert LLMConfig.Audit, LLMConfig.Modify, LLMConfig.Allocate
privileges into existing databases and associate LLMConfig.Audit/Modify
with the default User role.
2026-05-26 14:28:54 +08:00
YueGuobin 9fca2181a8 feat: add independent LLMConfig permissions for AI profile management
Add new privilege definitions:
- LLMConfig.Audit - View LLM model configurations
- LLMConfig.Modify - Update LLM model configurations
- LLMConfig.Allocate - Create/delete LLM model configurations

Add LLMConfig.Audit and LLMConfig.Modify to default User role so that
regular users can manage their own AI profiles without needing the
User.Manager role.

User-scoped LLM config endpoints now use LLMConfig.* permissions.
Group-scoped LLM config endpoints retain Group.* permissions.
2026-05-26 14:24:41 +08:00
YueGuobin 7e33772983 docs: add Phase 6 frontend permission query API to roadmap 2026-05-26 14:08:01 +08:00
YueGuobin 90d2263d2d docs: add Phase 5 ACE architecture refactoring plan to roadmap
Add future plan for ACE architecture refactoring to support:
- ACE name and description fields for better management
- Multiple paths and resource pools in a single ACE entry
- Solving ACE explosion problem (N groups × M pools)
- Updated permission checking logic for the new structure
2026-05-26 13:59:28 +08:00
YueGuobin f7a69bd546 feat: remove resource pools from 'all endpoints' list
Remove resource pools from the ACE endpoints list to prevent accidental
access through the 'all endpoints' option. Resource pools must be
explicitly configured for team sharing to maintain clear security
boundaries and prevent unintended exposure of shared projects.

This change aligns the UI behavior with the actual permission checking
logic where 'path: /' does not grant resource pool access.
2026-05-26 13:31:04 +08:00
YueGuobin 5e4d9e057e refactor: add efficient get_aces_for_path method for resource pool checks
Add a new repository method get_aces_for_path() that:
- Queries ACEs for a specific path at database level (more efficient)
- Preloads related user, group, and role objects to prevent 500 errors
- Keeps original get_aces() method unchanged to avoid performance impact

This improves both performance and code clarity for resource pool
deletion safety checks.
2026-05-26 12:59:37 +08:00
YueGuobin 6fcbb8e57b feat: prevent deletion of resource pools used by ACE configurations
Add safety check to prevent deletion of resource pools that are being
used by ACE configurations. If an attempt is made to delete a resource
pool that has ACE rules referencing it, the API returns a 400 error
with detailed information showing which users/groups are using the
pool and their roles.

The error message only shows the resource pool name for a clean,
user-friendly experience without exposing internal path details.
2026-05-26 12:54:48 +08:00
YueGuobin 9e5423f3f1 docs: update RBAC user isolation roadmap and add design memory
Updated the roadmap document to reflect the implemented three-step
permission check logic in the feature/simple-user-isolation branch.

Added comprehensive design memory documenting:
- Core problem and design conflicts
- Three-step permission check implementation
- Key design decisions and advantages
- Use cases and scenarios
- Design evolution process
2026-05-26 12:46:36 +08:00
YueGuobin ee36a9aec2 feat: fix permission check logic to properly handle ACE and user isolation
Implement the correct three-step permission check logic:
- Step 1: ACE check - basic access permission (get projects user has ACE for)
- Step 2: Filter ace_projects by created_by - user's own projects (project sharing only through resource pools)
- Step 3: Resource pool projects (projects shared through resource pools)

This fixes the design flaw where:
- ACE check could bypass user isolation with broad ACE configurations
- seen_project_ids mechanism prevented proper layered checking
- Project sharing was confused with direct ACE configuration

The new logic ensures:
- User isolation works even with broad ACE (path='/', propagate=True)
- Project sharing is only available through resource pools (clear design)
- Proper layered checking without seen blocking mechanism
2026-05-26 12:33:08 +08:00
Volobue b5e44b5403 added mock user in api endpoints tests 2026-05-25 22:17:14 +03:00
Volobue 01511f3aef added endpoint to v3 branch 2026-05-25 21:37:04 +03:00
Volobue b74ebafb8f api endpoint implemented 2026-05-25 20:07:05 +03:00
YueGuobin 265d0ff860 feat: implement layered permission checks for proper user isolation and sharing
Implement a three-layer permission system:
- Layer 1: ACE strategy check (explicitly authorized/shared projects)
- Layer 2: Ownership check (user's own projects based on created_by)
- Layer 3: Resource pools (team shared projects)

This approach:
- Resolves the conflict between ACE and user isolation
- Enables project sharing via ACE (other users can grant access)
- Maintains default user isolation via ownership
- Prevents duplicate projects in results
- Preserves resource pool functionality
2026-05-26 00:31:19 +08:00
Jeremy Grossmann 0e2045d4e8 Merge branch '3.1' into feature/simple-user-isolation 2026-05-25 18:23:59 +02:00
grossmj ee0e52b930 Enable GA tests on branch 3.1 2026-05-25 18:23:40 +02:00
YueGuobin 7c0b465b74 feat: implement simple user isolation based on project ownership
Users can only see projects they created (created_by field).
Super admins see all projects.
Resource pool projects continue to work as before.
2026-05-26 00:16:45 +08:00
grossmj e5636b0186 Update files to reflect 3.1 branch name 2026-05-25 18:10:23 +02:00
grossmj b3ef07e523 Update .whitesource 2026-05-25 18:07:50 +02:00
Jeremy Grossmann 0fdeb34f1a Merge pull request #2747 from yueguobin/feature/rbac-user-isolation-roadmap
docs: add RBAC user isolation roadmap
2026-05-25 04:40:04 +08:00
YueGuobinandClaude Opus 4.7 9e989566f5 docs: add RBAC user isolation roadmap
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 00:40:42 +08:00
Jeremy Grossmann ec55b9f089 Merge pull request #2746 from yueguobin/feature/gns3-copilot-packet-filter
feat: add packet filter management tool for GNS3-Copilot fault injection
2026-05-25 00:00:09 +08:00
YueGuobin ee80df9e9c docs: add AIOps fault injection testing pipeline roadmap
Roadmap for duplicating company network architecture into GNS3 and
building an automated pipeline to inject faults and validate AIOps
diagnosis, with traffic injection support for enhanced realism.
2026-05-24 23:25:01 +08:00
YueGuobin 045db5bdd8 fix: clean BPF syntax error message and specify loopback interface
- Add -i lo to tshark command to avoid "(null)" interface in errors
- Strip "for interface" suffix from error message for cleaner output
2026-05-24 23:00:41 +08:00
YueGuobin ce58e9adc8 feat: add BPF syntax validation using tshark
- Add _validate_bpf_syntax() method to validate BPF expressions
- Use tshark with 1-second timeout for syntax checking
- Check for "Invalid" in output to detect syntax errors
- Validate BPF filters before applying them to links
- Handle tshark not installed scenario gracefully
- Support both single and multiple BPF expressions
- Return detailed error messages for syntax validation failures
2026-05-24 22:49:59 +08:00
YueGuobin e71931d096 feat: add show_filters_icon parameter to packet filter tool
- Add show_filters_icon parameter with default value False
- Pass show_filters_icon to link.update() in set and clear operations
- Update tool description to explain default behavior
- Remove "clear" action from description to simplify interface
- Hide filter icon in GNS3 Web UI by default for cleaner UI during fault injection
2026-05-24 22:46:52 +08:00
YueGuobinandClaude Sonnet 4.6 dc04c29e7e docs: add GNS3 appliance loading mechanism to memory
Document how GNS3 loads appliance files from builtin and custom directories with priority rules, including storage locations and the design rationale that allows users to customize devices without losing changes during registry updates.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-24 22:31:28 +08:00
YueGuobin 8ba1f064d2 feat: add packet filter management tool for GNS3-Copilot fault injection
Add comprehensive packet filter management functionality to GNS3-Copilot,
enabling AI-powered fault injection scenarios with network simulation
capabilities like latency, packet loss, and corruption.

## Changes

### New Features
- **GNS3PacketFilterTool**: New LangChain tool for managing packet filters
  on GNS3 links with support for delay, packet loss, corruption,
  frequency_drop, and BPF filtering
  - Actions: get_available, set, get, clear
  - Integrated into troubleshooting_injection mode for fault scenarios

### API Integration
- **Link.available_filters()**: Added method to custom_gns3fy.py Link class
  - Queries available filter types for specific links
  - API v3+ only (raises ValueError for v2 connectors)
  - Returns filter definitions with parameters and constraints

### Tool Integration
- Added GNS3PacketFilterTool to TROUBLESHOOTING_INJECTION_MODE_TOOLS
- Positioned as 3rd tool in fault injection workflow
- Optimized for troubleshooting practice scenarios

## Files Modified
- gns3server/agent/gns3_copilot/agent/gns3_copilot.py
- gns3server/agent/gns3_copilot/gns3_client/custom_gns3fy.py
- gns3server/agent/gns3_copilot/tools_v2/__init__.py

## Files Added
- gns3server/agent/gns3_copilot/tools_v2/gns3_packet_filter.py

## Testing
- All validation tests passed
- Version checking verified (v3+ only)
- Tool integration confirmed in troubleshooting mode
2026-05-24 22:31:28 +08:00
Jeremy Grossmann 279ea9eed3 Merge pull request #2745 from yueguobin/feat/link-show-filters-icon
feat: add show_filters_icon property to Link for controlling Web UI filter icon display
2026-05-24 22:05:04 +08:00
YueGuobin fca4459e5f fix: update test_json expected output to include show_filters_icon field 2026-05-24 20:48:58 +08:00
YueGuobin 31d8046e30 fix: add getattr fallback to show_filters_icon property for backward compatibility 2026-05-23 17:09:50 +08:00
YueGuobin a1f4942746 feat: add show_filters_icon property to Link for controlling Web UI filter icon display
This commit adds a new  property to the Link class, allowing users to control whether filter icons are displayed in the Web UI at the individual link level.

**Changes:**
- Added  attribute to Link class (default: True)
- Added  property getter
- Added  method for updating the property
- Updated  to include the new field with backward compatibility
- Added  field to LinkBase schema using Optional[bool] = Field(True, ...) pattern
- Updated API routes to handle the new field in create and update operations
- Added loading logic for show_filters_icon in project.open() to preserve settings when reopening projects

**Schema Definition:**
Uses the same pattern as the  field:

**API Impact:**
- POST /v3/projects/{project_id}/links - accepts  in request body
- PUT /v3/projects/{project_id}/links/{link_id} - can update
- GET /v3/projects/{project_id}/links/{link_id} - returns  field

**Future Applications:**
This feature provides granular control for future AI fault injection modules to manage link-level protocol failures while maintaining clean UI presentation.
2026-05-23 16:57:39 +08:00
YueGuobin 367c565d7c fix: ensure show_filters_icon is always returned in API responses
Set default value for show_filters_icon in LinkBase schema to ensure the field is always included in API responses, even when response_model_exclude_unset=True is used.
2026-05-23 15:21:44 +08:00
YueGuobin aa6845b32b feat: add show_filters_icon property to Link for controlling Web UI filter icon display
This commit adds a new `show_filters_icon` property to the Link class, allowing users to control whether filter icons are displayed in the Web UI at the individual link level.

**Changes:**
- Added `_show_filters_icon` attribute to Link class (default: True)
- Added `show_filters_icon` property getter
- Added `update_show_filters_icon()` method for updating the property
- Updated `asdict()` to include the new field in both topology and regular dumps
- Added `show_filters_icon` field to LinkBase schema
- Updated API routes to handle the new field in create and update operations

**API Impact:**
- POST /v3/projects/{project_id}/links - accepts `show_filters_icon` in request body
- PUT /v3/projects/{project_id}/links/{link_id} - can update `show_filters_icon`
- GET /v3/projects/{project_id}/links/{link_id} - returns `show_filters_icon` field

**Future Applications:**
This feature provides granular control for future AI fault injection modules to manage link-level protocol failures while maintaining clean UI presentation.
2026-05-23 14:57:58 +08:00
Jeremy Grossmann 8719e12c59 Merge pull request #2742 from yueguobin/fix/paramiko-dependency-conflict
fix: remove explicit paramiko pin to resolve dependency conflict with netmiko
2026-05-19 19:32:18 +08:00
YueGuobinandClaude Opus 4.7 cd737cc5ed fix: remove explicit paramiko pin to resolve dependency conflict with netmiko
paramiko>=5.0.0 conflicts with netmiko 4.7.0 which requires paramiko<5.0.
Remove the explicit pin; paramiko is pulled in transitively via netmiko.
To fix CVE-2026-44405, upgrade paramiko separately:
  pip install "paramiko>=5.0.0"

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 08:52:19 +08:00
Volobue 9106ac4522 api endpoint implemented 2026-05-18 21:49:01 +03:00
Jeremy Grossmann ca2004e715 Merge pull request #2738 from yueguobin/docs/skills-editor-api
Documentation improvements and Skills Editor API roadmap
2026-05-19 01:13:20 +08:00
Jeremy Grossmann b65ce034e5 Merge pull request #2739 from yueguobin/fix/unclosed-client-session-websocket-proxy
fix: close DockerHTTPClient session to prevent UnixConnector leak in Web Wireshark
2026-05-19 01:12:22 +08:00
Jeremy Grossmann 529144901f Merge pull request #2740 from yueguobin/fix/cve-2026-44405-paramiko
fix: update netmiko to 4.7.0 and pin paramiko>=5.0.0 to fix CVE-2026-44405
2026-05-19 00:59:03 +08:00
Guobin Yue 0e45d62c06 Merge branch '3.0' into fix/cve-2026-44405-paramiko 2026-05-19 00:08:38 +08:00
YueGuobinandClaude Opus 4.7 6e7cab3fec fix: update netmiko to 4.7.0 and pin paramiko>=5.0.0 to fix CVE-2026-44405
CVE-2026-44405 allows SHA-1 signature algorithm in paramiko through
4.0.0. netmiko 4.7.0 still permits paramiko<5.0, so pip resolves to
the vulnerable 4.0.0. Explicitly pinning paramiko>=5.0.0 ensures the
fix commit a448945 is included.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 00:07:18 +08:00
Guobin Yue 11fe3a24cf Merge branch '3.0' into fix/unclosed-client-session-websocket-proxy 2026-05-19 00:02:26 +08:00
YueGuobin 868e317d24 fix: close DockerHTTPClient session to prevent UnixConnector leak in Web Wireshark
The Web Wireshark WebSocket endpoint created a WebWiresharkManager but
never called close(), leaving the DockerHTTPClient's ClientSession with
UnixConnector unclosed when users closed the browser tab.

Also switch asyncio.wait in WebSocket proxy from ALL_COMPLETED to
FIRST_COMPLETED to avoid blocking cleanup when one direction disconnects.
2026-05-18 23:59:56 +08:00
Guobin Yue 7444551a66 Merge branch '3.0' into docs/skills-editor-api 2026-05-18 23:42:31 +08:00
YueGuobinandClaude Sonnet 4.6 ef16c87a02 docs: add Web Wireshark Docker image optimization analysis
Add comprehensive roadmap document for optimizing the gns3/web-wireshark
Docker image size from current 2GB to target 1.5GB (25% reduction).

Key findings:
- 570MB of cleanable files identified (locales, docs, ibus, dev packages)
- Compression analysis shows limited benefit (1-5%) vs file cleanup (25%)
- Detailed implementation plan with safe optimization phases
- Focus on transfer optimization and build-time compression strategies

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 22:58:06 +08:00
grossmj ba79f1c226 Fix Docker build and publish API doc actions 2026-05-13 17:19:08 +08:00
grossmj 7cf25bc0d5 Release v3.1.0a2 2026-05-13 00:34:05 +08:00
grossmj 7bb0a2a863 Bundle web-ui v3.1.0a2 2026-05-13 00:29:25 +08:00
grossmj 748b8a1571 Sync appliances 2026-05-13 00:25:27 +08:00
YueGuobinandClaude Opus 4.7 c5a59acc40 docs: move packet analysis from roadmap to implemented
Rewrite the packet-analysis document based on actual code:
protocol-oriented analysis with tshark, 40+ supported protocols,
two-tool architecture (skills query + capture analysis), field
validation, and hot reload support.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-12 22:59:34 +08:00
YueGuobin fd08885d94 docs: reorganize roadmap files into dedicated subdirectory 2026-05-12 22:53:35 +08:00
YueGuobinandClaude Opus 4.7 0ee370d6ab docs: add Skills Editor API roadmap
Document the planned CRUD + PR management API for GNS3 skills
(prompts, fault injection, device skills, packet analysis),
enabling the Web UI to browse, edit, save, and contribute
skill changes back to the upstream repository.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-12 22:52:23 +08:00
Jeremy Grossmann c71dfbb6b5 Merge pull request #2729 from yueguobin/feature/troubleshooting-issue-injection
feat: add fault injection system and external skills repository
2026-05-12 22:24:00 +08:00
YueGuobin 30a140a9e3 fix: surface tshark stderr errors to LLM, not just log them 2026-05-12 15:10:27 +08:00
YueGuobin b79fea918d fix: hint LLM about -c behavior when tshark returns empty with -c 2026-05-12 14:54:50 +08:00
YueGuobin 09b0fbcfea fix: update search_fields examples to use existing field names 2026-05-12 14:48:37 +08:00
YueGuobin 73e0de7706 fix: reject multi-keyword search_fields, single keyword only 2026-05-12 14:47:00 +08:00
YueGuobin c357d52fbf fix: document action/query params in PacketAnalysisTool description 2026-05-12 14:36:21 +08:00
YueGuobin 2a34d0ef58 feat: add search_fields action to PacketAnalysisTool for real-time field lookup 2026-05-12 14:33:13 +08:00
YueGuobin 32c3b4cd35 feat: validate tshark -e field names before running analysis 2026-05-12 14:27:16 +08:00
YueGuobin 9c23f9037c fix: document -c behavior caveat in PacketAnalysisTool description 2026-05-12 14:00:58 +08:00
YueGuobinandClaude Opus 4.7 b7a0b611df fix: demote loader-level load logs to DEBUG, info already reported by manager
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-12 13:52:05 +08:00
YueGuobinandClaude Opus 4.7 89da58fe1b fix: promote skills/prompts load logs to INFO level
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-12 13:46:36 +08:00
YueGuobin c5af9ce389 fix: load packet analysis protocols during skills initialization
- Add reload_packet_analysis_protocols() call in _ensure_skills_manager()
- PACKET_ANALYSIS_REGISTRY was empty because it was never loaded
2026-05-12 13:41:52 +08:00
YueGuobin 67b3b778b8 feat: add PacketAnalysisSkillsTool
- Register packet_analysis_skills as a LangChain tool for LLM
- LLM can query protocol field definitions before calling packet_analysis
- Follows the same pattern as DeviceSkillsTool and InjectionSkillsTool
2026-05-12 13:37:59 +08:00
YueGuobin 2a38816d3d fix: remove remaining quoted example from tool input docstring 2026-05-12 13:30:18 +08:00
YueGuobin b991125c6c fix: use shlex.split for tshark_args parsing
- Replace str.split() with shlex.split() to handle quoted arguments
- LLM may pass args with or without quotes, both work correctly now
2026-05-12 13:29:31 +08:00
YueGuobin e0c2d64b7c feat: add packet analysis workflow to tool description
- Update PacketAnalysisTool.description with step-by-step workflow
- Instruct LLM to query packet_analysis skills first, then construct tshark_args
2026-05-12 13:13:24 +08:00
YueGuobin 2c5cfdbee8 refactor: remove old PacketCaptureTool, replaced by PacketAnalysisTool
- Delete packet_capture_tools.py (analyze_packets with packet_number)
- PacketAnalysisTool is more flexible and can do everything the old tool could
- Update tool registration to use only PacketAnalysisTool
- Cleaner, more unified packet analysis interface
2026-05-12 10:19:25 +08:00
YueGuobin 84b9742045 feat: add protocol-oriented packet analysis tool
- Add PacketAnalysisTool that accepts user-provided tshark arguments
- LLM constructs tshark commands based on protocol knowledge from skills
- Add PACKET_ANALYSIS_REGISTRY for protocol definitions
- Add load_packet_analysis_protocols() to SkillsLoader
- Add get_packet_analysis_protocol() and list functions to registry
- Register PacketAnalysisTool in teaching and lab automation modes
- Update SkillsManager to reload packet analysis protocols

Related: GNS3-Skills commit 7bc45d2
2026-05-12 09:59:10 +08:00
YueGuobin 6596011799 docs: add roadmap docs for planned features
Close GitHub issues and document as roadmaps instead:
- #2731: user preferences API
- #2732: server settings REST API
- #2733: injection fault tracking
- packet analysis: protocol-oriented analysis architecture
2026-05-12 00:03:07 +08:00
YueGuobin a408148073 feat: require superadmin for /reload/skills endpoint
Only administrators can reload skills from the external repository.
Non-admin users receive 403 Forbidden.
2026-05-11 22:59:28 +08:00
YueGuobinandClaude Opus 4.7 ae1a444677 fix: remove background init timeout and allow skills reload retry
- Remove 5s thread.join() timeout so git clone/pull is not truncated
- Remove _init_complete flag, reset _init_in_progress on failure instead
- Let /reload/skills API retry initialization after network failure
- Raise GIT_HTTP_LOW_SPEED_LIMIT from 1 KB/s to 10 KB/s

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-11 22:51:57 +08:00
YueGuobinandClaude Sonnet 4.6 27051a89ad deps: add PyYAML and GitPython to ai-requirements.txt
Add missing dependencies for the external skills repository feature:
- PyYAML>=6.0.0: for loading YAML skill files
- GitPython>=3.1.0: for Git operations (clone/pull) on skills repo

These dependencies are required by the SkillsManager and SkillsLoader
classes introduced in commit e68cc17e.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 15:59:52 +08:00
YueGuobin e68cc17ed5 feat: add fault injection system and external skills repository
## Summary

Add a complete fault injection system for GNS3 Copilot, migrate all
skills from local Python files to an external Git repository with
hot reload support, and restructure Copilot API under /copilot/.

## Key Changes

### Fault Injection
- New troubleshooting_injection mode with InjectionSkillsTool
- 368 fault scenarios across 39 protocol categories
- Context-based filtering (LLM must pass topology protocols)

### External Skills Repository
- SkillsManager: Git clone/pull, version tracking, smart updates
- SkillsLoader: YAML skills + Markdown prompts from external repo
- Hot reload via POST /copilot/reload/skills
- Configurable via gns3_server.conf

### Architecture
- API unified under /copilot/ prefix
- SkillsManager moved from Controller to agent module
- Lazy initialization with startup background preload
- Per-command Git timeout, smart update checks
- Forbidden commands hot-reloadable from external repo
- 32 INFO logs downgraded to DEBUG
2026-05-11 01:24:55 +08:00
Jeremy Grossmann 534bb5eded Merge pull request #2728 from yueguobin/feature/disable-deepseek-thinking-mode
fix: Disable DeepSeek thinking mode to avoid reasoning_content errors
2026-05-09 22:41:27 +08:00
YueGuobinandClaude Sonnet 4.6 156072118f fix: Disable DeepSeek thinking mode to avoid reasoning_content errors
DeepSeek models (deepseek-v4-flash/pro) enable thinking mode by default,
which returns reasoning_content that must be passed back to the API in
subsequent requests. This causes 400 errors in multi-turn conversations
when the reasoning_content is not properly handled.

This commit disables thinking mode by passing extra_body={"thinking": {"type": "disabled"}}
as an explicit parameter to DeepSeek models, preventing the reasoning_content
field from being generated.

Modified:
- create_base_model(): Add extra_body parameter with thinking mode disabled
- create_title_model(): Add extra_body parameter with thinking mode disabled

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 22:31:50 +08:00
grossmj 8b3d136a84 Update packages in requirements.txt 2026-05-09 18:41:02 +08:00
grossmj 97bf94e06e Merge branch '2.2' into 3.0
# Conflicts:
#	CHANGELOG
#	gns3server/compute/iou/iou_vm.py
#	gns3server/crash_report.py
#	gns3server/utils/asyncio/telnet_server.py
#	gns3server/version.py
#	requirements.txt
#	setup.py
2026-05-09 18:23:00 +08:00
Jeremy Grossmann 32959f1e04 Merge pull request #2724 from yueguobin/fix/import-project-skip-offline-computes
fix: Skip offline compute nodes during project import
2026-05-09 13:59:53 +08:00
YueGuobinandClaude Sonnet 4.6 5c7018283f fix: Skip offline compute nodes during project import
When importing a project, the round-robin logic would attempt to distribute
nodes across all configured compute resources, including offline ones. This
caused import failures when any remote compute was unreachable.

This fix filters the compute list to only include connected computes before
round-robin distribution. If no remote computes are connected, all nodes
are assigned to the local compute.

This matches the approach used in project._get_disconnected_computes() and
prevents the issue where importing a project fails with:
"Cannot connect to compute 'X' with request POST /projects"

Fixes issue introduced in commit 90e3a8d6 (2017) which added round-robin
load balancing without considering offline compute nodes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-09 13:46:58 +08:00
Jeremy Grossmann ae2fa31c5e Merge pull request #2721 from yueguobin/feature/list-node-files-api
feat: Add API endpoint to list node files with metadata
2026-05-09 00:04:16 +08:00
YueGuobin b4220d55c6 fix: Import status module in project.py
Fix F821 undefined name 'status' error by importing the status
module from fastapi. This resolves build errors when using
status.HTTP_403_FORBIDDEN and status.HTTP_404_NOT_FOUND.
2026-05-08 23:58:43 +08:00
Guobin Yue cd732ab4b5 Merge branch '3.0' into feature/list-node-files-api 2026-05-08 23:51:56 +08:00
Jeremy Grossmann 14c2172f1b Merge pull request #2722 from yueguobin/fix/console-stopping-error
fix: Handle connection errors when stopping node console
2026-05-08 23:43:39 +08:00
YueGuobin 3752b2bac8 fix: Handle connection errors when stopping node console
Add exception handling in stop_wrap_console to gracefully handle
ConnectionResetError, BrokenPipeError, and OSError when waiting
for console writer to close.

This prevents 500 errors when stopping QEMU nodes if the console
connection is reset before the writer finishes closing.

Fixes race condition where QEMU process exits and closes connections
before the console writer cleanup completes.
2026-05-08 23:30:41 +08:00
YueGuobinandClaude Sonnet 4.6 e6df144ae8 refactor: Remove MD5 calculation from node files listing
Remove MD5 checksum calculation from the node files API since
disk image files are dynamic and change frequently. MD5 calculation
was also causing significant performance overhead.

Changes:
- Remove md5sum field from NodeFile schema
- Remove MD5 calculation from list_node_files method
- Improve error handling for timestamp conversion
- Simplify code by removing lambda functions

Performance improvement:
- Response time reduced from ~0.5-1s to ~0.017s (30-60x faster)
- Especially beneficial for large files and multiple files

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 23:05:40 +08:00
YueGuobinandClaude Sonnet 4.6 fae7b2eabe fix: Export NodeFile schema to schemas module
Add NodeFile to the schemas __init__.py exports to fix
import error when starting the server.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 22:58:45 +08:00
YueGuobinandClaude Sonnet 4.6 51a4c73e21 feat: Add detailed metadata to node files listing
Enhance the node files API to include comprehensive file metadata:
- File size in bytes
- File creation time (ISO 8601 format)
- File modification time (ISO 8601 format)
- File extension

Create new NodeFile schema to support these additional fields
while keeping the existing ProjectFile schema for backward compatibility.

This provides users with better information to manage and identify
files in the Web UI.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 22:57:19 +08:00
YueGuobinandClaude Sonnet 4.6 5b75d633aa feat: Add API endpoint to list node files
Implement issue #2719 - Add API endpoint to list project files

- Add GET /v3/projects/{project_id}/nodes/{node_id}/files endpoint
- Add list_node_files() method to Project class
- Add security checks to prevent path traversal
- Filter out .ghost temporary files
- Return file paths with MD5 checksums
- Require Node.Audit privilege

This allows users to discover dynamically created files
such as QEMU disk images created via the disk image API.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 22:52:17 +08:00
Jeremy Grossmann 713dbb7f45 Merge pull request #2718 from GNS3/2.2
Release v2.2.59
2026-05-08 22:03:17 +08:00
grossmj c3d23d7cae Development on 2.2.60.dev1 2026-05-08 20:03:31 +08:00
grossmj a1edf74fcf Merge branch 'master' into 2.2 2026-05-08 19:49:53 +08:00
grossmj 59a95edd3d Release v2.2.59 2026-05-08 19:06:04 +08:00
grossmj e34a7afe79 Sync appliances 2026-05-08 19:03:14 +08:00
Jeremy Grossmann 2dcbe0f1c2 Merge pull request #2717 from GNS3/bugfix/2709
Fix snapshot restore does not work after export/import of project
2026-05-08 18:59:37 +08:00
grossmj b1c8ce8b58 Remove unneeded code 2026-05-08 18:56:56 +08:00
grossmj b304511b5e Fix snapshot restore does not work after export/import of project 2026-05-08 18:47:47 +08:00
grossmj 163d4e0534 Update requirements.txt & python_requires 2026-05-08 17:01:10 +08:00
grossmj 72f64ee60b Warn to use 64-bit IOU images. Fixes #2716
32-bit IOU image support has been removed from the GNS3 VM.
2026-05-08 16:37:06 +08:00
Jeremy Grossmann cd03abb7ed Merge pull request #2669 from arl1984/fix/telnet-proxy-reader-cleanup-2344
Fix telnet console silent-proxy hang on non-ConnectionError exit (#2344)
2026-05-08 15:42:51 +08:00
grossmj 6551bf56f8 Tweak and merge changes from 3.0 branch 2026-05-08 15:36:40 +08:00
Jeremy Grossmann e0860555ba Merge pull request #2713 from yueguobin/fix/docker-container-deletion-error-handling
Fix: Improve Docker container deletion error logging
2026-05-07 22:17:23 +08:00
YueGuobinandClaude Sonnet 4.6 822abbe671 Fix: Improve Docker container deletion error logging
When closing a Docker node, if container deletion fails, the error
is silently ignored. This can lead to stale containers remaining on
the system and causing 409 conflicts when reopening projects.

Changes:
- Distinguish between 404 (container already removed, normal) and
  other DockerError (deletion failed, needs attention)
- Log warning when deletion fails with error details
- Add comment explaining stale containers will be cleaned up on
  project open (via automatic 409 conflict resolution)

This improves observability without blocking project close operations.
The root cause of stale containers can now be diagnosed from logs.

Fixes #2708

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 12:45:05 +08:00
Jeremy Grossmann 3928377f80 Merge pull request #2710 from yueguobin/fix/compute-connection-timeout
Fix: Check compute connectivity before open() during project deletion
2026-05-07 11:36:45 +08:00
Jeremy Grossmann 0d88ff87e7 Merge pull request #2712 from yueguobin/fix/compute-reconnection-backoff
Fix: Add exponential backoff to compute reconnection attempts
2026-05-07 11:35:46 +08:00
YueGuobin efe6913d69 Fix: Add exponential backoff to compute reconnection attempts
When a remote compute is unreachable, the controller now uses exponential
backoff for reconnection attempts: 5s, 10s, 20s, 40s, 80s, then caps at
300s (5 minutes). Previously it retried every 5 seconds indefinitely.

User-initiated operations (open project, start node) still trigger an
immediate connection attempt, so recovery is not delayed in practice.

Related: #2704
2026-05-07 11:17:55 +08:00
YueGuobinandClaude Opus 4.6 f1b11e7cae Fix: Check compute connectivity before node creation in open()
When opening a closed project with nodes on an offline remote compute,
open() would block for 120s trying to connect before eventually
failing. Now checks compute connectivity after loading the topology
file but before creating nodes, allowing immediate failure with a
clear error message.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 10:48:18 +08:00
YueGuobinandClaude Opus 4.6 30ebde0cb0 Fix: Check compute connectivity before open() during project deletion
Previously the disconnected compute check ran after open(), which would
block for 120s trying to connect to unreachable remote computes before
rejecting the deletion. Now reads the topology file directly to extract
compute IDs and checks connectivity before calling open(), enabling
immediate rejection of deletions involving offline computes.

Also removes the redundant post-open() check since the early check
covers both opened and closed project states.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 09:58:20 +08:00
YueGuobinandClaude Opus 4.6 8ecd449dd8 Fix: Add error logging when closing/deleting projects on computes
Previously errors during close() and delete_on_computes() were silently
swallowed without any logging, making it difficult to diagnose failures
when remote computes are unreachable.

- close(): log warning instead of silent pass
- delete_on_computes(): wrap HTTP DELETE in try/except with warning log

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 09:37:51 +08:00
YueGuobin 4d06b2b7b6 Fix: Skip add_compute for existing computes when opening projects 2026-05-06 13:24:27 +08:00
YueGuobin 0f4b0c567e feat: add AI provider config files to .gitignore
Add deepseek, claude, gemini, and grok settings files to .gitignore to prevent accidental commits of local AI provider configurations.
2026-05-06 13:24:13 +08:00
Jeremy Grossmann 255d1e4057 Merge pull request #2705 from yueguobin/fix/project-deletion-compute-status-check
Fix: Check compute connection status before project deletion
2026-05-06 09:39:41 +08:00
YueGuobin a67cd66b60 Revert "Fix: Handle project deletion errors in autoidlepc"
This reverts commit c92188cad4.
2026-05-06 00:59:05 +08:00
YueGuobin c92188cad4 Fix: Handle project deletion errors in autoidlepc
When deleting the AUTOIDLEPC project in autoidlepc(), if a remote compute
is disconnected, the deletion fails with ControllerForbiddenError due to
our compute connection status check. This causes:
- The project to remain in the controller's memory
- Subsequent autoidlepc calls to fail
- User must restart the server to recover

This fix adds exception handling to ensure the project is always removed
from the controller's memory, even if deletion fails.

Related to #2703
2026-05-06 00:47:24 +08:00
YueGuobinandClaude Sonnet 4.6 9c868911e1 Fix: Use _computes instead of _project_created_on_compute for deletion check
The initial fix used _project_created_on_compute to check for disconnected
computes before deletion, but this set gets reset during project.open(),
causing the check to fail.

Now uses self._computes which is loaded from the topology file and
persists through the open() call.

Related: #2703

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 00:19:55 +08:00
YueGuobinandClaude Sonnet 4.6 4444da9ffa Fix: Check compute connection status before project deletion
This commit addresses issue #2703 where deleting a project with nodes
on remote compute nodes would result in long waits with no feedback
if those computes were unreachable.

Changes:
1. Compute connection status updates on connection failure
   - When a compute fails to connect, update connected=False and last_error
   - Send compute.updated notification to UI so users can see status
   - This allows Web UI to display real-time connection status

2. Project deletion checks compute status before attempting deletion
   - Check all computes used by the project are connected
   - If any compute is disconnected, immediately reject deletion
   - Provide clear error message indicating which computes are offline
   - This prevents long timeouts and gives users immediate feedback

Benefits:
- Immediate feedback instead of 120-second timeouts
- Clear error messages about which computes are disconnected
- Prevents orphaned resources on offline computes
- Improves user experience by avoiding silent waits

Related: #2703

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 00:05:10 +08:00
Jeremy Grossmann ee7c5d6d59 Merge pull request #2693 from cristian-ciobanu/ssh-console-support
feat(compute): add SSH console type support
2026-05-05 19:03:57 +08:00
Jeremy Grossmann 82d630a122 Merge branch '3.0' into ssh-console-support 2026-05-04 17:17:10 +08:00
Jeremy Grossmann 56455d3a27 Merge pull request #2701 from yueguobin/fix/iou-remote-path-validation
fix: convert absolute image paths to relative paths for remote compute nodes
2026-05-04 16:36:23 +08:00
Guobin Yue 069e139d2d Merge branch '3.0' into fix/iou-remote-path-validation 2026-05-04 15:51:30 +08:00
YueGuobin 1f5ba3cada chore: remove internal debug documentation 2026-05-04 15:48:46 +08:00
YueGuobin 38f5e8df76 fix: extend remote compute image path conversion to all node types
Previously only the "path" field was converted to a relative path for remote computes, causing issues with QEMU and VMware nodes that use different image path fields. Now all known image path fields are converted, ensuring consistent behavior across IOU, QEMU, Dynamips, and VMware node types.
2026-05-04 15:39:16 +08:00
Jeremy Grossmann 5f9b469679 Merge pull request #2700 from yueguobin/fix/issue-2680-static-directory
fix: handle directory access for static web-ui routes
2026-05-03 17:56:50 +08:00
YueGuobinandClaude Sonnet 4.6 6ff4f575bb docs: add analysis for issue #2676 remote compute image path validation
Add detailed documentation explaining:
- Problem description and root cause
- Architecture overview (Controller vs Compute)
- Why automatic upload is not triggered
- Affected node types
- Solution implementation
- Testing scenarios

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 17:47:25 +08:00
YueGuobinandClaude Sonnet 4.6 11fb5de84e fix: send relative image path to remote compute nodes
When creating a node on a remote compute, the controller now sends
only the image filename instead of the absolute local path. The remote
compute will search for the image in its own configured images_directories.

If the image is not found, the compute returns ImageMissingError, which
triggers the controller's automatic image upload mechanism.

This fixes issue #2676 where remote computes reject paths from the
controller due to mismatched directory prefixes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 17:44:47 +08:00
YueGuobinandClaude Sonnet 4.6 952ef66a6b fix: handle directory access for static web-ui routes
When accessing /static/web-ui without trailing slash, the request would
fail with "RuntimeError: File at path ... is not a file" because:

1. The route /static/web-ui/{file_path:path} doesn't match paths without
   trailing slash (Starlette's path regex requires the /)
2. The request falls through to StaticFiles mount, which tries to serve
   the directory as a file

This fix:
- Sets html=True on StaticFiles mount to automatically redirect directory
  URLs to trailing slash versions
- Adds os.path.isdir() check to handle empty file_path gracefully

Fixes #2680

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-03 17:21:03 +08:00
Jeremy Grossmann c45f6d9416 Merge pull request #2699 from yueguobin/fix/template-duplicate-name-validation
Fix duplicate template name validation when updating templates
2026-05-03 12:09:59 +08:00
YueGuobin 1d715e146b fix: add duplicate name validation when updating templates
Fixes #1658

Add validation in the update_template method to check if a template
with the same name already exists before updating. This prevents
users from creating duplicate template names by editing existing
templates.

The check excludes the current template being edited to allow
updating other properties without changing the name.
2026-05-03 11:08:20 +08:00
Jeremy Grossmann c3d202abc9 Merge branch '3.0' into ssh-console-support 2026-05-02 22:10:28 +08:00
Jeremy Grossmann 165209ba24 Merge pull request #2698 from yueguobin/fix/compute-update-password-none-error
fix: avoid AttributeError when password is not provided in compute update
2026-05-02 22:07:34 +08:00
Jeremy Grossmann b87ab8f86f Merge pull request #2696 from yueguobin/fix/rfc1123-error-message
fix: improve hostname validation error messages with allowed characters
2026-05-02 18:30:49 +08:00
YueGuobinandClaude Opus 4.6 a6dcab8110 fix: avoid AttributeError when password is not provided in compute update
When updating a compute without providing a password field,
compute_update.password is None and calling .get_secret_value()
on it causes a 500 Internal Server Error. Only set the password
in update_values when a password is actually provided.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-02 15:37:46 +08:00
YueGuobinandClaude Opus 4.6 ba220780a9 fix: improve hostname validation error messages with allowed characters
When a hostname validation fails, the error message now includes
the allowed character set to help users provide valid names.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-02 13:09:04 +08:00
Cristi e6de7cb60a feat(compute): Fix Dynamips to listen on the internal port when ssh is used for auxiliary console 2026-04-30 23:50:15 +03:00
CristiandCopilot d7c78f5744 feat(compute): Fix ambiguous log message related to the active console transport.
Co-authored-by: Copilot <copilot@github.com>
2026-04-30 18:07:23 +03:00
Cristi 9d451eb652 feat(compute): Updated server host key to use the secure ssh-ed25519 instead of old ssh-rsa algorithm 2026-04-30 17:56:05 +03:00
Cristi cc05eb5850 feat(compute): Fix missing SSH wrapping for auxiliary console 2026-04-30 17:47:54 +03:00
Cristi 8ff1698bfb feat(compute): Added AsyncioSSHServer dedicated tests 2026-04-30 16:35:21 +03:00
Cristi d64eca0418 feat(compute): add SSH console type support 2026-04-30 15:52:47 +03:00
Jeremy Grossmann f0ef65b8e8 Merge pull request #2688 from yueguobin/fix/llm-model-config-error-message
fix: include error details in LLM model config + docs: add troubleshooting guides
2026-04-25 16:30:47 +08:00
Guobin Yue c583462d2d Merge branch '3.0' into fix/llm-model-config-error-message 2026-04-25 16:26:59 +08:00
YueGuobin c688223e1b docs: add troubleshooting guide for WebSocket console authentication failure
Add documentation explaining the common issue where WebSocket console connections to remote compute nodes fail due to credential mismatch. The guide describes the error symptoms, root cause (Controller forwarding its own credentials to Compute), and solution (ensuring matching compute_username and compute_password in Compute's configuration).
2026-04-25 16:08:53 +08:00
YueGuobinandClaude Opus 4.6 d81a7410e2 docs: remove misleading Controller Hostname Unreachable section
This section was misleading - the actual root cause is host=0.0.0.0
causing controller to register as 127.0.0.1, not hostname resolution.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-25 15:55:37 +08:00
YueGuobinandClaude Opus 4.6 e88b12086a docs: clarify host=0.0.0.0 causes controller to register as 127.0.0.1
Add details about the "No common subnet" error when Controller's host
is set to 0.0.0.0, and how to verify via /v3/version endpoint.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-25 15:54:12 +08:00
YueGuobinandClaude Opus 4.6 f9d1ccc701 docs: add troubleshooting for controller hostname unreachable
Add documentation for the "No common subnet" error when the
controller's hostname in /etc/hosts resolves to an unreachable
or stale IP address.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-25 15:44:20 +08:00
grossmj 27d4c43ad9 Back on development on 3.1.0.dev2 2026-04-25 13:31:35 +08:00
grossmj c6e2bfa9b6 Release v3.1.0a1 2026-04-25 13:19:19 +08:00
grossmj 7fc5601405 Bundle web-ui v3.1.0a1 2026-04-25 12:58:56 +08:00
YueGuobinandClaude Opus 4.6 517764a7ac fix: include error details in LLM model config failure response
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-25 01:48:45 +08:00
grossmj ee43a5cdf5 Bump version to 3.1.0.dev2 2026-04-24 21:56:37 +08:00
grossmj ccf11d8f8b Sync appliances 2026-04-24 21:55:22 +08:00
Jeremy Grossmann b4f31222d0 Merge pull request #2685 from yueguobin/replace-wireshark-with-gns3server-web-wireshark-setup-in-installation-command
docs: replace 'wireshark' with 'gns3server-web-wireshark-setup' in installation commands
2026-04-24 10:51:53 +08:00
YueGuobinandClaude Opus 4.6 4dab36c08c docs: replace 'wireshark' with 'gns3server-web-wireshark-setup' in installation commands
The CLI entry point was renamed from 'wireshark' to 'gns3server-web-wireshark-setup'
to avoid conflicts with the system wireshark package.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-24 10:33:41 +08:00
Jeremy Grossmann d59c82892a Merge pull request #2684 from yueguobin/fix/wireshark-cli-name-conflict
fix: rename wireshark CLI to gns3-wireshark to avoid conflict
2026-04-24 00:48:57 +08:00
grossmj 640910ec8e Use gns3server-web-wireshark-setup in docs 2026-04-24 00:48:00 +08:00
grossmj 6fac4c8c8a Merge branch '3.0' into fork/yueguobin/fix/wireshark-cli-name-conflict
# Conflicts:
#	pyproject.toml
2026-04-24 00:42:48 +08:00
YueGuobinandClaude Opus 4.6 0b7c40a14a fix: rename wireshark CLI to gns3-wireshark to avoid conflict
The wireshark CLI entry point creates /usr/bin/wireshark which conflicts
with the system wireshark package on Arch Linux (owned by wireshark-qt),
causing package installation to fail.

Rename to gns3-wireshark to follow the same naming convention as other
GNS3 CLI tools (gns3server, gns3vmnet).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-24 00:04:21 +08:00
grossmj 746cc8531c Create an executable named gns3server-web-wireshark-setup instead of wireshark. Fixes #2683 2026-04-24 00:00:45 +08:00
Jeremy Grossmann 9d0bb4a592 Merge pull request #2682 from yueguobin/fix/packet-capture-https-skip-cert
fix(copilot): add verify=False for HTTPS with self-signed certs
2026-04-23 23:44:25 +08:00
YueGuobinandClaude Opus 4.6 d6d4f7262e fix(copilot): add verify=False for HTTPS with self-signed certs
Add verify=False to requests.get() when capture_url uses HTTPS protocol,
to skip SSL certificate validation. This allows PacketCaptureTool to
work with GNS3 servers using self-signed certificates.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-23 23:20:41 +08:00
Jeremy Grossmann f06b5fff21 Merge pull request #2681 from yueguobin/fix/wireshark-curl-https-skip-cert
fix(web-wireshark): add -k flag to curl for HTTPS with self-signed certs
2026-04-23 23:04:08 +08:00
Guobin Yue b49e6836cc Merge branch '3.0' into fix/wireshark-curl-https-skip-cert 2026-04-23 22:55:26 +08:00
YueGuobinandClaude Opus 4.6 fd6868efce fix(web-wireshark): add -k flag to curl for HTTPS with self-signed certs
Add -k flag to curl command when capture_stream_url uses HTTPS protocol,
to skip SSL certificate validation. This allows Web Wireshark to work
with GNS3 servers using self-signed certificates.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-23 22:52:51 +08:00
grossmj 85bbc74f7d Fix using SSL with remote computes. Fixes https://github.com/GNS3/gns3-gui/issues/3733 2026-04-23 21:59:51 +08:00
Jeremy Grossmann 98477371d2 Merge pull request #2679 from yueguobin/wireshark-alias
feat(web-wireshark): add container IP retrieval and Docker API version compatibility fixes
2026-04-22 23:47:43 +08:00
YueGuobinandClaude Sonnet 4.6 a189a98723 docs(web-wireshark): add Docker API compatibility documentation
- Document API version negotiation mechanism (1.44 with fallback to 1.40)
- Add tested configurations table for Docker 20.10 and 29.3+
- Document container IP retrieval dual-strategy approach
- Explain KeyError bug fix for missing NetworkSettings.Networks field

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 23:30:33 +08:00
YueGuobinandClaude Sonnet 4.6 117025a8a2 fix(web-wireshark): improve Docker API version compatibility with fallback mechanism
- Change initial API version from 1.40 to 1.44 to support Docker 29.3+ (API 1.54)
- Add automatic fallback to API 1.40 for older Docker versions (20.10, API 1.41)
- Fixes "client version 1.40 is too old. Minimum supported API version is 1.44" error
- Ensures compatibility across Docker versions 20.10 (API 1.41) to 29.3+ (API 1.54+)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 23:12:56 +08:00
YueGuobin 6c96e7493f feat(web-wireshark): add method to retrieve container IP and refactor websocket endpoint
- Add `get_container_ip` method to WebWiresharkManager for retrieving container IP addresses in wireshark network
- Method uses Docker API as primary approach with container command execution as fallback
- Refactor web_wireshark_websocket endpoint to use new method instead of direct Docker queries
- Improve error handling and logging for container IP retrieval failures
2026-04-22 22:35:50 +08:00
YueGuobin e304b19076 fix: lower Docker minimum API version to 1.40 for broader compatibility
The minimum Docker API version was reduced from 1.44 to 1.40 to support older Docker installations that do not provide API version 1.44, ensuring the web Wireshark agent can connect to a wider range of Docker environments.
2026-04-22 16:08:05 +08:00
YueGuobinandClaude Opus 4.6 2240012402 Rename gns3-wireshark-setup to wireshark for simpler command
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 14:13:19 +08:00
Jeremy Grossmann aac9b25b98 Merge pull request #2677 from yueguobin/add-url-branch-parameters
Add --url and --branch parameters to update-bundled-web-ui.sh
2026-04-21 22:54:01 +08:00
YueGuobinandClaude Opus 4.6 e6939513db Add --url and --branch parameters to update-bundled-web-ui.sh
Support specifying custom GitHub repository URL and branch name
when syncing WebUI with gns3server.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-21 22:24:46 +08:00
grossmj 8387b484cc Sync appliances 2026-04-21 18:15:00 +08:00
Jeremy Grossmann 0ac8fd9ff3 Merge pull request #2675 from GNS3/upgrade-dependencies
Upgrade dependencies
2026-04-21 14:00:04 +08:00
grossmj f0f09e0e2c Upgrade alembic version 2026-04-21 13:25:42 +08:00
grossmj 7d84c33598 Upgrade code dependencies 2026-04-21 13:21:45 +08:00
grossmj 19c0bbbc56 Merge remote-tracking branch 'origin/3.0' into 3.0 2026-04-21 13:16:59 +08:00
grossmj 5d60626175 Bundle dev version of the web-ui 2026-04-21 13:16:36 +08:00
Jeremy Grossmann 8311936bc8 Merge pull request #2674 from yueguobin/docs/api-error-responses
docs: add API error response format documentation
2026-04-21 12:48:44 +08:00
YueGuobinandClaude Opus 4.6 56921e10d2 docs: add API error response format documentation
Document unified error response format across all GNS3 API endpoints,
including HTTP status codes, error types, and client-side error handling
patterns.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-21 12:46:48 +08:00
Jeremy Grossmann 5ee26f5ed7 Merge pull request #2673 from yueguobin/fix/swagger-ui-cve-2018-25031
fix: use local swagger-ui static files to resolve CVE-2018-25031
2026-04-21 00:58:52 +08:00
Guobin Yue 1ea8ab0cf8 Merge branch '3.0' into fix/swagger-ui-cve-2018-25031 2026-04-21 00:54:27 +08:00
YueGuobinandClaude Opus 4.6 46d712723a fix: use local swagger-ui static files to resolve CVE-2018-25031
Replace CDN-hosted swagger-ui-dist@3.30.0 with local static files
from gns3server/static/ to address CVE-2018-25031 vulnerability.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-21 00:43:59 +08:00
Jeremy Grossmann a366007f72 Merge pull request #2672 from yueguobin/fix/update-bundled-web-ui-script
Fix update-bundled-web-ui script for newer Angular CLI
2026-04-21 00:41:49 +08:00
YueGuobinandClaude Opus 4.6 85b8b04d72 fix: update bundled web-ui script for newer Angular CLI
- Remove deprecated --build-optimizer flag
- Update copy path from dist/ to dist/browser/ for new Angular build output

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-21 00:39:08 +08:00
Guobin YueandClaude Opus 4.6 df28036a68 fix(deps): resolve 3 security vulnerabilities (CVE-2025-71176, CVE-2026-40347, CVE-2018-25031) (#2671)
* fix(deps): upgrade pytest to 9.0.3 to fix CVE-2025-71176

CVE-2025-71176: pytest 9.0.2 and earlier versions have a local
security vulnerability due to predictable temporary directory naming.

- pytest: 8.4.2 → 9.0.3
- Python 3.10+ is now required

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(deps): upgrade python-multipart to 0.0.26 to fix CVE-2026-40347

CVE-2026-40347: python-multipart < 0.0.26 has a denial of
service vulnerability when parsing multipart data.

- python-multipart: 0.0.22 → 0.0.26

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(deps): upgrade swagger-ui to 4.1.3 to fix CVE-2018-25031

CVE-2018-25031: swagger-ui < 4.1.3 has a spoofing vulnerability
where remote attackers can display remote OpenAPI definitions
via crafted URLs.

- swagger-ui: 3.30.0 → 4.1.3
- Updated swagger-ui-bundle.js and swagger-ui.css

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(api): change FastAPI version from "v3" to "3.0.0" for Swagger UI 4.1.3 compatibility

Swagger UI 4.x enforces stricter version format validation.
The version "v3" is not accepted by the new validator.

Changed from:
- version="v3"

To:
- version="3.0.0"

This affects both controller and compute API definitions.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(deps): upgrade swagger-ui to 5.32.4

Fixes "Unable to render this definition" error when loading OpenAPI 3.0
docs. Swagger UI 3.x had incomplete OpenAPI 3.0 support.

- swagger-ui: 3.19.1 → 5.32.4 (latest)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 00:35:15 +08:00
f07d21c511 feat(web-wireshark): add implementation plan for script-driven (#2666)
* feat(web-wireshark): add implementation plan for script-driven integration

Add comprehensive implementation plan for Web Wireshark integration using script-driven approach. The plan outlines:

- Background and motivation for script-based Web Wireshark integration
- Core workflow from API request to WebSocket proxy connection
- Management script architecture with WebWiresharkManager class
- Docker container configuration and resource management
- Performance analysis and optimization recommendations
- Network setup and management procedures

Key features include:
- JWT token extraction from Authorization header
- Automatic GNS3 server URL detection
- Container lifecycle management per project
- Xpra session isolation per link
- WebSocket proxy integration through gns3server
- Resource monitoring and scaling guidelines

The implementation enables users to start Web Wireshark sessions via POST requests with `wireshark: true` parameter, providing a unified web-based packet capture interface.

* feat(web-wireshark): implement script-driven Web Wireshark integration

Add complete Web Wireshark container integration with script-driven architecture:

- Create manage_wireshark.py script for Docker container management
- Add LinkCapture schema with wireshark boolean field
- Update Link class with wireshark and jwt_token parameters
- Implement WebSocket proxy endpoint for xpra HTML5 client
- Add cleanup logic in Project class for container lifecycle

Key features:
- Script-driven container and xpra session management
- JWT token extraction from Authorization header
- GNS3 URL auto-detection with Controller/Config fallback
- WebSocket proxy for unified access through gns3server
- Proper cleanup on project close/delete

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(web-wireshark): use aiohttp instead of docker SDK

Replace docker-py SDK with direct Docker HTTP API calls using aiohttp,
following GNS3's existing architecture pattern in gns3server/compute/docker/.

Changes:
- Create DockerHTTPClient class using aiohttp + Unix socket
- Implement all Docker operations as async methods
- Remove dependency on docker Python SDK
- Use Docker API v1.44 via /var/run/docker.sock

Benefits:
- No additional dependencies required
- Consistent with GNS3's async architecture
- Better integration with existing codebase

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(web-wireshark): add dynamic Docker API version detection

Implement dynamic Docker API version detection following GNS3's pattern
in gns3server/compute/docker/__init__.py.

Changes:
- Add DOCKER_MINIMUM_API_VERSION and DOCKER_PREFERRED_API_VERSION constants
- Remove hardcoded "v1.44" prefix (now using "1.44" format)
- Add _check_connection() method to detect Docker daemon version
- Dynamically select API version based on daemon capabilities
- Add proper error handling for version mismatches

Behavior:
- Initialize with minimum API version (1.40)
- On first connection, detect Docker daemon API version
- Use preferred API version (1.44) if supported
- Fall back to daemon's minimum API version if needed
- Raise error if daemon version is too old

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(web-wireshark): add optional --verbose logging parameter

Remove hardcoded logging.basicConfig() and add --verbose parameter
to control log output, following GNS3's logging pattern.

Changes:
- Remove logging.basicConfig(level=logging.INFO) from module level
- Add --verbose/-v command line parameter
- Configure logging only when --verbose is specified
- Use structured log format with timestamp when verbose

Behavior:
- When called by GNS3: uses GNS3's logging configuration (default)
- When run standalone: no output unless --verbose is specified
- With --verbose: shows detailed logs with timestamps

This prevents the script from interfering with GNS3's logging
configuration while still allowing debug output when needed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(web-wireshark): fix code quality issues from static analysis

Fix issues identified by flake8 and pylint static analysis:

Import and formatting fixes:
- Remove unused 'time' import
- Fix import order (stdlib before third-party)
- Remove unnecessary f-strings without placeholders
- Split long line to comply with flake8 (max line length: 127)

Code structure improvements:
- Remove unnecessary 'else' after 'return'
- Add 'from e' to exception re-raising for better tracebacks

Code quality metrics:
- pylint score: 8.11/10 → 9.97/10 (+1.86)
- flake8: 0 errors (max line length: 127, per CI/CD standard)
- All critical issues resolved

Note: R0914 (too-many-locals) warning is informational only,
code remains clear and maintainable.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web-wireshark): export LinkCapture schema in schemas module

Add LinkCapture to the schemas module exports in __init__.py to fix
the AttributeError when starting the GNS3 server.

Error was:
  AttributeError: module 'gns3server.schemas' has no attribute 'LinkCapture'

This was caused by adding the LinkCapture class to controller/links.py
but forgetting to export it in the schemas __init__.py.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(web-wireshark): add --image parameter for custom Docker images

Add optional --image parameter to allow using custom Docker images
for testing, instead of requiring gns3/web-wireshark:latest.

Changes:
- Add --image parameter to start command (default: gns3/web-wireshark:latest)
- Update get_or_create_container() to accept image parameter
- Update start_wireshark_session() to accept and pass image parameter
- Update TEST.md with examples of using custom images

Usage:
  # Using default image
  python3 manage_wireshark.py start --project-id x --link-id y --jwt-token z

  # Using custom image (for testing)
  python3 manage_wireshark.py start --project-id x --link-id y --jwt-token z --image ubuntu:latest

This makes it easier to test the script without having the official
gns3/web-wireshark image available.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(web-wireshark): add configurable resource limits and increase session capacity

Add configurable resource parameters and increase session support from 10 to 100.

Resource parameters:
- --memory: Memory limit (default: 2g)
- --memory-swap: Memory swap limit (default: same as memory)
- --cpus: CPU cores (default: 1.0)
- --pids-limit: Process limit (default: 1000)

Other improvements:
- Fix CPU quota calculation: 1000000 microseconds = 1.0 CPU core
  (was incorrectly 100000 = 0.1 CPU core)
- Add health check: xpra list command
- Add log configuration: json-file, max-size=10m, max-file=3
- Increase session capacity: 10 → 100 concurrent sessions
- Port range: 12300-12399 (was 12300-12309)
- Display range: :100-:199 (was :100-:109)

This matches the docker run command parameters and provides
better resource management and monitoring capabilities.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web-wireshark): update UDPLink.start_capture() to accept new parameters

Update UDPLink.start_capture() to accept the new wireshark and jwt_token
parameters and pass them to the parent Link class.

This fixes the TypeError when starting capture on UDP links:
  TypeError: UDPLink.start_capture() got an unexpected keyword argument 'wireshark'

The UDPLink class overrides start_capture() but didn't include the new
parameters added for Web Wireshark support.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: add project memory infrastructure and JWT token flow documentation

- Add memory skill for recording project knowledge
- Document JWT token flow in Web Wireshark integration
- Update .gitignore to track skills and memory directories

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web-wireshark): fix Docker API URL format and use docker exec CLI

- Add "v" prefix to Docker API URL (http://docker/v{version}/...)
- Remove unused exec_create/exec_start API methods
- Fix Healthcheck.Test format to ["CMD-SHELL", "command"]
- Use docker exec CLI instead of Docker API for command execution
- This aligns with GNS3 docker_vm pattern

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web-wireshark): improve xpra session management and error handling

- Check and clean up existing sessions before starting new xpra session
- Add verification that xpra session started successfully
- Use docker exec CLI consistently instead of Docker API
- Improve error logging and diagnostics

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(web-wireshark): add timeout handling and container health checks

- Add REQUEST_TIMEOUT constant for Docker HTTP API requests
- Add asyncio.timeout wrapper for Docker API calls to prevent hanging
- Add _is_container_healthy() to check container responsiveness
- Add _exec_in_container() helper with timeout support
- Improve unhealthy container handling with force remove
- Add detailed logging for container health state

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(web-wireshark): split monolithic file into modules

Split manage_wireshark.py into:
- docker_client.py: Docker HTTP API client
- manager.py: WebWiresharkManager with session management
- manage_wireshark.py: CLI entry point

This improves code organization and maintainability.
Keep all timeout handling and health check logic.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web-wireshark): correct NanoCpus calculation to use nanoseconds

NanoCpus in Docker API requires nanoseconds (1 CPU = 1000000000),
not the previous incorrect multiplier of 100000.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web-wireshark): fix xpra command quoting and session verification

- Add quotes around --xvfb parameter value to preserve spaces
- Fix session verification to check display number instead of session name
  (xpra list shows "LIVE session at :185" not session name)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web-wireshark): run wireshark in background with &

Wireshark with curl pipeline runs continuously, so it must run
in background to avoid blocking. Also reduced timeout since we
don't wait for completion.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(web-wireshark): add deterministic hash for display/port allocation

Use MD5-based hash instead of Python's hash() which is randomized
across process restarts. This ensures display and port numbers are
stable when the GNS3 server restarts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: extract link_id_to_port to shared utils module

Move deterministic hash functions to gns3server/utils/port_allocator.py
to avoid code duplication and ensure consistent algorithm across
manager.py and links.py.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(links): move import to top of file

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web-wireshark): use correct Config access pattern like gns3-copilot

The Server config is an object with .protocol.value, .host, .port
attributes, not a dict. Fixes URL detection failing and falling back
to 127.0.0.1:3080 which doesn't work from inside containers.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add UUID validation utility and use in manage_wireshark

Create gns3server/utils/uuid_validator.py with validate_uuid function
to validate UUID format and catch typos early with clear error messages.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: use argparse.ArgumentTypeError for proper error message display

Previously ValueError was used which only showed 'invalid validate_uuid value'.
Now shows the full helpful message about expected format.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(web-wireshark): add --dpi=96 to xpra start parameters

Set standard DPI for better display scaling in web Wireshark.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: update TEST.md with correct project-id format

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(web-wireshark): hide xpra shutdown menu via XPRA_CLIENT_CAN_SHUTDOWN

Prevents users from accidentally shutting down the xpra server
through the HTML5 client menu.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs(memory): add xpra-html5-client configuration reference

Document xpra HTML5 client configuration including:
- URL parameters for toolbar menu control
- default-settings.txt parameters (Features, Connection, Advanced)
- Server-controlled submenu items
- XPRA_CLIENT_CAN_SHUTDOWN environment variable
- Background image customization

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(web-wireshark): remove xpra stop cleanup to avoid zombie processes

xpra stop can leave zombie processes and timeout. Instead, let xpra start
reuse the display directly (it will overwrite existing session).

Also added --file-transfer=no, --printing=no, --sound=no to disable
unneeded features.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web-wireshark): add fullscreen_button=false to default-settings.txt

Also remove --file-transfer/--printing/--sound from command line since
xpra doesn't support these options. Configure in default-settings.txt instead.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(web-wireshark): update xpra background with GNS3 branding

- Replace default xpra background with GNS3 icon and modern gradient
- Update CSS to use SVG background image with cover sizing
- Change background color to gradient from #021d3a to linear gradient
- Improves visual integration with GNS3 web interface

* style: add GPLv3 headers with copyright to web_wireshark modules

Co-Authored-By: YueGuobin <yueguobin@gmail.com>

* feat(docker): use Alibaba Cloud Debian mirror for faster builds in China

Use mirrors.aliyun.com for Debian packages with correct paths for
both main repo (/debian) and security repo (/debian-security).

Co-Authored-By: YueGuobin <yueguobin@gmail.com>

* feat(web-wireshark): update xpra background styling and echo command

- Replace `echo -e` with `printf` for better POSIX compatibility in Dockerfile
- Update xpra HTML5 client background to use GNS3 icon with light gradient
- Change background color from dark blue to light gray for improved visibility

* fix(web-wireshark): use pkill to stop xpra sessions

Replace 'xpra stop :{display}' with 'pkill -f "xpra.*:{display}"' for more reliable session termination.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(web-wireshark): start Wireshark in fullscreen mode

Add --fullscreen flag to Wireshark startup command to prevent window decorations and improve user experience.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web-wireshark): use carrier-grade NAT subnet to avoid conflicts

Change Docker network subnet from 172.28.0.0/16 to 100.64.1.0/24 to avoid conflicts with common private networks.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(web-wireshark): update subnet to /22 for 1000+ projects

Change Docker network subnet from 100.64.1.0/24 to 100.64.0.0/22 to support 1000+ projects (1022 available IPs). Update all documentation to reflect the new subnet.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web-wireshark): replace CGNAT subnet with configurable private subnet

Replace the CGNAT address block (100.64.0.0/22) with a standard private
subnet (172.31.0.0/22) to avoid network access issues. Many networks and
ISPs block or cannot route CGNAT addresses.

Changes:
- Add WebWiresharkSettings to config schema with configurable subnet
- Read network_subnet from config, default to 172.31.0.0/22
- Add Web Wireshark configuration section to sample config

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web-wireshark): comment out dpi setting

Allow xpra to use default DPI settings for better display scaling.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web-wireshark): set DPI in Xvfb to prevent scaling warnings

Add -dpi 96 to Xvfb startup command to match xpra's expected DPI
and avoid "scaling problems" warnings.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web-wireshark): remove custom Xvfb to use default Xorg-dummy

Remove --xvfb parameter to let xpra use the default Xorg-dummy driver,
which properly handles DPI changes when resize-display is enabled and
prevents DPI mismatch warnings.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* revert(web-wireshark): restore Xvfb configuration

Restore the Xvfb display server configuration for xpra sessions.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(web-wireshark): enhance xpra HTML5 default settings

Update xpra HTML5 configuration to disable additional unused features:
- audio, keyboard, mediasource, aurora, http-stream
- Improve readability using heredoc format instead of printf

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(api): add RBAC authentication to web wireshark WebSocket endpoint

- Add `has_privilege_on_websocket` dependency to enforce Link.Capture privilege
- Include current_user parameter in endpoint for user identification and logging
- Update endpoint documentation to reflect token requirement and privilege
- Add test example WebSocket URL in TEST.md for reference

* refactor(web-wireshark): add generic WebSocket proxy and disable xpra HTML

- Add websocket_to_websocket.py utility for binary WebSocket proxy
- Disable xpra HTML server with --html=no flag
- Update manager return value: url -> ws_url
- Simplify WebSocket proxy implementation in links.py

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* perf(web-wireshark): remove unnecessary sleep delays

Remove 2-second sleep delays after container start and xpra initialization.
Health checks and verification happen immediately, improving startup time.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(agent): prevent blocking during project close

- Add 5s timeout for AgentService.checkpointer_conn.close()
- Optimize stop_all_sessions: single command instead of 100 docker exec calls
- Prevents indefinite hang when closing projects

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web-wireshark): return errors to client on startup failure

- Throw ControllerError when Web Wireshark startup fails
- Include detailed error messages from script stderr
- Support both ws_url and url response formats
- Client now receives proper error response instead of success

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* perf(web-wireshark): parallelize startup and remove unnecessary waits

- Parallel execution: container info query + xpra start
- Remove xpra list verification (unnecessary)
- Fire-and-forget Wireshark startup (no timeout wait)
- Startup time reduced from ~7s to ~1s

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(web-wireshark): add stop-container and delete-container commands

- Add stop-container command to stop container on project close
- Add delete-container command to delete container on project delete
- Enables proper container lifecycle management
- Containers are now stopped (not deleted) when project closes
- Containers are deleted when project is deleted

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* perf(project): simplify close flow by removing redundant xpra session cleanup

Since docker stop with timeout=0 already force-kills all processes in the
container, explicitly stopping xpra sessions before stopping the container
is unnecessary. Remove the _cleanup_web_wireshark_xpra_sessions() call
to reduce subprocess overhead and simplify the close flow.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* perf(docker): force kill containers on stop by default

Change docker stop timeout from 10 seconds to 0 (immediate SIGKILL).
Web Wireshark containers don't need graceful shutdown since they have
no persistent state.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web-wireshark): enable WebSocket protocol for xpra connection

- Change xpra bind from --bind-tcp to --bind-ws for WebSocket support
- Enable HTML client with --html=on for xpra WebSocket server
- Pass binary subprotocol when connecting to xpra container

The xpra WebSocket server requires the 'binary' subprotocol during
handshake. Without it, the server returns 403 with message:
"client does not support 'binary' protocol".

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web-wireshark): add WebSocket subprotocol negotiation support

Fix WebSocket proxy for xpra container by implementing proper subprotocol
negotiation. The xpra client requires the server to respond with the
negotiated subprotocol (binary) in the WebSocket handshake response.

Changes:
- Modified get_current_active_user_from_websocket to extract client's
  requested subprotocols from Sec-WebSocket-Protocol header
- Updated websocket.accept() call to include negotiated subprotocol
- Enhanced websocket_proxy to support subprotocol parameter
- Improved logging for WebSocket connection debugging

This fixes the issue where xpra clients would immediately disconnect
after connection due to missing subprotocol in server response.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(web-wireshark): remove verbose debug logging

Remove excessive debug logs from WebSocket proxy implementation while
keeping essential logs for troubleshooting:
- Keep: subprotocol negotiation, connection establishment, errors
- Remove: verbose step-by-step debugging information

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(web-wireshark): translate Chinese comments and docs to English

- Translate all Chinese comments in project.py, link.py, and links.py to English
- Convert TEST.md and maunal-test.md documentation to English
- Remove obsolete IMPLEMENTATION_PLAN.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore(docker): lock xpra version to 6.4.3 for reproducible builds

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore(docker): improve Dockerfile with TZ, no-install-recommends, and labels

- Add TZ=UTC timezone setting
- Use --no-install-recommends to reduce image size
- Add LABEL metadata for maintainer and description

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor(docs): rename and consolidate documentation

- Rename TEST.md to WEB_WIRESHARK.md for clearer naming
- Merge maunal-test.md content into main document under "Manual Testing" section
- Remove obsolete gns3_icon_black.svg

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(docker): add xpra-x11 package and remove --no-install-recommends

- Add xpra-x11 package required for seamless mode
- Remove --no-install-recommends to ensure all recommended packages are installed

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(api): add capture file download endpoint

Add GET /{link_id}/capture/file endpoint to download PCAP capture files.
Supports downloading while capture is active (streaming).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web_wireshark): improve session cleanup and add known issues

- Add cleanup of existing processes before starting xpra session to prevent
  "another window manager seems to be running" errors
- Stop all associated processes (xpra, wireshark, Xvfb) when stopping sessions
- Document known issues in WEB_WIRESHARK.md including JWT token security,
  duplicate code, and other implementation concerns

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(web_wireshark): add restart wireshark API endpoint

- Add POST /links/{link_id}/capture/wireshark/restart endpoint
- Add restart command to manage_wireshark.py CLI
- Add _restart_web_wireshark method in link.py controller
- Restart simply calls start_wireshark_session which handles cleanup

This allows users to recover after accidentally closing the Wireshark
window without having to stop and restart the entire capture.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: add Web Wireshark business process documentation

Document the Web Wireshark feature including architecture diagrams,
business processes for capture start/stop, container lifecycle,
WebSocket connection flow, and session management.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web_wireshark): fix container network access and improve session cleanup

- Fix GNS3 server URL detection to use container gateway IP (172.31.0.1)
  instead of localhost/127.0.0.1/0.0.0.0 which don't work from containers
- Add import socket module for gateway IP conversion
- Move urllib.parse import to file header (code style improvement)
- Add logging for Web Wireshark startup (capture stream URL, display, etc.)
- Fix X lock file cleanup to prevent "Server is already active" errors
- Use exec pkill to reduce zombie processes from docker exec bash
- Add _cleanup_x_lock() method to remove X lock files after stopping sessions
- Update link.py to always log subprocess stderr for debugging

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web_wireshark): avoid zombie pkill processes by using Docker API

Replace pkill commands with Docker API-based process killing to prevent
zombie process accumulation in Web Wireshark containers.

Changes:
- Add DockerHTTPClient.list_processes() method to query container processes
- Rewrite _kill_process_tree() to use Docker API instead of pkill
- Unify all process cleanup to use _kill_process_tree() method
- Add logging for killed processes (count and PIDs)
- Include fallback to pkill if Docker API fails

This prevents the accumulation of zombie pkill processes that occurred
when using bash -c "pkill -9 -f pattern" commands.

Testing: Started and stopped multiple capture sessions, verified no new
pkill zombie processes are created during cleanup.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web_wireshark): use docker-init and cleanup socket files

Enable Docker init system (tini) as PID 1 and clean up xpra socket
files when stopping sessions to prevent zombie processes and leftover
sockets.

Changes:
- Add "Init": True to container host_config to use docker-init (tini)
- Extend _cleanup_x_lock() to remove xpra socket files
  * /run/user/1000/xpra/{display}/socket
  * /run/user/1000/xpra/*-{display}
  * /home/gns3/.xpra/*-{display}

Benefits:
- docker-init (tini) automatically reaps orphan processes, eliminating
  zombie process accumulation (tested: 53 zombies -> 0 zombies)
- Socket cleanup prevents xpra list from showing UNKNOWN sessions
- Cleaner container state after stopping sessions

Testing:
- Started and stopped 3 capture sessions
- Verified 0 zombie processes after stopping
- Verified xpra list shows "No xpra sessions found" (no UNKNOWN)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(web_wireshark): add comprehensive CLI script documentation

Add detailed module docstring to manage_wireshark.py explaining:
- Script purpose: CLI tool for manual management, debugging, and testing
- Important note: Use WebWiresharkManager directly for programmatic access
- Usage examples for all commands (start, stop, restart, stop-all, delete)
- Available commands list with descriptions
- Output format specification (JSON to stdout/stderr)
- Help information for getting command-specific usage

This clarifies that the script is intended as a CLI utility, not for
subprocess calls from within GNS3 server code.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(web_wireshark): use direct API calls instead of subprocess

Replace subprocess calls to manage_wireshark.py with direct API calls
to WebWiresharkManager, eliminating subprocess overhead and JSON parsing.

Changes:
- Add import for WebWiresharkManager
- Refactor _start_web_wireshark() to use direct API call
- Refactor _stop_web_wireshark() to use direct API call
- Refactor _restart_web_wireshark() to use direct API call

Benefits:
- Code reduction: 78 lines (-68%)
- Better performance: No subprocess creation overhead
- Better logging: Manager logs directly to GNS3 logging system
- Simpler error handling: Direct exceptions instead of return codes
- No JSON parsing: Direct Python objects
- Resource cleanup: Added finally blocks to ensure manager.close()

Testing:
- All Web Wireshark operations work correctly
- Logs now appear in GNS3 server logs instead of stderr
- Error handling improved with proper exception propagation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web_wireshark): resolve circular import with delayed imports

Fix circular import error by moving WebWiresharkManager import from
module level to function level (delayed import).

Circular dependency was:
  link.py → WebWiresharkManager → Controller → link.py

Solution:
  - Remove top-level import of WebWiresharkManager
  - Add delayed imports in each method that uses it:
    * _start_web_wireshark()
    * _stop_web_wireshark()
    * _restart_web_wireshark()

This allows the controller module to fully initialize before importing
WebWiresharkManager, breaking the circular dependency.

Error before fix:
  ImportError: cannot import name 'Controller' from partially initialized
  module 'gns3server.controller' (most likely due to a circular import)

Testing:
  - Successfully imports Link module
  - GNS3 server starts without import errors

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: move imports to module level and remove Controller dependency

Remove circular dependency between link.py and manager.py by:

1. Remove Controller import from manager.py
   - Manager no longer imports Controller
   - URL detection now relies on Config or default only
   - link.py passes capture_stream_url to manager

2. Move WebWiresharkManager import to module level in link.py
   - No longer need delayed imports since no circular dependency
   - Clean, standard Python import pattern

3. Remove redundant Config import in ensure_network()
   - Config was already imported at module level

Changes:
- manager.py: -24 lines (removed _get_gns3_url_from_controller and redundant import)
- link.py: -30 lines net reduction after moving import to top

Testing:
- All imports work without circular dependency errors
- GNS3 server starts successfully

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(docker_client): use text response for list_processes API

Docker API /containers/{id}/top returns plain text, not JSON.
The generic _request method auto-parses JSON which caused:
  "'dict' object has no attribute 'strip'"

Fix by using session.get() directly with response.text()
instead of the generic _request method.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web_wireshark): use correct capture stream URL endpoint

Remove passing capture_stream_url from link.py to manager.py.
Manager.py auto-detects URL using correct endpoint:
  /v3/projects/{project_id}/links/{link_id}/capture/stream

This endpoint supports JWT authentication, unlike the compute URL
(/v3/compute/...) which requires compute credentials.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web_wireshark): use container-local PIDs for process killing

- Docker API returns host PIDs, not container PIDs - use pgrep inside
  container to get correct PIDs for kill
- Fix list_processes to parse Docker API JSON response correctly
- Remove unnecessary exec prefix in shell commands
- Add logging for debugging process killing

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* perf(web_wireshark): optimize process killing with single pgrep call

Replace sequential _kill_process_tree calls with a new _kill_process_tree_batch
method that combines all patterns into a single regex. This reduces docker exec
calls from 8 to 1, improving performance from ~8 seconds to ~0.9 seconds.

Changes:
- Add _kill_process_tree_batch() method with combined regex pattern matching
- Update start_wireshark_session() to use batch cleanup
- Update stop_wireshark_session() to use batch cleanup
- Update stop_all_sessions() to use batch cleanup

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* perf(web_wireshark): disable HTML5 client to improve xpra startup speed

Change --html=on to --html=off to disable the xpra HTML5 client interface.
This reduces xpra startup time from ~6.4s to ~2.9s (55% improvement) while
keeping the WebSocket server functional for browser connections.

The HTML5 client is not needed as we only require the WebSocket endpoint
for remote display forwarding.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* perf(web_wireshark): optimize container health check using Docker built-in status

Replace manual docker exec ping with Docker's built-in health check status
to reduce container startup latency by ~1 second.

Changes:
- Use container["Health"]["Status"] instead of manual ping check
- Skip health check for containers with "healthy" or "starting" status
- Only verify containers with "unhealthy" status
- Keep manual health check for newly started containers

This reduces the container verification time from ~1s to near-zero
for healthy running containers while maintaining safety for unhealthy ones.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* perf(web_wireshark): get gateway IP from Docker API instead of container exec

Replace slow docker exec method with fast Docker Network API call to get
gateway IP. This reduces gateway detection from ~850ms to ~1ms (1000x faster).

Changes:
- Use docker.get_network() API to get gateway from IPAM config
- Keep container exec methods as fallback if Docker API fails
- Remove container_id requirement (not needed for Docker API method)

The Docker network gateway is shared by all containers in the network,
so querying the network is more efficient than querying each container.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(web_wireshark): remove unreliable nameserver fallback for gateway detection

Remove the fallback method that reads /etc/resolv.conf nameserver as gateway.
This method is unreliable because:
- nameserver is not necessarily the gateway (could be upstream DNS)
- Many systems use 127.0.0.53 (systemd-resolved) or 127.0.0.1
- Even when not local, it could be public DNS (8.8.8.8, 1.1.1.1)

The current fallback strategy is sufficient:
1. Docker Network API (fast, reliable)
2. /proc/net/route (standard gateway detection)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* perf(web_wireshark): use host perspective for process killing (37x faster)

Replace docker exec with host perspective process management for killing
container processes. This reduces process cleanup from ~850ms to ~23ms.

Key optimization:
- Get container init PID using docker inspect (fast)
- Use pgrep -P <init_pid> to find child processes from host perspective
- Kill processes directly using host PID (no docker exec needed)

Performance improvements:
- Process finding: 850ms → 23ms (37x faster)
- Process killing: 850ms → <1ms (850x faster)
- File checking: 850ms → 0.003ms (280,000x faster)

Fallback to docker exec method if host perspective fails.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* perf(web_wireshark): use host perspective for file cleanup (891x faster)

Replace docker exec with direct filesystem access from host perspective
for cleaning up X lock files and xpra sockets. This reduces cleanup time
from ~890ms to ~1ms (891x faster).

Key optimization:
- Access /proc/<container_pid>/root/ directly from host
- Use os.remove() and glob.glob() instead of docker exec rm -f
- Fallback to docker exec if host perspective fails

This complements the earlier optimization for process killing, further
reducing startup time.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Revert "perf(web_wireshark): use host perspective for file cleanup (891x faster)"

* fix(web_wireshark): recursively kill all descendant processes to prevent orphans

Previous implementation only killed direct children of container init using
`pgrep -P <init_pid>`, but xpra spawns child processes (Xvfb, pulseaudio,
ibus-daemon) that become grandchildren and were not being terminated.

This fix walks the entire process tree recursively to find and kill all
descendant processes, ensuring complete cleanup without orphans.

Performance: ~20-40ms (only 10-20ms slower than previous 23ms, but ensures
thorough cleanup).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(web_wireshark): add comprehensive startup/shutdown performance metrics

Add detailed performance characteristics section documenting:
- Startup performance breakdown (before/after optimization)
- Shutdown performance breakdown (before/after optimization)
- First startup vs subsequent startup comparison
- Measured production data
- Key optimization techniques

Performance improvements: 67% faster startup, 78% faster shutdown,
zero orphan processes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web_wireshark): ensure container stops on project close

Remove dependency on _web_wireshark_container_created flag which gets
reset when project is reloaded, causing container to not stop on project close.

Now directly attempts to stop container on every project close. If container
doesn't exist, the script handles it gracefully. This is simpler and more
reliable than maintaining a flag.

Also removed unnecessary _cleanup_web_wireshark_xpra_sessions() call since
stopping the container automatically terminates all xpra sessions inside.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web_wireshark): ensure container deletion on project delete

Remove dependency on _web_wireshark_container_created flag from
_cleanup_web_wireshark_container() to ensure container is deleted
when project is deleted, even if project was reloaded and flag was reset.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(web_wireshark): remove unused _web_wireshark_container_created flag

This flag was set but never read for any conditionals since we changed
the stop/delete methods to directly attempt the operation. It's purely
redundant code that adds confusion.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* perf(web_wireshark): skip unnecessary cleanup using fast host perspective check

Add _check_residuals_exist() function that uses host perspective (~20ms)
to check if residual processes or socket files exist before cleanup.

Returns (has_process_residuals, has_socket_residuals) tuple to allow
selective cleanup - if only sockets need cleaning, skip the slower
process tree killing.

For new containers with no residuals, this saves ~3 seconds of
unnecessary docker exec calls.

Socket cleanup always uses docker exec for safety (avoiding accidental
host filesystem deletion from /proc/<pid>/root/ path errors).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web_wireshark): increase container exec timeout from 5s to 10s

xpra start with Xvfb initialization can take longer than 5 seconds in Docker containers, causing timeout failures. Increasing timeout to 10 seconds to allow sufficient startup time.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* perf(web_wireshark): optimize cleanup and document docker exec limitations

- Combine X lock and xpra socket cleanup into single docker exec call
  Reduces exec calls from 2 to 1 per stop operation, improving performance
  when stopping multiple capture sessions.

- Document Docker exec performance limitations with test data showing
  parallel exec is 42% slower than serial due to Docker daemon's
  internal queuing mechanism.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(links): prevent AssertionError in stream_pcap during rapid stop_capture

Fix race condition where stream_pcap checks link.capturing (True) but
link.capture_node becomes None before accessing link.compute.

This happens when stop_capture() is called and rapidly cleans up
_capture_node while WebSocket requests are still processing.

Now check both capturing and capture_node to ensure capture is still active.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(links): prevent AssertionError in stream_pcap during rapid stop_capture

Fix race condition where stream_pcap checks link.capturing (True) but
link.capture_node becomes None before accessing link.compute.

This happens when stop_capture() is called and rapidly cleans up
_capture_node while WebSocket requests are still processing.

Now check both capturing and capture_node to ensure capture is still active,
and log at DEBUG level since this is expected behavior during rapid stop.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(web_wireshark): load container config from settings

- Load memory, cpus, and pids_limit from WebWireshark config section
- Apply config only on container creation (_start_web_wireshark)
- Skip config on restart (_restart_web_wireshark) as container exists

Users can now configure container resources in gns3_server.conf:

[WebWireshark]
memory = 4g
cpus = 2.0
pids_limit = 2000

If not configured, defaults (2g, 1.0, 1000) are used.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(web_wireshark): add container statistics to /v3/statistics endpoint

Add Web Wireshark container monitoring to the statistics API for
better visibility into packet capture sessions.

Changes:
- Create new stats.py module with collect_webwireshark_stats()
  * Collects container info (status, project, active sessions)
  * Gets resource limits (memory, CPU, PIDs) from container config
  * Gets resource usage via docker stats (memory, CPU, PIDs)
  * Properly closes aiohttp connections to avoid leaks

- Update /v3/statistics endpoint to include webwireshark data
  * total_containers: Total number of Web Wireshark containers
  * running_containers: Number of containers currently running
  * active_sessions: Total active capture sessions
  * containers: Array with per-container details

- Update statistics-api.md documentation
  * Change URL from /v1/statistics to /v3/statistics
  * Add webwireshark field descriptions and examples
  * Add dashboard integration for Web Wireshark monitoring

Example response:
{
  "webwireshark": {
    "total_containers": 1,
    "running_containers": 1,
    "active_sessions": 2,
    "containers": [{
      "project_id": "...",
      "project_name": "test",
      "container_id": "6edc9029bac0",
      "status": "running",
      "memory_limit": "4.0 GB",
      "cpu_limit": "4.0",
      "pids_limit": 4000,
      "memory": "535.7MiB / 4GiB",
      "cpu": "0.29%",
      "pids": 124
    }]
  }
}

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(project): use WebWiresharkManager directly instead of subprocess

Replace subprocess calls to manage_wireshark.py with direct
WebWiresharkManager method calls in project.py. This eliminates
unnecessary process overhead and maintains consistent usage pattern
with link.py.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor(logging): use %-formatting instead of f-strings in WebWireshark methods

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor(web_wireshark): use info level log when container not found

Change log level from warning to info when container doesn't exist
during stop/delete operations, and fix f-string without placeholders.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor(logging): lower log level for client disconnection

Change log level from warning to debug when client possibly
disconnects, as this is normal behavior when users close
browser tabs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(linting): resolve ruff warnings and errors

- Remove unused variable proc (fire-and-forget subprocess)
- Remove duplicate nodes property definition
- Remove extraneous f-prefix from f-strings without placeholders
- Change bare except to except Exception
- Remove unused imports (sys, asyncio, json)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(web_wireshark): improve error message when Docker image not found

When creating a container fails due to missing image, provide helpful
error message with docker pull command and local build instructions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(schema): add wireshark field to Link schema

Add wireshark boolean field to Link Pydantic schema so it is
included in API responses when Web Wireshark session is active.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(link): add wireshark state tracking

Track whether Web Wireshark is running on a link by adding
_wireshark boolean property, updated on start/stop operations.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(chat): add session abort functionality

Add ability to abort streaming chat sessions via REST API.

Changes:
- Add abort flag to MessagesState for tracking abort requests
- Add session_id to state for abort event correlation
- Add _abort_flags dict and check/set/clear functions in gns3_copilot.py
- Add abort_handler_node to generate aborted tool messages
- Modify should_continue to route to abort_handler_node when aborting
- Add abort_session() method in AgentService
- Add POST /sessions/{session_id}/abort API endpoint
- Clear abort flag at stream start

When abort is triggered during streaming:
- If LLM has tool_calls pending, abort_handler_node generates
  aborted tool messages to maintain checkpoint consistency
- Prevents "insufficient tool messages" error on resume

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(chat): send tool_end event when stream is aborted

When a stream is aborted during tool execution, yield proper tool_end
events for aborted tools instead of a generic abort event. This maintains
compatibility with the frontend's expected tool_start/tool_end flow.

Changes:
- Add stream_aborted tracking flag
- After stream loop, check abort flag and yield tool_end events
- Add "abort" to ChatResponse type enum (unused but available)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(web_wireshark): add gns3-wireshark-setup command for Docker image setup

Add a new entry point script that allows users to setup the Web
Wireshark Docker image with a single command:

    pip install gns3-server && gns3-wireshark-setup

The script will:
1. Try to pull gns3/web-wireshark:latest from Docker Hub
2. If pull fails, build the image locally using the included Dockerfile
3. Show raw docker pull/build output for full visibility

Files changed:
- Add setup_wireshark_image.py (new entry point script)
- Update pyproject.toml (add gns3-wireshark-setup entry point)
- Update documentation (README.md, WEB_WIRESHARK.md, web-wireshark-business-process.md)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(appliance): add tags field support for appliances and templates

- Add tags field to ApplianceV1_6 and ApplianceV8 schemas
- Add tags propagation from appliance config to template
- Simplify VPCS builtin template tags

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix test in test_link.py

* Fix link.py after failed tests

* feat(copilot): add device skills system for LLM context injection

- Add skills module with registry and DeviceSkillsTool
- Skills organized by vendor/series for easy extensibility
- Support device_type, category (device/protocol/feature), operation (config/diagnosis)
- First implementation: VPCS skill (gns3_vpcs_telnet)
- Skills tool integrated into teaching_assistant and lab_automation modes

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(vpcs): change prompt detection log from warning to debug

The "VPCS prompt not clearly detected" message is not an error,
connection works fine. Change to debug level to reduce noise.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs(memory): add uBridge permission issue documentation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(copilot): include link_id in links_summary output

Return link_id in the links_summary method so that the AI can
identify which link to analyze when using the packet capture tool.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(copilot): add packet capture analysis tool

Add PacketCaptureTool that allows AI to analyze packets from an active
GNS3 capture. The tool downloads capture files from the GNS3 server
and runs tshark analysis to help users understand network traffic.

Features:
- Download capture file from /capture/file endpoint
- Run tshark with custom arguments for flexible analysis
- Support analyzing specific packets (e.g., "explain packet #42")
- Support protocol statistics, traffic analysis, and expert info

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(copilot): use shlex.split to properly parse quoted tshark arguments

tshark_args may contain quoted filter expressions like "-Y \"frame.number == 24\"".
Using plain str.split() breaks these quoted arguments, causing tshark warnings
about conflicting display filters. Use shlex.split() to correctly parse quoted
arguments.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor(copilot): simplify PacketCaptureTool to accept only packet_number

Instead of exposing complex tshark arguments to the LLM, the tool now
accepts a simple packet_number parameter and internally constructs the
tshark command with verbose output. This prevents the LLM from generating
incorrect tshark parameters while still providing detailed packet analysis.

Changes:
- Remove tshark_args and max_lines parameters
- Accept only packet_number as input
- Internal command: tshark -r <file> -Y "frame.number == N" -V
- Returns complete packet structure without line limits

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: add CC BY-SA 4.0 license headers to documentation files

Add SPDX license headers referencing docs/LICENSE file to all markdown
and HTML documentation files in the docs directory.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(copilot): add topology planner skill

Add new skill for automatic network lab topology planning:
- IOU as default image, 10.0.0.0/8 IP range, max 10 nodes
- Node naming convention: R/S/PC + number
- 7-step workflow for create/rename/link/start/verify/config
- IP allocation rules and troubleshooting guide

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(copilot): add node positioning rules to topology planner skill

Add grid-based positioning for GNS3 nodes:
- Minimum 250px distance between nodes
- Grid layout: 4 columns, 300x250px spacing
- Formula: x = -400 + col * 300, y = -200 + row * 250
- Update workflow params_required to include x, y coordinates

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor(copilot): remove unused helper functions from topology planner skill

Delete Python helper functions that cannot be serialized to JSON:
- calculate_node_positions()
- get_position_for_node()
- allocate_subnet()
- allocate_ip()
- TOPOLOGY_CREATION_STEPS (duplicate of workflow in skill dict)

LLM should use formula descriptions in skill to calculate positions/IPs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(copilot): add topology_planner workflow to lab automation prompt

Add device_skills tool to AVAILABLE TOOLS table.
Add TOPOLOGY PLANNING WORKFLOW section explaining:
- How to query topology_planner skill
- Default conventions (IOU, 10.0.0.0/8, naming rules, position formula)
- 7-step workflow for topology creation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(copilot): support name parameter in gns3_create_node tool

- Add optional 'name' field to node creation, allowing direct naming
- Update Node constructor to pass name parameter
- Remove separate rename step (step_3) from topology planner workflow
- Renumber workflow steps: 1-2-3-4-5-6 (skipping old step_3 rename)

This eliminates the need for a separate gns3_update_node_name_tool call
when creating nodes with predefined names.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs(copilot): update topology workflow to 6 steps

Remove rename step since name can be set directly in create_gns3_node.
Workflow changed from 7 steps to 6 steps.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor(copilot): replace grid positioning with topology-based layout

Redesign node positioning rules to follow classic network topologies:
- Star: hub at center, spokes radiating outward
- Ring: nodes in circular arrangement
- Bus: linear chain of nodes
- Mesh: grid pattern for interconnected nodes
- Hierarchical: three-tier (Core → Distribution → Access)
- Linear P2P: point-to-point WAN links in a line

Remove old grid formula. Update prompt and workflow to reflect new approach.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs(copilot): add note about combining topology types

LLM can mix topology types as needed, e.g., star + linear_p2p for WAN segments.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor(copilot): remove language matching rules from prompts

Remove language matching rules that cause inconsistent responses:
- "User writes in Chinese → Respond in Chinese"
- "User writes in English → Respond in English"

These created ambiguity and led to inconsistent language behavior.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor(copilot): remove Chinese from response template

Replace mixed Chinese/English headers with English only:
- "操作总结 / Operation Summary" → "Operation Summary"
- "详细信息 / Details" → "Details"

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor(copilot): remove Chinese mentions from prompts

Remove references to "Chinese" language in title_prompt.py:
- "Generates concise Chinese or English titles" → "Generates concise titles"
- "If the content is predominantly in Chinese, generate a Chinese title" → removed

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(copilot): use short_name for link labels and support short port names

- Match ports by both name and short_name for flexibility
- Use short_name (e.g. "e0/0") instead of full name (e.g. "Ethernet0/0")
  for link labels, improving visual clarity in dense topologies

* feat(topology): replace hardcoded interface names with dynamic placeholders

- Update topology planner skill template to use {short_name} placeholder
- Allows dynamic interface name generation based on device type
- Improves template flexibility for different network device configurations

* refactor(topology): use node-pair IP format and hyphenated naming

- Use 10.0.{node_pair}.x format for P2P links (e.g., 10.0.12.x for R-1-R-2)
- Change node naming to hyphenated format: R-1, R-2, SW-1, PC-1
- Use {short_name} as placeholder for port names in output template
- Remove unused IP_SUBNET_POOL constant
- Simplify ip_planning rules to intuitive format description

* fix(web_wireshark): raise minimum Docker API version to 1.44

Docker daemon requires API version 1.44+, so the minimum
supported version should match rather than defaulting to 1.40.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(web_wireshark): call ensure_network in start_wireshark_session

Ensure Docker network exists before creating container, so that
Web Wireshark works when started via API without going through CLI.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(agent): improve Docker image setup with network error detection

- Add `is_network_error()` function to detect network-related failures in Docker pull output
- Modify `pull_image()` to capture output and return success status along with output
- Enhance main logic to detect network errors and skip local build when Docker Hub is inaccessible
- Provide helpful suggestions for network issues (Docker mirror, VPN, manual image transfer)
- Improve error messages to differentiate between network failures and other errors

* feat(docs): add Ubuntu 24.04 development setup guide

Add a comprehensive development environment setup guide for Ubuntu 24.04. The guide includes steps to install dependencies via PPA, configure Docker with mirror accelerators for users in mainland China, set up user permissions, and run the server from source with a Python virtual environment. This provides a clear, step-by-step reference for new contributors and developers.

* feat(docs): add pip mirror note for China mainland users

Add a comment in the development setup documentation suggesting the use of the Aliyun PyPI mirror for users in China mainland to improve installation speed and reliability. This helps overcome network restrictions and slow downloads from the default PyPI repository.

* feat(docs): add LVM root partition expansion guide

Add optional section to development setup documentation with instructions for expanding the root partition when using LVM. This helps developers resolve low disk space issues by utilizing unallocated space in the volume group. The guide includes commands to check LVM status, extend the logical volume, and verify the changes.

* feat(docs): add tshark to development setup dependencies

Add tshark to the apt install command in the development setup documentation. Tshark is required for packet capture functionality in GNS3, ensuring the development environment has all necessary tools for network analysis and debugging.

* feat: add GNS3 documentation skill with standardized structure

Add new documentation skill file defining standards for GNS3 technical documentation. The skill establishes a structured approach focusing on architecture diagrams, flow diagrams, and text descriptions while prohibiting code examples and user scenarios. This ensures consistent, high-quality documentation across the GNS3 ecosystem.

* feat(docs): update documentation skill to focus on server technical docs

Update the GNS3 documentation skill to specifically target server technical documentation under the docs/ directory. The revised standard emphasizes high-level understanding over implementation details, using ASCII diagrams for architecture and business processes, API endpoint tables, and measured performance data. Code specifics are intentionally omitted, directing readers to the codebase for implementation details.

* feat(docs): rewrite documentation skill and statistics API doc

- Rewrite gns3-documentation skill to match actual server-side doc style:
  focus on architecture/flow diagrams, API data, skip code details
- Switch diagram standard from ASCII to Mermaid (GitHub native rendering)
- Rewrite statistics-api.md with Mermaid architecture and sequence diagrams,
  add missing webwireshark container fields (memory_limit, cpu_limit, pids_limit),
  remove speculative content

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(docs): update VNC WebSocket console documentation with Mermaid diagrams

- Replace ASCII diagrams with Mermaid flowcharts for better visualization
- Clarify connection flow between browser, controller, compute, and VNC server
- Update authentication details and endpoint descriptions
- Add missing documentation for packet capture workflow
- Improve overall readability and maintainability

* docs: add AI disclaimer to documentation files

Add a standardized disclaimer to multiple documentation files indicating that the content has been organized by AI with reference to actual code. The disclaimer warns users that AI can make mistakes and advises verification against the source code when in doubt. This improves transparency about the documentation's origin and encourages careful usage.

* feat(docs): update chat API documentation with new features and clarifications

- Update title from "Design Document" to reflect current implementation status
- Add new features: session abort, copilot modes (teaching_assistant, lab_automation_assistant), session pinning
- Enhance architecture diagram with LangGraph StateGraph details including abort_handler_node, title_generator_node, and conditional edges
- Clarify statistics tracking: add ai_response_counted flag, filter title_generator_node from LLM counts, explain incremental token counting
- Improve documentation accuracy for real-time statistics collection and token calculation methods

* feat(docs): restructure command security documentation with visual workflows

- Replace verbose implementation details with concise architecture overview
- Add Mermaid diagrams to visualize command filtering and multi-line expansion flows
- Simplify configuration instructions and remove redundant examples
- Consolidate file structure and function reference tables for clarity
- Maintain all security principles while improving readability and maintainability

* feat(context): refactor context window management documentation for clarity

- Reorganize documentation with improved structure and visual diagrams
- Add Mermaid diagrams to illustrate architecture and trimming process
- Simplify content while maintaining technical accuracy
- Update token counting and trimming strategy explanations
- Enhance readability with better formatting and component tables

* feat(docs): update LLM model configs documentation

- Change config column type from JSONB to JSON (JSONB on PostgreSQL)
- Update provider table to mark base_url as required with planned optional status
- Add note about base_url being currently required in API schema
- Clarify GET own configs endpoint returns plain array
- Add copilot_mode field to update request schema
- Document update limitations for context_strategy and copilot_mode fields

* feat(docs): add GNS3StartNodeQuickTool and update node creation examples

- Add documentation for new `GNS3StartNodeQuickTool` (`start_gns3_node_quick`) that starts nodes without waiting for boot completion
- Update node creation example to include optional `name` field in template placement
- Clarify dynamic wait time strategy for `GNS3StartNodeTool` and contrast with quick tool
- Update tool file structure to reflect new configuration, display, and packet capture tools
- Fix truncated line in suspend tool documentation

* feat(docs): add comprehensive documentation structure with CC BY-SA 4.0 license

Add initial documentation directory with detailed README.md that outlines:
- Dual license structure (CC BY-SA 4.0 for docs, GPLv3 for code)
- Complete directory structure for features, AI Copilot, and bugs
- Feature documentation covering Controller+Compute setup, Statistics API, VNC WebSocket console, and Web Wireshark
- AI Copilot implemented features including Chat API, LLM model configs, command security, and multi-vendor device support

This provides organized technical documentation for the GNS3 server project with proper licensing and feature coverage.

* docs: update multi-vendor device support documentation

- Simplify vendor support table by removing redundant platform column
- Add VPCS as a simulator in status column
- Improve VPCS driver diagram with Mermaid syntax and detailed components
- Document VPCS-specific Netmiko parameters (fast_cli, global_delay_factor)
- Update VPCS tool usage example with connection options structure
- Remove outdated Nornir configuration approaches, reference current implementation
- Add file reference for VPCS tools location
- Clean up documentation structure for better readability

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: YueGuobin <yueguobin@gmail.com>
Co-authored-by: Jeremy Grossmann <grossmj@gns3.net>
2026-04-20 22:56:55 +08:00
arl1984 de0d050689 Fix telnet console silent-proxy hang on non-ConnectionError exit (#2344)
The run() cleanup block was guarded by `except (ConnectionError, OSError):`,
so exits via asyncio.CancelledError or any other exception type skipped
cleanup. Result: `_reader_process` stays pinned to the dead reader and
`_get_reader()` returns None for every subsequent client — the silent-proxy
symptom described in #2344.

Convert the except block to try/finally so cleanup always runs, regardless
of how `_process()` exits. Also:
- catch asyncio.CancelledError + generic Exception (with log.exception) so
  unexpected failures don't swallow the cleanup
- reset `_current_read = None` after cancellation
- use `dict.pop(..., None)` instead of `del` to avoid KeyError races if
  the broadcast loop's timeout handler already removed the entry

Triggering pattern observed in practice: a diagnostic tool opens a console,
sends a few commands, and closes abruptly (e.g. from a test harness or
orchestration script that cancels its Task). If the `_process()` task was
awaiting on one of the `network_read` / `reader_read` futures at the time
of cancellation, the CancelledError propagates up through `run()` and
bypasses the ConnectionError-only except clause. The proxy accepts future
connections (the listen socket is still alive) but never forwards any data
because `_reader_process` never got reset.

Validated against gns3/gns3-server:latest (2.2.56.1) running a 10-scenario
sequential regression batch that previously hung reliably on the 4th
sp_v1 / L3VPN scenario and now completes cleanly across all 10.
2026-04-16 14:46:49 +00:00
grossmj 80cc85e5d5 Fix exception when custom adapters is not set 2026-04-15 14:17:12 +08:00
grossmj 737a174ae5 Merge branch '2.2' into 3.0
# Conflicts:
#	gns3server/controller/project.py
#	gns3server/crash_report.py
#	gns3server/version.py
2026-04-13 11:45:26 +08:00
Jeremy Grossmann d59709071a Merge pull request #2668 from GNS3/release/v2.2.58.1
Release v2.2.58.1
2026-04-12 21:18:23 +08:00
grossmj ae3ae46151 Development on 2.2.59.dev2 2026-04-12 21:17:17 +08:00
grossmj 58fc6a8478 Release v2.2.58.1 2026-04-12 20:59:20 +08:00
grossmj d9b8d0d1ff Sync appliances 2026-04-12 20:49:56 +08:00
grossmj 2b0b31b402 Merge branch 'master' into 2.2 2026-04-12 20:47:14 +08:00
grossmj 66ce3ec280 Fix bug when custom_adapters is None in port_factory.py 2026-04-12 14:05:56 +08:00
grossmj a040acfaa5 Have optional body in start node API endpoint 2026-04-12 14:04:04 +08:00
grossmj 9c988b34d0 Fix snapshots after merging 2026-04-11 19:54:49 +08:00
grossmj 0d3fad8c8f Merge branch '2.2' into 3.0
# Conflicts:
#	gns3server/controller/__init__.py
#	gns3server/controller/export_project.py
#	gns3server/controller/project.py
#	gns3server/controller/snapshot.py
#	gns3server/crash_report.py
#	gns3server/schemas/snapshot.py
#	gns3server/static/web-ui/26.34a83d9cee7db39cd0de.js
#	gns3server/static/web-ui/index.html
#	gns3server/static/web-ui/main.d74d38241f0602d1b3e0.js
#	gns3server/version.py
#	gns3server/web/route.py
#	tests/handlers/api/controller/test_project.py
#	tests/handlers/api/controller/test_snapshot.py
2026-04-11 19:22:05 +08:00
grossmj 4a47151526 Development on 2.2.59.dev1 2026-04-11 18:05:54 +08:00
Jeremy Grossmann adeec10188 Merge pull request #2667 from GNS3/release/v2.2.58
Release v2.2.58
2026-04-11 17:42:38 +08:00
Jeremy Grossmann e747deae88 Merge branch 'master' into release/v2.2.58 2026-04-11 17:37:31 +08:00
Jeremy GrossmannandCopilot Autofix powered by AI 264fffbc6c Potential fix for pull request finding 'CodeQL / Information exposure through an exception'
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-04-11 17:34:53 +08:00
grossmj a295d653b8 Release v2.2.58 2026-04-10 20:36:01 +08:00
grossmj c6eec799fb Remove old files 2026-04-10 20:27:46 +08:00
grossmj 8503840307 Bundle web-ui v2.2.58 2026-04-10 20:24:16 +08:00
grossmj c4dbecc1ea Sync appliances 2026-04-10 20:11:16 +08:00
Jeremy Grossmann 3d71967983 Merge pull request #2665 from GNS3/refector-snapshots
Snapshot refactoring
2026-04-10 20:01:45 +08:00
grossmj 161e016594 Remove log message 2026-04-10 19:58:55 +08:00
grossmj 82f795c9ee Add some additional tests 2026-04-10 19:50:42 +08:00
grossmj 2670c68467 Last adjustments for import/export 2026-04-10 18:58:21 +08:00
grossmj 6f7730c455 Update snapshots when duplicating a project 2026-04-09 23:18:55 +08:00
grossmj 274cef6cf5 Add description for snapshots 2026-04-09 20:25:44 +08:00
grossmj fbea9b655d Fix issue when restoring a snapshot of a duplicated project 2026-04-08 22:16:47 +08:00
grossmj 6869f2d71d Snapshot refactoring 2026-04-08 20:02:01 +08:00
Jeremy Grossmann da5a1e9172 Merge pull request #2664 from yueguobin/fix/symbol-cors-headers
Fix/symbol cors headers
2026-04-07 22:27:47 +08:00
YueGuobin 8ab3243c79 fix(symbols): add authentication to symbol raw endpoint
Enable Symbol.Audit privilege requirement for the symbol file download
endpoint. This was previously disabled as a workaround for a web-ui bug.
2026-04-07 20:56:20 +08:00
YueGuobin 8041d2906c fix(symbols): add CORS headers to symbol file responses
FileResponse does not properly include CORS headers when served from
a different origin. This fix manually adds the Access-Control-Allow-Origin
header based on the request origin.

Fixes CORS policy errors when accessing symbol files from frontend
applications running on localhost:4200 or other origins.
2026-04-07 20:22:15 +08:00
Jeremy Grossmann ae8ef84668 Merge pull request #2663 from cristian-ciobanu/project-monitoring
Enhancement: Refresh projects list without restarting the GNS3 server
2026-04-07 18:09:29 +08:00
grossmj 5b04fd0336 Allow to find new project in sub dirs 2026-04-07 18:05:32 +08:00
Jeremy GrossmannandCopilot de8abc0af0 Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-07 17:37:34 +08:00
Jeremy GrossmannandCopilot 725cd0428c Apply suggestion from @Copilot
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-07 17:35:33 +08:00
Jeremy Grossmann fdbb7bb70f Merge branch '3.0' into project-monitoring 2026-04-07 15:10:42 +08:00
grossmj e86a05a2ef Fix tests 2026-04-07 15:09:10 +08:00
Jeremy Grossmann 2ce7662c71 Merge branch '3.0' into project-monitoring 2026-04-07 12:58:56 +08:00
Cristi 104f56cb55 Enhancement: Refresh projects list without restarting the GNS3 server 2026-04-07 00:21:56 +03:00
grossmj b4edfdb063 Merge branch '2.2' into 3.0
# Conflicts:
#	gns3server/appliances/infix.gns3a
#	gns3server/appliances/juniper-vJunos-router.gns3a
#	gns3server/controller/ports/port.py
#	gns3server/crash_report.py
#	gns3server/utils/asyncio/telnet_server.py
#	gns3server/version.py
2026-04-06 23:36:03 +08:00
Jeremy Grossmann 2e1db7de6f Merge pull request #2662 from UmmmAGoodName/3.0
Fix addressing issue #2005 including tests
2026-04-06 20:10:47 +08:00
grossmj d97aedb625 Fix tests 2026-04-06 20:03:38 +08:00
grossmj b07685666b Regenerate DB migration script 2026-04-06 19:55:11 +08:00
grossmj b1852f7bcf Fix accessing username in authentication.py 2026-04-06 19:37:17 +08:00
UmmmAGoodName 4cf8b79692 Fix addressing issue #2005 including tests 2026-04-05 21:51:52 +02:00
Jeremy Grossmann e871a1aed6 Merge pull request #2661 from GNS3/revert-2660-backport-telnetlib3
Revert "Backport telnetlib3 changes"
2026-04-05 22:02:05 +08:00
Jeremy Grossmann b222fba42c Revert "Backport telnetlib3 changes" 2026-04-05 21:58:21 +08:00
Jeremy Grossmann f9957b1d90 Merge pull request #2660 from GNS3/backport-telnetlib3
Backport telnetlib3 changes
2026-04-05 21:08:43 +08:00
grossmj bc6374f7fc Add keepalive mechanism using the NOP command 2026-04-05 13:30:38 +08:00
Cristi c739a16d70 Improved exception handling and telnet client disconnect 2026-04-05 13:29:35 +08:00
Cristi 7684ce60ce Backport: Re-write current Telnet server implementation using telnetlib3 library 2026-04-05 13:29:25 +08:00
Jeremy Grossmann 1d10bda22e Merge pull request #2659 from GNS3/appliance-v8
Add support for appliance format version 8
2026-04-04 20:14:23 +08:00
grossmj 51eb88ead1 Use get method for registry_version to avoid KeyError 2026-04-04 20:09:31 +08:00
grossmj 630c2d811d Add support for appliance format version 8 2026-04-04 20:04:42 +08:00
grossmj ef546a46f9 Sync appliances 2026-04-04 19:55:13 +08:00
Jeremy Grossmann 9290b37292 Merge pull request #2654 from yueguobin/feature/extended-statistics
Feature/extended statistics
2026-04-03 21:43:50 +08:00
Guobin Yue 2a11ab6ba3 Merge branch '3.0' into feature/extended-statistics 2026-04-03 21:39:38 +08:00
Jeremy Grossmann 55fa7bb10c Merge pull request #2658 from GNS3/convert-db-fields-to-json
Convert database template fields from PickleType to JSON
2026-04-03 21:06:29 +08:00
grossmj 1dc31127d9 Convert database template fields from PickleType to JSON 2026-04-03 20:59:57 +08:00
Jeremy Grossmann d9f12366bc Merge branch '3.0' into feature/extended-statistics 2026-04-01 12:54:54 +08:00
YueGuobinandClaude Opus 4.6 050b7a80ab docs: add Controller + Compute setup guide
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-01 02:08:18 +08:00
Jeremy Grossmann c9f4f7983b Merge pull request #2645 from cristian-ciobanu/telnetlib3
Enhancement: Re-write current Telnet server implementation using telnetlib3 library
2026-03-31 20:22:59 +08:00
grossmj 0b6f17cf8e Add keepalive mechanism using the NOP command 2026-03-31 18:30:59 +08:00
grossmj 38ebaaa90a Remove requests dependency from dev-requirements.txt 2026-03-31 17:30:41 +08:00
grossmj 9a06830f88 telnetlib3 is a shared dependency with AI Copilot 2026-03-31 17:22:34 +08:00
Jeremy Grossmann bebf070e4d Merge branch '3.0' into telnetlib3 2026-03-31 14:33:35 +08:00
Guobin Yue 02dc2b9a41 Merge branch '3.0' into feature/extended-statistics 2026-03-30 22:48:39 +08:00
Jeremy Grossmann d40e292047 Merge pull request #2655 from yueguobin/fix/device-type-error-message
fix(copilot): improve device_type error message with tested types and…
2026-03-30 14:42:14 +08:00
YueGuobin 4cd74901a5 fix(copilot): improve device_type error message with tested types and config instructions
Add tested device types (cisco_ios_telnet, gns3_huawei_telnet_ce, gns3_ruijie_telnet)
to the error message and include Web UI configuration path.
2026-03-30 14:09:36 +08:00
YueGuobin d64e4e28e3 docs: add future optimization for per-compute node statistics 2026-03-30 00:23:35 +08:00
YueGuobin b379747aeb docs: add statistics API documentation
Document the extended /statistics endpoint with complete
response schema and field descriptions.
2026-03-30 00:09:09 +08:00
YueGuobin 33fdfd65ba feat(statistics): distinguish open vs closed project nodes
Closed project nodes don't have status info in topology JSON.
Add open_project_nodes and closed_project_nodes counts to
help clarify why by_status may be empty.
2026-03-30 00:06:50 +08:00
YueGuobin b4caffe13b fix(statistics): handle closed projects where nodes/links are dicts
Open projects store Node/Link objects, but closed projects store
dictionaries loaded from topology JSON. This fix checks the type
before accessing attributes.
2026-03-29 23:59:17 +08:00
YueGuobin 8b4c3a3517 feat(controller): extend /statistics API with project, node and link stats
Return aggregated statistics:
- computes: per-compute CPU/memory/disk stats (existing)
- projects: total, opened, closed counts
- nodes: total count with breakdown by type and status
- links: total count with capturing count
2026-03-29 23:49:36 +08:00
Jeremy Grossmann 3dbae9585c Merge pull request #2652 from GNS3/fix/2651
Use FastAPI Lifespan Events
2026-03-28 10:02:41 +08:00
grossmj 46f77eb7d5 Remove old add_event_handler 2026-03-28 09:59:29 +08:00
grossmj 01a68fb23a Use FastAPI Lifespan Events 2026-03-28 09:54:22 +08:00
Jeremy Grossmann 89d665f22b Merge pull request #2650 from yueguobin/feature/control-offset
feat(link): add control_offset field to LinkStyle
2026-03-28 08:08:10 +08:00
YueGuobin 7f9416a070 feat(link): add control_offset field to LinkStyle 2026-03-28 02:11:30 +08:00
grossmj b8764b29a5 Upgrade FastAPI to v0.135.2 2026-03-27 10:57:59 +08:00
Jeremy Grossmann 3b261ebbfc Merge pull request #2646 from yueguobin/feature/symbol-delete-api
feat(symbols): add DELETE API for removing custom symbol files
2026-03-27 10:51:51 +08:00
YueGuobin e651ad589b feat(symbols): add DELETE API for removing custom symbol files
- Add DELETE /v3/symbols/{symbol_id:path} endpoint
- Prevent deletion of built-in symbols (:/ prefix or in resource directory)
- Clear symbol size cache after deletion
- Require Symbol.Allocate privilege
2026-03-27 02:28:27 +08:00
Cristi 7f3468dcd3 Improved exception handling and telnet client disconnect 2026-03-24 15:23:00 +02:00
Cristi 83558d4d9f Enhancement: Re-write current Telnet server implementation using telnetlib3 library 2026-03-24 13:23:45 +02:00
Jeremy Grossmann 4701712a86 Merge pull request #2644 from GNS3/release/v2.2.57
Release v2.2.57
2026-03-24 10:10:22 +08:00
grossmj e5ff9e7f00 Development on 2.2.58.dev1 2026-03-24 08:35:49 +08:00
grossmj 7adb0c5226 Release v2.2.57 2026-03-23 09:45:46 +08:00
grossmj 667833dda5 Merge remote-tracking branch 'origin/master' into 2.2 2026-03-23 09:38:13 +08:00
grossmj 646ff00ade Sync appliances 2026-03-23 09:37:15 +08:00
Jeremy Grossmann 77bea35298 Merge pull request #2641 from cristian-ciobanu/3.0
Enhancement Added link type support on the server side
2026-03-20 13:15:03 +08:00
Jeremy Grossmann 53051dd481 Merge pull request #2631 from yueguobin/feature/ai-copilot-bridge
feature/ai-copilot-bridge Branch Summary
2026-03-20 13:05:50 +08:00
YueGuobin 77a38cef03 docs: clarify system scope - baseline config with tool handoff
Clarify the positioning of the template-based system:

Scope (0 → 1):
- Topology provisioning (nodes + links)
- Baseline configuration (IP, routing protocols)
- Management access setup (SSH/HTTPS/NETCONF)
- Basic security configuration

Handoff to Production Tools (1 → N):
- Terraform (Infrastructure as Code)
- REST API (modern device management)
- NETCONF/YANG (standardized configuration)
- Network Controllers (SDN, APIC, etc.)

This clarifies that:
1. The system focuses on rapid environment preparation
2. It complements rather than replaces production tools
3. It's ideal for labs, testing, training, and initial setup
4. Advanced config management is handled by specialized tools
2026-03-20 10:00:23 +08:00
YueGuobin 76c84798dc docs: refactor roadmap - reduce code, add comprehensive diagrams
Major documentation improvements:

Reduced Code Content (~60% reduction):
- Simplified Core Components section with concept-focused descriptions
- Condensed Large-Scale Topology section (kept concepts, removed implementation)
- Streamlined Node Creation Templates (kept workflows, removed tool code)
- Simplified Technical Considerations (kept diagrams, removed code)
- Streamlined Testing Strategy (kept test cases, removed test code)

Added Comprehensive Diagrams:
- System Architecture Overview (4-layer architecture)
- HITL State Transition Diagram (complete workflow with interrupts)
- REST API Endpoints (6 new endpoints with request/response formats)
- SSE Progress Stream (real-time event types)
- Data Flow Diagram (7-step process from user to results)
- Error Handling Flow (4 error types with recovery strategies)
- Template Lifecycle Management (5 stages from DRAFT to ARCHIVED)
- Automatic Layout Strategies (4 layout types with visual examples)
- Auto-Linking Strategies (4 link pattern types with diagrams)
- Security Considerations (3-layer validation approach)
- Error Categories (4 error types with recovery flows)
- Testing Strategy (unit, integration, E2E test scenarios)

Benefits:
- Easier to understand for non-technical stakeholders
- Focus on concepts and workflows rather than implementation
- Visual documentation aids comprehension
- Maintained all critical technical information
- Improved readability and structure
2026-03-20 09:54:58 +08:00
YueGuobin 382b2aefa9 docs: add link creation templates section to roadmap
Add comprehensive link creation templates documentation covering:
- Batch link creation workflow with HITL confirmations
- Link template schema with pattern-based connectivity
- Common topology patterns (Spine-Leaf, Ring, Mesh, Star, Three-tier)
- Intelligent port allocation strategies (round-robin, optimized)
- Performance benchmarks showing 99.9% token savings for large topologies
- Complete workflow example combining all three template systems
2026-03-20 09:44:03 +08:00
YueGuobin 3b4bc93e85 docs: add node creation templates section to roadmap
Added comprehensive node creation template system including:
- Batch node creation workflow (HITL with preview)
- Node template schema (groups, positioning, auto-linking)
- Automatic positioning algorithms (grid, spine-leaf, hierarchical)
- Auto-linking strategies (mesh, paired, linear)
- Batch parallel execution (20-50 concurrent)
- Performance benchmarks for 100-1000+ nodes
- Complete enterprise data center example (724 nodes, 4280 links)

Key benefits:
- 98% token savings for node creation (5000 → 100 tokens for 100 nodes)
- 90% time savings (10 min → 1 min for 100 nodes)
- Auto-linking eliminates manual connection setup
- Combined workflow: Create + configure 724 nodes in ~10 minutes

Updated implementation phases to include Phase 2.5 for node creation templates.
2026-03-20 09:35:45 +08:00
YueGuobin a627d45ca6 docs: add large-scale topology support (1000+ nodes) to roadmap
Added comprehensive section on large-scale topology support including:
- Direct execution mode (skip AI, use rule engine)
- Batch parallel execution (50-100 concurrent)
- Intelligent parameter generation (0 token cost)
- Real-time progress streaming
- Configuration summary generation
- Performance benchmarks for 1000+ nodes
- Multiple addressing schemes (sequential, VLAN-based, hierarchical)

Key benefits:
- 99.5% token savings for 1000 devices (150K → 400 tokens)
- 88% time savings (50 min → 3-5 min)
- Enables rapid provisioning of training labs, CI/CD testing, disaster recovery drills

Updated implementation phases to reflect large-scale support priorities.
2026-03-20 09:26:45 +08:00
YueGuobin 5c42a59413 docs: add template-based configuration roadmap with HITL workflow
Add comprehensive roadmap for implementing Jinja2 template-based
configuration with Human-in-the-Loop confirmations.

Key features:
- Three-step HITL workflow (Template → Parameters → Execute)
- 70-80% token savings for multi-device configurations
- Enhanced safety through human review at each step
- Template reusability across projects

Implementation plan:
- Phase 1: Core MVP (3-5 days)
- Phase 2: UX Enhancement (2-3 days)
- Phase 3: Template Library (2-3 days)
- Phase 4: Advanced Features (3-4 days)
2026-03-20 01:18:56 +08:00
YueGuobin 1378e3b5ec docs: add supported providers list and future enhancements
Add comprehensive documentation for LLM model providers:
- Provider list with default base URLs and requirements
- Examples for different providers (OpenAI, Anthropic, Ollama, Azure)
- Guidelines on when to specify base_url
- Future enhancements section for optional base_url field
2026-03-19 10:12:21 +08:00
YueGuobin 01d24403d3 feat: improve error handling for API configuration errors
Add error_handler utility to detect and format HTML error responses
from misconfigured API base URLs. When the API returns HTML (indicating
configuration issues), users now see a helpful message instead of raw
HTML content.
2026-03-19 00:46:49 +08:00
grossmj c5325fdee4 Install ai-copilot in testing.yml 2026-03-18 16:17:07 +08:00
grossmj 333386ac8b Use status.HTTP_501_NOT_IMPLEMENTED from FastAPI 2026-03-18 16:08:47 +08:00
YueGuobin cd1d28729a feat: make AI Copilot an optional dependency
This change makes AI Copilot features optional to reduce installation
size and support restricted environments.

Changes:
- Split AI dependencies into ai-requirements.txt
- Add ai-copilot optional dependency in pyproject.toml
- Add import protection in gns3server/agent/__init__.py
- Return 501 for AI endpoints when dependencies not installed
- Add gns3server-uninstall-ai-copilot command for cleanup
- Update README with installation and uninstallation instructions

Installation:
- Basic: pip install gns3-server
- With AI: pip install gns3-server[ai-copilot]
- Development: pip install gns3-server[ai-copilot,dev]

Uninstallation:
- gns3server-uninstall-ai-copilot
2026-03-18 15:21:23 +08:00
YueGuobin 0b741dd834 test: simplify class registration assertions in custom netmiko tests
Refactored test assertions for Huawei CE, Ruijie, and VPCS telnet drivers to compare only class names instead of full module paths. This change reduces test brittleness when classes are imported via different module paths while maintaining validation of correct class registration in CLASS_MAPPER and CLASS_MAPPER_BASE.
2026-03-17 22:45:02 +08:00
YueGuobin 55c7d249fb feat(tests): improve class comparison in custom netmiko tests
Refactor test assertions to compare classes by module and name instead of direct object comparison. This ensures tests remain reliable when classes are imported via different paths, preventing false failures due to import variations. Changes applied to Huawei CE, Ruijie, and VPCS telnet driver tests.
2026-03-17 22:33:28 +08:00
YueGuobin e1f25ce63b fix(tests): replace assertIs with assertEqual in custom netmiko tests
Changed test assertions from `assertIs` to `assertEqual` for class mapper comparisons in Huawei CE, Ruijie, and VPCS telnet driver tests. This ensures proper equality checking rather than identity checking, which is more appropriate for class comparisons in these test cases.
2026-03-17 22:06:53 +08:00
YueGuobin 2557614ba8 refactor(llm-configs):
remove unused reserved_jsonb fields

   Remove the three reserved JSONB fields (reserved_jsonb_1, reserved_jsonb_2, reserved_jsonb_3) from the llm_model_configs
   table. These fields were planned for future use but are no longer needed.
2026-03-17 21:43:48 +08:00
Cristi de1b539fb6 Enhancement Added link type support on the server side 2026-03-17 15:29:58 +02:00
YueGuobin a240620443 fix(custom_netmiko): use
assertIs instead of assertEqual for class comparison

   Fix test failures in custom Netmiko driver tests by using assertIs instead
   of assertEqual when comparing class objects registered in CLASS_MAPPER.

   The issue occurred because test files add project root to sys.path, allowing
   the same module to be imported with different paths (e.g., gns3_copilot...
   vs gns3server.agent.gns3_copilot...). assertEqual compares class __module__
   attributes which differ based on import path, while assertIs checks object
   identity which correctly identifies them as the same class.

   Modified files:
   - test_huawei_ce.py
   - test_ruijie_telnet.py
   - test_vpcs_telnet.py
2026-03-17 21:24:39 +08:00
YueGuobin bd06d3a08e feat(vpcs_tools_netmiko): update Nornir import to use core module
Update the import statement for Nornir from `nornir.core.nornir` to `nornir.core` to align with the latest Nornir library structure and avoid potential import errors. This ensures compatibility with updated Nornir versions.
2026-03-17 21:16:15 +08:00
YueGuobin a2a52c8a7d feat(vpcs_tools_netmiko): import Nornir class for type hints
Add import of Nornir class from nornir.core.nornir to support type annotations and improve code clarity in the VPCS tools module.
2026-03-17 16:31:44 +08:00
Jeremy Grossmann 8f325b4127 Merge branch '3.0' into feature/ai-copilot-bridge 2026-03-17 13:41:21 +08:00
grossmj cb18b60c5d Ignore HTTPException received when closing a project 2026-03-17 13:23:19 +08:00
Jeremy Grossmann 0d1341b4e0 Merge pull request #2640 from UmmmAGoodName/Dymamips_fix-3.0
Fixed issue #1605 regarding Cisco slots causing configs to break
2026-03-17 12:54:45 +08:00
grossmj 4f863f3767 Fix typo 2026-03-17 12:51:36 +08:00
grossmj 0aa6566e50 Prevent router to be duplicated when running and add tests 2026-03-17 12:49:38 +08:00
UmmmAGoodName 95bd76a212 Fixed issue #1605 regarding Cisco slots causing configs to break 2026-03-16 19:09:32 +01:00
YueGuobinandClaude Sonnet 4.5 a2c1a913ca docs: add VNC WebSocket console documentation
Add comprehensive documentation for VNC WebSocket console support in GNS3.

Topics covered:
- Architecture and connection flow
- API endpoints (Controller and Compute)
- WebSocket data forwarding implementation
- Supported node types (QEMU and Docker)
- Authentication and authorization
- Configuration examples
- Troubleshooting guide
- Performance considerations
- Security best practices
- Comparison with SPICE

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-17 01:28:52 +08:00
YueGuobinandClaude Sonnet 4.5 64d3c02d42 refactor(compute): remove SPICE WebSocket console support
Remove all SPICE WebSocket-related code due to frontend dependency issues
with spice-html5 library (missing RSAKey/BigInteger implementations).

Changes:
- Remove start_spice_websocket_console() from BaseNode
- Remove SPICE WebSocket endpoints from QEMU and Docker compute APIs
- Remove SPICE WebSocket proxy endpoint from controller API
- Remove WebSocket subprotocol handling from authentication layers
- Remove SPICE documentation

The SPICE console type remains functional for direct connections,
but WebSocket proxy support has been removed.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-17 01:15:26 +08:00
YueGuobin c98f802362 feat(compute): add SPICE WebSocket console support
Add WebSocket-based console support for SPICE protocol, enabling
   browser-based graphical console access with enhanced features
   like clipboard sharing, USB redirection, and audio streaming.

   Changes:
   - Add start_spice_websocket_console() method in BaseNode for SPICE
     WebSocket to TCP bridging with bidirectional binary forwarding
   - Add /console/spice WebSocket endpoints in QEMU and Docker compute APIs
   - Add /console/spice WebSocket proxy endpoint in controller API
   - Add comprehensive API documentation in docs/features/

   Supported console types:
   - spice: Basic SPICE protocol support
   - spice+agent: SPICE with spice-vdagent for enhanced features

   Architecture:
   - Browser WebSocket → Controller (JWT + RBAC) → Compute (Basic Auth)
   - No external websockify processes required
   - Consistent with existing VNC WebSocket implementation
2026-03-16 22:21:25 +08:00
YueGuobinandClaude Sonnet 4.5 ba92b405da feat: add VNC WebSocket console support for Docker and QEMU nodes
Add VNC console WebSocket endpoints for Docker and QEMU nodes:
- Add /console/vnc WebSocket endpoint to compute API (Docker & QEMU)
- Add /console/vnc WebSocket endpoint to controller API
- Implement start_vnc_websocket_console() in BaseNode
- Forward VNC WebSocket traffic between controller and compute layers

The implementation provides bidirectional WebSocket to TCP forwarding
for VNC protocol (RFB) connections, allowing browser-based VNC console
access to containers and VMs.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-16 16:40:00 +08:00
Guobin Yue 09aa12cf94 Merge branch '3.0' into feature/ai-copilot-bridge 2026-03-15 23:13:15 +08:00
YueGuobin ffcfa4ccb1 feat(telnet_server): improve error handling and connection management
- Catch OSError alongside ConnectionError in connection processing to handle more network errors
- Move client_info retrieval inside try block to prevent AttributeError on failed connections
- Replace bare except with specific exceptions (OSError, ConnectionError, asyncio.TimeoutError)
- Improve error logging to include specific exception details and client information
2026-03-15 23:07:06 +08:00
Jeremy Grossmann 6ac4c27bc1 Merge pull request #2639 from yueguobin/fix/telnet-server-connection-race-condition-3.0
Fix/telnet server connection race condition 3.0
2026-03-15 23:01:57 +08:00
Jeremy Grossmann 632b3daab7 Merge pull request #2635 from yueguobin/fix/iou-suspend-405
fix(iou): return 405 error for unsupported suspend operation
2026-03-15 22:47:42 +08:00
grossmj 6e7738a14f Return 405 error for unsupported actions for other node types 2026-03-15 22:38:51 +08:00
YueGuobin b71b323fd4 feat(agent): improve tiktoken initialization and device registration
- Configure tiktoken cache directory to isolate encoding files
- Add logging and timing for tiktoken initialization process
- Make Huawei CE and Ruijie Telnet device registration idempotent
- Add duplicate registration prevention with global flags
- Add logging for device type registration status
- Update .gitignore to exclude tiktoken cache files
2026-03-15 21:25:14 +08:00
YueGuobin 9a01e2194e chore: remove telnet race condition test files and documentation
Remove the bug report documentation and stress test files for the telnet server connection race condition issue.
2026-03-15 13:40:34 +08:00
YueGuobin 4f8daced17 Merge branch 'fix/telnet-server-connection-race-condition-3.0' into feature/ai-copilot-bridge 2026-03-15 13:38:40 +08:00
Guobin Yue 08b579ff83 Merge branch '3.0' into fix/telnet-server-connection-race-condition-3.0 2026-03-15 01:17:30 +08:00
Guobin Yue 9aa3f3b7a0 Merge branch '3.0' into feature/ai-copilot-bridge 2026-03-15 00:37:17 +08:00
YueGuobin 1aced27dc1 feat(docs): add telnet server connection race condition bug report
Add detailed bug report documenting a race condition in the telnet server's broadcast logic. The bug occurs when a client disconnects while the server is iterating through connections to broadcast data, causing an uncaught OSError from getpeername() call.

Key details included:
- Error logs showing OSError: [Errno 107] Transport endpoint is not connected
- Architecture diagram illustrating the telnet proxy server setup
- Root cause analysis showing the race condition timeline
- Problematic code location in telnet_server.py line 305
- Exception hierarchy explanation showing why OSError isn't caught
- Impact assessment and proposed solutions

This documentation will help track and resolve the issue where client disconnections during broadcast cause unhandled exceptions.
2026-03-15 00:19:51 +08:00
YueGuobin cda5fdd94b feat(telnet_server): improve error handling and connection management
- Catch OSError alongside ConnectionError in connection processing to handle more network errors
- Move client_info retrieval inside try block to prevent AttributeError on failed connections
- Replace bare except with specific exceptions (OSError, ConnectionError, asyncio.TimeoutError)
- Improve error logging to include specific exception details and client information
2026-03-15 00:19:51 +08:00
YueGuobin e4faf673af fix(telnet): handle connection race condition during broadcast
Fixes two critical issues in telnet server when clients rapidly
   connect/disconnect during broadcast operations:

   1. **OSError [Errno 107]**: Transport endpoint not connected
      - Root cause: getpeername() called outside try block
      - Fix: Move getpeername() inside try block and catch OSError
      - Expand exception handling to include OSError and TimeoutError

   2. **KeyError**: Double deletion from connections dictionary
      - Root cause: Connection deleted in broadcast loop, then deleted
        again in top-level exception handler
      - Fix: Use dict.pop(key, None) instead of del dict[key]

   **Changes**:
   - Line 216: Add OSError to top-level exception handler
   - Line 227-228: Use pop() to avoid KeyError on double deletion
   - Line 305-316: Move getpeername() inside try block, expand
     exception types, use pop() for safe deletion

   **Impact**:
   - Prevents unhandled exceptions from propagating to asyncio event loop
   - Ensures proper resource cleanup even with race conditions
   - No resource leaks or zombie connections
   - Long-lived clients unaffected by rapid client disconnects

   **Test Script**:
   - Added stress test script to reproduce the issue
   - Supports IOU-L3, VPCS, and generic device types
   - Rapid clients send broadcast-triggering commands (show/run/OSPF)

   **Related**: Fixes bug documented in docs/bugs/telnet-server-connection-race-condition.md
2026-03-15 00:19:51 +08:00
Jeremy Grossmann ad784fbf6f Merge pull request #2637 from UmmmAGoodName/3.0
Minor improvements
2026-03-14 19:10:51 +08:00
Jeremy Grossmann c6be1a28ae Change first() to one_or_none() for image query 2026-03-14 19:06:27 +08:00
YueGuobin 02b20e4ff3 feat(docs): add telnet server connection race condition bug report
Add detailed bug report documenting a race condition in the telnet server's broadcast logic. The bug occurs when a client disconnects while the server is iterating through connections to broadcast data, causing an uncaught OSError from getpeername() call.

Key details included:
- Error logs showing OSError: [Errno 107] Transport endpoint is not connected
- Architecture diagram illustrating the telnet proxy server setup
- Root cause analysis showing the race condition timeline
- Problematic code location in telnet_server.py line 305
- Exception hierarchy explanation showing why OSError isn't caught
- Impact assessment and proposed solutions

This documentation will help track and resolve the issue where client disconnections during broadcast cause unhandled exceptions.
2026-03-14 15:47:36 +08:00
YueGuobin c3b18f4ce2 feat(copilot): add dynamic wait time calculation for node startup
Optimize GNS3StartNodeTool with device-type-aware wait time calculation
   to significantly reduce startup time for fast devices (VPCS, IOU).

   Changes:
   - Add NODE_STARTUP_TIME configuration
     * VPCS: 15s base + 2s per additional node
     * IOU: 25s base + 3s per additional node
     * Other devices: 120s base + 10s per additional node (conservative)

   - Add calculate_startup_time() function
     * Detects device types via node.node_type
     * Uses fast startup time if all nodes are VPCS/IOU
     * Uses conservative time if any slow device present
     * Logs selected strategy and detected types

   - Optimize GNS3StartNodeTool._run() method
     * Retrieve node info (including node_type) before starting
     * Calculate wait time based on detected device types
     * Send start commands after info retrieval
     * Use calculated wait time for progress bar
     * Reuse collected node objects for status retrieval

   Performance improvements:
   - 1 VPCS node: 140s → 15s (89% faster)
   - 5 VPCS nodes: 180s → 23s (87% faster)
   - 1 IOU node: 140s → 25s (82% faster)
   - 5 IOU nodes: 180s → 37s (79% faster)
   - Mixed VPCS/IOU: 180s → 33s (82% faster)

   Documentation:
   - Update node-control-tools.md with dynamic wait time strategy
   - Add device type comparison table
   - Document performance improvements
   - Update changelog

   Code quality:
   - All comments in English
   - flake8 check passed
   - mypy check passed
2026-03-14 15:24:27 +08:00
YueGuobin a946ef2d69 eat(copilot): add dynamic wait time calculation for node startup
Optimize GNS3StartNodeTool with device-type-aware wait time calculation
   to significantly reduce startup time for fast devices (VPCS, IOU).

   Changes:
   - Add NODE_STARTUP_TIME configuration
     * VPCS: 10s base + 2s per additional node
     * IOU: 20s base + 3s per additional node
     * Other devices: 120s base + 10s per additional node (conservative)

   - Add calculate_startup_time() function
     * Detects device types via node.node_type
     * Uses fast startup time if all nodes are VPCS/IOU
     * Uses conservative time if any slow device present
     * Logs selected strategy and detected types

   - Optimize GNS3StartNodeTool._run() method
     * Retrieve node info (including node_type) before starting
     * Calculate wait time based on detected device types
     * Send start commands after info retrieval
     * Use calculated wait time for progress bar
     * Reuse collected node objects for status retrieval

   Performance improvements:
   - 1 VPCS node: 140s → 10s (93% faster)
   - 5 VPCS nodes: 180s → 18s (90% faster)
   - 1 IOU node: 140s → 20s (86% faster)
   - 5 IOU nodes: 180s → 32s (82% faster)
   - Mixed VPCS/IOU: 180s → 28s (84% faster)

   Documentation:
   - Update node-control-tools.md with dynamic wait time strategy
   - Add device type comparison table
   - Document performance improvements
   - Update changelog

   Code quality:
   - All comments in English
   - flake8 check passed
   - mypy check passed
2026-03-14 15:14:28 +08:00
YueGuobin df8338401e feat(copilot): filter built-in utility templates from GNS3TemplateTool
Add filtering logic to exclude built-in utility templates that are not
   useful for network device configuration, making AI focus on actual network
   devices.

   - Add FILTERED_TEMPLATES constant with 6 utility template types
     * atm_switch - ATM switch
     * cloud - Cloud
     * ethernet_hub - Ethernet hub
     * ethernet_switch - Ethernet switch (built-in)
     * frame_relay_switch - Frame Relay switch
     * nat - NAT device

   - Add should_filter_template() function
     * Exact match on template_type field
     * Simple and reliable filtering logic

   - Update GNS3TemplateTool
     * Apply filtering in _run() method
     * Log filtered count for transparency
     * Update tool description

   - Update documentation (node-control-tools.md)
     * Document filtered template types
     * List retained template types
     * Add changelog entry

   - Code quality
     * All comments in English
     * flake8 check passed
     * mypy check passed
2026-03-14 14:54:12 +08:00
YueGuobin e2e2e23cf7 feat(copilot): add VPCS Telnet driver with Netmiko and ANSI code stripping
Implement custom VPCS driver and unified tool architecture:

   - Add VPCSTelnet custom driver (vpcs_telnet.py)
     - No authentication (direct console access like VPCS behavior)
     - Simple prompt pattern matching (PC\d+>)
     - Automatic ANSI escape code stripping for clean output
     - Config mode methods return empty (VPCS has no config modes)

   - Replace vpcs_tools_telnetlib3.py with vpcs_tools_netmiko.py
     - Migrate from telnetlib3 to Netmiko + Nornir architecture
     - Unified tool architecture matching config/display tools
     - Improved code consistency and maintainability

   - Add comprehensive test coverage (test_vpcs_telnet.py)
     - 30 unit tests covering all VPCS driver functionality
     - Tests for ANSI code stripping, telnet_login, send_command
     - Tests for device registration and initialization

   - Update VPCS built-in template (services/templates.py)
     - Add platform:vpcs and device_type:gns3_vpcs_telnet tags
     - Automatic driver selection without manual configuration

   - Update documentation (docs/)
     - multi-vendor-device-support.md: VPCS driver documentation
     - netmiko_devices.md: Add VPCS to supported devices list
     - README.md: Update multi-vendor support description
2026-03-14 14:25:37 +08:00
YueGuobin bbe57f34b9 feat(llm): hide api_key from all API responses and document max_tokens as reserved
Security Enhancement:
   - API keys are now always filtered to null in all LLM config API responses
   - Created LLMModelConfigDataWithoutSecret schema for response validation
   - Added _filter_api_key_from_config() helper in API routes
   - Modified repository to always hide api_key in get_user_effective_configs()
   - Update/create operations still accept and store api_key securely

   Documentation Updates:
   - Updated API key visibility section to reflect new security policy
   - Updated all response examples to show api_key as null
   - Marked max_tokens field as reserved for future use
   - Added "Reserved Fields" section explaining unused fields

   This defense-in-depth approach prevents API keys from being leaked through
   logs, browser devtools, or network monitoring.
2026-03-14 13:12:22 +08:00
YueGuobin a58089cf48 fix(copilot): add exit command warning to prevent session disconnection
Add warnings about 'exit' command in three locations to prevent AI from
   disconnecting Telnet/SSH sessions during command execution:

   - Prompt system rules (lab_automation_assistant_prompt.py)
   - Display tool description (display_tools_nornir.py)
   - Config tool description (config_tools_nornir.py)

   The 'exit' command disconnects the session and causes all subsequent
   commands in the batch to fail. This prevents users from viewing
   command outputs properly.
2026-03-14 00:34:06 +08:00
YueGuobin c76982b29e refactor(copilot): rename Huawei CE driver and add Ruijie tests with format fixes
- Rename huawei_telnet_ce to gns3_huawei_telnet_ce for consistent naming
   - Add comprehensive test suite for RuijieTelnetEnhanced driver (10 tests)
   - Update list_netmiko_telnet_devices.py to include gns3_ruijie_telnet
   - Fix all flake8 format issues (line length, unused imports, variables)
   - Update documentation to reflect device type rename
2026-03-14 00:08:13 +08:00
YueGuobinandClaude Sonnet 4.5 6e88582ff1 docs(gns3-copilot): update documentation for Ruijie driver and new features
- Add gns3_ruijie_telnet to supported devices in netmiko_devices.md
- Document custom RuijieTelnetEnhanced driver with hybrid strategy
  - Preprocessing: auto-insert 'yes' after known interactive commands
  - Fast path: batch send (2-3s for 13 commands)
  - Fallback: one-by-one with real-time prompt detection
- Add AAA/password configuration prohibition documentation
  - System-level enforcement in lab_automation_assistant_prompt
  - Categories: AAA, login passwords, console/VTY auth, encryption
- Document multi-line command handling for banner and similar commands
- Update device_type tag validation with error feedback
- Update multi-vendor support to include Ruijie platform

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-13 23:56:57 +08:00
YueGuobin 4f4ddb6504 feat(ruijie-telnet): enhance interactive command handling with hybrid strategy
Add pre-processing of known interactive commands and implement hybrid send strategy for Ruijie Telnet devices. The new approach:
- Pre-processes configuration commands to automatically insert 'yes' responses after known interactive commands (router-id, erase, delete, format, reload, boot system)
- Implements hybrid strategy: first attempts fast batch send with pre-processed commands, then falls back to one-by-one send with real-time prompt detection if batch fails
- Maintains backward compatibility while improving reliability for interactive configuration scenarios

This improves configuration reliability for Ruijie devices that frequently require confirmation prompts during configuration changes.
2026-03-13 23:51:12 +08:00
YueGuobin ad771e2927 feat: add Ruijie telnet driver support to custom Netmiko tools
- Import and register Ruijie telnet device type in config_tools_nornir.py
- Import and register Ruijie telnet device type in display_tools_nornir.py
- Update custom_netmiko __init__.py to include RuijieTelnetEnhanced driver
- Add Ruijie telnet driver to __all__ exports for proper module exposure
- Extends custom Netmiko support to handle Ruijie devices with interactive prompt handling
2026-03-13 23:33:14 +08:00
YueGuobin 8d9fce1c12 feat(agent): enhance configuration safety and multiline command handling
- Add explicit AAA/password configuration prohibition to safety reminders
- Implement multiline command expansion for banner and similar commands
- Add error handling for devices with missing device_type tags
- Improve logging for configuration errors and multiline expansions
2026-03-13 22:24:36 +08:00
YueGuobin 364ff93783 efactor(copilot): adopt Nornir best
practice for multi-vendor device support

   Refactor Nornir configuration to use host-level connection_options
   instead of dynamic groups, following Nornir's configuration priority
   model (host > group > defaults).

   **Problem:**
   Previous implementation used first device's configuration for all
   devices, causing Cisco devices to use Huawei driver and vice versa.

   **Solution:**
   - Each host now has device-specific connection_options at host level
   - Single generic "network_devices" group for shared settings
   - Host-level config automatically overrides group-level config

   **Changes:**
   - Remove: _get_nornir_groups_config() helper function
   - Remove: _get_nornir_group() helper function
   - Simplify: _initialize_nornir() to use single generic group
   - Update: get_gns3_device_port.py() to return host-level config
   - Reserve: platform field for future NAPALM/scrapli plugin support

   **Benefits:**
   - Cleaner code structure (no dynamic group creation)
   - Follows Nornir best practice ("configuration proximity")
   - Easy to extend with new device types
   - Properly handles mixed-vendor topologies
2026-03-13 09:32:18 +08:00
YueGuobin 44f802ae4f fix: update netmiko platforms after custom device registration
Netmiko's `ssh_dispatcher` calculates platform lists at module import
time. When custom device types (like Huawei CE) are registered
dynamically, these cached lists become stale and do not include the
new platforms.

This change imports `netmiko.ssh_dispatcher` and recalculates the
`platforms`, `platforms_base`, and `telnet_platforms` attributes to
ensure Netmiko recognizes the custom device types.
2026-03-12 23:38:24 +08:00
YueGuobin effea3fb26 feat(copilot): add Netmiko device list generator and simplify Huawei driver
- Add script to generate Markdown documentation of all Netmiko supported
     devices (SSH and Telnet), grouped by platform with source attribution
   - Highlight custom GNS3-Copilot devices with "Custom ✨" marker
   - Auto-generate device list to docs/gns3-copilot/netmiko_devices.md
   - Simplify HuaweiTelnetCE driver: remove redundant aliases
     (huawei_ce, huawei_telnet_ce_telnet), keep only huawei_telnet_ce
   - Update tests to match simplified device registration
2026-03-12 23:03:19 +08:00
YueGuobin 50fa4f6e2a refactor(huawei_ce): disable mypy and refactor driver
Disable mypy type checking for the Huawei CE driver module due to
Netmiko library limitations. Netmiko lacks type stubs (py.typed) and
uses dynamic attributes, which causes unresolved import and attribute
errors in static analysis.

Added a comprehensive comment block at the top of the file explaining
the rationale for disabling mypy to prevent future confusion.

Additionally, performed code cleanup including:
- Reformatted module docstrings and comments for better readability
- Added missing imports (importlib, logging)
- Removed unused typing imports (Optional)
- Refactored variable assignments in send_config_set for clarity
2026-03-12 22:38:21 +08:00
Mr.GIitch 302878b391 Merge branch 'GNS3:3.0' into 3.0 2026-03-12 14:44:43 +01:00
YueGuobin db164e9d41 feat(copilot): add multi-vendor device support with custom Huawei driver
Add comprehensive multi-vendor support for GNS3 network automation,
   including a custom Netmiko driver for Huawei CloudEngine devices.

   Features:
   - Custom HuaweiTelnetCE driver for GNS3 emulation (no authentication)
   - Auto-commit before exit to prevent [Y/N/C] prompts
   - Dynamic device type detection from GNS3 node tags
   - Support for both Cisco IOS and Huawei devices
   - Proper VRP command handling (system-view, return confirmation)

   Implementation:
   - New package: utils/custom_netmiko/
     - huawei_ce.py: Huawei CloudEngine driver
     - tests/test_huawei_ce.py: Unit tests (9/9 passing)
     - README.md: Driver development guide
   - Updated tools for multi-vendor support:
     - display_tools_nornir.py: Dynamic group generation
     - config_tools_nornir.py: Multi-vendor config commands
     - get_gns3_device_port.py: Device port extraction
   - Documentation: multi-vendor-device-support.md

   Limitations:
   - huawei_telnet_ce driver requires devices without authentication
   - For devices with username/password, use standard huawei_telnet driver

   Co-Authored-By: Yue Guobin <yueguobin@outlook.com>"
2026-03-12 16:44:32 +08:00
Guobin Yue ab88bcd57e Merge branch '3.0' into feature/ai-copilot-bridge 2026-03-12 16:12:13 +08:00
grossmj 3abecc8492 Fix IOU tests 2026-03-12 14:18:35 +08:00
grossmj 27ce1a4e25 Merge remote-tracking branch 'origin/2.2' into 3.0
# Conflicts:
#	gns3server/schemas/iou_template.py
#	tests/handlers/api/compute/test_iou.py
#	tests/handlers/api/controller/test_template.py
2026-03-12 14:11:05 +08:00
Jeremy Grossmann 5c63928636 Merge pull request #2634 from GNS3/update-iol-ram-nvram
Deactivate 'use default IOU values' by default and update RAM/NVRAM values
2026-03-12 13:53:04 +08:00
grossmj f41cc24383 Fix for duplicating Qemu nodes 2026-03-12 13:24:30 +08:00
Jeremy Grossmann 9aca6aece3 Merge pull request #2636 from yueguobin/fix/acl-endpoint-paths
fix(acl): correct endpoint paths for users, groups, and roles
2026-03-12 12:31:59 +08:00
UmmmAGoodName afeb6a3196 Minor optimizations to logic 2026-03-11 18:51:32 +01:00
UmmmAGoodName 99e3529c93 Fixed an issue with the server causing errors when uploading large images + Preparation for a smarter check when uploading images 2026-03-11 18:50:43 +01:00
UmmmAGoodName 19503ab4f7 Implementet a smarter node_type system 2026-03-11 18:49:36 +01:00
UmmmAGoodName 4a45a68703 Changed errors to new type, was causing warnings 2026-03-11 18:48:36 +01:00
YueGuobin 75a4585c20 docs: restructure copilot docs and update node tools
Simplify the documentation structure in `README.md` by removing the
`todo/` directory reference and detailed design documents for planned
features. Consolidate future roadmap items into a high-level summary
under "Future Enhancements".

Update `node-control-tools.md` to include documentation for new topology
management tools (create node, create link, get template, rename node)
and reflect updated API imports for `Link` support.
2026-03-12 00:23:00 +08:00
Guobin Yue 085a485503 Merge branch '3.0' into fix/acl-endpoint-paths 2026-03-11 23:34:18 +08:00
YueGuobin f2fd725e07 fix(acl): correct endpoint paths for users, groups, and roles
Fix the path mismatch between /acl/endpoints API and actual routes:
- Users: /users/{id} → /access/users/{id}
- Groups: /groups/{id} → /access/groups/{id}
- Roles: /roles/{id} → /access/roles/{id}

This fixes the error where creating ACE entries fails with:
"Path '/groups/{id}' doesn't match any existing endpoint"

The actual routes are registered under /access/ prefix, but the
endpoints API was returning paths without the prefix.

Co-Authored-By: Yue Guobin <yueguobin@outlook.com>
2026-03-11 23:23:52 +08:00
YueGuobin 5155e10214 feat(deps): update langchain ecosystem and add langsmith SDK
- Upgrade langchain packages to latest versions (langchain 1.2.10, langgraph 1.0.9, etc.)
- Add langsmith SDK for enhanced observability and tracing
- Update Pillow to 12.1.1 for image processing improvements
- Maintain compatibility with existing AI and automation framework
2026-03-11 22:18:31 +08:00
YueGuobin e82bce9e16 feat(docs): add TOSCA-based topology description proposal
Add comprehensive documentation proposing TOSCA (Topology and Orchestration Specification for Cloud Applications) as the standard format for GNS3 network topologies. The document outlines strategic benefits including standardized YAML descriptions, toolchain ecosystem integration, Git-based workflows, and template reuse capabilities. This initiative aims to modernize GNS3 topology management, improve user experience, and align with industry best practices for network automation and orchestration.
2026-03-11 22:13:23 +08:00
YueGuobinandClaude Sonnet 4.5 0056bdd19b fix(iou): return 405 error for unsupported suspend operation
Fixed IOU node suspend API to return proper HTTP 405 Method Not Allowed
error instead of misleading 204 No Content response.

Changes:
- Added HTTPException import to iou_nodes.py
- Fixed suspend_iou_node route from /stop to /suspend (bug fix)
- Changed response from 204 No Content to 405 Method Not Allowed
- Added clear error message: "Suspend is not supported for IOU nodes"

This fix ensures clients receive explicit feedback when attempting to
suspend IOU nodes, which do not support suspend functionality.

Related issue: IOU nodes previously returned 404 when suspend was called
due to incorrect route registration.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-11 15:14:23 +08:00
YueGuobin ad3621db0f feat(gns3-copilot): add node stop and suspend tools for lab automation
- Add GNS3StopNodeTool and GNS3SuspendNodeTool to lab automation assistant mode
- Update tools_v2 __init__.py to export new node control tools
- Document node control tools in README with key features and implementation status
- Update last modified date in documentation

The new tools provide complete node lifecycle control for automated lab workflows, including stopping nodes for shutdown and suspending nodes while preserving state.
2026-03-11 14:44:51 +08:00
YueGuobin 1cd4aeb2a2 feat(schemas): simplify LLM model config descriptions
- Remove redundant "(REQUIRED)" and detailed explanations from context_limit field descriptions
- Shorten copilot_mode descriptions by removing parenthetical details about mode capabilities
- Maintain field formatting consistency across LLMModelConfigData, Create, and Update schemas
2026-03-11 10:17:06 +08:00
YueGuobin 10a827f0c5 feat(api): enhance max_tokens field with robust null handling
- Update LLMModelConfigUpdate schema to accept Union[int, str] for max_tokens
- Add field validator to gracefully handle various null representations:
  - Convert string "null" to null
  - Convert empty strings to null
  - Convert numeric strings to integers
  - Accept proper JSON null values
- Update documentation to reflect new behavior and explain robust null handling
- Prevents validation errors from incorrect null serialization by clients
2026-03-11 10:14:06 +08:00
YueGuobinandClaude Sonnet 4.5 e452f75ac3 docs: reorganize AI Copilot documentation structure
- Add README.md with documentation overview and structure guide
- Move implemented designs to docs/gns3-copilot/implemented/:
  - chat-api.md (from ai-chat-api-design.md)
  - llm-model-configs.md (from llm-model-configs-api.md)
  - command-security.md
  - context-window-management.md
- Add Jinja2 configuration template system design documents:
  - jinja2-config-templates-system.md
  - config-templates-implementation-guide.md
  - ai-prompting-for-config-templates.md
- Remove obsolete documents (acl-web-ui, Chinese RBAC doc)

This reorganization makes it clearer which features are implemented
vs planned, following the established documentation structure.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-10 23:20:24 +08:00
YueGuobin a6c33061c4 delete doc 2026-03-10 22:51:57 +08:00
YueGuobin 578f79cd6b feat(docs): add AI prompting guide for configuration templates
Add comprehensive documentation for AI prompting to generate structured configuration data for Jinja2 templates. The guide includes:

- Core system prompt with critical rules for structured data generation
- Supported vendors and OS types (Cisco, Juniper, Huawei, Arista, Mikrotik)
- Detailed schemas for network features including OSPF, BGP, VLANs, ACLs, and more
- Example prompts and expected structured outputs
- Integration with the configuration renderer system

This documentation ensures AI-generated configurations follow the required structured format for proper template rendering, preventing direct configuration text generation and maintaining consistency across different network device vendors.
2026-03-10 22:38:41 +08:00
grossmj 0624c1b945 Deactivate 'use default IOU values' by default and update RAM/NVRAM values 2026-03-10 20:28:00 +08:00
YueGuobin 2dcdadf5fa docs: add mypy type checking issues todo document
Add comprehensive documentation for mypy static type checking
issues found in gns3_copilot module.

Document includes:
- 35 type errors across 9 files
- Detailed error descriptions and line numbers
- 3-phase fix strategy (High/Medium/Low priority)
- Mypy configuration recommendations
- Resource links for type hints and mypy

Related files:
- chat_sessions_repository.py (8 errors)
- context_manager.py (5 errors)
- agent_service.py (5 errors)
- gns3_topology_reader.py (2 errors)
- message_converters.py (1 error)
- connector_factory.py (1 error)

Co-Authored-By: Yue Guobin <yueguobin@outlook.com>
2026-03-10 01:20:42 +08:00
YueGuobin 71802a8064 style: remove unused List import from llm_model_configs.py
Remove unused typing.List import flagged by ruff F401.

Co-Authored-By: Yue Guobin <yueguobin@outlook.com>
2026-03-10 01:11:37 +08:00
YueGuobin 5e9ec23a45 style: remove unused imports and fix E712 comparisons in llm_model_configs.py
Remove 5 unused imports flagged by ruff F401:
- sqlalchemy.func, sqlalchemy.or_
- sqlalchemy.ext.asyncio.AsyncSession
- sqlalchemy.orm.selectinload
- json

Fix 4 E712 errors - avoid equality comparisons to True:
- Use models.LLMModelConfig.is_default instead of == True

Co-Authored-By: Yue Guobin <yueguobin@outlook.com>
2026-03-10 01:10:19 +08:00
YueGuobin 7d031a6802 style: remove unused imports and variables in project.py
Remove unused import and exception variable flagged by ruff:
- Remove unused 'sys' import (F401)
- Remove unused exception variable 'e' in except clause (F841)

Co-Authored-By: Yue Guobin <yueguobin@outlook.com>
2026-03-10 01:08:20 +08:00
YueGuobin c0aec3f979 style: remove unused imports from llm_model_configs.py
Remove 3 unused imports that were flagged by ruff F401:
- fastapi.Response
- fastapi.security.OAuth2PasswordRequestForm
- gns3server.controller.controller_error.ControllerError

Co-Authored-By: Yue Guobin <yueguobin@outlook.com>
2026-03-10 01:07:23 +08:00
YueGuobin 7c3b832bca style: fix E501 line-too-long errors in gns3_copilot
Fix all 423 E501 line length violations across 26 files to comply with
   PEP 8 88-character line limit.

   Changes:
   - Split long f-strings across multiple lines
   - Break long docstring descriptions and parameter lists
   - Split markdown table rows and list examples
   - Break long URL construction f-strings
   - Split long logger messages and comments
   - Add noqa: E501 for SVG strings (cannot be split)

   Modified files:
   - agent/: context_manager.py, gns3_copilot.py, model_factory.py
   - gns3_client/: connector_factory.py, context_helpers.py, custom_gns3fy.py,
                   gns3_project_info.py, gns3_topology_reader.py
   - prompts/: __init__.py, lab_automation_assistant_prompt.py,
               prompt_loader.py, teaching_assistant_prompt.py
   - tools_v2/: __init__.py, config_tools_nornir.py, display_tools_nornir.py,
                gns3_create_link.py, gns3_create_node.py, gns3_get_node_temp.py,
                gns3_start_node.py, gns3_update_node_name.py,
                vpcs_tools_telnetlib3.py
   - utils/: __init__.py, command_filter.py, get_gns3_device_port.py,
             gns3_drawing_utils.py, llm_config_helper.py, message_converters.py,
             parse_tool_content.py, tool_call_stream.py

   All files now pass ruff E501 checks.

   Co-Authored-By: Yue Guobin <yueguobin@outlook.com>
2026-03-10 01:05:17 +08:00
Guobin Yue 25f2d1b56b Merge branch '3.0' into feature/ai-copilot-bridge 2026-03-09 21:50:37 +08:00
YueGuobin 7c2083d227 feat: update .gitignore to track project context and development docs
- Add exception for .claude/development.md to allow tracking development documentation
- Comment out PROJECT_CONTEXT.md exclusion to enable version control of project context file
- Create PROJECT_CONTEXT.md with comprehensive project overview for AI assistant support
- Document project structure, AI copilot data flow, SSE event types, and code standards
- Provide flake8 static analysis guidelines and common error fixes
2026-03-09 21:46:58 +08:00
grossmj 69eafda777 Merge remote-tracking branch 'origin/2.2' into 3.0
# Conflicts:
#	gns3server/version.py
2026-03-09 17:12:24 +08:00
grossmj b658f7ff68 Make sure the node shows as stopped when the wrap console cannot be stopped. Ref https://github.com/GNS3/gns3-registry/pull/1010 2026-03-09 17:10:00 +08:00
YueGuobin b936a52f6f docs: add LangGraph Agent and tool output serialization documentation
Added new section in ai-chat-api-design.md explaining:

- LangGraph Agent architecture and main components
- tool_node function and tool output serialization mechanism
- Why serialization happens in tool_node (not agent_service)
- Tool output data flow diagram showing SSE and history paths
- Explanation of JSON format consistency across streaming and storage

This documentation clarifies the fix for single-quotes issue in
conversation history and helps future maintenance.

Co-Authored-By: YueGuobin <yueguobin@outlook.com>
2026-03-09 15:54:44 +08:00
YueGuobin 9b85417a82 fix(copilot): serialize tool output to JSON in ToolMessage for history
Fixed tool output serialization in tool_node function to ensure
ToolMessage.content is always in JSON format, not Python str() representation.

This fixes the issue where conversation history showed tool outputs
with single quotes (Python format) instead of standard JSON.

Changes:
- Added json import to gns3_copilot.py
- Modified tool_node() to serialize observation to JSON before creating ToolMessage
- Ensures both SSE streaming and history storage use consistent JSON format

Root cause: ToolMessage was created with raw dict/list objects, which
LangChain converted to Python str() representation when saving to history.

Co-Authored-By: YueGuobin <yueguobin@outlook.com>
2026-03-09 15:50:36 +08:00
YueGuobin 8babaccd80 feat: add PROJECT_CONTEXT.md to gitignore
Add PROJECT_CONTEXT.md to the .gitignore file to prevent it from being tracked in version control. This file likely contains project-specific context or configuration that should not be committed to the repository.
2026-03-09 15:34:31 +08:00
YueGuobin 0f2d0e2859 fix(copilot): serialize tool output to standard JSON format for frontend parsing
Changed tool output serialization in AgentService._convert_event_to_chunk()
from str() to json.dumps() to ensure structured data (dict/list) is properly
formatted as standard JSON instead of Python string representation.

Changes:
- Added json import to agent_service.py
- Modified on_tool_end event handling to use json.dumps(output, ensure_ascii=False, indent=2)
- Updated ai-chat-api-design.md to document tool_output format

Benefits:
- Frontend can parse tool results with standard JSON.parse()
- Chinese and non-ASCII characters are preserved (not escaped)
- Formatted output (indent=2) improves readability

Co-Authored-By: YueGuobin <yueguobin@outlook.com>
2026-03-09 15:15:50 +08:00
YueGuobin 13a032ea2c chore: update author name and copyright headers
Updated the author name and copyright statements across the
gns3_copilot module. The name has been standardized from
"Guobin Yue" to "Yue Guobin (岳国宾)" to reflect the correct
author attribution including Chinese characters.
2026-03-09 11:46:28 +08:00
Guobin Yue d7e5fe065e Merge branch '3.0' into feature/ai-copilot-bridge 2026-03-08 13:20:27 +08:00
YueGuobin 9ba02e9436 feat(docs): enhance AI chat API documentation with examples and details
- Improve POST /chat endpoint documentation with request/response examples
- Add session ID management flow explanation
- Enhance GET /sessions endpoint with query parameters and response example
- Update GET /sessions/{session_id}/history with detailed response structure
- Format parameters as tables for better readability
- Clarify session ID usage in streaming conversations
2026-03-08 02:27:48 +08:00
YueGuobin fd34ef494f feat: add .claude directory to gitignore for API key security
Add .claude/ directory to .gitignore to prevent accidental
commit of Claude Code settings which may contain sensitive
API keys. This ensures development environment configuration
files with potential credentials are excluded from version
control.
2026-03-07 23:52:16 +08:00
Jeremy Grossmann cd51afb01f Merge pull request #2633 from GNS3/revert-2628-console
Revert "Fix QEMU serial console artifacts by filtering ANSI CPR responses in …"
2026-03-07 22:24:17 +08:00
Jeremy Grossmann 14ffa2c2d6 Revert "Fix QEMU serial console artifacts by filtering ANSI CPR responses in …" 2026-03-07 22:22:16 +08:00
grossmj 73ffb22aa2 Bundle web-ui v3.1.0.dev1 2026-03-07 17:47:44 +08:00
Jeremy Grossmann f81ab0cfbe Merge branch '3.0' into feature/ai-copilot-bridge 2026-03-07 13:00:39 +08:00
Jeremy Grossmann 0cedab1742 Merge pull request #2632 from GNS3/drop-python3.9
Drop support for Python 3.9
2026-03-07 11:19:03 +08:00
Guobin Yue 1cc48c1fb0 Merge branch '3.0' into feature/ai-copilot-bridge 2026-03-07 01:57:08 +08:00
YueGuobin 23b073a7bc docs: add troubleshooting guide for datetime timezone issue
Add comprehensive documentation for handling datetime timezone discrepancies between backend and frontend. The issue arises when backend returns naive datetime strings without timezone suffixes, causing JavaScript to parse them as local time instead of UTC. The guide includes problem description, root cause analysis, three frontend solutions (dayjs UTC parsing, manual 'Z' suffix addition, and global Axios interceptor), backend context, and testing checklist.
2026-03-07 01:42:18 +08:00
grossmj 679c690903 Drop support for Python 3.9 2026-03-06 19:03:53 +08:00
Jeremy Grossmann 09aaf43dd1 Merge pull request #2628 from Raizo62/console
Fix QEMU serial console artifacts by filtering ANSI CPR responses in …
2026-03-06 18:24:34 +08:00
Jeremy Grossmann 5755a48fa3 Merge pull request #2630 from UmmmAGoodName/3.0
Fixed the path traversal check
2026-03-06 18:05:57 +08:00
YueGuobin 3a287de8c1 docs: add ACL Web UI implementation guide for frontend developers
Add comprehensive implementation guide for ACL management feature in GNS3 Web UI. The guide includes:

- Feature overview with core functionality and user flow
- Detailed API endpoint specifications for ACE CRUD operations
- Data structures and relationships
- Frontend implementation guide with component architecture
- UI/UX design recommendations and wireframes
- Common usage scenarios and error handling patterns
- Example code with React components and API service layer

This document serves as a reference for frontend developers implementing ACL management interface, covering everything from API integration to user interface design.
2026-03-06 14:19:19 +08:00
YueGuobin 8660e9c8db feat(docs): add RBAC + ACL implementation guide for GNS3 Server
Add comprehensive documentation for the two-tier permission control system combining RBAC and ACL features. The guide covers system overview, core concepts, data model, permission check flow, usage examples, best practices, and common issues. This documentation is applicable for GNS3 Server v3.0+ and provides implementation details for administrators managing user permissions.
2026-03-06 13:07:15 +08:00
YueGuobin 3d781236c6 delete depreacted dir 2026-03-06 11:08:35 +08:00
YueGuobin 0f61a06557 feat(docs): clarify API key visibility for group configurations
Add detailed section explaining that plaintext API keys for group configurations are never exposed through the application API, even to super admins. This clarifies the security design where group configs are intended for inheritance only, not manual viewing, while maintaining internal decryption for inheritance functionality.
2026-03-06 11:06:18 +08:00
YueGuobin 903e48aecc feat(docs): clarify API key visibility rules and encryption details
Update the LLM model configs API documentation to provide clearer explanations of API key visibility controls and encryption behavior. The changes include:

- Enhanced visibility table with more specific scenarios and encryption states
- Added detailed rules explaining when API keys are visible as plaintext, hidden (null), or shown encrypted
- Clarified super admin capabilities and database-level access
- Updated JSON examples to reflect actual encrypted values and null placeholders
- Added important notes about Fernet encryption, on-the-fly decryption, and group config behavior

These updates provide better transparency about security measures and help users understand what to expect when viewing different types of configurations.
2026-03-06 10:05:17 +08:00
YueGuobin 4941dc13d8 feat(api): enhance /me endpoint with groups, pools, and ACEs
Add comprehensive user context to the `/me` endpoint by including group memberships, accessible resource pools, and access control entries (ACEs). This enables users to view inherited configurations, available resources, and their permissions directly from the API.

Key additions:
- Group membership details with inherited configs
- Resource pool access information
- ACE visibility for permission transparency
- Support for user-selectable group default configurations

The enhancement addresses user needs for better visibility into permissions and accessible resources within the system.
2026-03-06 09:50:34 +08:00
YueGuobin eb7a72f5e2 feat(docs): update copilot_mode value in LLM model configs API example
Changed the example value of `copilot_mode` from "lab_assistant" to "lab_automation_assistant" in the API documentation to reflect the correct mode name used in the system.
2026-03-06 02:00:02 +08:00
YueGuobin 77ef87f468 feat(prompts): rename prompt modules for clarity and consistency
Rename base_prompt.py to teaching_assistant_prompt.py and lab_assistant_prompt.py to lab_automation_assistant_prompt.py to better reflect their purposes. Update all imports and references accordingly to maintain consistency across the codebase. This improves code readability and aligns naming with the actual functionality of each prompt module.
2026-03-06 01:58:54 +08:00
YueGuobin dd3b06bd75 feat(docs): remove reference tool command from model configs API documentation
The `python scripts/show_model_context_limits.py` command was removed from the documentation as it is no longer necessary or relevant for users configuring model context limits. The remaining content still provides clear guidance on calculating context limits in K tokens.
2026-03-06 01:55:46 +08:00
Guobin Yue 87f8f22524 Merge branch '3.0' into feature/ai-copilot-bridge 2026-03-06 01:42:47 +08:00
YueGuobin 216b3d7219 docs: translate AI chat API design document to English
Translate the GNS3 Copilot Agent Chat API design document from Chinese to English to improve accessibility for international contributors and align with project documentation standards. The translation covers all sections including overview, core features, architecture design, API endpoints, and response formats.
2026-03-06 01:14:52 +08:00
YueGuobin 8fa6d6810a feat: add multi-user concurrency control design document
Add comprehensive design document outlining the race condition issue when multiple users simultaneously operate on the same network device via GNS3-Copilot Agent. The document details the problem statement, affected components, and proposes two solutions: device-level mutex lock (recommended) and connection pooling with session isolation. It includes implementation details, API changes, and UI considerations to ensure safe concurrent operations.
2026-03-06 01:08:45 +08:00
YueGuobin af6d87426b feat(agent): add runtime control parameters for agent behavior
Add support for runtime control parameters `max_iterations` and `max_tool_calls` in the chat API to allow users to dynamically adjust agent behavior per request. This addresses current limitations where iteration limits and tool call constraints are hardcoded, providing flexibility for complex tasks and cost control.
2026-03-06 00:54:33 +08:00
YueGuobin c317932f1a feat(security): add forbidden command filtering for device configurations
- Import filter_forbidden_commands utility from command_filter module
- Add _filter_forbidden_commands_from_device_configs method to filter out restricted commands before execution
- Store blocked commands information and log filtered commands for audit purposes
- Update _process_task_results to include blocked commands info in response
- Prevent execution of potentially dangerous commands while maintaining transparency about filtered content
2026-03-06 00:30:17 +08:00
YueGuobin f1b496df49 docs: add troubleshooting guide for force kill residual processes
Add comprehensive documentation for troubleshooting issues caused by using `kill -9` on gns3server processes. The guide explains the root cause where SIGKILL prevents proper cleanup of child processes like dynamips and vpcs, leading to port conflicts and resource allocation errors when restarting. It provides multiple solutions including manual process cleanup, proper shutdown procedures, and preventive measures with example scripts. This documentation helps users resolve common issues with Dynamips VM creation failures, undefined project_id errors, and TCP port warnings.
2026-03-05 23:39:59 +08:00
UmmmAGoodName 6ff4d46838 Fixed the path traversal check 2026-03-05 16:38:55 +01:00
YueGuobin aaba2d6181 docs: update node name from generate_title to title_generator_node
Updated references to the title generation node in both documentation and code:
- Changed node name from `generate_title` to `title_generator_node` in API design documentation
- Updated filtering logic in agent service to exclude `title_generator_node` from LLM call statistics, token counting, and frontend streaming events
- Maintains same functionality while using more descriptive node name for clarity
2026-03-05 23:19:20 +08:00
YueGuobin a7bc68d6e1 feat(docs): reorganize documentation and add orphan tool calls recovery plan
- Move command-security.md and hitl-implementation-plan.md to todo/ directory
- Add new documentation for orphan tool calls recovery with detailed problem analysis and implementation plan
- Document scenarios causing orphan tool calls and propose fix strategy using LangGraph API
2026-03-05 23:07:02 +08:00
YueGuobin b8cb0bdcb0 feat(agent): exclude generate_title node from LLM call and token statistics
Filter out internal LangGraph 'generate_title' node from LLM call counting and token usage tracking to avoid inflating statistics with internal operations. This ensures metrics only reflect user-facing AI interactions.
2026-03-05 23:01:41 +08:00
YueGuobin 511b155da8 feat(ai-chat-api): implement streaming tool calls with incremental parameter accumulation
- Update API documentation to reflect new streaming tool call mechanism
- Add `message_id` optional field to content and tool_call events
- Change tool_call structure from array to single object with incremental updates
- Add `tool_call_id` to tool_start events for better event correlation
- Implement ToolCallStreamAccumulator class to handle parameter accumulation
- Provide frontend example code for handling streaming tool calls
- Maintain backward compatibility with existing session_id tracking
2026-03-05 22:29:01 +08:00
YueGuobin 1de7d00db3 feat(agent): update SSE event schema and handle tool calls from LLM
- Update AI chat API documentation with revised SSE event schema
- Add support for multiple tool calls in `tool_call` events
- Include `session_id` in all event types for better session tracking
- Implement `on_chat_model_end` handler to process LLM tool call decisions
- Update example JSON payloads to reflect new schema structure
2026-03-05 22:03:27 +08:00
YueGuobin 54775faaf4 feat(copilot): rename copilot modes for clarity and add mode-specific tools
- Rename "teaching" mode to "teaching_assistant" for better clarity
- Rename "lab_assistant" mode to "lab_automation_assistant" to reflect expanded capabilities
- Implement mode-specific tool sets: teaching_assistant gets read-only diagnostic tools only, while lab_automation_assistant gets full diagnostic and configuration tools
- Update API documentation examples to reflect new mode names
- Maintain backward compatibility with default tool set initialization
2026-03-05 21:44:36 +08:00
YueGuobin 28f2fe03e6 feat: suppress nornir INFO logs to reduce console verbosity
Set logging level for nornir.core and nornir loggers to WARNING in config_tools_nornir.py and display_tools_nornir.py. This prevents nornir from logging task execution at INFO level to the console, as the logging={"enabled": False} parameter in InitNornir only disables plugin internal logs.
2026-03-05 21:04:46 +08:00
YueGuobin 2485bfec46 docs: add temperature parameter documentation and code formatting improvements
- Added `temperature` parameter to Chat API documentation with implementation notes
- Improved code formatting in context_manager.py with consistent string quotes and line breaks
- Added section on future runtime LLM parameter override capabilities
- Updated API schemas to include temperature parameter (currently unused but reserved for future implementation)
2026-03-05 20:58:14 +08:00
YueGuobin 7f8364fbf5 refactor: move context helpers to separate module for better organization
- Extract context variable management functions from connector_factory.py to new context_helpers.py module
- Update imports in gns3_copilot.py, agent_service.py, and __init__.py to use new module
- Remove inline imports and ensure consistent access to context helpers
- Improves code organization and maintainability by separating concerns
2026-03-05 20:40:16 +08:00
YueGuobin 16559d2ce2 feat(agent): reorganize imports and improve code structure
- Standardize import organization with clear sections (standard library, third-party, local)
- Move sys.path modification to top of imports for better clarity
- Fix circular import issues by reordering imports
- Remove duplicate imports and ensure proper import grouping
- Maintain all existing functionality while improving code readability
2026-03-05 18:06:36 +08:00
YueGuobin 08b5b44a50 feat(copilot): add copilot_mode field to LLM model configs API
- Add `copilot_mode` field to request examples in API documentation
- Update prompt loader to read `copilot_mode` from flattened config structure
- Support both "teaching" and "lab_assistant" modes for different assistant behaviors
2026-03-05 16:41:47 +08:00
YueGuobin a777c36a29 feat(copilot): add copilot_mode field and config command tool
- Add `copilot_mode` field to LLM model configs API with "teaching" (diagnostics only) and "lab_assistant" (full configuration access) modes
- Introduce new `ExecuteMultipleDeviceConfigCommands` tool for executing configuration commands on multiple devices
- Include `tags` field in node data structure for enhanced project management
- Update API documentation examples to reflect new `copilot_mode` field and context limit additions
2026-03-05 16:31:02 +08:00
YueGuobin 8dc8facb13 docs: simplify context window management documentation
Removed extensive implementation details and configuration examples from the context window management documentation. The document now focuses on core permissions and prohibitions for tool usage, providing a clearer and more concise reference for allowed and forbidden actions. This streamlines the documentation to essential guidelines only.
2026-03-05 14:05:58 +08:00
Jeremy Grossmann ea68d8b959 Merge pull request #2629 from GNS3/image-handling
Fix image handling
2026-03-05 12:43:47 +08:00
grossmj 4606613673 Fix image handling 2026-03-05 12:38:28 +08:00
YueGuobin a8044cc1c2 feat: add copyright and author attribution to source files
Add copyright notice and author attribution to multiple Python files in the gns3-copilot module. This ensures proper licensing attribution and clarifies authorship for the project files.
2026-03-05 11:34:00 +08:00
YueGuobin 2779734de4 feat: remove redundant project attribution comments from GNS3-Copilot modules
Removed repetitive "This module is part of the GNS3-Copilot project" and GitHub URL comments from multiple module docstrings. These comments were redundant since the project information is already established in the main package documentation. This cleanup improves code readability and reduces maintenance overhead by eliminating duplicate attribution statements across the codebase.
2026-03-05 11:26:54 +08:00
YueGuobin d12b2df306 feat(docs): update context window management documentation
- Refactor system message structure to combine system prompt and topology info using template variables
- Update token calculation process with merged system message approach
- Clarify priority order for message retention during context window management
- Add detailed token counting implementation using tiktoken library
- Include boundary case handling for system message exceeding budget
- Add SPDX license headers to tool files for proper licensing documentation
2026-03-05 11:23:11 +08:00
YueGuobin ed5fd7d17c feat(agent): inject topology into system prompt via template variable
Refactor context preparation to embed topology information directly into the system prompt using a {{topology_info}} placeholder, replacing the previous approach of appending a separate SystemMessage. This consolidates context into a single system message and simplifies token accounting. The logging is updated to reflect the new token breakdown, showing combined system prompt tokens (base + topology) instead of separate components.
2026-03-05 11:05:51 +08:00
YueGuobin 33df674cbf feat(agent): remove GNS3TopologyTool from available tools list
The GNS3TopologyTool has been removed from the list of available tools for the agent. This change simplifies the toolset by eliminating a tool that is no longer needed or supported in the current workflow.
2026-03-05 10:55:10 +08:00
YueGuobin 7fcdb57615 feat(context-manager): improve context window management with tool token accounting
Enhanced the context window management system to properly account for tool definition tokens when trimming messages. The key changes include:

- Updated `trim_messages_for_context` function to accept `tool_tokens` parameter
- Modified token budget allocation logic to subtract tool tokens before message trimming
- Added detailed documentation explaining the token budget distribution between messages and tool definitions
- Implemented prioritized trimming strategy that preserves system messages and recent conversation history
- Added boundary case handling for scenarios where system messages or tools exceed available budget

The improvements ensure more accurate context window management by accounting for the ~1000-2000 tokens typically consumed by tool definitions that LangChain automatically includes in LLM requests.
2026-03-05 01:50:48 +08:00
YueGuobin f8aa653ef9 feat(context-manager): add tiktoken dependency and improve token counting accuracy
- Add tiktoken as a required dependency for accurate token counting
- Update documentation with installation instructions and token counting strategy
- Improve logging to include tool definition token estimates
- Enhance error handling to fail fast when tiktoken is not available
- Update context manager to use tiktoken's cl100k_base encoding for GPT-4 compatibility
2026-03-05 01:01:34 +08:00
YueGuobin 7368ac098a docs: add context limit and strategy to LLM model configs API
- Add `context_limit` as required field for LLM model configurations
- Add `context_strategy` as optional field with three trimming strategies
- Update API documentation with detailed examples for GPT-4o and Claude 3.5 Sonnet
- Clarify that context limit is specified in K tokens (thousands of tokens)
- Update example payloads to reflect current model versions and new fields
2026-03-05 00:40:46 +08:00
YueGuobin 6a9f745c13 feat(copilot): add HITL confirmation for sensitive operations
- Move AI chat API design document to gns3-copilot directory
- Add comprehensive HITL implementation plan with architecture and workflow
- Introduce human-in-the-loop confirmation for dangerous configuration commands
- Include state management, API endpoints, and frontend integration details
- Provide testing plan and deployment steps for the new feature
2026-03-04 23:53:50 +08:00
YueGuobin 4e28adffb6 feat(copilot): add tool response normalization utility
Add `normalize_tool_response` function to standardize tool output formats for consistent frontend display. The function converts various response types (dict, list, string) into a unified structure with success metrics, detailed data arrays, and metadata. This ensures backward compatibility while providing predictable response formats for UI components.
2026-03-04 23:41:29 +08:00
YueGuobin f64daa96cd feat(agent): streamline conversation flow logic in copilot
- Remove unused `llm_calls` variable and redundant logging in `should_continue`
- Simplify title generation routing by eliminating unnecessary condition checks
- Improve code clarity and maintainability by focusing on essential flow control
2026-03-04 23:34:14 +08:00
YueGuobin 4a017b1a7f feat(chat): add session pinning feature with database migration
- Add `pinned` column to chat_sessions table with default FALSE
- Implement database migration for existing installations using PRAGMA table_info
- Create composite index for pinned + updated_at sorting
- Add pin/unpin API endpoints (PUT/DELETE /sessions/{id}/pin)
- Update session listing to sort by pinned status then updated_at
- Extend ChatSessionsRepository with pin_session method
- Update API documentation to reflect new pinning functionality

The feature allows users to pin important chat sessions to the top of the list. Sessions are sorted with pinned sessions first (by updated_at), followed by regular sessions (by updated_at). Database migration ensures backward compatibility with existing installations.
2026-03-04 23:18:30 +08:00
YueGuobin f688a2d5c0 feat(agent): enhance message handling with ID generation and format conversion
- Add message ID generation for initial HumanMessage creation
- Implement message converters for LangChain/OpenAI format interoperability
- Update documentation with detailed message format specifications
- Refactor AgentService to use centralized message conversion utilities
- Ensure tool_calls format compliance with OpenAI API standards
2026-03-04 23:05:43 +08:00
YueGuobin 6b73f00281 docs: update AI chat API design with detailed statistics collection
Update the AI chat API design documentation to provide comprehensive details about statistics collection during streaming conversations. The documentation now includes:

1. **Enhanced statistics collection logic**:
   - Clarified message_count increments for user messages, AI responses, and tool results
   - Added LLM call tracking via on_chat_model_start events
   - Detailed token counting methodology using LangGraph's usage_metadata

2. **Improved implementation details**:
   - Added specific event handlers for statistics collection
   - Explained LangGraph's cumulative token counting behavior
   - Provided real-world examples of token accumulation

3. **Updated data models**:
   - Enhanced ChatSession model documentation with field descriptions
   - Separated fields into categories (basic, statistics, timestamps, reserved)

4. **Refined architecture documentation**:
   - Added detailed flow for stream_chat method
   - Documented statistics collection mechanism during SSE streaming
   - Explained batch update strategy to reduce database writes

The changes ensure developers understand how conversation statistics are collected, processed, and stored without impacting streaming performance.
2026-03-04 22:33:28 +08:00
YueGuobin 48e2793719 feat(agent): initialize checkpointer before chat session retrieval
Add initialization check for `_checkpointer_conn` in `AgentService` to ensure the checkpointer database connection exists before attempting to retrieve chat sessions. This prevents potential null reference errors when the checkpointer hasn't been initialized yet during agent operations.
2026-03-04 22:09:09 +08:00
YueGuobin 03ab9cdf6c feat(chat-api): refactor design document with concise architecture overview
- Replace detailed implementation plan with high-level architecture design
- Focus on core features: project isolation, streaming responses, session management
- Remove FlowNet-Lab reference and implementation specifics
- Streamline document from 1172 to 483 lines for better maintainability
2026-03-04 21:58:23 +08:00
Raizo62 590eedeb46 Fix QEMU serial console artifacts by filtering ANSI CPR responses in telnet proxy
- filter incoming cursor position report sequences (`ESC[<row>;<col>R`) in `AsyncioTelnetServer`
- prevent stray `;1R;80R` characters on late telnet console attach after VM boot
- keep QEMU serial transport unchanged (`-serial telnet`) for BIOS compatibility
2026-03-04 14:26:52 +01:00
Jeremy Grossmann 2843e05e01 Merge pull request #2627 from GNS3/bugfix/2622
Qemu VMs: only compute MD5 checksums for existing disks
2026-03-04 18:57:52 +08:00
grossmj 8b245c96f8 Qemu VMs: only compute MD5 checksums for existing disks 2026-03-04 18:54:52 +08:00
YueGuobin b6c343c5b8 feat(agent): add GNS3UpdateNodeNameTool to copilot tools
Introduce a new tool for updating node names within the GNS3 copilot agent. This expands the agent's capabilities to include node name modifications alongside existing node and link management operations.
2026-03-04 17:55:16 +08:00
YueGuobin 0648b53a45 feat(gns3_copilot): enhance topology logging with structured details
Improve logging in GNS3 topology reader to provide more structured and informative output. The previous single-line JSON log has been replaced with separate info and debug logs:
- Info log now includes project ID, project name, node count, and link count
- Debug log retains the full topology details for deeper inspection
This makes it easier to monitor topology retrieval in production while keeping detailed data available for debugging.
2026-03-04 17:43:41 +08:00
YueGuobin ef712ad314 feat(copilot): simplify project context handling and remove mode parameter
- Remove `selected_project` tuple from MessagesState as it's no longer needed
- Replace tuple-based project selection with direct `project_id` from config
- Remove unused `mode` parameter from llm_call function
- Update topology retrieval to use project_id directly from configurable settings
- Streamline context messages by removing redundant project info formatting
- Move project_id from metadata to configurable section in agent_service config
2026-03-04 17:40:17 +08:00
grossmj 5b00529666 Copy config files and database from a previous version if it exists 2026-03-04 17:23:10 +08:00
Jeremy Grossmann a20e10f75a Merge pull request #2625 from markparonyan/3.0
feat(compute): option to disable compute authentication
2026-03-04 16:40:58 +08:00
grossmj 7010baccee Add enable_http_auth in gns3_server.conf sample 2026-03-04 16:35:26 +08:00
YueGuobin 4fa29f3bee feat(agent): add GNS3ProjectInfoTool to gns3_client exports
Add GNS3ProjectInfoTool to the __all__ list in gns3_client/__init__.py to make it available for import. This ensures the tool is properly exposed as part of the public API for use in copilot agent modules.
2026-03-04 16:06:13 +08:00
YueGuobin a278a6091c feat(agent): add comprehensive logging to LLM and tool execution nodes
- Add info and debug logging to llm_call node for tracking LLM invocations and configuration
- Add error handling and logging to tool_node for tool execution failures
- Add startup logging to stream_chat method with session details
- Improve observability of agent workflow and debugging capabilities
2026-03-04 15:46:12 +08:00
YueGuobin 1e9cf3fcbb feat(agent): make JWT token optional in GNS3 connector factory
The `get_gns3_connector` function now accepts an optional `jwt_token` parameter. If not provided, the token will be retrieved from context, improving flexibility for scenarios where authentication is handled externally or deferred.
2026-03-04 15:38:50 +08:00
YueGuobin 289ae0cddf feat(agent): remove redundant done message from stream_chat
The `stream_chat` method was yielding a "done" message after streaming all chunks, but this is unnecessary as the streaming completion is already indicated by the end of the stream. Removing this redundant message simplifies the response handling and aligns with typical streaming patterns.
2026-03-04 13:57:03 +08:00
YueGuobin 425ce43bdd feat(chat): add project status checks to chat endpoints
Add project status validation to all chat API endpoints to ensure the project is opened before allowing chat operations. This prevents unauthorized access and ensures chat functionality only works with active projects.

- Check project.status == "opened" in stream_chat, list_sessions, get_history, and delete_session endpoints
- Return HTTP 403 FORBIDDEN with descriptive error message if project is not opened
- Update docstring for stream_chat endpoint to document the requirement
2026-03-04 13:55:09 +08:00
YueGuobin eec4ebe3fd feat(copilot): replace LangGraph config with request-scoped context variables
- Refactor `llm_call` and `generate_title` nodes to retrieve `llm_config` from request-scoped context variable instead of LangGraph config
- Remove `jwt_token` and `llm_config` from LangGraph configurable parameters in `AgentService.stream`
- Add `set_current_llm_config` and `get_current_llm_config` functions to `connector_factory` and export them in `__init__.py`
- Update `tool_node` to no longer extract `jwt_token` from config as it is now handled via context variable
- Improves thread safety and decouples configuration from LangGraph's state management
2026-03-04 13:49:17 +08:00
YueGuobin b05e6a71b4 feat(copilot): refactor JWT token handling and improve metadata tracking
- Move JWT token from state to configurable context for better security and request isolation
- Add user_id parameter to agent service for enhanced metadata tracking
- Update checkpoint directory name from .gns3-copilot to gns3-copilot
- Implement context-aware JWT token management using ContextVar
- Improve tool node to extract JWT token from config instead of state
2026-03-04 13:36:16 +08:00
YueGuobin 5e9aac7514 feat(agent): handle AIMessageChunk content access in copilot streaming
Update agent service to properly access content from AIMessageChunk objects during chat model streaming. Instead of using dictionary get method on the chunk, now use getattr to directly access the content attribute, ensuring compatibility with the AIMessageChunk object structure.
2026-03-04 13:23:07 +08:00
YueGuobin b780bfaf53 feat(agent): refactor LLM configuration handling to use centralized config
- Replace separate user_id and jwt_token parameters with unified llm_config dict
- Simplify model factory to accept llm_config directly instead of fetching from API
- Update llm_call and generate_title nodes to extract llm_config from LangGraph config
- Remove deprecated API fetching logic from model factory
- Maintain backward compatibility for existing tool usage patterns

This change centralizes LLM configuration management, reducing API calls and improving performance by passing configuration directly from the API layer rather than fetching it repeatedly.
2026-03-04 13:13:54 +08:00
YueGuobin 4765e54d7a feat: improve async handling in LLM config retrieval
Refactor get_llm_config to handle various async contexts more robustly. The function now properly checks for running event loops using asyncio.get_running_loop() and handles edge cases when called from thread pools or existing loops. This prevents RuntimeErrors and ensures reliable execution in both sync and async environments.
2026-03-04 12:47:37 +08:00
YueGuobin d8c3a56503 feat(agent): remove environment variable fallback for LLM configuration
Remove support for environment variable fallback in LLM model configuration. The configuration now strictly follows:
1. Provided llm_config dictionary (highest priority)
2. Fetch from llm_model_configs system via connector_factory (requires user_id and jwt_token)

This change ensures consistent configuration management and eliminates the outdated environment variable approach. When no configuration is found, a clear ValueError is raised with appropriate error messages.
2026-03-04 12:45:09 +08:00
YueGuobin 2df05dff6e feat(api): nest chat endpoints under projects and refactor dependencies
- Change chat router prefix from `/chat` to `/projects/{project_id}/chat`
- Add `dep_project` dependency to inject Project instance into endpoints
- Remove manual project validation in `stream_chat` and use dependency instead
- Add placeholder `list_sessions` endpoint for future session listing
- Update `get_history` endpoint to use project dependency and adjust path
- Improve code organization and error handling for project retrieval
2026-03-04 12:43:36 +08:00
YueGuobin 479afc01b0 feat(api): add Query parameter description for chat session listing
Add explicit Query parameter with description to the `list_sessions` endpoint for better API documentation and clarity. The `project_id` parameter now includes a descriptive label indicating it is a GNS3 project ID.
2026-03-04 12:35:38 +08:00
YueGuobin 2fe30c69e6 feat(agent): update config parameter type to RunnableConfig in copilot nodes
- Change config parameter type from dict to RunnableConfig | None in llm_call and generate_title functions
- This improves type safety and aligns with LangChain's RunnableConfig usage
- No functional changes, only type annotations updated for better integration
2026-03-04 12:29:31 +08:00
YueGuobin dde2a00c5b feat(agent): update import paths for gns3_copilot modules
Updated import statements across multiple agent files to use absolute paths starting with `gns3server.agent.gns3_copilot` instead of relative `gns3_copilot` imports. This ensures proper module resolution within the gns3-server package structure and prevents import errors when the agent is executed from different contexts.
2026-03-04 12:27:50 +08:00
YueGuobin 73de248381 feat(copilot): add user-aware LLM calls and project cleanup
- Modified `llm_call` and `generate_title` functions to accept `config` parameter, extracting `user_id` and `jwt_token` for per-user LLM configuration and API authentication
- Updated `create_base_model_with_tools` and `create_title_model` calls to pass user authentication details
- Added `jwt_token` to state for tool usage in GNS3 API calls
- Integrated chat router into controller API routes under `/chat` endpoint
- Implemented `_cleanup_copilot_agent` method in `Project` class to remove AgentService resources upon project closure, preventing resource leaks
- Enhanced error handling in agent cleanup to avoid interrupting project close operations
2026-03-04 12:26:19 +08:00
YueGuobin e1f1bb7d9f feat(api): add AI chat API design document for GNS3 Copilot integration
This commit introduces a comprehensive design document outlining the implementation of AI Chat API for GNS3 Copilot Agent within GNS3 Server. The document provides:

- Overview and background on existing components including GNS3 Copilot Agent, LLM configuration management, and API framework
- Reference implementation details from FlowNet-Lab project
- Architecture design with clear component interactions between frontend clients and backend services
- RESTful API specifications for chat streaming, session management, and history retrieval
- Implementation details covering project-based agent management, SQLite checkpoint storage, and LangGraph integration
- Security considerations and deployment guidelines

The design enables clients to interact with GNS3 Copilot Agent through standardized APIs, supporting real-time chat streaming and persistent conversation sessions per project.
2026-03-04 12:08:47 +08:00
YueGuobin a1466dad0d feat(gns3_copilot): remove GNS3UpdateDrawingTool from client exports
Removed GNS3UpdateDrawingTool import and from __all__ list in gns3_client __init__.py to clean up the public interface and eliminate unused or deprecated components.
2026-03-04 01:17:20 +08:00
YueGuobin d525e5cad0 feat: rename FlowNet-Lab to GNS3-Copilot across codebase
Update all references from FlowNet-Lab to GNS3-Copilot in package names, documentation, and logging. This includes:
- Module and package __init__.py files
- License headers and file descriptions
- Log messages and internal comments
- Remove deprecated tools: GNS3CreateAreaDrawingTool and LinuxTelnetBatchTool

The renaming aligns with the project's new branding while maintaining all existing functionality.
2026-03-04 00:55:29 +08:00
YueGuobin 95b309c7af feat: add GNS3 Copilot AI agent dependencies to requirements
Add comprehensive dependencies for the new GNS3 Copilot AI agent feature. This includes:
- Core AI and automation frameworks (LangChain, LangGraph)
- Multiple model provider integrations (OpenAI, Anthropic, Google, AWS, Ollama, DeepSeek, xAI)
- Network automation tools (Netmiko, Nornir)
- Supporting libraries for telnet, HTTP requests, authentication, and image processing

The dependencies are organized into a dedicated section with clear comments for maintainability.
2026-03-04 00:49:46 +08:00
YueGuobin db9db56e7a feat(agent): enhance LLM config loading with priority system
Refactor model factory to support three configuration sources in priority order:
1. Direct llm_config dictionary parameter
2. Fetch from llm_model_configs system via connector_factory (requires user_id and jwt_token)
3. Environment variables as fallback for backward compatibility

This improves flexibility by allowing runtime configuration while maintaining compatibility with existing environment-based setups.
2026-03-04 00:47:35 +08:00
YueGuobin 15dc1e7ea0 feat(agent): remove checkpoint utilities from public API
Removed checkpoint-related imports and exports from the agent package's __init__.py to clean up the public API. This change reduces unnecessary exposure of internal checkpoint utility functions, focusing the public interface on the core agent_builder functionality.
2026-03-04 00:35:15 +08:00
YueGuobin cabcf4f1cb feat(gns3-copilot): add get_gns3_server_host utility and integrate into Nornir tools
- Add `get_gns3_server_host()` function to `connector_factory.py` for extracting GNS3 server hostname from controller, config, or default URL
- Export new function in `__init__.py` for public API access
- Replace `os.getenv("GNS3_SERVER_HOST", "127.0.0.1")` calls with `get_gns3_server_host()` in Nornir configuration tools (`config_tools_nornir.py`, `display_tools_nornir.py`)
- Ensures consistent host detection across tools using the same priority logic as `get_gns3_connector`
2026-03-04 00:28:52 +08:00
YueGuobin 8917ef39c9 feat: remove environment variable usage for Nornir credentials
Removed GNS3_SERVER_USERNAME and GNS3_SERVER_PASSWORD environment variables from Nornir configuration tools. Credentials are now set to empty strings by default, simplifying configuration and removing dependency on environment variables for authentication.
2026-03-04 00:22:47 +08:00
YueGuobin 983ed32663 feat(copilot): refactor prompts module for GNS3 Copilot
- Rename module description from FlowNet-Lab to GNS3 Copilot
- Replace linux_specialist_prompt and experiment_deploy_prompt imports with base_prompt
- Update __all__ export list to include SYSTEM_PROMPT instead of removed prompts
- Improve module docstring with detailed component descriptions and available prompts
- Maintain dynamic version management and module metadata
2026-03-03 23:31:38 +08:00
YueGuobin 4857cff59c feat(agent): refactor LLM configuration to support new llm_model_configs system
- Remove direct logging of LLM config from gns3_copilot.py
- Update model_factory to accept configuration from llm_model_configs dictionary
- Add fallback to environment variables for backward compatibility
- Centralize configuration loading in _load_llm_config function
2026-03-03 23:26:20 +08:00
YueGuobin 3c54a7d90a feat(gns3-copilot): add factory function to create GNS3 connector with LLM config
Introduce `get_gns3_connector_with_llm_config` as a convenience function that combines the creation of a GNS3 API connector and retrieval of the user's default LLM configuration. This simplifies initialization for operations requiring both GNS3 connectivity and AI model settings, reducing boilerplate code in callers. The function returns a dictionary containing the connector and LLM config, or None on failure.
2026-03-03 23:19:00 +08:00
YueGuobin 46b262a02c feat(agent): add gns3-copilot AI assistant integration module
Integrate the gns3-copilot AI assistant module to provide intelligent
   automation and interaction capabilities for GNS3 network emulation.

   Key components:
   - AI agent framework with LLM integration (supports Qwen vision model)
   - GNS3 client library for project topology management
   - Extensive prompt templates for various network operation scenarios
   - Tool library for node creation, linking, configuration, and management
   - Support for English level assessment (A1-C2) and specialized personas
   - Network drawing and topology visualization tools
   - Linux device automation via Nornir/Telnetlib
   - Window controller for UI interaction

   Features:
   - Multi-modal AI agent with vision capabilities
   - Automated network topology deployment and configuration
   - Interactive node and drawing management
   - File-based project operations (read, write, list)
   - Specialized prompts for different scenarios and skill levels
   - Comprehensive tool set for network device management
2026-03-03 23:08:07 +08:00
YueGuobin 7a2d15cb64 feat: clarify default LLM model config selection logic
Updated documentation and implementation to clearly define the priority order for selecting default LLM model configurations. The logic now explicitly states:
1. User's config marked with `is_default: true` (highest priority)
2. Group's config marked with `is_default: true`
3. First config in the list (user configs come before group configs)

This ensures consistent behavior between the API documentation and the actual implementation in the repository code.
2026-03-03 22:56:21 +08:00
YueGuobin f4723cd083 docs: restructure LLM model configs API documentation for nested config object
Update API documentation to reflect new nested `config` object structure in LLM model configurations endpoints. The response format now encapsulates provider-specific fields (provider, base_url, model, temperature, api_key, max_tokens) within a `config` object, while moving ownership metadata (user_id, group_id, is_default, version, created_at, updated_at) to the top level. This aligns the user-facing endpoints with the group configuration structure and improves API consistency.
2026-03-03 22:47:36 +08:00
YueGuobin 176b39145b docs: update LLM model configs API documentation for group endpoints
- Add note clarifying that GET endpoints for groups return the same structure as user endpoints
- Document LLMModelConfigListResponse schema with default configuration selection logic
- Add comprehensive example for GET group configurations endpoint
- Update endpoint numbering to accommodate new group endpoints
- Ensure consistency between user and group API documentation
2026-03-03 22:39:38 +08:00
YueGuobin 2e4c42fadc feat(api): clarify default LLM model config selection logic
- Update API documentation to explicitly describe default configuration selection logic
- Add fallback behavior in repository to use first config when no default is marked
- Clarify difference between `/default` endpoint and `default_config` field
- Document that `default_config` is never null when configs list is not empty
2026-03-03 22:27:28 +08:00
YueGuobin b06593cf2a feat(docs): add default config endpoints and clarify config inheritance
- Add `/default` endpoints for users and groups to retrieve default LLM model configurations
- Update documentation to clarify that users receive both own and inherited configurations
- Improve response examples to show combined configs with source field
- Add 404 response example for missing default configurations
- Fix optimistic locking documentation formatting
2026-03-03 22:15:17 +08:00
YueGuobin 8fb4bf1117 feat(db): manually set timestamps for SQLite compatibility
Add explicit datetime.utcnow() assignments for created_at and updated_at fields in LLMModelConfigsRepository to ensure proper timestamp handling with SQLite. This addresses issues where SQLite may not automatically populate these timestamp fields during create and update operations. Changes applied to both user and group configuration methods for consistency.
2026-03-03 21:35:26 +08:00
YueGuobin aef337e86f feat(config): load secret files even without main config
When no configuration file is found or readable, the server now still loads secret files. This ensures that secret configurations (like API keys or passwords) are available even if the primary config file is missing, improving robustness and security in environments where secrets are stored separately.
2026-03-03 18:16:37 +08:00
YueGuobin 8e43ad4912 feat(db): replace PostgreSQL-specific JSONB with cross-database JSON type
- Change `JSONB` columns to generic `JSON` in LLMModelConfig model for database compatibility
- Update migration to use `sa.String(32)` for UUID and `sa.JSON()` for config fields
- Remove PostgreSQL dialect imports to support multiple database backends
- Keep existing constraints and indexes with PostgreSQL-specific annotations where needed
2026-03-03 18:03:16 +08:00
YueGuobin 3632641127 feat(db): update migration dependency to correct previous revision
The migration file `20260303_create_llm_model_configs_table.py` had an incorrect `down_revision` reference. Changed from `7ceeddd9c9a8` to `98083573d011` to properly link to the previous migration in the Alembic history. This ensures the migration chain is consistent and rollbacks work as expected.
2026-03-03 17:58:48 +08:00
YueGuobin fc7275878e feat(db): replace deferred unique constraints with partial unique indexes for LLM model configs
Replace deferred UniqueConstraints with partial unique indexes for user and group default configurations in the LLM model configs table. This change improves performance and ensures at most one default config per user/group while maintaining data integrity. The migration script has been updated accordingly to create and drop the new indexes.
2026-03-03 17:57:32 +08:00
YueGuobin d42fff49a5 feat(docs): enhance LLM model configs API documentation with schema updates
- Add `model_type` field to database schema with supported values (text, vision, stt, tts, multimodal, embedding, reranking, other)
- Add `name` field as table-level column for indexing and filtering
- Add reserved JSONB fields for future extensibility
- Update API request/response schemas to include `model_type` and `name` fields
- Add new `LLMModelConfigWithSource` schema for detailed configuration responses
- Update usage examples to reflect new required fields
- Improve database constraints and indexing documentation
2026-03-03 17:54:30 +08:00
YueGuobin b968920a75 feat(docs): add optimistic locking documentation for LLM model configs API
Add comprehensive documentation for optimistic locking implementation in the LLM model configurations API. The update includes:

- Added "Optimistic Locking" feature to the overview section
- Added `version` field to the database schema table
- Updated `LLMModelConfigUpdate` schema to include `expected_version` parameter
- Updated `LLMModelConfigResponse` schema to include `version` field
- Added detailed examples for update operations with optimistic locking
- Included conflict handling workflow and client retry instructions

This documentation ensures users understand how to prevent concurrent modification conflicts when updating LLM model configurations.
2026-03-03 17:39:04 +08:00
YueGuobin 161b7feb01 feat(api): add optimistic locking to LLM model config updates
- Include `version` field in all LLM model config response schemas
- Add `expected_version` parameter to update endpoints for optimistic locking
- Handle concurrent modification errors with HTTP 409 Conflict status
- Update both user and group config endpoints consistently
2026-03-03 16:59:12 +08:00
YueGuobin 9315f06e1f feat(config): add encryption key loading for sensitive data
Add a new method `_load_encryption_key` to initialize encryption for sensitive data such as API keys. This method is called within `_load_secret_files` alongside JWT secret key loading, ensuring encryption is set up during server configuration. The change enhances security by enabling encryption for secrets stored in the server's secrets directory.
2026-03-03 16:46:23 +08:00
YueGuobin 8fad27d904 feat(db): improve database initialization and migration handling
- Add smarter database state detection during initialization to handle new databases, existing databases with new features, and old databases needing migration
- Make migration for llm_model_configs table idempotent to prevent conflicts when table already exists from code
- Add detailed logging for different database initialization scenarios
- Import sqlalchemy module for database inspection capabilities
2026-03-03 16:40:57 +08:00
YueGuobin bbd34f1f67 feat(api): add LLM model configurations endpoint and schemas
- Introduce new API route `/access` for managing LLM model configurations
- Add LLMModelConfig model to database models
- Include comprehensive schemas for LLM model config CRUD operations
- Register new router with tags for LLM Model Configurations
2026-03-03 16:34:48 +08:00
Mark Paronyan c48c89d309 tests(compute): test compute works with disabled auth 2026-03-03 00:30:00 +03:00
Mark Paronyan 8c3aaa78f5 feat(compute): option to disable compute authentication 2026-03-03 00:28:57 +03:00
Jeremy Grossmann d3710e8e9a Merge pull request #2621 from markparonyan/issue-2521
handle None port name to prevent TypeError in short_name method
2026-03-01 12:31:17 +08:00
Mark Paronyan 0da1a6639a tests(controller,port): short_name finishes successfully when port name is None 2026-02-28 21:45:08 +03:00
Mark Paronyan 729eb43115 fix(controller,port): handle None port name to prevent TypeError in short_name method 2026-02-28 21:45:00 +03:00
Jeremy Grossmann dce4a71004 Merge pull request #2619 from yueguobin/fix/docker-container-name-conflict
fix(docker): handle container name conflict automatically
2026-02-28 12:56:24 +08:00
grossmj 151feb369f Development on 3.1.0.dev1 2026-02-28 11:35:46 +08:00
YueGuobin ce90b2b92c fix(docker): handle container name conflict automatically
When a Docker container with the same name already exists (e.g., from a
   previous crashed GNS3 session), Docker returns a 409 Conflict error
   when trying to create a new container with that name. This causes the
   project open operation to fail.

   This fix adds automatic cleanup of stale containers when encountering
   a name conflict:
   - Added DockerHttp409Error exception class
   - Updated http_query to detect 409 status codes
   - Modified create() to remove conflicting containers and retry

   Fixes the issue where opening a project fails with:
   "Docker has returned an error: 409 Conflict. The container name
   '/GNS3.xxx' is already in use by container 'xxx'"
2026-02-27 23:35:11 +08:00
Jeremy Grossmann a0116902a6 Merge pull request #2618 from yueguobin/fix-port-nonename-error
feat(virtualbox): add fallback for VBoxManage executable detection
2026-02-27 00:39:31 +08:00
YueGuobin a343ace637 Revert: restore original port name handling logic 2026-02-27 00:12:30 +08:00
YueGuobin fe73d0e935 Merge branch 'fix-vboxmanage-case-sensitivity' into fix-port-nonename-error 2026-02-26 10:02:43 +08:00
YueGuobin c55fd9e066 feat(virtualbox): add fallback for VBoxManage executable detection
Add an additional fallback check for the VBoxManage executable using the capitalized "VBoxManage" command name. This improves compatibility on systems where the executable may be case-sensitive or installed with a different naming convention, ensuring the VirtualBox manager can locate the necessary binary when the lowercase "vboxmanage" is not found.
2026-02-26 09:57:51 +08:00
YueGuobin cde4bdc114 feat: simplify port name assignment logic
Refactor port name assignment to use `or` operator for fallback values, improving code readability and consistency. Changes applied in `node.py` and `port_factory.py` to handle custom adapter settings more cleanly.
2026-02-25 22:41:22 +08:00
YueGuobin f6777064db feat(ports): add null checks for port name in short name generation
Add conditional checks to ensure `self._name` is not None before performing string operations in the `short_name` property. This prevents potential AttributeError exceptions when port name is undefined, improving robustness and compatibility with edge cases in port configuration.
2026-02-25 22:21:05 +08:00
grossmj 4c6d40fd4b Upgrade httpx_ws 2026-02-25 19:20:18 +08:00
grossmj 4a2c1b7b23 Fix installing pytest-asyncio with Python 3.9 2026-02-25 19:06:56 +08:00
grossmj 47a7324eb5 Fix tests 2026-02-25 19:00:57 +08:00
Jeremy Grossmann 4519130a8c Merge pull request #2614 from yueguobin/3.0
Implement tags for nodes and templates
2026-02-25 00:33:15 +08:00
grossmj ef7c271a9a Development on 3.0.7.dev1 2026-02-24 21:32:36 +08:00
grossmj 4d85e517b4 Development on 2.2.57.dev2 2026-02-24 21:21:03 +08:00
grossmj ddacd956b2 Merge remote-tracking branch 'yueguobin/3.0' into fork/yueguobin/3.0 2026-02-23 23:32:15 +08:00
grossmj 547e68fd2b Remove unneeded rbac_repo in get_templates 2026-02-23 23:31:35 +08:00
Jeremy Grossmann 11e36cb32c Merge branch '3.0' into 3.0 2026-02-23 23:28:47 +08:00
grossmj 4d35477e46 Add/fix tests 2026-02-23 23:27:36 +08:00
grossmj a9525503c6 Set up database schema migration 2026-02-23 23:27:10 +08:00
grossmj bdcb6445c7 Use lists for tags instead of dicts 2026-02-23 23:26:42 +08:00
Jeremy Grossmann c49aa761ab Merge pull request #2617 from GNS3/bugfix/2560
Fix for resizing Qemu VMs disks
2026-02-23 17:18:57 +08:00
Jeremy Grossmann c88ac0c595 Merge branch '3.0' into bugfix/2560 2026-02-23 17:14:38 +08:00
grossmj 8f470fbe55 Update FastAPI dependency to support Python 3.9 2026-02-23 17:14:16 +08:00
grossmj c66e851498 Fix for resizing Qemu VM disks 2026-02-23 17:10:15 +08:00
grossmj a6043f0fc6 Upgrade dependencies 2026-02-23 16:48:26 +08:00
Guobin Yue 66f32cecf2 Merge branch 'GNS3:3.0' into 3.0 2026-02-23 01:37:05 +08:00
YueGuobin c05f667f3d feat(templates): safely access settings dict keys
Use dict.get() method to safely access 'image' and 'path' keys in settings dictionary to avoid KeyError exceptions when these keys are missing. This improves error handling and prevents server crashes when creating templates with incomplete settings.
2026-02-23 01:02:32 +08:00
YueGuobin e27ddf2cdf feat(api): fix ETag handling and JSON serialization in template endpoint
- Use `default=str` in `json.dumps` to handle non-serializable objects
- Return proper HTTP 304 response with ETag header instead of raising exception
- Ensure consistent ETag generation for template caching
2026-02-22 23:43:47 +08:00
YueGuobin a3616e6d33 feat(api): add tag filtering to nodes and templates endpoints
- Add optional `tags` query parameter to `/nodes` and `/templates` endpoints
- Support filtering by tags in format "key:value" with multiple tags ANDed together
- Example: `?tags=vendor:cisco&tags=model:7200` filters nodes/templates with both tags
- Maintain backward compatibility for existing API usage without tags parameter
2026-02-22 22:52:28 +08:00
Jeremy Grossmann 22c6b4b961 Merge pull request #2616 from StupidTreee/feature/project-created-by
Add 'created_by' field to track project creator
2026-02-22 18:33:54 +08:00
grossmj be4b87e8cd Update project schema and fix tests 2026-02-22 18:13:08 +08:00
Felix Schulz 8ab34924b5 Add 'created_by' field to track project creator 2026-02-21 22:15:21 +01:00
Jeremy Grossmann 1958deff09 Merge pull request #2615 from GNS3/bugfix/2532
Fix updating packet filters
2026-02-21 21:45:12 +08:00
grossmj 5e3ca29c58 Fix updating packet filters 2026-02-21 21:42:22 +08:00
grossmj 60abbade27 Revert merged changes from 2.2 introduced by PR #2607 2026-02-21 21:35:12 +08:00
YueGuobinandClaude Sonnet 4.5 56ece7ce88 Add vendor, model and netmiko_device_type fields to templates
Add three new optional fields to the template schema:
- vendor: Device vendor (e.g., Cisco, Juniper, Huawei)
- model: Device model (e.g., ISR4451-X, MX204, NE40E)
- netmiko_device_type: Netmiko device type for automation (e.g., cisco_ios, juniper_junos, huawei)

These fields enable AI/LLM integration to determine the appropriate
Netmiko device type when automating network device configuration.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-20 23:38:00 +08:00
grossmj c5b9f379fe Merge remote-tracking branch 'origin/2.2' into 3.0
# Conflicts:
#	Dockerfile
#	dev-requirements.txt
#	gns3server/compute/qemu/qemu_vm.py
#	gns3server/version.py
#	requirements.txt
2026-02-20 16:28:53 +08:00
Jeremy Grossmann 3b95859b79 Merge pull request #2612 from dalearbo/fix/busybox-musl-ldd-check
fix: busybox static link detection on Alpine/musl
2026-02-20 16:01:01 +08:00
Jeremy Grossmann 126a4099e6 Merge pull request #2613 from dalearbo/fix/emit-threadpool-runtime-error
fix: handle RuntimeError in notification_manager emit()
2026-02-20 15:59:01 +08:00
grossmj 47cc827c1f Remove some files not related to PR 2026-02-20 15:56:08 +08:00
grossmj 715b7032bc Fix tests 2026-02-20 15:51:49 +08:00
Jeremy Grossmann bc1729b255 Merge branch '2.2' into fix/busybox-musl-ldd-check 2026-02-20 15:24:54 +08:00
Dale Arbogast 279f05a14a fix: handle RuntimeError in notification_manager emit()
asyncio.get_running_loop() raises RuntimeError when emit() is called
from a thread without an active event loop (e.g. when the disk space
check in project_manager triggers a log.warning notification from a
threadpool worker).

This causes a 500 Internal Server Error on project creation/open when
disk usage is high, instead of the intended warning notification.

Wrap the emit loop in try/except RuntimeError so that notifications
are silently dropped when no event loop is available, rather than
crashing the request.

Fixes #2502
Fixes #2505
2026-02-19 16:49:50 -05:00
Dale Arbogast 3dd4184193 fix: busybox static link detection on Alpine/musl
On musl-based systems (Alpine), ldd returns exit code 0 for static
binaries, unlike glibc which returns 1. This causes install_busybox()
to reject all busybox binaries as "dynamically linked" on Alpine.

Fix by also accepting binaries whose executable name contains "static"
(i.e. busybox-static, busybox.static), which are the first two
candidates checked by the function. The generic "busybox" fallback
still relies on the ldd return code check.
2026-02-19 16:44:01 -05:00
grossmj 013ec341b3 Fix tests 2026-02-16 19:32:47 +08:00
grossmj bfed330ec2 Fix bug when updating compute password to be empty 2026-02-16 19:23:46 +08:00
grossmj 0a118dc9e7 Cancel tasks if controller cannot be started 2026-02-16 19:16:06 +08:00
grossmj 28e7c014c8 Enable parallel compression with zstandard. Fixes #2324 2026-02-16 18:28:11 +08:00
Jeremy Grossmann 2b4a05eedd Merge pull request #2608 from RishikesavanRamesh/patch-1
Add dynamips to Dockerfile dependencies
2026-02-12 21:13:51 +08:00
Jeremy Grossmann 898a9ce208 Merge branch 'master' into patch-1 2026-02-12 21:13:38 +08:00
grossmj 74bc3b5144 Upgrade dependencies 2026-02-11 18:11:16 +08:00
grossmj aabfd08524 Merge remote-tracking branch 'origin/2.2' into 3.0
# Conflicts:
#	CHANGELOG
#	dev-requirements.txt
#	gns3server/crash_report.py
#	gns3server/version.py
#	requirements.txt
2026-02-11 17:52:14 +08:00
grossmj dd87ccff4d Upgrade pytest and jsonschema dependencies 2026-02-11 17:38:49 +08:00
grossmj c1f8202d7c Revert "Upgrade python-multipart to v0.0.22. Fixes #2610"
This reverts commit fdcdce7d0d.
2026-02-11 17:14:03 +08:00
grossmj fdcdce7d0d Upgrade python-multipart to v0.0.22. Fixes #2610 2026-02-11 17:07:28 +08:00
Jeremy Grossmann 78c7d36b1c Merge pull request #2606 from GNS3/release/v2.2.56.1
Release v2.2.56.1
2026-02-11 16:52:43 +08:00
grossmj 44d4a426b5 Upgrade sentry-sdk and psutil dependencies 2026-02-11 16:46:21 +08:00
RishikesavanRamesh 3273f7e992 Add dynamips to Dockerfile dependencies 2026-02-06 20:34:44 +05:30
Jeremy Grossmann d2d19b43c2 Merge pull request #2607 from polsson86/update-pci-device-id-computation
Take populated disks into consideration when calculating PCI device ID
2026-02-06 12:45:30 +08:00
Patrik Olsson fe2014854e Take populated disks into consideration when calculating PCI device ID 2026-02-05 15:10:57 +01:00
grossmj 3915918c41 Release v3.0.6 2026-01-28 22:30:36 +08:00
grossmj a72980b2d9 Sync appliances 2026-01-28 22:24:10 +08:00
grossmj 600d3d38da Fix creating Qemu disk image. Fixes #2542 2026-01-28 19:36:22 +08:00
grossmj ebe4fdc5b5 Development on 2.2.57.dev2 2026-01-28 18:44:51 +08:00
grossmj 7f45cc6f47 Disable checking for available disk space. Ref #2548 2026-01-28 18:32:42 +08:00
grossmj 43d7e8a437 Release v2.2.56.1 2026-01-28 17:00:07 +08:00
grossmj 833b5a9ea8 Sync appliances 2026-01-28 16:52:30 +08:00
grossmj 05dda0117f Merge branch 'master' into 2.2 2026-01-28 16:00:14 +08:00
Jeremy Grossmann 6f0dfecc3d Merge pull request #2605 from iskanred/bugfix/2604
Fix telnet keepalive options on macOS
2026-01-28 15:56:13 +08:00
grossmj abaeab6242 Upgrade greenlet and sqlalchemy dependencies 2026-01-26 19:50:42 +08:00
Iskander Nafikov 2414b7a968 Fix telnet keepalive options on macOS 2026-01-26 00:31:03 +08:00
grossmj 1d45df6613 Upgrade dependencies 2026-01-24 21:38:58 +08:00
grossmj 69a695c9e6 Merge branch '2.2' into 3.0
# Conflicts:
#	dev-requirements.txt
#	gns3server/appliances/infix.gns3a
#	gns3server/crash_report.py
#	gns3server/run.py
#	gns3server/utils/asyncio/__init__.py
#	gns3server/version.py
#	requirements.txt
#	setup.py
2026-01-24 19:27:39 +08:00
grossmj 7b20314edb Delete random_query.py 2026-01-24 19:17:55 +08:00
grossmj 193f470eaf Upgrade dependencies 2026-01-24 19:12:58 +08:00
grossmj 4335fd7ce0 Drop Python 3.8 support 2026-01-24 18:51:44 +08:00
grossmj ef2cf277c1 Development on 2.2.57.dev1 2026-01-24 16:53:43 +08:00
Jeremy Grossmann 66db267e27 Merge pull request #2591 from GNS3/release/v2.2.56
Release v2.2.56
2026-01-24 16:49:35 +08:00
grossmj 27fbe37375 Release v2.2.56 2026-01-21 22:15:12 +08:00
grossmj 7b3fd4450e Sync appliances 2026-01-17 18:37:41 +08:00
grossmj 58d1e8f0c5 Set default location of udhcpc in "/etc/network/udhcpc". Fixes #2582 2026-01-17 18:01:42 +08:00
grossmj 8ce690ce78 Upgrade pywin32 to v311 2026-01-17 17:54:27 +08:00
grossmj c676a5bf82 Development on v2.2.56.dev1 2025-12-16 16:46:31 +08:00
grossmj 60c10e7ecc Merge remote-tracking branch 'origin/2.2' into 3.0
# Conflicts:
#	.github/workflows/testing.yml
#	CHANGELOG
#	README.md
#	gns3server/appliances/infix.gns3a
#	gns3server/compute/docker/__init__.py
#	gns3server/compute/docker/docker_vm.py
#	gns3server/crash_report.py
#	gns3server/version.py
#	gns3server/web/web_server.py
#	setup.py
#	tests/controller/test_project.py
2025-11-29 11:42:02 +10:00
grossmj 37f17209d3 Release v2.2.55 2025-11-19 12:13:56 +10:00
grossmj f24134a8f5 Sync appliances 2025-11-19 12:08:29 +10:00
Jeremy Grossmann 1f2036defd Merge pull request #2575 from GNS3/bugfix/2574
Handle Docker API version requirements
2025-11-17 22:31:41 +10:00
grossmj f2aaf5ab38 Docker API version requirements and process to handle older daemons 2025-11-17 22:26:18 +10:00
Jeremy Grossmann 32f48e555c Merge pull request #2573 from GNS3/bugfix/2541
Python 3.14 compatibility
2025-11-17 11:30:42 +10:00
grossmj 942f021b58 Fix test_config.py 2025-11-17 11:26:06 +10:00
Jeremy Grossmann 4dc321454e Merge pull request #2572 from GNS3/feature/name-of-container-in-docker
Set name of container in Docker
2025-11-17 11:13:47 +10:00
grossmj 3a24318694 Use docker_name property when creating a container 2025-11-17 11:11:11 +10:00
grossmj bae6221991 Set name of container in Docker 2025-11-17 10:59:05 +10:00
grossmj c67ba6da0d Fix config tests 2025-11-17 10:21:12 +10:00
grossmj 4d23ca221f Comment out some tests in test_project.py 2025-11-16 20:52:14 +10:00
grossmj 09eab9529a Fix syntax error in testing.yml 2025-11-16 19:32:19 +10:00
grossmj 3bb23708fc Support for Python 3.14 2025-11-16 19:30:45 +10:00
grossmj 672b3c052b Downgrade aiofiles version 2025-11-16 19:25:12 +10:00
grossmj bfe7b7a735 Upgrade dependencies 2025-11-16 19:16:38 +10:00
Jeremy Grossmann d269a4c125 Merge pull request #2570 from Mytic2330/3.0-patch3
Fixed Connection closed when exporting a running project
2025-11-04 04:07:01 +01:00
Jeremy Grossmann 8ada95b9fd Merge pull request #2569 from Mytic2330/3.0
Fix database pool error and non-ASCII character project export
2025-11-04 04:05:56 +01:00
Bine d5f360c176 Update projects.py 2025-10-18 19:28:15 +02:00
Bine e817228280 Fix non-ASCII characters in project names 2025-10-18 18:10:24 +02:00
BineandUfi 4a059be480 Increase DB engine pool size and max overflow
As described in #2568 when multiple clients connect simultaneously, an excessive number of database pool connections are created. This leads to resource exhaustion and connection management issues.

We have introduced the pool_size and max_overflow parameters to better control the database connection pool.
These parameters ensure the database can handle a sufficient number of concurrent connections without over-allocating resources.

Added pool_size and max_overflow arguments to the database initialization.

This change overrides the default initialization configuration where the temporary fix was applied.

Co-Authored-By: Ufi <86113085+ufiking@users.noreply.github.com>
2025-10-17 22:17:10 +02:00
Jeremy Grossmann 230866890e Merge pull request #2556 from GNS3/bugfix/2543
Enable ip cef in IOU L2 and IOU L3 base configs
2025-09-01 18:59:10 +02:00
grossmj 355cfb7571 Enable ip cef in IOU L2 and IOU L3 base configs 2025-09-01 18:55:36 +02:00
grossmj 8dddfe056e Merge branch 'master' into 2.2 2025-09-01 18:42:02 +02:00
Jeremy Grossmann 9c33827de3 Merge pull request #2555 from GNS3/update-gh-docker-build
Update docker-build.yml
2025-09-01 18:28:04 +02:00
grossmj a34fa53823 Update tags 2025-09-01 18:27:04 +02:00
grossmj 565a76ae27 Only build and push Docker image when releasing a new version 2025-09-01 18:23:52 +02:00
grossmj dc9c3b1c5d Fix pushing Docker image to Docker hub 2025-09-01 18:17:52 +02:00
grossmj a394fb71dc Update method to login to ghcr.io 2025-09-01 17:55:46 +02:00
grossmj 6cbf3baa1b Update docker-build.yml 2025-09-01 17:49:34 +02:00
grossmj 10322135e3 Upgrade sentry-sdk package 2025-08-30 21:51:20 +02:00
grossmj 12d1d04462 Update security issues again in README.md. Fixes #2535 2025-08-29 18:28:14 +02:00
grossmj 8b4c2f5e90 Update security issues in README.md. Fixes #2535 2025-08-29 18:25:57 +02:00
grossmj 1ed549fdb1 Upgrade requests dev dependency 2025-08-29 14:01:19 +02:00
grossmj 845cad35f0 Upgrade pydantic, fastapi & sqlalchemy dependencies 2025-08-29 13:55:00 +02:00
grossmj 31613630cf Update pyproject.toml to support LICENSE file 2025-06-09 22:24:23 +02:00
Jeremy Grossmann aaffc731ee Merge pull request #2538 from Nick1200000/enhancement/docker-build
Add automated Docker build and publish workflow
2025-06-09 22:14:11 +02:00
Nick1200000 5ce55aff02 Resolving the Error 2025-06-08 14:11:01 +05:30
Nick1200000 aa1c0bb557 Resolving the Errors 2025-06-08 13:38:35 +05:30
Nick1200000 25bc2dce57 Resolving the Errors 2025-06-08 13:30:49 +05:30
Nick1200000 7e35d164dc Resolving the Errors 2025-06-08 13:26:40 +05:30
Nick1200000 8666ffaff3 Resolving the Errors 2025-06-08 13:24:38 +05:30
Nick1200000 020f6a123d Docker build CI/CD pipeline 2025-06-07 18:16:47 +05:30
grossmj 232b9c2806 Fix tests 2025-05-25 17:35:45 +02:00
Jeremy Grossmann f260f6e2b4 Merge pull request #2531 from PsyBlade42/docker-vnc-name
use GNS3 node name as vnc Desktop name
2025-05-23 14:26:08 +02:00
Thomas Schmidt a7108e1592 use GNS3 node name as vnc Desktop name
Most VNC clients use the Desktop name in their window title.
Currently this defaults to user@host which means all docker vnc
connections have identical window names of e.g.
  SSVNC: gns3@gns3server

This uses the node name instead.
2025-05-22 13:13:47 +02:00
grossmj 975ca254fd Release v3.0.5 2025-05-14 19:11:44 +02:00
grossmj 89cf5ea8e7 Bundle web-ui v3.0.5 2025-05-14 19:06:42 +02:00
grossmj bfbe2bf885 Sync appliances 2025-05-14 18:55:51 +02:00
grossmj 5c036dfd90 Upgrade uvicorn and pydantic 2025-05-14 18:54:55 +02:00
grossmj 2fbfe5385a Use Ubuntu 24.04 LTS in Dockerfile. Ref #2523 2025-05-14 18:30:43 +02:00
grossmj 2cdaa1cd06 Fix tests 2025-05-14 17:19:18 +02:00
grossmj f2080979a1 Fix tests 2025-05-14 16:56:46 +02:00
grossmj df576f0668 Merge remote-tracking branch 'origin/2.2' into 3.0
# Conflicts:
#	gns3server/compute/qemu/qemu_vm.py
#	gns3server/schemas/template.py
2025-05-14 16:42:59 +02:00
grossmj c2c89b0ff3 Add missing 'nat' template type in schema. Fixes #2529 2025-05-13 20:52:44 +02:00
grossmj ef3570dc95 Merge branch 'master' into 2.2 2025-05-13 20:48:59 +02:00
grossmj 2bf3eff143 Remove debug message in tests 2025-05-13 20:47:38 +02:00
Jeremy Grossmann add8c4e8a2 Merge pull request #2526 from emmanuel-ferdman/master
Resolve deprecation warnings of regex library
2025-04-30 14:14:37 +07:00
Jeremy Grossmann 53eac771d6 Merge pull request #2528 from tobiasstein/fix-pci-bridges
Fix adding pci_bridges to qemu vms
2025-04-30 14:09:22 +07:00
grossmj 2b96e54629 Fix tests and require Qemu version >= 2.4 2025-04-30 13:38:52 +07:00
Tobias Stein cdf819f820 Fix adding pci_bridges to qemu vms
* Offset pci_device_id for network devices by 32 (formerly 4)
  to reserve first 32 IDs for non-netdev devices
  * This implies a new pci_bridge for the netdevs and
    the pci_device_ids starting at 0 (using modulo)
  * Fixes a bug in the creation of the qemu command
    when the number of qemu pcie devices (storage_controller, disks, …)
    was greater than 4 and the number of network devices
    saturated the 32 pcie ids of the root bridge
    causing qemu not to start.
2025-04-28 21:07:52 +02:00
Emmanuel Ferdman c05e6f4de4 Resolve deprecation warnings of regex library
Signed-off-by: Emmanuel Ferdman <emmanuelferdman@gmail.com>
2025-04-26 00:15:16 -07:00
grossmj d9dcc2738d Merge remote-tracking branch 'origin/2.2' into 3.0
# Conflicts:
#	CHANGELOG
#	Dockerfile
#	README.md
#	gns3server/appliances/infix.gns3a
#	gns3server/compute/docker/docker_vm.py
#	gns3server/compute/qemu/qemu_vm.py
#	gns3server/controller/gns3vm/virtualbox_gns3_vm.py
#	gns3server/crash_report.py
#	gns3server/static/web-ui/index.html
#	gns3server/static/web-ui/main.9bcf455e62558dedfd48.js
#	gns3server/version.py
2025-04-21 20:13:31 +07:00
grossmj e32576d5ed Development on 2.2.55.dev1 2025-04-21 19:35:13 +07:00
Jeremy Grossmann bd3657d8f3 Merge pull request #2524 from GNS3/release/v2.2.54
Release v2.2.54
2025-04-21 19:30:57 +07:00
grossmj 4418d6bb2b Release v2.2.54 2025-04-21 17:15:22 +07:00
grossmj dbcafdd314 Merge branch 'master' into 2.2 2025-04-21 17:08:59 +07:00
grossmj 4dd1803a70 Bundle web-ui v2.2.54 2025-04-21 16:40:59 +07:00
grossmj 99272fb7e0 Sync appliances 2025-04-21 16:30:32 +07:00
grossmj a24d2e25ed Add new method to find the IP address of a VBox GNS3 VM + allow NAT Network 2025-04-21 16:29:32 +07:00
grossmj a5a663bc99 Remove OVMF_CODE_4M.secboot.fd and associated code 2025-04-18 17:31:31 +07:00
grossmj 2b7eb91694 Add edk2-stable202502 UEFI firmwares and try to first use firmwares from the ovmf package if installed. Fixes #2494 2025-04-18 17:13:29 +07:00
grossmj 684770a220 Prettify TPM error message 2025-04-18 15:25:50 +07:00
grossmj f6546bf1de Fix bug in qemu_stdout message 2025-04-18 15:19:06 +07:00
grossmj 355b97398b Reduce matching error for TPM result 2025-04-18 15:13:41 +07:00
grossmj 6242a0be80 Try to detect swtpm and AppArmor issue. Ref https://github.com/GNS3/gns3-gui/issues/3725 2025-04-18 15:06:49 +07:00
grossmj 18413c923c Development on 2.2.54.dev1 2025-04-18 15:05:34 +07:00
grossmj ffd628902c Fix Docker logs decoding. Ref #2522 2025-04-18 13:58:56 +07:00
grossmj ca34053125 Add delay after starting a Docker container and adding connections in uBridge. Ref #2522 2025-04-18 13:50:20 +07:00
grossmj d06f93e772 Fix TypeError when reading Docker container logs. Ref #2522 2025-04-18 13:47:29 +07:00
grossmj 90cf73e434 Fix tests 2025-04-18 13:38:01 +07:00
grossmj aa8ccf4f82 Allow an image to be uploaded to the controller again even if it is already in the database 2025-04-17 19:07:22 +07:00
grossmj 0826b9c259 Fix controller not reporting an error if invalid options are passed to Qemu command line. Fixes #2517 2025-04-17 19:00:52 +07:00
grossmj 0e8d969cd2 Merge branch '2.2' into 3.0
# Conflicts:
#	gns3server/compute/docker/__init__.py
#	gns3server/compute/docker/docker_vm.py
#	requirements.txt
2025-04-16 17:53:44 +07:00
grossmj 0e89ff56a8 Replace "Docker hub" by "Docker repository" because it is possible to use different repositories 2025-04-16 17:42:40 +07:00
grossmj ffb5bc7ffd Upgrade aiohttp to v3.11.16 2025-04-16 17:09:09 +07:00
grossmj f00f21c4bd Upgrade dependencies 2025-04-16 17:08:08 +07:00
grossmj 773076c40e Fix unable to add NAT cloud after configuring “allowed_interfaces” in configuration file. Fixes #2508 2025-04-16 16:04:57 +07:00
grossmj 5019167098 Fix interface information API endpoint for Cloud/NAT devices 2025-04-16 15:26:56 +07:00
grossmj f525916195 Merge remote-tracking branch 'origin/3.0' into 3.0 2025-04-16 14:39:59 +07:00
grossmj 2ac3e0b39f Upgrade dependencies 2025-04-16 14:39:36 +07:00
Jeremy Grossmann e532c83538 Merge pull request #2518 from markparonyan/get-link-ifaces
Get iface/udp tunnel from links with Cloud,Nat
2025-03-23 20:10:23 +07:00
Mark Paronyan f21887dbab tests(get_iface): add unittests 2025-03-23 14:28:58 +00:00
Mark Paronyan bab173ee52 feat(get_iface): add type information in response 2025-03-23 14:28:27 +00:00
Mark Paronyan ea2856289a feat: add endpoint to get iface/udp tunnel from links with Cloud,Nat 2025-03-23 13:46:27 +00:00
grossmj 8e6f5d2b57 Merge branch '2.2' into 3.0
# Conflicts:
#	requirements.txt
2025-03-18 21:34:43 +07:00
grossmj 2e9127449c Upgrade Jinja2 to v3.1.6. Fixes #2515 2025-03-18 21:33:31 +07:00
grossmj ee9f974362 Fix packet capture for links connected to a cloud node. Fixes #2513 2025-03-16 21:12:33 +07:00
grossmj c9231d7b83 Upgrade dependencies 2025-03-16 20:26:26 +07:00
Jeremy Grossmann 483719568f Merge pull request #2511 from NAKNAO-nnct/feature/update-dockerfile-ubuntu-2404
Update Dockerfile base image to Ubuntu 24.04
2025-03-08 20:26:12 +07:00
NAKNAO-nnct 018598a300 refactor 2025-03-08 20:22:06 +09:00
NAKNAO-nnct e262a46cfd rm space 2025-03-08 20:19:37 +09:00
NAKNAO-nnct 00bf1c028b Update README to Run Docker Compose 2025-03-08 14:11:42 +09:00
NAKNAO-nnct 21ebb934f4 add compose.yaml 2025-03-08 14:08:42 +09:00
NAKNAO-nnct 2ecd2cfe3b update Ubuntu24.04 2025-03-08 13:59:05 +09:00
Jeremy Grossmann ce4b3091dd Merge pull request #2507 from GNS3/fix-remote-install-script
Improvements for remote-install.sh
2025-03-03 05:55:42 +07:00
grossmj f722816849 Improvements for remote-install.sh
* Use apt-add-repository to install repository
* Add option to not upgrade the system
* Check if Python version is >= 3.9 when installing from ppa-v3 repository
2025-03-02 22:27:53 +07:00
Jeremy Grossmann 4cb38b23eb Merge pull request #2506 from FedericoTorres233/patch-1
Check if remote-install.sh is being run as root
2025-03-02 16:14:33 +08:00
Federico Torres f3e46227d8 fix: check if remote-install.sh is being run as root 2025-03-01 16:56:21 -03:00
grossmj 3ba109c651 Development on 3.0.5.dev1 2025-02-25 22:39:38 +08:00
Jeremy Grossmann 185cd01e19 Merge pull request #2488 from GNS3/release/v2.2.53
Release v2.2.53
2025-01-21 09:47:43 +07:00
988 changed files with 248101 additions and 57505 deletions

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
# GNS3 Server Project Memory
> **Note**: This directory stores important project-related memories and case studies, managed with the code repository.
>
> **How to record**: Use the `/memory` skill to record important information to the project memory directory.
## Quick Reference
- **Memory directory**: `.claude/memory/`
- **Skill file**: `.claude/skills/memory/SKILL.md`
- **Main index**: `MEMORY.md` (this file)
## Topics
### Web Wireshark Integration
- **[JWT Token Flow](./web-wireshark-jwt-token-flow.md)** - JWT token transmission path in Web Wireshark
- Key point: UDPLink only passes through jwt_token, ultimately used by curl command inside Web Wireshark container to authenticate with GNS3 capture stream API
- **[Xpra HTML5 Client](./xpra-html5-client.md)** - Xpra HTML5 client menu control parameters for customizing the web interface
### RBAC & User Isolation
- **[RBAC User Isolation Design](./rbac-user-isolation-design.md)** — Three-step permission check design: ACE batch check → created_by filtering → resource pools
### Appliance Management
- **[GNS3 Appliance Loading](./gns3-appliance-loading.md)** - How GNS3 loads appliance files from builtin and custom directories with priority rules
### uBridge Permission
- **[uBridge Permission Issue](./gns3-ubridge-permission.md)** - Docker containers fail to start due to missing CAP_NET_ADMIN/CAP_NET_RAW capabilities on uBridge
- **[Docker iptables FORWARD blocks bridge](./docker-iptables-forward-bridge.md)** - Docker sets FORWARD chain to DROP, blocking kernel bridge forwarding; `sudo iptables -P FORWARD ACCEPT` to fix
### Docker Container Stop Delay
- **[Docker Container Stop Delay](./docker-container-stop-delay.md)** - Some containers take ~5s to stop because they don't handle SIGTERM (AlpiNet, OstinatoWireshark)
### Device Console / Copilot Known Bugs
- **[XRd Console --More-- Pager Bug](./xrd-console-more-pager-bug.md)** - FIXED: root cause was our own 80x24 initial PTY geometry for the docker_exec console (the XR pager reads PTY rows, not `terminal length`); initial geometry is now 511x10000. Copilot reconnect-before-retry + session_log still open; `--More--` auto-answer kept as fallback design
### MCP Service
- **[MCP Service Design](./mcp-service-design.md)** - MCP (Model Context Protocol) service architecture using FastMCP with SSE transport, JWT auth, 29 tools across 5 domains
- **[MCP Tool Description Location](./mcp-tool-description-guide.md)** - Where to define MCP tool descriptions: in `@mcp.tool()` functions in `__init__.py`, not in `*_TOOLS` arrays
### Python Code Verification
- **[Import Validation](./python-import-validation.md)** - Use actual module imports (`python -c "from ... import ..."`) instead of `py_compile` to catch missing imports
@@ -0,0 +1,41 @@
---
name: docker-container-stop-delay
description: Docker containers not responding to SIGTERM cause ~5s stop delays when closing a project
metadata:
type: reference
---
# Docker Container Stop Delay Analysis
## Background
When stopping a GNS3 project, some Docker containers take ~5s to exit while others stop instantly.
## Root Cause
Docker's `stop` command sends SIGTERM and waits `t` seconds (GNS3 sets `t=5`) before sending SIGKILL. Containers that don't handle SIGTERM are stuck waiting for the full timeout.
## Affected Containers
| Container | PID 1 | Why it's slow |
|-----------|-------|---------------|
| **AlpiNet** (alpine) | `dumb-init` → `bash -i` | Interactive bash ignores SIGTERM by design |
| **OstinatoWireshark** | `bash` (PID 1) | Linux kernel won't apply default signal actions to PID 1 without an explicit handler; interactive bash doesn't install one |
## Normal Containers (for comparison)
| Container | PID 1 | Why fast |
|-----------|-------|----------|
| Chromium | `/usr/bin/chromium` | Chromium handles SIGTERM natively |
| webterm | `dumb-init` → firefox | Firefox responds to SIGTERM immediately |
## Related Files
- `gns3-registry/docker/alpinet/Dockerfile`
- `gns3-registry/docker/ostinato-wireshark/Dockerfile`
- `gns3-registry/docker/ostinato-wireshark/entry.sh`
- `gns3-registry/docker/chromium/Dockerfile`
- `gns3-registry/docker/ipterm/web/Dockerfile`
- `gns3-server/gns3server/compute/docker/docker_vm.py:1040` — stop timeout parameter `t=5`
## Note
This is not a GNS3 server bug (except a minor `or` vs `and` logic issue at `docker_vm.py:1037` which doesn't affect behavior). The root cause is in the Docker images themselves.
See also: [[docker-container-stop-delay]]
@@ -0,0 +1,38 @@
---
name: docker-iptables-forward-bridge
description: Docker iptables FORWARD DROP blocks kernel bridge forwarding, fix and symptoms
metadata:
type: reference
---
Docker sets the iptables `FORWARD` chain default policy to `DROP` when the
Docker daemon starts. This blocks **all** forwarded traffic through Linux
kernel bridges on the host — including `gns3br{N}` bridges created by the
builtin Ethernet Switch (ubridge `brctl`).
## Symptoms
- Nodes connected to the switch can send frames into the bridge (visible in
`tcpdump -i gns3br{N}`) but never receive forwarded unicast frames.
- `bridge fdb show` may fail to learn MAC addresses (frames dropped before
the bridge learning path).
- ARP and multicast/broadcast may appear to work because they flood, but
unicast replies never reach the destination.
- OSPF Hello / CDP visible on both sides but ICMP echo reply never returns.
- `ubridge bridge get_stats` shows symmetric IN/OUT counts (relay is fine),
`bridge fdb show` shows learned MACs, `bridge link show` shows `state forwarding`
on all ports — yet unicast still doesn't work.
## Fix
Run once per host boot, or make persistent via iptables-persistent / firewall config:
```bash
sudo iptables -P FORWARD ACCEPT
```
## Related
- [[ethernet-switch-ubridge-brctl-migration]] — the kernel bridge that hits this
- [[gns3-server-linux-only]] — datapath constraint
- [[gns3-ubridge-permission]] — another host-level prerequisite (CAP_NET_ADMIN)
+20
View File
@@ -0,0 +1,20 @@
---
name: gns3-appliance-loading
description: GNS3 appliance file loading mechanism and storage locations
metadata:
type: reference
---
GNS3 loads appliance (.gns3a) files from two locations with specific priority order:
1. **Builtin appliances directory**: `~/.local/share/GNS3/appliances/`
- Stores automatically downloaded devices from GNS3 registry
- Maintained and updated by the system automatically
2. **Custom appliances directory**: `~/GNS3/appliances/`
- Stores user-customized or modified appliance files
- Manually managed by users
**Loading priority**: System loads builtin appliances first, then custom appliances. If both directories contain devices with the same `device_id`, the custom appliance overwrites the builtin one. This design allows users to customize devices without having their modifications overwritten by automatic registry updates.
**Implementation**: See `gns3server/controller/appliance_manager.py` in the `load_appliances()` method (lines 314-351).
+25
View File
@@ -0,0 +1,25 @@
# GNS3 uBridge Permission Issue
## Problem
Docker container node fails to start with error: `uBridge requires root access or the capability to interact with network adapters`
## Root Cause
- uBridge needs to create TAP network interfaces to connect Docker containers to GNS3 virtual network
- This requires `CAP_NET_ADMIN` and `CAP_NET_RAW` capabilities
- Other node types (like QEMU) may have their own network implementation and don't need uBridge
## Solution
```bash
sudo setcap cap_net_admin,cap_net_raw=eip /usr/bin/ubridge
```
## Code Locations
- uBridge path check: `gns3server/compute/base_manager.py:298` (`has_privileged_access`)
- Permission check call: `gns3server/compute/base_node.py:851`
- Error message definition: `gns3server/compute/base_node.py:852`
## Error Propagation Flow
Error is propagated via `NodeError` exception:
1. `NodeError` is caught at `gns3server/api/routes/compute/__init__.py:131-137`
2. Returns HTTP 409 with JSON: `{"message": "...", "exception": "NodeError"}`
3. Frontend should read error info from `message` field
+88
View File
@@ -0,0 +1,88 @@
---
name: mcp-service-design
description: MCP (Model Context Protocol) service architecture and tool design for GNS3 server
metadata:
type: project
---
# MCP (Model Context Protocol) Service Design
## Background
Provide a standard MCP interface for GNS3 Server, allowing AI assistants (Claude Code, Claude Desktop) to interact with GNS3 network simulations through the Model Context Protocol.
## Decision/Implementation
### Transport
- **SSE (Server-Sent Events)** with JWT token authentication
- Endpoint: `/v3/mcp/transport/sse`
- Message endpoint: `/v3/mcp/transport/messages/`
### Authentication
- JWT token obtained via `/v3/access/users/authenticate`
- Two ways to pass token:
- `Authorization: Bearer <jwt>` header (Claude Code via `-H`)
- `?token=<jwt>` query param (Claude Desktop, EventSource limitation)
- Token validated using GNS3's existing `auth_service`
- Token stored in `contextvars.ContextVar` for per-session isolation
- Python ≥ 3.9 `asyncio.to_thread` propagates contextvars to threads
### Architecture
```
Claude Code / Desktop → SSE → Auth Wrapper → FastMCP Server → Tool Handler → Gns3Connector → GNS3 REST API
```
### Tool Organization
Tools are separated by domain into individual files under `gns3server/api/routes/mcp/`:
| File | Domain | Tool Count |
|------|--------|:----------:|
| `projects.py` | Project CRUD, open/close/stats | 7 |
| `nodes.py` | Node CRUD, start/stop/reload/suspend, console WS | 10 |
| `links.py` | Link CRUD | 5 |
| `templates.py` | Template CRUD | 5 |
| `computes.py` | Compute list/get/images | 3 |
**Total: 30 tools**
### Handler Pattern
- Synchronous functions receiving `(params: dict, gns3_ctx: dict)`
- Run via `asyncio.to_thread()` to avoid blocking the event loop
- `gns3_ctx` contains `server_url` and `jwt_token`
- `Gns3Connector` is created per-handler from `gns3_client.connector` (per-handler instantiation keeps each tool call isolated)
### Token Lifetime
- Default: 1440 minutes (24 hours)
- Configurable via `jwt_access_token_expire_minutes` in `gns3_server.conf`
## Rationale
- **Why not Direct Controller calls**: MCP layer calls GNS3's own REST API through Gns3Connector, keeping full decoupling and supporting future multi-user/multi-instance scenarios
- **Why not Streamable HTTP**: Claude Code supports SSE natively via `--transport sse` with custom headers; Streamable HTTP session manager lifecycle conflicts with FastAPI mount
- **Why not stdio**: stdio is local-only; SSE supports both local and remote deployments
## Related Files
- `gns3server/agent/mcp/__init__.py` — FastMCP server, `@mcp.tool()` decorators, auth wrapper (`_resolve_token` exchanges API keys for JWTs)
- `gns3server/agent/mcp/*.py` — tool handlers for projects/templates/computes/snapshots/drawings/symbols/appliances/images
- `gns3server/agent/gns3_copilot/gns3_client/api_handlers.py` — shared node/link handler layer (single implementation, consumed by both MCP tools and copilot `tools_v2`; tests must patch `_get_connector` HERE, not in mcp modules)
- `gns3server/agent/gns3_copilot/gns3_client/connector.py` — Gns3Connector (JWT auth + http_call only; the old `custom_gns3fy.py` Node/Link/Project wrappers were removed)
- `gns3server/agent/gns3_copilot/gns3_client/project_inventory.py` — nodes/links aggregation feeding the topology context and Nornir inventory
## Configuration
### Claude Code
```bash
claude mcp add --transport sse My_GNS3_Server \
http://host:3080/v3/mcp/transport/sse \
-H "Authorization: Bearer <jwt>"
```
### Claude Desktop
```json
{
"mcpServers": {
"My_GNS3_Server": {
"url": "http://host:3080/v3/mcp/transport/sse?token=<jwt>"
}
}
}
```
@@ -0,0 +1,43 @@
---
name: mcp-tool-description-location
description: Where to define MCP tool descriptions so AI can see them
metadata:
type: reference
---
# MCP Tool Description Location
## Key Point
MCP tool descriptions are defined in `@mcp.tool()` decorator functions in `__init__.py`, NOT in the `*_TOOLS` arrays in individual module files.
## Correct Location
**File**: `gns3server/api/routes/mcp/__init__.py`
**Example**:
```python
@mcp.tool()
async def update_link(
project_id: Annotated[str, Field(description="UUID of the project")],
link_id: Annotated[str, Field(description="UUID of the link to update")],
**kwargs: Any,
) -> list[dict[str, Any]]:
"""Update a link's properties.
Put detailed descriptions here, especially for complex parameters.
Include format requirements, ranges, and examples.
"""
# implementation
```
## Wrong Location
- ❌ `LINK_TOOLS` in `gns3server/api/routes/mcp/links.py`
- ❌ `TEMPLATE_TOOLS` in `gns3server/api/routes/mcp/templates.py`
## Activation
**Must restart GNS3 server** for description updates to take effect.
## Description Requirements
- Be explicit about data formats (arrays vs single values)
- Include parameter ranges and constraints
- Provide usage examples
- Prevent common errors in the description itself
@@ -0,0 +1,30 @@
# Python Import Validation
## Background
When checking if modified Python code is correct, `py_compile` only validates syntax (e.g., balanced parentheses, valid keywords). It does **not** catch missing imports or other runtime errors (e.g., using `UUID()` without importing `UUID`).
## Decision/Implementation
Use actual module imports to verify code correctness:
```bash
# ✅ This catches missing imports and runtime errors
venv/bin/python -c "
from gns3server.api.routes.controller.dependencies.authentication import get_user_from_token
from gns3server.api.routes.mcp.__init__ import _resolve_token
print('All imports OK')
"
# ❌ This only checks syntax, not references
venv/bin/python -c "import py_compile; py_compile.compile('file.py', doraise=True)"
```
## Related Files
`gns3server/api/routes/controller/dependencies/authentication.py` — missed `from uuid import UUID`
`gns3server/api/routes/mcp/__init__.py` — missed `from uuid import UUID`
## Why
A `NameError` at runtime is far more expensive than a failed import check. Real import testing catches the full dependency chain.
@@ -0,0 +1,231 @@
---
name: rbac-user-isolation-design
description: GNS3 RBAC user isolation design and implementation thought process
metadata:
type: project
---
## RBAC User Isolation Design Summary
### Core Problem
GNS3 3.0 has a complete RBAC framework (ACE + Role + Privilege), but lacks user isolation implementation, causing users to see resources they shouldn't have access to.
### Design Conflict
Traditional RBAC's **path permission model** fundamentally conflicts with **user data isolation**:
- **Path permission model**: Controls which paths users can access (e.g., `/projects`)
- **User data isolation**: Controls which specific resources users can access (e.g., alice's project vs bob's project)
### Final Implementation Approach
#### Three-Step Permission Check Logic
```python
# Step 1: Batch ACE + resource pool check (3 DB queries regardless of project count)
direct_ace_ids, pool_accessible_ids = await rbac_repo.get_accessible_project_ids(
current_user.user_id, "Project.Audit", all_project_ids
)
# Step 2: Filter direct ACE projects by created_by (user's own projects)
# Direct project sharing is only available through resource pools
for p in controller.projects.values():
if p.id in direct_ace_ids and p.created_by == current_user.username:
projects.append(p.asdict())
# Step 3: Resource pool projects (no created_by filter)
for p in controller.projects.values():
if p.id in pool_accessible_ids:
projects.append(p.asdict())
```
##### Super Admin Bypass
```python
if current_user.is_superadmin:
return [p.asdict() for p in controller.projects.values()]
```
Super admins skip all three steps and see every project.
##### seen_project_ids Deduplication
A simple `seen_project_ids` set prevents the same project from appearing twice when it exists in both direct ACE and pool results. This is a lightweight dedup, not the complex blocking mechanism from earlier rejected designs.
### Key Design Decisions
#### 1. ACE vs created_by Relationship
- **ACE for basic access control**: Whether user can access the system
- **created_by for user isolation**: Which specific resources user can access
- **Step 2 filtering is critical**: Even with broad ACE, created_by filtering ensures user isolation
#### 2. Project Sharing Mechanism
- **Project sharing only through resource pools**: Cannot configure ACE directly for specific projects
- **Avoids complexity of direct ACE sharing**: Prevents permission configuration chaos
#### 3. Broad ACE Fault Tolerance
```
Even with configuration: ACE: Users group + User role + "/" + propagate: True
Result: Users still only see projects they created
Reason: Step 2 created_by filtering removes other users' projects
```
### RbacRepository.get_accessible_project_ids()
The core batch-check method in `gns3server/db/repositories/rbac.py` uses 3 DB queries:
1. **User ACEs**: Direct ACE entries matching user + privilege
2. **Group ACEs**: Group-level ACE entries via `UserGroup` membership
3. **All resources with pool memberships**: Preloads all resources and their pool relationships
Then it computes two sets:
- **`direct_ace_ids`**: Project paths matching user or group ACEs (path-based check)
- **`pool_accessible_ids`**: Projects in pools the user/group can access (pool-based check)
Pool IDs are precomputed into a `pool_id -> set(project_ids)` map for O(1) lookup.
### Problems Solved
#### Problem 1: Missing User Isolation
- **Issue**: All users can see all projects
- **Solution**: Filter by created_by to implement user isolation
#### Problem 2: Broad ACE Breaking Isolation
- **Issue**: `path: "/" + propagate: true` breaks user isolation
- **Solution**: Step 2 created_by filtering ensures user isolation even with broad ACE
#### Problem 3: Permission Check Order Conflicts
- **Issue**: seen mechanism blocks subsequent checks (from earlier design phases)
- **Solution**: Simple pipeline-style filtering with lightweight dedup set
### Technical Details
#### API Layer Permission Check
```python
@router.get("/projects") # Note: no has_privilege decorator
async def get_projects(current_user=..., rbac_repo=...):
# Permission checks in business logic
```
#### Duplicate Prevention
- Simple `seen_project_ids` set for deduplication between direct ACE and pool results
- Not the complex blocking mechanism from earlier phases
#### Performance Considerations
- Super admin path: O(1) — returns all projects directly
- Regular user path: 3 fixed DB queries regardless of project count
- Path-based ACE check: O(n * m) in worst case, where n = projects, m = ACE entries
- Pool lookup: O(1) via precomputed pool->project map
### Use Cases
#### Scenario 1: Personal Use
```
alice creates project → alice only sees alice's projects ✅
bob creates project → bob only sees bob's projects ✅
No extra configuration needed, automatic user isolation
```
#### Scenario 2: Team Collaboration
```
Admin creates resource pool → adds projects → team members can access
alice creates project → alice still sees her own projects ✅
Team sharing + user isolation coexist
```
#### Scenario 3: Broad ACE Configuration
```
ACE: Users group + "/" + propagate: True
alice still only sees alice's projects ✅
User isolation unaffected by ACE configuration
```
### Design Principles
#### 1. Separation of Concerns
- **Basic access permission**: Controlled by ACE
- **Data ownership**: Controlled by created_by
- **Team sharing**: Controlled by resource pools
#### 2. Defensive Design
- User isolation remains effective even with improper ACE configuration
- Secure by default: users only see their own resources
#### 3. Simplicity
- Avoid complex seen mechanisms and mutual exclusion logic
- Clear pipeline-style check order
### Relationship with Original ACE System
#### Preserved Components
- ✅ ACE framework (permission check mechanism)
- ✅ Role and privilege definitions
- ✅ Resource pool functionality
#### Improved Components
- ✅ Added user isolation (created_by filtering)
- ✅ Clarified project sharing mechanism (only through resource pools)
- ✅ Simplified permission check logic
#### Removed Components
- ❌ Removed `/projects` path privilege check on `get_projects` route
- ❌ Removed the old complex `seen_project_ids` blocking mechanism
- ❌ Avoided "can see all non-pool projects" privilege leak
### Implementation Details
- **Main modification**: `gns3server/api/routes/controller/projects.py`
- **Function**: `get_projects()`
- **Batch check method**: `gns3server/db/repositories/rbac.py::RbacRepository.get_accessible_project_ids()`
- **Privilege dependency**: `gns3server/api/routes/controller/dependencies/rbac.py::has_privilege()`
- **Branch**: `feature/simple-user-isolation`
- **Base branch**: `master`
### Key Commits
1. Implemented basic created_by filtering
2. Implemented three-layer permission check (with logic issues)
3. Fixed to correct three-step check logic
### Design Evolution Process
#### Phase 1: Simple created_by Filtering
```python
user_projects = [p for p in all_projects() if p.created_by == user.username]
```
**Issue**: Didn't integrate with ACE system
#### Phase 2: Three-Layer Check (Wrong Version)
```python
# Used complex seen_project_ids blocking mechanism
# Issue: Broad ACE breaks user isolation
```
#### Phase 3: Three-Step Check (Correct Version)
```python
# Step 1: Batch ACE check via get_accessible_project_ids()
# Step 2: Filter direct_ace_ids by created_by
# Step 3: Resource pool projects (no created_by filter)
```
**Solution**: User isolation works even with broad ACE
### Relationship with RBAC Roadmap
This implementation addresses items mentioned in the roadmap:
- **Phase 1 (MVP)**: Basic project isolation implementation
- **Auto-ACE on create**: Still needs to be implemented separately
- **Template isolation**: Can use same design pattern
### Unsolved Issues
1. **Auto-ACE on project creation**: Part of roadmap Phase 1 — `create_project()` sets `created_by` but doesn't create ACE entries
2. **Template and image isolation**: Can apply same design pattern
3. **Default ACE configuration**: Need reasonable default permissions for Users group
### Design Limitations
1. **Project sharing only through resource pools**: No direct ACE configuration for sharing
2. **ACE configuration required**: Users need basic ACE to access system
3. **Performance considerations**: ACE check queries database for each project path
### Future Improvement Directions
1. **Auto-create ACE**: Automatically add ACE for creator when creating projects
2. **Default ACE strategy**: Configure reasonable default permissions for Users group
3. **Performance optimization**: Cache ACE check results to reduce database queries
This design achieves effective user isolation while maintaining RBAC system integrity, and solves the problem of broad ACE configurations breaking isolation.
**Key insight**: The Step 2 created_by filtering is the critical innovation that allows ACE and user isolation to coexist properly.
@@ -0,0 +1,53 @@
# Web Wireshark JWT Token Flow
## Background
Question: What is the purpose of `jwt_token` parameter in UDPLink and how is it transmitted?
## JWT Token Complete Flow
1. **User initiates request** → HTTP request with `Authorization: Bearer <jwt_token>`
2. **API layer extracts token** → `gns3server/api/routes/controller/links.py`:
```python
auth_header = http_request.headers.get("Authorization", "")
jwt_token = auth_header.replace("Bearer ", "") if auth_header else None
```
3. **Pass to Link layer** → `Link.start_capture(wireshark=True, jwt_token=xxx)`
4. **UDPLink forwards** → `UDPLink.start_capture()` calls `super().start_capture(jwt_token=jwt_token)`
5. **Start Web Wireshark container** → `Link._start_web_wireshark(jwt_token)` calls management script
6. **Container uses token** → `manage_wireshark.py` executes inside container:
```bash
curl -N -H 'Authorization: Bearer {jwt_token}' \
'http://controller:3080/v3/projects/{project_id}/links/{link_id}/capture/stream' | \
wireshark -i - -k -display :{display}
```
## Why More Verbose Than gns3-copilot?
**gns3-copilot approach**:
- All code within the same process
- Uses `contextvars` to store and retrieve token
- Downstream code directly calls `get_current_jwt_token()`, no need to pass through layers
**Web Wireshark approach**:
- Token needs to be passed across processes (management script is separate process)
- Token needs to be passed across containers (Docker container isolation)
- Cannot use `contextvars`, must pass through command line arguments
## Conclusion
UDPLink does not use this token, it only forwards it to the parent class. Ultimately used by the curl command inside the Web Wireshark container to authenticate with the GNS3 controller's capture stream API.
Token flow: **Client → GNS3 API → Link → UDPLink → Web Wireshark container → GNS3 capture stream API**
## Related Files
- `gns3server/api/routes/controller/links.py:114-115` - JWT token extraction
- `gns3server/controller/link.py:321-360` - Web Wireshark startup logic
- `gns3server/controller/udp_link.py:178` - UDPLink start_capture signature
- `gns3server/agent/web_wireshark/manage_wireshark.py:527-529` - Container curl command with JWT
+148
View File
@@ -0,0 +1,148 @@
# Xpra HTML5 Client Configuration
## Overview
Web Wireshark integration uses xpra's built-in HTML5 client to provide browser-based packet capture viewing. The xpra HTML5 client is located at `/usr/share/xpra/www` in the container.
## Configuration Methods
### 1. URL Parameters (Per-Session)
Control toolbar menu items via URL query parameters (default: true):
| Parameter | Menu Item | Description |
|-----------|-----------|-------------|
| xpramenu | Xpra Menu | Main menu (Server, Information submenus) |
| open_windows | Open Windows | List of open windows |
| fullscreen_button | Fullscreen | Fullscreen toggle button |
| keyboard_button | Keyboard | Keyboard layout/shortcuts |
| clipboard_button | Clipboard Copy | Clipboard copy functionality |
| sound_button | Audio | Audio toggle |
| cursor_lock_button | Lock Cursor | Game cursor lock mode |
```bash
# Examples
?fullscreen_button=false&sound_button=false
?xpramenu=false&keyboard_button=false&clipboard_button=false&sound_button=false&cursor_lock_button=false
```
### 2. default-settings.txt (Recommended - Global/Persistent)
Modify `html5/default-settings.txt` (INI format) for all users.
**Features:**
| Parameter | Default | Description |
|-----------|---------|-------------|
| keyboard | auto-detect | Enable keyboard input |
| keyboard_layout | us | Keyboard layout |
| clipboard | yes | Clipboard sharing |
| printing | yes | Printer forwarding |
| file_transfer | yes | File transfer |
| swap_keys | MacOS yes | Swap Command/Control keys |
| scroll_reverse_x | no | Reverse mouse X-axis |
| floating_menu | yes | Show floating menu |
| toolbar_position | top-left | Toolbar position |
| autohide | no | Auto-hide toolbar |
| sound | yes | Audio forwarding |
| video | 64-bit yes | Video decoding |
**Connection Options:**
| Parameter | Description |
|-----------|-------------|
| server | Server address |
| port | Port number |
| username | Username |
| password | Password |
| ssl | Enable SSL |
| encryption | Encryption type (AES-CBC/CTR/CFB) |
| key | AES encryption key |
| sharing | Allow session sharing |
| steal | Steal session |
| reconnect | Auto-reconnect |
| bandwidth_limit | Bandwidth limit (bits/s) |
| override_width | Client desktop width |
**Advanced Options:**
| Parameter | Default | Description |
|-----------|---------|-------------|
| audio_codec | auto-detect | Audio codec |
| encoding | auto | Image encoding (png/jpeg/webp/etc) |
| remote_logging | yes | Send logs to server |
| action | connect | Connection mode (start/shadow) |
| submit | yes | Show diagnostics on disconnect |
### 3. default_settings in Code
Set directly in `<script>` tag in index.html:
```javascript
const default_settings = {};
default_settings["xpramenu"] = false;
```
### Priority Order
URL parameter > default_settings object > default-settings.txt > code default value
## Server-Controlled Submenu Items
The **Server submenu** items are controlled by server hello message:
| Menu Item ID | Content | Control Source |
|--------------|---------|----------------|
| clock_menu_entry | Clock | server-time in hello |
| upload_menu_entry | Upload file | file-transfer or file.enabled |
| download_menu_entry | Download file | file-transfer or file.enabled |
| shutdown_menu_entry | Shutdown Server | client-shutdown in hello |
**Information submenu** (About Xpra, Session Info, Bug Report) and fixed items (Reload, Disconnect) are always displayed.
To hide "Shutdown Server", set environment variable before starting xpra:
```bash
export XPRA_CLIENT_CAN_SHUTDOWN=false
xpra start :{display} ...
```
Code: `xpra/server/base.py:40` - `CLIENT_CAN_SHUTDOWN = envbool("XPRA_CLIENT_CAN_SHUTDOWN", True)`
## Customizing Background Image
Background image is defined in `html5/css/client.css`:
```css
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #021d3a;
background-image: url(../background.jpg);
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
```
### Methods
1. **Replace image file**: Create/replace `html5/background.jpg`
2. **Modify CSS**: Change `html5/css/client.css` line 9:
```css
background-image: url(../your-image.jpg);
```
### Notes
- Supported formats: jpg, png, svg, etc.
- Recommended resolution: 1920x1080 or higher
- `background-size: cover` auto-stretches to fill
### Temporary Modification (via URL)
Cannot modify background via URL directly, but can use browser DevTools:
```css
body { background-image: url(your-image-url); }
```
## Related Files
- Container Dockerfile: `gns3server/agent/web_wireshark/docker/Dockerfile`
- Container HTML5 client path: `/usr/share/xpra/www`
@@ -0,0 +1,72 @@
# XRd Console --More-- Pager Bug (PTY window size paging vs terminal length 0)
## Background
Copilot commands with long output consistently failed against XRd (IOS XRv 9000 container) nodes: `device_show_run` running `show ipv4 interface brief` always reported `netmiko_multiline (failed)` (even as a single command); short-output commands like `show ipv4 interface <iface>` worked fine.
Failure sequence (from the 2026-08-18 logs):
1. First failure: `ReadTimeout: Pattern not detected: 'RP/0/RP0/CPU0:ios\#'` — the command echo matched, but the prompt never appeared within 60s
2. The copilot's single-retry reused the same netmiko session (nornir caches it on the host object) with half-consumed output in the buffer → the second failure died earlier in `command_echo_read` — a follow-on effect of the dirty session, not an independent fault
## Root Cause (fully traced)
The XRd node uses the `docker_exec` console type (`gns3server/compute/docker/vendor_docker_vm.py`, `_LazyExecTelnetServer`): a telnet TCP server whose backend is a `docker exec` PTY. Three facts combine:
1. The XR pager (at least for table-engine/TABLAST-style commands) pages on the **PTY window size (TIOCGWINSZ)**, not the CLI-level `terminal length` — `show terminal` happily reports `Length: 0 lines` while output still pages
2. `_LazyExecTelnetServer.client_connected_hook` explicitly resized the exec PTY to **80×24** "before NAWS" (`await self._on_naws(80, 24)`) — the 24 rows were **our own initial geometry, not a Docker default**. Live test: `show ipv4 interface brief` paged after exactly 24 lines
3. netmiko's telnetlib never negotiates **NAWS**, so the initial geometry is never corrected for copilot/bare-telnet clients. Real NAWS clients resize to their own geometry via the existing `_on_naws` → `POST /exec/{id}/resize` wiring
### Dead ends (do not retry)
- `show ipv4 interface brief | no-more` → `% Invalid input detected`. `| no-more` is a **Junos** pipe modifier; IOS-XR does not have it
- `terminal length 0`: takes effect at the CLI layer, but this pager ignores it
- The XR CLI has no command to change PTY rows
### Related fact: paramiko vs docker_exec
paramiko (SSH) cannot connect to a `docker_exec` console — the client-side endpoint is a plain telnet server (`AsyncioTelnetServer`); only `console_type: ssh` (standard attach path, `AsyncioSSHServer`) speaks SSH. The copilot correctly uses netmiko `*_telnet` drivers (netmiko's vendored `_telnetlib`, stdlib-free on Python 3.13).
## Decision/Implementation
### Fix (implemented 2026-08-18, branch `feat/docker-exec-default-pty-geometry`)
Change the initial exec geometry in `vendor_docker_vm.py` `client_connected_hook` from 80×24 to **511×10000** (`await self._on_naws(511, 10000)`):
- Tall/wide default so CLIs that page on PTY rows never hit `--More--` for clients that never send NAWS (netmiko, bare telnet)
- Width 511 matches netmiko's `terminal width 511` convention
- Real NAWS clients still resize to their actual geometry right after connecting (existing `_on_naws` path unchanged)
- Test: `test_first_connect_sets_tall_default_pty_geometry` in `tests/compute/docker/test_vendor_docker_vm.py`
### Fallback design (NOT implemented — keep if the pager ever resurfaces on another console type)
Channel-level loop answering `--More--` in the copilot display tool for `cisco_xr*`: prompt regex breaks; **tail-anchored** `re.search(r"--More--\s*$", buf)` with a ~150ms quiet double-confirmation before `write_channel(" ")`. Never put `--More--` into netmiko's `expect_string` — expect `re.search`es accumulated output, so content containing "More" would false-trigger.
### Still-open copilot improvements (agreed, not yet implemented)
1. Reconnect before retry: `_run_all_device_configs_with_single_retry` (display tool) and the config tool's retry should `task.host.close_connection("netmiko")` first — retrying on a dirty session is doomed
2. `session_log_file` in hosts_data netmiko extras — the copilot has no session_log anywhere, which made this bug a guessing game
## Rationale
Resizing the PTY at exec creation attacks the root (geometry is fixed before the CLI outputs anything); it covers every consumer of the docker_exec console (copilot, MCP, bare telnet) with a one-line change, while the `--More--` auto-answer design remains as a generic fallback for consoles without a resize path.
## Related Files
- `gns3server/compute/docker/vendor_docker_vm.py` — `_LazyExecTelnetServer`: `_on_naws` (exec resize), `_create_exec` (Tty=True, TERM=xterm), `client_connected_hook` (initial geometry — the fix)
- `gns3server/compute/docker/docker_vm.py:1074-1087` — standard console path: NAWS → `containers/{cid}/resize`
- `gns3server/agent/gns3_copilot/tools_v2/display_tools_nornir.py:284-341` — dirty-session retry (open item)
- `gns3server/agent/gns3_copilot/utils/get_gns3_device_port.py` — hosts_data (session_log extras insertion point)
## Examples
Live console transcript (2026-08-17):
```
RP/0/RP0/CPU0:ios#show terminal
Length: 0 lines, Width: 511 columns <- CLI-layer setting in effect
RP/0/RP0/CPU0:ios#show ipv4 interface brief
(exactly 24 lines: timestamp + blank + header + 21 interface rows)
--More-- <- the 80x24 initial exec geometry was paging
```
@@ -0,0 +1,73 @@
---
name: gns3-api-test-writing
description: Use this skill when writing pytest tests for gns3-server API routes — the conftest fixture model, auth token variants, config isolation, and the shared-client order-dependency trap.
version: 1.0.0
---
# Writing pytest API Route Tests
## Test Environment
- Run tests with the repo venv: `venv/bin/python -m pytest tests/api/routes/controller/test_xxx.py` (there is no system python/pytest).
- The app runs in-process (httpx `ASGIWebSocketTransport`); the database is in-memory sqlite; superadmin `admin` is seeded when the users table is created.
- `pytestmark = pytest.mark.asyncio`. Tests run on function-scoped event loops while class-scoped fixtures bind to the class loop — this works, but don't move class fixtures to function scope casually.
## The Fixture Model (tests/conftest.py)
Class-scoped: `app`, `db_session`, `base_client` (**one** shared httpx `AsyncClient`), `test_user` (idempotent `user1` in the "Users" group).
`client` (admin), `authorized_client` (user1), `unauthorized_client`, `compute_client` are class-scoped wrappers that each **rewrite the shared `base_client.headers` at instantiation time**. They are instantiated lazily — by the first test that requests them.
### The order-dependency trap
- `unauthorized_client` is a passthrough: it sets no header and only behaves as "unauthorized" if nothing set a token on `base_client` before it.
- Mixing auth variants in one test class makes the default `Authorization` header depend on fixture instantiation order → tests pass alone but fail in a class run (or the reverse).
- Symptom signature: a 401/403 assertion receives 200. That is fixture pollution, **not** an RBAC/auth bug in the product.
### Rule: per-request headers for auth variants
Never rely on the client's default header for 401/403/specific-user tests. Send the token explicitly (request-level headers override client defaults — the `test_users.py` idiom):
```python
from gns3server.services import auth_service
from gns3server.services.authentication import DEFAULT_JWT_SECRET_KEY
token = auth_service.create_access_token(test_user.username, secret_key=DEFAULT_JWT_SECRET_KEY)
response = await client.get(url, headers={"Authorization": f"Bearer {token}"}) # specific user
response = await client.get(url, headers={"Authorization": "Bearer invalid_token"}) # 401
```
Note the import: `auth_service` lives in `gns3server.services`, NOT `gns3server.services.authentication` (which only exports `DEFAULT_JWT_SECRET_KEY` and the class).
Always pass `secret_key=DEFAULT_JWT_SECRET_KEY`: the autouse `run_around_tests` resets `Config` per test and forces the default secret, so a token minted with the config-of-the-moment dies in the next test.
## Config-Isolated Tests
- Request the function-scoped `config` fixture whenever the test reads/writes configuration or the endpoint under test reloads it. It points `Config` at `tmpdir/server.conf` (accessible as `config._main_config_file`).
- Any endpoint that triggers a config reload re-reads `<secrets_dir>/gns3_jwt_secret_key`, which invalidates class-scoped bearer tokens. Fix: write `DEFAULT_JWT_SECRET_KEY` to that file first — see the `stable_jwt_secret` fixture in `tests/api/routes/controller/test_settings.py`.
## Misc Gotchas
- Build URLs with `app.url_path_for("route_function_name")`. Router introspection is unreliable (lazy `_IncludedRouter` wrapper) — check `GET /openapi.json` instead.
- pydantic v2: an empty `SecretStr('')` serializes as `""`, **not** the mask — assert `in ("", SECRET_MASK)` for secrets that may be unset in tests.
- New privileges are seeded only at table creation (`gns3server/db/models/privileges.py`); the fresh in-memory test DB always has them, but existing deployments need manual grants.
- Error mapping: `ControllerBadRequestError` → 400, `ControllerError`/`HTTPException(409)` → 409, request schema violations → 422.
## Failure-Diagnosis Heuristic
**Passes in isolation, fails in a class run → suspect shared fixture state first** (`base_client.headers`, the `Config` singleton, class-scoped DB rows) — never the product code. Reproduce with `-k "test_a or test_b"` pairs to find the polluting test. Do not add debug prints to product code to chase test-order issues; make the test order-independent with explicit per-request headers instead.
## Order Independence
The suite runs in collection order by default, and a full run is green — but that hides order dependencies. Two real incident classes so far:
1. **The frozen from-import** (fixed 2026-09): `run_around_tests` monkeypatches `gns3server.utils.path.get_default_project_directory` with a lambda. A product module first-imported *while that patch is active* (e.g. `from gns3server.api.server import app` written inside a test body) freezes the patched lambda into its namespace forever — later tests then get a deleted tmpdir path (`FileNotFoundError` from `psutil.disk_usage`). The patched lambda now resolves `Config.instance()` at call time, so freezing is benign — keep it that way.
2. **Sequential-scenario DB tests**: `tests/api/routes/controller/test_users.py`, `test_roles.py`, `test_pools.py`, `test_templates.py`, `test_images.py`, `test_groups.py`, `test_appliances.py`, `test_acl.py` and `tests/controller/test_rbac.py` build shared rows across tests within a file (a test asserts on users/roles created by earlier tests). They are known-red under any reordering — do not copy this pattern into new files.
### Rules for new tests
- **Import product modules at test-module top level**, never first-import inside a test body (an autouse fixture's monkeypatches are live there, and module import executes product `from`-imports).
- **Autouse patch replacements must resolve state at call time** (`Config.instance().settings...`), never close over test-local values (tmppaths, fixture objects) — a closed-over value survives into other tests if the replacement object gets frozen anywhere.
- **Verify a new test file is order-independent**: `venv/bin/python -m pytest tests/<new_file>.py --random-order --random-order-seed=1 -q` (and a second seed). It must pass shuffled. `pytest-random-order` is pinned in `dev-requirements.txt`; it is inert unless `--random-order` is passed.
- A test that needs specific rows creates them itself (or via a fixture) — never relies on rows another test in the file created.
- Diagnosing a suspected order bug: rerun the exact failing pair with the seed printed by `--random-order` (`--random-order-seed=<n>` reproduces it), then bisect to the polluting test.
+172
View File
@@ -0,0 +1,172 @@
---
name: gns3-api-testing
description: Use this skill when testing GNS3 server REST API endpoints with curl — covers JWT auth, common patterns, and marker/link examples.
version: 1.0.0
---
# GNS3 Server API Testing with curl
## Core Principle
Fixed routine for testing the GNS3 server API: **get a JWT token first, then send `Authorization: Bearer <token>` with every request.**
Default address `http://127.0.0.1:3080`, API prefix `/v3`.
---
## Authentication (always first)
```bash
TOKEN=$(curl -s -X POST http://127.0.0.1:3080/v3/access/users/authenticate \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"admin"}' \
| python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])")
```
Persist to a file for reuse (avoids re-logging in each time):
```bash
echo "$TOKEN" > /tmp/gns3_token.txt
TOKEN=$(cat /tmp/gns3_token.txt)
```
Then attach to every request:
```bash
AUTH="Authorization: Bearer $TOKEN"
curl -s -H "$AUTH" http://127.0.0.1:3080/v3/...
```
> **Endpoint note**: login is `/v3/access/users/authenticate`, **not** `/v3/auth/login`.
> OpenAPI spec is at `/openapi.json` (not `/v3/openapi.json`).
---
## Common Variables
```bash
BASE="http://127.0.0.1:3080/v3"
PID=<project_id>
LID=<link_id>
NID=<node_id>
AUTH="Authorization: Bearer $TOKEN"
```
---
## Generic Request Patterns
### GET (query)
```bash
curl -s -H "$AUTH" $BASE/projects/$PID/links | python3 -m json.tool
```
### POST (create) — with JSON body
```bash
curl -s -X POST -H "$AUTH" -H "Content-Type: application/json" \
-d '{"name":"foo","bpf":"icmp"}' \
$BASE/projects/$PID/links/$LID/markers
```
### HTTP status code only (body not needed)
```bash
curl -s -o /dev/null -w "HTTP %{http_code}\n" -X DELETE -H "$AUTH" \
$BASE/projects/$PID/links/$LID/markers/global-icmp
```
### Extract a field from the response
```bash
LID=$(curl -s -H "$AUTH" -X POST ... | python3 -c "import sys,json; print(json.load(sys.stdin)['link_id'])")
```
---
## Status Code Reference
| Code | Meaning |
|---|---|
| 200 | GET/PUT succeeded |
| 201 | POST created |
| 204 | DELETE succeeded (no body) |
| 401 | Not authenticated (token missing/expired) |
| 404 | Resource not found |
| 409 | Conflict (e.g. per-link edit of an inherited marker) |
| 422 | Schema validation failed (e.g. marker name starting with `global`) |
---
## Marker Cheat Sheet
### Project-level global marker definitions (inheritance)
```bash
# Create a def → fans out to every link automatically
curl -s -X POST -H "$AUTH" -H "Content-Type: application/json" \
-d '{"name":"icmp","bpf":"icmp","tag":1,"color":"#ff5722"}' \
$BASE/projects/$PID/marker-definitions
# List all defs + the link_ids each is bound to
curl -s -H "$AUTH" $BASE/projects/$PID/marker-definitions
# Update a def → syncs to every link
curl -s -X PUT -H "$AUTH" -H "Content-Type: application/json" \
-d '{"bpf":"icmp","tag":99}' \
$BASE/projects/$PID/marker-definitions/icmp
# Delete a def → removes the inherited marker from every link
curl -s -X DELETE -H "$AUTH" $BASE/projects/$PID/marker-definitions/icmp
```
### Per-link markers
```bash
# List markers on a link
curl -s -H "$AUTH" $BASE/projects/$PID/links/$LID/markers
# Create a private marker (name cannot start with "global")
curl -s -X POST -H "$AUTH" -H "Content-Type: application/json" \
-d '{"bpf":"tcp port 80"}' \
$BASE/projects/$PID/links/$LID/markers
# Delete (inherited markers return 409)
curl -s -X DELETE -H "$AUTH" $BASE/projects/$PID/links/$LID/markers/<name>
```
### Project-level aggregation query
```bash
curl -s -H "$AUTH" $BASE/projects/$PID/markers # all markers across links, flattened
```
---
## Link / Node Cheat Sheet
```bash
# List all links in a project (includes the markers field)
curl -s -H "$AUTH" $BASE/projects/$PID/links
# List nodes (check ports[].link_id to find free ports)
curl -s -H "$AUTH" $BASE/projects/$PID/nodes
# Create a VPCS
curl -s -X POST -H "$AUTH" -H "Content-Type: application/json" \
-d '{"name":"t1","node_type":"vpcs","compute_id":"local"}' \
$BASE/projects/$PID/nodes
# Start a node
curl -s -o /dev/null -X POST -H "$AUTH" $BASE/projects/$PID/nodes/$NID/start
# Create a link (both ends: node + adapter/port)
curl -s -X POST -H "$AUTH" -H "Content-Type: application/json" \
-d "{\"nodes\":[{\"node_id\":\"$N1\",\"adapter_number\":0,\"port_number\":0},{\"node_id\":\"$N2\",\"adapter_number\":0,\"port_number\":0}]}" \
$BASE/projects/$PID/links
```
> **Port occupancy**: VPCS has only one interface (port 0); once linked it cannot connect again.
> Confirm `ports[].link_id` is empty before creating a link; `"Port is already used"` means the port is taken.
---
## Gotchas
- **`POST /links` response may show `markers: []`** — the create response is serialized before the inheritance hook runs.
The inherited marker is actually applied; check `GET /links/{lid}/markers` or refresh `GET /links` to see it.
- **Restart gns3server after code changes** — the Python process does not hot-reload.
- **Wrap JSON bodies in single quotes** in the shell (double quotes inside); to interpolate a shell variable use `\"$VAR\"`.
- **Pipe long output through `python3 -m json.tool`** to pretty-print; extract fields with `python3 -c "import sys,json; ..."`.
@@ -0,0 +1,74 @@
---
name: documentation
description: Use this skill when creating or updating technical documentation under docs/ directory for GNS3 server
version: 3.1.0
---
# GNS3 Server Technical Documentation Standard
## Core Principle
Documentation answers: **What is this, how does it work at a high level.**
Code details are left to the codebase — readers can use AI to find implementation specifics.
---
## Document Structure
```markdown
# Feature Name
## Overview
[What it does, in 2-3 sentences]
## Architecture
[Mermaid diagram: components and their relationships]
## Business Process
[Mermaid sequence/flowchart: key flows]
## API Endpoints
[Table: Method | Path | Description | Privilege]
## Notes
[Known limitations, performance data, security — only when relevant]
```
---
## What to Include
- Mermaid diagrams for architecture and flow (GitHub renders natively) — see Mermaid Diagram Rules below
- `graph` for component relationships
- `sequenceDiagram` for request/response flows
- `flowchart` for data processing steps
- API endpoint tables
- Request/response JSON examples (for interfaces)
- Performance data (only measured numbers, no estimates)
## Mermaid Diagram Rules
Draw only the diagram kinds the story needs — each kind answers exactly one reader question, in reading order:
- **Anatomy — "what exists, and who owns it?"** — `flowchart LR` with the fewest nodes that show ownership: one subgraph per ownership boundary (a process, a namespace, userspace vs kernel), anything shared between owners a bare node inside the enclosing boundary. The steady-state path is bidirectional solid (`<-->`) edges labeled with the carrying technology, never with a direction; each observer/configurator gets one dashed sideband edge per role.
- **Comparison — "how does X differ from Y?"** — the mirror of its counterpart diagram: same scenario, same node ids, same concrete names, one variable changed. Draw one direction with unidirectional `-->` and state in prose that the reverse is the mirror image.
- **Control sequence — "how is it built / torn down?"** — `sequenceDiagram` spanning every layer (API → coordinator → per-node handlers → the managed process): local steps are self-messages, concurrent fan-out is a `par / and / end` block, each message to the bottom layer is one real command in real order, and a closing `Note` names the steady state.
- **Walkthrough — "how does one item traverse it?"** — `flowchart LR` as a linear pipeline: one subgraph per stage, titled with that stage's role in this trace (`X — ingress`), sideband dashed edges (reverse-direction role, observation point) anchored at the stage they belong to.
Whatever the kind:
- **One step per node, one short line per label.** If a label needs `<br/>` lines to explain itself, split the node into smaller steps instead of packing text — needing many words means the flow needs further decomposition.
- **Details belong to prose.** Parentheticals, exceptions, and parameter lists go to the surrounding text or the section that owns the topic; a diagram never duplicates what prose already says.
- **Define jargon before the first diagram.** A Term | Meaning table placed above the diagrams covers the domain terms they use (interface names, kernel mechanisms), so readers don't have to scan forward.
- **Edge style is semantics.** Solid arrows carry the main flow (data plane); dashed `-.->` edges are sideband relationships (taps, control installs). A node with multiple sideband roles gets one dashed edge per role, each labeled with a single function — and edge *direction* matters too: a config edge points from the configurere to its target, an observation edge from the target to the observer.
- **Decision points are diamonds with labeled outcomes**, not text-packed rectangles spelling out every branch inside one node.
- **A comparison diagram changes exactly one variable.** When two diagrams contrast approaches (kernel vs relay, old vs new), everything else — scenario, topology, node names — stays identical between them; a difference that isn't the point belongs in a prose aside, not in the picture.
- **Numbered crossings stay consistent.** When kernel/user or process-boundary copies are the point of a diagram, number the crossing edges (`copy N: user→kernel`) and keep one numbering scheme across every diagram in the document.
- **Concrete names instantiate stated rules.** Every interface/bridge/instance name appearing in a diagram instantiates a deterministic naming rule stated in prose before the first diagram — never invent ad-hoc names.
## What to Skip
- Code snippets — let readers search the codebase
- Verbose prose — use diagrams and tables
- Implementation details — link file paths instead of pasting code
+98
View File
@@ -0,0 +1,98 @@
---
name: memory
description: This skill should be used when the user asks to "record memory", "save to memory", "remember this", "create a memory", "add to memory", or discusses documenting technical decisions, architectural choices, or important case studies for the project. Use this skill to record project knowledge to the .claude/memory/ directory.
version: 1.0.0
---
# Memory Skill
## Overview
Record project-related technical decisions, important case studies, and lessons learned to the project memory directory, ensuring critical knowledge is managed with the code repository.
## When This Skill Activates
Activate this skill when user requests involve:
- "Record to memory", "save to memory", "add to memory"
- "Remember this", "create a memory"
- Documenting technical decisions, architectural choices
- Recording problem solutions and lessons learned
- Discussing API design, performance optimization, security implementations
## Memory Location
Project memory is stored in: `.claude/memory/`
## Memory Structure
```
.claude/
├── memory/
│ ├── MEMORY.md # Main index file
│ └── <topic>.md # Detailed records for specific topics
└── skills/
└── memory/
└── SKILL.md # This file
```
## What to Record
### ✅ Should Record
- Important architectural decisions and rationale
- Solutions to complex problems
- Key considerations for API design
- Performance optimization experiences
- Security-related implementation details
- Integration approaches with other systems
- Common errors and solutions
- Design changes based on user feedback
### ❌ Should Not Record
- Temporary debugging information
- Session-specific state
- Obvious code implementation details (code is documentation)
- Content already documented elsewhere
## Memory Template
```markdown
# <Topic Title>
## Background
<Why this record exists>
## Decision/Implementation
<What was done or how it was implemented>
## Rationale
<Why this approach was chosen, what alternatives were considered>
## Related Files
<Code files involved, use file_path:line_number format>
## Examples
<If there are code examples or other examples>
```
## Recording Process
1. **Identify content to record**
2. **Determine topic title** (concise, descriptive)
3. **Create record using template**
4. **Update MEMORY.md index**
5. **Save to .claude/memory/<topic>.md**
## Examples
- `web-wireshark-jwt-token-flow.md` - JWT token flow in Web Wireshark integration
- `docker-api-version-detection.md` - Docker API version dynamic detection implementation
## Best Practices
- Use clear, descriptive filenames
- Include references to related code files (with line numbers)
- Document "why" not just "what"
- Keep records updated, remove outdated ones
- Link to related memory files
+7
View File
@@ -1,2 +1,9 @@
[run]
source = gns3server
branch = True
[report]
fail_under = 55
[paths]
source = gns3server
+57
View File
@@ -0,0 +1,57 @@
# Version control
.git
.gitignore
.gitattributes
# CI / GitHub / Docker
.github
.whitesource
.dockerignore
# Editor / IDE
.idea
.vscode
.settings
.project
.pydevproject
.mr.developer.cfg
# Claude
.claude
# Python build artifacts
__pycache__
*.py[cod]
*.so
*.egg
*.egg-info
build/
dist/
eggs/
parts/
var/
sdist/
develop-eggs/
.installed.cfg
lib/
lib64/
.ropeproject
# Test & coverage
tests/
pytest.ini
.coveragerc
.coverage
.coverage*
.tox
.cache
.pytest_cache
nosetests.xml
# Virtualenv
env/
venv/
.venv/
# Editor backup files
*~
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# Pre-commit checks mirroring the CI checks that are fast enough to run on
# every commit (justfile "lint" + "type-check"; pytest and pip check are not
# run here). Only staged Python files are checked.
#
# Install with: just install-hooks
set -euo pipefail
# Prefer the repo virtualenv, fall back to whatever python is on PATH
PYTHON="venv/bin/python"
if [ ! -x "$PYTHON" ]; then
PYTHON="python"
fi
if ! command -v "$PYTHON" >/dev/null 2>&1; then
echo "pre-commit: no python interpreter found, skipping checks" >&2
exit 0
fi
# Staged .py files (deletions excluded)
mapfile -t staged < <(git diff --cached --name-only --diff-filter=d -- '*.py')
if [ ${#staged[@]} -eq 0 ]; then
exit 0
fi
status=0
echo "pre-commit: ruff check"
"$PYTHON" -m ruff check --exit-non-zero-on-fix "${staged[@]}" || status=1
echo "pre-commit: ruff format --check"
"$PYTHON" -m ruff format --check --diff "${staged[@]}" || status=1
# mypy is configured with files = ["gns3server"] in pyproject.toml, i.e. CI
# never type-checks tests: only pass staged files from that package.
mypy_targets=()
for f in "${staged[@]}"; do
case "$f" in
gns3server/*) mypy_targets+=("$f") ;;
esac
done
if [ ${#mypy_targets[@]} -gt 0 ]; then
echo "pre-commit: mypy"
"$PYTHON" -m mypy "${mypy_targets[@]}" || status=1
fi
if [ "$status" -ne 0 ]; then
echo ""
echo "pre-commit: checks failed. Fix the issues above (try 'just format')," >&2
echo "or bypass with: git commit --no-verify" >&2
fi
exit "$status"
+40
View File
@@ -0,0 +1,40 @@
name: Bug report
description: Report a bug so we can fix it.
title: "[Bug]: "
labels: ["bug"]
body:
- type: textarea
id: what-happened
attributes:
label: What happened?
description: A clear description of the bug.
validations:
required: true
- type: textarea
id: reproduce
attributes:
label: Steps to reproduce
description: How can we reproduce this? Numbered steps if possible.
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behavior
description: What did you expect to happen instead?
- type: input
id: version
attributes:
label: Version / commit
description: Which version or commit hash are you on?
- type: textarea
id: environment
attributes:
label: Environment
description: OS, runtime version, anything else that might be relevant.
- type: textarea
id: logs
attributes:
label: Relevant logs
description: Paste any relevant log output. This is automatically rendered as code.
render: shell
@@ -10,7 +10,7 @@ jobs:
name: Add issue to project
runs-on: ubuntu-latest
steps:
- uses: actions/add-to-project@v1.0.1
- uses: actions/add-to-project@v2
with:
project-url: https://github.com/orgs/GNS3/projects/3
github-token: ${{ secrets.ADD_NEW_ISSUES_TO_PROJECT }}
+3 -3
View File
@@ -56,11 +56,11 @@ jobs:
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v7
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
uses: github/codeql-action/init@v4
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
@@ -88,6 +88,6 @@ jobs:
exit 1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
uses: github/codeql-action/analyze@v4
with:
category: "/language:${{matrix.language}}"
+68
View File
@@ -0,0 +1,68 @@
name: Build and Push Docker Image
on:
workflow_dispatch:
push:
tags:
- v2.*
- v3.*
jobs:
build:
runs-on: ubuntu-latest
env:
DOCKERHUB_ORG: ${{ vars.DOCKERHUB_ORG || 'gns3' }}
steps:
- name: Checkout code
uses: actions/checkout@v7
- name: Check for stable release
id: ver
run: |
TAG="${GITHUB_REF_NAME#v}"
echo "tag=$TAG" >> $GITHUB_OUTPUT
if echo "$TAG" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "stable=true" >> $GITHUB_OUTPUT
else
echo "stable=false" >> $GITHUB_OUTPUT
fi
- name: Set lowercase image name vars
if: steps.ver.outputs.stable == 'true'
id: names
run: |
echo "owner=$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_OUTPUT"
echo "repo=$(echo '${{ github.event.repository.name }}' | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_OUTPUT"
- name: Set up Docker Buildx
if: steps.ver.outputs.stable == 'true'
uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
if: steps.ver.outputs.stable == 'true'
uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Login to Docker Hub
if: steps.ver.outputs.stable == 'true'
uses: docker/login-action@v4
with:
registry: docker.io
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push
if: steps.ver.outputs.stable == 'true'
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: |
${{ env.DOCKERHUB_ORG }}/${{ github.event.repository.name }}:${{ steps.ver.outputs.tag }}
${{ env.DOCKERHUB_ORG }}/${{ github.event.repository.name }}:latest
ghcr.io/${{ steps.names.outputs.owner }}/${{ steps.names.outputs.repo }}:${{ steps.ver.outputs.tag }}
ghcr.io/${{ steps.names.outputs.owner }}/${{ steps.names.outputs.repo }}:latest
@@ -12,18 +12,18 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
with:
fetch-depth: 0
ref: "gh-pages"
- uses: actions/setup-python@v5
- uses: actions/setup-python@v6
with:
python-version: 3.9
- name: Merge changes from 3.0 branch
python-version: 3.12
- name: Merge changes from 3.1 branch
run: |
git config user.name github-actions
git config user.email github-actions@github.com
git merge origin/3.0 -X theirs
git merge origin/3.1 -X theirs
- name: Install GNS3 server and dependencies
run: |
python -m pip install --upgrade pip
+17 -28
View File
@@ -4,52 +4,41 @@ on:
push:
branches:
- master
- 3.0
- 3.1
pull_request:
branches:
- master
- 3.0
- 3.1
jobs:
build:
runs-on: ${{ matrix.os }}
runs-on: ubuntu-latest
strategy:
matrix:
os: ["ubuntu-latest"]
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
#include:
# only test with Python 3.10 on Windows
# - os: windows-latest
# python-version: "3.10"
python-version: ["3.11", "3.12", "3.13", "3.14", "3.15"]
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}
- name: Display Python version
run: python -c "import sys; print(sys.version)"
cache: pip
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install .[dev]
python -m pip install .[ai-features,dev]
- name: Install Windows specific dependencies
if: runner.os == 'Windows'
run: |
python -m pip install -r win-requirements.txt
curl -O "http://www.win10pcap.org/download/Win10Pcap-v10.2-5002.msi"
msiexec /i "Win10Pcap-v10.2-5002.msi" /qn /norestart
- name: Install sharkd (marker replay engine)
uses: awalsh128/cache-apt-pkgs-action@latest
with:
packages: wireshark-common
version: linux-amd64
- name: Lint with flake8
- name: Run all checks
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with pytest
run: |
python -m pytest -vv
just test
+26 -2
View File
@@ -25,8 +25,8 @@ var
sdist
develop-eggs
.installed.cfg
lib
lib64
/lib
/lib64
# Installer logs
pip-log.txt
@@ -37,6 +37,10 @@ pip-log.txt
.tox
.cache
nosetests.xml
coverage.xml
htmlcov/
.mypy_cache/
.ruff_cache/
# Translations
*.mo
@@ -67,3 +71,23 @@ env
venv
*venv
.ropeproject
# Claude Code settings (may contain API keys)
.claude/settings*.json
.claude/minmax-settings.json
.claude/zhipu-settings.json
.claude/settings.local.json
.claude/deepseek-settings.json
.claude/claude-settings.json
.claude/gemini-settings.json
.claude/grok-settings.json
!.claude/development.md # Exception: allow development docs
!.claude/skills/ # Exception: allow project skills
!.claude/memory/ # Exception: allow project memory
# PROJECT_CONTEXT.md # Commented out: allow tracking project context
# Tiktoken cache files
gns3server/agent/gns3_copilot/cache/tiktoken/
gns3.log
/configs/
+36 -5
View File
@@ -2,13 +2,44 @@
"scanSettings": {
"configMode": "AUTO",
"configExternalURL": "",
"projectToken" : "",
"baseBranches": ["master", "2.2", "3.0"]
"projectToken": "",
"baseBranches": []
},
"scanSettingsSAST": {
"enableScan": false,
"scanPullRequests": false,
"incrementalScan": true,
"baseBranches": [],
"snippetSize": 10
},
"checkRunSettings": {
"vulnerableCheckRunConclusionLevel": "failure"
"vulnerableCheckRunConclusionLevel": "failure",
"displayMode": "diff",
"useMendCheckNames": true
},
"checkRunSettingsSAST": {
"checkRunConclusionLevel": "failure",
"severityThreshold": "high"
},
"issueSettings": {
"minSeverityLevel": "LOW"
}
"minSeverityLevel": "LOW",
"issueType": "DEPENDENCY"
},
"issueSettingsSAST": {
"minSeverityLevel": "high",
"issueType": "repo"
},
"remediateSettings": {
"workflowRules": {
"enabled": true
}
},
"imageSettings":{
"imageTracing":{
"enableImageTracingPR": false,
"addRepositoryCoordinate": false,
"addDockerfilePath": false,
"addMendIdentifier": false
}
}
}
+871
View File
@@ -1,5 +1,876 @@
# Change Log
## 3.1.0a7 21/10/2026
* Bundle web-ui v3.1.0a7
* Change project creator on import
* feat: add QEMU support documentation and enforce minimum version requirement
* fix: SPICE socket binding failure
* fix(cloud): keep ports_mapping getter and setter adjacent
* feat(cloud): attach TAP interfaces to existing Linux bridges
* feat(qemu): support SATA CD-ROM interfaces
* fix: fetch remote-compute marker pcaps in tag replay
* feat(qemu): support two CD/DVD images and consistent ISO handling
* feat: default vxlan_dstport to the IANA VXLAN port 4789
* feat: cross-compute VXLAN kernel datapath
* fix: type User.username as str via Mapped-style column
* fix: refuse Docker node updates that recreate a running container
* fix: roll back a node update the compute refused
* fix(docker): give each VNC node its own X display
* fix: dial per-node console hosts in MCP device config tools
* feat: add auto_connect flag and disconnect endpoint for computes
* feat: concurrent kernel captures, one per interface
* fix: hide kernel-datapath interfaces from the cloud node
* fix(docker): accept the pinned image id when the stores report different ids
* feat: VPCS kernel datapath
* feat: add support for Python 3.15
* fix: enable Layer 1 keepalives by default. Ref #2975
* fix: update error logging to handle exceptions in WebSockets
* fix(deps): update paramiko and netmiko versions to address security vulnerability
* refactor: remove unused link filter schemas and fix test_add_v8_version_appliance
* fix(controller): stop flooding clients with transitional node statuses
* fix: remove incorrectly merged code
* refactor(mcp): drop the raw drawing_create tool
* feat(agent): share Web UI compatible drawing builders between MCP and copilot
* feat(mcp): add drawing_create_text tool with Web UI compatible SVG assembly
* fix(deps): install the SQLAlchemy asyncio module so the 'greenlet' library is installed
* fix(rbac): annotate query variables with Select type for better type checking
* fix: drop Python 3.10 and add Python 3.15 support
* feat: add optional ETag/If-Match concurrency for projects, nodes and links
* feat: add response models for endpoints returning untyped objects
* feat(api): generate unique readable OpenAPI operationIds
* feat(api): type link filters and available_filters response
* fix(links): reserve ports on add, accept port name and auto, add port_in_use code
* feat(api): add strict_names and batch node and link creation
* feat(api): return node and add wait option on node lifecycle calls
* feat(api): add Snapshot.created and type NodeFile timestamps as date-time
* fix(api): derive OpenAPI version from package, add servers, hide AI stub routes
* feat(api): add Notification schema and document notification streams
* feat(api): add discriminators to link iface, appliance version and template settings schemas
* feat(api): return token lifetimes and document API keys as bearer tokens
* feat(api): add machine-readable error codes and align OpenAPI error schemas
* fix(api): declare binary and streaming bodies in OpenAPI
* fix(api): return 200 instead of 201 for ACL endpoints, IOU license update
* feat(api): add exact-match name filter to list endpoints
* fix(console): keep SSH web console open after terminal resize
* fix: resolve the code-review findings on the kernel datapath
* fix(image-manager): Fix type-check errors in image uploads and appliance installation
* fix(templates): Fixed template test formatting to pass CI
* fix(iou): keep BridgeNIO filters across the NIO update route
* fix: repair imports lost in the 3.1 rebase and meet the new lint baseline
* fix(tools): merge same-device entries before device command execution
* fix(compute): a passive absorbed anchor no longer resets the switch's tc state
* fix(esw): harden the cascade end the create race leaves unhardened
* fix(compute): refuse a duplicate port NIO and wire before bookkeeping
* fix(controller): bind and release link members on their live ports
* fix(controller): keep port links across a port-list rebuild
* feat(controller): let IOL runner containers take the kernel datapath
* feat(iol): anchor IOL runner containers on persistent TAPs
* feat(compute): probe uBridge's swappable bridge TAP leg
* fix(controller): keep IOL runner containers off the kernel datapath
* fix(qemu): release the datapath under the execution lock
* fix(qemu): release the datapath after the process is gone
* feat(esw): wire peer anchors straight into the switch bridge
* feat(controller): offer Dynamips the kernel datapath
* feat(dynamips): anchor every Ethernet port on a persistent TAP
* fix(mcp): let link_list return kernel_datapath
* fix(schemas): one definition of the capabilities payload
* fix(iou): carry suspend from the NIO update body
* feat(controller): offer IOU the kernel datapath
* feat(ubridge): probe iol_bridge's TAP-port support
* feat(iou): anchor every Ethernet bay/unit on a persistent TAP
* fix(qemu): build a command line for a headless node
* feat(controller): offer QEMU the kernel datapath, gated per compute
* feat(qemu): anchor QEMU adapters on a persistent TAP
* refactor(compute): share the kernel-datapath machinery across node types
* fix(controller): re-arm window_drop and expose kernel_datapath
* feat(mcp): accept project/node names as tool locators
* feat(controller): expose kernel_datapath on the link payload
* feat(compute): report uBridge tc capabilities and gate filters on them
* fix(docker): delete the per-link kernel bridge when a node stops
* feat(docker): expose the eBPF time-window filter on kernel links
* feat(docker): eBPF stateful packet filters on kernel links
* feat(docker): expose netem-extension packet filters on kernel links
* fix(docker): bring the veth host end up before a relay attach
* feat(docker): bpf packet filter on kernel links via cls_bpf match-drop
* feat(docker): packet filters on kernel-datapath links via tc netem
* feat(docker): unify adapter interfaces on veth, allow kernel links at runtime
* feat(docker): traffic-insight markers on kernel-datapath links via AF_PACKET
* feat(docker): packet capture on kernel-datapath links via AF_PACKET
* fix(controller): don't push the synthetic suspend filter to kernel links
* feat(docker): wire Docker-to-Docker links through a kernel bridge
* feat(image-manager): Add support for nested image folders and appliance compatibility checks
* refactor: discriminate appliance settings by template_type
* fix: bump asyncssh - at least 2.24.1 for CVE-2026-62949 fixes
* fix: require Python >= 3.10 in remote-install.sh when installing v3
* fix(images): Fix symlinked image imports and add regression tests
* fix(images): Fix symlink support in image inventory
## 3.1.0a6 27/09/2026
* Bundle web-ui v3.1.0a6
* ci: no flake8 checks for now, ruff covers them
* ci: run just test
* fix(qemu): Fixed missing image replacement for linked-clone nodes
* Allow projects containing missing images to open in a degraded state instead of failing to load
* fix: make node working directory deletion robust
* feat: keep Docker images on computes consistent with the controller host
* feat: sync Docker images from the controller to remote computes
* fix: run the reclaim helper as root regardless of the image's default USER
* fix: reclaim root-owned container files so docker nodes and projects can be deleted
* ci: install sharkd in the test workflow and make manager tests hermetic
* fix: harden sharkd replay sessions and serve the uncapped frame list
* feat: accept link=<link_id> on the replay range and frames endpoints
* feat: drive marker replay with resident sharkd sessions
* fix: stop leaking a global os.kill mock from the shutdown route test
* fix: keep port_number in Docker NIO dispatch of the batch endpoints
* feat(copilot): make start_gns3_node immediate-return, add wait_seconds tool
* fix: keep upstream link-carrier commands off unix-socket NIO bridges
* feat: ship an iol-xe-base.txt base config for IOL Docker nodes
* fix: keep payload-delivered state across container (re)creation
* feat: IOU-style startup-config for IOL Docker nodes
* fix: normalize marker.match event tag to int to match the REST schema
* feat: allocate IOL Docker application IDs from a pool disjoint from IOU
* fix: derive per-node IOL app id so linked routers get distinct MACs
* feat: model IOL adapters as 4-port units like the IOU node type
* revert IOL port-name override; document custom_adapters instead
* feat: show IOL-style interface names on iol-runner ports
* refactor: wire unix-socket NIOs through a per-node runtime directory
* refactor: reach unix-socket NIOs through the container root in /proc
* fix: alias long unix-socket NIO paths through the runtime dir
* feat: add IOL (iol-runner) Docker node support
* fix: normalize marker.match event tag to int to match the REST schema
* fix: Fix failing tests and adress the MCP 2.x incompatibility failures
* feat: Add Docker link carrier and interface status support
* fix: list every project in template/image in-use refusal, not just the first
* feat: forbid deleting templates and images still used by projects
* fix: publish-api-documentation.yml
* fix: handle client disconnect in compute console WebSocket forwarding
* fix: update link_capture_download and symbol_get tool descriptions for tickets
* fix: replace Bearer JWTs with path-bound access tickets in MCP download tools
* fix: issue short-lived console tickets instead of JWTs in node_console MCP tool
* fix: handle client disconnect in console WebSocket forwarding
* fix: accept the 'local' compute id in compute tools
* fix: unify the device tool error contract
* fix: reject non-VPCS nodes in the VPCS config tool
* fix: dedupe and report automatic template creation from images
* fix: return the created template from appliance install
* fix: keep default node naming aligned with batch submission order
* fix: keep node file content byte-faithful in node_file_get
* fix: keep submission order and unify status in MCP batch handlers
* fix: propagate 405 when suspending a node without suspend support
* fix: report empty projects as not locked
* feat: expose data_link_type on the link_marker MCP tool (create-only)
* fix: never allow the projects directory to become a project directory
* refactor: sink shared REST handlers into gns3_client, drop gns3fy wrappers
* api: add endpoint serving the project .gns3 topology file
* fix: type optional configuration fields as Optional
* feat: add GET/PUT /v3/settings server settings API
* feat: add config read-modify-write update and harden file watcher
* refactor: move MCP service from api/routes to agent package
* fix: notification ping starved under sustained event load
* fix: compute notification stream silently died on uncaught exceptions
* docker: replace vendor SKIP_INIT exec volume bridge with create-time direct binds
* feat(copilot): device skills per-topic split layout and topic retrieval
* docker: don't lose a client size that races the exec creation
* docker: add GNS3_CONSOLE_RESIZE knob for paging CLIs
* console: forward client terminal size over the console WebSocket
* controller: allow markers and packet filters on Ethernet switch links
* docker: don't recreate containers on empty-string property PUTs
* mcp: don't run API keys through JWT validation
* mcp: fingerprint short-lived console tokens for copy-corruption checks
* auth: split JWT validation errors by failure cause
* docker: give the docker_exec console a tall default PTY geometry
* copilot: log into devices using the node default credentials
* api: expose installed netmiko device types for the web UI
* nodes: per-node default credentials seeded from the template
* templates: persist appliance metadata on install
* fix: address appliance v8 install review findings
* copilot: prefer netmiko_device_type over the device_type:<type> tag
* appliance: seed netmiko_device_type from the appliance file
* nodes: per-node netmiko_device_type (controller-only)
* templates: add netmiko_device_type for automation tools
* appliance: close the v8 gaps for Docker vendor appliances
* appliance: implement install support for registry version 8
## 3.1.0a5 19/08/2026
* Bundle web-ui v3.1.0a5
* Sync appliances
* copilot: sync CONSOLE_TYPES with the server ConsoleType enum
* feat: Enhance information displayed on the system status dashboard
* docker: cap GNS3_STOP_TIMEOUT at 210 s (controller stop budget)
* docker: harden the shm/devices/extra_configs/masking work (code review)
* docker: make the vendor graceful-stop grace period configurable (GNS3_STOP_TIMEOUT)
* docker: graceful stop for vendor NOS containers (SIGTERM + 60s grace)
* fix: UDP port allocation race causing link self-loop (one-way links)
* add support basic support for OpenBSD.
* docker: use the container's chown (not busybox) in vendor volume/perms path
* docker: mask systemd-udevd in privileged containers (GNS3_MASK_UDEV)
* docker: persist extra_configs in the template DB table
* docker: inject config files into containers via extra_configs
* docker: warn about low inotify/file-max and missing FUSE at connect
* docker: inject /dev/shm size and host devices via HostConfig from env
* appliance: expose custom_adapters on the v1-6 appliance model
* appliance: accept docker_exec console type in Docker appliances
* fix: recreate docker_exec console on reconnect after CLI exit
* vendor: drop the hardcoded /etc/network mount for SKIP_INIT containers
* vendor: skip /etc/network in volume bridge and permission passes
* fix: run _fix_permissions container-side on /gns3volumes mount targets
* fix: host-side permission fix + SKIP_INIT volume persistence docs
* refactor: move vendor NOS Docker support into VendorDockerVM subclass
* docker_exec console: wrap exec command in while-true loop so sr_cli restarts on quit
* Prototype: vendor NOS Docker node support (SR Linux etc.) — docker_exec console via Docker exec API (pty + hijacked HTTP + NAWS resize)
* fix: update CI configuration to use a single OS and remove Windows-specific dependencies
* fix: breaking change with dependency FastAPI v0.137.0 https://fastapi.tiangolo.com/release-notes/#specific-breaking-changes
* fix: suppress redundant console port setter log during Docker node create
* revert: restore force_close=True in compute._session()
* perf: parallelize batch NIO creation across nodes
* fix: scope marker reconcile to the current bridge/NIO
* cleanup: remove stray debug print in Dynamips node creation
* fix: reconcile marker filters in _ubridge_apply_markers (delete/update)
* log: suppress marker sink stats when no matches received
* log: add periodic marker.match throughput statistics
* marker: route marker.match to a dedicated project WS channel
* perf: raise marker UDP receive buffer from ~208KB to 8MB
* perf: move project-open marker inheritance to prepare phase
* perf: parallelise compute-side batch NIO update per node
* perf: batch update/delete marker-def fan-out too (full project-level)
* perf: batch marker-def fan-out to one PUT /nios/batch per compute
* log: add marker fan-out timing for project-open and interactive def-change
* tune: raise start_all concurrency from 3 to 10
* revert: drop _connect_nio thread-pool executor, restore async _ubridge_send
* fix: use socket.fromfd in send_batch_sync for Python 3.13 compat
* log: demote all per-node lifecycle INFO logs to DEBUG
* fix: await Dynamips.create_nio (it is async, unlike sync base)
* fix: use bound-method param count for Dynamips create_nio detection
* fix: Dynamips create_nio(node, nio_settings) takes extra arg + add tests
* log: add start/stop/close progress lines; revert start concurrency to 3
* log: lower per-node lifecycle logs in base_node to DEBUG
* perf: raise start/stop/suspend/reset-console concurrency from 3
* fix: race in concurrent node creation sending duplicate POST /projects
* log: lower per-node docker lifecycle logs to DEBUG
* log: emit progress lines for node and link loading on project open
* cleanup: remove project-open stage timing logs, lower NIO-added log to debug
* perf: skip per-link topology dump during project-open prepare
* perf: batch NIO dispatch on project open (one HTTP per compute)
* perf: cache compute.host_ip + add UDPLink.create timing log
* perf: dedicated 500-worker thread pool for ubridge batch I/O
* perf: offload per-NIO ubridge commands to thread-pool executor
* perf: enable TCP keep-alive for local compute HTTP requests
* debug: add per-command timing to _connect_nio ubridge calls
* perf: parallelize UDP port allocation and NIO creation in UDPLink.create
* fix: SIGKILL docker container on stop instead of 5s grace period
* fix: add event handling for deleted projects
* fix: tests after merging
* server: raise the open-files (RLIMIT_NOFILE) limit at startup
* marker: batch topology dumps in bulk fan-out (per-def on 500+ links was ~1 minute)
* marker: concurrent (bounded) definition fan-out
* marker: forward data_link_type on per-link marker create
* iou: skip already-installed markers in _ubridge_apply_markers (NIO update idempotency)
* marker: serial-link (WAN) support via data_link_type -> uBridge linktype
* iou: forward data_link_type on capture start so serial pcaps use the correct linktype
* ubridge: default the control transport to unix
* ubridge: require version >= 1.2.0
* fix: add missing HTTPException import
* mcp: drop direction from marker_definition tool
* marker: tighten marker name max length from 128 to 32
* marker: drop deleted marker from port NIO cache to stop empty pcap on restart
* marker: validate def BPF once, skip re-validation on inherited fan-out
* marker: point directional defs at BPF, refresh implementation doc
* marker: incremental apply, clear bridge map on uBridge stop
* marker: fine-grained filter ops, clean pcap on remove
* marker: restore direction on project load, reject tx/rx on definitions
* schema: accept direction='both' in marker schemas, normalize to None
* qemu: demote QEMU monitor connect and set_link logs to DEBUG
* marker: key _marker_filter_bridges by (name, link_id) so multi-link nodes toggle every copy
* marker: make per-filter toggle fall back to NIO rebuild when the marker isn't installed
* marker: make per-filter toggle a no-op when the marker isn't installed
* marker: rework pause/resume from project-wide to per-definition
* marker: fix PUT marker with an enabled-only body (bpf no longer required)
* marker: persist project-wide markers_paused to the .gns3 file
* marker: document pause/resume and instant enabled toggle
* marker: test enabled/pause/resume and instant toggle
* marker: drive uBridge enabled/pause/resume in real time
* marker: add direction-clear, routing, and ubridge transport tests
* marker: support clearing direction via explicit null / "both"
* marker: let callers pin the capture node via capture_node_id
* Name AF_UNIX sockets by node id for self-describing debuggability
* Detect unsupported -U flag and fail fast with a clear error
* Add configurable uBridge control channel transport (tcp/unix)
* fix(import): unvalidated symlink creation in import_project
* fix(qemu): move the bios options after the network ones
* fix(qemu): fix addition of QEMU RNG device causes interface names to change
* bugfix: docker workflow needs lowercase name
* fix(qemu): remove trailing space from RNG object argument
* Add MCP tools for traffic-insight marker feature
* Improve MCP tool descriptions for link_update, device_show_run, and link_reset
* Do not start nodes when deleting a project
* fix: correct always-true state check in DockerVM.stop()
* add bug report issue template
* Adds controller and compute API support for explicitly pulling or updating Docker images.
* feat(tests): increase maximum open file descriptors for test runs on Unix
* (feat): Implement functional Layer 1 keepalive support for IOU/IOL nodes
* Fix typo with ovmf_firmware_dir
* Fix issues after merging
* fix(builtin): hide GNS3 internal bridge interfaces from Cloud node
* feat(builtin): NAT node returns its interface IP info in asdict()
* fix(controller): refresh cloud/nat node interfaces from compute on GET
* refactor(builtin): use deterministic bridge name from switch UUID
* fix(builtin): bring kernel bridge UP after creation
* feat: migrate builtin EthernetSwitch from Dynamips ethsw to ubridge brctl
* fix(mcp): remove unreliable node_reload / node_reload_all tools
* fix(rbac): guard None current_user on websocket auth failure
* fix(mcp): thread token_version into console/download token minting
* fix(mcp): pass user.token_version when generating temp JWT from API key
* fix(marker): avoid reentrant-lock deadlock when uBridge starts lazily
* fix(marker): per-link attribution via link field in MARK signals
* fix(marker): set nio.markers on iou/dynamips/cloud nio update
* fix(marker): reject reserved global-prefix names only on create
* fix(marker): clean inherited markers on def delete
* feat(marker): add highlight_duration render hint
* fix(marker): fix inheritance hook, topology load, update sync, and asdict
* fix(marker): export MarkerDefinitionCreate from schemas package
* fix(marker): replace pydantic lookahead pattern with field_validator
* feat(marker): add project-level marker definition inheritance
* fix(marker): reserve "global" name prefix for future marker inheritance
* fix(marker): extend marker support to dynamips and cloud nodes
* fix(marker): enable marker support for docker nodes
* fix(marker): tolerate port conflict on marker listener startup
* fix(marker): validate marker name and expose enabled via REST
* fix(marker): uniquify auto-generated marker names per link
* feat(marker): add project-level marker aggregation endpoint
* feat(marker): add IOU node marker support via iol_bridge
* refactor(marker): converge to filter single-path model, remove dual-apply endpoints
* fix(marker): restore markers from topology on project load
* feat(marker): add optional color field to marker data model
* fix(marker): use allowlist in _choose_marker_side, align with _get_filter_node
* fix(marker): stop auto-deleting markers on node stop in node_updated
* fix(marker): ride markers on NIO so they survive node restart and project reload
* config: set marker_listen_port default to 3070 and document in config templates
* fix(marker): add _choose_marker_side to exclude non-uBridge node types
* Only set IOU images to be executable when importing images
* fix(import): project import does not move images symlinks into place
* Search for system UEFI that is compatible with Python < 3.12
* UEFI improvements for Qemu VMs * Add OVMF firmware directory configuration * Automatically add a Random Number Generator (RNG) device when using uefi option is enabled
* fix(docker): handle container name conflict automatically
* fix: gns3-server crashes on startup if "Open this project in the background" is active but there is a problem with that project
* Handle HTTPNotFound exception when retrieving compute status
* Replace ControllerForbiddenError with aiohttp.web.HTTPForbidden for project deletion error handling
* Fix: Check compute connectivity before open() during project deletion
* Use typed InterfaceStatus enum and simplify stats fallback in interfaces()
* Expose full interface address list and link state in cloud node API
## 2.2.61 30/07/2026
* Sync appliances
* fix(import): unvalidated symlink creation in import_project
* fix(qemu): fix addition of QEMU RNG device causes interface names to change
* fix(qemu): remove trailing space from RNG object argument
* fix: do not start nodes when deleting a project
* fix: correct always-true state check in DockerVM.stop()
## 2.2.60 15/07/2026
* Sync appliances
* Only set IOU images to be executable when importing images
* fix(import): project import does not move images symlinks into place
* Search for system UEFI that is compatible with Python < 3.12
* Add OVMF firmware directory configuration
* Automatically add a Random Number Generator (RNG) device when using uefi option is enabled
* fix(docker): handle container name conflict automatically
* fix: gns3-server crashes on startup if "Open this project in the background" is active but there is a problem with that project
* Handle HTTPNotFound exception when retrieving compute status
* Fix: Check compute connectivity before open() during project deletion
* API endpoints to manage base configuration files for templates
## 3.1.0a4 09/07/2026
* Bundle web-ui v3.1.0a4
* Add jwt_refresh_token_expire_minutes to sample configuration
* Remove deleted web-ui files from git
* .dockerignore ignore .dockerignore
* typo made me reconsider and move out to env
* defaulted DOCKERHUB_ORG repository variable
* Remove API docs from 2.2 after merging
* Update GitHub Actions workflows
* Fix web-wireshark docker build broken by xpra 6.5 release
* Update CI to install [ai-features,dev] instead of [ai-copilot,dev]
* Make AI features (AI Copilot + MCP) optional via [ai-features] extra
* Add refresh token mechanism documentation under docs/features/
* Add /refresh to allowed public endpoints list in route auth test
* Add stateless JWT refresh token mechanism
* Add project/node/link handler tests: 39 total, covering list/get/create/delete/start/stop/suspend/reload/console/update/fields
* Add MCP tool parameter consistency tests
* Fix appliance_install: add version parameter
* Add coordinate system note to docs
* Document canvas coordinate system in node_create x/y params
* Update docstring: batch concurrency from 10 to 100
* Remove unused import time
* Add list type check before nodes[0] access in _normalize_link_nodes
* Add fields type validation in create handlers
* Use pop() instead of pop(0) for O(1) port removal
* Fix review issues: key_prefix length, count validation, WAL log, timeout comment, pointless temp var
* Fix: pass name from TemplateUsage to add_node_from_template
* Remove unused imports (logging, log, select)
* Add warning for unconsumed pre-allocated UDP ports after link creation
* Remove FIXME comment about middleware in server.py
* Rename device_command_run_handler → device_show_run_handler to match tool name
* Rename device_command_run → device_show_run for clarity
* Fix device_command_run KeyError('commands'): tool desc said show_commands but backend expects commands
* Fix template_list return type annotation to match _run_handler_sync envelope
* Add performance optimization documentation
* Update MCP service docs: API key format, auth flow, tool parameters, concurrency
* Increase HTTP connection pool to 500/1000
* Increase BATCH_MAX_WORKERS and Pool concurrency from 20 to 100
* Remove final timing artifact in projects.py
* Remove remaining dead timing variables and imports
* Remove database warmup (proven ineffective - real bottleneck was bcrypt blocking event loop)
* Clean up all timing/debug logs
* Add memory: import validation best practice
* Fix: add missing UUID imports
* Generate fresh JWT on API key auth instead of returning raw key
* Optimize API key auth: O(1) lookup via UUID-embedded key format
* Fix: offload bcrypt.checkpw to thread pool to prevent blocking event loop
* Add timing to API key auth path and log api_keys count
* Replace SELECT 1 warmup with full database file read to warm OS page cache
* Add timing logs to auth dependency chain to identify 6s pre-handler delay
* Add granular timing to get_template: separate execute vs fetch time
* Warm up database connection pool on startup to avoid 8s cold-start penalty on first API request
* Fix: register WAL PRAGMA on sync_engine instead of Engine class for async compat
* Add timing logs to get_template to identify DB query bottleneck
* Add timing middleware to log slow requests (>1s) with [CTRL-TIMING] prefix
* Fix: _time → time in compute.py timing log
* Add [CTRL-TIMING] logs to controller create_node flow
* Fix: pass template_id to batch mode handler so top-level template_id works as default
* Add detailed timing logs to MCP node creation and HTTP client
* Add fields filter to template_list tool with description for AI
* Fix: add missing _filter_link_response function
* Pass name parameter through to controller API when creating node from template
* Add validation to compact link format with clear error messages
* Add compact array format for link node entries to reduce token usage
* Add fields filter to link_create tool
* Reduce md5sum cache write failure log level from error to warning
* Add fields filter to node_create tool description for AI
* Optimize MCP create_node: support inherited template_id and default fields filter
* Increase MCP HTTP client timeout from 10s to 30s
* Enable SQLite WAL mode to fix 'database is locked' errors under concurrent API requests
* Cache IOU image default values per image path to avoid redundant subprocess calls
* Increase node and link creation concurrency from 5 to 20
* Fix: revert IOU lock optimization, serialize IOU node creation for correct application_id assignment
* Performance: accelerate project opening with parallel link creation and batch UDP port allocation
* feat: Add batch link_ids to link_delete/link_reset, fields filter to link_list
* feat: Add fields filter to link_list
* feat: Add batch node_ids to node_delete
* fix: Convert http to ws scheme in node_console WebSocket URL
* feat: Add batch link_ids to link_capture_download
* feat: Add batch link_ids to link_capture_start/stop
* fix: Store username in gns3_ctx during auth, use for short-lived download JWTs
* fix: Generate independent short-lived JWT for pcap download
* revert: Remove _configs_map changes in tools_v2 (handled by template renderer now)
* fix: Merge commands for duplicate device_names in _configs_map
* fix: Actually pass template param to device_config/command handlers
* fix: Correct Jinja2 template commands_field per tool type
* feat: Jinja2 template support in device_command_run
* feat: Jinja2 template support in device_config_send
* feat: Add batch node_ids support to node_start/stop/reload/suspend
* feat: Add fields filter to appliance_list
* feat: Add fields filter to node_list
* feat: node_get fields filter — match controller Node schema fields
* fix: Set auto_close=False on project_create so projects stay open when clients disconnect
* feat: Add batch mode to node_create and link_create (parallel, max 10 workers)
* fix: Pass API key directly instead of generating short-lived JWT
* feat: API key lifecycle — revoke/restore/delete
* fix: Rename revoke_api_key → delete_api_key
* fix: Hard-delete API keys instead of soft delete (revoked flag)
* feat: Support API keys in REST API authentication (reuse gns3_ prefix keys)
* fix: Lazily access db engine for API key validation
* fix: Add missing updated_at column to api_keys table
* fix: Export ApiKeyCreate from schemas package
* feat: Add API Key support for MCP authentication
* fix: Validate JWT token exp claim — was silently ignored after migration to joserfc
* fix: Add image field to template_create, document type-specific params in description
* fix: Remove .json() calls on 204 responses for prune/install images
* fix: Skip always-running nodes in start_all/stop_all
* fix: Add missing rotation parameter to drawing_update MCP tool
* fix: Map MCP device_command_run parameter to tool's expected field name
* fix: Update link_reset description to match actual behavior (delete + recreate)
* fix: Remove unsupported description param from project_create
* fix: Fix symbol_get/upload/delete handlers for correct API paths
* feat: Log registered MCP tools at startup
* fix: Type compute_id as uuid.UUID to reject non-UUID values at MCP input layer
* fix: Require UUID for compute_get/images, remove 'local' string default
* feat: Add device configuration MCP tools (config_send, command_run, vpcs_config_set)
* refactor: unify MCP tool naming to <module>_<action> convention
* feat: Add symbol upload/delete, project load, and locked check MCP tools
* feat: Add image management MCP tools
* feat: Add symbol and appliance MCP tools
* feat: Add node bulk ops, project lock, and server info MCP tools
* feat: Add snapshot and drawing MCP tools
* refactor: unify MCP handlers to use http_call directly, relocate node file ops to Node class
* feat: Add node file operations as MCP tools (list, get, write, delete)
* Add comment about rootful Docker permissions at container start
* Fix _fix_permissions test: set process.returncode=0 and update assertion
* Fix list_node_files PermissionError on os.scandir
* Fix _fix_permissions error handling and list_node_files PermissionError
* Add async_iterable_to_stream utility to avoid aiohttp compatibility issues
* Add descriptive detail to 403 errors in compute file endpoints
* Fix silent file write failure in write_compute_project_file
* feat: Node file streaming, recursive listing, file type detection, and file delete
* Update README tool descriptions: .txt → .md
* Update README tool descriptions to mention Markdown format
* Add MCP project tools: update, duplicate, and README operations
## 3.1.0a3 06/06/2026
* Bundle web-ui v3.1.0a3
* fix: update MCP link tools descriptions with detailed filter info
* fix: correct MCP nodes and links tool parameter handling for nested kwargs
* fix: correct MCP template tool parameter handling for nested kwargs
* feat: add client information logging to MCP connection rejection
* refactor: replace MCP ready state polling with asyncio.Event
* fix: revert duplicate image check to fix failing tests
* fix (templates): Add ordering to handle the duplicate cases gracefully
* fix(templates): Database error detected when saving a template with a disk image change
* fix: return 503 error on MCP server ready timeout
* fix: add MCP server ready check to prevent initialization errors
* fix: resolve MCP server URL host via default route IP when bound to 0.0.0.0
* fix: correct MCP transport security config to actually allow all hosts by default
* feat: add configurable MCP transport security settings via gns3_server.conf
* fix: add load_feature_skills() to properly load network planning features
* refactor: convert all MCP tool parameter descriptions to Annotated+Field
* fix: remove platformdirs upper bound to resolve fastmcp-slim dependency conflict
* fix: add missing fastmcp dependency to resolve CI test failures
* refactor: move all imports to top of __init__.py
* test: add /v3/mcp/ to allowed public endpoints
* fix: remove console_host/port from get_node_console_info
* feat: add get_node_console_info tool
* feat: add 3 Compute MCP tools - Add list_computes, get_compute, get_compute_images - Total MCP tools: 29
* feat: add 5 Template MCP tools
* feat: add Node and Link MCP tools, update copyright - Add 9 node tools and 5 link tools - Update copyright year to 2026, add author
* feat: complete MCP SSE transport with JWT auth
* feat: support Authorization header and query param for MCP token
* feat: implement standard MCP protocol with SSE transport
* feat: add MCP (Model Context Protocol) service with project tools
* Add project memory: Docker container stop delay analysis
* Remove extra blank line from merge
* Revert container state detection in create()
* Fix Docker VM tests for container status detection on node creation
* Add running project check for fast duplication
* Move running project check before fast duplication
* Add running project check for fast duplication
* Fix Docker container status detection on node creation
* Fix web-ui update script to handle custom GitHub URL changes
* Fix unnecessary Docker container recreation when renaming a project
* Fix project rename and duplicate issues
* Fix double deletion issue in remove_resource_from_pool
* Complete fix: delete resource records when deleting resource pool
* Apply fix from PR #2315: delete resource from resource table when removing from pool
* Remove deprecated 'PermissionsStartOnly' setting for Systemd service. Ref #1830
* Optimize project loading by implementing parallel node creation
* Fix delay filter validation: ensure delay: [0, X] returns proper error message
* Fix packet filter validation tests: use correct ubridge filter type names
* Update tests to match show_interface_labels default change
* Set default value of show_interface_labels to True
* Optimize project variable updates to use parallel node processing
* Fix ghost Docker nodes causing 60-second VNC timeout on variable updates
* Fix Docker container variable compatibility with Pydantic models
* Fix delay latency minimum: ubridge rejects latency <= 0
* Improve packet filter validation: use tcpdump, handle multi-line BPF, safe project load
* Add packet filter parameter validation to prevent ubridge errors
* chore: update GNS3 skills repository to official organization
* docs: update RBAC user isolation design doc to match actual implementation
* docs: update skills repo URL in command-security.md
* docs: remove Chinese overview docs, keep only English versions
* docs: add overview docs for packet analysis, fault injection, and AI assistant
* feat: add mermaid-to-SVG conversion script with environment setup
* test: fix privilege count assertions after adding LLMConfig privileges
* docs: add user node limit roadmap
* test: fix RBAC test to match implementation logic
* test: add --prefix and --cleanup-only parameters to benchmark script
* perf: batch RBAC permission checking for GET /projects
* test: add benchmark script for GET /projects performance testing
* fix: prevent duplicate projects when user projects are in resource pools
* fix: check both regular ACEs and resource pool ACEs for proper access control
* test: update RBAC test to use test_user.username for user isolation
* docs: add Phase 9 and 10 user self-registration and email service
* docs: add Phase 8 per-user project namespace to roadmap
* docs: add Phase 7 resource pool renaming to roadmap
* feat: add alembic migration for LLMConfig privileges
* feat: add independent LLMConfig permissions for AI profile management
* docs: add Phase 6 frontend permission query API to roadmap
* docs: add Phase 5 ACE architecture refactoring plan to roadmap
* feat: remove resource pools from 'all endpoints' list
* refactor: add efficient get_aces_for_path method for resource pool checks
* feat: prevent deletion of resource pools used by ACE configurations
* docs: update RBAC user isolation roadmap and add design memory
* feat: fix permission check logic to properly handle ACE and user isolation
* feat: implement layered permission checks for proper user isolation and sharing
* feat: implement simple user isolation based on project ownership
* fix: clean BPF syntax error message and specify loopback interface
* feat: add BPF syntax validation using tshark
* feat: add show_filters_icon parameter to packet filter tool
* docs: add GNS3 appliance loading mechanism to memory
* feat: add packet filter management tool for GNS3-Copilot fault injection
* fix: update test_json expected output to include show_filters_icon field
* fix: add getattr fallback to show_filters_icon property for backward compatibility
* feat: add show_filters_icon property to Link for controlling Web UI filter icon display
* fix: ensure show_filters_icon is always returned in API responses
* feat: add show_filters_icon property to Link for controlling Web UI filter icon display
* fix: remove explicit paramiko pin to resolve dependency conflict with netmiko
* fix: update netmiko to 4.7.0 and pin paramiko>=5.0.0 to fix CVE-2026-44405
* fix: close DockerHTTPClient session to prevent UnixConnector leak in Web Wireshark
## 3.1.0a2 12/05/2026
* Bundle web-ui v3.1.0a2
* fix: surface tshark stderr errors to LLM, not just log them
* fix: hint LLM about -c behavior when tshark returns empty with -c
* fix: update search_fields examples to use existing field names
* fix: reject multi-keyword search_fields, single keyword only
* fix: document action/query params in PacketAnalysisTool description
* feat: add search_fields action to PacketAnalysisTool for real-time field lookup
* feat: validate tshark -e field names before running analysis
* fix: document -c behavior caveat in PacketAnalysisTool description
* fix: demote loader-level load logs to DEBUG, info already reported by manager
* fix: promote skills/prompts load logs to INFO level
* fix: load packet analysis protocols during skills initialization
* feat: add PacketAnalysisSkillsTool
* fix: remove remaining quoted example from tool input docstring
* fix: use shlex.split for tshark_args parsing
* feat: add packet analysis workflow to tool description
* refactor: remove old PacketCaptureTool, replaced by PacketAnalysisTool
* feat: add protocol-oriented packet analysis tool
* docs: add roadmap docs for planned features
* feat: require superadmin for /reload/skills endpoint
* fix: remove background init timeout and allow skills reload retry
* deps: add PyYAML and GitPython to ai-requirements.txt
* feat: add fault injection system and external skills repository
* fix: Disable DeepSeek thinking mode to avoid reasoning_content errors
* fix: Skip offline compute nodes during project import
* fix: Import status module in project.py
* fix: Handle connection errors when stopping node console
* refactor: Remove MD5 calculation from node files listing
* fix: Export NodeFile schema to schemas module
* feat: Add detailed metadata to node files listing
* feat: Add API endpoint to list node files
* Fix snapshot restore does not work after export/import of project
* Warn to use 64-bit IOU images. Fixes #2716 32-bit IOU image support has been removed from the GNS3 VM.
* Fix: Improve Docker container deletion error logging
* Fix: Add exponential backoff to compute reconnection attempts
* Fix: Check compute connectivity before node creation in open()
* Fix: Check compute connectivity before open() during project deletion
* Fix: Add error logging when closing/deleting projects on computes
* Fix: Skip add_compute for existing computes when opening projects
* feat: add AI provider config files to .gitignore
* Fix: Use _computes instead of _project_created_on_compute for deletion check
* Fix: Check compute connection status before project deletion
* fix: extend remote compute image path conversion to all node types
* fix: send relative image path to remote compute nodes
* fix: handle directory access for static web-ui routes
* fix: add duplicate name validation when updating templates
* fix: avoid AttributeError when password is not provided in compute update
* fix: improve hostname validation error messages with allowed characters
* feat(compute): Fix Dynamips to listen on the internal port when ssh is used for auxiliary console
* feat(compute): Fix ambiguous log message related to the active console transport.
* feat(compute): Updated server host key to use the secure ssh-ed25519 instead of old ssh-rsa algorithm
* feat(compute): Fix missing SSH wrapping for auxiliary console
* feat(compute): Added AsyncioSSHServer dedicated tests
* feat(compute): add SSH console type support
* fix: include error details in LLM model config failure response
* Fix telnet console silent-proxy hang on non-ConnectionError exit (#2344)
## 2.2.59 08/05/2026
* Sync appliances
* Fix snapshot restore does not work after export/import of project
* Warn to use 64-bit IOU images. Fixes #2716 32-bit IOU image support has been removed from the GNS3 VM.
* Fix telnet console silent-proxy hang on non-ConnectionError exit (#2344)
## 3.1.0a1 25/04/2026
* New completely revamped Web interface.
* Add GNS3 Copilot AI agent back-end
* Web-wireshark: packet capture and live traffic analysis in the browser
* Fix using SSL with remote computes. Fixes https://github.com/GNS3/gns3-gui/issues/3733
* Add --url and --branch parameters to update-bundled-web-ui.sh
* Fix bug when custom_adapters is None in port_factory.py
* Have optional body in start node API endpoint
* Fix snapshots after merging
* Potential fix for pull request finding 'CodeQL / Information exposure through an exception'
* Refactored the way snapshots are handled in the server
* fix(symbols): add authentication to symbol raw endpoint
* fix(symbols): add CORS headers to symbol file responses
* Allow to find new project in sub dirs
* Enhancement: Refresh projects list without restarting the GNS3 server
* Fix accessing username in authentication.py
* Improved exception handling and telnet client disconnect
* Use get method for registry_version to avoid KeyError
* Add support for appliance format version 8
* Convert database template fields from PickleType to JSON
* feat(statistics): distinguish open vs closed project nodes
* fix(statistics): handle closed projects where nodes/links are dicts
* feat(controller): extend /statistics API with project, node and link stats
* Use FastAPI Lifespan Events
* feat(link): add control_offset field to LinkStyle
* feat(symbols): add DELETE API for removing custom symbol files
* Enhancement: Re-write current Telnet server implementation using telnetlib3 library
* feat: improve error handling for API configuration errors
* Enhancement Added link type support on the server side
* Ignore HTTPException received when closing a project
* Prevent router to be duplicated when running and add tests
* Fixed issue #1605 regarding Cisco slots causing configs to break
* feat: add VNC WebSocket console support for Docker and QEMU nodes
* Return 405 error for unsupported actions for other node types
* feat(telnet_server): improve error handling and connection management
* fix(telnet): handle connection race condition during broadcast
* Change first() to one_or_none() for image query
* Fix for duplicating Qemu nodes
* Minor optimizations to logic
* Fixed an issue with the server causing errors when uploading large images + Preparation for a smarter check when uploading images
* Implemented a smarter node_type system
* docs: restructure copilot docs and update node tools
* fix(acl): correct endpoint paths for users, groups, and roles
* fix(iou): return 405 error for unsupported suspend operation
* feat(api): enhance max_tokens field with robust null handling
* feat(docs): add AI prompting guide for configuration templates
* Deactivate 'use default IOU values' by default and update RAM/NVRAM values
* Make sure the node shows as stopped when the wrap console cannot be stopped. Ref https://github.com/GNS3/gns3-registry/pull/1010
* chore: update author name and copyright headers
* feat(docs): enhance AI chat API documentation with examples and details
* feat: add .claude directory to gitignore for API key security
* Revert "Fix QEMU serial console artifacts by filtering ANSI CPR responses in …"
* docs: add troubleshooting guide for datetime timezone issue
* Drop support for Python 3.9
* feat: add multi-user concurrency control design document
* docs: add troubleshooting guide for force kill residual processes
* Fixed the path traversal check
* Fix image handling
* Qemu VMs: only compute MD5 checksums for existing disks
* Copy config files and database from a previous version if it exists
* Add enable_http_auth in gns3_server.conf sample
* feat(compute): option to disable compute authentication
* tests(controller,port): short_name finishes successfully when port name is None
* fix(controller,port): handle None port name to prevent TypeError in short_name method
* fix(docker): handle container name conflict automatically
* feat(virtualbox): add fallback for VBoxManage executable detection
* feat: simplify port name assignment logic
* feat(ports): add null checks for port name in short name generation
* Remove unneeded rbac_repo in get_templates
* Use lists for tags instead of dicts
* Fix for resizing Qemu VM disks
* feat(templates): safely access settings dict keys
* feat(api): fix ETag handling and JSON serialization in template endpoint
* feat(api): add tag filtering to nodes and templates endpoints
* Update project schema and fix tests
* Add 'created_by' field to track project creator
* Fix updating packet filters
* Add vendor, model and netmiko_device_type fields to templates
* fix: handle RuntimeError in notification_manager emit()
* fix: busybox static link detection on Alpine/musl
* Fix bug when updating compute password to be empty
* Cancel tasks if controller cannot be started
* Enable parallel compression with zstandard. Fixes #2324
* Add Dynamips to Dockerfile dependencies
* Take populated disks into consideration when calculating PCI device ID
* Fix telnet keepalive options on macOS
## 2.2.58.1 12/04/2026
* Sync appliances
## 2.2.58 10/04/2026
* Bundle web-ui v2.2.58
* Sync appliances
* Snapshot refactoring
## 2.2.57 23/03/2026
* feat(telnet_server): improve error handling and connection management
* Deactivate 'use default IOU values' by default and update RAM/NVRAM values
* Make sure the node shows as stopped when the wrap console cannot be stopped
* tests(controller,port): short_name finishes successfully when port name is None
* fix(controller,port): handle None port name to prevent TypeError in short_name method
* fix: busybox static link detection on Alpine/musl
* Take populated disks into consideration when calculating PCI device ID
## 2.2.56.1 28/01/2026
* Fix telnet keepalive options on macOS
* Upgrade dependencies
* Drop Python 3.8 support
## 3.0.6 28/01/2026
* Sync appliances
* Fix creating Qemu disk image. Fixes #2542
* Disable checking for available disk space. Ref #2548
* Set default location of udhcpc in "/etc/network/udhcpc". Fixes #2582
* Support for Python 3.14
* Fix non-ASCII characters in project names
* Increase DB engine pool size and max overflow
* Enable ip cef in IOU L2 and IOU L3 base configs
## 2.2.56 21/01/2026
* Set default location of udhcpc in "/etc/network/udhcpc". Fixes #2582
* Upgrade pywin32 to v311
## 2.2.55 19/11/2025
* Docker API version requirements and process to handle older daemons
* Use docker_name property when creating a container
* Set name of container in Docker
* Support for Python 3.14
* Enable ip cef in IOU L2 and IOU L3 base configs
* Only build and push Docker image when releasing a new version
* Fix pushing Docker image to Docker hub
* Update security issues in README.md. Fixes #2535
* Add missing 'nat' template type in schema. Fixes #2529
* Resolve deprecation warnings of regex library
## 3.0.5 14/05/2025
* Bundle web-ui v3.0.5
* Sync appliances
* Use Ubuntu 24.04 LTS in Dockerfile. Ref #2523
* Fix tests and require Qemu version >= 2.4
* Fix adding pci_bridges to qemu vms
* Resolve deprecation warnings of regex library
* Remove OVMF_CODE_4M.secboot.fd and associated code
* Add edk2-stable202502 UEFI firmwares and try to first use firmwares from the ovmf package if installed. Fixes #2494
* Prettify TPM error message
* Fix bug in qemu_stdout message
* Try to detect swtpm and AppArmor issue. Ref https://github.com/GNS3/gns3-gui/issues/3725
* Fix Docker logs decoding. Ref #2522
* Add delay after starting a Docker container and adding connections in uBridge. Ref #2522
* Fix TypeError when reading Docker container logs. Ref #2522
* Allow an image to be uploaded to the controller again even if it is already in the database
* Fix controller not reporting an error if invalid options are passed to Qemu command line. Fixes #2517
* Replace "Docker hub" by "Docker repository" because it is possible to use different repositories
* Fix unable to add NAT cloud after configuring “allowed_interfaces” in configuration file. Fixes #2508
* Fix interface information API endpoint for Cloud/NAT devices
* Upgrade Jinja2 to v3.1.6. Fixes #2515
* Fix packet capture for links connected to a cloud node. Fixes #2513
* fix: check if remote-install.sh is being run as root
## 2.2.54 21/04/2025
* Bundle web-ui v2.2.54
* Add new method to find the IP address of a VBox GNS3 VM + allow NAT Network
* Add edk2-stable202502 UEFI firmwares and try to first use firmwares from the ovmf package if installed. Fixes #2494
* Try to detect swtpm and AppArmor issue. Ref https://github.com/GNS3/gns3-gui/issues/3725
* Fix Docker logs decoding. Ref #2522
* Add delay after starting a Docker container and adding connections in uBridge. Ref #2522
* Fix TypeError when reading Docker container logs. Ref #2522
* Replace "Docker hub" by "Docker repository" because it is possible to use different repositories
* Upgrade dependencies
* Improvements for remote-install.sh
## 3.0.4 25/02/2025
* Require minimum 8 characters for passwords
+4 -4
View File
@@ -1,4 +1,4 @@
FROM ubuntu:focal
FROM ubuntu:noble
WORKDIR /gns3server
@@ -31,7 +31,7 @@ RUN add-apt-repository ppa:gns3/ppa && apt update && DEBIAN_FRONTEND=noninteract
COPY . /gns3server
RUN mkdir -p ~/.config/GNS3/3.0/
RUN cp scripts/gns3_server.conf ~/.config/GNS3/3.0/
RUN mkdir -p ~/.config/GNS3/3.1/
RUN cp scripts/gns3_server.conf ~/.config/GNS3/3.1/
RUN python3 -m pip install .
RUN python3 -m pip install --break-system-packages --ignore-installed .
+374
View File
@@ -0,0 +1,374 @@
# GNS3 Server - Project Context for Claude Code
> This document provides project context information for the Claude Code AI assistant to work more efficiently.
---
## Project Overview
**Project Name**: GNS3 Server
**Description**: Network simulation server supporting the GNS3 network virtualization platform
**Primary Language**: Python
**Current Branch**: `feature/ai-copilot-bridge`
**Main Branch**: `master`
---
## Project Structure
```
gns3server/
├── agent/ # AI Copilot related modules
│ └── gns3_copilot/ # GNS3-Copilot AI Assistant
│ ├── agent/ # LangGraph Agent implementation
│ ├── tools_v2/ # Tool collection (device config, display commands, etc.)
│ ├── utils/ # Utility functions and helper modules
│ ├── gns3_client/ # GNS3 API client
│ ├── prompts/ # AI prompt templates
│ ├── agent_service.py # Agent service layer
│ └── project_agent_manager.py # Project Agent manager
│
├── api/ # API routes
│ └── routes/controller/ # Controller API
│ └── chat.py # AI Chat API endpoint
│
├── controller/ # Core controller
│ ├── project.py # Project management
│ └── ...
│
├── schemas/ # Pydantic data models
│ └── controller/
│ └── chat.py # Chat API Schema
│
├── db/ # Database module
│ └── tasks.py # Database tasks
│
└── docs/ # Documentation
└── gns3-copilot/ # AI Copilot documentation
```
---
## Key Module Descriptions
### 1. AI Copilot Data Flow
```
Tool Layer → Agent Layer → Service Layer → API Layer → Frontend
```
**Tool Output Format**: All tools return `dict` or `list[dict]`, automatically serialized to JSON in the Service layer
**Key Files**:
- `agent/gns3_copilot/tools_v2/*.py` - Tool implementations
- `agent/gns3_copilot/agent_service.py:460-473` - Event conversion logic
- `agent/gns3_copilot/utils/parse_tool_content.py` - Tool result parsing
### 2. SSE Event Types
| Type | Description |
|------|-------------|
| `content` | AI text streaming output |
| `tool_call` | LLM tool invocation (progressive parameters) |
| `tool_start` | Tool execution started |
| `tool_end` | Tool execution completed (output as JSON) |
| `error` | Error message |
| `done` | Stream ended |
### 3. Important Tools
| Tool Name | File | Function |
|-----------|------|----------|
| `ExecuteMultipleDeviceCommands` | `display_tools_nornir.py` | Read-only diagnostic commands |
| `ExecuteMultipleDeviceConfigCommands` | `config_tools_nornir.py` | Configuration commands |
| `VPCSMultiCommands` | `vpcs_tools_telnetlib3.py` | VPCS virtual PC commands |
| `GNS3TemplateTool` | `gns3_get_node_temp.py` | Get GNS3 templates |
| `GNS3CreateNodeTool` | `gns3_create_node.py` | Create nodes |
---
## Code Standards
### Static Code Analysis (Flake8)
The project uses **flake8** for static code analysis. You must run checks before committing code.
#### Running Flake8
```bash
# Activate virtual environment
source venv/bin/activate
# Check a single file
flake8 path/to/file.py
# Check the entire project
flake8 gns3server/
# Check a specific directory
flake8 gns3server/utils/
```
#### Common Flake8 Error Codes
| Code | Description | Example |
|------|-------------|---------|
| **F401** | Module imported but unused | `import os` never used |
| **F841** | Local variable assigned but never used | `x = 1` not used later |
| **F824** | `global` declaration never assigned | `global _bar` never assigned in scope |
| **E501** | Line too long (>79 characters) | Single line exceeds 79 characters |
#### Fix Examples
```python
# F401: Remove unused imports
# Bad
import os # Never used
# Good: Delete this line
# F841: Mark as intentionally unused
# Bad
def foo():
x = 1 # Never used
# Good: Use or mark as intentionally unused
def foo():
x = 1
_ = x # Mark as intentionally unused
# F824: Remove unnecessary global declaration
# Bad
def foo():
global _fernet # Never assigned in this scope
# Good: Remove global statement (if only reading)
def foo():
# Just read the global variable, no global declaration needed
pass
# E501: Break long lines
# Bad
raise RuntimeError("Encryption not initialized. Call init_encryption() first.")
# Good
raise RuntimeError("Encryption not initialized. Call init_encryption() first.")
```
#### Ruff (Alternative)
[Ruff](https://docs.astral.sh/ruff/) is a faster Python linter that can replace flake8, isort, black, and more.
```bash
# Install
pip install ruff
# Usage
ruff check gns3server/ # Check code
ruff check --fix gns3server/ # Auto-fix
ruff format gns3server/ # Format code
```
### Python Code Style
```python
# 1. Type annotations
def process_data(input_data: dict[str, Any]) -> list[dict[str, Any]]:
pass
# 2. Error handling
try:
result = tool.invoke(args)
except Exception as e:
logger.error("Tool failed: %s", e, exc_info=True)
return {"error": str(e)}
# 3. JSON serialization
if not isinstance(output, str):
output = json.dumps(output, ensure_ascii=False, indent=2)
```
### Import Order
```python
# 1. Standard library
import asyncio
import json
import logging
# 2. Third-party libraries
from langchain.tools import BaseTool
from pydantic import BaseModel
# 3. Local modules
from gns3server.agent.gns3_copilot.agent import agent_builder
from gns3server.controller import Controller
```
### Copyright Header
```python
# SPDX-License-Identifier: GPL-3.0-or-later
#
# GNS3-Copilot - AI-powered Network Lab Assistant for GNS3
#
# Copyright (C) 2025 Yue Guobin (岳国宾)
# Author: Yue Guobin (岳国宾)
#
# Project Home: https://github.com/yueguobin/gns3-copilot
```
---
## Git Commit Standards
### Commit Message Format
```
<type>(<scope>): <subject>
<body>
<footer>
```
### Type Categories
| Type | Description | Example |
|------|-------------|---------|
| `feat` | New feature | `feat(copilot): add user authentication` |
| `fix` | Bug fix | `fix(api): correct JSON serialization` |
| `docs` | Documentation update | `docs: update API design doc` |
| `refactor` | Refactoring | `refactor(agent): simplify state management` |
| `chore` | Build/toolchain | `chore: update dependencies` |
### Example
```
fix(copilot): serialize tool output to standard JSON format
Changed tool output serialization in AgentService._convert_event_to_chunk()
from str() to json.dumps() to ensure structured data is properly formatted.
Changes:
- Added json import to agent_service.py
- Modified on_tool_end event handling
Benefits:
- Frontend can parse tool results with JSON.parse()
- Chinese characters are preserved (not escaped)
Co-Authored-By: YueGuobin <yueguobin@outlook.com>
```
### IMPORTANT: Use Your Own Git Account for Commits
When creating git commits, **ALWAYS** use your own git account information for authorship.
**Before committing**, verify your git configuration:
```bash
# Check current git user configuration
git config user.name
git config user.email
# If incorrect, set your own information
git config user.name "Your Name"
git config user.email "your.email@example.com"
```
**For this project**, the current configured user is:
```
Name: YueGuobin
Email: yueguobin@outlook.com
```
You may use `Co-Authored-By` to credit contributors, but the `Author` field should always be **your own account**:
```bash
git commit -m "feat: add new feature
Co-Authored-By: ContributorName <contributor@example.com>"
```
---
## Development Notes
### 1. When Modifying Tool Output Format
**Must update the following locations**:
- `agent/gns3_copilot/tools_v2/*.py` - Tool implementation
- `agent/gns3_copilot/agent_service.py` - Event conversion
- `docs/gns3-copilot/ai-chat-api-design.md` - API documentation
### 2. Data Serialization Principles
- **Tool Layer**: Return Python `dict`/`list`
- **Service Layer**: Use `json.dumps()` for serialization
- **API Layer**: Use Pydantic validation then serialize to SSE
### 3. Logging
```python
logger.info("Operation started: project_id=%s", project_id)
logger.debug("Detailed info: data=%s", data)
logger.error("Error occurred: %s", error, exc_info=True)
```
### 4. Security Considerations
- Prohibit dangerous commands (reload, erase startup-config, etc.)
- Use `filter_forbidden_commands()` to filter commands
- Validate user input (project_id format, etc.)
---
## Common Commands
```bash
# Run tests
pytest tests/
# Static code analysis (must run before committing)
source venv/bin/activate
flake8 gns3server/
# Check a single file
flake8 path/to/file.py
# Syntax check
python3 -m py_compile gns3server/agent/gns3_copilot/agent_service.py
# Check git status
git status
# View git history
git log --oneline -15
# View file modification history
git blame file.py -L 100,120
# Commit code (verify your git user info first!)
git config user.name && git config user.email
git add files...
git commit -m "type(scope): description"
```
---
## Related Documentation
- [AI Chat API Design](./docs/gns3-copilot/ai-chat-api-design.md)
- [Command Security Policy](./docs/gns3-copilot/command-security.md)
- [LLM Model Configuration](./docs/gns3-copilot/llm-model-configs-api.md)
- [Context Window Management](./docs/gns3-copilot/context-window-management.md)
---
**Document Maintenance**: Please update this document promptly when project structure or development standards change.
+66 -5
View File
@@ -1,7 +1,7 @@
# GNS3 server repository
[![Style](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![GitHub Actions tests](https://github.com/GNS3/gns3-server/workflows/testing/badge.svg?branch=3.0)](https://github.com/GNS3/gns3-server/actions?query=workflow%3Atesting+branch%3A3.0)
[![GitHub Actions tests](https://github.com/GNS3/gns3-server/workflows/testing/badge.svg?branch=3.1)](https://github.com/GNS3/gns3-server/actions?query=workflow%3Atesting+branch%3A3.0)
[![Latest PyPi version](https://img.shields.io/pypi/v/gns3-server.svg)](https://pypi.python.org/pypi/gns3-server)
[![Snyk scanning](https://snyk.io/test/github/GNS3/gns3-server/badge.svg)](https://snyk.io/test/github/GNS3/gns3-server)
@@ -54,7 +54,50 @@ python3 -m pip install gns3-gui
python3 -m pip install gns3-server
```
The downside of this method is you will have to manually install all dependencies (see below).
#### Optional Features
GNS3 server supports optional features that can be installed as needed:
**AI Features** (Optional — includes AI Copilot and MCP):
```shell
python3 -m pip install gns3-server[ai-features]
```
AI-powered assistant for network topology design, automation, and MCP protocol support for AI agent integration.
**Development** (For contributors):
```shell
python3 -m pip install gns3-server[dev]
```
**Web Wireshark** (Optional):
```shell
pip install gns3-server && gns3server-web-wireshark-setup
```
Browser-based packet capture analysis using Wireshark in a Docker container.
**Combination Installation**:
You can install multiple optional features together:
```shell
python3 -m pip install gns3-server[ai-features,dev]
```
**Why optional?**
- Reduces installation size for users who don't need specific features
- Supports restricted environments (government, education, corporate) where certain libraries may not be allowed
- Faster installation for basic GNS3 usage
- Allows users to choose only the features they need
**Note:** If you install without optional extras, the server will work normally but optional features will be disabled. You can add features later by running the appropriate install command.
**Uninstalling AI Features:**
To remove AI Features dependencies (AI Copilot + MCP):
```shell
gns3server-uninstall-ai-features
```
This will remove all AI Copilot and MCP dependencies while keeping the core functionality intact. The server will continue to work, but AI features will be disabled.
Please see our [documentation](https://docs.gns3.com/docs/getting-started/installation/linux) for more details.
@@ -77,18 +120,30 @@ Note that Docker needs the script program (`bsdutils` or `util-linux` package),
### Setting up
These commands will install the server as well as all Python dependencies:
These commands will install the server with core Python dependencies:
```shell
git clone https://github.com/GNS3/gns3-server
cd gns3-server
git checkout 3.0
git checkout 3.1
python3 -m venv venv-gns3server
source venv-gns3server/bin/activate
python3 -m pip install .
python3 -m gns3server
```
**For AI Copilot development**, install with additional dependencies:
```shell
python3 -m pip install .[ai-features,dev]
```
**For development (tests and linting)**:
```shell
python3 -m pip install .[dev]
```
You will have to manually install other software dependencies (see above), for Dynamips, VPCS and uBridge the easiest is to install from our PPA.
### Docker container
@@ -99,6 +154,12 @@ Alternatively, you can run the GNS3 server in a container
bash scripts/docker_dev_server.sh
```
#### use Docker Compose
``` {.bash}
docker compose up -d
```
### Running tests
First, install the development dependencies:
@@ -131,4 +192,4 @@ Bug fixes or small improvements pull requests go here.
3.x development brand for the next major release.
**Never** use this branch for production. Pull requests for major new features go here.
**Never** use this branch for production. Pull requests for major new features go here.
+51
View File
@@ -0,0 +1,51 @@
# ==============================================================================
# GNS3 Copilot AI Agent Dependencies
# ==============================================================================
# Install with: pip install gns3-server[ai-features]
# Or directly: pip install -r ai-requirements.txt
# ==============================================================================
# Core AI and Automation Framework
# Note: aiosqlite is in core requirements.txt
langchain>=1.2.10
langchain-core>=1.7.3
langgraph>=1.2.19
langgraph-checkpoint>=4.0.0
langgraph-checkpoint-sqlite>=3.1.3
langgraph-checkpoint-postgres>=3.0.4
# Model Providers
langchain-openai>=1.7.3
langchain-anthropic>=1.7.10
langchain-google-genai>=4.4.2
langchain-aws>=1.9.0
langchain-ollama>=1.1.0
langchain-deepseek>=1.1.1
langchain-xai>=1.3.0
# Token Counting
tiktoken>=0.14.0
# LangSmith SDK
langsmith>=0.14.7
# Network Automation
paramiko>=5.1.0 # install version >= 5.0.0 to address CVE-2026-44405
netmiko>=4.8.0
nornir>=3.6.1
nornir-netmiko>=1.0.1
nornir-utils>=0.3.0
nornir-salt>=0.23.4
# Environment & Configuration
python-dotenv>=1.2.4
# Authentication
PyJWT>=2.15.1
psycopg-pool>=3.1.0
# Skills Repository Management
PyYAML>=6.0.3
GitPython>=3.1.0
# Note: httpx is only for testing (in dev-requirements.txt)
+7
View File
@@ -0,0 +1,7 @@
services:
gen3-server:
build:
context: .
dockerfile: Dockerfile
ports:
- "8001:3080"
+9 -6
View File
@@ -1,7 +1,10 @@
pytest==8.3.4
flake8==7.1.1
pytest-timeout==2.3.1
pytest-asyncio==0.25.2
requests==2.32.3
pytest==9.2.0
pytest-timeout==2.4.0
pytest-asyncio==1.4.1
httpx==0.28.1
httpx_ws==0.7.1
httpx_ws==0.9.0
pytest-random-order==1.2.0 # opt-in: --random-order --random-order-bucket=global (legacy suites are not shuffle-clean yet, see .claude/skills/gns3-api-test-writing)
pytest-cov==7.1.0
ruff==0.17.3
mypy==2.4.1
rust-just==1.59.0 # provides the `just` command runner, see justfile
+443
View File
@@ -0,0 +1,443 @@
Creative Commons Attribution-ShareAlike 4.0 International
Copyright (c) 2026 GNS3 Web UI Project
=======================================================================
Creative Commons Attribution-ShareAlike 4.0 International
Copyright (C) 2025 Creative Commons Corporation
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Creative Commons Attribution-ShareAlike 4.0 International Public
License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-ShareAlike 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and conditions.
Section 1 – Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
publication, distribution, public performance, public display, and
adaptation rights, and rights in database extensions and
collections.
d. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
e. Licensed Rights means rights granted to You subject to the terms
and conditions of this Public License, which are limited to all
Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
f. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
g. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
h. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and
of the Council of 11 March 1996 on the legal protection of
databases, as amended and/or succeeded, as well as other
essentially equivalent rights anywhere in the world.
i. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 – Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt,
where Exceptions and Limitations apply to Your use, this
Public License does not apply, and You do not need to
comply with its terms and conditions.
3. Term. The term of this Public License is specified in
Section 6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor – Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. Additional offer from the Licensor – Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You
apply.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights. Moral rights, such as the right of integrity, are
not licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to the
extent possible, the Licensor waives and/or agrees not to assert
any such rights held by the Licensor to the limited extent
necessary to allow You to exercise the Licensed Rights, but not
otherwise.
c. Patent and trademark rights are not licensed under this Public
License.
d. To the extent possible, the Licensor waives any right to collect
royalties from You for the exercise of the Licensed Rights,
whether directly or through a collecting society under any
voluntary or waivable statutory or compulsory licensing scheme.
In all other cases the Licensor expressly reserves any right to
collect such royalties.
Section 3 – License Conditions.
Your exercise of the Licensed Rights is expressly made subject to
the following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the
Licensor with the Licensed Material:
i. identification of the creator(s) of the
Licensed Material and any others designated to
receive attribution, in any reasonable manner
requested by the Licensor (including by
pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to
the extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI
or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may
be reasonable to satisfy the conditions by providing a URI
or hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the
Adapted Material from complying with this Public License.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to,
the Adapter's License You apply. You may satisfy this
condition in any reasonable manner based on the medium,
means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
Section 4 – Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 – Disclaimer of Warranties and Limitation of Liability.
a. Unless otherwise separately undertaken by the Licensor, to the
extent possible, the Licensor offers the Licensed Material as-is
and as-available, and makes no representations or warranties of
any kind concerning the Licensed Material, whether express,
implied, statutory, or other. This includes, without limitation,
warranties of title, merchantability, fitness for a particular
purpose, non-infringement, absence of latent or other defects,
accuracy, or the presence or absence of errors, whether or not
known or discoverable. Where disclaimers of warranties are not
allowed in full or in part, this disclaimer may not apply to You.
b. To the extent possible, in no event will the Licensor be liable
to You on any legal theory (including, without limitation,
negligence) or otherwise for any direct, special, indirect,
incidental, consequential, punitive, exemplary, or other losses,
costs, expenses, or damages that arise out of this Public License
or use of the Licensed Material, even if the Licensor has been
advised of the possibility of such losses, costs, expenses, or
damages. Where a limitation of liability is not allowed in full
or in part, this limitation may not apply to You.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 – Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply
with this Public License, then Your rights under this Public
License terminate automatically.
b. Where Your right to use the Licensed Material has terminated
under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured,
provided it is cured within 30 days of Your discovery of
the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 – Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 – Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License
is deemed unenforceable, it shall be automatically reformed to
the minimum extent necessary to make it enforceable. If the
provision cannot be reformed, it shall be severed from this
Public License without affecting the enforceability of the
remaining terms and conditions.
c. No term or condition of this Public License will be waived and
no failure to comply consented to unless expressly agreed to by
the Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public licenses. Notwithstanding,
Creative Commons may elect to apply one of its public licenses to
material it publishes and in those instances will be considered the
"Licensor." The text of the Creative Commons public licenses is
dedicated to the public domain under the CC0 Public Domain Dedication.
The text of the Creative Commons public licenses is dedicated to the
public domain under the CC0 Public Domain Dedication. Except for the
limited purpose of indicating that material is shared under a Creative
Commons public license or as otherwise permitted by the Creative Commons
policies published at creativecommons.org/policies, Creative Commons
does not authorize the use of the trademark "Creative Commons" or any
other trademark or logo of Creative Commons without its prior written
consent including, without limitation, in connection with any
unauthorized modifications to any of its public licenses or any other
arrangements, understandings, or agreements concerning use of licensed
material. For the avoidance of doubt, this paragraph does not form part
of the public licenses.
Creative Commons may be contacted at creativecommons.org.
=======================================================================
For the GNS3 Web UI documentation:
- Documentation License: CC BY-SA 4.0
- Project License: GPLv3 (see root LICENSE file)
- License URL: https://creativecommons.org/licenses/by-sa/4.0/
All documentation files in this directory are licensed under the
Creative Commons Attribution-ShareAlike 4.0 International License
(CC BY-SA 4.0).
=======================================================================
IMPORTANT: ShareAlike Requirements for Software Derivatives
Under the CC BY-SA 4.0 ShareAlike condition, if you create derivative
works based on this documentation, including software that is considered
a derivative of the documentation, you must:
1. **License your derivative work under CC BY-SA 4.0 or a compatible
license** (such as GPLv3, which is compatible with CC BY-SA 4.0)
2. **Attribute the original documentation** to the GNS3 Web UI Project
3. **Indicate if you modified the documentation** and retain
indications of previous modifications
4. **Include the license notice** and link to the CC BY-SA 4.0 license
What constitutes a derivative work:
- Translations of the documentation
- Adaptations, modifications, or enhancements to the documentation
- Software that incorporates substantial portions of the documentation
- Works based on the documentation's structure, organization, or content
Compatible licenses include:
- CC BY-SA 4.0 or later
- GPLv3 (GNU General Public License version 3)
- AGPLv3 (GNU Affero General Public License version 3)
- Other licenses approved as compatible by Creative Commons
For more information on CC BY-SA compatibility, see:
https://creativecommons.org/compatiblelicenses
If you are unsure whether your use constitutes a derivative work or
which license to apply, please consult the full CC BY-SA 4.0 license
text above or seek legal advice.
+160
View File
@@ -0,0 +1,160 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# GNS3 Server Documentation
---
## License
This documentation is licensed under the **Creative Commons Attribution-ShareAlike 4.0 International License (CC BY-SA 4.0)**.
⚠️ **Important - ShareAlike Requirement**: If you create derivative works based on this documentation (including software that incorporates substantial portions of the documentation), your work must also be licensed under **CC BY-SA 4.0 or a compatible license** (such as GPLv3).
- 📄 **Full License Text**: See [docs/LICENSE](./LICENSE)
- 🔗 **License URL**: https://creativecommons.org/licenses/by-sa/4.0/
- 📖 **Compatibility**: https://creativecommons.org/compatiblelicenses
**Dual License Structure**:
- 📚 **Documentation**: CC BY-SA 4.0 (this directory)
- 💻 **Software Code**: GPLv3 (see root [LICENSE](../LICENSE))
---
Technical documentation for the GNS3 server project, covering features, AI Copilot, development setup, and known issues.
## Directory Structure
```
docs/
├── README.md # This file
├── development-setup.md # Ubuntu 24.04 development environment setup
├── openapi.json # OpenAPI specification
├── features/ # Feature documentation
│ ├── compute-controller-setup.md # Controller + Compute architecture & configuration
│ ├── packet-filters.md # Link impairment filters: 13 kernel types + relay
│ ├── statistics-api.md # Aggregated statistics API for monitoring
│ ├── vnc-websocket-console.md # Browser-based VNC console via WebSocket
│ └── web-wireshark-business-process.md # Web Wireshark (Docker + xpra packet capture)
├── design/ # Design proposals & roadmaps (not yet implemented)
│ └── docker-image-type.md # Docker image types: vendor profile discriminator + registry
├── gns3-copilot/ # AI Copilot feature documentation
│ ├── netmiko_devices.md # Netmiko supported devices (366 types)
│ ├── template-based-configuration-roadmap.md # Future: template-based config with HITL
│ └── implemented/ # Implemented features
│ ├── chat-api.md # Chat API (SSE, session management)
│ ├── llm-model-configs.md # LLM model configuration system
│ ├── command-security.md # Command security and filtering
│ ├── context-window-management.md # Context window optimization
│ ├── node-control-tools.md # Node start/stop/suspend tools
│ └── multi-vendor-device-support.md # Multi-vendor device support
└── bugs/ # Known issues & bug reports
└── telnet-server-connection-race-condition.md
```
---
## Features
### Image inventory synchronization
Image Manager's **Sync Images** action reconciles the catalog with the configured
image directories. Automatic synchronization uses filesystem events and periodic
scans (`auto_discover_images`, `image_sync_interval`, default 900 seconds).
New and changed images are checksummed; missing records retain their IDs and
template associations and become available again when restored at the same path.
The `/v3/images/sync` API supports dry-run and forced checksum verification.
Database migration `d9e8a2b7c401` is required when upgrading an existing catalog.
Atomic image publication requires filesystem hard-link support.
### Controller + Compute Setup (`features/compute-controller-setup.md`)
Architecture and minimum configuration for setting up GNS3 Controller with remote Compute nodes. Covers compute node config, controller registration, and multi-compute deployment.
### Statistics API (`features/statistics-api.md`)
Aggregated server statistics API (`GET /v3/statistics`) for monitoring dashboards. Collects compute resources, project/node/link counts, and Web Wireshark container status in a single request.
### VNC WebSocket Console (`features/vnc-websocket-console.md`)
Browser-based VNC console access via WebSocket. The Controller acts as WebSocket-to-WebSocket relay, and Compute bridges WebSocket to TCP for QEMU/Docker VMs. Supports noVNC clients.
### API Error Responses (`features/api-error-responses.md`)
Unified error response format across all GNS3 API endpoints. Documents HTTP status codes, error types, and client-side error handling patterns.
### Web Wireshark (`features/web-wireshark-business-process.md`)
Web-based packet capture analysis using Docker + xpra HTML5 client. Zero-install Wireshark experience directly in the browser, integrated with GNS3 topologies.
### Marker (Traffic Insight) (`features/marker-traffic-insight.md`)
Real-time traffic insight via per-link BPF markers and project-level inherited definitions. A marker taps a link in uBridge, emitting match notifications and pcap capture on BPF hit; definitions fan out to every capable link automatically.
### Marker Tag Replay (`features/marker-tag-replay.md`)
Aggregate playback across links keyed by `tag`: once every marker under a tag is paused, their pcaps merge into one timestamp-ordered timeline; frames are decoded on demand via tshark into an isomorphic JSON protocol tree. The cross-link delta of the same packet measures the intermediate node's forwarding latency.
### Packet Filters (`features/packet-filters.md`)
Link impairment filters on both datapaths: the 13 kernel types (one netem qdisc, cls_bpf match-drop, the eBPF stateful classifier) with the per-frame evaluation order, plus the 5 relay userspace types; reconcile semantics, capability gating through `available_filters`, and the window/quota drop models.
### Docker exec Console (Vendor NOS) (`features/docker-exec-console.md`)
Console for vendor NOS containers (SR Linux, XRd, …) whose CLI is a TUI off PID 1: runs the vendor CLI via the Docker exec API, plus `GNS3_SKIP_INIT`/`GNS3_INTERFACE_NAMES` boot knobs and SKIP_INIT volume persistence.
### Cisco XRd Control Plane (`features/vendor-nos-xrd.md`)
Cisco XRd as a GNS3 Docker router: vendor path + shm/device injection (`GNS3_SHM_SIZE`/`GNS3_DEVICES`), config-file injection (`extra_configs`), udev masking (`GNS3_MASK_UDEV`) so privileged systemd containers don't disturb the host, and the host-readiness check.
### IOL Images with iol-runner (`features/iol-runner-docker.md`)
Cisco CML containerized IOL (e.g. `iol-xe/iol-xe:17-18-02`) as GNS3 Docker routers: generic unix-socket NIO (`GNS3_UNIX_SOCKET_NIO` — adapters wired via AF_UNIX datagram socket pairs instead of TAP/netns) plus `IOLDockerVM` (`GNS3_IOL_RUNNER=1` — per-start config generation, `/tmp/run` preparation, stale-socket cleanup, console on PID 1 stdio).
---
## Design & Roadmaps (`design/`)
### Docker Image Types (`design/docker-image-type.md`)
Proposed `image_type` discriminator on Docker templates plus a compute-side profile registry: vendor parameters graduate from environment markers into schema-gated fields, generic-feature applicability becomes declared capability data, and the existing markers remain as a compatibility fallback. Not a new node type — vendor images are content, not mechanism.
---
## GNS3 AI Copilot (`gns3-copilot/`)
### Implemented Features
| Feature | Description | Status |
|---------|-------------|--------|
| [Chat API](gns3-copilot/implemented/chat-api.md) | SSE streaming, session management, token statistics | Implemented |
| [LLM Model Configs](gns3-copilot/implemented/llm-model-configs.md) | Multi-level model config (system/group/user) | Implemented |
| [Command Security](gns3-copilot/implemented/command-security.md) | Command filtering, dangerous operation detection, HITL | Implemented |
| [Context Window Management](gns3-copilot/implemented/context-window-management.md) | Token optimization, content filtering, compression | Implemented |
| [Node Control Tools](gns3-copilot/implemented/node-control-tools.md) | Start/stop/suspend with batch ops and progress tracking | Implemented |
| [Multi-Vendor Support](gns3-copilot/implemented/multi-vendor-device-support.md) | Cisco, Huawei, Ruijie, VPCS with custom Netmiko drivers | Implemented |
### Reference
- [Netmiko Supported Devices](gns3-copilot/netmiko_devices.md) — 366 device types (154 SSH, 55 Telnet, 3 custom GNS3 drivers)
### Roadmap
- [Template-Based Configuration with HITL](gns3-copilot/template-based-configuration-roadmap.md) — Jinja2 templates with human-in-the-loop confirmations for device configuration and node creation
---
## Known Issues (`bugs/`)
- [Telnet Server Connection Race Condition](bugs/telnet-server-connection-race-condition.md) — `getpeername()` error when client disconnects during connection setup (High severity, Open)
- [Docker Link UDP Self-Loop](bugs/link-udp-self-loop.md) — intermittent one-way link (both ends handed the same UDP port by an allocation race); **fixed** (Medium severity)
- [SIGHUP on SSH Session Disconnect Kills All Nodes](bugs/sighup-session-disconnect-kills-nodes.md) — server survives (SIGHUP=reload) while every emulator child default-terminates without cleanup; sticky TAPs then 409 the first start; **root-caused, deployment guidance** (Medium severity)
---
## Development Setup (`development-setup.md`)
Quick-start guide for Ubuntu 24.04: install via PPA, set up dependencies, and run gns3-server from source.
---
## Related Documentation
- [GNS3 Server API Documentation](https://api.gns3.com/) — Interactive API docs (also available locally via `redoc.html`)
- [GNS3 Web UI Documentation](https://docs.gns3.com/)
- [LangGraph Documentation](https://langchain-ai.github.io/langgraph/)
---
_Last updated: 2026-09-01_
+101
View File
@@ -0,0 +1,101 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Docker Link UDP Self-Loop Bug (One-Way Link)
## Bug Report
**Date**: 2026-08-14
**Severity**: Medium (one-way connectivity, CPU burn from packet duplication; intermittent)
**Status**: **Fixed** — root cause found and unit-tested (same day)
**Component**: UDP port allocation — `gns3server/compute/port_manager.py`
(`get_free_udp_port` find-then-add race); secondary: `gns3server/controller/udp_link.py`
(`_prepare` accumulated stale `_link_data` on reset)
## Symptoms
Two Docker nodes (observed with Cisco XRd; node-type agnostic) linked on the
same compute cannot ping each other. Packet capture on the link shows only **one**
side sending ARP. The other side's traffic never appears on the link at all.
## Evidence (from the live occurrence)
Captured simultaneously on both nodes' uBridge `bridge1` (see diagnostics below):
| Direction | Result |
|---|---|
| A → B | works — A's ARP requests arrive at B's bridge, B replies |
| B → A | dead — B's replies/ICMP appear only on **B's own bridge** (duplicated ×2–×3), nothing arrives at A |
| B's `ethN` counters | RX ≈ TX ≈ 5000+ — B receives its own transmissions back |
| A's `ethN` counters | TX > 0, RX = 0 — never receives anything |
## Root Cause (confirmed)
**`PortManager.get_free_udp_port` had an unguarded find-then-add sequence.**
A link allocates the UDP port for **both ends concurrently**
(`asyncio.gather` in `UDPLink._prepare` → two `POST /ports/udp`). The route
handler is a sync `def`, so FastAPI executes the two requests **in parallel
threads**. Both threads ran `find_unused_port` (socket-probing, GIL-releasing)
before either reached `_used_udp_ports.add(port)` — the set add is idempotent,
so no error was raised and **both ends were handed the same port number**:
`lport == rport` on both NIOs, a literal self-loop.
Why it was *silent* and *asymmetric*:
- uBridge sets `SO_REUSEADDR` on UDP NIO sockets (`ubridge/src/nio_udp.c`), so
the second bind of the same port **succeeds** instead of failing with
`EADDRINUSE` — link creation returned success.
- With two sockets bound to the same port, the kernel delivers to one of them
(last bound wins). The node that started later — in the live case B,
restarted ~77 s after A — received **everything**: A's packets *and* its own
transmissions echoed back. The 77 s restart did not cause the corruption; it
only decided which end starves.
- The same-compute condition is part of the trigger: both allocations hit the
same `PortManager` instance (a cross-compute link races two processes and
cannot self-collide).
A second, smaller defect was found while auditing: `UDPLink._prepare()`
**appended** to `self._link_data` but the committed NIOs are always taken from
indices 0/1 — after `reset()` (delete + create on the same object) the stale,
already-released port pair was re-committed and the freshly allocated ports
were leaked.
## Fix
| Change | Where |
|---|---|
| `threading.RLock` making find-then-add (and reserve/release) atomic for TCP and UDP | `gns3server/compute/port_manager.py` |
| `_prepare()` rebuilds `_link_data` from scratch instead of appending | `gns3server/controller/udp_link.py` |
| Regression tests: threaded allocation never returns duplicates (red on the old code); `reset()` commits the fresh mirrored pair with `lport != rport` | `tests/compute/test_port_manager.py`, `tests/controller/test_udp_link.py` |
## Diagnostics (uBridge console is the fast path)
1. **uBridge console** — each node's uBridge listens on a Unix socket
`/run/user/1000/gns3/ubridge-<node_id>.sock`; connect and send:
`bridge list` (NIO count per bridge), and
`bridge start_capture bridge<N> "/tmp/ub-<node>.pcap"` /
`bridge stop_capture bridge<N>` to capture what the bridge actually forwards.
Comparing the two ends' pcaps localizes the break immediately.
2. **Container counters** — `docker exec <cid> ip -s link show ethN`:
TX>0/RX=0 → peer never returns; RX≈TX huge with µs-scale duplicates → self-loop.
3. **UDP sockets** — `ss -uln` (no `-p`; uBridge runs setuid-root so process names
are hidden, ports are visible): a two-node link owns exactly two "orphan" UDP
ports. **One port instead of two = this bug.**
4. **Recovery** — delete and re-create the link (or stop/start both nodes);
with the fix, the corruption no longer occurs in the first place.
Note: a Docker node's in-container `ethN` is a **TAP device** whose file descriptor
lives inside uBridge (the interface is created host-side, then moved into the
container namespace and renamed). There is no veth host end to look for — do not
waste time hunting for one in the host namespace.
## Related
- `docs/features/vendor-nos-xrd.md` — troubleshooting table entry pointing here.
- Link-create batch optimization (`controller/udp_link.py`, project-open bulk path)
was exonerated: the pool path allocates sequentially in one handler and cannot
self-collide.
+191
View File
@@ -0,0 +1,191 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# NetworkManager Releases Enslaved TAP Anchors from Their Bridge (Silent Link Death)
## Bug Report
**Date**: 2026-10-05 (root-caused; the same signature first hit on 2026-10-01 during the Ethernet-switch kernel-datapath development)
**Severity**: High on affected hosts (one link dies silently — API and UI stay green; ~50 % per re-enslavement while NetworkManager has not yet assumed the TAP; environment-dependent and intermittent)
**Status**: **Root-caused; host-side fix verified.** The NetworkManager declaration (`unmanaged-devices`) takes the reproducing loop from 19-20/40 to 0/40 and lets the e2e scenario pass with all test-side workarounds disabled. Test-side best-effort hardening is shipped (`harness.unmanage_from_networkmanager`); a product-side guard remains an open decision.
**Component**: Host environment — NetworkManager × uBridge-created TAP anchors. No GNS3 code path performs the detaching operation: gns3-server and uBridge log nothing and their bookkeeping stays intact.
## Symptoms
On a kernel-datapath link, after a **re-enslavement of the TAP anchor** — a link delete + recreate, a port re-join after a peer restart — the link may die: ping 0 %, routing protocols never form — while every API/UI surface reports health (`kernel_datapath: true`, no error, no log). The node, the emulated router and the anchor device itself keep running; only the bridge membership is gone.
Self-heal exists but nothing forces it: any subsequent NIO update re-checks `/sys/class/net/<bridge>/brif/<anchor>` and re-attaches (`EthernetSwitch.update_nio`'s "not joined" branch, and the equivalent attach path per node type), which is why the state heals on the next filter change, suspend toggle or peer restart. The *first* enslavement of a freshly created TAP is stable in every observation; the hazard is re-enslavement before NetworkManager has assumed the device (a window of minutes), at ~50 % per attempt.
## Forensic signatures (what the corpse looks like)
- `/sys/class/net/<bridge>/brif/<anchor>` missing, `/sys/class/net/<anchor>/brport/` gone — the port was released, not the device destroyed: **ifindex unchanged**, `ip -d link show` reports no master.
- Flags drop `IFF_PROMISC|IFF_ALLMULTI` (0x300, set by the kernel bridge on enslavement): as seen with a 50 Hz brif sampler, `fl 0x1303 → 0x1003` while administrative UP is kept.
- The release lands **58-87 ms after the join** — after the attach API has already returned success, so `wait_until`-style checks see the join and the next traffic sample sees the blackhole.
- No `brctl delif` (or any netlink write) from any GNS3 process; server-side registrations (`_kernel_ports`, NIO state) are untouched; uBridge logs stay clean.
- `nmcli device status` shows the anchor as managed by NetworkManager: `disconnected` before it assumes the device, `connected (externally)` after.
## Root Cause (NetworkManager side, source-level)
On hosts where NetworkManager manages the anchors — it claims uBridge-created tun/tap devices by default (`nmcli device` then shows them managed) — NM's device state machine resolves the fresh enslavement in its own favour while the device is in its pre-assumption window:
1. An **external enslavement** triggers an assumption recheck — NetworkManager commit `a6ceb382e9` ("device: connect slave assumption recheck on external enslavement") exists precisely for `ip link set <dev> master <bridge>` performed by someone else.
2. The recheck activates (assumes) the device, and activation enforces that **a connection which does not declare a master must not keep its kernel master**: the slave is force-released, reason `NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED` — NetworkManager commit `ec12912908` ("device: enforce the absence of a master during activation"). This is the detaching operation; it runs several asynchronous state-machine steps after the enslavement, which is the 60-80 ms latency.
3. Once the device is assumed (`connected (externally)`), later external enslavements take the opposite path: **external changes must not touch the device** — NetworkManager commit `3127fb0d17` ("device: don't let external changes cause a release of the slave", `configure = FALSE`, "let the device be"). The model is updated; the kernel is left alone. This is why assumed taps were stable across 14 re-enslavements in the field, and why the hazard window ends at assumption.
Both processes' worlds are mutually exclusive here: NM requires "no master during activation", the datapath requires "enslaved to the switch/per-link bridge" — there is no configuration in which both hold. The sanctioned resolution is a jurisdiction declaration (mark the devices unmanaged), not a race.
Docker veth host ends are not NM-managed (and the veth naming/type heuristics historically keep NM away — see History), so only the TAP anchor families are affected: `gd` (Dynamips), `gq` (QEMU), `gi` (IOU), `gx` (IOL runner containers), and switch-absorbed anchors.
## Reproduction (minimal, gns3-server not involved)
A self-contained reproducer — one uBridge, one TAP, one kernel bridge, an enslavement loop — needs none of the server. It drives uBridge's control socket through the repository's own client, so no build step and no extra dependencies beyond the venv:
```python
#!/usr/bin/env python3
"""Minimal reproducer: NetworkManager releases an enslaved TAP from its bridge.
Run from the gns3-server repo root on an affected host (Linux + NetworkManager
managing the TAPs; uBridge installed with cap_net_admin):
venv/bin/python nm_tap_release_repro.py # 40 re-enslavements
nmcli device set gdlab-nm managed no # the A/B flip (same tap!)
venv/bin/python nm_tap_release_repro.py # -> 0 releases
The tap and bridge are kept between runs (same device = same NM state).
Clean up afterwards:
venv/bin/python nm_tap_release_repro.py --cleanup
"""
import asyncio
import os
import shutil
import subprocess
import sys
import time
sys.path.insert(0, os.getcwd()) # run from the repo root for gns3server imports
from gns3server.compute.ubridge.ubridge_hypervisor import UBridgeHypervisor
TAP = "gdlab-nm"
BRIDGE = "gns3lab-nm"
SOCK = "/tmp/nm_tap_release_repro.sock"
ITERATIONS = 40
SAMPLE_MS = 200 # membership sampled at ~1 kHz for this long after each addif
def in_bridge():
return os.path.exists(f"/sys/class/net/{BRIDGE}/brif/{TAP}")
async def main():
ubridge = shutil.which("ubridge")
if not ubridge:
sys.exit("ubridge not found in PATH")
if os.path.exists(SOCK):
os.unlink(SOCK)
proc = subprocess.Popen(
[ubridge, "-U", SOCK], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, cwd="/tmp"
)
try:
h = UBridgeHypervisor(socket_path=SOCK)
await h.connect()
async def send(cmd):
try:
await h.send(cmd)
except Exception:
pass # ENOENT during setup/teardown is expected
if "--cleanup" in sys.argv:
await send(f'tap delete "{TAP}"')
await send(f'brctl delete "{BRIDGE}"')
return
await send(f'tap create "{TAP}"') # no-op if the tap already exists
await send(f'brctl create "{BRIDGE}"')
await send(f'link set "{BRIDGE}" up')
await send(f'brctl vlanfiltering "{BRIDGE}" on')
releases, latencies = 0, []
for _ in range(ITERATIONS):
await send(f'link set "{TAP}" up')
await send(f'brctl addif "{BRIDGE}" "{TAP}"')
t0 = time.time()
for _ in range(SAMPLE_MS):
await asyncio.sleep(0.001)
if not in_bridge():
releases += 1
latencies.append(round((time.time() - t0) * 1000, 1))
break
await send(f'brctl delif "{BRIDGE}" "{TAP}"')
await send(f'link set "{TAP}" down')
await asyncio.sleep(0.005)
print(f"releases: {releases}/{ITERATIONS} re-enslavements", flush=True)
if latencies:
print(f"release latency after join (ms): {latencies[:10]}")
print(f"expect ~19-20/40 while NetworkManager manages {TAP}, "
f"0/40 after `nmcli device set {TAP} managed no`")
finally:
proc.kill()
asyncio.run(main())
```
How the numbers are produced:
- 40 iterations; each is one **re-enslavement**: `link set <tap> up`, `brctl addif`, then membership sampled at ~1 kHz for 200 ms, then `brctl delif` + `link set down`.
- A **release** is counted when `/sys/class/net/<bridge>/brif/<tap>` disappears inside that 200 ms window; the script prints the release latency after the join (the NM release lands at 58-87 ms).
- The tap is kept between runs, so the A/B flip is single-variable on the *same* device; a fresh device would reset NM's assumption state (the first enslavement of a fresh tap is always stable).
- The numbers below were measured on a host **without** the declaration from *Fix*. On a host that already carries it the tap is unmanaged from birth and the loop prints `0/40` by design; to re-observe the baseline there, temporarily remove the conf.d file (`sudo rm /etc/NetworkManager/conf.d/99-gns3-datapath.conf && sudo systemctl reload NetworkManager`) or run on an un-declared host. A runtime `nmcli device set <tap> managed yes` is *not* enough — the configuration match wins (the device stays `unmanaged` and the loop still prints 0/40; measured).
Measured on an affected host (same code, five baseline runs, then the A/B between runs):
| Condition | Releases / 40 re-enslavements |
|---|---|
| NM-managed (default) | 19, 20, 19, 20, 20 |
| `nmcli device set <tap> managed no`, same tap | **0** |
| re-managed (`nmcli device set <tap> managed yes`), same tap | 20 |
e2e-level reproduction: `tests/e2e/test_ethernet_switch_kernel_datapath.py::test_ethernet_switch_kernel_fast_path` fails at its link delete/recreate step (`wait_ping` after the anchor re-join) roughly half of fresh runs on an NM host — it failed twice consecutively on 2026-10-05 during the 3.1 rebase validation before the fix.
## Fix
Three layers, of which the first is the verified root fix:
1. **Host declaration** — `/etc/NetworkManager/conf.d/99-gns3-datapath.conf`:
```ini
[keyfile]
unmanaged-devices=interface-name:gd*;interface-name:gq*;interface-name:gi*;interface-name:gx*;interface-name:gv*;interface-name:gns3*
```
then `systemctl reload NetworkManager`. Devices matching are unmanaged from birth (also future ones and after re-creations); hosts without NM treat the file as inert. Verified on the affected host: minimal loop **0/40**, and the e2e scenario passes with the test-side workaround disabled (pure host config); re-verify with the reproducer below — same tap, expect 0/40 after the reload. This belongs in installers/documentation, not in the server (no root; and the server must not reconfigure the host's NM).
2. **Test-side best effort** — `harness.unmanage_from_networkmanager(*taps)` runs `nmcli device set <tap> managed no` where nmcli exists (no-op otherwise); kernel-datapath scenarios that re-enslave anchors call it after their nodes have booted. This keeps the e2e deterministic on un-declared hosts.
3. **Product-side guard** — open decision: a bounded post-attach re-check (~250 ms) that re-attaches once and warns (naming NetworkManager), a warn-only variant, or nothing (documentation only). Until decided, an undeclared host relies on the existing heal-on-next-update path.
## Scope
- Affected: Linux hosts where NetworkManager manages the TAPs — desktop-native `gns3server` deployments (the most common GNS3 form factor for Linux users). Every TAP anchor family, the switch fast path and per-link kernel links alike.
- Not affected: the GNS3 VM (its Ubuntu-server stack is netplan/systemd-networkd, no NM — verified against the gns3-vm repository), hosts without NM, Docker veth anchors, relay links, cross-compute links (relay by default).
- Blast radius of one occurrence: exactly one link, silently dead; no incorrect data, but it can mislead an experiment's conclusions (e.g. "this protocol never converges here") and it mimics the project's own "API green, data plane dead" bug class — during the rebase validation it was triaged as a regression until the timing signature (join, then +60 ms release with no command) identified it as environmental.
## History
- **2026-10-01**: the same signature first hit during the Ethernet-switch development, described then as "an anchor occasionally losing its bridge membership right after a `ports_mapping` update"; reproduced with QEMU, IOU and Dynamips peers (all TAPs) and never with Docker veths; the then-unknown cause was worked around by making VLAN reconfiguration in-place (no re-enslavement) and the failure mode was assumed gone "by construction". See `docs/features/ethernet-switch-kernel-datapath.md`.
- **2016**: the same NM-vs-GNS3 jurisdiction class hit Docker veths — NM configured them like plain NICs and a container DHCP server hijacked the host's default route (issue #440, closed). Upstream worked around it by renaming `gns3-veth…` to `veth-gns3-…`, the commit message reading "the name create different behavior with network manager" (`59c1e125d`). NM's management heuristics even depend on interface names — the rename moved the veths into NM's ignored namespace.
- **2026-10-05**: root-caused with the minimal harness and the single-variable A/B; host fix applied and verified; test-side hardening shipped; full write-up (this document).
## Related
- NetworkManager commits: [`a6ceb382e9`](https://codetest.hyprland.org/fdo-mirrors/NetworkManager/commit/a6ceb382e90a9ebc278e380a3b204ad8c2c543c4), [`ec12912908`](http://git.baserock.org/cgit/delta/NetworkManager.git/commit/src/devices/nm-device.c?id=ec12912908d739459ff3913917e9937500345c2a), [`3127fb0d17`](https://codetest.hyprland.org/fdo-mirrors/NetworkManager/commit/3127fb0d17bff0b250218c7bf82b4335b5290825).
- GNS3 issue [#440](https://github.com/GNS3/gns3-server/issues/440) and commit `59c1e125d` (veth rename).
- `docs/design/ubridge-l2-anchor-spec.md` — "NetworkManager releases managed TAPs from bridges" subsection (short form).
- `docs/features/ethernet-switch-kernel-datapath.md` — the corrected account of the 2026-10-01 incident.
- `tests/e2e/harness.py` — `unmanage_from_networkmanager`.
@@ -0,0 +1,80 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# SIGHUP on SSH Session Disconnect Kills All Node Processes (Server Survives)
## Bug Report
**Date**: 2026-10-29 (incident), root-caused 2026-10-30
**Severity**: Medium — every node dies silently while the server stays up; only affects interactive-session launches
**Status**: Root-caused; addressed by deployment guidance (systemd / `setsid nohup` / tmux), no code change. Product-side hardening options noted under *Fix* are deliberately deferred.
**Component**: `gns3server/server.py` `_signal_handling()` — the SIGHUP→reload semantics — interacting with default SIGHUP disposition in every emulator child (uBridge, IOU, Dynamips, QEMU, VPCS) and with the kernel-datapath persistent anchor TAPs.
## Symptoms
`gns3server` started directly from an interactive SSH session (plain `gns3server ... &`, no `nohup`/`setsid`/tmux) with running kernel-datapath nodes. When the SSH client disconnects:
- Every node becomes `stopped`, but **gns3server keeps running** (it treats SIGHUP as reload).
- The server log records **no stop operation at all** — no `stopping N nodes`, nothing. The nodes simply vanish from its perspective.
- Anchor TAPs (`gi*`, `gq*`, `gd*`, …) survive as orphans — the children died without running any cleanup.
- The next `start`/`start_all` typically fails on the first round with
`Error while sending command 'tap create "gi…"': Could not create TAP gi…: Device or resource busy`
(HTTP 409 on the batch endpoint) and succeeds on the retry seconds later, once the sweep has won.
## Evidence (from the live occurrence)
Second-level correlation between the system journal and the GNS3 server log, 2026-10-29:
| Time | Source | Record |
|---|---|---|
| 01:43:41 | journalctl / sshd | `Received disconnect from 192.168.1.140 port 48684:11: disconnected by user` |
| 01:43:41 | gns3.log | `Server has got signal SIGHUP, reloading...` (server.py:164) followed by `Controller is reloading` |
| 01:43:42 | gns3.log | node consoles dying: repeated `EOFError: telnet connection closed` (R-3/R-4/R-5) |
Supporting state:
- The server process ran uninterrupted from 01:13 through the incident (single PID, never restarted); its PPID became 1 — the launching shell was gone.
- Five IOU nodes plus their uBridge hypervisors were dead; no `stopping`/`stopped` lines exist for this project in the log.
- Dozens of anchor TAPs still present on the host afterwards, still enslaved to their `gns3*` per-link bridges — only an unclean death leaves that surface behind.
- uBridge's own stderr during the recovery attempt shows the sweep fighting the leftovers: `Error configuring kernel: File exists` / `No such file or directory`, then the `tap create … Device or resource busy` failure at 23:51:55, and clean hypervisor starts at 23:52:03–22 on the immediate retry.
## Root Cause (confirmed)
Standard Unix session machinery, not a GNS3 logic error — but GNS3's mixed signal dispositions turn it into a silent mass death:
1. SSH disconnect → sshd tears down the PTY → kernel sends **SIGHUP to the session**; bash, on receiving SIGHUP, **forwards it to all its jobs** — i.e. the whole process group: gns3server *and* every emulator/ubridge child it spawned.
2. gns3server installs a SIGHUP handler (`server.py` `_signal_handling`, upstream since 2013) whose semantics are *reload* — so the server absorbs the signal and stays up.
3. The children have the **default SIGHUP disposition** and terminate immediately, bypassing every cleanup path (`stop()`, `_delete_anchor_taps`, port release). The persistent anchor TAPs — designed to outlive their creator and be swept on the next start — are exactly what remains behind.
4. `_create_anchor_taps` (kernel_datapath.py) sweeps same-name leftovers with a suppressed `tap delete` before `tap create`, but that sweep assumes an *unheld* leftover. On the first start after this incident the delete did not take effect yet, so `tap create` surfaced EBUSY; the second round, seconds later, succeeded.
## Fix
No code change required; the fix is how the server is launched:
- **systemd** (the gns3vm deployment — a service is outside every SSH session, gets `Restart=on-failure`, journald logging, and ordered SIGTERM shutdown that cleans up nodes properly), or
- `setsid nohup gns3server … >/dev/null 2>&1 &` (ignored dispositions are inherited across fork/exec, protecting the whole child tree), or
- tmux/screen.
Recovery after hitting it: start the nodes again (the anchor sweep wins on the second round); manually `ip link delete <tap>` only for interfaces that stay DOWN and block a start.
Product-side hardening (deferred, recorded for a rainy day):
- children spawned with SIGHUP ignored or `start_new_session=True` would make the whole tree immune; and
- `_create_anchor_taps` could take the sysfs-check + short-grace retry pattern its sibling `_delete_anchor_taps` already uses (`kernel_datapath.py`), so a *held* leftover self-heals instead of failing the first start with 409.
## Scope
- Affected: bare-metal `gns3server` launched from an interactive SSH/login session without `nohup`/`setsid`/tmux — including "typed `&` and forgot about it" runs that stay up for days.
- Not affected: the GNS3 VM and any systemd/service deployment; a clean `exit` from the shell usually leaves jobs alive (bash's `huponexit` is off by default, and its SIGHUP forwarding only fires on disconnect-type hangups), which is why this bites intermittently rather than always.
- Blast radius: all nodes on the server, silently, with no log trail — plus a 409 on the first start attempt afterwards.
## Related
- `gns3server/server.py` — `_signal_handling()`: SIGHUP→`Controller.instance().reload()` since 2013 (commit `798f0367b`, "Catch SIGTERM, SIGINT, SIGHUP and SIGQUIT…").
- `gns3server/compute/kernel_datapath.py` — `_create_anchor_taps` (the sweep) and `_delete_anchor_taps` (the sysfs+grace retry pattern a future hardening would mirror).
- `docs/bugs/networkmanager-tap-release.md` — same "stale TAP surface after an uncooperative host event" family, different mechanism.
- `docs/features/*-kernel-datapath.md` — the anchor-TAP lifecycle these leftovers come from.
@@ -0,0 +1,316 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Telnet Server Connection Race Condition Bug
## Bug Report
**Date**: 2026-03-14
**Severity**: High
**Status**: Open
**Component**: Telnet Server (`gns3server/utils/asyncio/telnet_server.py`)
## Error Logs
```
2026-03-14 15:21:31 ERROR asyncio:1879 Unhandled exception in client_connected_cb
transport: <_SelectorSocketTransport fd=67 read=polling write=<idle, bufsize=0>>
Traceback (most recent call last):
File "/home/yueguobin/myCode/GNS3/gns3-server/gns3server/utils/asyncio/telnet_server.py", line 215, in run
await self._process(network_reader, network_writer, connection)
File "/home/yueguobin/myCode/GNS3/gns3-server/gns3server/utils/asyncio/telnet_server.py", line 305, in _process
client_info = connection_key.get_extra_info("socket").getpeername()
File "/usr/lib64/python3.13/asyncio/trsock.py", line 77, in getpeername
return self._sock.getpeername()
~~~~~~~~~~~~~~~~~~~~~~^^
OSError: [Errno 107] Transport endpoint is not connected
```
## Root Cause Analysis
### Architecture
The GNS3 Telnet server architecture supports multiple concurrent client connections to a single node console:
```
┌──────────────────────────────────────────────────────────┐
│ Node (VPCS/Docker/Router/Switch, etc.) │
│ - Independent process │
│ - Normal operation, processing business logic │
└────────────────────┬─────────────────────────────────────┘
│ stdout (device output)
│
┌────────────▼─────────────────────────────────────┐
│ AsyncioTelnetServer (Telnet Proxy Server) │
│ - Reads output from Node │
│ - Broadcasts to all connected clients │
│ - ← ← Bug occurs at this layer ← ← │
└────────────┬─────────────────────────────────────┘
│
┌────────────┼────────────┬──────────────────┐
│ │ │ │
Web Console Auto Script Client 1 Client 2
(long-lived) (quick disco) (normal) (normal)
```
### The Race Condition
The bug occurs in the broadcast logic when a client disconnects while the server is iterating through connections:
**Timeline**:
```
t1: Clients A, B, C connect to the same Telnet port
t2: Device has output (e.g., log message)
t3: Client A receives data and script immediately disconnects (FIN sent)
t4: Server hasn't read EOF yet (event loop hasn't checked this connection)
t5: Server iterates through connections to broadcast data
t6: When iterating to Client A, getpeername() is called → OSError!
```
### Code Location
**File**: `gns3server/utils/asyncio/telnet_server.py`
**Line**: 305
**Problematic Code**:
```python
# Line 304-305
for connection_key in list(self._connections.keys()):
client_info = connection_key.get_extra_info("socket").getpeername() # ← OSError here
connection = self._connections[connection_key]
try:
connection.writer.write(data)
await asyncio.wait_for(connection.writer.drain(), timeout=10)
except:
log.debug(f"Timeout while sending data to client: {client_info}, closing and removing from connection table.")
connection.close()
del self._connections[connection_key]
```
### The Core Issue
The `getpeername()` call is **outside** the try-except block, so any OSError from it is not caught.
Additionally, the top-level exception handler at line 216 only catches `ConnectionError`:
```python
# Line 212-227
try:
await self._write_intro(network_writer, echo=self._echo, binary=self._binary, naws=self._naws)
await connection.connected()
await self._process(network_reader, network_writer, connection)
except ConnectionError: # ← Only catches ConnectionError
async with self._lock:
network_writer.close()
if self._reader_process == network_reader:
self._reader_process = None
if self._current_read is not None:
self._current_read.cancel()
await connection.disconnected()
del self._connections[network_writer]
```
**Python Exception Hierarchy**:
```
BaseException
└─ Exception
├─ ConnectionError ← Only this is caught
│ ├─ ConnectionResetError
│ ├─ BrokenPipeError
│ └─ ...
└─ OSError ← Actually thrown! (not a subclass of ConnectionError)
└─ [Errno 107] Transport endpoint is not connected
```
Since `OSError` is **not** a subclass of `ConnectionError`, it propagates uncaught to the asyncio event loop.
## Impact Assessment
### Immediate Effects
| Impact | Severity | Description |
|--------|----------|-------------|
| Connection interrupted | 🔴 High | The connection triggering the exception is terminated |
| Resource leak | 🟠 Medium | socket/connection not properly cleaned up |
| Other clients affected | 🟡 Low | Other clients on same port may miss broadcast data |
| Service stability | 🟡 Low | Long-running may accumulate zombie connections |
### User-Reported Symptoms
After this error occurs, users report:
1. **Cannot open the affected node** - Clicking on the node fails
2. **Cannot close the node** - Close button doesn't work
3. **"Node not found" errors** - Operations on the node return 404
4. **Refresh fixes it temporarily** - Reloading the page restores functionality
### Why This Happens
When the uncaught `OSError` occurs, the cleanup code at lines 217-227 **never executes**:
```python
except ConnectionError:
async with self._lock:
network_writer.close() # ✗ Not executed
if self._reader_process == network_reader:
self._reader_process = None # ✗ Not executed
if self._current_read is not None:
self._current_read.cancel() # ✗ Not executed
await connection.disconnected() # ✗ Not executed
del self._connections[network_writer] # ✗ Not executed
```
This leads to:
- **Resource leaks**: socket and writer not closed, file descriptors leaked
- **State inconsistency**: `_connections` dictionary retains disconnected connections
- **Potential deadlocks**: Locks may not be released if exception occurs while holding them
- **Subsequent operation failures**: Future operations may access zombie connections
### Effect on Node Process
**The Node process itself is NOT affected**:
- Node continues running normally
- Node's stdout has already been read by the proxy
- The bug occurs during the broadcast phase, after data has been read
The issue is in the **Telnet Proxy layer**, not the node itself.
## Trigger Conditions
This error is more likely to occur with:
| Scenario | Probability | Reason |
|----------|-------------|--------|
| **Automated scripts** | 🔴 High | Fast connect → execute → disconnect, small time window |
| **Manual operation** | 🟡 Medium | Can occur (e.g., closing terminal, network fluctuation) |
| **Normal usage** | 🟢 Low | Human operations slower, server usually detects EOF first |
### Typical Scenario
1. User opens Web Console (long-lived connection)
2. Automated script connects → executes command → quickly disconnects
3. While script disconnects, device has output that needs broadcasting
4. During connection iteration, script connection already closed
5. `getpeername()` call fails with OSError
## Related Issues
A secondary issue was found in the error handler:
**File**: `gns3server/api/server.py`
**Line**: 162
```python
@app.exception_handler(ControllerNotFoundError)
async def controller_not_found_error_handler(request: Request, exc: ControllerNotFoundError):
log.error(f"Controller not found error in {request.url.path} ({request.method}): {exc}")
# ^^^^^^^^^^^^^^^
return JSONResponse(...)
```
**Problem**: `request.method` only exists in HTTP requests, not WebSocket connections.
When a WebSocket request triggers this exception handler:
```
ControllerNotFoundError: Node ID xxx doesn't exist
↓
Attempt to log error
↓
AttributeError: 'WebSocket' object has no attribute 'method'
```
This masks the original error with an attribute error.
## Proposed Fix
### Primary Fix (Telnet Server)
Move `getpeername()` inside the try block and catch OSError:
```python
# Lines 303-314
for connection_key in list(self._connections.keys()):
connection = self._connections[connection_key]
client_info = None
try:
client_info = connection_key.get_extra_info("socket").getpeername()
connection.writer.write(data)
await asyncio.wait_for(connection.writer.drain(), timeout=10)
except (OSError, ConnectionError, asyncio.TimeoutError) as e:
log.debug(f"Error sending data to client {client_info}: {e}, closing and removing from connection table.")
connection.close()
del self._connections[connection_key]
```
### Secondary Fix (Top-level Exception Handler)
Catch OSError in the main handler to ensure cleanup:
```python
# Lines 212-227
try:
await self._write_intro(network_writer, echo=self._echo, binary=self._binary, naws=self._naws)
await connection.connected()
await self._process(network_reader, network_writer, connection)
except (ConnectionError, OSError): # ← Add OSError
async with self._lock:
network_writer.close()
if self._reader_process == network_reader:
self._reader_process = None
if self._current_read is not None:
self._current_read.cancel()
await connection.disconnected()
del self._connections[network_writer]
```
### Tertiary Fix (API Error Handler)
Fix the WebSocket error handler:
```python
@app.exception_handler(ControllerNotFoundError)
async def controller_not_found_error_handler(request: Request, exc: ControllerNotFoundError):
method = getattr(request, "method", "WebSocket")
log.error(f"Controller not found error in {request.url.path} ({method}): {exc}")
return JSONResponse(
status_code=status.HTTP_404_NOT_FOUND,
content={"message": str(exc)},
)
```
## Reproduction Steps
**To be documented** after testing.
Potential reproduction scenario:
1. Start a GNS3 node with console enabled (e.g., VPCS)
2. Open web console to keep a long-lived connection
3. Run automated script that:
- Connects to the same console port
- Executes a command
- Immediately disconnects
4. While script is disconnecting, trigger device output
5. Observe the error in logs
## References
- **Files**:
- `gns3server/utils/asyncio/telnet_server.py:305` (primary issue)
- `gns3server/utils/asyncio/telnet_server.py:216` (exception handler)
- `gns3server/api/server.py:162` (secondary issue)
- **Related Commits**:
- Recent telnet-related work on feature branch
- **Error Patterns**:
- Race condition in connection management
- Incomplete exception handling in asyncio code
+28
View File
@@ -0,0 +1,28 @@
# QEMU support
GNS3 server requires QEMU 6.2 or newer. This is the minimum QEMU version that the server actively supports on Linux.
For compatibility checks, the project evaluates the Linux distributions that are commonly used in server deployments and that still have supported releases: CentOS Stream, Debian, Fedora, openSUSE, RHEL, SLES, and Ubuntu LTS. Other distributions are assumed to ship similar package versions and are treated by the same rule: if the distro ships QEMU 6.2 or newer, it is considered compatible; if it ships an older version, it is not supported by GNS3 server.
This document reflects the currently supported release set as of October 2026, based on the active releases listed by the major distro end-of-life trackers and package versions shipped by those releases.
## Minimum supported version
- Minimum supported QEMU version: 6.2
- QEMU 6.2 was first shipped in Ubuntu 22.04 LTS and is the baseline used to determine whether a Linux distribution is suitable for GNS3 server.
- Distributions shipping QEMU 6.2 or later are generally acceptable.
- Older package versions are considered unsupported by policy.
## Currently supported Linux releases and shipped QEMU versions
The following supported releases are the current reference points used by the project. They are based on the active release lists published by the distributions' end-of-life trackers and the QEMU versions typically shipped by those releases.
| Distribution | Current supported OS release(s) | QEMU version shipped | Source |
| --- | --- | --- | --- |
| Ubuntu LTS | 24.04 LTS, 22.04 LTS | 8.2 for 24.04, 6.2 for 22.04 | https://endoflife.date/ubuntu |
| Debian | 13 (trixie), 12 (bookworm) | 9.x for 13, 7.2 for 12 | https://endoflife.date/debian |
| Fedora | 42, 41, 40 | 9.x | https://endoflife.date/fedora |
| openSUSE | Leap 15.6, Tumbleweed | 8.x to 9.x | https://endoflife.date/opensuse |
| CentOS Stream | 10, 9 | 9.x / 8.x | https://endoflife.date/centos |
| RHEL | 10, 9.5, 9.4 | 9.x / 8.x | https://endoflife.date/redhat-enterprise-linux |
| SLES | 15 SP7, 15 SP6 | 8.x | https://endoflife.date/sles |
+144
View File
@@ -0,0 +1,144 @@
# Docker Image Types (Vendor Profiles) — Roadmap
Status: **proposal, not implemented**. This is the agreed direction for the
next iteration of vendor Docker support. Four vendor profiles already
exist across branches and prototypes — iol-runner (this branch), XRd and
the SR Linux prototype (vendor/skip-init family), and the FRR registry
appliance — enough evidence to justify the registry. Implement it as a
follow-up to the current PR series, shaped by all four rather than by
iol-runner alone.
## Problem
All Docker nodes share one template type (`template_type: "docker"`) and
one template schema. Vendor images (iol-runner, SR Linux, XRd, …) are
selected and configured today through **environment markers** — free-form
strings parsed by the compute (`GNS3_IOL_RUNNER`, `GNS3_IOL_MEMORY`,
`GNS3_IOL_STARTUP_CONFIG`, `GNS3_SKIP_INIT`, `GNS3_UNIX_SOCKET_NIO`, …).
Three pains have already surfaced:
1. **Invisible and unvalidated.** The markers do not exist in the API
schema: no OpenAPI documentation, no validation, typo or bad value
silently falls back to a default (`GNS3_IOL_MEMORY=notanumber` → 2048).
2. **The shared-schema dilemma.** Adding a vendor-specific field to the
Docker template schema pollutes every Docker template with a field only
one vendor reads; not adding it pushes everything into environment
strings. The `startup_config` discussion (ended in the
`GNS3_IOL_STARTUP_CONFIG` knob) is the canonical example — the tension
exists because there is no legitimate discriminator dimension.
3. **Generic-feature applicability is implicit.** Which generic Docker
features apply to which image is only documented in code comments:
`mac_address` is meaningless under unix-socket NIO, `/etc/network`
seeding is dead weight for skip-init images, `extra_configs` targets
under persisted volumes get a (correct-but-noisy) shadow warning.
## Non-goal: new node types
A `template_type`/`node_type` per vendor (`"iol"`, `"srlinux"`, …) is
explicitly rejected. `node_type` is a top-level concept: it drives compute
module routing (`/projects/{id}/{node_type}/nodes`), capability
reporting, GUI node types and link handling. N vendor types that are all
Docker underneath would multiply routing and schema surface for zero
mechanism — vendor images are *content*, not mechanism, and GNS3's
appliance/template system is where content belongs.
## Design
### One discriminator field on Docker templates
```json
{
"template_type": "docker",
"image_type": "iol-runner",
"image": "iol-xe/iol-xe:17-18-02"
}
```
`image_type` is optional; absent (or `"generic"`) keeps today's plain
`DockerVM` behavior and marker sniffing. The profiles that exist today,
mapped to their current mechanisms and archetypes:
| Profile | Current mechanism | Archetype |
|---|---|---|
| FRR appliance | plain `DockerVM`: init.sh `/etc/network` + `start_command` (frrinit.sh), console on PID 1 | generic |
| XRd | `VendorDockerVM` skip-init + `GNS3_SHM_SIZE`/`GNS3_DEVICES`, `extra_configs`, udev masking | vendor skip-init |
| SR Linux (prototype) | `VendorDockerVM` skip-init + `docker_exec` console + `GNS3_INTERFACE_NAMES` | vendor skip-init |
| iol-runner | `IOLDockerVM`: unix-socket NIO, per-start config generation, NVRAM startup-config | iol-runner |
Possible first values: `generic`, `iol-runner`, and a value for the
skip-init vendor NOS family once its common shape settles (XRd and SR
Linux may end up sharing it or splitting — that is exactly what the
registry should decide with all four in front of us).
### A compute-side registry
```python
IMAGE_PROFILES = {
"iol-runner": {
"class": IOLDockerVM,
"fields": ("iol_memory", "startup_config"), # schema-gated
"capabilities": {...}, # see below
},
...
}
```
* **Class selection** moves from environment sniffing
(`Docker._select_node_class`) to the field, with the existing markers
kept as a fallback for templates created before the field existed
(zero-migration compatibility).
* **Vendor parameters graduate into schema fields**, gated by pydantic
conditional validation (accepted — and validated — only when
`image_type` matches). This resolves the shared-schema dilemma properly:
the field exists, but only means something for its profile. The
environment knobs remain as the wire-level compatibility entry.
* **Capability declaration** makes generic-feature applicability data
instead of comments:
| Capability | plain Docker | vendor skip-init | iol-runner |
|---|---|---|---|
| `mac_address` honored | yes | yes | **no** (IOL derives MACs from the app id) |
| `/etc/network` seeding | yes | no | no |
| `extra_configs` targets under volumes | shadowed | works (real-path binds) | works |
| console | telnet/http/… | `docker_exec` | PID 1 stdio (telnet) |
| startup config | `extra_configs` injection | image-specific | nvram build (`nvram_import`) |
Consumers: error/warning quality (don't warn about inapplicable
features), the WebUI (vendor-aware template forms — a bonus, not a
driver), and documentation generation.
The existing class hierarchy (`DockerVM` → `VendorDockerVM` →
`IOLDockerVM`) is unchanged — the registry only externalizes selection
and declaration.
## Migration & compatibility
* Old templates (markers only) keep working via the fallback; a one-time
optional converter can rewrite markers → `image_type` + fields.
* The controller-side materialization conventions
(`GNS3_IOL_STARTUP_CONFIG` file → `startup_config_content`, sent once)
carry over unchanged — the field version references the same content
pipeline.
## Roadmap steps
1. Add `image_type` to the Docker template schema (+ DB column +
Alembic migration — see the three-place rule for template fields) and
wire class selection through the registry, markers as fallback.
2. Move iol-runner knobs to gated fields (`iol_memory`,
`startup_config`), deprecating-but-supporting the env forms.
3. Introduce the capability table and use it to silence inapplicable
warnings (`mac_address`, `/etc/network`, extra-config shadowing).
4. Revisit per-vendor *schemas* (a sub-model per profile) only if a
profile grows more than a handful of fields — not before.
## Open questions
* Field name: `image_type` vs `vendor` vs `runner` — decide when the
second profile lands; the value vocabulary should name the *runtime
contract*, not the vendor.
* Should appliances (`.gns3a`) carry `image_type` explicitly, or should
installation keep deriving it from the appliance's environment block?
* Where the gated vendor fields live long-term: flat on the Docker
template (simple, gated) vs nested `{"image_type": ..., "settings":
{...}}` (cleaner, more schema churn).
+268
View File
@@ -0,0 +1,268 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> Frozen requirements spec for the **uBridge** project. Status: **delivered
> and verified from the server side** — implemented on the
> `feature/iol-tap-anchor` branch of the ubridge fork (both commands, the §B
> hardening, and one fix beyond the spec: `iol_bridge delete` now releases
> every port NIO even when the bridge was not running, so a stopped node's
> anchor fds never leak). The server side landed on
> `feat/iou-kernel-datapath` and passed a live e2e (64/64 kernel, 62/62
> relay; see `docs/features/iou-kernel-datapath.md`).
>
> Notes from the implementation: the two new commands answer `208` for a
> missing bridge where the older `add_nio_udp` answered `214` (no client
> branches on the code), and a write to an admin-DOWN anchor logs one
> `perror` line per dropped frame.
>
> Scope guard: no wire format change, no change to existing commands or
> replies. This adds one NIO type to the existing `iol_bridge` module (two
> commands) plus one error-tolerance fix in the two listener threads. The
> `tap`, `brctl`, `link`, `tc`, `marker` and `capture` modules are reused
> as-is.
# IOL bridge TAP anchor ports (`iol_bridge add_nio_tap`)
## 0. Background & scope
### What IOU's physical layer is
An IOU instance has no host netdev. Its only wire is the Unix-datagram
fabric in `/tmp/netio<uid>/`: frames carry an 8-byte IOL header (dst id,
src id, dst port, src port, message type, channel), and the NETMAP file
maps every `bay/unit` of the instance to a second, fake instance — which
today is uBridge itself (`iol_bridge create <name> <app_id + 512>`,
binding `/tmp/netio<uid>/<app_id + 512>`). Each port of that fake
instance terminates on a **destination NIO**, and the only destination
NIO type is UDP (`iol_bridge add_nio_udp`): one listener thread per port
relays fabric → NIO, and one bridge listener relays fabric-side reads →
NIO sends.
### The problem
With UDP as the only termination, every IOU link is a uBridge userspace
relay leg:
- an IOU port cannot join a per-link kernel bridge, so IOU ↔ Docker/QEMU
traffic always crosses through a UDP relay even when both ends sit on
the same compute;
- kernel-class impairments (`tc netem`, the clsact eBPF classifiers) and
the `*_kernel` capture/marker commands cannot anchor on an IOU port —
only the userspace packet filters apply, whose delay implementation is
the known blocking-nanosleep defect that inflates RTT under load;
- suspend of a single link has no clean mapping.
### What this change is — and what it cannot be
Give the port a second destination NIO type: a **persistent TAP,
created by gns3-server with the existing `tap create` command and opened
(held) by uBridge**. uBridge's iol_bridge then plays, on that TAP, the
same role the QEMU process plays on its TAP: it is the device's
userspace endpoint. Everything the anchor model already delivers —
`brctl addif` enslavement, `tc` on the anchor, `capture start_kernel`,
`marker add_kernel`, `link set up/down` for carrier/suspend — is keyed
on the interface name and does not care who holds the fd.
One userspace hop on the IOU leg is irreducible: the Unix fabric is
IOU's only physical layer, so frames always pass
fabric ↔ listener thread ↔ TAP fd. What kernelization buys is that the
**link segment itself** is the kernel: anchor → per-link bridge → peer
anchor, with kernel filters, markers and capture on the anchors, and
suspend mapped to anchor admin-down. That is the accepted design, not a
deficiency of this spec.
### Goal
`iol_bridge` ports can terminate on a pre-existing persistent TAP
anchor, with the same lifecycle semantics as `add_nio_udp` (attach
before or after `iol_bridge start`, replace a previous NIO, delete and
re-add), and the relay survives — without exiting — the anchor being
administratively DOWN, which is a steady state of this design (port
anchored but no link attached; link suspended).
Explicitly **not** in scope:
- creating or deleting the TAP device itself — the server owns the
anchor lifecycle through the existing `tap` module (`tap create`,
`tap delete`; the device is created hardened per the L2-only spec);
- serial bays — a TAP carries Ethernet frames; serial links stay on
`add_nio_udp`;
- an MTU command (`link set <if> mtu <n>`) — does not exist today and is
not required by default-MTU IOU traffic; noted as future work if
jumbo frames ever matter;
- any change to the NETMAP, the IOL header encoding, or the L1
keepalive protocol.
## A. New commands
Belong to the existing `iol_bridge` module, next to their UDP
counterparts. `bay`/`unit` and the IOL header handling are identical to
`add_nio_udp`.
### `iol_bridge add_nio_tap <bridge> <iol_id> <bay> <unit> <tap_name>` (6 args)
| Arg | Description |
|-----|-------------|
| `<bridge>` | An existing IOL bridge (`208` if not) |
| `<iol_id>` | The real instance's application id, encoded into the IOL header as with `add_nio_udp`; the existing "`iol_id` == bridge id" refusal in `create_iol_port_entry` applies unchanged |
| `<bay>`, `<unit>` | Port coordinates, same encoding and MAX_PORTS check as `add_nio_udp` |
| `<tap_name>` | A **pre-existing** network device (`208` if not, see below); ≤ IFNAMSIZ−1 chars (`204` otherwise) |
Semantics:
1. **Require an existing device.** Resolve `<tap_name>` with
`if_nametoindex` first and refuse with `208` when absent. This is the
same reasoning as the `tap` module's `tap_require_existing`: without
the check, `TUNSETIFF` silently *creates a transient* TAP that dies
with the fd — an anchor that vanishes on detach is worse than a
clear error.
2. Open the device with the existing `create_nio_tap()` (by-name
`TUNSETIFF`, `IFF_TAP | IFF_NO_PI`, default carrier). No owner or
persistence ioctl — the device is persistent and owned already.
3. Install it through the existing `create_iol_port_entry()`, which is
generic over `nio_t *`: it frees whatever NIO the port held before
(listener stop guarded on `tid`, delay lines torn down under
`iol_delay_lock`, capture/filters freed), pre-computes the IOL
header, and starts the port listener if the bridge is running. A
port may therefore swap `add_nio_udp` ↔ `add_nio_tap` repeatedly —
that is the datapath-switch path and must keep working.
4. If the fd cannot be opened (`create_nio_tap` fails), reply `206` and
free the nio as the UDP handler does.
No `carrier` argument: administrative state is the server's lever, via
the existing `link set <tap> up|down`.
### `iol_bridge delete_nio_tap <bridge> <bay> <unit>` (3 args)
Same body as `cmd_delete_nio_udp`, including its thread-safety guards:
stop the port listener (cancel guarded on `tid != 0`, join), destroy
both delay lines under `iol_delay_lock`, free capture, filters and the
NIO (which closes the TAP fd). **The persistent device itself survives**
— the server deletes it with `tap delete` when the node stops, exactly
as it does for QEMU anchors. Deleting a port that holds no NIO is a
no-op `100` (mirrors `delete_nio_udp`).
Replies:
```
iol_bridge add_nio_tap IOL-BRIDGE-513 1 0 0 gi0badfe9e0p0
100-NIO TAP added to IOL bridge 'IOL-BRIDGE-513'
iol_bridge delete_nio_tap IOL-BRIDGE-513 0 0
100-NIO TAP deleted from IOL bridge 'IOL-BRIDGE-513'
```
## B. Required hardening: the anchor can be administratively DOWN
A TAP anchor is expected to sit admin-DOWN for long periods (port
anchored, no link attached yet; or the link suspended). The listeners
must treat that as normal:
1. **`iol_bridge_listener`, NIO send path** (IOL → TAP, `nio->send` = a
`write` on the fd): a write to an admin-DOWN TAP fails with **EIO**.
The current tolerated set is `ECONNREFUSED | ENETDOWN | EINVAL`,
anything else is `exit(EXIT_FAILURE)` — which would take the whole
uBridge down the first time a suspended link carries traffic. Add
`EIO` to the tolerated set: drop the frame (optionally a debug log)
and continue.
2. **`iol_nio_listener`, NIO receive path** (TAP → IOL, `nio_recv` = a
`read` on the fd): while the device is DOWN the read blocks (no
carrier), which is fine — but a return of `0` must not be counted or
forwarded (it would fabricate header-only packets for the instance).
Treat `recv <= 0` as continue; treat `-1` with `EIO` as continue
alongside the existing `ECONNREFUSED | ENETDOWN`.
No other listener behavior changes: the fabric-side `sendto` already
tolerates `ENOENT`/`ECONNREFUSED` for the window where the IOU process
has not created its endpoint yet, and that stays.
## C. Implementation notes
- The command handlers are thin: existence check + `create_nio_tap` +
`create_iol_port_entry` (add), and the `cmd_delete_nio_udp` body
(delete). The three copies of that teardown block in the module are a
pre-existing pattern — a shared helper is welcome but not required by
this spec.
- Do **not** route the TAP through `nio_tap_open`'s `/dev/net/tun`
path-name variant; the anchor is addressed by interface name.
- Statistics (`iol_bridge get_stats`) work unchanged: the counters hang
off the generic nio and both listeners already update them.
- Port filters, delay lines, capture (`iol_bridge add_packet_filter`,
`start_capture`, …) keep working on a TAP-terminated port; gns3-server
simply will not combine userspace filters with `tc` on the same port
(see the alignment section).
## D. Reply contract & error codes
| Code | Meaning |
|------|---------|
| `100` | OK — NIO added/deleted (delete of an empty port is also `100`) |
| `203` | Bad number of parameters |
| `204` | Invalid parameter (tap name longer than IFNAMSIZ−1) |
| `206` | Unable to create (bridge exists but the TAP fd cannot be opened) |
| `208` | Unknown object — bridge or **tap device** does not exist |
Old builds answer `202-Unknown command` for both commands; gns3-server
uses that to fall back to the UDP datapath, mirroring the `tap`-probe
degradation.
## E. Test requirements
1. **Both-direction relay.** On a running IOL bridge with one
TAP-terminated port: a frame sent on the fabric for that bay/unit
appears on the TAP netdev (stripped of the IOL header); a frame
injected on the netdev reaches the fabric with the port's correct
8-byte header. (A scratch Unix-datagram endpoint can play the
instance; no IOU binary is needed.)
2. **No transient device.** `add_nio_tap … nosuchtap0` → `208`, and no
interface is created (`ip -o link` unchanged).
3. **Unknowns.** Unknown bridge → `208`; name ≥ IFNAMSIZ → `204`; a
bridge-id == iol_id → the existing refusal.
4. **Delete keeps the device.** After `delete_nio_tap`, the port has no
NIO (stats/list reflect that), the TAP netdev still exists, and the
port accepts `add_nio_udp` (and re-`add_nio_tap`) afterwards.
5. **Swap semantics.** A port holding a UDP NIO that gets `add_nio_tap`
releases the UDP socket (old listener joined, port usable), and vice
versa — no fd or thread leak after several swaps.
6. **DOWN-anchor resilience.** With the TAP admin-DOWN, drive traffic
from the fabric side for ≥ 100 frames: uBridge stays alive, frames
are dropped, nothing is written to the netdev. After `link set up`,
traffic flows again. This is the regression test for §B.1.
7. **Idle DOWN port is quiet.** A DOWN anchored port produces no
header-only or zero-length fabric sends (§B.2).
8. **Kernel-bridge interop.** Enslave the anchor into a kernel bridge
(`brctl create` + `addif`) while the port relays: frames cross
bridge ↔ fabric through the port, and a peer port on the same bridge
receives them. This is the actual deployment shape.
## gns3-server alignment (informational — not uBridge scope)
- **Anchors**: one TAP per Ethernet bay/unit, `gi{node_id[:8]}e{bay}p{unit}`,
created persistent (hardened by `tap create` per the L2-only spec) at
node start, swept for stale leftovers first, `tap delete`d at node
stop — the exact lifecycle QEMU anchors use. All Ethernet ports are
anchored at start ("tap-everywhere"); serial bays never are.
- **Links**: kernel links enslave the anchor via the shared
`KernelDatapathMixin` (`brctl create`/`addif`, `tc`, markers,
`capture start_kernel`, suspend = anchor admin-down). Relay links keep
`add_nio_udp` and never touch the anchor. A port switching datapaths
is just an NIO swap (§A.3).
- **Filters are never double-applied**: on a kernel link only the anchor
`tc` path is used; the port's userspace filters carry relay links
only.
- **Capability gating**: the eligibility check needs to know the command
exists before creating a link. Probe by attempting the operation on a
scratch bridge + scratch TAP (create, `add_nio_tap`, delete, clean
up), cached by binary identity like `probe_tap_support`, reported
through `/capabilities`; an old build answering `202` keeps IOU on
the relay datapath.
- **L1 keepalives**: unchanged — an anchored-but-unconnected port holds
no NIO from the server's perspective, so the responder keeps ignoring
it and IOU sees the port down, which matches the anchor being DOWN.
## Roadmap note
`link set <if> mtu <n>` does not exist today. Default-MTU IOU traffic
does not need it; if jumbo IOU frames ever matter it becomes a small,
separate requirement on the `link` module.
@@ -0,0 +1,379 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> Frozen requirements spec for the **uBridge** project. Delivery status:
> **all parts delivered and integrated.** A (netem keyword extensions,
> uBridge `feature/tc-netem-ext`), C + D + E (cBPF match-drop, full-restore
> idempotent `tc reset`, `tc capabilities` — uBridge `feature/tc-bpf-drop`)
> and **B (eBPF stateful classifier — uBridge `feature/tc-precision`
> 59e2b38, including the non-root setcap load fix)** are consumed by
> gns3-server on the branch stack ending at `feat/docker-kernel-window-drop`
> (B: `frequency_drop` → `tc nth_drop`, the kernel-only `quota` type →
> `tc quota_drop`, and the kernel-only `window_drop` type → `tc window_drop`
> against uBridge `feature/tc-window`). The originally shipped netem surface
> (delay/jitter/loss/dup/corrupt) exists in uBridge 1.2.3+ and is verified
> against gns3-server branch `feat/docker-kernel-filters`.
>
> **Deviation found during integration (part A/D):** the delivered
> `tc netem set` uses NLM_F_REPLACE, but the *kernel's* netem change merges
> optional attributes — rate, correlation, reorder, corrupt, gemodel,
> distribution and seed keep their previous value when the new message
> omits them, so "netem set atomically replaces" (D's reconcile
> assumption) does not hold for parameter *removals*. gns3-server works
> around it by sending `tc reset` before every `netem set` (the bpf_drop
> filters are re-added right after in the same flow, so clsact churn is
> invisible). If uBridge later emits explicit zero/absent clears for every
> optional attribute, the server-side reset-before-set can be dropped; the
> two behaviours are compatible either way.
>
> **Deviation found during B integration, resolved uBridge-side
> (2026-09-29):** `window_drop` as first delivered advanced the window
> start by one length on expiry with no gap, making the windows
> back-to-back — after the first `start_ms` the "outside the window
> packets pass" behaviour described in B.2 was unreachable (inside ≡
> always), so gns3-server did not expose it. uBridge now takes
> `tc window_drop <if> <start_ms> <outage_ms> <pct> [<period_ms>
> [<jitter_ms>]]`: 4-arg = single window (pass before *and after*),
> 5-arg = recurring outage with `period ≥ outage`, 6-arg adds a uniform
> ±jitter re-drawn per cycle (0 = exactly the fixed schedule) for
> randomized flap. The program advances whole cycles in a handful of
> straight-line steps — **no loop at all**, because the verifier's
> non-root path (the one production ubridge runs under: `CAP_BPF`, never
> uid 0) cannot keep a loop counter's bound and rejects the *whole*
> program with `E2BIG` past its jump-sequence budget, which took all four
> modes down on the gns3-server host while the same binary verified fine
> as root; uBridge's `doc/tc.md` has the trace. The steps are resumable by
> each further packet, so the
> B.2 semantics are now reachable; no caller ever depended on the old
> back-to-back form (it was never exposed). `flow_drop` is delivered and
> functional but not yet exposed as a GNS3 filter type (its mask/target
> parameter shape needs a UX decision). Additionally, the delivered B.1
> program had to fold the flow-hash L4 port reads to constant offsets
> (IHL==20 only) because the verifier prohibits variable packet-pointer
> arithmetic for non-root — even with CAP_BPF (Spectre-mitigation gating
> by uid); documented in uBridge's doc/tc.md.
# uBridge kernel impairment: tc netem extensions + eBPF classifiers
## 0. Background & scope
On the kernel datapath (Docker veth pairs enslaved into per-link Linux
bridges) frames never pass through uBridge's userspace relay, so link
impairment must live in the kernel: a **netem qdisc** on each veth host end
(serving delay / jitter / loss / dup / corrupt — *shipped*) plus **tc
classifiers** on the clsact egress hook for everything netem cannot express.
This spec freezes:
| Part | Content | New capability needed |
|---|---|---|
| A | netem keyword extensions: `rate`, `reorder`, loss models, jitter distributions, correlation, `seed`, `limit` | none (netlink only) |
| B | eBPF stateful classifier: `frequency_drop` (nth-packet), byte quota, time window, flow select | **CAP_BPF** |
| C | classic-BPF match-drop: the GNS3 `bpf` filter | none (netlink only) |
| D | lifecycle, composition & ordering contract, `tc reset` semantics fix | — |
| E | error strings, `tc capabilities` probe | — |
| F | test requirements | — |
Non-goals (explicitly out of scope for now): packet mangling (`pedit`,
`csum`), mirroring (`mirred`), HTB hierarchies, RST/connection-kill
injection, ingress-side (XDP) impairment.
All commands operate on **egress of the veth host end** (traffic entering
the container), consistent with the existing netem placement.
---
## A. `tc netem set` keyword extensions *(P6a)*
Extend the shipped grammar — existing keywords and their encoding are
frozen and unchanged:
```
tc netem set <if>
[delay <ms>] [jitter <ms>] [distribution uniform|normal|pareto|paretonormal] [seed <u32>]
[loss <pct> [correl <pct>]]
[loss gemodel <p> [<r> [<1-h>]]] # mutually exclusive with plain loss
[dup <pct> [correl <pct>]] [corrupt <pct>]
[reorder <pct> [correl <pct>] [gap <n>]] # requires delay
[rate <bw>] # e.g. 10mbit, 512kbit
[limit <pkts>]
```
### A.1 Parameter validation
| Keyword | Range / format | Errors |
|---|---|---|
| `rate` | `<bw>` = integer + unit `bit\|kbit\|mbit\|gbit\|bps\|kbps\|mbps` (decimal), max 100gbit | 204 `invalid rate '<v>'` |
| `reorder` | pct 0–100, correl 0–100, gap 1–1000 | 204; 204 `reorder requires delay` if no `delay` present (mirror the kernel's EINVAL instead of passing it through — the server keys on the string) |
| `loss gemodel` | p 0–100, r 0–100, h as `1-h` where h is 0–100 (default r=0, 1-h=0) | 204 |
| `distribution` | one of the four names | 204 `unknown distribution '<v>'` |
| `seed` | u32 decimal | 204 |
| `limit` | 1–1000000 packets (replaces the current fixed 1000 default) | 204 |
| `correl` suffix on loss/dup | 0–100, only directly after its keyword | 204 |
Max token count for the command table rises accordingly (recommend 32).
`loss gemodel` semantics (mirrors the kernel, verified against a veth link
with per-direction qdisc counters): `p` is the good→bad state transition
probability (PGAP), `r` the bad→good transition (PGBP), and `1-h` the loss
probability **inside the bad state** (the good state loses nothing). The
steady-state mean loss is `p/(p+r) * (1-h)` per direction — e.g.
`loss gemodel 10 30 100` drops 25 % of the offered packets in each
direction, `loss gemodel 5 45 100` drops 10 %.
### A.2 Netlink encoding notes
* Correlation: loss/dup/reorder use their existing nested structs with the
`correlation` field set (`tc_netem_loss`? no — see `struct tc_netem_qopt`
+ `TCA_NETEM_CORR` carrying `tc_netem_corr` {delay, loss, dup}). Fill the
loss correlation there; dup likewise.
* gemodel: `TCA_NETEM_LOSS` nested attr, kind `TCA_NETEM_LOSS_GEMODEL`
(`struct tc_netem_gemodel` {p, r, h}), probabilities in the same % × 2³²
encoding as `qopt.loss`. When gemodel is set, `qopt.loss` stays 0.
* reorder: `TCA_NETEM_REORDER` (`struct tc_netem_reorder`
{probability, correlation}).
* rate: prefer `TCA_NETEM_RATE64` (u64 bits/s) and also fill legacy
`TCA_NETEM_RATE` (`tc_netem_rate`) with the truncated value for older
kernels; `slot_overhead = 0`.
* distribution: `TCA_NETEM_JITTER64` + `TCA_NETEM_DIST` must carry the
distribution table (s16 deltas). **Embed the three standard tables**
(normal / pareto / paretonormal — same values iproute2 ships as
`*.dist`, generated by netem's `maketable`) as const arrays in uBridge;
select by name. Without DIST the kernel silently uses uniform jitter.
* seed: `TCA_NETEM_PRNG_SEED` (u64; uapi slot 14, introduced in Linux 6.6)
— makes random draws reproducible for tests. When omitted keep the
current behaviour (kernel picks). Pre-6.6 kernels parse the qdisc
options non-strictly and silently drop the attribute: determinism is
unavailable there while every other knob still applies. A build against
pre-6.6 `linux/pkt_sched.h` must define the constant behind a
`LINUX_VERSION_CODE` guard (enum constants are invisible to the
preprocessor, so `#ifndef` cannot detect them).
### A.3 Reply contract (unchanged shape)
```
100-netem set on <if>
204-invalid <kw> value '<v>'
204-reorder requires delay
207-Could not set netem on <if>: <strerror>
```
---
## B. eBPF stateful classifier *(frequency_drop + P6b modes)*
**One** SCHED_CLS eBPF program, loaded once per interface, attached to the
clsact egress hook. All modes are configured through one ARRAY map entry —
no program reload on parameter changes.
### B.1 Program
* Source `src/tc_impair.bpf.c` committed for reference; the build commits
the compiled object (`tc_impair.bpf.o`, freestanding: no CO-RE, no
BTF-typed ptr, plain `struct __sk_buff` + direct packet access).
No runtime clang/libbpf dependency.
* Maps:
* `CFG` — `BPF_MAP_TYPE_ARRAY`, 1 entry:
```
struct cfg {
__u32 nth; /* 0 = off, else drop every Nth packet */
__u64 quota_bytes; /* 0 = off */
__u32 quota_pct; /* random drop % after quota reached */
__u64 win_start_ns; /* recurring window start (monotonic) */
__u64 win_len_ns; /* 0 = off */
__u32 win_pct; /* random drop % inside the window */
__u32 flow_mask; /* bitmask: 1=src 2=dst 4=sport 8=dport 16=proto */
__u32 flow_target; /* required hash remainder, 0 = off */
};
```
* `CNT` — `BPF_MAP_TYPE_ARRAY`, 1 entry: `{__u64 packets; __u64 bytes; __u64 nth_state;}`
Counters are updated with `__sync_fetch_and_add` on the map/global value
so the every-Nth count is exact across CPUs (requires kernel ≥ 5.1 —
acceptable; probe at load, see E).
* Evaluation order is fixed: **nth → quota → window → flow**; the first
rule that decides a drop returns `TC_ACT_SHOT`, otherwise `TC_ACT_OK`.
Random percentages use the same 2³²-probability comparison as netem
(`prandom` seeded via map so tests are reproducible).
* Verifier-friendly: no loops, bounded accesses (check `data + eth+h` before
reading fields; when flow_mask touches ports, verify L4 header length).
### B.2 Command surface
```
tc nth_drop <if> <n | off>
tc quota_drop <if> <bytes> <pct> | off
tc window_drop <if> <start_ms> <outage_ms> <pct> [<period_ms> [<jitter_ms>]] | off
tc flow_drop <if> <mask> <target> | off
```
* First enable on an interface: create clsact (EEXIST tolerated), load the
program, attach one filter at **prio 1** (see D). Subsequent commands only
update `CFG`/reset the relevant `CNT` fields.
* `off` for every mode → the filter is removed (and the prog fd closed).
Each `off` resets that mode's counters.
* `flow_drop` mask is the decimal bitmask from B.1 (server composes it);
hash = Jenkins/equal-fold over the selected header fields modulo
`flow_target` == remainder 0 → drop. Server documents: per-flow drop only
(a filter cannot delay; delay stays netem's job).
* Window semantics: `win_start_ns`/`win_len_ns` define a window on the
monotonic clock — inside the window drop with `win_pct`; outside pass.
The program computes the first start (command time + `start_ms`) and then
advances whole cycles, catching up in a bounded loop when it fell behind
(single writer — the CFG update — so this is safe). Omitting `period`
makes it a **single** window: after `start + outage` nothing drops. With
`period ≥ outage` the outage recurs; `jitter` re-draws each cycle's
outage and period uniformly in nominal ± jitter (0 = fixed schedule), on
the integer-ms grid so the multiply-shift draw cannot overflow.
### B.3 Capability requirement
`BPF_PROG_LOAD(SCHED_CLS)` needs **CAP_BPF** (or CAP_SYS_ADMIN) on kernels
≥ 5.8. Installation must therefore set:
```
setcap cap_bpf,cap_net_admin,cap_net_raw=ep <ubridge>
```
On EPERM: reply `210-uBridge lacks CAP_BPF (setcap cap_bpf,cap_net_admin,cap_net_raw=ep) and the kernel requires it for stateful filters`
— the gns3-server side falls back to the relay datapath on this string (E).
---
## C. classic-BPF match drop (the GNS3 `bpf` filter)
No eBPF, no CAP_BPF: `cls_bpf` accepts **classic bytecode** via
`TCA_BPF_BYTECODE` (`sock_fprog`), and the kernel internally migrates it to
eBPF. uBridge already links libpcap.
```
tc bpf_drop add <if> <prio> "<expression>" # prio: 10..99, server-assigned
tc bpf_drop flush <if>
```
* `add`: `pcap_compile(DLT_EN10MB, snaplen 65535)` the expression; on
failure reply
`209-Cannot compile filter '<expr>': <pcap_geterr>` — gns3-server keys on
this exact prefix (same shape as the relay's error so one regex serves
both datapaths). Netlink: RTM_NEWTFILTER on clsact egress, protocol
ETH_P_ALL, `TCA_KIND "bpf"`, `TCA_BPF_BYTECODE`, action nested
`TCA_BPF_ACT` → `gact` with `action = TC_ACT_SHOT` (pcap match ≠ 0 →
filter matches → drop; non-match falls through, no action → pass).
* Multiple expressions (GNS3 sends one line per filter): server adds one
filter per line at successive prios — any match drops (OR).
* `flush`: delete every bpf_drop filter uBridge added on this interface
(track prios in-process), tolerate ENOENT per filter. Does NOT touch the
eBPF prio-1 filter or netem.
* Update-by-replace: server always `flush` + re-`add` (mirrors `netem set`).
---
## D. Lifecycle, composition & ordering (frozen contract)
* **clsact coexists with the netem root qdisc** — never replace the root.
* Execution order on egress: classifier filters by ascending prio —
eBPF impair filter at **prio 1**, `bpf_drop` at **prio 10..99** — then the
root netem qdisc. Dropped packets therefore never reach netem **nor the
AF_PACKET tap points** (capture/markers will not observe cls_bpf-dropped
frames; documented server-side).
* **`tc reset <if>` becomes the full restore** (behaviour change + fix):
1. remove all bpf_drop filters and the eBPF filter (clsact egress side we
own), 2. delete clsact, 3. delete the root qdisc. On an untouched
interface it must now reply **100-OK** (idempotent — currently returns
207-ENOENT; gns3-server tolerates both, but the new contract is OK).
* All state is kernel state tied to the interface: deleting the veth
(container stop) clears everything; no ubridge-side bookkeeping survives
a restart (a re-attached link rebuilds from the NIO, as today).
---
## E. Errors & capability probe
Error strings are contract (gns3-server matches them):
| Reply | Meaning |
|---|---|
| `100-netem set on <if>` / `100-qdisc reset on <if>` | success |
| `203-Bad number of parameters (%d with min/max=%d/%d)` | argc mismatch |
| `204-invalid <kw> value '<v>'` | value validation |
| `204-reorder requires delay` | keyword dependency |
| `207-Could not (set netem\|reset qdisc) on <if>: <strerror>` | netlink/kernel failure |
| `209-Cannot compile filter '<expr>': <err>` | bpf_drop pcap_compile failure |
| `210-uBridge lacks CAP_BPF ...` | stateful filters unavailable |
New introspection command (also serves the gns3-server degradation TODO —
old uBridge without these commands simply stays on the relay datapath):
```
tc capabilities
100-netem=delay,jitter,loss,dup,corrupt,rate,reorder,gemodel,dist,seed,limit;ebpf=1;cbpf=1;ebpf_modes=nth,quota,window,flow
```
`ebpf=0` when the load probe fails at startup (kernel < 5.1 or no CAP_BPF);
`cbpf=0` when RTM_NEWTFILTER/cls_bpf is unavailable. gns3-server hides the
corresponding filter types per capability.
`ebpf_modes` (added on uBridge `feature/tc-window`, commit 40c36ae) is a
build fact, orthogonal to the runtime probes: the same binary flips `ebpf`
between users and kernels while the mode set changes only with the binary.
A mode is usable iff `ebpf=1` **and** its token is listed — gating
`window_drop` on `ebpf=1` alone silently accepts the 4-arg form on a
pre-correction build (`feature/tc-precision`: back-to-back windows, no
gap). Builds that do not emit the field at all predate it and get legacy
treatment; an incompatible mode revision renames its token
(`window` → `window2`) rather than versioning in place.
---
## F. Test requirements
* **Unit**: per keyword → expected netlink attrs (assert message bytes);
every 204 table row; `bpf_drop` compile-fail path; capabilities string.
* **Functional** (root, veth pair + netns + nsenter ping):
delay+reorder observable (mdev), gemodel loss within ±5% of
`p/(p+r) * (1-h)` measured **per direction** — a round-trip ping figure
reads `1-(1-L)²` instead, and with `1-h=100` the ARP cache must be
pre-warmed or the neighbour-resolution blackhole during a long burst
inflates the observed loss,
rate within ±10% (measured byte throughput), nth_drop **exact** pattern
(ICMP seq survives 1,2,…,N-1, Nth dropped), quota/window/flow with
crafted senders, `tc reset` idempotent on a clean interface, P5 surface
regression (delay/jitter/loss/dup/corrupt, REPLACE semantics).
* Determinism: netem `seed` + the CFG-seeded prandom make runs repeatable;
CI asserts identical drop patterns for identical seeds.
---
## gns3-server alignment (informational — not uBridge scope)
* **Done** (`feat/docker-kernel-netem-ext`): the P6a types map 1:1 onto new
GNS3 filter entries (rate, reorder, gemodel, duplicate, seed, limit, plus
the delay `distribution` and loss/dup `correlation` parameters), translated
in `DockerVM._ubridge_apply_netem`; extension keywords are gated on the
`tc capabilities` netem token list (old uBridge builds are never probed
for the original surface).
* **Done** (`feat/docker-kernel-bpf-drop`): `bpf` runs as cBPF match-drop.
* **Done** (`feat/docker-kernel-ebpf-drops`): the eBPF classifier (part B)
is consumed — `frequency_drop` → `tc nth_drop` (-1 → every 1st), the new
kernel-only `quota` type → `tc quota_drop`, both keyed on `ebpf=1` from
the per-process `tc capabilities` probe. `KERNEL_UNSUPPORTED_FILTERS` is
gone entirely: kernel/relay eligibility is purely topological now.
* **Done** (`feat/docker-kernel-window-drop`): `window_drop` is exposed
with the corrected semantics (uBridge `feature/tc-window`) as the
kernel-only `window_drop` filter type
`[start, outage, pct, period?, jitter?]` → `tc window_drop`; the server
mirrors the grammar's `period ≥ outage` rule and treats `start = 0` as
active (an immediate outage).
Not yet exposed: `flow_drop` (parameter-shape UX decision).
* **Done** (capability reporting): the `ebpf_modes` contract is consumed
end to end — the compute applies it per mode (window requires its token;
pre-field builds keep their shipped modes), the compute
`GET /capabilities` payload reports `ubridge_tc` through a standalone
spawn-as-own-user probe cached by binary identity, and the controller's
`available_filters` hides kernel-datapath filter types an endpoint
compute reports it cannot run (computes without a report keep the full
list; apply-time 409 stays the guard).
* Every veth end owns one qdisc + its filters: per-direction impairment is
an architectural freebie to expose later (API `direction` field), aligned
with marker `dir` semantics.
+253
View File
@@ -0,0 +1,253 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> Frozen requirements spec for the **uBridge** project. Status: **delivered**
> (uBridge `e2e3155` — `link l2only` plus the creators that apply it;
> `fb72758` — the fifth creator: the TAP `bridge add_nio_tap` creates for a
> free name) and verified from the server side: anchors and per-link bridges
> report `addrgenmode none`, `ip -4/-6 addr` are empty, and an idle anchor is
> silent once the one-shot membership burst of §0 has settled.
>
> **Residual, accepted (measured after delivery):** enslaving a port still
> makes the *bridge device* announce its multicast memberships — one IGMPv3
> plus one or two MLDv2 reports in the first second — which floods into the
> emulated segment. It is outside this command's reach by design (no addresses
> are involved, and IPv4 has no per-device IGMP off switch); see §0.
>
> Scope guard: no wire format, no command grammar change to existing
> commands — this adds one command and one internal step in four creators.
# L2-only host anchor devices (`link l2only`)
## 0. Background & scope
### What an anchor is
The host-side device that carries a node's adapter in the root namespace:
the veth host end of a Docker adapter (`gv…`, created by `docker create_veth`),
the persistent TAP of a QEMU adapter (`gq…`, created by `tap create`), and the
per-link kernel bridge those anchors are enslaved to (`brctl create`). Links
attach *to* these devices (kernel bridge port or uBridge relay endpoint); the
devices themselves are the only thing uBridge creates on the host's behalf.
### The problem (measured)
A host-side anchor that is UP gets an IPv6 link-local address from the kernel
automatically — no user-space actor involved — and with it the kernel emits its
own traffic on that device:
- a freshly created persistent TAP, brought UP: **6 frames in 2 s** of MLD
reports (`33:33:00:00:00:16`, `33:33:00:00:00:fb`) and DAD neighbor
solicitations (`33:33:ff:…`, ICMPv6 next-header 0/17/58), all sourced from the
device's own link-local address;
- production: the Docker veth host end `gv6ee8d537e1p0` carries
`fe80::5c30:e8ff:fe00:5d8d/64` (`disable_ipv6=0`), and the per-link bridge
`gns30dbb78c5718` carries `fe80::f0d9:94ff:feac:e42b/64`.
Consequences inside an emulated topology:
- on a **kernel-datapath** link the bridge floods those frames into the emulated
segment; on a **relay** link uBridge relays them to the peer compute;
- they land in captures and marker pcaps, so "idle link" is not quiet;
- the host **answers** neighbor solicitations for its own link-local address, so
an emulated IPv6 router can form a real adjacency with the host — a phantom
neighbour inside the emulated network.
IPv4 needs no equivalent knob: nothing self-provisions an IPv4 address, and the
invariant we keep is *no addresses at all* (measured: `ip -4 addr` is empty on
every anchor and per-link bridge on the deployment above, with NetworkManager
reporting them `unmanaged`). IPv6 is the only protocol that lights itself up.
### The residual this command does not remove (measured after delivery)
With `l2only` in place (anchors and bridges report `addrgenmode none`, no
addresses), **enslaving a port still makes the bridge device speak once** —
the kernel announces the multicast memberships the enslavement brings to the
bridge:
```
+0.00 s 90 B IPv6 MLDv2 report dst 33:33:00:00:00:16 (ICMPv6 143)
+0.09 s 54 B IPv4 IGMPv3 report dst 01:00:5e:00:00:16 0.0.0.0 → 224.0.0.22
+0.73 s 90 B IPv6 MLDv2 report dst 33:33:00:00:00:16
```
(Scratch tap pair + per-link bridge on the test host, unprivileged; source MAC
= the bridge's. A 10 s window contains exactly those three frames, then silence.
The same burst appears through the server: one 90 B IPv6 frame inside a 2 s
window right after a link is created.)
It is outside `l2only`'s reach by design: no addresses are involved (the report
sources are `::` and `0.0.0.0`), and IPv4 has no per-device "no IGMP" knob to
set. **Decision: accepted and documented, not suppressed** — it is standard L2
control traffic, one-shot per link creation or port change, and it stops. The
acceptance test in §E.2 therefore measures after a settle window. Suppressing
it (e.g. `disable_ipv6` on the bridge before enslaving, for the MLD half) would
be a new, separate requirement and has not been asked for.
### NetworkManager releases managed TAPs from bridges (measured)
On hosts where NetworkManager manages the data-plane TAPs — it claims uBridge-created tun/tap devices on many desktops (`nmcli device` shows them as `disconnected` before NM's state machine has assumed them, `connected (externally)` after) — NM can **release a tap from its bridge** some 60-70 ms after enslavement, while the port is in that not-yet-assumed state. Measured with a minimal harness (one uBridge, one fresh tap, one bridge, an `addif`/`delif` loop, no server): ~50 % of re-enslavements lose the port, the freed device stays administratively **up** with the bridge's promiscuity/allmulti cleared, and no GNS3 process sends anything — gns3-server and uBridge log nothing, and the server's attachment bookkeeping stays intact. The *first* enslavement of a newly created tap was stable in every run; the hazard is a **re-enslavement** (link delete + recreate, a port re-join after a peer restart) before NM assumes the device — on the same tap, `nmcli device set <tap> managed no` flips the failure rate from 20/40 to 0/40, and re-managing it restores 20/40.
Consequence for an affected link: the port silently leaves the bridge (frames drop) while the API stays green — the next NIO update re-heals it, because the switch's `_kernel_update` re-checks `brif` membership, but nothing forces one. Docker's veth host ends are not NM-managed and never showed the failure; every TAP anchor family is exposed (Dynamips `gd`, QEMU `gq`, IOU `gi`, IOL `gx`, and switch-absorbed anchors). Host-side remedy: `nmcli device set <tap> managed no` (runtime, per device), or NM's `unmanaged-devices` configuration keyed on the anchor name prefixes; the e2e harness takes the anchors it re-enslaves out of NM's hands (`harness.unmanage_from_networkmanager`). Full root-cause record with the minimal reproducer, the NetworkManager source-level mechanism and the verified fix: `docs/bugs/networkmanager-tap-release.md`.
### Goal
Every host-side device uBridge creates for the data plane is **pure L2**: no
IPv4 address, no IPv6 address, and no IPv6 stack activity on that device.
Explicitly **not** in scope:
- the guest/container side (the peer veth end inside a container netns keeps its
normal IPv6 behaviour);
- global sysctls and any change outside the named interface;
- `brctl addip`-style L3 use of a bridge (cloud / Ethernet-switch paths) — those
devices are meant to have addresses and are not data-plane anchors.
## A. New command: `link l2only <iface> [on|off]`
Belongs to the `link` module (per-interface operations: `link set`, `link veth`,
`link addr`, `link delete`).
| Arg | Description |
|-----|-------------|
| `<iface>` | An **existing** device. A missing name must fail (`208/ENODEV`), never create a transient device — mirror the `tap` module's `tap_require_existing` reasoning. |
| `on` / `off` | Default `on`. `on` = suppress IPv6 address generation and stack activity on the device; `off` = restore the kernel default. |
Semantics of `on`: after the call the kernel has assigned **no** IPv6
link-local address to the device, and the device's `addrgenmode` reports `none`
(`IFLA_INET6_ADDR_GEN_MODE = IN6_ADDR_GEN_MODE_NONE`), so no DAD, MLD or RS is
generated from it. If an address already exists it is removed as part of the
call (an anchor that was created and brought up before this command must end up
clean, not just "no new addresses from now on").
Replies:
```
link l2only gq1234abcd e0
100-L2-only set on gq1234abcd e0
link l2only gq1234abcd e0 on
100-L2-only set on gq1234abcd e0 # idempotent, same reply
link l2only gq1234abcd e0 off
100-L2-only cleared on gq1234abcd e0
```
The success reply is emitted only after a read-back (`RTM_GETLINK` +
`IFLA_AF_SPEC` → `IFLA_INET6_ADDR_GEN_MODE`) confirms the device state, so a
caller may treat `100` as verified rather than requested.
## B. Where it must be applied
The creators apply it themselves — gns3-server never issues `link l2only`
directly, and a caller cannot forget it:
| Creator | Device hardened | Notes |
|---|---|---|
| `tap create <name>` | the persistent TAP | before the success reply; the device already exists (TUNSETPERSIST) |
| `docker create_veth <host> <guest>` | the **host** end only | the guest end moves into a container netns and is deliberately untouched |
| `link veth <name> <peer>` | both ends | both ends are host-side |
| `brctl create <bridge>` | the bridge device itself | the fabric the anchors are enslaved to; the bridge's own link-local floods to every port |
| `bridge add_nio_tap <br> <name>` | the TAP it **creates** (name free) | by-name `TUNSETIFF` creates a transient device when the name is free — cloud's bridge interfaces, and the relay swap's create-if-missing path. Hardened at creation; an attach to an existing device is left untouched (the caller may name a user-owned TAP that has addresses). |
Rule for future creators: any command that creates a host-side device for the
data plane hardens it, and the acceptance checks in §E apply to it.
An **attach** is not a creation: `bridge add_nio_tap` (and every other open
of a TAP that already exists) must leave that device's addresses alone. The
transient TAP `bridge add_nio_tap` creates for a free name is a creation and
is hardened like the rest — best-effort, before the NIO is handed back.
## C. Implementation notes (netlink, not `/proc`)
- Use `RTM_SETLINK` with `IFLA_AF_SPEC{ AF_INET6, IFLA_INET6_ADDR_GEN_MODE =
IN6_ADDR_GEN_MODE_NONE }` — this is what `ip link set dev X addrgenmode none`
does. Removing an already-assigned link-local is `RTM_DELADDR` on that
address (or letting the kernel drop it once generation is off; verify the end
state either way).
- Optionally also set the nested `IFLA_INET6_CONF` attributes
(`DEVCONF_DISABLE_IPV6 = 1`, `DEVCONF_ACCEPT_RA = 0`) when the running kernel
accepts writes for them. The addr-gen-mode attribute alone already removes the
address, and without an address there is no DAD/MLD/RS.
- Do **not** write `/proc/sys/net/ipv6/conf/<if>/disable_ipv6`. The sysctl files
are root-owned mode 0644, so a setcap'd, non-root uBridge can be refused by
the DAC check despite holding `CAP_NET_ADMIN`. The netlink route has no such
problem.
- Failure handling: `EOPNOTSUPP` / `EINVAL` from an old kernel without the
attribute must be **non-fatal** (log, continue) so device creation never fails
because of this hardening; `ENODEV` and any other error are real and reported.
## D. Reply contract & error codes
| Code | Meaning |
|------|---------|
| `100` | OK — device verified L2-only (or verified restored for `off`) |
| `203` | Bad number of parameters |
| `204` | Invalid parameter (`on`/`off` expected) |
| `208` | Object not found (`ENODEV`): no such device |
| `206` | Unable to set (netlink error other than EOPNOTSUPP/EINVAL) |
## E. Test requirements
1. **No addresses.** After each creator: `ip -6 addr show dev <dev>` is empty
(in particular no `fe80::`) and `ip -4 addr show dev <dev>` is empty; the
same for the bridge created by `brctl create`.
2. **Idle silence, after the settle window.** Let the last port enslavement
settle (≥ 2 s — that burst is expected, see §0), then with the device UP and
in its normal role (TAP with an open fd / veth with its peer up / bridge with
two attached ports) nothing appears on it for 5 s — measured from the peer
end, or via `capture start_kernel <dev> <pcap>` while idle with the pcap
asserted empty. Baseline before this work: 6 frames / 2 s, continuous.
3. **Idempotency & revert.** `on` twice → `100` both times, state unchanged;
`off` restores the kernel default (link-local returns after the device is
cycled down/up).
4. **No transient device.** `link l2only nosuchif0` → `208`, and no interface is
created (check `ip -o link`).
5. **Far side untouched.** Inside the container / VM the normal IPv6 link-local
still exists — nothing in this change reaches the peer.
6. **Non-fatal on old kernels.** Simulated by testing on a kernel without the
attribute: the creators still succeed, and §E.1 is then expected to fail with
the device left in the default state.
## gns3-server alignment (informational — not uBridge scope)
- **Call sites**: the creators harden the devices; the server issues no
`link l2only` itself, and no NIO/JSON schema, filter or MCP tool
description changes. This is host-side hygiene only.
- **The fifth creator was found by these servers' e2e assertions**: on a
build predating `fb72758`, the Ethernet switch's relay port TAPs
(`gns3{id}-N`, created implicitly by `bridge add_nio_tap`) carried a live
`fe80::` — the §E.1 assertion failed on exactly that device, live. The
close is uBridge-side (§B table row 5): the transient TAP is hardened at
creation, attaches stay untouched. The server side needed no change for
it — the assertion alone caught it, and it now guards the fixed build.
- **e2e assertions** (landed in `tests/e2e/harness.py`, asserted by the
kernel-datapath suites alongside the existing capture/marker/filter checks):
- anchors and per-link bridges have no IPv4/IPv6 addresses, addrgenmode
`none` (`assert_pure_l2`, §E.1) — on the kernel scenarios' anchors and
bridges, and on relay-mode anchors/switch TAPs alike (the hardening is a
creation-time property, not a datapath one). The switch relay-TAP
assertion is what exercises the fifth creator end-to-end (the same
uBridge creation path cloud's transient TAPs take);
- an idle link stays silent for 5 s after the settle window
(`assert_idle_silence`, §E.2) — measured with the guests silenced (the
IOS consoles' interfaces shut, the Docker guests' links down, all four
cascade routers shut) over the anchors, the per-link bridge and the
switch bridges, in every kernel scenario: Dynamips, Docker, QEMU, IOU,
the IOL container, the switch fast path and the switch cascade. That
covers each creation
path — `tap create`, `docker create_veth` (plus the server-side
harden-after-create on the cascade's race-loser end), `bridge
add_nio_tap` and the `brctl` switch bridges (whose multicast snooping
is off precisely so the bridge role can reach silence);
- a silent-failure guard found while validating this spec: after attach, every
bridge port reports `brport/state == 3` (forwarding) (`assert_forwarding`).
A bridge device left DOWN keeps its ports `DISABLED` (`state == 0`) and
forwards nothing — with no error anywhere, so the assertion is the only
signal.
- **Rollout**: with a uBridge that lacks the command the anchors keep today's
behaviour (noise present). The e2e assertions skip when `link l2only` answers
`202-Unknown command` (`harness.l2only_supported()` probes a throwaway
uBridge once), mirroring the existing tc-capability degradation. A build
that has the command but predates `fb72758` fails the switch relay-TAP
assertion instead of skipping: the gap is exactly what it exists to catch.
@@ -0,0 +1,266 @@
# uBridge bridge ports must forward link-local frames (per-port `group_fwd_mask`)
> **Status: landed and verified.** uBridge branch `feature/bridge-tap-l2only`,
> commits `0284500` (feat), `03a18f1` (test suite), `cf4e494` (docs) — the
> implicit `addif` hook of §A.1 plus the `setportgroupfwd` escape hatch of
> §A.3. gns3-server carries **zero product-code changes**: the behavior
> reaches every `brctl addif` call site as specified. Verified by the uBridge
> suite (`tests/brctl/test_linklocal.py`, 28/28) and live through a real
> server by `tests/e2e/test_docker_link_local_frames.py`. The three
> `test_vlan` kernel-state failures seen alongside are pre-existing on the
> parent commit (verified by an fb72758 control run). The version bump (R8)
> is still open, pending review.
## 0. Background & scope
### The datapath this serves
GNS3's kernel datapath wires a link by enslaving each endpoint's host-side
anchor (veth host end, TAP) into a per-link Linux bridge. The same shape is
used by the Ethernet switch node (its bridge absorbs peers' anchors), by
switch-to-switch cascades (a veth pair joining two bridges) and by the Cloud
node (pnet bridges). Functionally these bridges stand in for **a cable** — a
transparent L2 segment — and that is the contract users expect from them.
### The problem: a Linux bridge is not a transparent cable
`br_handle_frame()` in `net/bridge/br_input.c` treats the IEEE 802.1D
reserved link-local range `01:80:c2:00:00:00`–`01:80:c2:00:00:0f` specially
and, by default, does **not** forward it. Measured on a stock mainline kernel
(7.2.6, no patches) with two ports in one bridge:
| Destination MAC | Protocol | Default bridge | Notes |
|---|---|---|---|
| `ff:ff:ff:ff:ff:ff`, `01:00:5e:*`, `33:33:*` | broadcast, IPv4/IPv6 multicast | forwarded | unaffected |
| `01:80:c2:00:00:00` | STP / RSTP BPDU | **forwarded** | special-cased: forwarded while the bridge runs no STP |
| `01:80:c2:00:00:01` | 802.3x PAUSE / 802.1Qbb PFC | not forwarded | kernel drops unconditionally — see §0.3 |
| `01:80:c2:00:00:02` | LACP / slow protocols | not forwarded | |
| `01:80:c2:00:00:03` | 802.1X EAPOL | not forwarded | |
| `01:80:c2:00:00:0e` | LLDP (DCBX) | not forwarded | |
| `01:80:c2:00:00:10` and up | — | forwarded | outside the reserved nibble range |
Consequence: on a kernel-datapath link, two emulated devices that run LACP,
LLDP/DCBX or 802.1X never see each other, while the same lab over the uBridge
UDP relay (a dumb store-and-forward, fully transparent) works. The two
datapaths disagree, and the failure is silent.
### Why the bridge-level knob is not enough
`IFLA_BR_GROUP_FWD_MASK` (the bridge-level attribute, already reachable via
uBridge's `brctl setgroupfwd`) is restricted by `BR_GROUPFWD_RESTRICTED`
(`BR_GROUPFWD_STP | BR_GROUPFWD_MACPAUSE | BR_GROUPFWD_LACP`): writes
containing bits 0/1/2 fail with `EINVAL`. Measured: bridge-level accepts at
most `0xfff8`, which forwards LLDP/EAPOL but **not LACP**.
The per-port attribute `IFLA_BRPORT_GROUP_FWD_MASK` (commit
`5af48b59f35cf712793badabe1a574a0d0ce3bd3`, "net: bridge: add per-port
group_fwd_mask with less restrictions", net-next 2017, Linux 4.15) exists
precisely for this: its commit message names "transparent forwarding of
most link-local frames (e.g. STP, LACP) through tunnels (vxlan, qinq)" and
restricts only MAC PAUSE. Measured: port-level accepts `0xfffd` and then
forwards STP, LACP, EAPOL, LLDP and every other reserved address.
The mask is evaluated on the **ingress** port (setting it on the egress port
only has no effect), so every port of a bridge needs it — which is exactly
what a per-addif hook gives us.
### What this change is — and what it cannot be
PAUSE / PFC is **not** in scope and cannot be delivered by any mask: the
`case 0x01:` branch in `br_handle_frame()` drops unconditionally
(`kfree_skb_reason(..., SKB_DROP_REASON_MAC_IEEE_MAC_CONTROL)`) without
consulting `fwd_mask`, and the port-level setter rejects bit 1 with `EINVAL`.
Forwarding PAUSE would require patching that branch. Emulation of PFC
semantics is out of reach anyway (no hardware pause generation/response, no
per-priority queues, no headroom/watchdog), so the GNS3 documentation will
state PFC as unsupported on kernel links rather than pretending otherwise.
### Goal
A kernel-datapath link (and every other uBridge bridge) carries link-local
frames exactly like the cable it emulates: STP, LACP, EAPOL, LLDP and the
remaining reserved addresses flow; PAUSE/PFC is documented as impossible.
---
## A. The requested change
### A.1 One step in `br_enslave_if()` (`hypervisor_brctl.c:251`)
After the port is enslaved (step 1) — and using the existing u16 port-attribute
helper — set the link-local forwarding mask:
```c
/* Step 3 – link-local transparency. A Linux bridge stands in for a cable
* here: LACP/LLDP/EAPOL/STP must cross it. The kernel restricts the
* *bridge-level* mask to bits 3..15 (BR_GROUPFWD_RESTRICTED), so LACP is
* only reachable per port. 0xfffd = every reserved address except MAC
* PAUSE (bit 1), which the kernel refuses and hard-drops anyway.
* Best-effort: kernels before 4.15 have no such port attribute, and the
* cable simply keeps today's behaviour there. */
if (br_set_port_attr_u16(bridge, port, IFLA_BRPORT_GROUP_FWD_MASK,
LINK_LOCAL_FWD_MASK) < 0)
fprintf(stderr, "ubridge: %s: link-local forwarding mask not set\n", port);
```
with
```c
/* bit 0 STP (harmless: already forwarded while STP is off), bit 2 LACP,
* bit 3 802.1X EAPOL, bit 14 LLDP; bit 1 MAC PAUSE must stay clear or the
* kernel rejects the whole value with EINVAL. */
#define LINK_LOCAL_FWD_MASK 0xfffdu
```
`br_set_port_attr_u16()` (`hypervisor_brctl.c:811`) already does everything
needed: it checks membership via `br_check_master()`, builds the
`IFLA_PROTINFO` nested attribute on `AF_BRIDGE`/`RTM_SETLINK`, and — critically
— encodes the value as **2 bytes**, which is what the kernel's port policy
requires (`NLA_U16`); a 1-byte payload is rejected with `-ERANGE` (the same
trap documented in that helper's comment for `IFLA_BRPORT_PRIORITY`).
### A.2 Why in `br_enslave_if()` rather than in any single caller
* **Every** enslavement in uBridge funnels through this helper — per-link
bridges, the Ethernet switch's own ports, peers absorbed into a switch
bridge, cascades, pnet/Cloud bridges. One hook covers all of them, and
covers future callers too.
* gns3-server **cannot** do it itself: the packaged service runs unprivileged
(`init/gns3.service.systemd`: `User=gns3`) and `CAP_NET_ADMIN` is carried by
the uBridge binary (`base_manager.py:_has_privileged_access()`). A
server-side `ip link set … type bridge_slave …` is not possible in the
supported deployment.
* Doing it at addif time also means ports that are re-attached after a node
restart (the server re-pushes NIOs) are re-covered without extra logic.
### A.3 Alternative interface, if the project prefers explicit policy
If uBridge would rather keep this policy out of `addif`, the equivalent
explicit command is:
```
brctl setportgroupfwd <bridge> <port> <mask> (3 args)
```
implemented as a thin wrapper over `br_set_port_attr_u16(..., (unsigned
short)mask)` and registered next to `setportprio` in the command table
(`hypervisor_brctl.c:2049`). In that case gns3-server will call it at its
five `brctl addif` sites and gate it on a probe of the running build. The
implicit form is preferred by gns3-server because it needs no server change
and cannot be forgotten at a new call site.
---
## B. Requirements (normative)
* **R1** After a successful `brctl addif <bridge> <port>`, the port carries
`group_fwd_mask = 0xfffd` (`LINK_LOCAL_FWD_MASK`).
* **R2** The value must **exclude bit 1 (MAC PAUSE)**. `0xfffe`/`0xffff` are
rejected by the kernel with `EINVAL` and would silently lose the whole
mask — do not use them.
* **R3** The attribute payload must be encoded as u16 (`br_set_port_attr_u16`).
A u8 payload fails `validate_nla` with `-ERANGE` on kernels that enforce the
policy strictly.
* **R4** **Best-effort**: a failed mask write must never fail the `addif`
(kernels < 4.15 have no per-port attribute; unusual deployments may lack
`CAP_NET_ADMIN`). Reply to `addif` is unchanged; the failure is logged to
stderr.
* **R5** Ordering: set the mask after the port is enslaved (both
`br_check_master()` and the kernel's `IFLA_PROTINFO` handling require
membership). The step-2 "bring the port up" may run before or after; both
work.
* **R6** Idempotent: re-`addif` of an already-enslaved port must succeed and
keep the mask set (gns3-server re-attaches links on node start).
* **R7** Applies uniformly to every bridge/port this helper touches — no
per-bridge or per-caller switch (a real switch terminates link-local frames,
but GNS3's Ethernet switch node is used as a transparent segment, so
forwarding is the wanted behaviour there too).
* **R8** Version: bump the reported version so gns3-server can raise its
minimum (the server already gates on `ubridge version X.Y.Z`,
`compute/ubridge/hypervisor.py:_check_ubridge_version`, currently ≥ 1.2.3).
* **R9** Document the PAUSE/PFC exclusion in uBridge's help/docs, so the gap
is not rediscovered as a bug.
---
## C. Implementation notes
* `IFLA_BRPORT_GROUP_FWD_MASK` is defined in `include/uapi/linux/if_link.h`
(Linux ≥ 4.15); guard the build on its presence if uBridge must compile
against older headers — behavior on such kernels is "no mask", which R4
already tolerates.
* The kernel's `br_set_group_fwd_mask()` (port variant) validates against
`BR_GROUPFWD_MACPAUSE`; there is also a follow-up fix
(`16c42db48522`, "bridge: check for attempt to forward STP PDU's with STP
enabled") that moves STP validation into the setter — bit 0 is harmless for
our case because we never enable STP on these bridges.
* No interaction with existing commands: `brctl setgroupfwd` (bridge-level)
stays as is and is unused by gns3-server; `hairpin`/`isolated`/`setportstate`
continue to use their own attributes through the same helper family.
---
## D. Reply contract & error behavior
`addif` replies (`HSC_INFO_OK` / `HSC_ERR_*`) are unchanged. The mask write
does not produce its own reply and does not alter the addif verdict; on
failure it writes one line to stderr (§A.1). No new error codes.
---
## E. Test requirements
The uBridge test suite already drives bridge/veth setups; the following cases
pin the contract (all are cheap AF_PACKET probes — send a frame with a given
destination MAC into port A, observe whether it arrives on port B, using
`PACKET_OUTGOING` filtering so a port's own transmissions do not count):
* **T1 transparency**: with two veths in one bridge created via `brctl`:
`01:00:5e:00:00:01` forwarded, `01:80:c2:00:00:0e` (LLDP) forwarded,
`01:80:c2:00:00:02` (LACP) forwarded, `01:80:c2:00:00:00` (STP) forwarded,
`01:80:c2:00:00:01` (PAUSE) **not** forwarded.
* **T2 ingress semantics**: mask on the egress port only → LACP not forwarded
(documents why every port is set; regression guard against "set it once").
* **T3 best-effort**: force the mask write to fail (fault-injection hook or an
invalid attribute id) and assert `addif` still replies `HSC_INFO_OK`.
* **T4 idempotency**: `addif` twice → both succeed, mask still `0xfffd`.
* **T5 value boundary** (optional, documents R2): a direct write of `0xfffe`
through the port setter fails with `EINVAL`.
---
## gns3-server alignment (informational — not uBridge scope)
* **No server change is required** for the behavior: all five server-side
enslavements (`compute/kernel_datapath.py:165`,
`compute/builtin/nodes/ethernet_switch.py:399,518`,
`compute/builtin/nodes/cloud.py:377`, and anything added later) go through
`brctl addif`.
* If R8's version bump lands, gns3-server can raise
`_check_ubridge_version`'s minimum so that a compute that cannot deliver
the behavior is reported instead of silently degrading.
* GNS3 documentation will state the resulting matrix for kernel links:
LLDP/DCBX ✅, LACP ✅, 802.1X ✅, STP ✅, **PAUSE/PFC ❌** (kernel-level,
not fixable by mask).
* The planned VXLAN datapath inherits the same story: the vxlan device is a
bridge port, so the same per-port mask applies; PAUSE/PFC stays out of
reach there too. That must be decided before VXLAN ships, because today's
cross-compute relay links *do* carry PFC and would silently regress.
## Roadmap note
If PFC emulation ever becomes a hard requirement, the only paths are a
patched kernel (`case 0x01`), a tc/eBPF ingress redirect on the anchor, or a
userspace AF_PACKET pass-through in uBridge (packet sockets see these frames
before the bridge drops them). None of these is part of this spec.
## References
* Kernel: `net/bridge/br_input.c` (`br_handle_frame`, the link-local switch),
`net/bridge/br_private.h` (`BR_GROUPFWD_*`, `BR_GROUPFWD_RESTRICTED`).
* Per-port mask: commit
[`5af48b59f35c`](https://github.com/Freescale/linux-fslc/commit/5af48b59f35cf712793badabe1a574a0d0ce3bd3)
("net: bridge: add per-port group_fwd_mask with less restrictions");
[patchwork entry](https://patchwork.ozlabs.org/project/netdev/patch/1506517964-17479-1-git-send-email-nikolay@cumulusnetworks.com/).
* Measurements: stock mainline 7.2.6-1-default, two veth ports in one Linux
bridge, AF_PACKET probes (2026-10).
+146
View File
@@ -0,0 +1,146 @@
# Ubuntu 24.04 GNS3 Development Environment Setup
## Simplified Development Environment Setup
### 1. Add PPA
```bash
sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository ppa:gns3/ppa
sudo apt update
```
### 2. Install Dependencies
Binary tools (Dynamips, VPCS, uBridge, etc.) are automatically installed as gns3-server dependencies
```bash
sudo apt install gns3-server tshark
```
### 3. Remove gns3-server While Keeping Dependencies
If you only want to run the server from source:
```bash
# Remove main package only, keep dependencies
sudo apt remove gns3-server
# Mark dependencies as manual to prevent autoremove deletion
sudo apt-mark manual ubridge dynamips vpcs libvirt
```
### 4. Install and Start Docker
```bash
sudo apt install docker.io
sudo systemctl enable --now docker
```
#### Configure Docker Mirror Accelerator (China Mainland)
If Docker Hub is inaccessible, configure mirror accelerators:
```bash
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<'EOF'
{
"registry-mirrors": [
"https://docker.1ms.run",
"https://docker.xuanyuan.me"
]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker
```
Verify:
```bash
docker info | grep -i mirror
```
### 5. Add User to Groups
```bash
# If running as gns3 user (created by PPA install):
sudo usermod -aG ubridge,docker,kvm gns3
# If running as your own user, add yourself to these groups:
sudo usermod -aG ubridge,docker,kvm $USER
# Then logout and login again for group membership to take effect
```
### 6. Install Python venv
```bash
sudo apt install python3.12-venv
```
### 7. Run Development Version from Source
Clone the repository (official or your fork):
```bash
# Official repository
git clone https://github.com/GNS3/gns3-server.git
# Or your forked repository
git clone https://github.com/yourname/gns3-server.git
cd gns3-server
git checkout your-branch
```
Setup virtual environment and install dependencies:
```bash
python3 -m venv venv
source venv/bin/activate
# For China mainland users, use mirror:
# pip install -e . -i https://mirrors.aliyun.com/pypi/simple/
pip install -e . && gns3server-web-wireshark-setup
pip install -e .[ai-features]
pip install -e .[dev]
```
Run the server:
```bash
python3 -m gns3server
```
## Optional: Install AI Features Development Dependencies
```bash
python3 -m pip install .[ai-features,dev]
```
## Optional: Expand LVM Root Partition
If the root partition is low on space but the volume group has unallocated space:
Check LVM status:
```bash
sudo lvm pvdisplay
sudo lvm vgdisplay
sudo lvm lvdisplay
```
Extend the root LV using all free space:
```bash
sudo lvm lvextend -l +100%FREE /dev/mapper/ubuntu--vg-ubuntu--lv
sudo resize2fs /dev/mapper/ubuntu--vg-ubuntu--lv
```
Verify:
```bash
df -h
```
+80
View File
@@ -0,0 +1,80 @@
# API Error Response Format
## Overview
GNS3 Server uses a unified error response format across all API endpoints. All error responses return a JSON object with a `message` field containing the error details.
## Response Format
```json
{
"message": "Error description here"
}
```
## Error Types
| Error Type | HTTP Status | Description |
|------------|-------------|-------------|
| `ControllerBadRequestError` | 400 | Invalid request parameters (e.g., validation failure) |
| `ControllerUnauthorizedError` | 401 | Missing or invalid authentication |
| `ControllerForbiddenError` | 403 | User lacks required privileges |
| `ControllerNotFoundError` | 404 | Resource not found |
| `ControllerError` | 409 | General conflict (e.g., duplicate name) |
| `ControllerTimeoutError` | 408 | Operation timed out |
| `ComputeConflictError` | 409 | Compute node returned a conflict |
| `RequestValidationError` | 422 | Pydantic/FastAPI validation error (field missing or type mismatch) |
| `SQLAlchemyError` | 500 | Database error |
## Error Response Examples
### Template Already Exists (409)
```json
{
"message": "A template with name 'my-template' already exists"
}
```
### Validation Error (422)
```json
{
"message": "image field is required"
}
```
### Permission Denied (403)
```json
{
"message": "Permission denied (privilege Template.Allocate is required)"
}
```
### Invalid Template Type (400)
```json
{
"message": "JSON schema error received while creating new template: ..."
}
```
## Client-Side Error Handling
When handling errors in the GNS3 Web UI or API clients:
```javascript
// Extract error message from response
function extractErrorMessage(error) {
if (error.error && error.error.message) {
return error.error.message;
}
if (error.message) {
return error.message;
}
return 'Unknown error';
}
```
## References
- Exception handlers: `gns3server/api/server.py`
- Template validation: `gns3server/schemas/controller/templates/`
- Error classes: `gns3server/controller/controller_error.py`
@@ -0,0 +1,266 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is AI-generated with reference to actual code and verified
> against real-kernel testing (Linux 7.1.2-1-default). AI can make mistakes —
> please verify against the source code when in doubt.
# Builtin Ethernet Switch — uBridge brctl Backend
## Overview
The historical GNS3 Ethernet Switch was an emulated L2 device inside Dynamips
(`ethsw`). This implementation replaces it with a **real Linux kernel bridge**
driven through uBridge's `brctl` module — one bridge per switch node. The
migration makes the switch a first-class builtin node (no Dynamips dependency)
and enables native-kernel-speed L2 switching with VLAN filtering and QinQ.
| | Old (Dynamips ethsw) | New (uBridge brctl) |
|---|---|---|
| Switching engine | Dynamips user-space emulation | Linux kernel bridge (netlink) |
| VLAN model | ethsw ACL per port | Kernel VLAN filtering + PVID/untagged |
| QinQ | 0x8100/0x88A8/0x9100/0x9200 | 0x8100 (802.1Q) / 0x88A8 (802.1ad) |
| Data path | Node NIO ↔ ethsw NIO (Dynamips) | Node NIO ↔ uBridge relay ↔ TAP ↔ kernel bridge |
| Console | Inactive (reserved TCP port) | None (console_type=none) |
| Node type | `dynamips`-routed | `builtin` (always-on) |
## Architecture
```
┌───────────┐ ┌──────────────┐ ┌───────────────┐ ┌───────────┐
│ Peer A │ │ uBridge │ │ Kernel │ │ Peer B │
│ (Dynamips │◄───►│ per-port │◄───►│ Bridge │◄───►│ (IOU / │
│ / IOU / │ UDP │ relay │ TAP │ gns3{id[:6]}│ TAP │ QEMU / …) │
│ QEMU) │ │ nio_tap↔udp │ │ vlan_filter │ │ │
└───────────┘ └──────────────┘ └──────┬────────┘ └───────────┘
│
┌─────┴─────┐
│ ... more │
│ ports │
└───────────┘
```
Each switch port is a **dual-role TAP** — uBridge holds the file descriptor as a
`nio_tap` relay endpoint, and the same TAP is enslaved to the kernel bridge via
`brctl addif`. This is the same pattern the Cloud node already uses for host
bridges (`cloud.py:_add_linux_ethernet`). uBridge is **only** the per-port UDP
transport; the kernel bridge performs the actual MAC learning, forwarding, and
VLAN filtering.
### Component map
| File | Role |
|------|------|
| `compute/builtin/nodes/ethernet_switch.py` | Node implementation |
| `api/routes/compute/ethernet_switch_nodes.py` | REST endpoints (repointed to Builtin) |
| `schemas/compute/ethernet_switch_nodes.py` | Request/response models (unchanged) |
| `controller/udp_link.py` | Link creation — pushes NIO to switch via standard adapter endpoint |
## Lifecycle
### `create()` → `start()`
1. `_start_ubridge(require_privileged_access=True)` — launch uBridge instance
2. `_ensure_bridge()`:
- Derive deterministic bridge name: `gns3` + first 6 hex chars of `self.id`
- `brctl delete` (best-effort — crash recovery, cleans stale interfaces)
- `brctl create`
- `link set … up` (bridge is DOWN after create)
- `brctl vlanfiltering … on`
### `add_nio(nio, port_number)`
Per port, one uBridge relay bridge `{node_id}-{port}` is wired:
```
bridge create {node_id}-{port}
bridge add_nio_tap {node_id}-{port} "{tap}" ← uBridge holds TAP fd
brctl addif "{bridge}" "{tap}" ← enslave to kernel bridge
brctl vlan_del/vlan_add … ← apply port VLAN mode
bridge add_nio_udp {node_id}-{port} lport rhost rport
bridge reset_packet_filters {node_id}-{port} ← from _ubridge_apply_filters
bridge start {node_id}-{port}
```
Captures and marker signals are applied via the existing `_ubridge_apply_filters`
and `_ubridge_apply_markers` helpers from `BaseNode`. The controller therefore allows
packet filters and traffic-insight markers on switch links (including switch-to-switch):
`ethernet_switch` is a marker/filter-capable node type, and the compute API exposes the
matching NIO-update and per-marker endpoints. The `ethernet_hub` — still Dynamips-hosted,
no uBridge — remains excluded.
### `remove_nio(port_number)`
```
brctl delif "{bridge}" "{tap}"
bridge delete {node_id}-{port}
release_udp_port(nio.lport)
```
### `close()`
```
for each port: release UDP port
brctl delete "{self._bridge_name}" ← kernel bridge teardown
_stop_ubridge() ← destroys remaining TAPs
```
**Cleanup paths:**
| Scenario | Bridge cleanup | TAP cleanup |
|----------|---------------|-------------|
| Normal project close | `close()` → `brctl delete` | uBridge stops → TAP fd closed → kernel destroys |
| gns3server crash / kill | Next `_ensure_bridge()` → `brctl delete` before `create` | uBridge dies → TAP fd closed by kernel |
| Manual project-file deletion after crash | Leaked (no GNS3 record of `gns3{id[:6]}`) | Leaked (same — but uBridge probably dead, TAPs gone with it) |
## Port mode → VLAN translation
All VLAN operations ride on the `brctl` hypervisor module (`../ubridge/doc/brctl.md`).
The kernel bridge must have `vlan_filtering on` before any `vlan_*` call.
### access VLAN N
```
brctl vlan_del {br} {tap} 1 ← remove default PVID 1
brctl vlan_add {br} {tap} N pvid untagged
```
### dot1q trunk (native VLAN V)
A dot1q trunk in ESW is "admit all VLANs tagged, native VLAN PVID + untagged":
```
brctl vlan_del {br} {tap} 1
brctl vlan_add {br} {tap} 1 vid 4094 ← admit all VIDs tagged
brctl vlan_add {br} {tap} V pvid untagged ← override native
```
### qinq (outer VLAN O, ethertype 0x88A8)
Bridge-level (once):
```
brctl setvlanproto {br} 0x88a8 ← switch to 802.1ad (outer S-tag)
```
Port-level:
```
brctl vlan_del {br} {tap} 1
brctl vlan_add {br} {tap} O pvid untagged ← S-tag push for untagged ingress
```
Ethertype 0x8100 qinq ports are treated as plain access ports (the bridge
defaults to 0x8100; no `setvlanproto` needed). Ethertype 0x9100/0x9200 are
not supported by the kernel bridge — see § Limitations.
### Runtime reconfiguration (`update_port_settings`)
On `ports_mapping` update, existing port VLANs are reset before re-apply:
```
brctl delif {br} {tap} ← release from bridge (clears VLAN state)
brctl addif {br} {tap} ← re-enslave (resets to default PVID 1)
brctl vlan_del/vlan_add … ← apply new mode
```
This prevents stale VLAN membership from a previous mode leaking into the new
configuration (e.g., access→trunk transition leaving old access VLAN behind).
## Bridge naming
Deterministic from the switch's UUID: `gns3` + first 6 hex chars (no dashes).
```
gns3a1b2c3 ← bridge (10 chars, ≤ 15 IFNAMSIZ limit)
gns3a1b2c3-0 ← tap for port 0 (12 chars)
gns3a1b2c3-1 ← tap for port 1 (12 chars)
```
- 6 hex = 48 bits of entropy — collision risk is astronomically low even with
thousands of switches on the same host.
- **Crash recovery**: `brctl delete` (best-effort, ignore if not found) then
`brctl create` — stale interfaces from a previous abnormal shutdown are
reclaimed automatically when the switch is re-created.
## Controller integration
No controller or API contract changes are required. The migration is entirely
compute-internal:
- `node_types.BUILTIN_NODE_TYPES` already classified `ethernet_switch` as a
builtin, always-running node.
- `udp_link.create()` pushes the NIO to the switch via the standard
`POST /adapters/0/ports/{p}/nio` endpoint (same as Dynamips).
- The REST API paths, request/response schemas, and port model
(`EthernetSwitchPort`: type/vlan/ethertype) are unchanged.
- `/start`, `/stop`, `/suspend`, `/reload` return 405 (switch is always-on).
The sole observable difference: the `console` field in the response is now
`null` (the switch has no console; `console_type="none"` makes `BaseNode`
skip TCP port reservation). The old Dynamips ethsw returned an unused TCP
port number. Both are valid under `Optional[int]`.
## Known limitations
### Default PVID 1 must be deleted explicitly
A port freshly enslaved to a `vlan_filtering` bridge inherits default PVID 1
(PVID + Egress Untagged). Access/trunk mode application must issue
`vlan_del … 1` first — `vlan_add … pvid` moves the PVID but does not remove
the old PVID's membership. This matches iproute2 semantics and is documented
in `../ubridge/doc/brctl.md#limitations`.
### QinQ is outer-tag (S-VLAN) only
With `setvlanproto 0x88a8` the bridge filters on the outer S-tag; the inner
C-tag passes through transparently. Selective QinQ (inner-VLAN classification
or remapping) requires `IFLA_BRIDGE_VLAN_TUNNEL_INFO` which is not implemented.
Documented in `../ubridge/doc/brctl.md#limitations`.
### Ethertype 0x9100 / 0x9200
The GNS3 schema allows legacy QinQ ethertypes `0x9100` and `0x9200`, but the
Linux kernel bridge only supports `0x8100` (802.1Q) and `0x88a8` (802.1ad).
Configuring these on a qinq port produces a `NodeError` at creation/update
time. Handling policy (map to 0x88A8 + warn vs. reject with error) is
pending per design discussion.
### No FDB read/write
The `brctl` module exposes no `fdb_show`/`fdb_flush`. The kernel bridge
learns and ages MAC entries autonomously; uBridge has never exposed MAC-table
access and gns3-server does not consume it. Consumers that need the FDB
(e.g., a WebUI switch view) should read `/sys/class/net/<br>/brforward` or
`bridge fdb show dev <br>` directly, without uBridge involvement.
## Troubleshooting
### Docker iptables: FORWARD chain DROP
Docker sets the iptables `FORWARD` chain default policy to `DROP` when the
Docker daemon starts. This blocks **all** forwarded traffic through kernel
bridges on the host, including `gns3*` bridges.
**Symptoms**: nodes can send frames into the bridge (visible in `tcpdump -i
gns3*`) but never receive unicast replies. ARP and multicast may work
because they flood, but unicast forwarding silently fails.
**Fix**:
```bash
sudo iptables -P FORWARD ACCEPT
```
### Bridge left DOWN after creation
`brctl create` creates the bridge but leaves it administratively DOWN.
The node now sends `link set … up` after `brctl create`. If forwarding
is not working, verify:
```bash
ip -d link show gns3* | grep -E "state|vlan_filtering"
```
### Kernel version differences
This implementation has been tested on Linux 7.1.2-1-default (x86_64) with
uBridge installed via `make install` (cap_net_admin,cap_net_raw=ep). The
ubridge `brctl` module has a 168-test suite covering kernel-side VLAN
behaviour on this kernel.
+146
View File
@@ -0,0 +1,146 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Controller + Compute Setup
This document describes the minimum configuration required to set up a GNS3 Controller with remote Compute nodes.
## Architecture Overview
- **Compute**: Runs individual nodes (QEMU, Docker, etc.) and provides resource monitoring
- **Controller**: Manages multiple computes, projects, and provides the REST API
- **Database**: Controller uses SQLite to store projects, nodes, and compute registration
## Minimum Configuration
### 1. Compute Node Configuration
Create the configuration file at `~/.config/GNS3/3.1/gns3_server.conf`:
```ini
[Server]
host = 0.0.0.0
port = 3080
compute_username = gns3
compute_password = gns3
```
Start the Compute:
```bash
gns3server
```
### 2. Controller Node Configuration
Create the configuration file at `~/.config/GNS3/3.1/gns3_server.conf`:
```ini
[Server]
host = 192.168.1.140
port = 3080
compute_username = gns3
compute_password = gns3
```
Start the Controller:
```bash
gns3server
```
### 3. Register Compute with Controller
Use the API to register a remote compute:
```bash
POST /v3/computes
{
"protocol": "http",
"host": "192.168.1.x",
"port": 3080,
"user": "gns3",
"password": "gns3"
}
```
## Important Notes
### Host Configuration
- **Controller `host`**: If set to `0.0.0.0`, the controller will register itself as `127.0.0.1`, which breaks remote compute connections
- **Symptom**: Compute nodes report "No common subnet for compute X (controller) and Y" even when on the same network
- **Solution**: Always use the actual LAN IP address for the Controller's `host` field (e.g., `host = 192.168.1.104`)
- **Dynamic IP**: If the controller machine uses DHCP, set a static lease on the router or use mDNS (`.local` domain)
### Password Configuration
- If `compute_password` is not set, a random 16-character password is auto-generated on startup
- The Controller must use the same credentials as the Compute's configuration
### Network Requirements
- Controller and Compute must be on the same LAN for cross-compute links to work
- UDP tunnel is used for cross-compute links, requiring network connectivity on UDP ports
### Configuration File Location
- Default location: `~/.config/GNS3/3.1/gns3_server.conf`
- Version `3.0` uses `~/.config/GNS3/3.0/`
## Troubleshooting
### 401 Unauthorized on Compute Connect
1. Check that Compute's `compute_username` and `compute_password` match what was passed to the API
2. Verify the Compute's configuration file is correctly loaded
3. Ensure the `[Server]` section is used (not `[Controller]`)
### No Common Subnet Error
If compute nodes report:
```
Cannot get an IP address on same subnet: No common subnet for compute X (controller) and Y
```
1. **Primary cause**: Controller's `host` is set to `0.0.0.0` - it registers as `127.0.0.1` which is unreachable from compute nodes
2. Check the controller's `/v3/version` endpoint - if `controller_host` shows `127.0.0.1`, this is the issue
3. Set the Controller's `host` to its actual LAN IP address (e.g., `192.168.1.104`)
4. Verify both machines are on the same network and can ping each other
5. Check firewall rules allow TCP/UDP communication on required ports
### WebSocket Console Authentication Failed
When connecting to a remote compute node's console via WebSocket, the connection may fail with errors in the logs:
**Controller log:**
```
New client 192.168.1.104:33268 has connected to controller console WebSocket
Forwarding console WebSocket to 'ws://192.168.1.3:3080/v3/compute/projects/.../console/ws'
Client 192.168.1.104:33268 has disconnected from controller console WebSocket
```
**Compute log:**
```
WebSocket /v3/compute/projects/.../console/ws" [accepted]
ERROR gns3server.api.routes.compute.dependencies.authentication:103 Could not authenticate while connecting to compute WebSocket: Could not validate credentials
```
**Cause**: The Controller forwards its own `compute_username` and `compute_password` credentials when connecting to the Compute's WebSocket endpoint. If the Compute node does not have matching credentials configured, authentication fails.
**Solution**: Ensure the Compute node's configuration file has matching credentials:
```ini
[Server]
enable_http_auth = True
compute_username = gns3
compute_password = your_password
```
The Controller automatically uses its configured `compute_username` and `compute_password` when establishing WebSocket connections to remote computes (see `gns3server/api/routes/controller/nodes.py` lines 627-628).
**Note**: If `compute_password` is not explicitly set in the Compute's config, a random 16-character password is auto-generated at startup, making authentication impossible for any external Controller.
+571
View File
@@ -0,0 +1,571 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Docker exec Console (Vendor NOS Containers)
## Overview
GNS3 Docker nodes normally expose their console by attaching to the container's
PID 1 stdio. That works for CLIs that run as PID 1 (e.g. FRR's `vtysh`), but it
does **not** work for vendor NOS containers (Nokia SR Linux, Arista cEOS,
Juniper cRPD, …) whose CLI is a separate, full-screen TUI process that is *not*
on PID 1. For those, attaching to PID 1 only shows boot logs and never yields a
CLI prompt.
The `docker_exec` console type solves this. It runs a chosen command inside the
running container via the Docker exec API (with a pty) and bridges it to the
GNS3 console, so the vendor's native TUI CLI renders in the Web UI (xterm.js)
exactly as if you had run `docker exec -it <container> <cli>` in a real
terminal.
Two companion environment knobs (`GNS3_SKIP_INIT`, `GNS3_INTERFACE_NAMES`) make
the container itself boot and wire correctly for vendor NOS images. Together
they let a vendor NOS run as a first-class GNS3 Docker router node.
> Prototype status: the knobs are environment-driven and intentionally avoid
> schema changes, so existing Docker nodes (FRR, ipterm, …) are unaffected.
> `console_type: "docker_exec"` is added to the `ConsoleType` enum.
## Environment knobs
All are read from the node's `environment` field. Entries prefixed with
`GNS3_` are **not** forwarded into the container (existing GNS3 behaviour), so
they stay host-side configuration. The console-relevant ones (the full vendor
set, incl. `GNS3_SHM_SIZE` / `GNS3_DEVICES` / `GNS3_MASK_UDEV` /
`GNS3_STOP_TIMEOUT`, is documented in [vendor-nos-xrd.md](./vendor-nos-xrd.md)):
| Variable | Purpose |
|----------|---------|
| `GNS3_SKIP_INIT=1` | Do **not** prepend `/gns3/init.sh` to the entrypoint. Vendor NOS images must run their own entrypoint (e.g. SR Linux's `sr_linux`); GNS3's init script (busybox bootstrap, `ifup`, eth wait) interferes with them. |
| `GNS3_INTERFACE_NAMES=mgmt0,e1-1,e1-2,e1-3` | Rename the injected interfaces in adapter order instead of the default `eth{N}`. SR Linux expects `mgmt0` + `e1-N`; without this it does not recognise its datapath. |
| `GNS3_CONSOLE_CMD=/opt/srlinux/bin/sr_cli` | Command run by the `docker_exec` console inside the container. |
| `GNS3_CONSOLE_RESIZE=0` | Ignore client-driven console resizes (WS terminal-size control frames / telnet NAWS) and keep the tall no-paging PTY geometry. Set for CLIs that page on the PTY window size (IOS-XR) — see [Terminal geometry](#terminal-geometry-and-size-forwarding). |
## Architecture: `VendorDockerVM` subclass
All vendor-specific logic lives in a `VendorDockerVM(DockerVM)` subclass in
`gns3server/compute/docker/vendor_docker_vm.py` — `docker_vm.py` itself stays
on its baseline behaviour and is never touched by this feature.
`DockerVM` exposes four small extension hooks (pure refactorings, zero
behaviour change for existing nodes):
| Hook | Baseline behaviour | `VendorDockerVM` override |
|------|--------------------|---------------------------|
| `_prepare_init_and_interface_env(params)` | prepend `/gns3/init.sh`, set `GNS3_MAX_ETHERNET=eth{N-1}` | conditional init.sh (`GNS3_SKIP_INIT`), `GNS3_MAX_ETHERNET` follows the interface rename |
| `_start_console_server()` | telnet/ssh/http console dispatch | adds the `docker_exec` branch |
| `_get_container_ifname(adapter_number)` | `eth{N}` | `GNS3_INTERFACE_NAMES` lookup, fallback `eth{N}` |
| `_cleanup_console_resources()` | no-op | closes the docker-exec pty socket before restart/stop |
### Class selection
The Docker manager picks the class per node in `Docker.create_node()`
(`gns3server/compute/docker/__init__.py`):
```python
def _select_node_class(self, **kwargs):
if kwargs.get("console_type") == "docker_exec":
return VendorDockerVM
return DockerVM
```
`console_type == "docker_exec"` is the **only** trigger — every other console
type (telnet, vnc, ssh, http, …) keeps using the unmodified `DockerVM`. All
vendor features are opt-in: without the `GNS3_*` environment variables a
`VendorDockerVM` instance behaves identically to `DockerVM` (init.sh still
runs, interfaces stay `eth{N}`, the exec command defaults to `/bin/sh`), so a
regular container can use `docker_exec` too.
## The `docker_exec` console type
Setting `console_type: "docker_exec"` makes the node's primary console port run
`_start_docker_exec_console()` instead of the attach-to-PID-1 path.
### Console architecture
```mermaid
graph LR
A[Web UI xterm.js] -->|console WS: text frames| B[Controller forward]
B -->|WS: text + binary| C[GNS3 Compute telnet server]
C -->|binary pty stream| D[Docker exec API]
D -->|Tty:true pty| E[sr_cli / vendor CLI]
A -.->|binary control frame {"cols","rows"}| B
B -.-> C
C -.->|POST exec/.../resize| D
```
The console uses GNS3's **existing shared/broadcast telnet model**: a single
exec instance (one CLI session) is broadcast to every console client, exactly
like the primary console shares one PID 1. There is deliberately **no
per-client session isolation** — this matches how every other GNS3 console
behaves. The PTY geometry is likewise shared: the last client resize wins
(see [Terminal geometry](#terminal-geometry-and-size-forwarding)).
### Implementation
**File**: `gns3server/compute/docker/vendor_docker_vm.py` —
`_start_docker_exec_console()`
A small subclass `_LazyExecTelnetServer(AsyncioTelnetServer)` implements the
console. Key points:
1. **Lazy exec creation.** The exec is created on the **first client
connection** (`client_connected_hook`), not when the node starts. This is
essential: vendor CLIs (e.g. `sr_cli` via `prompt_toolkit`) send a
cursor-position request (`\e[6n`, CPR) during startup and block waiting for
the terminal's answer. If the exec starts at node-start time there is no
xterm.js client to answer, the probe times out, and the TUI degrades (no
status bar, "Terminal doesn't support CPR" warning). Creating the exec on
first connect means the probe runs with a real xterm.js attached, which
answers CPR → full TUI. After creation the exec is shared by all clients.
2. **Exec API with a pty.** `POST containers/{cid}/exec` with
`Tty: true`, `User: "root"` (vendor CLIs reject the image's default
unprivileged user — SR Linux returns *"User 'user' is not authorized to use
CLI"* otherwise), and `Env: ["TERM=xterm"]` (the TUI library needs a
recognised terminal).
3. **No while-true wrapper.** The command runs as `sh -c "<cmd>"` (no
restart loop). When the CLI exits (`quit`, the NOS's own idle timeout, or a
crash) the exec pty closes, the broadcast task ends, and the next client
connection **recreates** the exec (see *Reconnection*). A `while true`
wrapper would restart the CLI mid-session with no client attached to
answer its startup CPR probe, producing a blank/degraded screen on
reconnect.
### Reconnection
The exec is created lazily and **recreated on reconnect if it has died**.
`client_connected_hook` checks `_upstream_alive()` (exec id set, writer open,
broadcast task not done) before each connect:
- **First connect / dead upstream** → (re)create the exec. Because a client is
now attached, the CLI's startup CPR probe is answered by xterm.js → full
TUI. A half-dead writer is closed first to avoid a socket leak.
- **Live upstream** → reuse the existing exec, just send `Ctrl-L` to redraw
for the new client.
This is what makes the console survive `quit`, idle timeout, and CLI
crashes: the death is detected (pty EOF ends the broadcast task) and the
next connection spins up a fresh exec with a terminal present. The
`_LazyExecTelnetServer` is extracted to module level specifically so this
reconnect logic is unit-tested.
4. **Hijacked raw-HTTP start.** The exec is started with
`POST exec/{eid}/start` sent as a raw HTTP upgrade over the Docker unix
socket (`asyncio.open_unix_connection`), the same approach docker-py uses.
This is required because aiohttp's websocket client (`ws_connect`) is
rejected by Docker's exec-start endpoint (HTTP 400), while a raw POST
upgrade succeeds (101). With `Tty:true` the response body is a raw,
non-multiplexed bidirectional pty byte stream — no frame demux needed.
5. **NAWS → exec resize.** The telnet server runs with `naws=True`; the
`window_size_changed_callback` (`_on_naws`, gated by
`GNS3_CONSOLE_RESIZE`) calls `POST exec/{eid}/resize?h=&w=` so the TUI
lays out for the client's window size. The internal `_resize_exec` path
(creation-time default, restore-on-idle) is not gated. See
[Terminal geometry](#terminal-geometry-and-size-forwarding).
6. **Binary passthrough + redraw.** `binary=True` so TUI escape sequences reach
xterm.js intact; `echo=False` (the pty echoes). On every client (re)connect
a `Ctrl-L` (`\x0c`) is sent to the pty so a TUI that already drew its
screen for a previous client redraws for the new one (otherwise a
reconnect shows a blank screen until the next output).
### Terminal geometry and size forwarding
The exec PTY geometry is a shared resource with three consumers that want
different things:
- **Browser clients (xterm.js)** need the PTY to match their real window, or
TUI CLIs misrender and over-render (below).
- **Non-NAWS clients** (netmiko, bare telnet — no terminal-size negotiation)
need the PTY *tall*: CLIs that page on the PTY window size (the IOS-XR
pager ignores `terminal length 0`) park at `--More--` on a 24-row PTY.
- **Concurrent sessions share one exec** — one browser resize changes what
every attached client sees.
Resolution:
1. **Tall default.** The exec is created at 511×10000 (width 511 matches
netmiko's `terminal width 511` convention). Non-NAWS clients get no paging
and no hard wrapping.
2. **WS terminal-size forwarding.** Console WebSocket clients may send
**binary control frames** — UTF-8 JSON `{"cols": N, "rows": N}` —
alongside text frames carrying terminal data (xterm.js's AttachAddon only
sends text, so binary is an unambiguous side channel; valid ranges are
cols 2–5000, rows 2–100000, anything else is silently ignored). The
controller forwards binary frames (previously only text was forwarded —
and a binary frame would have crashed the old `receive_text` loop), and
the compute side turns them into a telnet NAWS subnegotiation for
telnet-based consoles (docker_exec included) or an asyncssh
`change_terminal_size` for SSH consoles
(`base_node.py` `start_websocket_console`).
3. **Races.** A size frame that arrives before/during the exec creation is
remembered and applied right after creation — it is **not** overwritten by
the tall default. When the **last** client disconnects the exec goes back
to 511×10000, so a later non-NAWS client attaching to the still-live exec
doesn't inherit a browser geometry and hit PTY-window paging.
4. **`GNS3_CONSOLE_RESIZE=0`** makes the console ignore client resizes
entirely (the tall default is then permanent). Set it for paging CLIs
where a browser resize would break concurrent netmiko sessions on the
shared exec — XRd, which is line-oriented and doesn't need browser
resizing at all.
**Why the browser must send its size — the SR Linux flicker.** `sr_cli` is a
prompt_toolkit TUI that anchors its layout with cursor-position requests
(CPR), which xterm.js answers. On a 10000-row PTY canvas the CPR-anchored
model conflicts with the winsize model, and every incremental render re-emits
the accumulated output: measured with a CPR-answering client, one `info`
command produces **~145 KB instead of ~60 KB** (~7× duplicated lines either
way — the CLI re-renders its output region as a scroll-append stream; that
part is inherent to `sr_cli` and identical outside GNS3, verified via manual
`docker exec`). The inflation is driven by **rows** (24/32 → normal, 10000 →
pathological, at any width) and is invisible without CPR answers — which is
why plain-telnet probes and real xterm.js sessions behaved so differently.
In the Web UI the excess renders as frequent full-screen clear/redraw — the
"flicker". With the browser's real size forwarded (rows ≈ 30), output volume
and rendering return to normal.
**File**: `gns3server/compute/base_node.py` — the console WebSocket guard now
allows `docker_exec` (alongside `telnet`/`ssh`), since the WS bridge connects to
the console TCP port exactly as it does for telnet. The same WS handler also
intercepts binary control frames and propagates client terminal sizes (see
[Terminal geometry](#terminal-geometry-and-size-forwarding)).
### Why earlier approaches failed (context)
- `script` + `docker exec -it`: the `script` pty had size 0 (no NAWS) → the TUI
could not lay out → blank.
- `docker exec -i` (no `-t`) + `sr_cli -d` (dumb mode): line-mode output was
block-buffered and visually messy.
- Direct pipe relay: telnet `CRLF` polluted line input.
The exec-API approach fixes all of these: a real pty (`Tty:true`), a real size
(NAWS resize), and a real terminal emulator (xterm.js answering CPR).
## Configuration
### SR Linux node example
```json
{
"name": "srlinux-1",
"node_type": "docker",
"image": "ghcr.io/nokia/srlinux:latest",
"adapters": 4,
"console_type": "docker_exec",
"start_command": "sudo -E bash -c 'touch /.dockerenv && /opt/srlinux/bin/sr_linux'",
"environment": "GNS3_SKIP_INIT=1\nGNS3_INTERFACE_NAMES=mgmt0,e1-1,e1-2,e1-3\nGNS3_CONSOLE_CMD=/opt/srlinux/bin/sr_cli"
}
```
- `start_command` is the SR Linux launch line (as used by containerlab).
- Connect the node's ports as usual — links still use GNS3's UDP NIO datapath
(container-agnostic); the rename only affects the in-container interface name.
- For the Web UI port **labels** to match (display `mgmt0`/`e1-1` instead of
`Ethernet0..3`), set `custom_adapters` per port
(`{"adapter_number": 0, "port_name": "mgmt0"}`, …). Port labels are a
controller-side concept, independent of the compute-side interface rename.
### Appliance (`gns3a`) packaging
A SR Linux appliance lives in `gns3-registry/appliances/srlinux.gns3a`
(`registry_version: 6`). It sets the full chassis — **35 adapters**
(`mgmt0` + `e1-1`..`e1-34`) — with matching `GNS3_INTERFACE_NAMES` and 35
`custom_adapters` entries (`mgmt0`, `e1-1`..`e1-34`) so the canvas labels,
the kernel interface names and the `ethernet-1/N` CLI names all line up.
Three appliance-schema fixes are required for this appliance to load (all on
the gns3-server side; the registry JSON schema is unchanged because its docker
block allows `additionalProperties`):
1. **`DockerConsoleType`** (`schemas/controller/appliances.py`) must include
`docker_exec`, or the Pydantic appliance model rejects the file at import.
2. **`ApplianceV1_6.custom_adapters`** must be declared on the top-level
appliance model, or `GET /appliances` (response_model=`schemas.Appliance`)
strips `custom_adapters` from the API response even though the file and the
server-side template conversion handle it. (Node creation still worked
because `appliance_to_template._add_docker_config` reads it from the raw
dict; only the GET response was lossy.)
3. `extra_volumes` rides inside the `docker` block (passed through by
`new_config.update(appliance_config["docker"])`); no schema change needed.
> **Symbol theme caveat.** An appliance `symbol` that starts with
> `:/symbols/` is forcibly rewritten at load time
> (`appliance_manager._load_appliances`) to the current theme's default for the
> appliance category — so `:/symbols/affinity/circle/blue/router_cloud.svg` (or
> `router2.svg`) becomes `:/symbols/affinity/circle/blue/router.svg`, because
> the theme maps only the canonical name `"router"`. This is intentional: it
> lets theme switching re-skin every node consistently. To use a non-default
> icon (e.g. `router_cloud`), install it as a **custom symbol** under the
> configured `symbols_path` and reference it by filename (no `:/symbols/`
> prefix) — custom symbols do not participate in re-theming. The SR Linux
> appliance uses `router.svg`.
### Persistent state
For SR Linux, persist `/etc/opt/srlinux` (config / AAA users / TLS certs) and
`/var/log/srlinux` (logs, optional) by adding them to the node's
`extra_volumes`. The image also declares its own `VOLUME` directories
(e.g. `/opt/srlinux/appmgr`), which GNS3 persists automatically.
## Volume persistence with `GNS3_SKIP_INIT`
This is the one place where skipping init.sh changes behaviour beyond boot:
`/gns3/init.sh` normally performs the volume-persistence bridge, and without it
**nothing writes through to the host** — the container writes to its overlay
filesystem and the data is lost on stop.
init.sh (as the entrypoint) is safe because it runs **before** the
application: for each volume it seeds the host directory with the image's
original files on first start, then `mount --bind /gns3volumes<path> <path>`
bridges persistent storage into place.
`VendorDockerVM` cannot use that position (the NOS must own its entrypoint),
so the same persistence is established entirely **outside the container and
before it exists**:
```
create() 之前: host dir seeded from the image (docker create + docker cp, first time only)
create() 时: host ──Docker bind mount──▶ /etc/opt/srlinux (direct, at the real path)
启动: NOS native entrypoint — the persisted config is visible from the first process
```
1. **`_prepare_volumes()`** — host-side, at `create()` time (after the image
is present, before the container is created). For each persistent volume
whose host directory lacks the `.gns3_perms` marker, a throwaway
`docker create` container (nothing executes) is used as a `docker cp -a`
source to seed the host directory with the image's original content. The
marker is written after the copy attempt — a volume that has it (every
node that ever started, on any GNS3 version) is **never re-seeded**, so
saved configuration is never overwritten with factory content.
2. **`_mount_binds()` override** — the volume binds target the **real
in-container paths** (`/etc/opt/srlinux`) instead of `/gns3volumes<volume>`.
With the content seeded first, the image's files are never shadowed by an
empty mount, and the NOS sees its persisted configuration from the very
first process — no post-start mount pass that could race the NOS reading
its startup config (see "History: the exec-bridge race" below).
3. **Container-side `_fix_permissions()` override** — runs the same busybox
record/chmod/chown script **inside the container (as root) on the volume
paths**. Because the volumes are Docker bind mounts created with the
container, the in-container paths resolve to the host files for the whole
container lifetime. A stopped/exited container is **not** restarted (the
base class would, just to chown; vendor NOS images are heavy to boot):
the pass is skipped and the next start fixes ownership. It runs at start
(so the controller can read project files while the node runs) and at
stop (for files written during runtime).
> The fix must run container-side: files written by the container are
> host-side root-owned, and an unprivileged GNS3 process cannot chown them
> from the host. Container-side root (with GNS3's `UsernsMode: host`) can.
With `GNS3_SKIP_INIT`, GNS3's hardcoded `/etc/network` volume (see
`docker_vm.py` `_mount_binds()`) is dropped entirely by
`VendorDockerVM._mount_binds()`: it holds GNS3's own network config for
init.sh's `ifup`, which never runs for SKIP_INIT containers — the NOS
manages its own interfaces. The override removes the bind, filters the
volume out of `self._volumes`, and deletes the host-side skeleton directory
the base class just created. Without `GNS3_SKIP_INIT` the mount is kept
(behaviour matches the base class).
### Lifecycle summary
| Phase | Normal Docker node | `VendorDockerVM` + `GNS3_SKIP_INIT` |
|-------|--------------------|--------------------------------------|
| create | — | `_prepare_volumes()` seeds host dirs from the image (first create only); volumes bound **directly** at their real paths |
| start | init.sh seeds + bind-mounts + restores perms (in-container, before the app starts) | container-side `_fix_permissions` on the volume paths (skips dead containers, no restart) |
| stop | container-side `_fix_permissions` on in-container paths (restarts an exited container) | container-side `_fix_permissions` on the volume paths (skips dead containers, no restart) |
| volume config | `_mount_binds`: host → `/gns3volumes<path>` | `_mount_binds` override: host → `<path>` directly |
### Runtime ownership safety
The start-time fix pass chowns the volume files to the host user **while the
container is running** — a deliberate deviation from the standard model, where
init.sh restores container-native ownership at start and the container never
sees host-owned files during runtime. Verified harmless for SR Linux:
1. **Most processes run as root** (`sr_linux`, appmgr) — root ignores file
ownership entirely.
2. **Self-healing daemons.** SR Linux's `aaamgr` rewrites its managed files
with its own ownership at boot: after the start-time pass chowned
`etc/opt/srlinux/aaamgr_local_user.json` to the host user, the daemon
re-created it as `srlinux:srlinux` (uid 1002, mode 700) within seconds.
3. **ACL-based access.** The directory carries a default ACL
(`default:group:srlinux:rwx`, `default:other::rwx`), so named group ACL
entries grant access independently of the owner uid; the observed file ACL
(`group:srlinux:rwx`, owner `srlinux`) survives chown.
Caveat: a NOS that strictly validates ownership of its files (e.g. "SSH keys
must be root:root 600 or refuse to start") would not tolerate this. If that
ever matters, drop the start-time pass and keep only the stop-time one
(standard behaviour — the trade-off is mid-run `Permission denied` in the
file browser, identical to regular Docker nodes).
### History: the exec-bridge race (fixed)
The first SKIP_INIT implementation replicated init.sh's script **via
`docker exec` after the container started** instead of binding directly at
create time. That copied the mechanism but not the invariant that makes
init.sh safe — the entrypoint position, which guarantees the volume is in
place *before* the application runs. An exec-based bind runs **concurrently**
with the NOS boot, so whether the NOS reads its persisted config or the
overlay's factory copy was a timing race:
- a single node stop/start on an idle system won it (the exec landed ~1 s
in, SR Linux reads its startup config at ~2–4 s) — which is why the
round-trip "save → stop → start → config still there" passed;
- a server restart + project reload lost it (all nodes start concurrently,
the Docker API queue delays the execs by several seconds) — SR Linux
booted factory while the persisted `config.json` sat intact on the host;
- XRd was immune either way (systemd boots for tens of seconds before any
XR process touches `/xr-storage`), which is why the race was never seen
on it.
The direct-bind-at-create design removes the window entirely; there is no
ordering requirement left to verify when adopting a new NOS image.
## Troubleshooting
**1. Console shows only boot logs, no CLI**
- You are on the primary attach console. Set `console_type: "docker_exec"` and
use `GNS3_CONSOLE_CMD` to point at the vendor CLI.
**2. `User '...' is not authorized to use CLI`**
- The exec must run as root. The implementation sets `User: "root"`; if you
fork it, keep that.
**3. `Terminal doesn't support cursor position requests (CPR)`**
- This means the exec was started without an xterm.js client connected (the
startup probe had no one to answer). The lazy-start design avoids this; if you
see it, ensure the exec is created on first connect, not at node start.
**4. Reconnecting the Web console shows a blank screen**
- A `Ctrl-L` is sent on each connect to force a TUI redraw. If the TUI does not
redraw, verify the `client_connected_hook` still writes `\x0c` to the pty.
**5. `aiohttp WSServerHandshakeError: 400` on exec start**
- Do **not** use the websocket client to start an exec. Use the hijacked raw
HTTP upgrade over the unix socket (see Implementation).
**6. SR Linux data interfaces stay down**
- SR Linux defaults its data ports to `admin-state disable`; enable them in the
CLI (`interface ethernet-1/1 admin-state enable`) and bind the interface to a
network-instance before ping works. This is SR Linux behaviour, not a GNS3
issue.
**7. "Session has been idle, will logout in 300 seconds" → Connection closed**
- SR Linux's own CLI idle timeout logs the CLI out, the exec pty closes, and
the console disconnects. Reopening the console recreates the exec (see
*Reconnection*) and gives a fresh login. To keep a permanent session,
disable the timeout in the CLI: `enter candidate` →
`/system cli idle-timeout disable` → `commit now`.
**8. Controller logs `Permission denied` reading files under the node's
project directory while the node runs**
- Root-written files inside a persistent volume. The container-side
`_fix_permissions` pass runs at start (fixes the seeded files) and at stop;
files created by the container *during* runtime become readable after the
next stop.
- Concrete example: SR Linux's `aaamgr` daemon rewrites
`etc/opt/srlinux/aaamgr_local_user.json` during boot, **after** the
start-time pass, as the image's `srlinux` user (uid 1002, mode 700) — so
the host-side file stays `1002:1002` until the stop-time pass chowns it.
- The log line comes from the file-browser API chain: Web UI *Show in file
manager* → `GET /v3/projects/{pid}/nodes/{nid}/files`
(`controller/nodes.py:538`) → `project.list_node_files`
(`compute/project.py:510`), where `magic.from_file()` cannot read the
file and the `file_type` field is left empty for that entry. The MCP
`list_node_files` tool uses the same code path. Size/modified-at fields
and everything else keep working; only the type sniff and one warning
line are affected — same behaviour as any regular Docker node writing
root-owned files at runtime.
**9. Persistent volume empty on the host after `save` + stop**
- Ensure `GNS3_SKIP_INIT=1` is set (so the direct-bind path is taken) and
the volume path is in `extra_volumes`; check that the host directory
carries the `.gns3_perms` marker (written at create-time seeding) and the
compute log for `Seeded persistent volume`.
**10. Persisted config present on the host but not applied after restart**
- On builds since the direct-bind rework this should not happen: the volume
is in place before the first process. If you see it, confirm the server
build includes the rework (older builds established the bind via a
post-start `docker exec` that could lose the race against the NOS reading
its startup config — see *History: the exec-bridge race*).
**11. Web console flickers (full-screen clear/redraw) on every command**
- The PTY is stuck at the tall 511×10000 default while a CPR-answering client
is attached — see
[Terminal geometry](#terminal-geometry-and-size-forwarding). Check that the
Web UI actually sends the binary size control frames on connect/resize
(F12 → the console WS should show outgoing binary frames), and that the
server is new enough to forward them (the controller used to forward text
frames only). A client that never negotiates/forwards size (old Web UI,
bare telnet without NAWS) cannot trigger the fix — but also never answers
CPR, so it doesn't flicker either.
- The much milder per-keystroke/5 s cursor toggles (`\e[?25l…\e[?25h`) from
the TUI are normal and not this bug.
## Limitations
1. **Shared session (broadcast).** All console clients share one CLI session
and can see each other's input — identical to GNS3's existing primary
console model. There is no per-client independent session. The PTY
geometry is shared too (last resize wins): two browsers of different sizes
disagree harmlessly, but a browser on a *paging* CLI needs
`GNS3_CONSOLE_RESIZE=0` to stop resizing on behalf of concurrent netmiko
sessions (see [Terminal geometry](#terminal-geometry-and-size-forwarding)).
2. **`reset_console` not wired.** The console-reset action only handles
`telnet`/`ssh`; it is a no-op for `docker_exec` (non-blocking; reconnect
works fine).
3. **Prototype knobs.** `GNS3_SKIP_INIT` / `GNS3_INTERFACE_NAMES` /
`GNS3_CONSOLE_CMD` / `GNS3_CONSOLE_RESIZE` are environment-driven; they are
not yet first-class node schema fields and are not declared in the
appliance (`gns3a`) schema.
4. **Rootful-Docker assumption** (`UsernsMode: host`, set for all GNS3
Docker nodes) so the container-side chown acts on the host files' real
uid/gid (see the volume-persistence section).
5. **Docker CLI dependency.** Volume seeding shells out to the `docker`
binary (`docker create` + `docker cp` + `docker rm`) at create time —
the same dependency the permission passes already have.
## References
- `gns3server/compute/docker/vendor_docker_vm.py` — `VendorDockerVM`:
`_start_docker_exec_console`, `_LazyExecTelnetServer`,
`_prepare_volumes` (host-side seeding), direct volume binds in
`_mount_binds`, container-side `_fix_permissions`, `start()`.
- `gns3server/compute/docker/docker_vm.py` — `DockerVM` extension hooks
(`_prepare_init_and_interface_env`, `_start_console_server`,
`_get_container_ifname`, `_cleanup_console_resources`).
- `gns3server/compute/docker/__init__.py` — `Docker._select_node_class` /
`create_node` factory.
- `gns3server/compute/base_node.py` — console WebSocket guard; binary
terminal-size control frames → NAWS / asyncssh resize
(`start_websocket_console`).
- `gns3server/api/routes/controller/nodes.py` — console WS forwarding
(text and binary frames).
- `gns3server/schemas/common.py` — `ConsoleType.docker_exec`.
- containerlab `nodes/srl/srl.go` — reference for SR Linux launch command and
interface naming.
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.7 | 2026-08-22 | SKIP_INIT volume persistence rebuilt: host-side seeding at create time (`docker create` + `docker cp -a`, marker-gated so saved config is never overwritten) and direct bind mounts at the real in-container paths replace the post-start `docker exec` bridge. Root cause: the exec bridge raced the NOS reading its startup config — SR Linux read `config.json` at ~2–4 s and booted factory whenever concurrent node starts (server restart + project reload) delayed the exec past that point, while single-node stop/start and XRd (systemd touches `/xr-storage` tens of seconds in) never lost the race. New `_prepare_volumes` hook on `DockerVM`; `_fix_permissions` now targets the volume paths directly. |
| 1.6 | 2026-08-20 | Terminal geometry and size forwarding: WS binary control frames `{"cols","rows"}` → NAWS / asyncssh resize (controller now forwards binary frames; compute intercepts them); tall 511×10000 default kept for non-NAWS clients, applied post-creation and restored on last disconnect (client size racing exec creation wins over the default); new `GNS3_CONSOLE_RESIZE=0` knob for paging CLIs (XRd) where a browser resize would break concurrent netmiko sessions on the shared exec; documented the SR Linux flicker root cause (tall rows × CPR-answering client → ~2.4× re-emitted output; rows-driven, width-independent). |
| 1.5 | 2026-08-13 | Add appliance (`gns3a`) packaging section: 35-adapter full-chassis design, the three server-side schema fixes (DockerConsoleType, ApplianceV1_6.custom_adapters, extra_volumes passthrough), and the symbol-theme caveat (any `:/symbols/` symbol is rewritten to the category default at load). |
| 1.4 | 2026-08-13 | Reconnect fix: drop the while-true wrapper (it restarted the CLI with no client to answer CPR → blank screen on reconnect); the exec is now recreated on connect when the upstream has died. `_LazyExecTelnetServer` extracted to module level and unit-tested. |
| 1.3 | 2026-08-12 | Document runtime ownership safety (root processes, self-healing daemons, ACL evidence for SR Linux), the boot-ordering caveat (bridge after boot → verify save/stop/start closed loop), and troubleshooting #10. |
| 1.2 | 2026-08-12 | `_fix_permissions` rewritten: container-side (as root) on the `/gns3volumes` bind-mount targets instead of host-side — host-side chown cannot touch root-owned files when GNS3 is unprivileged. Dead containers are skipped instead of restarted. |
| 1.1 | 2026-08-12 | Refactor: vendor logic extracted from `DockerVM` into `VendorDockerVM` subclass with 4 hook points + class-selection factory. Add SKIP_INIT volume persistence (`_setup_skip_init_volumes` + `_fix_permissions`) and lifecycle comparison. Add troubleshooting entries for idle timeout and permission-denied files. |
| 1.0 | 2026-08-12 | Initial documentation of the `docker_exec` console and vendor NOS knobs. |
+330
View File
@@ -0,0 +1,330 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is AI-generated with reference to actual code and verified against real-kernel testing. AI can make mistakes — please verify against the source code when in doubt.
# Docker Kernel Datapath (veth + per-link Linux bridge)
## Overview
Docker node links historically flowed through a uBridge userspace relay: each adapter was a TAP whose file descriptor uBridge pumped between the container and UDP tunnels. This implementation replaces that model with **kernel-native forwarding**: every adapter is born as a **veth pair**, and each link is a **dedicated Linux kernel bridge** enslaving the two endpoints' veth host ends. Frames never leave the kernel.
| | Old (relay) | New (kernel datapath) |
|---|---|---|
| Adapter interface | TAP moved into the container netns | veth pair (guest end in container, host end in root ns) |
| Link | uBridge bridge, TAP fd ↔ UDP, userspace copy | per-link kernel bridge `gns3{link_id[:11]}`, zero-copy |
| Relay latency | ~0.3 ms RTT | ~0.05 ms RTT (measured) |
| Link attach at runtime | yes (relay attaches the pre-existing TAP) | yes (brctl addif / add_nio_ethernet — interface untouched) |
| Packet filters | uBridge userspace filters | tc netem on the veth host end (delay / packet_loss / corrupt / duplicate + the netem extensions rate, reorder, gemodel, seed, limit, jitter distributions, loss correlation); bpf as cls_bpf match-drop classifiers; frequency_drop, quota and window_drop as the eBPF stateful classifier — every filter type has a kernel equivalent |
| Capture / markers | relay bridge | uBridge AF_PACKET modules on the veth host end |
The work landed in nine stages on branch stack `feat/docker-kernel-datapath` → `feat/docker-kernel-capture` → `feat/docker-kernel-markers` → `feat/docker-veth-everywhere` → `feat/docker-kernel-filters` → `feat/docker-kernel-bpf-drop` → `feat/docker-kernel-netem-ext` → `feat/docker-kernel-ebpf-drops` → `feat/docker-kernel-window-drop`:
1. **Kernel datapath** — NIOBridge NIO type, per-link bridges, carrier-based suspend, crash-safe reconciliation.
2. **Capture** — `capture start_kernel` (AF_PACKET) on the veth host end.
3. **Markers** — `marker add_kernel` (AF_PACKET + BPF) with the same signals, pcaps and fine-grained REST operations as the relay `mark` filter.
4. **veth-everywhere** — the TAP path deleted; every adapter is a veth and the datapath is a *runtime* decision (kernel or relay) that never touches a running container's interfaces.
5. **Filters** — impairment filters (delay, packet_loss, corrupt) become one tc netem qdisc per veth host end, pushed through uBridge's netlink `tc` module. This also removes the relay delay filter's nanosleep bottleneck (upstream #2827) from the kernel path.
6. **bpf match-drop** — the `bpf` filter (any line matching drops) runs as cls_bpf classifiers on the veth host end's clsact egress (`tc bpf_drop`: uBridge pcap-compiles the line to classic BPF, the kernel migrates it to eBPF internally — no CAP_BPF needed). Requires a uBridge reporting `cbpf=1` via `tc capabilities`; older builds get a clear upgrade error.
7. **netem extensions** — the netem-extension surface delivered in uBridge `feature/tc-netem-ext` is exposed as GNS3 filter types: `rate`, `reorder`, `gemodel`, `duplicate`, `seed`, `limit`, plus the delay `distribution` and loss/dup `correlation` parameters. Kernel-datapath links only (the relay has no equivalent); capability-gated per uBridge process. Reconcile became reset-before-set: the kernel's netem replace merges optional attributes, so removing a parameter needs the explicit reset.
8. **eBPF stateful drops** — `frequency_drop` becomes the eBPF classifier's exact every-Nth mode (`tc nth_drop`, uBridge `feature/tc-precision`; -1 = drop everything → every 1st) and the new kernel-only `quota` type the byte-cap mode (`tc quota_drop`). Needs a uBridge reporting `ebpf=1` (setcap cap_bpf,cap_net_admin,cap_net_raw=ep — verified working for a non-root server process, the production credential shape). With this, no filter type forces the relay anymore: kernel/relay is a purely topological choice.
9. **window_drop flaps** — the eBPF classifier's time-window mode (`tc window_drop`, uBridge `feature/tc-window`): a single outage that passes traffic before and after, a recurring flap with `period ≥ outage`, and an optional per-cycle jitter that randomizes each beat's outage and period. The originally delivered back-to-back window implementation (which made "outside the window packets pass" unreachable) was fixed uBridge-side; this stage exposes the corrected semantics as the kernel-only `window_drop` filter type.
## Adapter interface types
Which interface a Docker node's adapters use is decided by the node class (`Docker._select_node_class`, from `console_type` + `GNS3_*` environment markers):
| Node class | Selected by | Adapter interface | Kernel links |
|---|---|---|---|
| `DockerVM` | default | veth pair | yes |
| `VendorDockerVM` (non-unix-socket) | `console_type=docker_exec` (XRd, SR Linux, …) | veth pair (same path via `super()`) | yes |
| `IOLDockerVM` | `GNS3_IOL_RUNNER=1` | AF_UNIX datagram socket pairs (`sNN`/`cNN`) — the container netns is unused; kernel links ride persistent `gx` TAP anchors through the port bridge's swappable TAP leg (see `iol-docker-kernel-datapath.md`) | yes (gated on `ubridge_bridge_tap` + `ubridge_tap`) |
| `VendorDockerVM` (unix-socket) | `GNS3_UNIX_SOCKET_NIO=1` | same socket contract, generic capability for vendor NOS images | rejected |
The other `GNS3_*` markers a vendor image sets (`GNS3_SKIP_INIT`, `GNS3_INTERFACE_NAMES`, …) are behavior knobs of the selected class, not class selectors — an environment carrying only `GNS3_SKIP_INIT` stays on `DockerVM`. Unix-socket containers are detected both in the controller (`_is_unix_socket_docker`, link eligibility) and on the compute side (NIO rejection) — a missed detection surfaces as a clearer-late error, except on the Ethernet-switch fast path, where an absent anchor is deferred forever by design (the join must not fail while the peer is stopped), leaving a silently dead cable.
## Architecture
Kernel link between two containers on the same compute. Interface names follow two deterministic rules — `gv|gc{node_id[:8]}e{adapter}p{port}` for the veth pair (`gv` = GNS3 veth host end, `gc` = its guest end, moved into the container and renamed `eth{N}`) and `gns3{link_id[:11]}` for the bridge; the concrete names in the diagrams use node ids `3f2a1b9c` / `7c9d4e2f` and link id prefix `5d3c2b1a4e6`. Terms the diagrams use:
| Term | Meaning |
|---|---|
| uBridge | the per-node helper process gns3-server spawns with elevated capabilities; its hypervisor command surface executes all host-side wiring (veths, bridges, carrier, tc, taps) — on a kernel link it builds and observes the path but never carries frames |
| anchor | the host-side interface a link attaches to — for Docker, the `gv` veth host end |
| per-link bridge | the Linux bridge `gns3{link_id[:11]}` that stands in for the cable; the two anchors are its only ports |
| veth pair | a kernel virtual Ethernet pair — two interfaces created together and wired so a frame into one end comes out the other; here one end is the container's `eth0`, the other the `gv` host end |
| bridge port | an interface enslaved to a Linux bridge (`brctl addif`) — it no longer sends or receives on its own: frames arriving on it go to the bridge's forwarding logic, and the bridge transmits through it |
| veth crossing | a frame passing through the veth pair between a container netns and the root namespace — pure kernel, no userspace |
| FDB | the bridge's forwarding database (learned MAC → port); unknown, broadcast and multicast destinations are flooded |
| `01:80:c2` / `group_fwd_mask` | the IEEE 802.1D reserved multicast range (STP, LACP, LLDP, 802.1X, PAUSE); the bridge forwards it only per the port's `group_fwd_mask` — `0xfffd` passes everything except PAUSE/PFC |
| tc / qdisc | traffic-control objects the kernel inserts into the host end's egress path — stages frames pass through in flight, not external packet consumers; uBridge only installs them over netlink |
| `clsact` | the tc classifier carrier on the host end; its egress chain is where the drop classifiers run |
| eBPF classifier | the stateful drop classifier at clsact egress prio 1 — modes every-Nth, quota, time window and flow (GNS3 exposes the first three as filter types) |
| `bpf_drop` | match-drop BPF expressions at clsact egress prio 10–99 |
| `netem` | the impairment qdisc behind clsact: delay, loss, rate, corrupt, duplicate, … |
| `AF_PACKET tap` | uBridge's packet socket bound to the host end; the kernel clones every frame the interface sends or receives to it (the tcpdump mechanism) — read-only copies, the original stays on the kernel path |
| carrier | the host end's admin state (`link set up/down`); suspend is carrier down on both ends = 100 % loss |
| `nio_bridge` | the NIO record the controller posts to each endpoint node: bridge name, filters, markers, suspend flag |
```mermaid
flowchart LR
subgraph NetA["container A netns"]
ethA["eth0"]
end
subgraph RootNS["root namespace"]
gvA["gv3f2a1b9ce0p0 — anchor"]
BR["gns35d3c2b1a4e6 — per-link bridge"]
gvB["gv7c9d4e2fe0p0 — anchor"]
UB1["uBridge A"]
UB2["uBridge B"]
end
subgraph NetB["container B netns"]
ethB["eth0"]
end
ethA <-->|"veth pair"| gvA
gvA <-->|"bridge port"| BR
BR <-->|"bridge port"| gvB
gvB <-->|"veth pair"| ethB
gvA -. "frame copies" .-> UB1
UB1 -. "qdisc install" .-> gvA
gvB -. "frame copies" .-> UB2
UB2 -. "qdisc install" .-> gvB
```
Everything in the root namespace is built the same way: gns3-server creates the veth pairs at container start, the bridge and its memberships at link creation, and every later change (carrier, capture, markers, filters) by sending hypervisor commands to its per-node uBridge process — the privileged agent that turns them into netlink/ioctl operations (the production credential shape is a non-root server with a capabilities-equipped ubridge). That build flow is the Link creation sequence below; this diagram is the steady state that remains, where the only uBridge relationships left are the two dashed kinds.
uBridge sits off the forwarding path — the dashed edges are control and observation, never data flow. The `qdisc install` edge is uBridge configuring the kernel over netlink; the kernel then runs those qdiscs in-flight on the host end's egress (they are stages of the transmit path, not packet consumers). The `frame copies` edge is the AF_PACKET tap: bound to the host end, the kernel clones every frame the interface sends or receives to uBridge's packet socket (the tcpdump mechanism) — read-only copies; the originals never leave the kernel.
Relay link on the same unified veth and the same single compute as above — what the link becomes when `enable_kernel_datapath` is off (cross-compute wiring and an endpoint that cannot anchor — a cloud node, … — fall back too; across computes the UDP hop rides the real network instead of loopback, the copy count unchanged):
```mermaid
flowchart LR
subgraph KA["container A netns"]
EA["eth0"]
end
subgraph KERN["kernel — root ns"]
GVA["gv host end"]
UDP["UDP sockets (loopback)"]
GVB["gv host end"]
end
subgraph UBA["uBridge A — userspace"]
NEA["AF_PACKET nio"]
ENA["relay + userspace filters"]
NUA["UDP nio"]
end
subgraph UBB["uBridge B — userspace"]
NUB["UDP nio"]
ENB["relay + userspace filters"]
NEB["AF_PACKET nio"]
end
subgraph KB["container B netns"]
EB["eth0"]
end
EA -->|"veth pair"| GVA
GVA -->|"copy 1: kernel→user"| NEA
NEA --> ENA --> NUA
NUA -->|"copy 2: user→kernel"| UDP
UDP -->|"copy 3: kernel→user"| NUB
NUB --> ENB --> NEB
NEB -->|"copy 4: user→kernel"| GVB
GVB -->|"veth pair"| EB
```
Drawn one-way; the reverse direction is the mirror image. A relayed frame crosses the kernel/user boundary **four times each way** (eight per round trip — the measured ≈0.3 ms RTT against ≈0.05 ms on the kernel datapath, whose crossings are zero), and the relay's filters run in userspace on the frames between the copies.
Both datapaths anchor on the *same* veth host end; switching between them (link delete + recreate) never touches the container-side interface.
Frame path for one A → B frame. The impairment chain fires on the egress of the *destination* end's veth, in order clsact → netem (a classifier drop means netem never sees the frame); each direction is impaired exactly once and B → A is symmetric on gvA — hence `delay 100` ≈200 ms RTT, `packet_loss 30` ≈51 % round trip:
```mermaid
flowchart LR
subgraph ANS["container A netns"]
S1["eth0 A sends"]
end
subgraph ROOT["root namespace"]
subgraph GVA["gvA — ingress (its egress chain serves B→A)"]
S3["ingress"]
end
subgraph BRP["per-link bridge"]
G1{"reserved 01:80:c2?"}
D["dropped"]
S4["FDB lookup / flood"]
end
subgraph GVB["gvB — egress chain (clsact, then netem)"]
S5["eBPF prio 1"]
S6["bpf_drop prio 10-99"]
S7["netem qdisc"]
end
T["capture / markers"]
end
subgraph BNS["container B netns"]
S9["eth0 B receives"]
end
S1 -->|"veth pair"| S3
S3 --> G1
G1 -->|"PAUSE 0x01"| D
G1 -->|"0xfffd passes"| S4
S4 --> S5
S5 --> S6 --> S7
S7 -->|"veth pair"| S9
S3 -. "AF_PACKET tap" .-> T
S7 -. "AF_PACKET tap" .-> T
```
What each stage drops: the reserved-range gate passes LACP, LLDP, 802.1X and STP per the port mask but never PAUSE/PFC (Link-local frames below); the clsact/netem stages drop or impair per the installed filters (Packet filters below). Whichever end hosts capture / markers, its AF_PACKET tap — the dashed sideband above — clones the frame at that anchor: a tap on gvA sees the frame on arrival, a tap on gvB only if the clsact chain let it through.
All dozen-plus GNS3 filter types ride these three kernel objects — nine of them (delay, packet_loss, corrupt, duplicate, rate, reorder, gemodel, seed, limit) are parameters of the single netem qdisc, `bpf` expressions are the cls_bpf filters, and frequency_drop / quota / window_drop map to three of the one eBPF program's four modes (evaluated nth → quota → window → flow; the flow-hash mode has no GNS3 filter type). The complete type-to-object mapping and the per-frame evaluation order are documented in `packet-filters.md`.
## Datapath selection
`UDPLink._kernel_datapath_eligible` decides in the controller at NIO prepare time; the compute side only reacts to the NIO type:
* both endpoints on the same compute, both able to anchor — Docker anchors via its veth (any class except unix-socket containers), and QEMU / IOU / Dynamips / Ethernet-switch peers anchor via their own mechanisms, so mixed links take the kernel path too
* cross-compute pairs take the kernel path as a **VXLAN tunnel** when `Server.enable_vxlan_cross_compute` is enabled and both computes can create the device — see [vxlan-cross-compute](vxlan-cross-compute.md); the default there is the relay, because the tunnel caps the usable MTU at the underlay minus 50 bytes
* `Server.enable_kernel_datapath` enabled (default)
Filters never disqualify the kernel path anymore — every type has a kernel equivalent (netem / cls_bpf / eBPF classifier).
There is **no stopped-node requirement**. Since every adapter is a veth, links attach to running containers: `brctl addif` (kernel) or `bridge add_nio_ethernet` (relay) are runtime-safe operations on the host end. On project (re)open every link re-runs `_prepare`, so relay links whose endpoints became eligible are upgraded to the kernel datapath automatically.
Which datapath a link ended up on is visible in its REST payload (and the `link_list` / `link_get` MCP tools) as the read-only boolean `kernel_datapath`, recomputed from the NIO wiring — a relay link upgraded on reopen flips the field. It is not persisted and never sent on create/update.
## Link creation sequence
Both Docker nodes sit on the same compute (a kernel-link precondition) and each drives its own uBridge process. They attach concurrently and compute the same bridge name independently (a pure function of the link id), so either may win the `brctl create` race — the loser verifies the bridge exists (`brctl show`) and continues:
```mermaid
sequenceDiagram
participant API as REST API
participant C as Controller
participant CA as Docker node A
participant CB as Docker node B
participant UA as uBridge A
participant UB as uBridge B
API->>C: POST /links
C->>C: eligibility check
C->>C: bridge = gns3 + link_id[:11]
C--)CA: nio_bridge
C--)CB: nio_bridge (same bridge)
par Docker node A
CA->>UA: brctl create
CA->>UA: link set bridge up
CA->>UA: brctl addif gvA
CA->>UA: capture / markers if any
CA->>UA: tc netem + bpf + eBPF
CA->>UA: link set gvA up
and Docker node B
CB->>UB: same on gvB
end
Note over UA,UB: steady state — kernel forwards, uBridge taps
```
Every arrow to uBridge is one `_ubridge_send` command line on the node's local hypervisor console; uBridge executes it (netlink/ioctl) and replies OK or an error synchronously before the next command is sent — those replies are omitted for brevity. uBridge never initiates anything: it is a pure executor, and the only data ever flowing back (capture/marker frame copies) rides separate AF_PACKET sockets, not this console.
The veth pairs already exist at attach time — every adapter is born as a veth at container start (Adapter lifecycle below), which is what makes the attach a runtime-safe operation on a running container.
## Adapter lifecycle
* **Birth (container start)** — `_create_veth`: stale sweep of any leftover pair (crash residue), `docker create_veth`, host end admin-down, MAC from the adapter base, `docker move_to_ns` of the guest end (renamed `eth{N}`, or the `GNS3_INTERFACE_NAMES` mapping). Names are deterministic: `gv|gc{node_id[:8]}e{adapter}p{port}` (≤ 15 chars). Unconnected adapters are born too (carrier off) so the interface is visible inside the container.
* **Life (running)** — the veth is never created/deleted/moved again. Link create/delete/switch, suspend, capture and markers only change *what is attached to the host end*.
* **Death (container stop)** — `_remove_kernel_veths` deletes the host ends explicitly: unlike a TAP (which died with the container netns), a veth host end outlives the container. Deleting either end destroys the pair. The node's per-link kernel bridges go with them — deleting a node or closing a project never runs the link-teardown path (no per-link delete is issued), so a bridge whose ports just disappeared would stay behind as an empty orphan. Both endpoints do this and the peer's still-enslaved port makes the delete fail with EBUSY (suppressed, last one wins), the same contract as link deletion; a node restart rebuilds the bridge from the NIO.
* **Host L3 noise (known, hardening specified).** An anchor is a host-side netdev like any other, so the kernel gives it an IPv6 link-local address and emits its own MLD/DAD from it (measured ≈6 frames / 2 s on an idle TAP; the production anchors and per-link bridges carry `fe80::…` today). On a kernel link the bridge floods those frames into the emulated segment — and the host answers neighbor solicitations for its own address, which looks like a phantom IPv6 neighbor to the emulated nodes. The fix is to make anchors pure L2 at creation time on the uBridge side: `docs/design/ubridge-l2-anchor-spec.md`.
## Link operations
| Operation | Kernel-datapath action |
|---|---|
| Create / attach | `brctl create` (EEXIST tolerated via `brctl show` verify) + `link set up` + `brctl addif` both ends (concurrent, race-tolerant) + capture / markers if any + the tc chain (netem, bpf, eBPF) + carrier up |
| Delete / detach | marker teardown → `tc reset` (netem teardown — the veth survives the link) → carrier off → `brctl delif` → `brctl delete` (last endpoint wins; EBUSY/ENOENT suppressed). The veth survives — unlike a relay bridge, whose death dropped its filters, an orphaned AF_PACKET marker would keep sniffing, hence the explicit teardown |
| Reset (`POST /links/{id}/reset`) | delete + create (re-evaluates eligibility) |
| Suspend (`PUT /links/{id}` `{"suspend": true}`) | veth host end admin-state down both ends — 100 % loss, no synthetic filter needed; resume restores (netem qdisc survives the carrier flap) |
## Capture
Kernel links capture via uBridge's AF_PACKET module bound to the veth host end: `capture start_kernel <if> "<pcap>" [dlt]` / `capture stop_kernel <if>`. One capture per interface, any number of interfaces concurrently — a node can capture several ports at once; a same-interface duplicate answers EALREADY, which the server's per-port `capturing` flag already refuses before uBridge sees it. Stops are per interface too: each port's stop names its own anchor, never touching a sibling port's capture. Start/stop key on the **NIO type**, not on veth presence — a relay NIO riding a veth captures at its relay bridge.
## Markers
Markers ride the NIO like on the relay datapath, routed by `capture_node_id`; the anchor is the veth host end instead of a relay bridge (`_ubridge_apply_markers(anchor, nio)` is datapath-agnostic; DockerVM overrides the add/delete/enable primitives to translate the commands):
```
marker add_kernel <name> <if> "<bpf>" [tag <id>] [link <id>] [dir <tx|rx>] [linktype <name>] [pcap "<path>"]
marker delete_kernel <if> <name> # idempotent
marker enable_kernel <if> <name> <on|off> # off = installed but silent
```
* Per-deployment convention: **only the capture node's end** runs `add_kernel` (symmetric with capture) — signals form clean send/return pairs (`PACKET_OUTGOING` on the host end = container receiving = `rx`).
* Same BPF compilation, MARK UDP signals, pcap files and fine-grained REST toggle/rebuild/delete endpoints as the relay `mark` filter.
* Node restart reinstalls markers from the NIO; link deletion tears them down.
## Packet filters
Impairment filters are documented once for every kernel-datapath node type in `packet-filters.md` — the 13 filter types ride three kernel objects on the anchor (one netem qdisc, cls_bpf match-drop classifiers, the eBPF stateful classifier; the frame-path diagram above shows where the chain sits), and the type-to-object mapping, per-frame evaluation order, reconcile behaviour, capability gating and window semantics all live there. `KernelDatapathMixin` keys everything on the anchor interface name, which is why this veth datapath and the TAP datapaths (QEMU, IOU, Dynamips) share the implementation unchanged.
## Link-local frames (LACP, LLDP, 802.1X, STP)
The bridge stands in for a cable, but the kernel's `br_handle_frame()` does not forward the IEEE 802.1D reserved range (`01:80:c2:00:00:00`-`0f`) by default — LACP, LLDP/DCBX and 802.1X would never cross a kernel link while the UDP relay carries them fine. uBridge therefore opens every port's per-port `group_fwd_mask` (`IFLA_BRPORT_GROUP_FWD_MASK`) to `0xfffd` at `brctl addif` time (Linux 4.15+, best-effort on older kernels). The bridge-level knob cannot do this: `BR_GROUPFWD_RESTRICTED` rejects bits 0-2, so LACP is reachable per port only.
Result on kernel links: ordinary multicast, STP/RSTP, LACP, 802.1X and LLDP/DCBX all cross; **802.3x PAUSE / PFC does not** — `case 0x01` in `br_handle_frame()` drops it unconditionally and no mask can enable it. That is a documented limit, not a regression (PFC's hardware semantics are out of emulation's reach anyway); a lab that needs PAUSE frames on the wire must use a relay link. Verified live by `tests/e2e/test_docker_link_local_frames.py` (per-MAC guest-to-guest matrix); the contract and kernel references live in `docs/design/ubridge-link-local-frame-forwarding-spec.md`.
## uBridge command surface
No uBridge changes were needed beyond the marker module's `*_kernel` commands (the AF_PACKET capture module was pre-existing):
```
docker create_veth / delete_veth / move_to_ns / set_mac_addr
brctl create / delete / addif / delif / show
link set <if> up|down
capture start_kernel / stop_kernel
marker add_kernel / delete_kernel / enable_kernel
tc netem set <if> [delay <ms>] [jitter <ms>] [loss <%> [correl <%>] | loss gemodel <p> <r> <1-h>]
[dup <%> [correl <%>]] [corrupt <%>] [reorder <%> [correl <%>] [gap <n>]]
[rate <bw>] [limit <pkts>] [distribution uniform|normal|pareto|paretonormal] [seed <u32>]
tc bpf_drop add <if> <prio 10-99> "<expr>" / tc bpf_drop flush <if>
tc nth_drop <if> <n | off> # eBPF exact every-Nth (frequency_drop)
tc quota_drop <if> <bytes> <pct> | off # eBPF byte cap (quota)
tc window_drop <if> <start_ms> <outage_ms> <pct> [<period_ms> [<jitter_ms>]] | off # eBPF time window (window_drop)
tc reset <if> # full restore: eBPF filter -> bpf_drops -> clsact -> root qdisc, idempotent
tc capabilities # "netem=<kw,...>;ebpf=0|1;cbpf=0|1[;ebpf_modes=<modes>]", probed once per process
bridge add_nio_ethernet / add_nio_udp / start / stop / start_capture / stop_capture
```
## Configuration
```ini
[Server]
# Wire eligible links through kernel interfaces instead of the uBridge UDP relay
enable_kernel_datapath = True
```
This is now the global datapath switch — `_kernel_datapath_eligible` consults it first, and every node type that can anchor a kernel link has landed:
* **Docker** — veth host ends as anchors (this document)
* **QEMU** — persistent TAP anchors, see `docs/features/qemu-kernel-datapath.md`
* **IOU** — TAP-terminated fabric ports (`iol_bridge add_nio_tap`), see `docs/features/iou-kernel-datapath.md`
* **Dynamips** — uBridge-created TAPs the hypervisor opens, see `docs/features/dynamips-kernel-datapath.md`
* **IOL runner containers** — persistent `gx` TAPs through the bridge module's swappable TAP leg, see `docs/features/iol-docker-kernel-datapath.md`
* **Ethernet Switch** — its own uBridge `brctl` bridge that absorbs the peer's anchor as a fast path (switch-to-switch cascades over a veth pair), see `docs/features/ethernet-switch-kernel-datapath.md`
A link rides the kernel when both endpoints sit on one compute, both can anchor (per-type uBridge capabilities), the switch is on and the ports are Ethernet; everything else falls back to the relay. The shared compute machinery behind all of these lives in `gns3server/compute/kernel_datapath.py`.
## Verification
End-to-end on a five-container FRR topology (mixed runtime-drawn and reloaded links): 8/8 links on the kernel datapath, ping RTT ≈ 0.05 ms, FDB learning, suspend = 100 % loss / resume restores, project reopen upgrades relay links, runtime link creation on running containers, marker pcaps exact (tx/rx pairs), capture freeze on stop, server restart reconciliation.
Filters (two-container kernel link, 27/27 checks): baseline 0.06 ms → `delay 100` = 200.2 ms RTT (2× per direction) → `delay 50` = 100.2 ms (atomic replace) → clear = baseline (qdisc detached); `packet_loss 30` = 48 % round-trip loss (expected 51 % = 1 − 0.7²); `frequency_drop` = 409 (at that stage — superseded by the eBPF stage below); suspend with delay active = 100 % loss, resume keeps the qdisc (200.1 ms); node restart restores it (200.1 ms); link delete detaches it (`/usr/sbin/tc qdisc show` — no netem left); re-created link has no residual impairment.
bpf match-drop (same setup, 22/22 checks): `bpf "icmp"` = 100 % loss on both ends' clsact; size-discriminating expression (`greater 150`) = small pings pass / 300-byte pings dropped (real byte-level BPF match); two-line OR; coexistence with netem (delay 50 → small pings 100.2 ms while big dropped); clear removes clsact entirely; suspend/resume keeps the drops; link delete + recreate leaves no residual filters; `frequency_drop` still 409 and hidden (at that stage — superseded by the eBPF stage below); `available_filters` shows `bpf`. Unit tests: `tests/compute/docker/test_docker_kernel_datapath.py`, `tests/controller/test_kernel_datapath_link.py`.
netem extensions (same setup, 24/24 checks): `rate 512kbit` on both veths, 1400-byte pings measure 45.5 ms RTT = baseline + 2× the 22.2 ms serialization (exact); `delay 100 20 paretonormal` applies delay+jitter and clears the previous rate (leak detector for the kernel's merge-on-replace); `reorder 25 gap 5` visible in the qdisc dump and traffic passes; `gemodel 100/0/30` = 50 % bursty round-trip loss with the previous reorder cleared; `duplicate 50` link alive; `packet_loss 30 correl 50` shows `loss 30% 50%`; `seed 42` + `limit 5000` both visible in the dump, RTT exactly 2×50 ms; suspend/resume and node restart keep the filters; a docker↔ethernet-switch relay link rejects `rate` with 409 and its `available_filters` hides the kernel-only types while the kernel link shows them all (frequency_drop included since the eBPF stage); `reorder` without `delay` and `gemodel`+`packet_loss` are 409s; teardown leaves no netem on either veth. Also verified live: a relay attach (`bridge add_nio_ethernet`) on the admin-down veth host end fails in libpcap — the relay path now brings the interface up before attaching.
eBPF stateful drops (same setup, 13/13 checks): `frequency_drop 3` installs the tc_impair classifier on both veths (clsact egress pref 1, visible in `tc filter show`); round-trip loss 57 % against the per-direction theory 1 − (2/3)² = 55.6 % (each direction drops every 3rd independently — the relay's single shared counter would give ≈ 1/3); `frequency_drop -1` = exactly 100 % loss; `quota 3000B/100 %` = pings pass until the byte cap then hard cutoff; coexistence with `delay 50` (RTT 100.3 ms with every-4th drops); clearing filters leaves no residual bpf filter; suspend = 100 % while down with drops persisting after resume; node restart restores every-Nth on the fresh veth; `available_filters` shows frequency_drop + quota on kernel links and hides quota on relay links; a two-leg relay path through an Ethernet switch still serves frequency_drop from the userspace filter (56 % round-trip for N=3). The e2e also exposed and fixed a pre-existing restart bug: the relay bridge-name registry was not cleared on stop, so a node restart with a relay link skipped `bridge create` and failed. Unit tests: `tests/utils/test_packet_filter_validation.py` (P6a class), `tests/compute/docker/test_docker_kernel_datapath.py`, `tests/controller/test_kernel_datapath_link.py`.
window_drop (same setup, 15/15 checks, against uBridge `feature/tc-window`): a single outage `[1000, 1500, 100]` delivers **per-seq evidence** of the B.2 semantics — one ping per 200 ms arrives as `[0,1,2,3,4, 13…19]`: passing before the window, dropped inside it, passing again after; a recurring flap `[300, 1000, 100, 2000]` measures 52 % round-trip loss (the 1000/2000 duty cycle); `period == outage` is a permanent outage (100 %); `period < outage` is a 409 before uBridge sees it; a jittered flap `[0, 1000, 100, 2000, 400]` keeps the ~50 % duty cycle (62 % sampled over 4 cycles — the per-cycle re-draw widens the variance by design); a 30 % chance on a permanent window measures 53 % round trip against the per-direction theory 1 − 0.7² = 51 % (the same arithmetic as `packet_loss 30`); `start = 0` is stored as an *active* filter; the window coexists with netem (`delay 50` + a permanent window = 100 % inside the outage); clearing removes the classifier; a node restart restores the schedule on the fresh veth; `available_filters` shows window_drop on kernel links and a relay link both hides it and 409s it; teardown leaves no filter or qdisc behind. The P6b e2e was re-run as a regression on the same uBridge build (13/13 — nth/quota unaffected by the de-looping below).
In-repo live coverage: `tests/e2e/test_docker_kernel_datapath.py` (pytest marker `e2e`) runs two real Alpine containers on an isolated instance — the per-link bridge enslaving exactly the two veth host ends, real ICMP, the L2-anchor spec §E assertions (no L3 identity, forwarding ports, idle silence with the guests' links down), the filter matrix one type at a time (netem core and extensions, cls_bpf match-drop, the eBPF classifier, each asserted through real traffic), suspend, capture, link delete/re-create, container stop/start, a relay negative control — whose own filters (delay/frequency_drop/bpf) really shape the relay wire, whose capture and markers ride the same relay engine (`bridge start_capture`, the bridge `mark` filter) — and the relay→kernel upgrade on project reopen (the datapath choice is flipped across a server restart). The container image is digest-pinned and pulled through the server's own pull route on a cache miss, so collaborators test the same bytes.
The uBridge-side window work took two fixes that are worth recording, both found by *this* integration rather than by unit tests: the delivered catch-up loop tripped the verifier's 8192 **jump-sequence** budget — on the non-root path the verifier drops the loop counter's bound (`R4=scalar(smax=umax32=0xfffff086)`), treats the loop as unbounded and unrolls it until the pending-state limit, so the program was rejected wholesale (`E2BIG`, `The sequence of 8193 jumps is too complex`) and `tc capabilities` reported `ebpf=0` — taking `frequency_drop` and `quota` down with it, since the classifier loads as one program; lowering the trip cap did not help (128 trips failed identically), removing the loop did (572ca0c: 16-step unroll + outer guard, zero back edges). A latent Makefile header-dependency gap (53e34bb) had been shipping the *old* truncated program object — the kernel answered `jump out of range from insn 9 to 421` with `processed 0 insns`. Both matter to anyone rebuilding uBridge: `ebpf=1` from a direct probe is the only trustworthy signal.
+241
View File
@@ -0,0 +1,241 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
# Dynamips kernel datapath
Dynamips routers emulate every port inside the Dynamips process; on the relay datapath a link reaches a router through a UDP tunnel (a Dynamips `nio create_udp`, a loopback port pair, the node's uBridge relay, and the link's UDP NIOs). The kernel datapath replaces that segment with the same anchor model Docker, QEMU and IOU use: every **Ethernet slot/port** owns a persistent TAP (`gd{node_id[:8]}e{slot}p{port}`), created by the server through uBridge's tap module, and links attach to the anchor — a per-link Linux bridge enslaves it, tc impairments run on it, capture and markers anchor on it. The Dynamips **hypervisor** opens the TAP with `nio create_tap` (QEMU's move: an external process holds the fd), unprivileged because the server handed the device's ownership to its own user.
## Architecture
The diagram shows the e2e shape — two c7200 routers on one link (slot 1 port 0 each, a PA-2FE-TX — slot 0 is the c7200's fixed I/O slot), the topology `tests/e2e/test_dynamips_kernel_datapath.py` drives. A Dynamips↔Docker/QEMU/IOU link is the same shape with the peer's own anchor on the other side; a routed transit is two such links with IOS forwarding between them. Interface names follow the deterministic rules `gd{node_id[:8]}e{slot}p{port}` for the anchor TAPs and `gns3{link_id[:11]}` for the bridge; the concrete names in the diagrams use node ids `7c1d4e2f` / `9e8b6a3f` and link id prefix `5d3c2b1a4e6` (`gdA`/`gdB` shorthand in the sequence below). Terms the diagrams use:
| Term | Meaning |
|---|---|
| hypervisor | the Dynamips process emulating the router; it holds every anchor TAP's fd |
| anchor | the host-side interface a link attaches to — for Dynamips the `gd` persistent TAP, for Docker the `gv` veth host end |
| persistent TAP | the TAP created per Ethernet slot/port at node start (`tap create` + `tap set_owner`, ownership handed to the server user so the unprivileged hypervisor can open it); born DOWN, it outlives `vm stop` and hypervisor crashes |
| per-link bridge | the Linux bridge `gns3{link_id[:11]}` that stands in for the cable; the two anchors are its only ports |
| tap fd | a TAP's file descriptor: writes inject frames into the kernel as if the device received them, reads return frames the kernel transmits through the device (bridge-forwarded, toward the router) — the hypervisor opens it with `nio create_tap` and holds it for the port's lifetime |
| FDB | the bridge's forwarding database (learned MAC → port); unknown, broadcast and multicast destinations are flooded |
| `01:80:c2` / `group_fwd_mask` | the IEEE 802.1D reserved multicast range (STP, LACP, LLDP, 802.1X, PAUSE); the bridge forwards it only per the port's `group_fwd_mask` — `0xfffd` passes everything except PAUSE/PFC |
| `clsact` | the tc classifier carrier on the anchor; its egress chain is where the drop classifiers run |
| eBPF classifier | the stateful drop modes (every-Nth, quota, time window) at clsact egress prio 1 |
| `bpf_drop` | match-drop BPF expressions at clsact egress prio 10–99 |
| netem | the impairment qdisc behind clsact: delay, loss, rate, corrupt, duplicate, … |
| `AF_PACKET tap` | uBridge's packet socket on the anchor — how capture and markers observe frames off the forwarding path |
| carrier | the anchor's admin state (`link set up/down`); suspend is carrier down — traffic dead both ways |
| `nio_bridge` | the NIO record the controller posts to each endpoint node: bridge name, filters, markers, suspend flag |
| uBridge | the per-node helper process — on a kernel link it created the anchor, enslaves it and taps it, but never carries frames |
```mermaid
flowchart LR
subgraph H1["Dynamips hypervisor R1"]
ios1["IOS router 1"]
end
subgraph RootNS["root namespace"]
gdA["gd7c1d4e2fe1p0"]
BR["gns35d3c2b1a4e6"]
gdB["gd9e8b6a3fe1p0"]
ub1["uBridge R1"]
ub2["uBridge R2"]
end
subgraph H2["Dynamips hypervisor R2"]
ios2["IOS router 2"]
end
ios1 <-->|"TAP fd"| gdA
gdA <-->|"bridge port"| BR
BR <-->|"bridge port"| gdB
gdB <-->|"TAP fd"| ios2
gdA -.->|"AF_PACKET tap"| ub1
ub1 -.->|"tc qdisc"| gdA
gdB -.->|"AF_PACKET tap"| ub2
ub2 -.->|"tc qdisc"| gdB
```
The only userspace crossings left are the Dynamips processes themselves — the routers *are* the emulation, and the hypervisor reads and writes the TAP directly (QEMU's external-fd-holder shape, no extra relay hop on the node leg unlike IOU's fabric). What the kernel datapath buys is the link segment: anchor → per-link bridge → peer anchor crosses entirely in the kernel, impairments run as kernel tc instead of userspace filters, and suspend maps to anchor admin-down. Each side's uBridge does its own tap-and-qdisc work on its node's anchor — but neither dashed edge is a steady fixture: the qdisc exists only while the link carries filters (deletion `tc reset`s it), the tap only while capture or markers run, and by convention only on the capture node's end, so an unfiltered, uncaptured link shows neither. The anchors themselves were created through uBridge at node start (Anchor lifecycle below).
The legacy relay is untouched: a port without a kernel link keeps its Dynamips UDP NIO and the node's uBridge relay tunnel exactly as before, and a kernel link binds the same port to its anchor instead — per port, no node-wide switch. The same R1 ↔ R2 link on the relay — one direction drawn, the reverse is the mirror image; this is the exact shape the negative control keeps when `enable_kernel_datapath = false` (Verified below). Each relay bridge is named `DYNAMIPS-{lport}-{rport}` after the loopback port pair its NIO allocates at link time:
```mermaid
flowchart LR
subgraph H1["Dynamips hypervisor R1"]
ios1["IOS router 1"]
nio1["UDP NIO"]
end
subgraph ub1["uBridge R1"]
rl1["relay bridge"]
end
subgraph KERN["kernel"]
lp1["loopback UDP"]
tun["UDP tunnel"]
lp2["loopback UDP"]
end
subgraph ub2["uBridge R2"]
rl2["relay bridge"]
end
subgraph H2["Dynamips hypervisor R2"]
nio2["UDP NIO"]
ios2["IOS router 2"]
end
ios1 --> nio1
nio1 -->|"copy 1: user→kernel"| lp1
lp1 -->|"copy 2: kernel→user"| rl1
rl1 -->|"copy 3: user→kernel"| tun
tun -->|"copy 4: kernel→user"| rl2
rl2 -->|"copy 5: user→kernel"| lp2
lp2 -->|"copy 6: kernel→user"| nio2
nio2 --> ios2
```
Six kernel/user crossings each way, against the kernel datapath's two — and those two are the TAP-fd legs that are the emulation itself, so the relay's four extra copies are pure overhead. Userspace filters run inside the relay bridges, between copies 2-3 and 4-5. On a same-compute link the UDP tunnel rides loopback as drawn; cross-compute it rides the real network with the copy count unchanged.
Frame path for one R1 → R2 frame. The impairment chain fires on the egress of the *destination* end's anchor, in order clsact → netem (a classifier drop means netem never sees the frame); each direction is impaired exactly once and R2 → R1 is symmetric on gdA:
```mermaid
flowchart LR
subgraph H1["Dynamips hypervisor R1"]
S1["IOS port sends"]
end
subgraph ROOT["root namespace"]
subgraph GA["gd7c1d4e2fe1p0 — ingress (egress chain serves R2→R1)"]
S3["ingress"]
end
subgraph BRP["per-link bridge"]
G1{"reserved 01:80:c2?"}
D["dropped"]
S4["FDB lookup / flood"]
end
subgraph GB["gd9e8b6a3fe1p0 — egress chain (clsact, then netem)"]
S5["eBPF prio 1"]
S6["bpf_drop prio 10-99"]
S7["netem qdisc"]
end
T["capture / markers"]
end
subgraph H2["Dynamips hypervisor R2"]
S9["IOS port receives"]
end
S1 -->|"tap fd, copy 1: user→kernel"| S3
S3 --> G1
G1 -->|"PAUSE 0x01"| D
G1 -->|"0xfffd passes"| S4
S4 --> S5
S5 --> S6 --> S7
S7 -->|"tap fd, copy 2: kernel→user"| S9
S3 -. "AF_PACKET tap" .-> T
S7 -. "AF_PACKET tap" .-> T
```
What each stage drops: the reserved-range gate passes LACP, LLDP, 802.1X and STP per the port mask but never PAUSE/PFC (Link-local frames below); the clsact/netem stages drop or impair per the installed filters (Capture, markers, filters below). The R2 → R1 reply is symmetric — its impairment points are `gd9e8b6a3fe1p0`'s egress (entering R2) and `gd7c1d4e2fe1p0`'s egress (entering R1) — so every direction is impaired exactly once, and `delay 100` adds one-way 100 ms per direction, ≈200 ms round trip (the e2e pins the lower bound: RTT ≥ 150 ms with 100% success). Copies 1-2 are the whole kernel/user bill — both are the TAP-fd legs of the emulation itself; the same frame on the relay datapath crosses six times (diagram above). The dashed sideband is uBridge's observation: capture and markers run as AF_PACKET taps on whichever end hosts them, cloning this frame at that anchor's stage — gdA's rx or gdB's tx — and a clsact-dropped frame never reaches the tap.
## Datapath selection
`UDPLink._kernel_datapath_eligible` extends the common rules with:
* the compute must report **`ubridge_tap`** — the anchors are uBridge-created TAPs the hypervisor merely opens, the same capability QEMU gates on; there is no Dynamips-specific one;
* **both ports must be Ethernet**. The controller's port matrix decides per port (the port's `link_type`); serial, ATM and POS ports keep the relay whatever the capabilities. Anchor creation on the compute side uses its own registry of Ethernet models — `ETHERNET_ADAPTERS` / `ETHERNET_WICS` in `compute/dynamips/adapters/adapter.py`, WIC-1ENET included at its Dynamips port number `16 * (wic_slot + 1)` — a name-keyed list kept in step with the controller's matrix by convention, not derivation.
## Link creation sequence
Both routers sit on the same compute (a kernel-link precondition) and each drives its own uBridge process; the hypervisor is one process per router. The sequence shows the running-router case — a router that is stopped stores the NIO and defers every step here to its next start (deferred wiring, below). The two node handlers attach concurrently and compute the same bridge name independently (a pure function of the link id), so either may win the `brctl create` race — the loser verifies the bridge exists (`brctl show`) and continues:
```mermaid
sequenceDiagram
participant API as REST API
participant C as Controller
participant R1 as Router R1
participant HY1 as Hypervisor R1
participant UB1 as uBridge R1
participant R2 as Router R2
participant HY2 as Hypervisor R2
participant UB2 as uBridge R2
API->>C: POST /links
C->>C: eligibility check
C->>C: bridge = gns3 + link_id[:11]
C--)R1: nio_bridge
C--)R2: nio_bridge (same bridge)
par Router R1
R1->>HY1: nio create_tap
R1->>HY1: vm slot_add_nio_binding
R1->>HY1: vm slot_enable_nio
R1->>UB1: brctl create
R1->>UB1: link set gns35d3c2b1a4e6 up
R1->>UB1: brctl addif gns35d3c2b1a4e6 gdA
R1->>UB1: capture start_kernel gdA
R1->>UB1: marker add_kernel <name> gdA
R1->>UB1: tc netem set gdA
R1->>UB1: link set gdA up
and Router R2
R2->>HY2: nio create_tap
R2->>UB2: same on gdB
end
Note over HY1,UB2: steady state — kernel forwards between the anchors, the hypervisors hold the tap fds
```
`nio create_tap`, `vm slot_add_nio_binding` and `vm slot_enable_nio` are the Dynamips-specific steps: the hypervisor opens the anchor and binds it to the slot/port before any bridge work, so a half-wired port never appears on the link. Capture, markers and `tc netem set` run only when the NIO carries them — a marker's real form is `marker add_kernel <name> <if> "<bpf>"`, `bpf` expressions arrive as `tc bpf_drop add`, the stateful modes as `tc nth/quota/window_drop` — and `brctl addif` is itself what opens the port's `group_fwd_mask` to `0xfffd` — the server sends no separate command for it (uBridge does have one, `brctl setportgroupfwd`, last-writer-wins against addif's default, which re-applies on every re-attach). The anchor's carrier stays down while the link is suspended. A link created while the router is **stopped** is stored and wired by the next start — the NIO simply waits in the slot adapter (deferred wiring, Anchor lifecycle below).
## Anchor lifecycle
* **Birth (node start)** — `_prepare_tap_datapath` probes the tap module (one create/delete cycle) and creates one persistent TAP per Ethernet slot/port, ownership handed to the server user, born DOWN. A stale leftover from a previous run is swept first; an anchor that already exists (restart) is kept — an anchor is never recreated under a live link. Serial/ATM/POS ports simply have no anchor.
* **Life** — a kernel link opens the anchor in the hypervisor (`nio create_tap`), binds it to the slot/port and enslaves it into the per-link bridge; removing the link unbinds the port, deletes the hypervisor's TAP NIO (releasing the fd) and tears the anchor out of the bridge. A link bound while the router is **stopped** is stored and wired by the next start (deferred wiring — the NIO simply waits in the slot adapter).
* **Death (node close)** — the fd holder releases before the devices are deleted, the order every node type uses: here the Dynamips hypervisor (not uBridge) holds the anchor fds, so its TAP NIOs go first (`nio delete` closes the fd), then `tap delete` per anchor, then the per-link kernel bridges, then uBridge itself.
**A stop is not a close.** `stop` only halts the emulated router: the hypervisor process — and with it the TAP fds, the port bindings and the per-link bridges — survives `vm stop` (the same reason a relay link's tunnel always survived a stop). Links therefore keep working through a stop/start with no re-wiring at all; the restart's attach pass skips every port that still has its TAP NIO. If the hypervisor died mid-flight (crash or kill), the persistent TAPs remain, but the node cannot simply be started again — `start()` speaks to the dead hypervisor and nothing respawns it; recovery is re-creating the node (a project reopen does it), where the stale anchors are swept and rebuilt and the controller re-posts the link NIOs.
## Link operations
| Operation | Kernel-datapath action |
|---|---|
| Create / attach | `nio create_tap` (hypervisor holds the fd) + `vm slot_add_nio_binding` + `brctl create` + `brctl addif` + carrier up + markers + `tc netem set` |
| Delete / detach | marker teardown → `tc reset` → carrier off → `brctl delif`/`brctl delete` → unbind + `nio delete` (release the fd) |
| Update (filters/markers/suspend changed) | reconcile on the anchor only — no re-binding, no re-enslaving |
| Suspend | anchor admin-down (traffic dead both ways) + resume restores |
| Adapter hot-add (OIR) | anchors for the new adapter's Ethernet ports created at once, so a kernel link can attach immediately |
## Capture, markers, filters
Capture on a kernel link is `capture start_kernel <anchor>`; markers ride the base reconcile with the anchor as the location (`marker add_kernel` — the shared KernelDatapathMixin machinery, no Dynamips-specific code); filters are one tc netem qdisc per anchor plus cls_bpf/eBPF drops. A relay port keeps its Dynamips NIO and the node's uBridge relay bridge (`DYNAMIPS-*`) with userspace filters, exactly as before.
## Link-local frames (LACP, LLDP, 802.1X, STP)
The bridge stands in for a cable, but the kernel's `br_handle_frame()` does not forward the IEEE 802.1D reserved range (`01:80:c2:00:00:00`-`0f`) by default — LACP, LLDP/DCBX and 802.1X would never cross a kernel link while the UDP relay carries them fine. uBridge therefore opens every port's per-port `group_fwd_mask` (`IFLA_BRPORT_GROUP_FWD_MASK`) to `0xfffd` at `brctl addif` time (Linux 4.15+, best-effort on older kernels). The bridge-level knob cannot do this: `BR_GROUPFWD_RESTRICTED` rejects bits 0-2, so LACP is reachable per port only.
Result on kernel links: ordinary multicast, STP/RSTP, LACP, 802.1X and LLDP/DCBX all cross; **802.3x PAUSE / PFC does not** — `case 0x01` in `br_handle_frame()` drops it unconditionally and no mask can enable it. That is a documented limit, not a regression (PFC's hardware semantics are out of emulation's reach anyway); a lab that needs PAUSE frames on the wire must use a relay link. Verified live by `tests/e2e/test_docker_link_local_frames.py` (per-MAC guest-to-guest matrix); the contract and kernel references live in `docs/design/ubridge-link-local-frame-forwarding-spec.md`.
## Relay fallback
A uBridge without the tap module keeps the node relay-only: `_prepare_tap_datapath` warns, no anchors are created, the warning says the node cannot carry kernel links, and every link keeps its `nio create_udp` tunnel. The controller never offers such a node a kernel link (capability unreported).
## Verified
Unit level (`tests/compute/dynamips/test_dynamips_kernel_datapath.py`): anchor topology (Ethernet models and WIC-1ENET port numbering only), the lifecycle (create/sweep/skip-existing), deferred wiring of NIOs bound while stopped, attach/update/remove command shapes on both datapaths, the idempotent re-attach across a restart, the stop order (hypervisor NIO delete before tap delete before brctl delete), capture and marker shapes, hot-added adapters, and the manager's `nio_bridge` construction. Plus the controller-eligibility cases (mixable with docker/qemu/iou, tap capability required, serial excluded) in `tests/controller/test_kernel_datapath_link.py`.
End-to-end (`tests/e2e/test_dynamips_kernel_datapath.py`, pytest marker `e2e`) on a live server with **two real c7200 routers on a real IOS image**, driven through the REST API and the IOS consoles with real ICMP:
* a link created while both routers are stopped selects the kernel datapath and is wired by node start (deferred wiring);
* the per-link kernel bridge on the host has exactly the two anchor TAPs enslaved; `show ip int brief` is up/up and ping R1→R2 succeeds;
* `delay 100` ⇒ netem qdisc visible on both anchors and the ping RTT grows by ~200 ms (one-way 100 per direction, each anchor's egress chain impairing the direction entering its own router); clearing resets the qdiscs and the RTT;
* suspend ⇒ anchor administratively down, ping 0%; resume restores both;
* capture writes a pcap full of ICMP-over-Ethernet records;
* a **serial** link between the same two routers stays on the relay (per-port exclusion) and pings over it — the relay regression net;
* link delete/re-create: the bridge goes and comes back, the anchors survive, traffic resumes;
* router stop/start keeps the wiring intact (bridge membership unchanged — the no-duplicate-NIO half is the unit-tested idempotent re-attach) and traffic resumes after the reboot;
* deleting the project removes every anchor and bridge.
`test_dynamips_relay_control` is the negative control: the same topology on an isolated relay-configured instance (`enable_kernel_datapath = false`) has no per-link bridge and nothing enslaved, and still pings — so the kernel objects above can only come from the kernel datapath.
## Configuration
```ini
[Server]
# Wire eligible links (same compute, both endpoints Ethernet and able to
# anchor) through kernel interfaces instead of the uBridge UDP relay.
enable_kernel_datapath = True
```
## Roadmap
The Ethernet switch has landed (see `ethernet-switch-kernel-datapath.md` — it absorbs the peer's anchor into its own kernel bridge, and switch-to-switch cascades with it), and so has the IOL runner container (`iol-docker-kernel-datapath.md`) and VPCS (`vpcs-kernel-datapath.md` — it attaches to a pre-created anchor with `-e -d`). Every router and switch node type now anchors, and so does VPCS; the hub, the cloud and the NAT node stay on the relay by design. Cross-compute kernel links need VXLAN/GENEVE encapsulation — a separate, still-deferred project.
@@ -0,0 +1,220 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
# Ethernet switch kernel datapath
The builtin Ethernet switch has been a real Linux kernel bridge since its
brctl migration: one bridge per switch node, every port a persistent TAP
enslaved to it (see `ethernet-switch-ubridge-brctl-migration` design notes
in `gns3server/compute/builtin/nodes/ethernet_switch.py`). What remained on
the userspace path was the *cable*: each port's TAP doubled as a uBridge
relay endpoint, and a link to another node crossed
`peer anchor/UDP tunnel → uBridge relay ↔ port TAP → bridge` — two extra
copies of every frame.
The kernel datapath removes the cable's userspace leg: the switch absorbs
the **peer's anchor directly into its own bridge**. The peer's veth host
end / TAP becomes the switch port; frames cross
`peer anchor → switch bridge → other switch ports` entirely in the kernel.
```
relay (before): peer ──UDP── ubridge[nio_udp↔nio_tap] ──tap── kernel bridge
kernel (now): peer anchor ──────────────────────────► kernel bridge
(the peer's own interface IS the switch port)
```
## Datapath selection
A link with an `ethernet_switch` endpoint rides the fast path when the
**peer** can anchor (same compute; Docker always — including IOL runner
containers, per their own capability gate — QEMU/IOU/Dynamips per
their capabilities) — the switch side needs no anchoring capability of its
own, its bridge and brctl exist by construction. Exclusions, all staying
on the relay:
* **switch ↔ switch** cascades ride the kernel too — through a veth pair
joining the two bridges (one end per switch, each side applying its own
port mode to its own end); see the wire format below;
* anchor-less peers (cloud, the Dynamips-hosted hub, generic
`GNS3_UNIX_SOCKET_NIO` containers, a VPCS binary without `-n` — see
`vpcs-kernel-datapath.md`);
* cross-compute links, non-Ethernet ports: the common rules.
**Relay port TAPs.** The switch's own relay-path port TAPs (the
`gns3{id}-N` devices) are created *implicitly* by uBridge's
`bridge add_nio_tap` — a name that is free is minted as a transient TAP,
and uBridge hardens it L2-only at creation (the fifth creator of
`docs/design/ubridge-l2-anchor-spec.md` §B, uBridge `fb72758`). The server
issues nothing extra: without that hardening the device would take a
kernel-default IPv6 identity whose DAD/MLD noise floods the segment, which
is exactly what the e2e's relay-control §E.1 assertion guards against.
## The wire format: one NIO names the other end's interface
```
controller ──► switch compute: nio_anchor { anchor: "gv00010203e0p0", filters, markers }
controller ──► peer compute: nio_bridge { bridge: null, filters: {}, markers }
```
* `nio_anchor` (new, `NIOAnchor`) is the mirror of `nio_bridge`: "enslave
*this* interface into *my own* bridge". The switch joins the anchor and
applies the port's VLAN mode to it (`brctl addif` + the access/dot1q/
qinq composition), exactly as it programs its own port TAPs.
* `nio_bridge` with `bridge: null` on the peer end means "externally
bridged": the peer keeps everything its node type does around the anchor
(Dynamips opens the TAP in the hypervisor, IOU binds the fabric to it,
QEMU's netdev, Docker's carrier) and applies markers/impairments, but
never touches bridge membership — including on detach, where deleting a
bridge it does not own would take the switch down.
The anchor's **name** is the shared naming contract
(`gns3server/utils/kernel_anchor.py`): `g<type>{node_id[:8]}e{adapter}p{port}`,
the same function the four node types create their anchors with. It is a
pure function of (node type, node id, adapter, port) — valid whether or
not the peer is running, which is what makes links to stopped nodes
wireable at all.
**Ownership.** The switch owns everything about the anchor's bridge state
(membership, VLANs). The link's *link state* — capture, markers, tc
impairments, suspend — is attached to the same interface by exactly one
end: filters and capture go to the switch (the controller assigns them
single-sided; both ends would hit one interface twice), suspend rides both
(same admin state either way), markers follow the usual capture-node
routing and work from either end.
## Stopped peers: deferred join and the re-push
The peer's anchor exists only while the peer runs. A link created against
a stopped peer cannot be joined immediately, so the switch **defers**: it
remembers the anchor and touches nothing (the link must not fail — this is
the normal case when a project reopens while nodes are still starting).
The controller completes the wiring: after any node of a link reaches the
started state (`Node.start` → `UDPLink.node_started`), a switch link's NIO
is re-pushed to the switch, which joins the anchor now. The same re-join
runs when a peer restart *replaced* its interface under the same name
(QEMU recreates its TAPs at every start): the membership is checked against
the kernel (`/sys/class/net/<bridge>/brif/<anchor>`), not assumed.
Port setting changes (`ports_mapping` update) edit VLAN membership **in
place**: only the ports whose mode/VLAN actually changed are touched, and
each change deletes the previous mode's entries the new mode does not want
and adds the new mode's (the dot1q admits-all entry is one range operation
in both directions). A port never leaves the bridge to change its VLANs —
no traffic gap, no FDB flush, and nothing that detaches an interface this
switch does not own.
This replaced an earlier "reset by re-enslaving" shortcut (`delif` +
`addif`, so the kernel would hand the port a fresh default membership —
used because a mode change must drop stale entries, e.g. dot1q's all-VIDs
range). On the switch's own relay TAPs it merely cost a brief traffic gap;
on **absorbed anchors** re-enslaving an interface owned by another node
proved to be where links died: live testing showed an anchor occasionally
losing its bridge membership right after a `ports_mapping` update (later
updates then failed `delif` with EINVAL), reproducibly with qemu, IOU and
Dynamips peers, never with Docker's veths. That failure was root-caused
later: it is NetworkManager releasing NM-managed TAPs from their bridge
tens of milliseconds after (re)enslavement — veths are not NM-managed,
which is exactly why only TAP peers showed it (the mechanics and the
`nmcli device set <tap> managed no` remedy are in the L2-anchor spec). The
in-place reconcile removes this particular re-enslavement, but link delete
+ recreate and peer restarts still re-enslave the anchor, so the hazard
remains on NM hosts wherever NM manages the taps; the kernel e2e scenarios
take the anchors out of NM's hands
(`harness.unmanage_from_networkmanager`) before they exercise those paths.
The full record — forensic signatures, the minimal server-free reproducer,
the NetworkManager source-level mechanism and the verified host fix — is in
`docs/bugs/networkmanager-tap-release.md`.
## Link-local frames (LACP, LLDP, 802.1X, STP)
The bridge stands in for a cable, but the kernel's `br_handle_frame()` does
not forward the IEEE 802.1D reserved range (`01:80:c2:00:00:00`-`0f`) by
default — LACP, LLDP/DCBX and 802.1X would never cross a kernel link while
the UDP relay carries them fine. uBridge therefore opens every port's
per-port `group_fwd_mask` (`IFLA_BRPORT_GROUP_FWD_MASK`) to `0xfffd` at
`brctl addif` time (Linux 4.15+, best-effort on older kernels). The
bridge-level knob cannot do this: `BR_GROUPFWD_RESTRICTED` rejects bits 0-2,
so LACP is reachable per port only.
Result on kernel links: ordinary multicast, STP/RSTP, LACP, 802.1X and
LLDP/DCBX all cross; **802.3x PAUSE / PFC does not** — `case 0x01` in
`br_handle_frame()` drops it unconditionally and no mask can enable it.
That is a documented limit, not a regression (PFC's hardware semantics are
out of emulation's reach anyway); a lab that needs PAUSE frames on the wire
must use a relay link. Verified live by
`tests/e2e/test_docker_link_local_frames.py` (per-MAC guest-to-guest
matrix); the contract and kernel references live in
`docs/design/ubridge-link-local-frame-forwarding-spec.md`.
The switch node's own bridge ports carry the same mask: the builtin
Ethernet switch is a transparent L2 segment in GNS3, not a protocol
endpoint, so LACP/LLDP between two peers crosses it (a physical switch
would terminate them itself).
## Verified
Unit level (all under `tests/`): the switch's kernel-port lifecycle (join
with VLAN composition, deferred join, re-join, detach with marker/tc/
carrier teardown, capture on the anchor, batch acceptance for project
open); the in-place VLAN reconcile (every mode transition, untouched ports
emit nothing, relay TAPs and absorbed anchors alike); the shared naming
contract; the mixin's externally-bridged branch (no bridge membership work
in attach/remove, the bridge sweep never deletes a bridge the node does not
own); the controller's eligibility table, wire format (anchor name,
single-sided filters, endpoint-order alignment), `kernel_datapath`
reporting and the node-start re-push.
Live end-to-end on a real server (`tests/e2e/test_ethernet_switch_kernel_datapath.py`
plus scripted reproduction rounds over the REST API):
* two qemu peers (the previously 2-out-of-2 failing scenario): deferred
links → start → both anchors joined; four `ports_mapping` cycles
(10/20 ↔ 10/10) with both anchors in the bridge throughout, no failed
update, kernel VLAN state correct at every step;
* a mixed switch (2 × IOU + 2 × Dynamips on one bridge, four kernel
ports): four anchors stable across updates that changed all ports and
across updates that changed only two;
* Docker peers with real ICMP: isolating VLANs cuts the ping with **both
anchors still enslaved** (the filter does the cutting, not a broken
link); restoring the VLAN restores the ping;
* VPCS peers (the relay path, same switch-side mechanics as cloud): the
relay TAPs likewise stay enslaved across VLAN changes, with a real ping
proving isolation and recovery.
The cascade has its own in-repo e2e
(`tests/e2e/test_ethernet_switch_cascade.py`): two switches joined by the
link-owned veth pair, two c7200 routers per switch, real ICMP crossing both
bridges — the pair is born UP with exactly one end per bridge, a dot1q
trunk cascade carries two VLANs at once, the §E.2 idle-silence window with
all four router interfaces shut (the absorbed anchors, both cascade ends
and both switch bridges), the symmetric access/trunk mode flip on the
cascade ends isolates and revives a VLAN in place, a `delay` filter lands
as netem on both ends (one per direction, RTT ≈ 2×delay), suspend
admin-downs both ends, and a link delete/re-create retires the whole pair
and mints a new one under the new link id — with zero host residue after
the project goes.
The host-side checks throughout are the kernel's own view: bridge
membership under `/sys/class/net/<bridge>/brif/`, the `master` link
attribute, `bridge vlan show`, and live pings where the peer allows it.
## Configuration
Same switch as every node type:
```ini
[Server]
enable_kernel_datapath = True
```
## Roadmap
Switch-to-switch links (a veth pair joining the two kernel bridges, with
each side's port mode applied at its own end) have landed (see above), and
so has the IOL runner container (`iol-docker-kernel-datapath.md` — its
`iol_docker` anchors absorb like any peer's). Cross-compute kernel links
need VXLAN/GENEVE encapsulation, deferred until every node type is
kernelized.
+277
View File
@@ -0,0 +1,277 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is AI-generated with reference to actual code and verified against real-kernel testing. AI can make mistakes — please verify against the source code when in doubt.
# IOL runner container kernel datapath
## Overview
IOL runner containers (`IOLDockerVM`, selected by the `GNS3_IOL_RUNNER` environment marker — the Cisco CML `iol-runner` images such as `iol-xe/iol-xe:17-18-02`) have no container-namespace networking at all: their guest leg is the runner's per-interface AF_UNIX datagram socket pairs. A unix socket is not a kernel interface, so until now every link of such a container rode the uBridge userspace relay (unix ↔ UDP).
The kernel datapath gives every Ethernet bay/unit a **persistent TAP anchor** (`gx` names, born at node start exactly like IOU's) and wires the *link segment* through the kernel. One userspace hop on the container leg is irreducible — the socket pair is the only physical layer the runner exposes — but the anchor → per-link bridge → peer anchor crossing, the kernel filters, the suspend carrier and the AF_PACKET capture/markers are all native now.
The port bridge is the deployment shape ubridge's `doc/gns3server-integration.md` § *bridge — generic NIO relay with a swappable TAP leg* froze: one bridge per bay/unit, all created at start, the unix NIO in the first slot for the node's whole life, the topology leg in the second — `add_nio_udp` (relay) or `add_nio_tap` (kernel link) — swapped through stop → delete → add → start whenever a link is deleted, re-created or switched between datapaths. Suspend swaps no leg (an in-place NIO update), and a project reopen is a fresh build from the NIO, not a swap. The c-socket binding never re-binds across a swap: frames the container sends while the bridge is stopped queue on the socket and relay after `start` (regression-tested in ubridge's bridge suite).
## Architecture
Kernel link between two IOL runner containers on the same compute. Interface names follow the shared deterministic rules — `gx{node_id[:8]}e{bay}p{unit}` for the persistent TAP anchors (one per Ethernet bay/unit) and `gns3{link_id[:11]}` for the bridge; the concrete names in the diagrams use node ids `1a2b3c4d` / `99aa88bb`, Ethernet0/0 on both, and link id prefix `9a8b7c6d5e4`. Terms the diagrams use:
| Term | Meaning |
|---|---|
| netiomux | the runner's network agent: one AF_UNIX datagram socket pair per interface, carrying raw Ethernet frames |
| `sNN.sock` / `cNN.sock` | the interface's socket pair (`NN = bay×4 + unit`): frames sent to `s` are injected into the guest, the guest's egress arrives on `c` |
| wiring dir | the host-side directory bind-mounted at the container's `/tmp` (`$XDG_RUNTIME_DIR/gns3/unixio/<node-id>`) — the same socket files on both sides, short enough for the 107-byte `sun_path` cap |
| uBridge | the per-node helper process gns3-server spawns; its hypervisor command surface executes all host-side wiring (anchors, bridges, carrier, tc, taps) — and, unique to this node type, it also carries frames: the socket guest leg has no kernel form |
| port bridge | the per-bay/unit uBridge bridge (`bridge{bay}` on unit 0, `bridge{bay}_{unit}` on units 1-3 — the historical `_bridge_name` naming): `nio_unix` in its first slot for the node's whole life, the topology leg — `nio_tap` (kernel link) or `nio_udp` (relay) — in the second |
| anchor | the persistent TAP `gx…` a link attaches to: born at node start, DOWN, its fd held by the port bridge while a kernel link binds the port |
| per-link bridge | the Linux bridge `gns3{link_id[:11]}` that stands in for the cable; the two anchors are its only ports |
| bridge port | an interface enslaved to a Linux bridge (`brctl addif`) — it no longer sends or receives on its own: frames arriving on it go to the bridge's forwarding logic, and the bridge transmits through it |
| FDB | the bridge's forwarding database (learned MAC → port); unknown, broadcast and multicast destinations are flooded |
| `01:80:c2` / `group_fwd_mask` | the IEEE 802.1D reserved multicast range (STP, LACP, LLDP, 802.1X, PAUSE); the bridge forwards it only per the port's `group_fwd_mask` — `0xfffd` passes everything except PAUSE/PFC |
| tc / qdisc | traffic-control objects the kernel inserts into the anchor's egress path — stages frames pass through in flight, not external packet consumers; uBridge only installs them over netlink |
| `clsact` | the tc classifier carrier on the anchor; its egress chain is where the drop classifiers run |
| eBPF classifier | the stateful drop modes (every-Nth, quota, time window) at clsact egress prio 1 |
| `bpf_drop` | match-drop BPF expressions at clsact egress prio 10–99 |
| netem | the impairment qdisc behind clsact: delay, loss, rate, corrupt, duplicate, … |
| `AF_PACKET tap` | uBridge's packet socket bound to the anchor; the kernel clones every frame the interface sends or receives to it (the tcpdump mechanism) — read-only copies for capture and markers, the original stays on the kernel path |
| carrier | the anchor's admin state (`link set up/down`); suspend is carrier down on both anchors = 100 % loss |
| `nio_bridge` | the NIO record the controller sends each compute: bridge name, filters, markers, suspend flag — the bridge name is None when an Ethernet-switch peer absorbs the anchor into its own kernel bridge (then no per-link bridge exists on this side) |
```mermaid
flowchart TB
subgraph NetA["container A netns (iol-runner)"]
IOLA["IOL process"]
MUXA["netiomux"]
IOLA <-->|"Eth0/0"| MUXA
end
subgraph RootNS["root namespace"]
subgraph UBA["uBridge A process"]
PBA["port bridge A"]
end
gxA["gx1a2b3c4de0p0 — anchor"]
subgraph LBR["per-link Linux bridge"]
BR["gns39a8b7c6d5e4"]
end
gxB["gx99aa88bbe0p0 — anchor"]
subgraph UBB["uBridge B process"]
PBB["port bridge B"]
end
end
subgraph NetB["container B netns (iol-runner)"]
MUXB["netiomux"]
IOLB["IOL process"]
MUXB <-->|"Eth0/0"| IOLB
end
MUXA <-->|"nio_unix"| PBA
PBA <-->|"nio_tap"| gxA
gxA <-->|"bridge port"| BR
BR <-->|"bridge port"| gxB
gxB <-->|"nio_tap"| PBB
PBB <-->|"nio_unix"| MUXB
PBA -. "qdisc install" .-> gxA
gxA -. "frame copies" .-> PBA
PBB -. "qdisc install" .-> gxB
gxB -. "frame copies" .-> PBB
```
Everything in the root namespace is built the same way: gns3-server creates the anchor TAPs at node start, the per-link bridge and its memberships at link creation, and every later change (carrier, capture, markers, filters) by sending hypervisor commands to the node's uBridge process. That build flow is the Link operations sequence below; this diagram is the steady state that remains.
The solid chain is the frame path, and it passes through the port bridges — the one userspace hop per container leg the socket pair forces, and the only one on the whole path; unlike the Docker veth datapath, where uBridge sits entirely off the forwarding path, here it is on it. The dashed edges are control and observation: `qdisc install` is the port bridge configuring the kernel over netlink (the kernel then runs those qdiscs in-flight on the anchor's egress — stages of the transmit path, not packet consumers), and `frame copies` is the AF_PACKET tap — read-only clones for capture and markers. Everything sideband is keyed on the anchor's interface name, which is why a TAP anchor and a veth host end are interchangeable in the shared mixin (`gns3server/compute/kernel_datapath.py`).
Relay link (what a missing capability, a cross-compute peer or `enable_kernel_datapath = off` falls back to — same sockets, same port bridge, only the topology leg changes):
```mermaid
flowchart LR
subgraph CTA["container A (iol-runner)"]
MUXA["netiomux A"]
end
subgraph KRN["kernel — sockets & loopback"]
SOCKA["c00.sock"]
UDP["UDP sockets (loopback)"]
SOCKB["s00.sock"]
ANCH["gx anchors — idle"]
end
subgraph UBA["uBridge A — userspace"]
UNA["unix nio"]
ENA["port bridge relay + userspace filters"]
NDA["udp nio"]
end
subgraph UBB["uBridge B — userspace"]
NDB["udp nio"]
ENB["port bridge relay + userspace filters"]
UNB["unix nio"]
end
subgraph CTB["container B (iol-runner)"]
MUXB["netiomux B"]
end
MUXA -->|"copy 1: user→kernel"| SOCKA
SOCKA -->|"copy 2: kernel→user"| UNA
UNA --> ENA --> NDA
NDA -->|"copy 3: user→kernel"| UDP
UDP -->|"copy 4: kernel→user"| NDB
NDB --> ENB --> UNB
UNB -->|"copy 5: user→kernel"| SOCKB
SOCKB -->|"copy 6: kernel→user"| MUXB
```
Drawn one-way; the reverse direction is the mirror image. The IOL relay crosses the kernel/user boundary **six times each way** — but four of them are the socket guest leg itself, paid identically on the kernel datapath (six there too): unlike Docker's four-against-zero, the crossing count is datapath-invariant here, and the choice swaps only the middle two — loopback UDP between the port bridges (filters userspace, at them) for the per-link bridge between the anchors (filters as tc, on them).
Two further contrasts with Docker's relay: the IOL relay's local leg is the unix NIO itself, so the anchors never appear on the path (idle from birth — a Docker relay attaches to the *same* veth host end the kernel link enslaves); and the port bridge's first slot is shared with the kernel datapath — the unix NIO and its c-socket binding survive every leg swap, so frames the container sends while the bridge is stopped for a swap queue on the socket and relay after `start`. On this datapath suspend rides the synthetic frequency_drop filter (the kernel datapath's suspend is the anchor's admin state).
Frame path for one A → B frame, with the relay diagram's copy numbering: copies 1, 2, 5 and 6 are the socket guest legs and are paid identically on both datapaths — only the middle two swap (TAP fd write/read here, loopback UDP there). The impairment chain fires on the egress of the *destination* anchor, in order clsact → netem (a classifier drop means netem never sees the frame); each direction is impaired exactly once and B → A is symmetric on gxA's egress chain — `delay 100` is therefore collected once per direction, ~200 ms on the RTT (measured ≥ 150 ms):
```mermaid
flowchart LR
subgraph CTA["IOL A container — userspace"]
S1["IOL A sends on Eth0/0"]
end
subgraph KERN["kernel"]
SOCKA["c00.sock"]
SOCKB["s00.sock"]
end
subgraph UBA["uBridge port bridge A — userspace"]
S2["relay"]
end
subgraph GXA["gxA — ingress (egress chain serves B→A)"]
S4["ingress"]
end
subgraph BRP["per-link bridge"]
G1{"reserved 01:80:c2?"}
D["dropped"]
S5["FDB lookup / flood"]
end
subgraph GXB["gxB — egress chain (clsact, then netem)"]
S6["eBPF prio 1"]
S7["bpf_drop prio 10-99"]
S8["netem qdisc"]
end
subgraph UBB["uBridge port bridge B — userspace"]
S9["relay"]
end
subgraph CTB["IOL B container — userspace"]
S11["IOL B receives on Eth0/0"]
end
tap["capture / markers"]
S1 -->|"copy 1: user→kernel"| SOCKA
SOCKA -->|"copy 2: kernel→user"| S2
S2 -->|"copy 3: user→kernel"| S4
S4 --> G1
G1 -->|"PAUSE 0x01"| D
G1 -->|"0xfffd passes"| S5
S5 --> S6
S6 --> S7 --> S8
S8 -->|"copy 4: kernel→user"| S9
S9 -->|"copy 5: user→kernel"| SOCKB
SOCKB -->|"copy 6: kernel→user"| S11
S4 -.->|"AF_PACKET tap"| tap
S8 -.->|"AF_PACKET tap"| tap
```
The reserved-range gate passes LACP, LLDP, 802.1X and STP per the port mask but never PAUSE/PFC (Link-local frames below); the clsact/netem stages drop or impair per the installed filters (Capture, markers, filters below). The AF_PACKET taps observe both anchors but never a clsact-dropped frame.
## Datapath selection
`UDPLink._kernel_datapath_eligible` treats an IOL runner container like any Docker node (same compute, Ethernet port) with one gate of its own in `_kernel_endpoint_ready`: the compute must report both
* `ubridge_tap` — the tap module (`tap create`/`tap delete`), the same capability QEMU and Dynamips gate on, and
* `ubridge_bridge_tap` — `bridge delete_nio_tap`, the swappable-leg command (probed with one command against a bridge that cannot exist: 202 = old build, 214 = new; no scratch objects, no capabilities, cached by binary identity like every other probe).
Both strict `True`; anything unreported (old uBridge, failed probe) keeps the link on the relay, where it always works. The generic `GNS3_UNIX_SOCKET_NIO` containers stay excluded as before — that marker's semantics are image-specific, while `GNS3_IOL_RUNNER` selects a class whose anchors this server owns.
## Anchor lifecycle
* **Birth (node start, before any link)** — `_start_ubridge` runs `_prepare_tap_datapath` right after the hypervisor connects: probe both capabilities, then for every (bay, unit 0-3) sweep a leftover (`tap delete`, suppressed), `tap create` (hardened, starts DOWN) and `link set down` — carrier off until a link attaches. The anchors exist whether or not any link ever uses them: an anchor born with its link would leave the Ethernet switch fast path's deferred join waiting forever. No `tap set_owner`: uBridge itself holds these fds.
* **Life** — the anchor is never recreated. Link create/delete/switch, suspend, capture and markers only change what is attached to it, and the ensure-then-add contract guards the one window where the device could have been swept (`/sys/class/net` existence check — `tap create` is strictly create-only, `IFF_TUN_EXCL`, and refuses an existing device with EBUSY).
* **Death (node stop)** — the port bridges hold the anchor fds (`bridge add_nio_tap`), so they are deleted first (`bridge delete` stops their relay threads and frees the NIOs), then the anchors themselves (`tap delete` answers EBADFD on a device another fd still holds), then the per-link kernel bridges — all while the control channel lives, before the hypervisor stops. A restart recreates everything from the NIO.
## Link operations
Both endpoints attach concurrently and compute the same bridge name independently (a pure function of the link id), so either may win the `brctl create` race — the loser verifies the bridge exists (`brctl show`) and continues:
```mermaid
sequenceDiagram
participant API as REST API
participant C as Controller
participant CA as IOL node A
participant CB as IOL node B
participant UA as uBridge A
participant UB as uBridge B
API->>C: POST /links
C->>C: eligibility check
C->>C: bridge = gns3 + link_id[:11]
C--)CA: nio_bridge
C--)CB: nio_bridge (same bridge)
par IOL node A
CA->>UA: ensure port bridge
CA->>UA: ensure anchor
CA->>UA: bridge add_nio_tap
CA->>UA: brctl create
CA->>UA: link set bridge up
CA->>UA: brctl addif gxA
CA->>UA: port fwd_mask 0xfffd
CA->>UA: markers / capture if any
CA->>UA: tc netem + bpf + eBPF
CA->>UA: bridge start
CA->>UA: link set gxA up
and IOL node B
CB->>UB: same on gxB
end
Note over UA,UB: steady state — kernel forwards between the anchors, port bridges relay to the containers
```
Every arrow to uBridge is one `_ubridge_send` command line on the node's local hypervisor console; uBridge executes it (netlink/ioctl) and replies OK or an error synchronously before the next command is sent — those replies are omitted for brevity. uBridge never initiates anything: it is a pure executor, and the only data ever flowing back (capture/marker frame copies) rides separate AF_PACKET sockets, not this console.
The attach above is `_attach_kernel_link`; its ensures are the frozen ensure-then-add contract: the port bridge (`bridge create` + `add_nio_unix`) comes from the node's start loop or is created here, and `tap create` runs only when `/sys/class/net` shows the anchor missing — it is strictly create-only (`IFF_TUN_EXCL`) and answers EBUSY on the device the start loop just made. `bridge add_nio_tap` is what opens and holds the anchor fd, `bridge start` starts the [unix ↔ tap] relay, and the final `link set up` refines the anchor's admin state to the NIO's suspend flag — `brctl addif` has already brought the port up (addif auto-UPs it along with its fwd_mask), so on an unsuspended link the command changes nothing, and a suspended one is what pushes the anchor back down.
* **Link delete** (`_release_port_tap`): `bridge stop` (delete_nio_tap refuses while running — the relay threads hold the NIO pointers for their whole life; freeing under them is a use-after-free) → `bridge delete_nio_tap <bridge> "<tap>"` (matched on the kernel-resolved name) → the mixin teardown (markers, tc reset, `brctl delif`, per-link bridge deletion). The anchor survives — the node owns it, not the link.
* **Relay link** — unchanged: the port bridge's second leg is `add_nio_udp`, userspace filters at the port bridge. The unix NIO stays in its slot across every datapath switch.
## Capture, markers, filters
Inherited from `KernelDatapathMixin` unchanged — everything is keyed on the anchor interface name, which is why a TAP and a veth host end are interchangeable there: `capture start_kernel` / `marker add_kernel` (AF_PACKET), one tc netem qdisc (the full netem surface plus the extensions), `bpf` as cls_bpf match-drop, `frequency_drop`/`quota`/`window_drop` as the eBPF stateful classifier — all capability-gated per compute exactly like the Docker veth datapath (the filter semantics live in `packet-filters.md`).
Suspend semantics: anchor admin-down. The port bridge's TAP writes fail EIO (tolerated by the delivered uBridge hardening) and its reads fall silent — traffic stops both ways. The runner itself is unaware of the link state (netiomux has no carrier signal), exactly as on the relay datapath where suspend rode the synthetic frequency_drop filter instead.
## Link-local frames (LACP, LLDP, 802.1X, STP)
The bridge stands in for a cable, but the kernel's `br_handle_frame()` does not forward the IEEE 802.1D reserved range (`01:80:c2:00:00:00`-`0f`) by default — LACP, LLDP/DCBX and 802.1X would never cross a kernel link while the UDP relay carries them fine. uBridge therefore opens every port's per-port `group_fwd_mask` (`IFLA_BRPORT_GROUP_FWD_MASK`) to `0xfffd` at `brctl addif` time (Linux 4.15+, best-effort on older kernels). The bridge-level knob cannot do this: `BR_GROUPFWD_RESTRICTED` rejects bits 0-2, so LACP is reachable per port only.
Result on kernel links: ordinary multicast, STP/RSTP, LACP, 802.1X and LLDP/DCBX all cross; **802.3x PAUSE / PFC does not** — `case 0x01` in `br_handle_frame()` drops it unconditionally and no mask can enable it. That is a documented limit, not a regression (PFC's hardware semantics are out of emulation's reach anyway); a lab that needs PAUSE frames on the wire must use a relay link. Verified live by `tests/e2e/test_docker_link_local_frames.py` (per-MAC guest-to-guest matrix); the contract and kernel references live in `docs/design/ubridge-link-local-frame-forwarding-spec.md`.
## Relay fallback
Missing either capability, the node runs relay-only: links ride unix ↔ UDP, `kernel_datapath` stays false, and anchors are simply never created (or, with `enable_kernel_datapath` off server-wide, created but never attached — the same semantics as QEMU's and Dynamips' anchors).
## Verified
Live on the real server (`tests/e2e/test_iol_docker_kernel_datapath.py`, isolated instance, real `iol-xe/iol-xe:17-18-02` images, real uBridge with `bridge delete_nio_tap`):
* kernel link reports `kernel_datapath`, anchors exist from node start, the per-link bridge enslaves exactly the two of them;
* real ICMP crosses the [unix ↔ tap] port-bridge relay (100 % ping);
* the L2-anchor spec on the anchors: FORWARDING ports always, and on a uBridge with `link l2only` §E.1's pure-L2 checks plus §E.2's silence window with the guests shut — the behavioral half of the hardening on anchors created by uBridge's bridge TAP module (`bridge add_nio_tap`);
* `delay 100` lands as netem on both anchors, measured RTT grows ≥ 150 ms and returns < 50 ms when cleared;
* the classifier spot check on a TAP anchor (the Docker suite runs the full matrix on veth host ends), each behind its capability gate: `bpf "icmp"` drops everything (clsact on the anchor, needs cbpf), `frequency_drop 3` as the eBPF every-nth mode (needs the nth token) — round-trip loss asserted 20-90 % around the per-direction theory 1-(2/3)² = 55.6 %, both restoring on clear;
* suspend admin-downs the anchor and kills the traffic; resume restores;
* AF_PACKET capture writes a real pcap of the ICMP exchange;
* link delete/re-create swaps the port bridge's TAP leg out and back in (unix binding never re-binds) with the ping returning;
* node stop tears the anchors down (no `gx` devices left), a restart recreates the whole wiring from the NIO;
* project delete leaves no anchors and no bridges; the relay control on a relay-configured instance keeps the link off the kernel and still pings.
Also caught and fixed live: `tap create` is strictly create-only (`IFF_TUN_EXCL`) — the ensure-then-add guard must check existence first (`/sys/class/net`), not re-create unconditionally (EBUSY on the device the start loop just made).
## Configuration
```
[Server]
enable_kernel_datapath = True # the global switch (link attachment)
```
The anchor lifecycle needs no configuration of its own — the capability probes decide per compute, and an IOL runner container without them simply never anchors.
## Roadmap
Cross-compute kernel links need VXLAN/GENEVE encapsulation — deferred until every node type is kernelized; with the IOL runner container anchored, every node type in scope can now anchor (hub, cloud and NAT stay on the relay by decision; VPCS anchors since `vpcs-kernel-datapath.md`), so the encapsulation work is all that remains.
+218
View File
@@ -0,0 +1,218 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# IOL Images with iol-runner (Cisco CML containerized IOL) as Docker Nodes
## Overview
IOL images packaged with Cisco CML's container runner — for example
`iol-xe/iol-xe:17-18-02` (IOS-XE 17.18.02 IOL in a scratch image driven by
`iol-runner`, module `virl.lab/cmd/iol-runner`) — run as first-class GNS3
Docker router nodes with **zero changes to the image**. The integration adds
two generic server mechanisms:
1. **Unix-socket NIO** (`GNS3_UNIX_SOCKET_NIO=1`, on `VendorDockerVM`): link
adapters through per-interface AF_UNIX datagram sockets instead of a TAP
interface moved into the container's network namespace.
2. **`IOLDockerVM`** (marker `GNS3_IOL_RUNNER=1`): generates the runner's
config file per start, prepares its runtime directory and cleans up stale
sockets — the iol-runner-specific glue on top of the vendor path.
## How the image works
```mermaid
graph LR
subgraph Container["scratch container (PID 1)"]
RUNNER["/iol-runner -config /config/iol-config.json -stdio"]
IOL["IOL process<br/>(IOS-XE 17.18.02)"]
NETIOMUX["netiomux"]
SOCKETS["/tmp/s00.sock (recv)<br/>/tmp/c00.sock (send-to path)<br/>… one pair per interface"]
RUNNER -->|"spawn -e/-s/-m + app id"| IOL
IOL -->|"netio bus /tmp/netio&lt;uid&gt;/"| NETIOMUX --> SOCKETS
end
subgraph Host
UBRIDGE["uBridge bridgeN<br/>add_nio_unix …/gns3/unixio/&lt;node&gt;/cNN.sock …<br/>+ add_nio_udp (topology)"]
RTDIR["/run/user/&lt;uid&gt;/gns3/unixio/&lt;node&gt;<br/>(bind-mounted at /tmp)"]
VOL["project-files/docker/&lt;node&gt;/config<br/>(+ tmp/run, nested bind at /tmp/run)"]
end
SOCKETS <-->|"same files, two spellings<br/>(the /tmp bind)"| RTDIR <--> UBRIDGE
UBRIDGE -.->|"iol-config.json +<br/>persistent /tmp/run"| VOL
```
* **Console**: the runner muxes the IOS console onto PID 1 stdio (`-stdio`
entrypoint flag). The plain `console_type: "telnet"` attaches to it — no
`docker_exec` needed. The runner requires a TTY, which GNS3 always
allocates; without one the runner exits (`inappropriate ioctl for device`).
* **Networking**: the runner does not touch the container's network
namespace. Per interface N it creates, inside the container's `/tmp`: a
receive socket `s%02d.sock` (frames sent there are injected into guest
interface N) and a send-to path `c%02d.sock` (whoever binds it receives
the guest's frames). Frames are **raw Ethernet**, one datagram per frame —
the same two-mailbox convention uBridge's `add_nio_unix` natively speaks
(it binds the c-socket, sends to the s-socket). GNS3 bind-mounts a
per-node directory from the runtime directory
(`/run/user/<uid>/gns3/unixio/<node-id>`, next to the uBridge control
sockets) at the container's `/tmp`, so uBridge reaches the sockets as
plain host files: the path stays far under AF_UNIX's 107-byte `sun_path`
cap (a projects-tree node path alone exceeds it) and the directory is
owned by the server user, to whom the runner drops its privileges. This
mirrors how CML itself runs the image (`source=…/tmp,target=/tmp` in its
node definition). The directory is ephemeral and removed with the node.
* **Licensing**: the image ships a self-consistent `/etc/hostid` + `.iourc`
pair, and the runner regenerates the license from the host ID at boot —
nothing to configure.
* **Persistence**: `/tmp/run` (the IOL working directory) holds the NETMAP,
the startup-config (`config`, plain IOS format) and NVRAM (`nvram_00001`).
It is the only `/tmp` path that needs to survive: GNS3 bind-mounts the
node directory's `tmp/run/` at `/tmp/run` (nested inside the runtime-dir
bind), so the router's configuration survives stop/start and container
recreation while sockets, netio buses and runner logs stay ephemeral.
The generated config maps the runner to the server's uid/gid
(`user-id`/`group-id`), so all files it creates are owned by the server
user (no permission-fix pass needed).
## Template
Create the template once via `POST /v3/templates` (authenticated — see the
API docs for the auth flow), or in the Web UI under
*Edit → Preferences → Docker templates → New* with the same fields:
```json
{
"name": "IOS-XE 17.18.02 IOL",
"template_type": "docker",
"image": "iol-xe/iol-xe:17-18-02",
"category": "router",
"symbol": ":/symbols/router.svg",
"adapters": 2,
"console_type": "telnet",
"environment": "GNS3_IOL_RUNNER=1",
"extra_volumes": ["/config"]
}
```
| Field | Value | Why |
|---|---|---|
| `environment` | `GNS3_IOL_RUNNER=1` | The switch that selects `IOLDockerVM` (skip-init, unix-socket NIO, auto volumes). Optional: `GNS3_IOL_MEMORY=<MB>` (default 2048), `GNS3_IOL_STARTUP_CONFIG=<file>` (initial configuration, see below). |
| `extra_volumes` | `["/config"]` | `/tmp/run` is auto-added. **Never add `/tmp`** — it would persist the socket directory into the projects tree and uBridge would reject the too-long AF_UNIX path. |
| `adapters` | number of 4-port units | The IOU convention: one adapter = `Ethernet0/0`–`Ethernet0/3`, two adapters add `Ethernet1/0`–`1/3`, … (8 units / 32 ports max). Ports are addressed as (adapter, port 0–3) and shown grouped in the UI. |
| `memory` | optional; `0` (default) = no cap | Unset works — Docker applies no limit. When you do set a cap, keep it at IOL memory + ~512 MB, or the cgroup OOM-killer shoots the router. |
| `console_type` | `telnet` | The runner muxes the IOS console onto PID 1 stdio; `docker_exec` is not needed. |
### Verify
1. The node's port list shows the grouped IOL interfaces
(`Ethernet0/0`–`Ethernet1/3` for two adapters), addressed
(adapter, port).
2. Drop a node into a project and start it — the console shows the
`Linux Unix (i686)` banner within seconds.
3. `$XDG_RUNTIME_DIR/gns3/unixio/<node-id>/` contains `s00.sock`… (one
pair per port).
4. A node created with a startup-config boots straight to the configured
hostname — no initial configuration dialog (interface names in the
config are `Ethernet0/0`, not `GigabitEthernet0/0`).
## Startup configuration
IOL Docker nodes load an initial configuration exactly like native IOU
nodes: the **template references a config file**, and every node created
from it boots with that configuration as its personal starting point.
```json
"environment": "GNS3_IOL_RUNNER=1\nGNS3_IOL_STARTUP_CONFIG=iol-xe-base.txt"
```
* The file lives in the controller's configs directory (the `configs_path`
server setting, by default `~/GNS3/configs`) — the same place IOU and
VPCS base configs live. A minimal `iol-xe-base.txt` ships with the
server and is installed there on startup (never overwriting a
user-modified copy); an absolute path in the knob bypasses the directory
entirely. `%h` in the content is replaced with the node name at start.
* **Creation materializes it once**: the controller reads the file and
sends its content with the node; afterwards the knob is consumed and the
template file is never referenced again — editing it does not affect
existing nodes. The knob also disappears from the node's `environment`
(`GNS3_IOL_RUNNER=1` remains — it re-selects the node class on every
recreation), so a node whose environment shows only `GNS3_IOL_RUNNER=1`
is the normal sign that the file was found and its content delivered;
when the file is missing the knob stays in the environment (with a
server-side warning) and the lookup is retried at the next creation.
* **NVRAM is the source of truth at boot** (verified on the runner): the
content is built into the node's `tmp/run/nvram_<app id>` — IOL and IOU
share the nvram container format, so the server-side `nvram_import`
utility produces a file IOL boots from directly. Consequences:
* `write memory` survives stop/start and container recreation (a plain
restart never re-applies the startup-config over it). The first
`write memory` after a server-built NVRAM asks for a one-time
`[confirm]` (the builder stamps an IOS 15.4 version marker into the
nvram header; press return — IOS then writes its own).
* Editing a node's `startup_config_content` property (PUT) re-applies it
on the next start, overwriting what `write memory` had saved — the
explicit edit wins, as with IOU.
* Renaming a node rewrites the `hostname` line in its NVRAM, so a
duplicated/renamed node boots under its new name.
* **Resetting a node to its template config**: stop the node, delete
`project-files/docker/<node>/tmp/run/nvram_*`, then re-apply the content
(or recreate the node).
## Server mechanisms
| Mechanism | Where | What it does |
|---|---|---|
| `GNS3_UNIX_SOCKET_NIO=1` | `VendorDockerVM` | `_add_ubridge_connection` override: `bridge create` + `bridge add_nio_unix <dir>/c{N:02d}.sock <dir>/s{N:02d}.sock` instead of TAP + `docker move_to_ns`. No TAP allocation, no `set_mac_addr`, namespace untouched. The socket directory is bound from a per-node runtime directory unless a persisted volume already covers it. |
| `GNS3_UNIX_SOCKET_DIR=<dir>` | `VendorDockerVM` | In-container socket directory (default `/tmp`). Any image whose agent exposes the `s%02d`/`c%02d` datagram pairs can use this without the IOL specifics. |
| `GNS3_IOL_RUNNER=1` | `IOLDockerVM` (selected in the manager) | Forces skip-init + unix-socket NIO + the `/config` and `/tmp/run` volumes; on every start writes `<node>/config/iol-config.json` (`num-eth` = adapter count, `num-serial` = 0, memory from `GNS3_IOL_MEMORY`, default 2048), creates `<node>/tmp/run/` (the IOL process dies without it) and removes stale sockets/netio dirs from the socket directory (`tmp/run` is never touched). |
| `restart()` hardening | `IOLDockerVM` | The base `docker restart` would boot the runner on a stale config and leave uBridge wired to the previous run's sockets; reload becomes graceful stop (SIGTERM → NVRAM flush) + full start. |
| `GNS3_IOL_STARTUP_CONFIG=<file>` | controller `Node._node_data` + `IOLDockerVM` | Startup-config plumbing (see above): the controller translates the file into `startup_config_content` on node creation (sent once); the compute builds it into `nvram_<app id>` at the next start via the IOU `nvram_import` utility and rewrites the hostname line on rename. |
`GNS3_STOP_TIMEOUT` (default 60) controls the SIGTERM grace period on stop.
Extra iol-runner flags can be passed via `start_command`, e.g. `-keep`
(L1 keepalives) or `-debug 9` (verbose `process.log` — very useful when
diagnosing wiring issues).
## Notes and caveats
* **Console typing latency**: single keystrokes are echoed on a ~50 ms
cadence — the image services console input on an internal poll.
Measured directly on the container console (bypassing the GNS3 server
entirely, through the same Docker attach endpoint it uses): keystroke
echo is bimodal — 1–11 ms when the keystroke lands just before a poll
tick, ~50–100 ms when it just misses one — while a pasted line is
picked up as one batch (~1.4 ms) and command output streams
back-to-back (inter-frame gaps ~0.01 ms). A control container on the
same attach endpoint echoes in ~1 ms, so the GNS3 telnet path is not a
factor; this matches IOS's low-priority console-input polling and there
is nothing to fix server-side. Paste long commands instead of typing
them.
* **Memory sizing**: `memory` caps the whole container; the IOL process gets
`GNS3_IOL_MEMORY` (default 2048 MB). Keep container memory at IOL memory
+ ~512 MB headroom or the OOM-killer will shoot the router.
* **MAC addresses**: the `mac_address` template field and per-adapter custom
MACs are ignored — IOL derives its own scheme from the node's application
ID (`aabb.cc{app}{iface}`), e.g. `aabb.cc03.0400`. The controller
allocates the ID at node creation from the upper half of the id space
(512–1022, disjoint from IOU's 1–511, limit 511 IOL Docker nodes across
opened projects sharing computes). Starting a node without an allocation
(raw compute API, pre-allocation topologies) is an error, not a fallback —
an uncoordinated ID could collide with the pool and make nodes silently
drop each other's frames as MAC loops.
* **Interface names are IOL-style `Ethernet0/0`**, not `GigabitEthernet0/0`
(4 ports per unit, matching the adapter-count granularity) — startup
configs addressing `GigabitEthernet…` are rejected by the parser.
* **Adapters**: one adapter is a 4-port unit (the IOU model): change the
count while the node is stopped; the config is regenerated on the next
start (`num-eth` = adapters × 4) and the runner creates the matching
socket set.
* **Stop before editing**: NVRAM is only flushed on a graceful stop (SIGTERM,
"cleanup done" in `process.log`); a kill loses the running-config changes
since the last `write memory`.
* **Class selection is create-time**: toggling `GNS3_IOL_RUNNER` via PUT
takes effect after a project reload (same as `docker_exec`).
* The startup-config lives at `project-files/docker/<node>/tmp/run/config`;
`extra_configs` targets under persisted volumes are warned against by the
generic create path — edit the file directly or paste via the console.
+264
View File
@@ -0,0 +1,264 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
# IOU kernel datapath
IOU's only physical layer is the Unix-datagram IOL fabric (`/tmp/netio<uid>/`, 8-byte IOL headers, NETMAP), so it has no host netdev to enslave — a kernel link instead gives each **Ethernet bay/unit** a persistent TAP anchor (`gi{node_id[:8]}e{bay}p{unit}`), and uBridge's `iol_bridge` (the fake IOL instance the NETMAP maps to) binds the port to that TAP with `iol_bridge add_nio_tap`. Links then attach to the anchor exactly as they do for Docker (veth) and QEMU (TAP): a per-link Linux bridge enslaves it, tc impairments run on it, capture and markers anchor on it. The uBridge capability is specified in `docs/design/ubridge-iol-tap-anchor-spec.md` and delivered by the `feature/iol-tap-anchor` branch of the ubridge fork.
Serial bays never anchor (a TAP carries Ethernet frames): serial links stay on the relay datapath whatever the compute's capabilities.
## Architecture
The diagram shows the native shape — two IOU devices linked on the kernel datapath, the scenario the e2e suite drives. A Docker or QEMU peer on the far end is the same link segment with a different anchor (a `gv` veth host end or a `gq` TAP — see `docker-kernel-datapath.md`); each IOU still terminates its own fabric in its own uBridge. Interface names follow the deterministic rules `gi{node_id[:8]}e{bay}p{unit}` for the anchors and `gns3{link_id[:11]}` for the per-link bridge (ids stripped of dashes before the slice); the concrete names in the diagrams use node ids `a1b2c3d4` / `5e6f7a8b` (IOU A/B), link id prefix `5d3c2b1a4e6`, and application ids 1 / 2 (so the fake instances are `IOL-BRIDGE-513` / `IOL-BRIDGE-514`). Terms the diagrams use:
| Term | Meaning |
|---|---|
| IOL fabric | the `/tmp/netio<uid>/` unix-datagram mailboxes — one directory shared by every IOU node on the host, namespaced by IOL id; every frame carries an 8-byte IOL header |
| NETMAP | the per-node redirect table pointing a port's fabric traffic at another IOL id — here uBridge's fake instance |
| `iol_bridge` | uBridge's fake IOL instance — one per node, named `IOL-BRIDGE-{application_id + 512}` (the NETMAP redirects the node's own id to it); one listener thread per bound port, and it holds the anchor TAP fds |
| anchor | the host-side interface a link attaches to — here the `gi` persistent TAP; a Docker peer's `gv` veth host end or a QEMU `gq` TAP is interchangeable as the other port |
| persistent TAP | the TAP created per Ethernet bay/unit at node start (`tap create`): born DOWN, address-free, 4 units per bay (as many bays as the node has Ethernet adapters) |
| per-link bridge | the Linux bridge `gns3{link_id[:11]}` that stands in for the cable; the two anchors are its only ports |
| tap fd | a TAP's file descriptor: reads return frames the kernel received on the device, writes inject frames into it — on this datapath the `iol_bridge` listener holds it |
| FDB | the bridge's forwarding database (learned MAC → port); unknown, broadcast and multicast destinations are flooded |
| `01:80:c2` / `group_fwd_mask` | the IEEE 802.1D reserved multicast range (STP, LACP, LLDP, 802.1X, PAUSE); the bridge forwards it only per the port's `group_fwd_mask` — `0xfffd` passes everything except PAUSE/PFC |
| `clsact` | the tc classifier carrier on the anchor; its egress chain is where the drop classifiers run |
| eBPF classifier | the stateful drop modes (every-Nth, quota, time window) at clsact egress prio 1 |
| `bpf_drop` | match-drop BPF expressions at clsact egress prio 10–99 |
| netem | the impairment qdisc behind clsact: delay, loss, rate, corrupt, duplicate, … |
| `AF_PACKET tap` | uBridge's packet socket on the anchor — how capture and markers observe frames off the forwarding path |
| carrier | the anchor's admin state (`link set up/down`); suspend is carrier down — a down TAP answers EIO in both fd directions (writes drop the frame; the §B hardening tolerates both) |
```mermaid
flowchart LR
subgraph IOSPA["IOU A process"]
iosA["IOS (IOL binary)"]
end
subgraph RootNS["root namespace"]
subgraph UBA["uBridge A"]
brA["IOL-BRIDGE-513"]
end
giA["gia1b2c3de0p0"]
BR["gns35d3c2b1a4e6"]
giB["gi5e6f7a8be0p0"]
subgraph UBB["uBridge B"]
brB["IOL-BRIDGE-514"]
end
end
subgraph IOSPB["IOU B process"]
iosB["IOS (IOL binary)"]
end
iosA <-->|"IOL fabric (NETMAP)"| brA
brA <-->|"TAP fd 0/0"| giA
giA <-->|"bridge port"| BR
BR <-->|"bridge port"| giB
giB <-->|"TAP fd 0/0"| brB
brB <-->|"IOL fabric (NETMAP)"| iosB
brA -.->|"AF_PACKET tap"| giA
brA -.->|"tc qdisc"| giA
brB -.->|"AF_PACKET tap"| giB
brB -.->|"tc qdisc"| giB
```
Unlike the Docker veth datapath, where uBridge sits off the forwarding path and only taps, here each node's uBridge is **on** it: the `iol_bridge` listener terminates the fabric and relays frames between the mailboxes and the anchor TAP fd. That one userspace hop per leg is **irreducible** — the fabric is Unix sockets, so frames always cross fabric → listener thread → TAP fd. What the kernel datapath buys is the **link segment**: anchor → per-link bridge → peer anchor crosses entirely in the kernel (including IOU ↔ Docker/QEMU links), impairments run as kernel tc instead of the userspace delay line (the known blocking-nanosleep RTT defect), and suspend maps to anchor admin-down (writes to a down TAP fail EIO and are dropped by the delivered §B hardening). Direction semantics on the anchor match QEMU's exactly: uBridge holds the fd like the QEMU process does.
Relay link between the same two nodes (what an old uBridge build, a serial port or `enable_kernel_datapath` off falls back to; a cross-compute peer is the same tunnel with the far socket on the real network instead of loopback): each port rides a UDP NIO inside its `iol_bridge` and no kernel interface exists — anchors untouched, filters/capture/markers on the port's userspace list:
```mermaid
flowchart LR
subgraph IOPA["IOU A process — userspace"]
iosA["IOS (IOL binary)"]
end
subgraph KERN["kernel"]
mbxA["netio sockets"]
UDP["UDP sockets (loopback)"]
mbxB["netio sockets"]
end
subgraph UBA["uBridge A — userspace"]
ioA["IOL nio"]
enA["relay + userspace filters"]
nuA["UDP nio"]
end
subgraph UBB["uBridge B — userspace"]
nuB["UDP nio"]
enB["relay + userspace filters"]
ioB["IOL nio"]
end
subgraph IOPB["IOU B process — userspace"]
iosB["IOS (IOL binary)"]
end
iosA -->|"copy 1: user→kernel"| mbxA
mbxA -->|"copy 2: kernel→user"| ioA
ioA --> enA --> nuA
nuA -->|"copy 3: user→kernel"| UDP
UDP -->|"copy 4: kernel→user"| nuB
nuB --> enB --> ioB
ioB -->|"copy 5: user→kernel"| mbxB
mbxB -->|"copy 6: kernel→user"| iosB
```
Drawn one-way; the reverse direction is the mirror image. A relayed frame crosses the kernel/user boundary **six times each way** (twelve per round trip — each `sendto` copies user→kernel, each `recvfrom` kernel→user), the UDP hop additionally traversing the protocol stack twice; the relay's filters run in userspace on the frames between the copies.
Frame path for one A → B frame (`giA` = `gia1b2c3de0p0`, `giB` = `gi5e6f7a8be0p0`). The controller ships the same filter dict to **both** endpoints, so the link carries **two impairment points** — each anchor's egress chain — but a one-way frame crosses exactly one of them: the destination anchor's, in order clsact → netem (a classifier drop means netem never sees the frame). The asymmetry is the trace's, not the configuration's — both anchors carry the identical chain: the frame enters the kernel at the sender's anchor **ingress** (the TAP-fd write; this datapath installs nothing on ingress), and the bridge's forward out of the far anchor is an **egress** transmission, which is where the tc chain sits. B → A is symmetric on giA. Capture and markers are the observation point: one AF_PACKET tap at whichever end captures, seeing **both** directions through its anchor:
```mermaid
flowchart LR
subgraph IOPA["IOU A process — userspace"]
S1["IOS A sends on e0/0"]
end
subgraph KERN["kernel"]
mbxA["netio sockets"]
mbxB["netio sockets"]
end
subgraph UBA["uBridge A — userspace"]
S2["relay"]
end
subgraph GIA["giA — ingress (its egress chain serves B→A)"]
S4["ingress"]
end
subgraph BRP["per-link bridge"]
G1{"reserved 01:80:c2?"}
X1["dropped"]
S5["FDB lookup / flood"]
end
subgraph GIB["giB — egress chain (clsact, then netem)"]
S6["eBPF prio 1"]
S7["bpf_drop prio 10-99"]
S8["netem qdisc"]
end
subgraph UBB["uBridge B — userspace"]
S9["relay"]
end
subgraph IOPB["IOU B process — userspace"]
S11["IOS B receives on e0/0"]
end
S1 -->|"copy 1: user→kernel"| mbxA
mbxA -->|"copy 2: kernel→user"| S2
S2 -->|"copy 3: user→kernel"| S4
S4 --> G1
G1 -->|"PAUSE 0x01"| X1
G1 -->|"0xfffd passes"| S5
S5 --> S6
S6 --> S7 --> S8
S8 -->|"copy 4: kernel→user"| S9
S9 -->|"copy 5: user→kernel"| mbxB
mbxB -->|"copy 6: kernel→user"| S11
tap["capture / markers"]
S4 -.->|"AF_PACKET tap"| tap
S8 -.->|"AF_PACKET tap"| tap
```
What each stage drops: the reserved-range gate passes LACP, LLDP, 802.1X and STP per the port mask but never PAUSE/PFC (Link-local frames below); the clsact/netem stages drop or impair per the installed filters (Capture, markers, filters below); the AF_PACKET tap — capture and markers ride it, installed at whichever end captures — observes both directions of the link through its anchor (tx/rx signal pairs) but never a clsact-dropped frame. The crossings do not disappear on this datapath: each leg still crosses the kernel/user boundary three times (`sendto`/`recvfrom` on the fabric, then the TAP write — the B leg mirrors them, six per one-way frame, the same count as the relay); what moves into the kernel is the link segment — no UDP tunnel, no protocol-stack pass — and with it the impairment chain. A fabric → anchor → bridge → anchor → fabric round trip measures ≈0.2 ms (Verified below).
## Datapath selection
`UDPLink._kernel_datapath_eligible` extends the Docker/QEMU rules with:
* the compute must report **`ubridge_iol_tap`** (its own capability: the tap module and `iol_bridge add_nio_tap` land independently, and either can be missing on an old build). Probed by running one add/delete cycle on a scratch bridge + scratch TAP (`probe_iol_tap_support`, cached by binary identity, scratch bridge id 1050 — above the per-node id space 513..1024 the fabric locks); any failure means unknown → relay;
* **both linked ports must be Ethernet** — an IOU serial port disqualifies the kernel path per-port, not per-node, so serial links between capable IOU nodes silently stay on the relay instead of failing at the compute.
The NIO schema on the compute NIO routes accepts `nio_bridge` alongside the UDP/TAP/Ethernet NIOs (the same widening QEMU needed — without it, the controller's NIO POST is 422'd before the node ever sees it).
## Link creation sequence
Both endpoints sit on the **same compute** (a kernel-link prerequisite). The controller derives the bridge name once from the link id and ships one `nio_bridge` record to each endpoint — same bridge name, each side's own filters/markers and the suspend flag — the two POSTs overlapping (`asyncio.gather`, either failure rolls the peer back). The bridge has no owner: both sides race `brctl create` (EEXIST tolerated, the loser verifies via `brctl show`). When both endpoints run, the anchors already exist (born at node start — Anchor lifecycle below), so attaching only binds and enslaves:
```mermaid
sequenceDiagram
participant API as REST API
participant C as Controller
participant NA as Node A handler
participant NB as Node B handler
participant UA as uBridge A
participant UB as uBridge B
API->>C: POST /links
C->>C: eligibility check
C->>C: bridge = gns3 + link_id[:11]
par POST nio_bridge to node A
C->>NA: nio_bridge (bridge, A's filters/markers, suspend)
NA->>UA: iol_bridge add_nio_tap
NA->>UA: brctl create
NA->>UA: link set bridge up
NA->>UA: brctl addif giA
NA->>UA: capture / markers if any
NA->>UA: tc netem + bpf + eBPF
NA->>UA: link set giA up
and POST nio_bridge to node B
C->>NB: nio_bridge (same bridge, B's filters/markers)
NB->>UB: same on giB
end
Note over UA,UB: steady state — kernel forwards between the anchors, iol_bridge relays to the IOU processes
```
`iol_bridge add_nio_tap <bridge> <iol_id> <bay> <unit> "<tap>"` is the one IOU-specific step: it binds the fabric port to the anchor and hands uBridge the TAP fd. Deletion reverses it in miniature — markers, tc reset, delif, `brctl delete`, then `iol_bridge delete_nio_tap` releases the fd while the control channel lives (Link operations below).
A stopped endpoint defers its whole side of the flow — the common case, since a project is typically opened with its links already drawn. With no uBridge up, the NIO POST lands as bookkeeping only (the duplicate-port guard still applies), and the node's start replays this same attach from the recorded NIO once the anchors exist (`_networking` → `_attach_kernel_nio`), capture and filters included — which is also how a link survives its node's stop/start.
## Anchor lifecycle — and why the fd holder must let go first
* **Birth (node start)** — `_prepare_tap_datapath` probes the capability and creates one persistent TAP per Ethernet bay/unit (4 units per bay, swept for stale leftovers first, born DOWN). uBridge holds a device's fd only while a kernel link binds the port; until then the TAP has no holder.
* **Life** — link churn never recreates the TAP. A kernel link adds `iol_bridge add_nio_tap <bridge> <iol_id> <bay> <unit> <tap>` then enslaves the anchor (`_kernel_attach`); a relay link keeps `iol_bridge add_nio_udp` and never touches the anchor. Switching a port between datapaths is just an NIO swap — the IOL port frees its previous NIO (fd or socket) on attach.
* **Death (node stop)** — the fd holder must let go before the devices are deleted. Here the holder is uBridge itself (on QEMU it is the VM's own process), so the uBridge side retires first: `iol_bridge delete` (releases every port's TAP fd) → `tap delete` per anchor (a held TAP answers EBADFD/207) → `brctl delete` for per-link bridges still held → stop uBridge. The IOU process is stopped last, holding no anchor fd — the reverse of QEMU's process-first sequence. Removing a single kernel link does the same in miniature: `_remove_kernel_nio` (markers, tc reset, delif, brctl delete) then `iol_bridge delete_nio_tap` — releasing the fd while the control channel lives.
## Link operations
| Operation | Kernel-datapath action |
|---|---|
| Create / attach | `iol_bridge add_nio_tap` (bind port ↔ anchor, uBridge holds the fd) + `brctl create` (EEXIST tolerated) + `link set <bridge> up` + `brctl addif` + capture/markers + `tc netem set` + carrier up |
| Delete / detach | marker teardown → `tc reset <tap>` → carrier off → `brctl delif`/`brctl delete` (last endpoint wins) → `iol_bridge delete_nio_tap` (release the fd; the device survives) |
| Update (filters/markers changed) | reconcile on the anchor only — no re-binding, no re-enslaving |
| Suspend | anchor admin-down (TAP-fd writes fail EIO → dropped; reads answer EIO too — the §B hardening tolerates both) + resume restores |
## Capture, markers, filters
Capture on a kernel link is `capture start_kernel <tap>` (driven by the NIO type); markers ride the base reconcile with the anchor as the location — IOU's marker primitives are polymorphic (`marker add_kernel/enable_kernel/delete_kernel` on an anchor, `iol_bridge … mark` on an IOL location), which let the old IOU-specific reconcile override be deleted outright. Filters are one tc netem qdisc per anchor plus cls_bpf/eBPF drops — the port's userspace `iol_bridge add_packet_filter` filters carry relay links only and are never combined with tc on the same port.
## Link-local frames (LACP, LLDP, 802.1X, STP)
The bridge stands in for a cable, but the kernel's `br_handle_frame()` does not forward the IEEE 802.1D reserved range (`01:80:c2:00:00:00`-`0f`) by default — LACP, LLDP/DCBX and 802.1X would never cross a kernel link while the UDP relay carries them fine. uBridge therefore opens every port's per-port `group_fwd_mask` (`IFLA_BRPORT_GROUP_FWD_MASK`) to `0xfffd` at `brctl addif` time (Linux 4.15+, best-effort on older kernels) — delivered by the fork's `feature/bridge-tap-l2only` branch (which also carries the `iol_bridge add_nio_tap` anchor work; a build from an earlier branch point leaves ports at the kernel default). The bridge-level knob cannot do this: `BR_GROUPFWD_RESTRICTED` rejects bits 0-2, so LACP is reachable per port only.
Result on kernel links: ordinary multicast, STP/RSTP, LACP, 802.1X and LLDP/DCBX all cross; **802.3x PAUSE / PFC does not** — `case 0x01` in `br_handle_frame()` drops it unconditionally and no mask can enable it. That is a documented limit, not a regression (PFC's hardware semantics are out of emulation's reach anyway); a lab that needs PAUSE frames on the wire must use a relay link. Verified live by `tests/e2e/test_docker_link_local_frames.py` (per-MAC guest-to-guest matrix, driven on the Docker datapath — the same per-link-bridge mechanism; the IOU e2e does not repeat it); the contract and kernel references live in `docs/design/ubridge-link-local-frame-forwarding-spec.md`.
## Relay fallback
A uBridge without `iol_bridge add_nio_tap` (old build) keeps the node on the relay datapath unchanged: every link rides `iol_bridge add_nio_udp`, the node starts fine, and the warning says it cannot carry kernel links. The controller never offers such a node a kernel link (capability unreported).
## Verified
Unit level: anchor lifecycle and naming, kernel/relay binding on add, update and remove, the stop order (iol_bridge delete before tap delete before brctl delete before uBridge stops), `_networking` on restart with mixed kernel/relay ports, capture and marker command shapes on both datapaths, the capability probe (cycle, old-build fallback, cleanup, caching), capability plumbing, and controller eligibility (per-compute capability, its independence from `ubridge_tap`, serial-port exclusion).
An isolated-instance validation run — a development harness that is not part of this repository: two IOU nodes behind a fake ELF image, the driver playing the IOL fabric on `/tmp/netio<uid>/` and pushing frames through it — passed **64/64 checks** on the kernel datapath and **62/62** on the relay (`enable_kernel_datapath = false`). Kernel highlights:
* 8 anchors per node (2 bays × 4 units), persistent, DOWN, address-free; `link_list` reports `kernel_datapath: true` and one per-link bridge holds both anchors with `brport/state = 3`;
* fabric → anchor → bridge → anchor → fabric in both directions at ~0.2 ms; `delay 100` ⇒ netem on both anchors and a measured **100.5 ms** one-way;
* suspend ⇒ anchor DOWN, no traffic, resume ⇒ 100.4 ms with the qdisc intact;
* capture ⇒ a 328-byte pcap written by `capture start_kernel`;
* link delete ⇒ bridge gone, qdisc clean, anchor alive, re-create at 0.6 ms;
* a **serial** link between the same two capable nodes stays on the relay (`kernel_datapath: false`) — per-port exclusion, not per-node;
* single-sided restart ⇒ stopped node's anchors removed, peer's kept, link re-attached from the NIO (0.3 ms); stop ⇒ no stray anchors, bridges or fabric sockets.
The relay run exercises the same lifecycle with the IOL UDP NIOs (no tc qdiscs, userspace `delay` at 100.7 ms, suspend via the synthetic frequency_drop, `iol_bridge start_capture`), which is also the regression net for the port-coordinate capture restore this work touched.
The repository's live e2e suite carries the same scenario with **real IOU routers** — the reproducible run in the tree (`tests/e2e/test_iou_kernel_datapath.py`, pytest marker `e2e`): a real L3 IOU image provides the fabric and the real IOS CLI on the server's telnet console, driving anchors-born-with-the-node, the §E.2 idle-silence window with the guests shut, real ICMP through the port bridge, netem delay, the TAP-anchor classifier spot check (bpf match-drop; the eBPF every-nth mode at 56 % measured round-trip loss, 55.6 % expected), suspend, capture, link delete/re-create, node stop/start rewiring with a delay filter restored on the fresh anchor (tc and traffic both), the serial link staying on the relay, and a relay negative control whose real `delay`/`frequency_drop` filters ride the port's `iol_bridge add_packet_filter` list — capture and markers on the same engine (`iol_bridge start_capture` / the port's `mark` filter).
The uBridge side passed its own 30/30 (`tests/iol/test_tap_anchor.py` in the fork), including the DOWN-anchor resilience and kernel-bridge interop this design depends on.
One pre-existing bug surfaced here and is fixed: the IOU NIO **update** route never copied the body's `suspend` onto the NIO (Docker and QEMU routes do). Harmless on the relay, where suspend is emulated by the synthetic frequency_drop filter, but fatal for a kernel link, whose suspend *is* the anchor's admin state — a "suspended" link kept forwarding.
**Measuring seeded impairments on IOU**: IOL emits CDP/keepalive frames of its own, and they draw from the netem RNG stream — a `seed`-reproducible run never matches while they are on (measured: three rounds of mismatches, then bit-identical pcaps after `no cdp run`). Turn the platform chatter off before comparing seeded runs; the extra frames are visible in the capture.
## Configuration
```ini
[Server]
# Wire eligible links (same compute, both endpoints Ethernet and able to
# anchor) through kernel interfaces instead of the uBridge UDP relay.
enable_kernel_datapath = True
```
## Roadmap
Dynamips has landed (see `dynamips-kernel-datapath.md` — the hypervisor opens uBridge-created TAPs, the same shape QEMU uses), and so has the Ethernet switch (see `ethernet-switch-kernel-datapath.md` — it absorbs the peer's anchor into its own kernel bridge). Switch-to-switch cascades (a veth pair between the two kernel bridges) have landed, and so has the IOL runner container — see `iol-docker-kernel-datapath.md` (same persistent-TAP shape, through the generic bridge module's swappable TAP leg instead of the IOL bridge). Cross-compute kernel links need VXLAN/GENEVE encapsulation — deferred until every node type is kernelized.
+361
View File
@@ -0,0 +1,361 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Marker Tag Replay (Aggregate Playback)
## Overview
Replays traffic captured by [markers](marker-traffic-insight.md) **across links**, keyed by
`tag`. Markers on different links that share a tag form one *distributed capture session*;
once every marker under the tag is paused, their per-marker pcaps are merged into a single
timestamp-ordered timeline. The Web UI browses that timeline (with Wireshark-style packet
list columns) and fetches individual frames on demand — each fetch decodes exactly one
frame via the resident **sharkd** daemon into a self-describing JSON protocol tree.
The unique observable: the delta between the same packet hitting two consecutive links
measures the **intermediate node's forwarding latency** (host view) — something a
single-link capture can never show.
**sharkd is a hard requirement** (part of the Wireshark package). Without it every replay
endpoint that needs the engine returns 501 — there is deliberately no degraded mode; one
engine, one rendering shape for the Web UI. (A tag whose sources captured nothing returns
an empty timeline without consulting the engine — an empty answer, not a degraded one.)
## Architecture
```mermaid
graph TB
UI["Web UI"]
subgraph Controller["Controller (replay endpoints)"]
GATE["Tag gate<br/>(all markers under tag paused?)"]
SCAN["Timeline backbone<br/>(pcap record-header scan,<br/>merge ordering, hex reads)"]
SESS["sharkd sessions<br/>(one per source pcap)"]
end
FS[("markers dir<br/>{node}_{link}_{marker}.pcap")]
TMP["/tmp scratch copies<br/>(hardened-profile workaround)"]
SK["sharkd -<br/>(resident JSON-RPC on stdio)"]
subgraph Remote["Remote compute"]
RFS[("its markers dir")]
end
UI -->|"GET range / frames [?filter=&link=]"| GATE
GATE --> SCAN
SCAN -->|"columns / filter matches"| SESS
SESS --> TMP --> SK
SCAN -->|"hex: raw bytes"| FS
RFS -->|"HTTP fetch → local cache"| SCAN
UI -->|"GET frame detail (lazy)"| SESS
```
Backbone vs engine, deliberately separated:
- **Timeline backbone** (plain Python): the tag gate, 16-byte-per-frame pcap record-header
scan, cross-source merge ordering, canonical ts strings, and raw-bytes reads for the hex
view. Identity and ordering never depend on the engine.
- **Engine layer (sharkd)**: packet-list columns, display filters, and per-frame protocol
trees. One resident `sharkd -` process per source pcap (sharkd loads one file at a
time), spawned lazily on first use, addressed with one-line JSON-RPC on stdio.
Session lifecycle: each session is validated per request against the source pcap's
`(mtime, size)` — a mismatch (e.g. the capture node restarted and uBridge truncated the
pcap while paused) kills and respawns it. Sessions are refcounted while a request holds
them and the LRU bound (16) only ever evicts **idle** sessions, so neither a request's
own walk over a tag with more sources than the bound nor a concurrent request can have
its session killed mid-RPC. A single manager lock makes check-spawn atomic (concurrent
requests share one spawn instead of double-spawning a process nobody reaps). Each RPC
is serialized by a per-session lock (sharkd serves one request at a time), carries a
timeout and an **id check** — any transport failure (timeout, dead pipe, malformed or
stale reply, oversized line) kills the session for good, because a desynchronized
session would serve shifted results. sharkd reads a `/tmp` scratch **directory**
containing a copy of the pcap plus pinned Wireshark preferences (the column layout the
frames RPC is parsed against is a contract the server owns, immune to system or user
column customization) — hardened profiles (AppArmor &c.) deny it the project directory
and the user's home even though the server process can read both. The pcap copy runs
off the event loop, and server shutdown kills every session so no scratch copy leaks
into `/tmp` across restarts.
Capture-file locality: a marker's pcap is written by uBridge on the compute hosting the capture node, so only local markers' pcaps sit in the controller's project directory. A remote marker's pcap is fetched through the compute's project-files API on every acquire into a bounded cache (32 idle files under `/tmp`, wiped at shutdown) — a paused marker's pcap holds matched packets only, so the refetch stays cheap. The cached copy is replaced only when the bytes changed, so an unchanged refetch keeps the previous file's mtime and the resident sharkd session keyed by it survives; for remote sources the per-request `(mtime, size)` validation runs against the cache copy. A compute that cannot be reached flags its source (`count: 0` plus an `error` message in `sources`) instead of silently shrinking the timeline; the frame-detail endpoint then answers 409 with the fetch failure.
### Resource bounds
Three independent bounds, easily confused:
| Bound | Value | Governs |
|-------|-------|---------|
| `_STREAM_LIMIT_BYTES` | 16 MB | Max **single JSON-RPC reply line** read from sharkd. A full 1000-row page measures ~190 KB against asyncio's 64 KB default — the trigger is the frame count in one pcap (≥ 1000), never the number of pcaps |
| `_FRAMES_PAGE` | 1000 | Rows fetched per `frames` RPC while draining one source's columns |
| `SESSION_MAX` | 16 | Resident **idle** sharkd sessions (LRU eviction) |
The `range` frame list itself is uncapped by decision — the client owns the
rendering cost of a huge list.
Process count follows usage, not the pcap inventory. sharkd loads one file per
process, so a session exists per source pcap **actually consulted** — a replay
request only touches its own tag's sources, and a session is either in use
(refcounted, held for a whole pagination drain rather than per RPC) or idle
(no holder — the only state the LRU cap ever evicts). At any moment the pool
holds at most `SESSION_MAX` idle sessions plus one per source being drained by
an in-flight request: a project with a thousand marker pcaps still runs at
most `16 + Σ(in-flight sources)` sharkd processes. Each process holds its pcap
in memory (~file size), which is the quantity the session cap primarily bounds.
## Business Process
```mermaid
sequenceDiagram
participant UI as Web UI
participant C as Controller
participant SK as sharkd session
Note over UI: ① configure — same tag on every link's marker
Note over C: ② capture — uBridge appends matches, replay forbidden (409)
Note over UI: ③ pause every marker under the tag
Note over UI,SK: ④ replay
UI->>C: GET /markers/tags/666/replay/range[?filter=…&link=…]
C->>C: gate → scan record headers → merge order
C->>SK: frames {filter, skip, limit} → columns + matches
C-->>UI: {start, end, sources, frames[] with src/dst/proto/info/bg/fg}
UI->>C: GET frames?ts=T&window_ms=W (paging — {"frames": []} on a miss)
UI->>C: GET frame/detail?ts=…&node_id=…&link_id=…&marker=…[&frame_number=…]
C->>C: hex straight from the pcap
C->>SK: frame {frame: N, proto: true}
SK-->>C: tree (keys renamed to the REST contract)
C-->>UI: protocol tree + hex
```
## The tag gate
Replay reads append-only pcaps, so it is only available while the data is at rest. Every
replay endpoint evaluates the same gate: walk every marker in the project carrying the
requested tag; if any has `enabled: true` → 409 (the response names them); a tag with no
markers at all → 404.
| Marker state under the tag | pcap file | Replay |
|---------------------------|-----------|--------|
| any `enabled: true` (capturing) | growing | denied — 409 |
| all `enabled: false` (paused) | retained, frozen | **allowed** |
| deleted | file unlinked | no data |
| `bpf`/`tag`/`direction` changed (rebuild) | pcap reopened (truncated) — new session | prior history gone |
| capture node (re)started | pcap reopened (truncated) — new session | prior history gone |
- **Pause, not delete.** Deleting a marker (or its definition) deletes its pcap — replay
before deleting or the data is gone.
- **Pause → resume → pause is fine.** The pcap accumulates the full history; replay covers
everything up to the current pause point.
- **The replay window ends when nodes restart.** A pcap's lifetime equals its uBridge's
lifetime: a fresh uBridge reinstalls every desired marker — paused ones too — and
uBridge opens the pcap with truncate semantics (`pcap_dump_open`, not `_append`). Server
restart + project reopen **without starting nodes** is safe: nothing touches the files
until a uBridge comes up. Docker nodes effectively restart on server restart as well
(stale-container cleanup), so their window is shorter still.
## API Endpoints
All read-only; JWT bearer token, privilege `Project.Audit`. All require sharkd — 501
without it.
| Method | Path | Description |
|--------|------|-------------|
| GET | `/v3/projects/{pid}/markers/tags/{tag}/replay/range[?filter=&link=]` | Timeline metadata + full merged frame list with packet-list columns |
| GET | `/v3/projects/{pid}/markers/tags/{tag}/replay/frames?ts=&window_ms=&limit=[&filter=&link=]` | Frames with ts in `[T, T+window]`, merged across sources |
| GET | `/v3/projects/{pid}/markers/tags/{tag}/replay/frame/detail?ts=&node_id=&link_id=&marker=[&frame_number=]` | Single frame: protocol tree + raw hex (lazy — one call per frame the user opens) |
### `range` — the timeline
```json
{
"tag": 102,
"start": "1788369209.406812",
"end": "1788369219.249085",
"frame_count": 29,
"sources": [
{ "node_id": "47703cad…", "link_id": "2697a7c6…", "marker": "global-ospf",
"data_link_type": "DLT_EN10MB", "count": 4, "error": null }
],
"frames": [
{ "ts": "1788369209.406812", "len": 114,
"node_id": "47703cad…", "link_id": "2697a7c6…",
"marker": "global-ospf", "frame_number": 1,
"src": "10.0.12.1", "dst": "224.0.0.5",
"proto": "OSPF", "info": "Hello Packet",
"bg": "fff3d6", "fg": "12272e" }
]
}
```
- `frames` is the **full, merged, time-ordered list** — one request lays out the whole
timeline, **deliberately uncapped**: rendering a huge list is the client's concern,
and the window endpoint exists for incremental views. There is no `truncated` flag
and no bucket histogram; `frame_count` always equals `len(frames)`.
- Every frame entry carries the Wireshark packet-list columns — `src` / `dst` / `proto`
/ `info` — plus the **coloring-rule hints `bg` / `fg`** (Wireshark's own palette
decisions, so the UI can color rows exactly like Wireshark without shipping the
colorization engine). Columns are `null` only for a frame the engine could not describe.
- Each frame entry carries `(node_id, link_id, marker, frame_number)` — the locating
tuple for the detail request, and the link association for timeline/topology rendering
(`link_id` joins the Web UI's own link objects).
### Display filter
`?filter=<expression>` on both `range` and `frames` is a Wireshark display filter,
applied **before** counting and slicing — `start` / `end` / `frame_count` / `frames`
are all computed on the matching frames only. Filtered frames keep
their original pcap frame numbers. The filter travels as one argv-style element (never
through a shell) and is capped at 2000 characters. An invalid expression is a **400**
whose message carries sharkd's original error text — suitable for inline display in the
filter bar, and distinct from the 409 gate / 404 unknown-tag semantics. Only sharkd's
filter-rejection error maps to 400; any other engine failure while a filter is set is a
502 (the filter was fine — the engine was not).
### Capture-source selection
`?link=<link_id>` on both `range` and `frames` narrows the frame stream to one
capture source — a pure identity filter applied **before** any engine work (only the
selected link's pcap gets a sharkd pass), AND-composing with `filter`. Windows and the
histogram therefore always agree with the link-filtered view. Two boundaries by
design:
- **`sources` is the stable inventory of the tag**: every capture source is always
listed, with engine-free **total** counts, unaffected by `link` / `filter` — a
source dropdown must not shrink when the view narrows. A source whose capture file
could not be fetched from its compute keeps its entry with `count: 0` and an `error`
message (compute unreachable) — a partial timeline must be visible as partial, never
mistaken for the whole capture.
- **An unknown `link_id` matches nothing**: `frame_count: 0`, `start: null`, empty
`frames` — the same shape as a zero-match display filter, deliberately not a 404.
### `frames` — point / window query (paging)
A time with no frames is a normal, successful answer — an empty array, no sentinel
strings:
```json
GET …/replay/frames?ts=1788196700.000&window_ms=500
→ { "frames": [] }
```
Paging is deliberately **ts + window_ms only** (no offset/limit over the filtered set):
the merge spans multiple pcaps, so slicing happens server-side on the merged stream
either way, windows align with timeline semantics, and the gate freezes the data (the
window answer is deterministic).
### `frame/detail` — lazy single-frame decode
Invoked only when the user opens a frame. The `ts` must be the **exact string received
in the timeline/frame list** (round-tripped verbatim — never re-serialized through a
float); `node_id + link_id + marker` identify the pcap. The server re-resolves the ts
against the file, guarding against a capture rebuilt between the timeline view and this
click. Since ts is **not unique within one pcap** (same-microsecond frames are kept
deliberately), the optional `frame_number` — carried by every frame list entry —
disambiguates them: it must still land on the exact ts, and without it the first ts
match decodes.
```json
{
"ts": "1788369209.406812",
"source": { "node_id": "47703cad…", "link_id": "2697a7c6…",
"marker": "global-ospf", "frame_number": 1 },
"field_count": 89,
"hex": "01005e000005…",
"tree": [
{ "element": "proto", "label": "Internet Protocol Version 4, …", "children": [
{ "element": "field", "name": "ip.ttl", "label": "Time to Live: 1",
"filter_expr": "ip.ttl == 1", "pos": 22, "size": 1, "children": [] }
] }
]
}
```
The tree is sharkd's protocol tree with **keys renamed into the REST contract** — a
closed, protocol-independent key set (census-verified across ICMP / TCP / VLAN+OSPF
trees and pinned by a test), with values untouched:
| sharkd | Contract key | Meaning |
|--------|--------------|---------|
| `t` | `element` | node type (`proto`, …) |
| `l` | `label` | display text |
| `fn` | `name` | field name (`ip.ttl`) |
| `f` | `filter_expr` | **ready-made display filter with the value baked in** — click-to-filter |
| `h` | `pos` + `size` | byte range — click field → highlight hex bytes |
| `s` | `expert` | expert severity name (`Chat` / `Warn` / …) |
| `g` | `generated` | generated-by-Wireshark flag |
| `n` | `children` | nested fields |
| `e` | *(dropped)* | Wireshark-internal hf id, unstable across versions |
Unknown keys from a newer Wireshark pass through verbatim (never silently dropped); a
census test flags new keys for naming. `hex` is the raw frame bytes read straight from
the pcap; `field_count` is the mapped node count (client-side sanity check).
## Ordering and timestamps
- `ts` is the pcap record timestamp (µs) written by uBridge at match time — a userspace
`gettimeofday()` instant measured after the packet has crossed the kernel twice. The
last digit or two are scheduling noise; microseconds are sufficient in a simulated
environment.
- The sort key is `(ts, source file, frame_number)` — ts alone is **not** unique (two
links can hit the same microsecond); the tiebreaker yields a stable, determined order
instead of a fictional one.
- The cross-link delta is the intermediate node's end-to-end forwarding latency
(veth/TAP → guest protocol stack → back to host), typically hundreds of microseconds to
milliseconds. UI labels should read *node forwarding latency (host view)*, not link
propagation delay. A live capture pair confirmed it end-to-end: same `ip.id`,
TTL 64→63, 509 µs between two links.
## Error Responses
All error bodies are `{"message": "…"}` (the app's unified format).
| Status | Description |
|--------|-------------|
| 400 | Invalid display filter (sharkd's filter rejection only; message carries its original text) or filter longer than 2000 chars |
| 401 | Not authenticated |
| 404 | Tag has no markers in the project; detail source unknown; `ts`/`frame_number` do not match the file (the capture may have been rebuilt); or the pcap vanished mid-request |
| 409 | Tag gate: a marker under the tag is still `enabled: true` (the response lists them); detail endpoint only — the compute hosting the capture file could not be reached (message names the compute) |
| 501 | sharkd not installed / unavailable — replay is unavailable, no degraded mode |
| 502 | sharkd failed, timed out (10 s per RPC), or answered out of sync — the session is killed and re-spawned on the next request |
## Notes
- **In-repo e2e coverage (2026-10).** `tests/e2e/test_marker_kernel_datapath.py` exercises
the whole contract against a paused tag on real marker pcaps: the `range` aggregate
(frame_count, sources inventory with the node/link/marker identity, first-frame
src/dst/proto from sharkd), the display filter narrowing (`icmp.type == 8`), the
unknown-link empty stream, the `frames` window endpoint, and the 409 gate while a
marker under the tag is still capturing.
- **Heterogeneous link types coexist.** Frames are never merged into a single pcap
(mergecap is deliberately not used) — each frame carries its source and is decoded
individually, so Ethernet and serial (cHDLC/PPP) markers can share one timeline.
Malformed packets are dissected like any other; sharkd marks them in the tree.
- **Live validation (2026-09, 9-link OSPF project, 29 frames over 9 sources).** Cold
`range` (spawning all sharkd sessions) answered in 0.84 s with full columns and
Wireshark coloring; filters verified in all four regimes (match / zero-match with
`start: null`, invalid expression → 400 with sharkd's text, oversized → 400); window
hit and miss behaved per contract; a frame detail returned 89 nodes with
`filter_expr: "ip.ttl == 1"` (OSPF multicast TTL) and byte ranges for hex
highlighting.
- **Columns are re-fetched per request** (~90 ms per source against a loaded session).
The data is frozen while the gate passes, so a cache keyed on `(mtime, size)` is a
natural follow-up if list latency ever matters at many-source scale.
- **Session invalidation is cheap and total.** Every request stats the source pcap; a
rewritten file (mtime/size change) respawns the session — a paused-but-restarted
capture can never serve stale dissect state. Transport failures are equally total: a
timeout, dead pipe, malformed or stale reply (id mismatch) kills the session instead
of leaving a poisoned one resident, and concurrent requests for the same pcap share a
single spawn.
- **The packet-list layout is pinned, not assumed.** sharkd runs with a scratch `HOME`
whose Wireshark preferences fix `gui.column.format` to exactly the four columns the
frame entries carry (personal config overrides any `/etc/wireshark` customization), so
the column indexes the server parses are a contract it owns.
- **Server shutdown kills every resident session** and drops its `/tmp` scratch
directory — nothing accumulates across restarts.
- **Tag type.** REST and the `marker.match` WS event both carry `tag` as `int` (the
listener normalizes); replay keys on that int value.
- **Follow-ups.** Convenience APIs (`GET …/markers/tags` to list tags, `POST …/markers/tags/{tag}/pause` to batch-pause — a one-call path to the replayable state); uBridge-side `pcap_dump_open_append` (with a linktype-header check on the existing file) so capture history survives node restarts instead of being truncated on every reinstall.
+397
View File
@@ -0,0 +1,397 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Marker (Traffic Insight)
## Overview
A **marker** is a passive traffic-insight tap attached to a link. It runs a libpcap BPF
expression inside uBridge; on every match uBridge emits a real-time `MARK` signal and
appends the matching packet to a per-marker pcap file. Markers exist at two layers that
coexist on the same link: **per-link private markers** and **project-level definitions**
that are inherited by every capable link.
## Architecture
```mermaid
graph TB
UI["Web UI"]
subgraph Controller["Controller"]
DEF["Project definitions<br/>(inheritance templates)"]
LNK["Per-link markers"]
end
Compute["Compute Node"]
UB["uBridge<br/>mark filter"]
PCAP[("pcap file")]
LSTN["Marker listener<br/>(UDP, per compute)"]
UI -->|"REST + notifications ws"| Controller
DEF -.->|"fan-out: global-{name}"| LNK
LNK -->|"node.post /markers"| Compute
Compute --> UB
UB -->|"BPF match"| PCAP
UB -->|"UDP MARK signal"| LSTN
LSTN -->|"marker.match"| UI
```
Inheritance is a controller-only fan-out: a definition CRUD loops over links and reuses the
existing per-link marker operations, so the compute side sees an ordinary marker and is
unchanged. Each compute process runs one UDP listener serving every uBridge on that host; the
`node` and `link` fields in each signal together identify the source link (see
[Per-link attribution](#per-link-attribution)).
On **kernel-datapath** links (see
[docker-kernel-datapath.md](docker-kernel-datapath.md)) there is no relay
bridge: the marker attaches directly to the veth host end via uBridge's
AF_PACKET marker module (`marker add_kernel`), with identical BPF matching,
signals, pcaps and REST operations. Deployment convention: only the capture
node's end carries the marker, so each exchange produces one clean
`tx`/`rx` signal pair.
## Business Process
```mermaid
sequenceDiagram
participant UI as Web UI
participant C as Controller
participant L as Capable Link
participant N as Compute / uBridge
UI->>C: POST /marker-definitions {name, bpf, ...}
C->>C: store definition
loop every capable link
C->>L: start_marker("global-{name}")
L->>N: install mark filter (BPF + pcap)
end
C-->>UI: 201 + link_ids
Note over N: later: a packet matches the BPF
N->>N: emit MARK signal + append pcap
N-->>UI: marker.match notification (per-project ws)
```
Updating a definition syncs `bpf / tag / color / highlight_duration` to every inherited
copy; deleting a definition removes every inherited copy. A newly created link inherits all
existing definitions automatically.
## Per-link attribution
A uBridge `MARK` signal carries `node`, `filter`, `link`, `tag`, and `len` — but no bridge
name. When one node is the capture side for several links — the common case for a project-level
`global-{name}` marker on a multi-interface router — `node` + `filter` alone are identical
across those links, so they cannot tell the signals (or pcap files) apart. The `link` field
resolves this:
1. At install time the controller stamps each filter with its link id
(`mark <bpf> [tag <id>] link <link_id> [pcap <path>]`).
2. uBridge treats `link` as opaque and echoes it verbatim in the signal (`link=<link_id>`).
3. The listener takes the signal's `link=` as the **authoritative** `link_id` of the
`marker.match` event, falling back to its registry only for legacy signals that carry no
`link=`.
This is also why the pcap path is keyed on link —
`<project>/markers/<node_id>_<link_id>_<filter>.pcap`, not on `bridge`+`filter`: a single
uBridge bridge can serve several links, and only the link id keeps their captures distinct.
### IOU: one bridge, many interfaces
IOU runs a single `IOL-BRIDGE` per node shared by every interface, so `bridge`+`filter` are
identical across that node's links. uBridge keeps a separate filter list **per port
(bay/unit)** within the bridge, so each interface gets its own `global-{name}` filter, its own
pcap file, and its own `link=`. The shared bridge name is irrelevant to attribution. Other
capable node types (`qemu`, `docker`, `vpcs`, `cloud`, `ethernet_switch`) already use one
bridge per link (the switch's per-port relay); `link` applies uniformly to all of them.
## Direction
A `MARK` signal optionally carries `dir=<tx|rx>` — the matched packet's travel direction
**relative to the capture node** (the `node=<id>` in the same signal, i.e. the node whose
uBridge hosts the marker):
| `dir` | Ingress NIO | Meaning |
|-------|-------------|---------|
| `tx` | device side (`source_nio` on a generic bridge; the IOL instance on an IOU `IOL-BRIDGE`) | capture node is **sending** |
| `rx` | link side (`destination_nio` on a generic bridge; the NIO side on an IOU `IOL-BRIDGE`) | capture node is **receiving** |
A marker is single-sided: only the chosen capture node's uBridge installs the `mark` filter,
yet both directions of the link transit that one bridge (it carries exactly two NIOs — the
device side and the link side), so that single uBridge observes and classifies both
directions. The `marker.match` event forwards `dir` through unchanged; the Web UI combines it
with the link's two endpoints and the capture `node_id` to draw an arrow:
- `dir=tx` → `capture_node → far_node`
- `dir=rx` → `far_node → capture_node`
- `dir` absent (older uBridge) → undirected highlight (current behaviour)
Because the listener ignores unknown keys, `dir` is **additive**: an older server silently
drops it and an older uBridge simply omits it — either way the system falls back to
undirected rendering with no error.
### Choosing the capture node
Since `dir` is relative to the capture node, *which* endpoint is the observer decides what
`tx`/`rx` mean. By default the server auto-picks (first started marker-capable endpoint, in
link-endpoint order). To pin it — e.g. so `dir=tx` unambiguously means "vpcs1 is sending" —
pass `capture_node_id` on marker **create**:
```json
{ "bpf": "icmp", "direction": "tx", "capture_node_id": "<vpcs1 node uuid>" }
```
The value must be one of the link's two endpoints and a marker-capable type (`vpcs`, `qemu`,
`docker`, `iou`, `dynamips`, `cloud`, `ethernet_switch`); any other id is rejected with `409`. Omit it to keep
the auto-pick. The chosen id is echoed back as `capture_node_id` in the marker entry and in
each `MARK` signal's `node=<id>`, so the Web UI always knows the observer regardless of who
picked it.
`capture_node_id` is **create-only**: it is fixed once the marker exists (changing the
observer would silently flip the meaning of stored `direction`, so recreate the marker
instead). It is not accepted on project-level definitions — a definition is link-agnostic and
has no endpoints to choose from, so inherited markers always auto-pick per link.
For the same reason, a definition **rejects `direction: tx|rx`** (HTTP 409): each inherited
copy auto-picks its capture node, so a fixed tx/rx would denote different session directions
on different links. A definition is `both` only; encode the direction you want in the BPF
instead — e.g. `icmp and icmp[icmptype]==8` for echo requests, a packet-intrinsic property
that is consistent on every link regardless of capture node. tx/rx remains available on
per-link markers, where the capture node is fixed.
## Pause & resume
Two levels of silencing, both instant (no NIO rebuild, no pcap flush):
- **Per-marker (private)** — `PUT /v3/projects/{pid}/links/{lid}/markers/{name}`
with `{"enabled": false}` flips that one filter off in place (uBridge
`enable_packet_filter … off`): no signal, no pcap, but traffic still relays —
a paused `mark` is a no-op tap, not a drop. `{"enabled": true}` flips it back.
A change to `enabled` alone is a single command (the pcap identity and emitted
counter are preserved). Changing `bpf`, `tag`, or `direction` rebuilds just that
one filter (`delete_packet_filter` + add) — only that marker's own pcap reopens
(a new capture session for the new BPF); changing `color`/`highlight_duration`
is UI-only, nothing is pushed to uBridge.
- **Per-definition (inherited)** — `POST /v3/projects/{pid}/marker-definitions/{name}/pause`
and `/resume` toggle **every** inherited `global-{name}` copy across all links
at once (same `enable_packet_filter on|off`, fanned out per copy). Use to
pause or resume a whole rule independently of the others. The definition's
`paused` flag is persisted to the `.gns3` and echoed on the definition object,
so links created later inherit it already paused, and the Web UI renders the
per-rule button from server truth.
| Action | signal | pcap | sink |
|--------|--------|------|------|
| per-marker `enabled: false` | stop | stop | n/a |
| per-def `pause` (all `global-{name}` copies) | stop | stop | n/a |
| per-def `resume` | resume | resume | n/a |
## Capture files
Each marker appends matches to `<project>/project-files/markers/<node_id>_<link_id>_<filter>.pcap`.
Removing a marker — per-link `DELETE .../markers/{name}` or deleting a definition (which
removes every inherited copy) — deletes that marker's pcap too, even with the capture node
stopped (the filter is removed with `delete_packet_filter`, the file is unlinked). uBridge's
`reset_packet_filters` (run on NIO/filter changes) preserves mark filters, so unrelated
changes no longer close/reopen any marker's pcap.
## API Endpoints
All endpoints require a JWT bearer token (`POST /v3/access/users/authenticate`). The
`Auth` column lists the required privilege.
### Per-link markers
| Method | Path | Description | Auth |
|--------|------|-------------|------|
| GET | `/v3/projects/{pid}/links/{lid}/markers` | List markers on a link | Link.Audit |
| POST | `/v3/projects/{pid}/links/{lid}/markers` | Attach a marker | Link.Modify |
| PUT | `/v3/projects/{pid}/links/{lid}/markers/{name}` | Update a marker | Link.Modify |
| DELETE | `/v3/projects/{pid}/links/{lid}/markers/{name}` | Remove a marker | Link.Modify |
### Project-level definitions
| Method | Path | Description | Auth |
|--------|------|-------------|------|
| GET | `/v3/projects/{pid}/marker-definitions` | List definitions + bound `link_ids` | Project.Audit |
| POST | `/v3/projects/{pid}/marker-definitions` | Create definition (fans out to every link) | Project.Modify |
| PUT | `/v3/projects/{pid}/marker-definitions/{name}` | Update definition (syncs all copies) | Project.Modify |
| DELETE | `/v3/projects/{pid}/marker-definitions/{name}` | Delete definition (clears all copies) | Project.Modify |
| POST | `/v3/projects/{pid}/marker-definitions/{name}/pause` | Pause every inherited copy (instant, persisted) | Project.Modify |
| POST | `/v3/projects/{pid}/marker-definitions/{name}/resume` | Resume every inherited copy | Project.Modify |
### Aggregation
| Method | Path | Description | Auth |
|--------|------|-------------|------|
| GET | `/v3/projects/{pid}/markers` | All markers across links, flat | Project.Audit |
The link object returned by `GET /v3/projects/{pid}/links[/{lid}]` also carries a `markers`
field (including inherited markers), so the Web UI can render a link's markers without an
extra request.
## Request / Response
**Marker create body** (`MarkerCreate`, shared by per-link POST and PUT):
```json
{
"name": "icmp",
"bpf": "icmp",
"tag": 1,
"direction": "tx",
"capture_node_id": "a37e2235-e21f-46c9-a2ab-ba0f8c5465e6",
"color": "#ff5722",
"highlight_duration": 800,
"enabled": true
}
```
`direction` and `capture_node_id` are both optional and create-only (see
[Direction](#direction)).
**Definition create body** (`MarkerDefinitionCreate`, shared by POST and PUT):
```json
{
"name": "arp",
"bpf": "arp",
"tag": 5,
"color": "#ff5722",
"highlight_duration": 1200
}
```
**Marker entry** (returned by GET/POST/PUT, and the value of each link's `markers[name]`):
```json
{
"bpf": "icmp",
"tag": 1,
"enabled": true,
"color": "#ff5722",
"highlight_duration": 800,
"capture_node_id": "a37e2235-e21f-46c9-a2ab-ba0f8c5465e6",
"inherited_from": null
}
```
**Definition GET response** (adds `link_ids`):
```json
{
"arp": {
"bpf": "arp",
"tag": 5,
"color": null,
"highlight_duration": 1200,
"direction": null,
"paused": false,
"link_ids": ["656ed826-...", "6bd9d156-..."]
}
}
```
## Field Reference
### Marker entry
| Field | Type | Description |
|-------|------|-------------|
| `bpf` | string | libpcap BPF expression (required) |
| `tag` | int \| null | Correlation id echoed in `MARK` signals |
| `enabled` | bool | Whether the marker is active. Toggle is instant: `false` flips the uBridge filter off in place (no signal/pcap), `true` back on — no NIO rebuild (see [Pause & resume](#pause--resume)) |
| `color` | string \| null | Hex color render hint, e.g. `#ff5722` |
| `highlight_duration` | int \| null | UI highlight duration in ms after a match; `null` = UI default |
| `direction` | string \| null | `tx` / `rx` filter relative to the capture node; `null` = both |
| `capture_node_id` | string | Node whose uBridge hosts the marker — caller-set on create, else auto-picked |
| `inherited_from` | string | Source definition name — present on inherited markers only |
### Definition
| Field | Type | Description |
|-------|------|-------------|
| `bpf` | string | libpcap BPF expression (required) |
| `tag` | int \| null | Correlation id |
| `color` | string \| null | Hex color render hint |
| `highlight_duration` | int \| null | UI highlight duration in ms; `null` = UI default |
| `direction` | string \| null | `tx` / `rx` filter relative to the capture node; `null` = both |
| `paused` | bool | Per-definition mute flag — `true` mutes every inherited copy (persisted) |
| `link_ids` | string[] | Links currently carrying an inherited copy (GET only) |
### Notifications
| Event | Payload | Delivered to |
|-------|---------|--------------|
| `link.updated` | Link object (its `markers` field is the source of truth) | Project notification ws |
| `marker.match` | `project_id`, `node_id`, `link_id`, `filter`, `tag`, `ts`, `len`, `dir` | Project notification ws only |
The `marker.match` `link_id` is taken from the signal's `link=` field (authoritative); see
[Per-link attribution](#per-link-attribution). The `dir` field is the matched packet's travel
direction relative to the capture node; see [Direction](#direction).
## Error Responses
| Status | Description |
|--------|-------------|
| 401 | Not authenticated |
| 404 | Link / marker / definition not found |
| 409 | Per-link edit or delete of an inherited marker; reserved (`global`) name or duplicate name on create |
| 422 | Validation failure (name format, `highlight_duration < 1`, missing `bpf`) |
## Notes
- **Live e2e coverage.** `tests/e2e/test_marker_kernel_datapath.py` drives two real
Alpine containers over a kernel-only link with markers attached to a veth anchor
(`marker add_kernel`): it asserts the exact `marker.match` identity on the dedicated
marker WebSocket (filter/tag/link_id/node_id/ts/len and the tx/rx direction set of a
ping), that the main project channel carries no `marker.match`, that a non-matching
BPF and a `tx`-directioned sibling each see exactly their intended traffic, the host
pcap frame count, pause/resume silence counting against a still-firing sibling,
marker delete removing the pcap and silencing signals, and the empty marker
directory at the end.
- **Marker name is immutable.** It is the identifier across the controller, the uBridge
filter, the pcap filename, and `MARK` signal routing — so rename is a delete + recreate,
not a field update. PUT ignores the body `name`; the `{name}` path parameter identifies
the target, and only `bpf / tag / color / enabled / highlight_duration` are changeable.
Names are 1–32 chars (`[A-Za-z0-9][A-Za-z0-9_.-]*`); inherited copies carry a `global-`
prefix, so their filter names reach ~39.
- **`global` prefix reserved.** User-chosen names may not start with `global`; inherited
markers are stored as `global-{definition_name}` so the two namespaces cannot collide.
Omitting `name` on create yields an auto-generated, prefix-free name.
- **Inherited markers are read-only per-link.** PUT/DELETE on an inherited marker returns
409 — edit them through the definitions API.
- **Render hints are not enforced.** `color` and `highlight_duration` (milliseconds, `>= 1`)
are stored on the link and never sent to uBridge; `null` lets the UI apply its own
default. A partial PUT (e.g. changing only `bpf`) leaves them untouched.
- **BPF is validated once per source.** A private per-link marker validates its BPF inline
on create/update. A definition validates its BPF once at create/update (and once per
definition on project load, dropping any whose BPF has gone invalid); the inherited
fan-out to every link then skips re-validation, so creating a definition over *N* links
runs one `tcpdump -d` rather than *N*. (uBridge still runs `pcap_compile` itself at
install time, so an invalid expression can never slip through.)
- **Supported node types.** A marker needs a uBridge bridge: `vpcs`, `qemu`, `docker`,
`iou`, `dynamips`, `cloud`, `ethernet_switch` (one capable endpoint suffices). The
`ethernet_switch` hosts markers on its per-port uBridge relays (brctl backend); the
`ethernet_hub` is still Dynamips-hosted and has no uBridge. Types without a uBridge are
silently skipped by the inheritance fan-out. IOU uses one shared `IOL-BRIDGE` per node but
keeps filters, pcap files, and `link=` ids per port, so multi-interface nodes are handled
(see [Per-link attribution](#per-link-attribution)).
- **Shared capture-side node.** When one node hosts markers for several links (typical for
`global-*` definitions on a router), each filter is stamped with its `link_id` so signals
and pcap files stay link-distinct; the controller never collapses them to a single link.
- **Persistence.** Definitions and private markers persist in the topology; inherited
markers are re-created from definitions on project load, so reopening a project restores
the same configuration and stale inherited copies cannot survive on disk.
- **Log interpretation across node types.** Each node type logs its startup and link
operations differently — do not mistake sparse logs from one type for inactivity.
QEMU prints `set_link gns3-<N> on` via its QEMU monitor, which is the most visible
startup log among all types. VPCS, Docker, IOU, Dynamips, and Cloud each have their own
startup paths (fork + ubridge, container veth, iouyap, Dynamips hypervisor, and TAP
device respectively) and none of them emit QEMU-monitor-style logs. To verify marker
operations (toggle, pause, resume) on non-QEMU types, either inspect uBridge's
own log for `enable_packet_filter` / `marker pause` / `marker resume` commands, or
watch the gns3server log for the corresponding compute-route calls at INFO level.
+559
View File
@@ -0,0 +1,559 @@
# MCP (Model Context Protocol) Service
## Overview
GNS3 Server provides a standard [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) interface, allowing AI assistants like Claude to interact with GNS3 network simulations through the Streamable HTTP transport (the SSE transport was deprecated in the MCP specification on 2025-06-18).
The MCP service exposes GNS3 project management operations as MCP tools that can be discovered and called by MCP clients.
## Endpoints
| Path | Method | Description |
|------|--------|-------------|
| `/v3/mcp/` | GET | MCP service metadata |
| `/v3/mcp/transport` | POST | JSON-RPC requests (initialize, tools/list, tools/call, notifications) |
| `/v3/mcp/transport` | GET | Optional server-to-client event stream (opened after initialize) |
| `/v3/mcp/transport` | DELETE | Session termination |
The server assigns a session on `initialize` and returns it in the `Mcp-Session-Id` response header; subsequent requests carry it back as a request header.
## Authentication
Every request to `/v3/mcp/transport` is authenticated. Two types of credentials are supported, passed either way.
1. **Authorization header** (recommended):
```
Authorization: Bearer <jwt_or_api_key>
```
2. **Query parameter** (for clients that can't set headers, e.g. browser EventSource):
```
GET /v3/mcp/transport?token=<jwt_or_api_key>
```
### Option 1: JWT Token (24h expiry)
```bash
curl -X POST http://localhost:3080/v3/access/users/authenticate \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "admin"}'
```
Default lifetime is **1440 minutes (24 hours)**. Configurable in `gns3_server.conf`:
```ini
jwt_access_token_expire_minutes = 1440 ; 24 hours
```
### Option 2: API Key (permanent, revocable) — Recommended for MCP
API keys never expire and can be revoked individually. Format: `gns3_<api_key_id>_<random_secret>` — the embedded UUID enables O(1) lookup without scanning all keys.
Create one via the REST API:
```bash
# Create an API key (requires a JWT to authenticate)
curl -X POST http://localhost:3080/v3/access/api-keys \
-H "Authorization: Bearer <your_jwt>" \
-H "Content-Type: application/json" \
-d '{"name": "MCP Production"}'
# Response: {"api_key": "gns3_550e8400-e29b-41d4-a716-446655440000_a1b2c3d4...", ...}
# ⚠️ The key is only shown once — save it immediately.
```
API key management endpoints:
| Endpoint | Description |
|----------|-------------|
| `POST /v3/access/api-keys` | Create a new key (returns plaintext once) |
| `GET /v3/access/api-keys` | List all your keys |
| `POST /v3/access/api-keys/{id}/revoke` | Revoke a key (can be restored) |
| `POST /v3/access/api-keys/{id}/restore` | Restore a revoked key |
| `DELETE /v3/access/api-keys/{id}` | Permanently delete a key |
Both JWT tokens and API keys work for MCP and REST API endpoints interchangeably.
### Authentication Flow
When connecting with an API key:
```
POST initialize → Authorization: Bearer gns3_<uuid>_<secret>
↓
MCP auth wrapper extracts UUID → single DB query → 1 bcrypt (thread pool)
↓
Generates a fresh 24h JWT → stored in ContextVar for the session
↓
Tool handlers run in the session task created by that request → they use this JWT
↓
Later requests re-validate the credential (result cached ~5 min → no repeated bcrypt)
↓
Once the session's JWT ages past its 24h lifetime, tool handlers renew it
from the API key automatically — long-lived sessions keep working
```
### Concurrency
| Setting | Value |
|---------|-------|
| MCP batch workers | 100 (`BATCH_MAX_WORKERS`) |
| MCP HTTP client timeout | 30s |
| HTTP connection pool (`pool_connections`/`pool_maxsize`) | 500 / 1000 |
| REST API node/link creation pool | 100 (`Pool(concurrency=100)`) |
## Available Tools
**80 tools** across 11 categories:
### Project (14)
| Tool | Description |
|------|-------------|
| `project_list` | List all projects |
| `project_get` | Get project details |
| `project_create` | Create a project |
| `project_delete` | Delete a project |
| `project_open` | Open a closed project |
| `project_close` | Close an open project |
| `project_stats` | Get project statistics |
| `project_update` | Update project properties |
| `project_duplicate` | Duplicate a project |
| `project_readme_get` | Get project README content |
| `project_readme_update` | Update project README |
| `project_lock` | Lock project (prevent edits) |
| `project_unlock` | Unlock project |
| `project_locked` | Check if project is locked |
### Node (22)
| Tool | Description |
|------|-------------|
| `node_list` | List all nodes (`fields` to filter columns, e.g. `["name","status"]`) |
| `node_get` | Get node details (`fields` to filter columns) |
| `node_create` | Create node(s) — single via `template_id` or batch via `nodes` array. Supports `fields` to filter response. Top-level `template_id` applies as default in batch mode. Pass `name` to override template naming. Coordinates: left-handed Cartesian (origin at canvas center, X right-positive, Y down-positive). |
| `node_delete` | Delete a node |
| `node_update` | Update node properties |
| `node_start` | Start node(s) — `node_id` or `node_ids` array |
| `node_stop` | Stop node(s) — `node_id` or `node_ids` array |
| `node_suspend` | Suspend node(s) — `node_id` or `node_ids` array |
| `node_console_exec` | Run commands on a node's console (one call = one complete session) |
| `node_file_list` | List files in node directory |
| `node_file_get` | Read a file (with offset/limit) |
| `node_file_write` | Write a file |
| `node_file_delete` | Delete a file |
| `node_start_all` | Start all nodes |
| `node_stop_all` | Stop all nodes |
| `node_suspend_all` | Suspend all nodes |
| `node_duplicate` | Duplicate a node |
| `node_isolate` | Isolate a node (suspend links) |
| `node_unisolate` | Un-isolate a node (resume links) |
| `node_links` | List links connected to a node |
### Link (9)
| Tool | Description |
|------|-------------|
| `link_list` | List all links (`fields` to filter columns) |
| `link_get` | Get link details |
| `link_create` | Create link(s) — single via `nodes` or batch via `links` array. Nodes support compact `[id, ad, pt, id, ad, pt]` format. Supports `fields` to filter response. |
| `link_delete` | Delete link(s) — `link_id` or `link_ids` array |
| `link_update` | Update link (suspend, filters) |
| `link_reset` | Reset link(s) — `link_id` or `link_ids` array |
| `link_capture_start` | Start capture(s) — `link_id` or `link_ids` array |
| `link_capture_stop` | Stop capture(s) — `link_id` or `link_ids` array |
| `link_capture_download` | Get PCAP download URL(s) — `link_id` or `link_ids` array |
### Template (5)
| Tool | Description |
|------|-------------|
| `template_list` | List all templates. Supports `fields` to filter response columns. |
| `template_get` | Get template details |
| `template_create` | Create a template (Docker needs `image`) |
| `template_update` | Update a template |
| `template_delete` | Delete a template |
### Compute (3)
| Tool | Description |
|------|-------------|
| `compute_list` | List registered remote computes |
| `compute_get` | Get compute details (requires UUID) |
| `compute_images` | List emulator images on a compute |
### Snapshot (4)
| Tool | Description |
|------|-------------|
| `snapshot_list` | List snapshots |
| `snapshot_create` | Create a snapshot |
| `snapshot_delete` | Delete a snapshot |
| `snapshot_restore` | Restore a snapshot |
### Drawing (5)
| Tool | Description |
|------|-------------|
| `drawing_list` | List drawings on canvas |
| `drawing_get` | Get drawing details |
| `drawing_create_text` | Create a text label (SVG assembled server-side, Web UI compatible) |
| `drawing_create_rectangle` | Create a rectangle annotation |
| `drawing_create_ellipse` | Create an ellipse/circle annotation |
| `drawing_update` | Update drawing (position, rotation, SVG) |
| `drawing_delete` | Delete a drawing |
<!--
Symbol tools (symbol_list / symbol_get / symbol_dimensions /
symbol_defaults / symbol_upload / symbol_delete) are disabled for now:
they require a vision-capable model to be genuinely useful. Revisit later.
-->
### Appliance (3)
| Tool | Description |
|------|-------------|
| `appliance_list` | List appliances (`fields` to filter, e.g. `["name","category"]`) |
| `appliance_get` | Get appliance details |
| `appliance_install` | Create template from appliance (images must exist locally) |
### Image (5)
| Tool | Description |
|------|-------------|
| `image_list` | List all images |
| `image_get` | Get image details |
| `image_delete` | Delete an image |
| `image_prune` | Remove images not referenced by any template |
| `image_install` | Auto-create templates from uploaded images by checksum |
### Server (2)
| Tool | Description |
|------|-------------|
| `server_version` | Get GNS3 server version |
| `server_statistics` | Get server statistics (computes, projects, nodes) |
### Device Config & Skills (5)
| Tool | Description |
|------|-------------|
| `device_config_send` | Push config commands to devices via console (Nornir + Netmiko), batch and parallel. Supports Jinja2 `template` + `vars` |
| `device_show_run` | Run read-only show commands on devices (whitelist-enforced). Supports Jinja2 `template` + `vars` |
| `vpcs_config_set` | Configure VPCS devices in batch (Nornir + Netmiko, parallel, VPCS command syntax validated) — the VPCS counterpart of `device_config_send` |
| `device_skill_get` | Read device knowledge from the GNS3-Skills repository (list → topic index → single topic; same access protocol as the copilot's `device_skills` tool) |
| `injection_skill_get` | Read fault-injection knowledge from the GNS3-Skills repository (topology context → fault category → single fault; same protocol as the copilot's `injection_skills` tool) |
**Which tool when** — the console-facing tools divide the work by shape:
| Scenario | Use |
|---|---|
| Push the same-shaped config to many network devices, one call | `device_config_send` (Jinja2 template + parallel fan-out) |
| Configure many VPCS PCs in one call | `vpcs_config_set` (parallel, VPCS syntax validated) |
| Inspect many devices read-only, one call | `device_show_run` (command whitelist — safe for AI) |
| Network OS console, any interaction | `device_config_send` / `device_show_run` (batch drivers manage config mode themselves) |
| Unfamiliar device: read its quirks before driving the console | `device_skill_get` (list first, then fetch by key) |
| Practise troubleshooting: inject a realistic fault | `injection_skill_get` (list with the topology's protocols, then one fault) + `device_config_send` |
| Any console interaction outside those drivers (incl. Docker/Linux nodes) | `node_console_exec` (one call = one session, plain-text output) |
The tool connects to each device's console via telnet/SSH. Nodes must be in the `started` state (use `node_start` or `node_start_all`). Device type is auto-detected from the node's `device_type:<type>` tag in GNS3.
#### Jinja2 Template Mode
Both `device_config_send` and `device_show_run` support an optional `template` parameter. When provided, each device's `vars` dict is rendered against the template to produce commands. Entries with the same `device_name` are merged into a single device session.
```python
# Direct commands (single/batch)
device_config_send(
project_id,
device_configs=[
{"device_name": "R1", "config_commands": ["int lo0", "ip add 1.1.1.1 255.255.255.255"]},
],
)
# Jinja2 template (reduces token usage for batch)
device_config_send(
project_id,
template="interface lo{{ n }}\nip address {{ ip }} 255.255.255.255",
device_configs=[
{"device_name": "R1", "vars": {"n": 0, "ip": "1.1.1.1"}},
{"device_name": "R2", "vars": {"n": 0, "ip": "2.2.2.2"}},
],
)
# Show commands with template
device_show_run(
project_id,
template="show ip route {{ protocol }}",
device_configs=[
{"device_name": "R1", "vars": {"protocol": "ospf"}},
{"device_name": "R2", "vars": {"protocol": "bgp"}},
],
)
```
### Best Practices
**Prefer template over direct commands for batch.** When ≥2 nodes share the same config structure with different values, use `template`+`vars` instead of writing `config_commands` per node. This reduces token usage and transcription errors.
**Batch merging.** Multiple entries with the same `device_name` are merged into a single Nornir session. The output contains all commands' results in one block. Match results by `device_name`, not list index.
**Don't rely on `status: success` alone.** It only means commands entered config mode. IOS errors (`% Invalid input`, `% overlaps`, `% Incomplete command`) appear inside `output` text — always scan for `%` lines.
**Pilot before full rollout.** Test template + vars on 1–2 devices first to verify rendering and syntax, then expand to all nodes.
**Config backup via file operations.** IOU and Dynamips nodes save startup config as a plain text file (`startup-config.cfg`) in the node directory after `write memory`. These can be backed up and restored via `node_file_get`/`node_file_write`.
```python
# Save config on device
device_show_run(
project_id,
device_configs=[
{"device_name": "R1", "commands": ["write memory"]},
],
)
# Backup
config = node_file_get(project_id, node_id, "startup-config.cfg")
# Restore if config breaks
node_file_write(project_id, node_id, "startup-config.cfg", config)
node_stop(project_id, node_id)
node_start(project_id, node_id)
```
#### Device Skills (`device_skill_get`)
The GNS3-Skills repository (the same one the embedded copilot reads) carries per-device operational knowledge that the generic tools cannot know: FRR's console lands directly in vtysh (its ping has no `-c`, scripted config needs `do` prefixes), VPCS command syntax, IOS paging pitfalls, SR Linux's TUI-only CLI. `device_skill_get` exposes it to MCP clients with the copilot's multi-call protocol — list, then the device's topic index, then one targeted body:
```python
device_skill_get(action="list") # 1. every loaded skill
device_skill_get(action="list", category="device") # optional category filter
device_skill_get(device_type="frr_vtysh") # 2. that device's skill + topic index
device_skill_get(device_type="frr_vtysh", topic="bgp") # 3. one targeted topic body
device_skill_get(device_type="gns3_vpcs_telnet") # single-file device: complete skill
```
Step 2 returns the base skill plus the topic index; topic bodies load **only** on an explicit `topic` request (step 3). The key is passed back exactly as step 1 returned it.
The repository ships two device layouts: split directories (`device/frr/` = `_base.yaml` + one file per protocol topic) and single files (`device/vpcs.yaml`). Single-file skills have **no topics** — step 2 with the default `full` detail returns the complete skill and there is no step 3. On such a skill, `detail="index"` returns a `sections` list (`config_commands`, `display_commands`, `notes`, ...) instead of an empty body, so the caller knows there is content to fetch.
#### Fault Injection Skills (`injection_skill_get`)
The same repository carries fault-injection knowledge for troubleshooting practice: per protocol, a set of realistic faults with symptoms, injection commands and verification steps. The list step is **context-filtered** — it requires the protocols/services found in the topology:
```python
injection_skill_get(action="list", context=["ospf", "bgp"]) # 1. matching fault categories
injection_skill_get(device_type="injection_ospf_issues", detail="index") # 2. fault names in that category
injection_skill_get(device_type="injection_ospf_issues",
issue="ospf_hello_dead_mismatch") # 3. one fault's full detail
```
`context` is matched case-insensitively against each skill's category, key and declared `protocols`, so aliases such as `ebgp` and `ospfv3` work. Category keys are derived from the repository filenames (`injection_<file>_issues`) — always pass the key returned by step 1. Step 3 returns the injection commands; apply them with `device_config_send` and verify with `device_show_run`.
### Device Config Workflow
```mermaid
sequenceDiagram
participant AI as AI Agent
participant MCP as MCP Handler
participant TM as Template Renderer
participant DP as Device Discovery
participant NR as Nornir
participant NM as Netmiko
participant D as Device Console
Note over AI: Decide: template or direct commands?
alt Direct commands
AI->>MCP: device_config_send(config_commands=[...])
else Jinja2 template
AI->>MCP: device_config_send(template + vars)
MCP->>TM: Render template per device
TM->>TM: Jinja2.render(**vars)
TM-->>MCP: device_configs with rendered commands
end
MCP->>DP: get_device_ports_from_topology()
DP-->>MCP: hosts_data (console port, device_type)
Note over MCP: Prepare Nornir inventory
MCP->>NR: InitNornir(hosts, threaded runner)
par Device 1 to N (parallel, max 10)
NR->>NM: netmiko_send_config(commands)
NM->>D: telnet/SSH console session
D-->>NM: command output
NM-->>NR: execution result
end
NR-->>MCP: aggregated results
MCP-->>AI: per-device results with output
```
## Configuration
### Claude Code (CLI)
```bash
# Option A: Using API key (recommended — never expires)
claude mcp add --transport http My_GNS3_Server \
http://localhost:3080/v3/mcp/transport \
-H "Authorization: Bearer gns3_a1b2c3d4..."
# Option B: Using JWT token (expires after 24h)
TOKEN=$(curl -s -X POST http://localhost:3080/v3/access/users/authenticate \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "admin"}' | python3 -c \
"import sys,json; print(json.load(sys.stdin)['access_token'])")
claude mcp add --transport http My_GNS3_Server \
http://localhost:3080/v3/mcp/transport \
-H "Authorization: Bearer $TOKEN"
```
Verify and manage the registration:
```bash
claude mcp list # health check — should show ✓ Connected
claude mcp remove My_GNS3_Server
```
By default the server is registered for the current directory only. Use `--scope user` to make it available in all projects:
```bash
claude mcp add --scope user --transport http My_GNS3_Server \
http://localhost:3080/v3/mcp/transport \
-H "Authorization: Bearer gns3_a1b2c3d4..."
```
## Transport Security
MCP server uses the MCP SDK's DNS rebinding protection to prevent attackers from
exploiting DNS resolution to access the MCP endpoint through unauthorized domains.
### Default Behaviour
DNS rebinding protection is **disabled by default**, allowing connections from
any host. This aligns with GNS3 server's default `host = 0.0.0.0` binding policy,
which is designed for VM distribution scenarios where users access the server
from various network locations.
### Enabling Protection
Add to `gns3_server.conf` under the `[Server]` section:
```ini
; Enable DNS rebinding protection for MCP server
mcp_enable_dns_rebinding_protection = True
; Allowed hosts (comma-separated, "host:*" port wildcard patterns only)
mcp_allowed_hosts = 127.0.0.1:*,localhost:*,192.168.1.3:*
; Allowed origins (comma-separated)
mcp_allowed_origins = http://127.0.0.1:*,http://localhost:*,http://192.168.1.3:*
```
> **Note**: The MCP library only supports `"host:*"` port wildcard patterns
> (e.g., `"192.168.1.3:*"`). Standalone `"*"` wildcards are not supported.
### Protection Mechanism
When protection is enabled, the MCP server validates the `Host` header of
incoming MCP requests:
```python
# Verify the request's Host header matches allowed patterns
validate_request → check Host header → 421 Misdirected Request if invalid
```
This prevents DNS rebinding attacks:
1. Attacker registers `evil.com` pointing to your server's IP
2. User's browser makes requests to `evil.com:3080`
3. MCP server checks Host header = `"evil.com:3080"`
4. `"evil.com:3080"` is not in `allowed_hosts` → connection rejected
### Behaviour Summary
| `mcp_enable_dns_rebinding_protection` | Result |
|:---|:---|
| `False` (default) | All hosts allowed |
| `True` + correct hosts configured | Only configured hosts allowed |
| `True` + missing/wrong hosts | Connections rejected with 421 |
For public-facing MCP servers, set `allowed_hosts` to your server's domain name.
## Architecture
```mermaid
sequenceDiagram
participant Client as Claude Code
participant MCP as MCP Service
participant Auth as Auth
participant GNS3 as GNS3 REST API
Note over Client: 1. Initialize with API Key or JWT
Client->>MCP: POST /transport initialize (Authorization: Bearer <key>)
alt API Key (gns3_&lt;uuid&gt;_&lt;secret&gt;)
MCP->>Auth: Extract UUID → DB lookup → 1 bcrypt (thread pool)
Auth-->>MCP: Generate fresh JWT
else JWT
MCP->>Auth: Decode JWT
Auth-->>MCP: Token valid
end
MCP-->>Client: initialize result + Mcp-Session-Id header
Note over Client: 2. Call Tools (each request re-authenticated)
Client->>MCP: POST /transport tools/call (Mcp-Session-Id + Bearer)
MCP->>GNS3: HTTP request (with JWT pinned at session creation)
GNS3-->>MCP: Response
MCP-->>Client: tool result (SSE or JSON response body)
```
## Internal Implementation
- **MCPServer** (official MCP SDK, `mcp.server.mcpserver` — `FastMCP` was renamed in SDK 2.x) is used for tool registration and the Streamable HTTP transport
- The Streamable HTTP app is mounted as a Starlette sub-application at `/v3/mcp` (endpoint `/v3/mcp/transport`)
- The session manager (`mcp.session_manager.run()`) is entered in the FastAPI lifespan (`gns3server.core.tasks.lifespan`) — Starlette does not run lifespans of mounted sub-apps
- **Auth:** JWT validation via `auth_service` on every request. API key (`gns3_<uuid>_<secret>`) extracts UUID for O(1) DB lookup, runs bcrypt in thread pool, returns a fresh JWT — resolutions are cached ~5 minutes so repeated requests cost no extra bcrypt.
- Tool handlers use `Gns3Connector` (from `gns3_copilot.gns3_client.connector`) via the shared handler layer (`gns3_copilot.gns3_client.api_handlers`), keeping the MCP layer decoupled
- The JWT token is stored in a `contextvars.ContextVar` so it is available within tool handler threads (Python ≥ 3.9 propagates contextvars through `asyncio.to_thread`). In stateful Streamable HTTP the session task inherits the context of the opening request, so handlers see the token presented at `initialize`
### Node Console Execution
The `node_console_exec` tool runs commands on a node's text console server-side. One tool call is one complete console session: the server spawns `timeout N websocat -b --no-close '<console-ws-url>'`, feeds the command lines through stdin (one line per turn, ~0.3 s pacing, `\r\n` line endings), keeps reading stdout until the timeout kills websocat, and returns the collected output as plain text (`output: …`, or bare error text — no JSON envelope, no status field: the server cannot judge whether the command itself succeeded). Works for **telnet** and **ssh** console types on all computes (the controller proxies the WebSocket); **vnc** consoles have no text channel and fail with a plain message. The client never sees a URL or token — the whole websocat chain is an implementation detail.
Binary mode (`-b`) is required, not cosmetic: in text mode (`-t`, and also the default) websocat appends a newline after every received WebSocket message and turns CR/LF inside a message into spaces. The compute ships console output as one BINARY frame per `read(1024)` burst, so text mode injects a newline at every arbitrary frame boundary — output comes back diced into short lines mid-word, and carriage-return redraws are lost. `-b` is byte-exact in both directions; binary command frames are still handled as data by the compute console handler.
Prerequisites: the node must be started, and the host running gns3server must have the `websocat` binary on its PATH (a missing binary returns a plain install hint).
Output handling (the funnel):
- Raw console bytes are decoded as UTF-8 with replacement — telnet negotiation and ANSI escapes are **not** stripped; stray bytes in the output are expected.
- `grep=<python regex>` filters the captured lines (Python `re`, a superset of `grep -E`).
- Up to 50 lines return as-is; beyond that a 10-line sample returns with retrieval hints.
- `regrep=true` re-uses the node's last captured output — re-filter (`grep=`) or dump its tail (`full=true`) without re-running the command (no side effects).
- `full=true` returns the last 400 lines / 64 KiB.
- When output exceeds 50 lines, the full capture is also written to the node's files (`console-capture.txt`, overwritten per session) and the hint includes a `curl` URL with a short-lived **access ticket** (10 min) bound to that exact download path — the same mechanism `link_capture_download` uses. Tickets are short random strings (`gns3t_…`); they replaced long Bearer JWTs in returned URLs because LLM clients reliably corrupted those when retyping them (logging out invalidates outstanding tickets).
Node-side state persists between calls (config mode, running pings, pager position) — a new session lands where the previous one ended. On QEMU serial consoles, log in in ONE call: send the username and the password in the same `command` string. `login` flushes typed-ahead input before printing `Password: `, so a password sent in a separate call is lost and the console loops on `Login incorrect`. Once logged in, the shell persists across calls. Control keys are sent as real characters: an interrupt is `"\u0003"` as its own line in the `command` string; the 4-character spelling `"\x03"` is not translated. `command=""` sends a single Enter (wake an idle console / read the prompt). The session stays open the full `timeout` window (default 15 s, max 300 s) — set it just above the expected output time.
The console WebSocket URL is built from the server's `_server_url()`, which resolves the host as follows:
| `Server.host` value | Resolved host in URL |
|:---|:---|
| Specific IP or hostname (e.g. `192.168.1.3`) | Used as-is |
| `0.0.0.0` (IPv4 any, default) | Detected via **default route interface IP** |
| `::` (IPv6 any) | Detected via default route interface IP |
| Detection failure | Fallback to `127.0.0.1` |
When `Server.host` is `0.0.0.0` (listen on all interfaces), the MCP server discovers the default route interface IP using a UDP socket connect to `8.8.8.8:80` — no network data is sent, the operating system simply selects the interface that would be used for the default route. This ensures the console URL uses a reachable address (e.g. `192.168.1.3` instead of `127.0.0.1`). If the configured host is already a specific IP or hostname (not `0.0.0.0`), it is used directly without modification.
### Source Files
| File | Purpose |
|------|---------|
| `gns3server/agent/mcp/__init__.py` | MCPServer, tool decorators, Streamable HTTP transport, JWT auth wrapper |
| `gns3server/agent/mcp/projects.py` | Project tool handlers |
| `gns3server/agent/mcp/nodes.py` | Node tool handlers |
| `gns3server/agent/mcp/links.py` | Link tool handlers |
| `gns3server/agent/mcp/templates.py` | Template tool handlers |
| `gns3server/agent/mcp/computes.py` | Compute tool handlers |
| `gns3server/api/server.py` | Mounts MCP routes via `register_starlette_routes()` |
+381
View File
@@ -0,0 +1,381 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is AI-generated with reference to actual code and verified against real-kernel testing. AI can make mistakes — please verify against the source code when in doubt.
# Packet Filters (link impairments)
## Overview
Per-link impairment filters — delay, packet loss, corruption, rate limiting, deterministic drops — configured through a link's `filters` dict and applied by **both link endpoints**, so every direction of a link is impaired exactly once. A `delay 100` link therefore measures ≈200 ms RTT; `packet_loss 30` measures ≈51 % round trip (1 − 0.7²).
Every kernel-datapath node type shares one implementation: `KernelDatapathMixin` keys everything on the anchor interface name, which is why a Docker adapter's veth host end and a QEMU / IOU / Dynamips adapter's TAP are interchangeable. On the kernel datapath the filters run **in the kernel** as tc objects that uBridge installs over netlink (`tc netem set`, raw netlink — no `tc` binary needed): one netem qdisc, cls_bpf match-drop classifiers and one eBPF stateful classifier per anchor. Relay links run the uBridge userspace filters on the single relay bridge instead — five types there (`delay`, `packet_loss`, `corrupt`, `frequency_drop`, `bpf`); the rest are kernel-only.
## Terms
| Term | Meaning |
|---|---|
| anchor | the host-side interface a link attaches to — a Docker adapter's veth host end, a QEMU / IOU / Dynamips adapter's persistent TAP |
| tc / qdisc | traffic-control objects the kernel inserts into the anchor's egress path — stages frames pass through in flight, not external packet consumers; uBridge only installs them over netlink |
| `clsact` | the tc classifier carrier on the anchor; its egress chain is where the drop classifiers run |
| netem | the impairment qdisc behind clsact: delay, loss, rate, corrupt, duplicate, … |
| eBPF classifier | the stateful drop classifier at clsact egress prio 1 — modes every-Nth, quota, time window and flow (GNS3 exposes the first three as filter types) |
| `bpf_drop` | match-drop BPF expressions at clsact egress prio 10–99 |
| relay filter | a uBridge userspace filter on the relay bridge — both directions cross the single filtered bridge |
## Evaluation order (kernel datapath)
All 13 types in evaluation order for one frame with every filter set — the chain runs once per direction on the destination anchor's egress, the classifier chain first and the single netem qdisc behind it. A drop at any stage ends the frame: whatever the classifiers drop never reaches netem, nor the AF_PACKET tap points — captures and markers will not observe it:
```mermaid
flowchart LR
subgraph CLS["clsact egress — the classifier chain"]
subgraph EB["eBPF stateful classifier — prio 1"]
M1{"frequency_drop (nth)"}
M2{"quota"}
M3{"window_drop (window)"}
end
BP{"bpf lines — prio 10-99"}
end
subgraph NET["netem root qdisc"]
DUP["duplicate — copy queued"]
LOS{"packet_loss / gemodel"}
COR["corrupt"]
TS["delay · reorder · rate"]
TFQ["delay queue — limit"]
SEED["seed"]
end
FR["frame from the link bridge"]
OUT["into the node"]
DROP["dropped"]
FR --> M1 --> M2 --> M3 --> BP
BP --> DUP --> LOS --> COR --> TS --> TFQ --> OUT
M1 -->|"every Nth"| DROP
M2 -->|"cap reached"| DROP
M3 -->|"in window"| DROP
BP -->|"match"| DROP
LOS -->|"hit"| DROP
TFQ -->|"full"| DROP
```
Semantic model rather than kernel source order: the netem draws fire at enqueue (a `duplicate` hit queues a copy alongside the original, `corrupt` damages and passes), `delay`/`reorder`/`rate` fold into one time_to_send that the delay queue drains when due, `limit` is that queue's capacity — the `full` edge above — and `seed` is no stage but the PRNG behind every stochastic draw (duplicate, loss/gemodel, corrupt, jitter). The eBPF program's fourth mode (flow) has no GNS3 filter type, and the attached parameters (jitter, correlation, distribution) ride their types and add no stages. On the relay datapath there is no such chain — the five relay-supported types run as uBridge userspace filters on the single relay bridge, both directions through one filter list.
## Filter types
On the kernel datapath the 13 types ride three kernel objects on the anchor. The `tc …` verbs in the table are uBridge's own hypervisor command names — **not the iproute2 `tc` binary**: uBridge builds every netlink message itself (RTM_NEWQDISC for the netem qdisc, RTM_NEWTFILTER for the cls_bpf and eBPF classifiers), loads the eBPF program through raw `bpf()` syscalls with the instruction array embedded in the binary, embeds the jitter-distribution tables the `tc` CLI would read from disk, and uses libpcap only as a library to compile `bpf` expressions — the same compiler the relay filter uses. The `tc` and `ip` binaries appear only in uBridge's test suite, as kernel-state oracles:
| GNS3 filter | kernel implementation | Notes |
|---|---|---|
| `delay [ms, jitter, dist]` | netem `delay X jitter Y [distribution D]` | jitter 0 omitted; dist ∈ uniform/normal/pareto/paretonormal (kernel-only parameter) |
| `packet_loss [%, correl]` | netem `loss P [correl C]` | per direction (see below); correlation is a kernel-only parameter — and collapses small rates, see the correlation-bias bullet |
| `corrupt [%]` | netem `corrupt P` | |
| `duplicate [%, correl]` | netem `dup P [correl C]` | kernel-only type |
| `rate ["512kbit"]` | netem `rate B` | tc-style integer+unit (bit/kbit/mbit/gbit/bps/kbps/mbps, ≤100gbit); kernel-only type |
| `reorder [%, correl, gap]` | netem `reorder P [correl C] [gap G]` | requires `delay`; kernel-only type |
| `gemodel [p, r, 1-h]` | netem `loss gemodel P R H` | Gilbert-Elliot bursty loss: p = good→bad transition, r = bad→good transition, 1-h = loss chance in the bad state (good loses nothing) — mean one-way loss p/(p+r)×(1-h); mutually exclusive with `packet_loss`; kernel-only type |
| `seed [u32]` | netem `seed N` | reproducible random draws; kernel-only type — seeded draws need Linux ≥ 6.6, older kernels silently ignore the seed (every other knob applies) |
| `limit [pkts]` | netem `limit N` | queue depth above the 1000 default (rate+delay BDP); kernel-only type |
| `bpf` (one line per expression, OR) | `tc bpf_drop add <if> <prio> "<expr>"` — cls_bpf on clsact egress + gact drop | needs uBridge `cbpf=1` (`tc capabilities`, probed once per uBridge process); a line that fails to compile on the compute is skipped with a warning, mirroring the relay |
| `frequency_drop [N]` | `tc nth_drop <if> N` — the eBPF stateful classifier's exact every-Nth mode (clsact egress prio 1) | needs uBridge `ebpf=1`; -1 = drop everything → every 1st; per-direction counters (see below) |
| `quota [bytes, %]` | `tc quota_drop <if> <bytes> <pct>` — after the byte quota is consumed, each further packet drops with the given chance (100 = hard cutoff) | kernel-only type; needs `ebpf=1`; per-direction byte counters |
| `window_drop [start, outage, %, period?, jitter?]` | `tc window_drop <if> <start> <outage> <pct> [<period> [<jitter>]]` — packets drop with the given chance inside `[start, start+outage)` | kernel-only type; needs `ebpf=1`; see the window semantics below |
## Parameter reference
The API surface of the 13 types — parameters, ranges and cross-filter rules, validated by the controller before anything reaches uBridge (`gns3server/utils/packet_filter_validation.py`; the same data drives `available_filters`, which reports it per link). Trailing parameters are optional everywhere: a client sending only the first N values of a filter keeps working. **K** marks the kernel-datapath-only types; two further *parameters* are kernel-only and marked inline. The row order matches the Filter types table above. The **UI name** column is the display name served by `available_filters` (`gns3server/controller/link.py`, the `FILTERS` catalog) and shown by the Web UI — `gemodel` appears there as *Gilbert-Elliot loss*, not under its API type.
| Filter | UI name | Parameters | Constraint |
|---|---|---|---|
| `delay` | Delay | Latency (1…32767 ms) · Jitter (0…32767 ms) · Distribution | Distribution kernel-only, needs Jitter > 0; the four shapes are compared in the Per-filter guide |
| `packet_loss` | Packet loss | Chance (0…100 %) · Correlation (0…100 %) | Correlation kernel-only; Chance ≲ Correlation collapses (see Semantics) |
| `corrupt` | Corrupt | Chance (0…100 %) | |
| `duplicate` **K** | Duplicate | Chance (0…100 %) · Correlation (0…100 %) | |
| `rate` **K** | Bandwidth limit | Rate — tc-style string, e.g. `"512kbit"` (≤ 100gbit) | integer + unit; bps-family units count bytes/s |
| `reorder` **K** | Reorder | Reorder (0…100 %) · Correlation (0…100 %) · Gap (1…1000 packets) | requires `delay` |
| `gemodel` **K** | Gilbert-Elliot loss | p (good-to-bad) · r (bad-to-good) · 1-h (bad-state loss) (each 0…100 %) | mutually exclusive with `packet_loss` |
| `seed` **K** | Random seed | Seed (0…4294967295) | pins the netem draws only; reproducibility needs Linux ≥ 6.6 |
| `limit` **K** | Queue limit | Limit (1…1000000 packets) | queue depth above the 1000 default |
| `bpf` | Berkeley Packet Filter (BPF) | Filters — text, one expression per line | any match drops |
| `frequency_drop` | Frequency drop | Frequency (−1…32767) | −1 drops everything; 0 disables |
| `quota` **K** | Byte quota | Quota (1…10¹⁵ bytes) · Chance (0…100 %) | both required; Chance 100 = hard cutoff |
| `window_drop` **K** | Time window drop | Start (0…10¹² ms) · Outage (1…10¹² ms) · Chance (0…100 %) · Period (1…10¹² ms) · Jitter (0…10⁹ ms) | 3/4/5 params = one-shot / recurring / randomized flap; Period ≥ Outage |
Cross-filter rules (violations return 409): `reorder` requires `delay`; `gemodel` and `packet_loss` map to the same netem loss slot and are mutually exclusive; `window_drop` Period ≥ Outage; `delay` Distribution requires Jitter > 0; `rate` must be an integer plus a unit no larger than 100gbit.
The disabled convention: a filter whose first value is 0 (or an empty string) reads as off and is skipped. Two exceptions — `delay [0, 0]` is the explicit off while `delay [0, X>0]` is a validation error (Latency ≥ 1), and `window_drop` is active whenever present (`Start = 0` means the outage begins immediately, not off).
## Per-filter guide
What each filter is for and what each parameter means. Ranges live in the Parameter reference above and are not repeated beyond the parameter names; mechanics live in the sections below. Order matches the Parameter reference table; (kernel-only) in a heading marks a type the relay cannot run.
### `delay` — fixed latency with jitter
**Purpose**: propagation delay — geographic distance, satellite hops; amplifying RTT to observe TCP window/BDP behaviour, protocol timers, interactive traffic; combined with `rate`, a narrowband high-latency path.
| Parameter | Meaning |
|---|---|
| Latency (1…32767 ms) | fixed one-way delay added per direction — both endpoints apply it, so RTT ≈ 2×. Minimum 1; `[0, 0]` is the explicit off |
| Jitter (0…32767 ms) | per-packet offset drawn in Latency ± Jitter; omitted = 0 |
| Distribution | the shape of the jitter draw (kernel-only, needs Jitter > 0; default uniform) — see the table below |
The four distributions, for Jitter = 5 ms:
| Distribution | Shape | Effect | Use for |
|---|---|---|---|
| uniform (default) | flat rectangle | every offset in −5…+5 ms equally likely, hard bound | simplest model — worst case is exactly ±J |
| normal | bell (Gaussian) | most offsets near 0, extremes rare, ±5 almost never reached | mild, concentrated jitter — same-DC, premium lines |
| pareto | heavy tail (L shape) | most offsets ≈0 with occasional spikes several times the typical value | queueing spikes, congestion bursts; stress-testing timeout/retransmit logic |
| paretonormal | bell body + Pareto tail | concentrated majority with occasional spikes | closest to measured Internet/WAN jitter; the netem-recommended default |
Real-network jitter is heavy-tailed because delay variation is mostly queueing — a buffer filling up produces one large spike, "calm most of the time, occasionally wild", exactly a bell body with a heavy tail. `normal` suffices for intra-DC paths; use `pareto` / `paretonormal` for the WAN. (Implementation aside: the kernel stores a pre-sampled lookup table, not the distribution's math — which is why `tc qdisc show` cannot print the name.)
**Note**: the first packet after a suspend/resume takes one extra interval (netem idle baseline; steady state exact); a large delay combined with `rate` needs `limit` raised (see `limit`).
**Example**: `{"delay": [80, 5, "paretonormal"]}` — 80 ± 5 ms per direction, heavy-tailed jitter.
### `packet_loss` — random loss
**Purpose**: wireless loss, congestion tail-drop; observing TCP backoff and retransmission, application retries, protocol tolerance.
| Parameter | Meaning |
|---|---|
| Chance (0…100 %) | independent per-packet loss probability, per direction — a round trip measures ≈ 1−(1−P)² |
| Correlation (0…100 %, kernel-only) | consecutive-loss correlation — a loss raises the next packet's loss probability, forming bursts |
**Note**: Chance ≲ Correlation collapses toward zero effective loss (kernel netem defect, quantified in Semantics) — for bursty loss at a chosen mean use `gemodel`. The relay strips this parameter; sending only the single chance argument keeps working.
**Example**: `{"packet_loss": [2]}`; correlated `{"packet_loss": [10, 25]}` (10 < 25 sits in the collapse zone — measured ≈1.8 % effective; shown for syntax only).
### `corrupt` — bit errors
**Purpose**: degraded physical layer — CRC errors, wireless interference, failing optics; checksum coverage, retransmission, FEC.
| Parameter | Meaning |
|---|---|
| Chance (0…100 %) | per-packet probability of content corruption. The damaged frame **passes** — the receiver's checksum does the dropping, and a capture on the link shows the damaged frame |
**Example**: `{"corrupt": [5]}`.
### `duplicate` — duplicated packets (kernel-only)
**Purpose**: the real-world prototype is **wireless link-layer retransmission** — an 802.11 ARQ retransmit of a frame the receiver already got (the ACK was lost); 1–3 % duplicates are normal on WiFi captures. Transient L2 loops (the STP convergence window) and bonding failover also duplicate. Tests protocol idempotence and sequence-number/dedup handling (TCP is immune by sequence number; non-idempotent application logic executes twice).
| Parameter | Meaning |
|---|---|
| Chance (0…100 %) | per-packet probability of being copied (the original continues; a copy is added) |
| Correlation (0…100 %) | consecutive-duplicate correlation — wireless retransmissions cluster in time (the marginal-signal periods); Chance ≲ Correlation collapses the same way, see Semantics |
**Note**: the copy draws its own delay (under `delay 100` the duplicate arrives at a different time than the original); duplicates have no gemodel equivalent — for bursty duplication keep Chance at or above the Correlation.
**Example**: `{"duplicate": [2]}` — mild WiFi-like duplication; `{"duplicate": [10, 25]}` — syntax illustration (10 < 25 sits in the collapse zone, measured ≈1.8 % effective); `{"duplicate": [25, 25]}` — chance at the correlation does not collapse, ≈16.7 % effective (measured anchor).
### `rate` — bandwidth limit (kernel-only)
**Purpose**: narrowband access lines (512k, 2M), bandwidth bottlenecks; QoS, queuing and bulk-transfer behaviour.
| Parameter | Meaning |
|---|---|
| Rate | tc-style integer + unit: `bit`/`kbit`/`mbit`/`gbit` count bits/s, `bps`/`kbps`/`mbps` count bytes/s, ≤ 100gbit |
**Note**: the limit shapes **each direction independently** (symmetric full duplex — one shaper per endpoint, no shared budget: 10 Mbit/s each way simultaneously). Asymmetric rates (e.g. 20M down / 1M up) are not expressible through the link `filters` dict; use in-guest netem on each side. Per-packet serialization time ≈ packet size / rate, applied once per direction → ≈2× on RTT; a large `rate` combined with a large `delay` needs `limit` raised (see `limit`).
**Example**: `{"rate": ["512kbit"]}`.
### `reorder` — out-of-order delivery (kernel-only)
**Purpose**: multipath forwarding (ECMP, bonding), parallel switch fabrics; TCP SACK, reordering buffers, RACK.
| Parameter | Meaning |
|---|---|
| Reorder (0…100 %) | the chance a packet is held back until a later packet has passed it |
| Correlation (0…100 %) | consecutive-reorder correlation |
| Gap (1…1000 packets) | reorder cadence — every gap-th packet sent immediately, the rest held back to create reordering; without it, purely probabilistic |
**Note**: requires `delay` (validated with 409). The mechanism is **queue-jumping**: `delay` holds packets in the netem queue until due, and reorder lets the chosen packets skip the wait and transmit immediately, overtaking the packets still held in that same queue — the one `limit` bounds. Aggressive reorder + rate + delay overflows `limit` the same way (tail-drops no filter asked for), and the reorder depth is bounded by the delay (a packet is held at most `delay` ms).
**Example**: `{"delay": [50], "reorder": [25, 25, 5]}` — 25 % reordering at a 5-packet cadence on a 50 ms path.
### `gemodel` — bursty loss, Gilbert-Elliot (kernel-only)
**Purpose**: real loss comes in bursts — microburst congestion, transient memory exhaustion, wireless fades. Use it for "chosen mean rate + tunable burst shape"; it is immune to the correlation collapse.
| Parameter | Meaning |
|---|---|
| p (good-to-bad, 0…100 %) | good→bad transition — per-packet chance of entering a burst; burst spacing averages ≈ 1/p packets |
| r (bad-to-good, 0…100 %) | bad→good transition — average burst length ≈ 1/r packets |
| 1−h (bad-state loss, 0…100 %) | per-packet loss chance inside the bad state (the good state loses nothing) |
Steady-state mean one-way loss = **p/(p+r)×(1-h)** — "one-way" meaning per direction: each endpoint runs its own independent instance (uncorrelated state machines), so a round trip compounds to ≈ 1−(1−mean)²; loss in only one direction is not expressible through the link `filters` dict (it is pushed to both endpoints symmetrically — use in-guest netem for that).
**Note**: mutually exclusive with `packet_loss` (one netem loss slot; 409). Same mean, different script — and the script is what protocols feel (scattered losses trigger TCP fast retransmit; a burst wiping a window stalls into RTO):
```
packet_loss [5] (independent): ──X───X────X───X────X───X── 5 % per packet, evenly scattered
gemodel [1, 19, 100] (bursty): ────────▒▒▒▒▒───────────▒▒▒── long clean runs, ≈5 packets die together ≈100 apart
```
Choosing parameters: pick the target mean M and average burst length L (packets) → r ≈ 1/L, p ≈ M·r/(1−M) (with 1-h = 100); lower 1-h to let some packets survive inside a burst.
**Example**: `{"gemodel": [1, 19, 100]}` — 5 % mean loss, bursts of ≈5 packets fully lost, ≈100 packets apart.
### `seed` — reproducible randomness (kernel-only)
**Purpose**: reproducible experiments and A/B comparisons — same seed + same filter set → the identical loss/jitter/corruption/duplication sequence.
| Parameter | Meaning |
|---|---|
| Seed (0…4294967295) | the netem PRNG seed |
**Note**: pins the netem draws only — the eBPF percentage draws (quota, window) ride a PRNG seeded at program load, outside `seed`'s reach; any filter-set change resets schedules and counters. Two more boundaries: reproduction also requires the same traffic pattern (draws are consumed per arriving packet — classifier-stage drops upstream change the sequence), and a fixed seed pins one realization, not the distribution — for statistical conclusions (average throughput under loss) run several seeds. One more: the seeded PRNG itself is a Linux 6.6 addition — on older kernels the seed attribute is silently ignored (no error), the draws stay random while every other netem knob applies.
**Example**: `{"packet_loss": [10], "seed": [42]}`.
### `limit` — impairment queue depth (kernel-only)
**Purpose**: the netem queue's capacity — it exists for `rate` + `delay` combinations: the backlog grows toward the bandwidth-delay product, and past `limit` it tail-drops, losing packets no filter asked to lose. Alone it does essentially nothing (no delay, no backlog).
| Parameter | Meaning |
|---|---|
| Limit (1…1000000 packets) | packets the queue can hold; 1000 default |
Rule of thumb: limit ≈ rate × delay / average packet size, with headroom. Symptom to watch for: with rate + delay set, measured throughput below the configured rate or loss no filter asked for usually means the 1000 default is overflowing — raise `limit`.
**Example**: `{"rate": ["10mbit"], "delay": [2000], "limit": [5000]}` — 10 Mbit/s × 2 s ≈ 2.5 MB ≈ 1700 full-size packets, past the 1000 default → 5000.
### `bpf` — match-drop by content
**Purpose**: selective blackholing — drop only ICMP (a ping blackhole), only BGP (`tcp port 179`) to watch sessions drop, OSPF hellos (`ip proto 89`) for convergence timing, VRRP advertisements (`proto 112`) to force a failover.
| Parameter | Meaning |
|---|---|
| Filters | libpcap/tcpdump expression, **one per line**, any match drops. Each line is compiled with `tcpdump -d` before apply; a line that fails to compile on the compute is skipped with a warning |
**Note**: the semantics are match-drop — only matches drop; "allow only X" is written `not <X>`. Runs on both datapaths (cls_bpf on the kernel, libpcap in the relay).
**Example**: `{"bpf": "icmp"}`; multi-line `{"bpf": "tcp port 179\nip proto 89"}`.
### `frequency_drop` — deterministic periodic drops
**Purpose**: deterministic loss with no dice — an exact drop cadence for worst paths: retransmission, FEC, fast-fail logic; also experiments needing a steadily advancing drop counter.
| Parameter | Meaning |
|---|---|
| Frequency (−1…32767) | positive N = drop every Nth packet; −1 = drop everything; 0 = disabled |
**Note**: the two datapaths count differently — the relay runs one counter shared by both directions (phase-locked); the kernel counts per direction (N=3 → 55.6 % round-trip, measured 57 %), exact atomic counters (see Semantics).
**Example**: `{"frequency_drop": [3]}` — every 3rd packet.
### `quota` — traffic quota (kernel-only)
**Purpose**: quota/billing — a volume budget exhausted cuts or degrades the link; application resilience to "cut off mid-stream".
| Parameter | Meaning |
|---|---|
| Quota (1…10¹⁵ bytes) | the byte budget, counted per direction — until it is consumed the filter is fully transparent (counting only) |
| Chance (0…100 %) | an independent per-packet drop chance after the quota is consumed — 100 = hard cutoff, lower = degraded service. The draw mathematics equal `packet_loss`, but it runs in the eBPF classifier stage: no Correlation parameter (immune to the correl collapse), outside `seed`'s reach, and its drops are invisible to captures/markers (see Semantics) |
**Note**: counting starts when the filter is applied; any filter-set change resets the counters (reconcile = reset + re-apply, see Semantics). Needs `ebpf=1`.
**Example**: `{"quota": [1000000000, 100]}` — hard cut after 1 GB.
### `window_drop` — scheduled outage (kernel-only)
**Purpose**: planned outages (a maintenance window "link dies at T for M seconds"), recurring flaps (failing cable, wireless fades), link-flap convergence and failover testing.
| Parameter | Meaning |
|---|---|
| Start (0…10¹² ms) | window start, relative to the moment of apply; 0 = begins immediately (valid and active) |
| Outage (1…10¹² ms) | window length |
| Chance (0…100 %) | an **independent per-packet draw** inside the window — equivalent to `packet_loss` gated to the window (per direction, a round trip compounds to ≈ 1−(1−C)²; 100 = full outage, lower = a degraded window) |
| Period (1…10¹² ms, optional) | recurring: outages at [Start + k·Period, Start + k·Period + Outage) for k = 0, 1, 2, …; duty cycle = Outage/Period; omitted = one-shot |
| Jitter (0…10⁹ ms, optional) | breaks the metronome phase: each cycle re-draws the outage length and the cycle gap independently, uniformly in nominal ± Jitter (integer-ms grid; 0 = the fixed schedule) — stops protocol timers from phase-locking with the outage |
Timelines of the three forms (▒ = outage):
```
one-shot [1000, 1500, 100]:
pass ────────┬▒▒▒▒▒▒▒▒┬──────────────── (down t=1.0–2.5 s, passes before and after)
recurring [1000, 1500, 100, 10000]:
pass ──┬▒down 1.5s▒┬───────────────┬▒down 1.5s▒┬────── (every 10 s, 15 % duty cycle)
t=1.0s 2.5s t=11.0s 12.5s
jittered [0, 2000, 100, 10000, 500]:
▒~1.8s▒───── ~9.7s ─────▒~2.2s▒───── ~10.4s ─────▒~1.5s▒… (length and gap re-drawn per cycle within ±0.5 s)
```
**Note**: **any filter change, node restart or link reset restarts the schedule** — a one-shot window that has already passed must be re-armed: apply immediately before generating traffic, or use a Period. Both endpoints run their own schedule; a round trip survives only when both directions are outside their windows (see Semantics). Needs `ebpf=1` plus the uBridge mode token.
**Example**: `{"window_drop": [1000, 1500, 100]}` — dead 1.5 s starting at t=1 s, one-shot; `{"window_drop": [0, 2000, 100, 10000, 500]}` — dead 2 s now, recurring every ~10 ± 0.5 s.
## Semantics
* **Both endpoints** receive the filter dict and attach one qdisc to *their* anchor. The qdisc's egress covers traffic entering that node, so every direction of the link is impaired exactly once — the same net effect as the relay, where both directions cross the single filtered bridge. A `delay 100` link measures ≈200 ms RTT; `packet_loss 30` measures ≈51 % round-trip (1 − 0.7²); `rate 512kbit` adds ≈2× the per-packet serialization time to the RTT.
* **Correlation collapses small rates (kernel netem defect, quantified).** netem's correlated draw mixes `answer = (value·(2³²−ρ) + last·ρ) >> 32` — truncated, never wrapped modulo 2³² — so the stationary distribution is starved at both edges: a draw almost never lands in the bottom ρ slice of the range. The effective rate of nominal P under correl C collapses toward zero whenever P ≲ C. Reproduced with stock iproute2 `tc` on this kernel (uBridge's netlink encoding is identical — GNS3 shows the same numbers): `1% 25%` → measured 0/1000 pings (theoretical ≈0.0002 %), `5% 25%` → ≈0.2 %, `10% 25%` → ≈1.8 % one-way (3.8 % round-trip measured), `25% 25%` → ≈16.7 %; nominal 50 % stays 50 % under every correl (the distribution's symmetry point). The same edge-starvation suppresses small `duplicate`/`reorder` rates under their correl and thins the tails of correlated jitter. `gemodel` is immune — a Markov chain over plain uniform draws — and is the honest tool for bursty loss at a chosen mean rate (p/(p+r)×(1-h)). Not fixable server- or uBridge-side without deviating from stock `tc` behavior; the kernel fix would be to wrap the mixing modulo 2³².
* **Reconcile = reset + full re-apply.** The kernel's netem replace MERGES optional attributes (rate, correlation, reorder, corrupt, gemodel, distribution: an absent attr keeps its previous value), so re-applying a filter set with a parameter *removed* would silently keep the old value. Every apply therefore starts with `tc reset` (also drops clsact and its bpf_drop filters — re-added right after in the same flow) followed by one `netem set` built from the current filters; no per-parameter diffing. An empty filter set is the reset alone (ENOENT-tolerated).
* **Extension gating.** The netem-extension keywords (rate, reorder, gemodel, dist, seed, limit — plus the correl suffixes, which gate on the `rate` token as the extension-build marker) probe `tc capabilities` once per uBridge process and require the tokens; a plain delay/loss/corrupt/dup filter never probes — an old uBridge serves the original surface untouched.
* **kernel-only vs relay-available.** The extension types, `quota` and `window_drop` have no uBridge relay equivalent: `available_filters` hides them on relay links, setting one on a created relay link returns 409, and a project loaded with such filters on a link that cannot be kernel-wired drops them with a warning (invalid filters are dropped the same way at load). `frequency_drop` runs on both datapaths (relay userspace filter / eBPF every-Nth).
* **frequency_drop counting semantics differ per datapath.** The relay's single filtered bridge counts packets of BOTH directions through one counter; the kernel attaches one classifier per anchor, so each direction drops every Nth independently. For a round-trip measurement with every-Nth N: relay ≈ 1/N of frames (phase-locked), kernel = 1 − ((N−1)/N)² (e.g. N=3 → 55.6 % round-trip loss, measured 57 %). The kernel count is exact (atomic counter), unlike netem's stochastic loss.
* **Classifier order** on clsact egress: the eBPF stateful filter runs at prio 1, `bpf_drop` expressions at 10–99 — a packet dropped by the stateful modes never reaches the expression drops, and dropped packets never reach netem. Within the stateful program the modes evaluate in the fixed order nth → quota → window → flow.
* **window_drop semantics.** `start` is relative to the moment the filter is applied — and because reconcile re-sets the classifier on every apply (any filter change, node restart, link reset reloads the program after the netem reset), every such event **restarts the schedule**. 3 parameters = one single outage (`[start, start+outage)`), traffic passes before and after — the classic "link dies at T, comes back at T+outage". 4 parameters = recurring flap: `period ≥ outage` (validated), so the outage occupies `outage/period` of each cycle. 5 parameters = randomized flap: each cycle's outage and period are re-drawn uniformly in nominal ± `jitter` (integer-ms grid; jitter 0 draws nothing and equals the fixed schedule). Inside a window each packet drops with the given chance (100 = full outage, lower = degraded service during the window). Both endpoints run their own schedule, started ~simultaneously by the controller — a round trip survives only when **both** directions are outside their windows. Note `start = 0` (outage begins immediately) is a valid, active configuration — unlike other filters, a zero first parameter does not mean "disabled". A PUT re-sending an unchanged filters dict is normally a controller no-op, but one still carrying `window_drop` is reconciled anyway, so re-applying the same window re-arms a one-shot outage that has already passed (arm the filter immediately before generating traffic, or use a period for a repeatable event).
* **Node restart** restores the qdisc from the NIO (like capture and markers); **link deletion** detaches it explicitly — the anchor survives the link and an orphaned qdisc would keep impairing the next one.
* **Suspend** keeps the qdisc (carrier-driven loss); the first packet after resume takes one extra delay interval (known netem idle-baseline behaviour) and steady state is exact.
* **bpf reconcile = flush + re-add** (`tc bpf_drop flush`, then one add per line at priorities 10, 11, …). `tc reset` (link delete / filter clear) is the full restore in uBridge: filters → clsact → root qdisc, idempotent.
* **Observability caveat:** clsact drops happen before the AF_PACKET tap points — markers/captures on the same anchor do not observe cls_bpf-dropped frames (on the relay, filter-vs-mark ordering determined visibility instead). Also note `tc qdisc show` cannot print a distribution's name (the kernel stores only the sampled table).
* **eBPF mode tokens.** A stateful mode is usable iff `tc capabilities` reports `ebpf=1` **and** lists the mode's token in `ebpf_modes` (uBridge `feature/tc-window`+). Builds predating the field keep the modes that shipped with it — everything but `window`, whose semantics were corrected exactly when the field was added: gating on `ebpf=1` alone would silently install the broken back-to-back-window behaviour on a pre-correction build. Requesting an unusable mode fails the apply with an upgrade error; the cleanup ("off") path only touches modes the build declares.
* **Capability reporting.** The compute exposes the probe through `GET /v3/compute/capabilities` as `ubridge_tc` (netem keyword list, `ebpf`/`cbpf` flags, and the usable `ebpf_modes` — legacy fallback applied), answered by a throwaway uBridge spawned as the server's own user and cached by binary identity — the runtime `ebpf` flag flips between users and kernels for the same binary, so a root-run probe would lie for a non-root server. The controller forwards it through `GET /v3/computes` and `available_filters` hides kernel-datapath filter types an endpoint compute reports it cannot run (both ends apply their own filters, so one incapable compute is enough). Computes that report nothing — older servers, failed probe — keep the full list; apply-time validation (409) stays the guard.
## Combining filters
The composition model in one line: **deterministic drops are an OR-gate** (first kill wins, the rest never run), **netem draws are independent probabilities that multiply**, and **a round trip squares everything** — the only genuine coupling inside one direction is `limit` backstopping the backlog that `rate` + `delay` create.
Classifier-stage composition: a frame dropped at clsact never reaches netem, so it consumes no `rate` serialization time, no delay-queue capacity (`limit`), and no netem counter — and captures/markers will not see it (the observability caveat above). The stateful modes interact only through their counters: `quota`'s byte count sees just the `frequency_drop` survivors (evaluation is ordered), so every-Nth drops slow the quota burn by the nth pass rate; the `window_drop` schedule and the nth counter are independent of each other. A frame the eBPF program lets pass continues to the `bpf` lines — the program returns `TC_ACT_UNSPEC` on a pass, not `TC_ACT_OK`, so the prio chain continues — making the two classifier stages a chain, not an exclusion.
Within netem, the nine types are **one qdisc pass, not nine stages**: duplicate, loss/gemodel and corrupt are independent draws (their probabilities multiply; a duplicated copy draws its own delay; corrupt damages and passes, leaving the receiver's checksum to do the dropping), while `delay`/`reorder`/`rate` fold into a single time_to_send. The coupling to watch is `limit` × `rate` × `delay`: rate serializes while delay holds, so the backlog grows toward the bandwidth-delay product — once it passes `limit`, the queue tail-drops and the link loses packets no filter asked to lose. Raise `limit` when combining a large `rate` with a large `delay`. `seed` pins only the netem draws (duplicate, loss, corrupt, jitter) — the eBPF program's percentage draws (quota, window) ride a separate PRNG seeded at program load, outside `seed`'s reach.
Round-trip composition: both endpoints run their own instance on their own anchor (each direction impaired exactly once), so per-direction survival multiplies across drop sources and then squares for a round trip — `delay 100` → ≈200 ms RTT, `packet_loss 30` → ≈51 % round-trip loss, `frequency_drop 3` → 55.6 % (the per-type arithmetic in Semantics above); `window_drop` schedules start ~simultaneously on both ends, so a round trip survives only when **both** directions are outside their windows, and `quota` burns two independent byte counters. The combinations that cannot merge — `packet_loss` + `gemodel` (one netem loss slot), `reorder` without `delay`, `distribution` without jitter, `period < outage` — are rejected at validation (409), never silently merged.
A fully-loaded example — `delay 100 jitter 10`, `packet_loss 10`, `corrupt 5`, `duplicate 10`, `rate 512kbit`, `reorder 25 gap 5`, `limit 5000`, `seed 42`, `bpf "icmp"`, `frequency_drop 3`, `quota 3000000 100`, `window_drop [1000, 1500, 100]` — sends one A→B frame through this gauntlet at B's anchor: it dies exactly on every 3rd send (nth), else it counts toward a 3 MB budget after which it is hard-cut (quota), else it drops when it lands inside the 1–2.5 s outage (window), else it drops when the expression matches (bpf); a survivor enters netem, where it may be duplicated (the copy draws its own delay), lost (10 %), or corrupted (5 %, passes damaged), and otherwise waits 100 ± 10 ms with 25 % reorder while 512 kbit/s serializes it inside a 5000-packet queue — every draw reproducible under `seed 42`. The B→A direction runs the same gauntlet independently on A's anchor.
## REST surface
Filters travel on the link API: a `filters` dict on the link object (`filter type → positional values`), validated by the controller (the cross-filter rules above return 409 on violation) and pushed to both endpoints on create, update and project reopen.
| Method | Path | Purpose | Privilege |
|---|---|---|---|
| GET | `/v3/projects/{project_id}/links/{link_id}` | read the link incl. its `filters` | Link.Audit |
| PUT | `/v3/projects/{project_id}/links/{link_id}` | replace the `filters` dict | Link.Modify |
| GET | `/v3/projects/{project_id}/links/{link_id}/available_filters` | the per-link vocabulary with parameter names, ranges and units | Link.Audit |
Setting filters is a plain link update — send only the `filters` property:
```json
PUT /v3/projects/{project_id}/links/{link_id}
{
"filters": {
"delay": [50, 5],
"packet_loss": [1]
}
}
```
`available_filters` is the authoritative per-link vocabulary: kernel-only types appear only on kernel-datapath links whose endpoint computes report a uBridge able to run them, and relay links list the five relay types only (per the capability reporting above).
Common recipes — all values are per direction, so round trips double the delay and compound the loss (see Semantics):
| Goal | `filters` value |
|---|---|
| WAN latency with jitter | `{"delay": [50, 5]}` |
| 1 % random loss | `{"packet_loss": [1]}` |
| Bursty ~5 % mean loss | `{"gemodel": [1, 19, 100]}` — mean = p/(p+r)×(1-h) = 5 % |
| 512 kbit/s cap | `{"rate": ["512kbit"]}` |
| Drop all ICMP | `{"bpf": "icmp"}` |
| 1.5 s full outage starting now, one-shot | `{"window_drop": [0, 1500, 100]}` |
## Where the chain sits
The per-node-type frame paths — where an anchor's egress chain sits in the whole journey from one node to another — are drawn in the datapath docs: `docker-kernel-datapath.md` (veth), `qemu-kernel-datapath.md` and `dynamips-kernel-datapath.md` (TAP), `iou-kernel-datapath.md`, `ethernet-switch-kernel-datapath.md` and `iol-docker-kernel-datapath.md`. The frozen uBridge contract behind the kernel objects (netlink encoding, `tc capabilities`, the full-restore `tc reset`) is `../design/ubridge-kernel-impairment-spec.md`.
+148
View File
@@ -0,0 +1,148 @@
# Project Open Performance
## Overview
Optimizations to accelerate project opening (`POST /projects/{id}/open`) and node creation for topologies with many nodes and links. The main bottlenecks were sequential link creation, redundant subprocess calls, and SQLite write contention.
## Before vs After
| Scenario | Before | After |
|----------|--------|-------|
| 20 IOU nodes + 20 links (project open) | ~2s | ~1s |
| 40 QEMU nodes creation (MCP batch) | ~40s | ~1-2s |
## Optimizations
### 1. Parallel Link Creation
**File:** `gns3server/controller/project.py`
Links were created sequentially during project loading, each requiring up to 5 HTTP round-trips to the compute. Now uses `Pool(concurrency=100)` for parallel creation.
```python
# Before: sequential loop
for link_data in topology.get("links", []):
link = await self.add_link(...)
await link.add_node(...)
# After: parallel Pool
pool = Pool(concurrency=100)
for link_data in topology.get("links", []):
pool.append(self._create_link_from_topology_data, link_data)
await pool.join()
```
### 2. Batch UDP Port Allocation
**Files:** `gns3server/api/routes/compute/compute.py`, `gns3server/controller/project.py`, `gns3server/controller/udp_link.py`
During project loading, all required UDP ports are pre-allocated per compute in a single batch call before link creation begins. `UDPLink.create()` checks the pre-allocated pool first, falling back to individual allocation if unavailable.
```python
# New batch endpoint
POST /projects/{id}/ports/udp/batch → {"count": N} → {"udp_ports": [...]}
```
### 3. IOU Image Subprocess Cache
**File:** `gns3server/compute/iou/iou_vm.py`
Each IOU VM creation spawned `ld-linux --verify` and `iou-image -h` subprocesses. With 20 nodes using the same image, this ran 40 redundant subprocesses. Now results are cached per image path at the class level.
```python
# Class-level caches shared across all instances
IOUVM._loader_cache = {} # image path → loader command
IOUVM._default_values_cache = {} # image path → (ram, nvram)
```
Only the first node with a given image runs the subprocesses; subsequent nodes reuse cached values.
### 4. SQLite WAL Mode
**File:** `gns3server/db/tasks.py`
Write-Ahead Logging allows concurrent reads without blocking on writes. The PRAGMA is registered on `engine.sync_engine` instead of the `Engine` class to correctly fire for async engine connections.
```python
@event.listens_for(engine.sync_engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA journal_mode=WAL")
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
```
Without WAL mode, concurrent API requests caused `sqlite3.OperationalError: database is locked`.
### 5. API Key Authentication O(1) Lookup
**Files:** `gns3server/api/routes/controller/api_keys.py`, `gns3server/api/routes/controller/dependencies/authentication.py`
**Old format:** `gns3_<random>` — required scanning ALL keys and running bcrypt on each (O(n)).
**New format:** `gns3_<api_key_id>_<random_secret>` — extract UUID from token, single DB query (O(1)), single bcrypt.
```python
# New auth flow
parts = token.split("_", 2)
key_id = UUID(parts[1])
secret = parts[2]
db_key = await api_keys_repo.get_api_key(key_id) # O(1) lookup
if await asyncio.to_thread(bcrypt.checkpw, secret.encode(), db_key.key_hash.encode()):
# Authenticated — 1 query + 1 bcrypt regardless of total key count
```
### 6. bcrypt in Thread Pool
**File:** `gns3server/api/routes/controller/dependencies/authentication.py`
`bcrypt.checkpw()` is CPU-bound (~1.3s per call) and was blocking the async event loop. With 5 API keys and 10 concurrent requests, this caused ~13s delay before any handler could start.
```python
# Before: blocking the event loop
if bcrypt.checkpw(token.encode(), db_key.key_hash.encode()):
...
# After: offloaded to thread pool
if await asyncio.to_thread(bcrypt.checkpw, secret.encode(), db_key.key_hash.encode()):
...
```
### 7. Concurrency Settings
| Setting | Before | After | File |
|---------|--------|-------|------|
| Node creation Pool | 5 | 100 | `controller/project.py` |
| Link creation Pool | 5 | 100 | `controller/project.py` |
| MCP BATCH_MAX_WORKERS | 10 | 100 | `agent/mcp/nodes.py` |
| MCP HTTP timeout | 10s | 30s | `agent/gns3_copilot/gns3_client/connector.py` |
| HTTP connection pool | 10 (default) | 500/1000 | `agent/gns3_copilot/gns3_client/connector.py` |
| Start nodes Pool | 3 | 3 (unchanged) | `controller/project.py` |
### 8. MCP Auth Returns JWT
**File:** `gns3server/agent/mcp/__init__.py`
When an MCP client connects with an API key, the `_resolve_token` function validates the key then returns a fresh short-lived JWT instead of the raw API key. The JWT is stored in a `ContextVar` and reused for all subsequent tool calls within the same MCP session — zero extra bcrypt.
```python
if user:
fresh_token = auth_service.create_access_token(user.username)
return fresh_token # JWT for subsequent REST API calls
```
## Related Files
| File | Changes |
|------|---------|
| `gns3server/controller/project.py` | Parallel link creation, batch UDP, Pool(100) |
| `gns3server/compute/iou/iou_vm.py` | Image subprocess cache |
| `gns3server/db/tasks.py` | WAL mode + sync_engine event listener |
| `gns3server/api/routes/compute/compute.py` | Batch UDP endpoint |
| `gns3server/controller/udp_link.py` | Pre-allocated port consumption |
| `gns3server/api/routes/controller/api_keys.py` | O(1) key format |
| `gns3server/api/routes/controller/dependencies/authentication.py` | O(1) auth + thread pool bcrypt |
| `gns3server/agent/mcp/__init__.py` | Auth returns JWT, tool enhancements |
| `gns3server/agent/mcp/nodes.py` | fields filter, inherited template_id, name passthrough |
| `gns3server/agent/mcp/links.py` | fields filter, compact array format |
| `gns3server/agent/gns3_copilot/gns3_client/connector.py` | Timeout 30s, connection pool 500/1000 |
| `gns3server/utils/images.py` | md5sum cache error → warning |
+286
View File
@@ -0,0 +1,286 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is AI-generated with reference to actual code and verified against real-kernel testing. AI can make mistakes — please verify against the source code when in doubt.
# QEMU kernel datapath
QEMU adapters anchor on a **persistent TAP**, and links between two QEMU nodes — or a QEMU node and a Docker container — on the same compute are wired in the kernel (per-link Linux bridge) instead of the uBridge UDP relay. The compute side is the same machinery Docker already uses: `KernelDatapathMixin` (`gns3server/compute/kernel_datapath.py`) takes an *anchor interface* and does not care whether it is a veth host end or a TAP.
## Architecture
Kernel link between two QEMU nodes on the same compute. Interface names follow the shared contract of `gns3server/utils/kernel_anchor.py`: `gq{node_id[:8]}e{adapter}p{port}` for the persistent TAP (one per QEMU adapter, port always 0) and `gns3{link_id[:11]}` for the bridge; the concrete names in the diagrams use node ids `3f2a1b9c` / `7c9d4e2f` and link id prefix `5d3c2b1a4e6`. A mixed Docker↔QEMU link is the same bridge with the Docker end's `gv` veth host end as its other anchor — the shared mixin is anchor-agnostic; the pure-veth picture is `docker-kernel-datapath.md`. Terms the diagrams use:
| Term | Meaning |
|---|---|
| uBridge | the per-node helper process gns3-server spawns with elevated capabilities; its hypervisor command surface executes all host-side wiring (TAPs, bridges, carrier, tc, taps) — on a kernel link it builds and observes the path but never carries frames |
| anchor | the host-side interface a link attaches to — here the `gq` persistent TAP |
| persistent TAP | the TAP uBridge creates per QEMU adapter at node start (`tap create`, `tap set_owner`); it outlives restarts and crashes, and QEMU opens it by name as its `-netdev tap` |
| per-link bridge | the Linux bridge `gns3{link_id[:11]}` that stands in for the cable; the two anchors are its only ports |
| bridge port | an interface enslaved to a Linux bridge (`brctl addif`) — it no longer sends or receives on its own: frames arriving on it go to the bridge's forwarding logic, and the bridge transmits through it |
| tap fd | a TAP's file descriptor: reads return frames the kernel received on the device, writes inject frames into it — on this datapath QEMU itself holds it |
| FDB | the bridge's forwarding database (learned MAC → port); unknown, broadcast and multicast destinations are flooded |
| `01:80:c2` / `group_fwd_mask` | the IEEE 802.1D reserved multicast range (STP, LACP, LLDP, 802.1X, PAUSE); the bridge forwards it only per the port's `group_fwd_mask` — `0xfffd` passes everything except PAUSE/PFC |
| tc / qdisc | traffic-control objects the kernel inserts into the anchor's egress path — stages frames pass through in flight, not external packet consumers; uBridge only installs them over netlink |
| `clsact` | the tc classifier carrier on the anchor; its egress chain is where the drop classifiers run |
| eBPF classifier | the stateful drop modes (every-Nth, quota, time window) at clsact egress prio 1 |
| `bpf_drop` | match-drop BPF expressions at clsact egress prio 10–99 |
| netem | the impairment qdisc behind clsact: delay, loss, rate, corrupt, duplicate, … |
| `AF_PACKET tap` | uBridge's packet socket bound to the anchor; the kernel clones every frame the interface sends or receives to it (the tcpdump mechanism) — read-only copies for capture and markers, the original stays on the kernel path |
| carrier | the anchor's admin state (`link set up/down`); suspend is carrier down plus QMP `set_link off` so the guest notices |
| QMP | the QEMU machine protocol — how the server drives a running QEMU (link state on suspend/resume) without restarting it |
| `nio_bridge` | the NIO record the controller posts to each endpoint node: bridge name, filters, markers, suspend flag |
```mermaid
flowchart LR
subgraph GA["guest A (in the VM)"]
nA["NIC 0"]
end
subgraph RootNS["root namespace"]
gqA["gq3f2a1b9ce0p0 — anchor"]
BR["gns35d3c2b1a4e6 — per-link bridge"]
gqB["gq7c9d4e2fe0p0 — anchor"]
UBA["uBridge A"]
UBB["uBridge B"]
end
subgraph QPA["QEMU A process"]
ndA["netdev gns3-0 (tap fd)"]
end
subgraph QPB["QEMU B process"]
ndB["netdev gns3-0 (tap fd)"]
end
subgraph GB["guest B (in the VM)"]
nB["NIC 0"]
end
nA <-->|"virtio / e1000"| ndA
ndA <-->|"tap fd"| gqA
gqA <-->|"bridge port"| BR
BR <-->|"bridge port"| gqB
gqB <-->|"tap fd"| ndB
ndB <-->|"virtio / e1000"| nB
gqA -. "frame copies" .-> UBA
UBA -. "qdisc install" .-> gqA
gqB -. "frame copies" .-> UBB
UBB -. "qdisc install" .-> gqB
```
Everything in the root namespace is built the same way: gns3-server creates the persistent TAPs at node start (before QEMU is launched), the per-link bridge and its memberships at link creation, and every later change (carrier, capture, markers, filters) by sending hypervisor commands to the node's uBridge process — the privileged agent that turns them into netlink/ioctl operations. That build flow is the Link creation sequence below; this diagram is the steady state that remains, where the only uBridge relationships left are the two dashed kinds.
uBridge sits off the forwarding path — the dashed edges are control and observation, never data flow. The `qdisc install` edge is uBridge configuring the kernel over netlink; the kernel then runs those qdiscs in-flight on the anchor's egress (stages of the transmit path, not packet consumers). The `frame copies` edge is the AF_PACKET tap, there only while a capture or markers is active (a kernel link leaves no uBridge endpoint on the anchor otherwise): the kernel clones every frame the TAP sends or receives to uBridge's packet socket (the tcpdump mechanism) — read-only copies for capture and markers; the originals never leave the kernel. The only userspace on the path is the two QEMU processes pumping their own tap fds — the irreducible VM leg, one fd crossing at each end per direction.
Relay link between the same two QEMU nodes on the same single compute — what every link becomes when `enable_kernel_datapath` is off (mixed node types and cross-compute wiring fall back too; there the UDP hop rides the real network instead of loopback, the copy count unchanged):
```mermaid
flowchart LR
subgraph GA["guest A (in the VM)"]
EA["NIC sends"]
end
subgraph QA["QEMU A — userspace"]
NDA["netdev tap fd"]
end
subgraph KERN["kernel — root ns"]
TA["gq3f2a1b9ce0p0 — anchor"]
UDP["UDP sockets (loopback)"]
TB["gq7c9d4e2fe0p0 — anchor"]
end
subgraph UBA["uBridge A — userspace"]
NEA["AF_PACKET nio"]
ENA["relay + userspace filters"]
NUA["UDP nio"]
end
subgraph UBB["uBridge B — userspace"]
NUB["UDP nio"]
ENB["relay + userspace filters"]
NEB["AF_PACKET nio"]
end
subgraph QB["QEMU B — userspace"]
NDB["netdev tap fd"]
end
subgraph GB["guest B (in the VM)"]
EB["NIC receives"]
end
EA -->|"virtio"| NDA
NDA -->|"copy 1: user→kernel"| TA
TA -->|"copy 2: kernel→user"| NEA
NEA --> ENA --> NUA
NUA -->|"copy 3: user→kernel"| UDP
UDP -->|"copy 4: kernel→user"| NUB
NUB --> ENB --> NEB
NEB -->|"copy 5: user→kernel"| TB
TB -->|"copy 6: kernel→user"| NDB
NDB -->|"virtio IRQ"| EB
```
Drawn one-way; the reverse direction is the mirror image. A relayed frame crosses the kernel/user boundary **six times each way** (twelve per round trip): the two halves of the irreducible VM leg — QEMU's tap-fd write at the sending end, its read at the receiving end — plus the four the relay adds around them (AF_PACKET read, UDP send, UDP receive, AF_PACKET inject). The kernel datapath's only crossings are the VM leg's two; the relay's filters run in userspace, on the frames between the copies.
The relay attaches the TAP with `bridge add_nio_ethernet` (AF_PACKET, which does not take the device over) — **never** `bridge add_nio_tap`, which would claim the fd QEMU itself holds. And unlike the IOL runner container, whose anchors idle on the relay, the anchor here is the netdev itself: it stays up and carries as the relay's AF_PACKET endpoint — QEMU has no other leg (the legacy socket-netdev fallback below is the one shape without the TAP).
Frame path for one A → B frame. The impairment chain fires on the egress of the *destination* end's TAP, in order clsact → netem (a classifier drop means netem never sees the frame); each direction is impaired exactly once and B → A is symmetric on gqA — hence `delay 100` ≈200 ms round trip (measured 100.3 ms one-way). Each one-way trip crosses the kernel/user boundary exactly twice — the sending QEMU's tap-fd write and the receiving QEMU's tap-fd read, the irreducible VM leg:
```mermaid
flowchart LR
subgraph ANS["guest A (in the VM)"]
S1["NIC sends"]
end
subgraph QPA["QEMU A — userspace"]
S2["tap fd to kernel"]
end
subgraph ROOT["root namespace"]
subgraph GQA["gqA — ingress (its egress chain serves B→A)"]
S3["ingress"]
end
subgraph BRP["per-link bridge"]
G1{"reserved 01:80:c2?"}
D["dropped"]
S4["FDB lookup / flood"]
end
subgraph GQB["gqB — egress chain (clsact, then netem)"]
S5["eBPF prio 1"]
S6["bpf_drop prio 10-99"]
S7["netem qdisc"]
end
T["capture / markers"]
end
subgraph QPB["QEMU B — userspace"]
S8["tap fd to QEMU"]
end
subgraph BNS["guest B (in the VM)"]
S9["NIC receives"]
end
S1 -->|"virtio"| S2
S2 -->|"tap fd, copy 1: user→kernel"| S3
S3 --> G1
G1 -->|"PAUSE 0x01"| D
G1 -->|"0xfffd passes"| S4
S4 --> S5
S5 --> S6 --> S7
S7 -->|"tap fd, copy 2: kernel→user"| S8
S8 -->|"virtio IRQ"| S9
S3 -. "AF_PACKET tap" .-> T
S7 -. "AF_PACKET tap" .-> T
```
What each stage drops: the reserved-range gate passes LACP, LLDP, 802.1X and STP per the port mask but never PAUSE/PFC (Link-local frames below); the clsact/netem stages drop or impair per the installed filters (Capture, markers, filters below). The AF_PACKET taps observe both anchors but never a clsact-dropped frame. Copies 1–2 are the whole path's only kernel/user crossings — both halves of the emulation's own TAP-fd leg (QEMU A's write, QEMU B's read); every stage between them runs in the kernel.
## Why a TAP works like a veth host end
| Event | Docker anchor (veth host end) | QEMU anchor (TAP) |
|---|---|---|
| Frames the node sends | arrive on the veth as `PACKET_HOST` | written to the tap fd, arrive as RX (`PACKET_HOST`) |
| Frames the peer sends | injected by uBridge, seen as `PACKET_OUTGOING` | injected by uBridge, seen as `PACKET_OUTGOING` |
| `tc` egress qdisc impairs | traffic entering the container | traffic entering the VM |
| Capture/marker anchor | the interface | the same interface |
So every filter, capture and marker primitive carries over verbatim, and `delay 100` on both anchors still measures ≈200 ms round trip while each direction is impaired exactly once.
## Datapath selection
`UDPLink._kernel_datapath_eligible` needs both endpoints on one compute and both able to anchor (an Ethernet-switch endpoint is the exception — it absorbs the peer's anchor into its own bridge, so the switch side needs no anchoring capability of its own; `docs/features/ethernet-switch-kernel-datapath.md`):
* Docker can (adapters are born as veth pairs), except the IOL runner container, whose unix-socket guest leg anchors on a TAP under its own capability pair (`docs/features/iol-docker-kernel-datapath.md`);
* QEMU can when that compute's uBridge reports the `tap` module — asked per compute through `/capabilities` (`ubridge_tap`, probed by creating and deleting one throwaway TAP, cached by binary identity), because an old uBridge leaves QEMU on the legacy socket-netdev datapath and cannot anchor a kernel link. An unknown/failed probe keeps the link on the relay.
Because the `-netdev` type is fixed when QEMU is launched, this is all-or-nothing per VM: on the TAP datapath *every* link can attach to (or detach from) a running VM, including switching a link between the two datapaths (delete + re-create, or a project reopen).
## Link creation sequence
Both endpoints attach concurrently and compute the same bridge name independently (a pure function of the link id), so either may win the `brctl create` race — the loser verifies the bridge exists (`brctl show`) and continues. The topology above's link, at attach time:
```mermaid
sequenceDiagram
participant API as REST API
participant C as Controller
participant CA as QEMU node A
participant CB as QEMU node B
participant UA as uBridge A
participant UB as uBridge B
API->>C: POST /links
C->>C: eligibility check
C->>C: bridge = gns3 + link_id[:11]
C--)CA: nio_bridge
C--)CB: nio_bridge (same bridge)
par QEMU node A
CA->>UA: brctl create
CA->>UA: link set bridge up
CA->>UA: brctl addif gq3f2a1b9ce0p0
CA->>UA: capture / markers if any
CA->>UA: tc netem + bpf + eBPF
CA->>UA: link set gq3f2a1b9ce0p0 up
and QEMU node B
CB->>UB: same on gq7c9d4e2fe0p0
end
Note over UA,UB: steady state — kernel forwards, uBridge taps
```
Every arrow to uBridge is one `_ubridge_send` command line on the node's local hypervisor console; uBridge executes it (netlink/ioctl) and replies OK or an error synchronously before the next command is sent — those replies are omitted for brevity. The per-port `group_fwd_mask` 0xfffd is deliberately not an arrow: uBridge applies it inside `brctl addif` itself (Link-local frames below). uBridge never initiates anything: it is a pure executor, and the only data ever flowing back (capture/marker frame copies) rides separate AF_PACKET sockets, not this console.
The TAP already exists at attach time — created at node start, before QEMU launched (Adapter lifecycle below) — which is what makes the attach runtime-safe on a running VM: anchors, bridge memberships and qdiscs all change around the `-netdev tap` QEMU already holds, and the only QEMU traffic is carrier replication — QMP `set_link` on attach, detach and suspend/resume, gated by the node's `replicate_network_connection_state` option (default on), so the guest's carrier follows the link.
A mixed Docker↔QEMU link runs the identical sequence per end — each node's uBridge receives the same commands on its own anchor, the Docker end's `gv` veth host end in place of the `gq` TAP; only the anchor name differs (the mixin is anchor-agnostic, which is the point of the shared `gns3server/compute/kernel_datapath.py`).
## Adapter lifecycle
* **Birth (node start, before QEMU is launched)** — `_prepare_tap_datapath` probes the tap module, then `_create_taps` sweeps any leftover (a persistent TAP outlives a crash) and creates one TAP per adapter: `tap create gq{node_id[:8]}e{adapter}p{port}` → `tap set_owner <uid>` (so the unprivileged QEMU process can open it) → `link set <tap> down` (carrier off until a link attaches). QEMU then opens it as `-netdev tap,id=gns3-{adapter},ifname=<tap>,script=no,downscript=no`.
* **Life (running)** — the TAP is never created or destroyed again. Link create/delete/switch, suspend, capture and markers only change *what is attached to it*.
* **Death (node stop)** — the QEMU process is stopped **first**, then `_remove_taps` un-persists the TAPs (`tap delete`) and deletes the per-link kernel bridges the node still holds. The order matters: uBridge's `tap delete` refuses a device another process holds open ("Device or resource busy") and that best-effort delete is suppressed, so deleting the TAPs while QEMU still ran leaked every persistent TAP (process side first, then the devices — the same lesson as IOU's stop order, where uBridge itself holds the anchors and is made to release them before `tap delete`). Stopping a node never runs the link-teardown path — links survive stops by design, and project close is the same (it stops nodes without deleting links) — so those bridges would otherwise stay behind as empty orphans; a restart rebuilds them from the NIO. Deleting a node from the project is not that case: the controller deletes its links first, so the teardown does run.
## Link operations
| Operation | Kernel-datapath action |
|---|---|
| Create / attach | `brctl create` (EEXIST tolerated via `brctl show`) + `link set <bridge> up` + `brctl addif <bridge> <tap>`, then capture and markers and filters on the anchor (`tc netem set`, bpf/eBPF drops), carrier up last |
| Delete / detach | marker teardown → `tc reset <tap>` → carrier off → `brctl delif` → `brctl delete` (last endpoint wins; EBUSY/ENOENT suppressed). The TAP survives — the adapter keeps it for the next link |
| Reset (`POST /links/{id}/reset`) | delete + create (re-evaluates eligibility) |
| Suspend (`PUT /links/{id}` `{"suspend": true}`) | tap admin-down (writing to a down TAP fd fails with EIO, so the link is genuinely dead) + QMP `set_link gns3-N off` so the guest notices; resume restores both, and the netem qdisc survives the flap |
## Capture, markers, filters
Identical to Docker's kernel links, on the TAP: `capture start_kernel <tap>` (driven by the NIO type, not by a link flag), `marker add_kernel <tap> …` (only the capture node's end), and one `tc netem set` per anchor so each direction is impaired once. `frequency_drop`/`quota`/`window_drop` run as the eBPF classifier on the anchor's clsact egress.
## Link-local frames (LACP, LLDP, 802.1X, STP)
The bridge stands in for a cable, but the kernel's `br_handle_frame()` does not forward the IEEE 802.1D reserved range (`01:80:c2:00:00:00`-`0f`) by default — LACP, LLDP/DCBX and 802.1X would never cross a kernel link while the UDP relay carries them fine. uBridge therefore opens every port's per-port `group_fwd_mask` (`IFLA_BRPORT_GROUP_FWD_MASK`) to `0xfffd` at `brctl addif` time (Linux 4.15+, best-effort on older kernels). The bridge-level knob cannot do this: `BR_GROUPFWD_RESTRICTED` rejects bits 0-2, so LACP is reachable per port only.
Result on kernel links: ordinary multicast, STP/RSTP, LACP, 802.1X and LLDP/DCBX all cross; **802.3x PAUSE / PFC does not** — `case 0x01` in `br_handle_frame()` drops it unconditionally and no mask can enable it. That is a documented limit, not a regression (PFC's hardware semantics are out of emulation's reach anyway); a lab that needs PAUSE frames on the wire must use a relay link. Verified live by `tests/e2e/test_docker_link_local_frames.py` (per-MAC guest-to-guest matrix); the contract and kernel references live in `docs/design/ubridge-link-local-frame-forwarding-spec.md`.
## Legacy fallback
A uBridge build without the `tap` module (or without `CAP_NET_ADMIN`) keeps the previous datapath untouched: local UDP tunnels into uBridge, QEMU launched with `-netdev socket`, and the node logs a warning that it cannot carry kernel links. Such a node is never offered a kernel link, so nothing fails.
## Verified
End-to-end through a real server (isolated instance, two QEMU nodes with a stub binary, the test playing the guest by holding the TAP fds and pushing frames): **32/32 checks** on the kernel datapath and **29/29** on the relay variant (`enable_kernel_datapath = false`). Kernel run highlights:
* anchors created persistent and owned by the server user, QEMU's netdev is the TAP, no local UDP tunnel left; the link object reports `kernel_datapath: true` (the `POST /links` response) and one per-link bridge holds both taps;
* frames cross in both directions (~0.1 ms); `delay 100` ⇒ netem on both anchors and a measured **100.3 ms** one-way;
* suspend ⇒ anchor DOWN, no traffic, resume ⇒ 100.3 ms again (filter kept);
* capture ⇒ a 252-byte pcap written by `capture start_kernel`;
* link delete ⇒ bridge gone, qdisc clean, anchor alive; re-create ⇒ 0.1 ms with no residual impairment; node stop ⇒ no taps, no bridges left.
Relay run the same script with the flag off: same lifecycle, filter measured at 109.8 ms (applied by uBridge's bridge — no netem on the anchor, as expected), no kernel bridge holding the tap.
The repo suite `tests/e2e/test_qemu_kernel_datapath.py` covers the same ground with a *real* guest: two IOSv routers (a real qcow2 image, linked clone, the real IOS CLI on the telnet console) — the full kernel lifecycle (anchors at start, per-link bridge membership, pure-L2 anchors, the §E.2 idle-silence window with the guests shut, real ICMP, netem delay, suspend, capture, link delete/re-create, node stop/start rewiring, zero residue on project delete) plus the relay negative control, where the anchor is up and carrying as the relay's AF_PACKET endpoint (QEMU has no other leg — the TAP is the netdev on the relay too). It needs an L3 IOSv image in the images directory's `QEMU` subfolder; a raw node must also name `hda_disk_interface` (the default `none` attaches no frontend device and the VM comes up diskless — the IOSv appliance boots virtio).
## Configuration
```ini
[Server]
# Wire eligible links (both endpoints on one compute, both able to anchor)
# through kernel interfaces instead of the uBridge UDP relay.
enable_kernel_datapath = True
```
## Known caveat
Anchors are host-side netdevs, so the kernel gives them an IPv6 link-local address and emits MLD/DAD from them; those frames flood into the emulated segment. The hardening requirement (anchors must be pure L2, no L3 identity) is specified for uBridge in `docs/design/ubridge-l2-anchor-spec.md` and is **delivered**: anchors and per-link bridges come up with `addrgenmode none`, no addresses, and an idle anchor is silent (asserted in the e2e after a 2.5 s settle).
One residual is accepted and documented there: enslaving a port makes the *kernel* announce the bridge's multicast memberships once — an IGMPv3 plus one or two MLDv2 reports in the first second — which floods into the segment like any L2 control frame. It stops; it is outside the L2-only command's reach (no addresses involved, IPv4 has no per-device IGMP switch).
## Roadmap
The rest of the node family has landed on the same mixin: **IOU** — see `docs/features/iou-kernel-datapath.md` (Ethernet bays anchor on persistent TAPs bound to the IOL fabric, `iol_bridge add_nio_tap` per `docs/design/ubridge-iol-tap-anchor-spec.md`; serial links stay relay, and one userspace hop on the IOU leg is irreducible — the fabric is Unix sockets); **Dynamips** — see `docs/features/dynamips-kernel-datapath.md` (the hypervisor opens uBridge-created TAPs with `nio create_tap`: the same external-fd-holder shape QEMU uses; serial/ATM/POS ports stay relay); **the Ethernet switch** — see `docs/features/ethernet-switch-kernel-datapath.md` (the switch absorbs a peer's anchor into its own kernel bridge; switch-to-switch cascades too); **the IOL runner container** — see `docs/features/iol-docker-kernel-datapath.md` (persistent TAP anchors through the generic bridge module's swappable TAP leg; the unix-socket guest leg keeps one userspace hop, like IOU's fabric).
Still on the relay: the cloud paths (their anchors are ubridge-owned by design); and cross-compute kernel links need VXLAN/GENEVE encapsulation, which is a separate project (it would serve Docker links the same way).
+154
View File
@@ -0,0 +1,154 @@
# Stateless JWT Refresh Token Mechanism
## Overview
GNS3 server now supports a stateless JWT refresh token mechanism for interactive sessions (e.g., Web UI). This allows clients to stay authenticated across page reloads without repeated username/password prompts, while keeping access tokens short-lived.
No new database table or migration is required — refresh tokens are signed JWTs using the same secret and algorithm as access tokens.
## Architecture
```mermaid
graph TD
Client -->|login / authenticate| API[Controller API]
API -->|access_token + refresh_token| Client
Client -->|POST /refresh| Refresh[Refresh Endpoint]
Refresh -->|new access_token + new refresh_token| Client
Client -->|Bearer access_token| Protected[Protected Endpoints]
Protected -->|401| Client
Client -->|refresh_token in body| Refresh
Refresh -->|401 if invalid/expired/revoked| Client
Refresh -->|verify type, exp, ver| AuthService[AuthService]
AuthService -->|check token_version| DB[(users table)]
```
## Business Process
### Login / Authenticate Flow
```mermaid
sequenceDiagram
participant C as Client
participant API as Controller API
participant AS as AuthService
participant DB as Database
C->>API: POST /login or /authenticate (username + password)
API->>DB: authenticate_user()
DB-->>API: user (with token_version)
API->>AS: create_access_token(user, ver)
API->>AS: create_refresh_token(user, ver)
AS-->>API: access_token (type: access, exp: 15min)
AS-->>API: refresh_token (type: refresh, exp: 30d)
API-->>C: { access_token, token_type, refresh_token }
```
### Refresh Flow (Silent Renewal)
```mermaid
sequenceDiagram
participant C as Client
participant API as Controller API
participant AS as AuthService
participant DB as Database
Note over C: access_token expired
C->>API: POST /refresh { refresh_token }
API->>AS: get_token_data(refresh_token)
AS-->>API: { username, ver, token_use: "refresh" }
API->>DB: get_user_by_username()
DB-->>API: user (with current token_version)
Note over API,DB: rejects if user not found, inactive, or token_version mismatch
API->>AS: create_access_token(user, ver)
API->>AS: create_refresh_token(user, ver)
AS-->>API: new access_token (sliding window)
AS-->>API: new refresh_token (sliding window)
API-->>C: { access_token, token_type, refresh_token }
C->>API: Retry original request with new access_token
```
### Logout — Token Revocation
```mermaid
sequenceDiagram
participant C as Client
participant API as Controller API
participant DB as Database
C->>API: POST /logout (Bearer access_token)
API->>DB: logout_user(user_id) → token_version += 1
DB-->>API: done
API-->>C: 204 No Content
Note over C, DB: All existing access and refresh tokens with old ver are now invalid
```
## API Endpoints
| Method | Path | Description | Authentication |
|--------|------|-------------|---------------|
| POST | `/v3/access/users/login` | Login with form data, returns access + refresh tokens | Public |
| POST | `/v3/access/users/authenticate` | Login with JSON, returns access + refresh tokens | Public |
| POST | `/v3/access/users/refresh` | Exchange a refresh token for a new access token + refresh token | Public (token itself proves identity) |
| POST | `/v3/access/users/logout` | Revoke all tokens for the current user | Bearer token required |
### POST /v3/access/users/refresh
**Request:**
```json
{
"refresh_token": "<refresh_token>"
}
```
**Response 200:**
```json
{
"access_token": "<new_access_token>",
"token_type": "bearer",
"refresh_token": "<new_refresh_token>"
}
```
**Error Responses:**
- `401` — Invalid, expired, or revoked refresh token
- `422` — Missing `refresh_token` field in request body
## Security Design
### Token Claims
| Claim | Access Token | Refresh Token |
|-------|-------------|---------------|
| `sub` | username | username |
| `exp` | 24h (configurable) | 30d (configurable) |
| `ver` | user's `token_version` | user's `token_version` |
| `type` | `"access"` | `"refresh"` |
### Key Security Properties
- **Type-based isolation**: Access tokens (`type: access`) are rejected by `/refresh`. Refresh tokens (`type: refresh`) are rejected by HTTP and WebSocket authentication paths. This prevents a stolen long-lived refresh token from being used directly for API access.
- **Token version integration**: Both token types carry the user's `token_version`. `logout` increments `token_version` in the database, immediately invalidating all outstanding access and refresh tokens.
- **Stateless (no replay detection)**: Since there is no `refresh_tokens` database table, a stolen refresh token remains valid until its `exp` or until the user logs out. This is an accepted trade-off for avoiding a new table and migration.
- **Sliding window**: Each `/refresh` call issues a new refresh token with a fresh expiry, keeping active sessions alive indefinitely until logout or inactivity.
### Implementation Files
- `gns3server/services/authentication.py` — `_create_token`, `create_access_token`, `create_refresh_token`, `get_token_data`
- `gns3server/api/routes/controller/users.py` — `refresh_access_token` endpoint handler
- `gns3server/api/routes/controller/dependencies/authentication.py` — `_reject_refresh_token` guard in HTTP and WebSocket paths
- `gns3server/schemas/controller/tokens.py` — `Token`, `TokenData`, `RefreshTokenRequest` models
- `gns3server/schemas/config.py` — `jwt_refresh_token_expire_minutes` configuration
## Configuration
| Setting | Default | Description |
|---------|---------|-------------|
| `Controller.jwt_access_token_expire_minutes` | 1440 (24h) | Access token TTL. Web UI recommends 15 min. |
| `Controller.jwt_refresh_token_expire_minutes` | 43200 (30d) | Refresh token TTL. |
| `Controller.jwt_secret_key` | (random) | HMAC signing key for all JWT tokens. |
## Notes
- **Web UI integration**: The client should implement a response interceptor that catches 401, silently calls `/refresh`, and retries the original request. Multiple concurrent 401s should be queued with a single refresh request.
- **No per-session revocation**: All tokens for a user share the same `token_version`. Logout revokes everything. Per-session granularity would require adding a `refresh_tokens` table.
- **Rate limiting**: `/refresh` is a public endpoint with a valid credential (the refresh token). Rate limiting is recommended if brute-force attacks are a concern.
+236
View File
@@ -0,0 +1,236 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Statistics API
## Overview
Aggregated server statistics API for monitoring dashboards. Collects compute resources, project/node/link counts, and Web Wireshark container status in a single request.
## Architecture
```mermaid
graph TB
Client["Client (Dashboard)"]
subgraph Controller["GET /v3/statistics"]
direction TB
F1["1. Compute Resources<br/>GET compute/statistics"]
F2["2. Project/Node/Link<br/>Iterate in memory"]
F3["3. Web Wireshark<br/>Docker API + docker stats"]
end
Compute["Compute Nodes<br/>(psutil)"]
Memory["Controller<br/>(in-memory data)"]
Docker["Docker Daemon"]
Client -->|GET /v3/statistics| Controller
F1 -->|HTTP| Compute
F2 -->|read| Memory
F3 -->|Docker API| Docker
```
## Data Collection Flow
```mermaid
sequenceDiagram
participant Client
participant Controller as Controller API
participant Compute as Compute Nodes
participant Docker as Docker Daemon
Client->>Controller: GET /v3/statistics
rect rgb(240, 248, 255)
Note over Controller: 1. Compute Resources
loop For each compute
Controller->>Compute: GET /statistics
Compute-->>Controller: psutil data
Note over Controller: skip on error
end
end
rect rgb(240, 255, 240)
Note over Controller: 2. Projects / Nodes / Links
Note over Controller: Count projects by status (opened/closed)
Note over Controller: Count nodes: open→by_type+by_status, closed→by_type only
Note over Controller: Count links: total + capturing
end
rect rgb(255, 248, 240)
Note over Controller: 3. Web Wireshark
loop For opened projects only
Controller->>Docker: Query container status
Controller->>Docker: docker stats (2s timeout)
Docker-->>Controller: Container resource usage
end
end
Controller-->>Client: JSON response
```
## API Endpoints
| Method | Path | Description | Auth |
|--------|------|-------------|------|
| GET | `/v3/statistics` | Aggregated server statistics | Session |
| GET | `/v3/compute/statistics` | Single compute resource stats | Basic Auth |
## Response
```json
{
"computes": [
{
"compute_id": "local",
"compute_name": "Local",
"statistics": {
"memory_total": 16777216000,
"memory_free": 8000000000,
"memory_used": 8777216000,
"swap_total": 2147479552,
"swap_free": 1500000000,
"swap_used": 647279552,
"cpu_usage_percent": 45,
"memory_usage_percent": 52,
"swap_usage_percent": 30,
"disk_usage_percent": 67,
"load_average_percent": [12, 8, 5]
}
}
],
"projects": {
"total": 5,
"opened": 3,
"closed": 2
},
"nodes": {
"total": 42,
"open_project_nodes": 30,
"closed_project_nodes": 12,
"by_type": { "qemu": 20, "docker": 12, "dynamips": 6, "vpcs": 4 },
"by_status": { "started": 25, "stopped": 12, "suspended": 5 }
},
"links": {
"total": 38,
"capturing": 2
},
"webwireshark": {
"total_containers": 1,
"running_containers": 1,
"active_sessions": 2,
"containers": [
{
"project_id": "e16e2b51-9ba9-403b-9df4-b2915d7508a3",
"project_name": "test-project",
"container_id": "6edc9029bac0",
"status": "running",
"running": true,
"active_sessions": 2,
"memory_limit": "2.0 GB",
"cpu_limit": "1.0",
"pids_limit": 1000,
"memory": "272.5MiB / 4GiB",
"cpu": "0.23%",
"pids": 69
}
]
}
}
```
## Field Reference
### `computes[]`
| Field | Type | Description |
|-------|------|-------------|
| `compute_id` | string | Compute identifier |
| `compute_name` | string | Display name |
| `statistics` | object | Resource usage (see below) |
**`statistics` fields:**
| Field | Type | Description |
|-------|------|-------------|
| `memory_total` | int | Total RAM (bytes) |
| `memory_free` | int | Available RAM (bytes) |
| `memory_used` | int | Used RAM (bytes) |
| `swap_total` | int | Total swap (bytes) |
| `swap_free` | int | Free swap (bytes) |
| `swap_used` | int | Used swap (bytes) |
| `cpu_usage_percent` | int | CPU usage 0-100 |
| `memory_usage_percent` | int | RAM usage 0-100 |
| `swap_usage_percent` | int | Swap usage 0-100 |
| `disk_usage_percent` | int | Project dir disk usage 0-100 |
| `load_average_percent` | int[] | Load avg per core (1/5/15 min) |
### `projects`
| Field | Type | Description |
|-------|------|-------------|
| `total` | int | All projects |
| `opened` | int | Currently opened |
| `closed` | int | Currently closed |
### `nodes`
| Field | Type | Description |
|-------|------|-------------|
| `total` | int | All nodes across projects |
| `open_project_nodes` | int | Nodes in opened projects (has runtime status) |
| `closed_project_nodes` | int | Nodes in closed projects (from topology JSON, no status) |
| `by_type` | object | Count by node type (qemu, docker, etc.) |
| `by_status` | object | Count by status — **open project nodes only** |
### `links`
| Field | Type | Description |
|-------|------|-------------|
| `total` | int | All links across projects |
| `capturing` | int | Links currently capturing |
### `webwireshark`
| Field | Type | Description |
|-------|------|-------------|
| `total_containers` | int | All Wireshark containers |
| `running_containers` | int | Currently running |
| `active_sessions` | int | Active capture sessions |
| `containers` | array | Per-container details (opened projects only) |
**`containers[]` fields:**
| Field | Type | Description |
|-------|------|-------------|
| `project_id` | string | Project UUID |
| `project_name` | string | Project name |
| `container_id` | string | Docker container ID (12 chars) |
| `status` | string | Container status (running, exited, etc.) |
| `running` | bool | Is running |
| `active_sessions` | int | Active captures in this project |
| `memory_limit` | string | Configured memory limit (e.g. `"2.0 GB"`, `"unlimited"`) |
| `cpu_limit` | string | Configured CPU limit (e.g. `"1.0"`, `"unlimited"`) |
| `pids_limit` | int/string | Process limit (e.g. `1000`, `"unlimited"`) |
| `memory` | string | Live memory usage (conditional, see notes) |
| `cpu` | string | Live CPU usage (conditional, see notes) |
| `pids` | int | Live process count (conditional, see notes) |
## Error Responses
| Status | Description |
|--------|-------------|
| 401 | Unauthorized — invalid or missing session |
| 500 | Internal server error |
## Notes
- **Compute stats are best-effort**: if a compute is unreachable, it is skipped (logged as error) and other data is still returned
- **`by_status` only reflects open project nodes**: closed projects store topology in JSON without runtime status
- **Live container stats** (`memory`, `cpu`, `pids`) are only present when `docker stats` succeeds — may be absent if the Docker daemon is slow (2s timeout)
- **Web Wireshark containers** are only queried for opened projects
+221
View File
@@ -0,0 +1,221 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Cisco XRd Control Plane (Vendor NOS Adaptation)
## Overview
Cisco XRd Control Plane runs as a first-class GNS3 Docker router node by
combining the existing vendor NOS path (`console_type: "docker_exec"` +
`GNS3_SKIP_INIT=1`, see [docker-exec-console.md](./docker-exec-console.md))
with four generic server mechanisms added for heavy/systemd NOS containers:
`/dev/shm` and host-device injection, config-file injection (`extra_configs`),
and udev masking. XRd itself is pure appliance configuration — no image
rebuild, no source patching.
## Why XRd must take the vendor path
XRd boots `/usr/sbin/init` (systemd) as PID 1. GNS3's generic init.sh
wrapper chain (`/gns3/init.sh → su → run-cmd.sh → /usr/sbin/init`) crashes
XRd's glibc loader with `Fatal glibc error: dl-call-libc-early-init.c:37
(sym != NULL)` (SIGABRT loop). With `GNS3_SKIP_INIT=1` the container runs
its native entrypoint directly and boots cleanly — same arrangement as
SR Linux.
## Architecture
```mermaid
graph TB
subgraph Appliance["XRd appliance (.gns3a) — pure configuration"]
ENV["environment: GNS3_SKIP_INIT / GNS3_CONSOLE_CMD / GNS3_MASK_UDEV / GNS3_SHM_SIZE / GNS3_DEVICES + XR_*"]
XC["extra_configs: /firstboot.cfg"]
XV["extra_volumes: /xr-storage + /xr-storage-shadow"]
end
subgraph Server["gns3-server (generic mechanisms)"]
CREATE["DockerVM.create() HostConfig"]
MASK["GNS3_MASK_UDEV → /dev/null binds"]
HOSTCFG["ShmSize / Devices"]
CFGINJ["extra_configs → RO single-file bind"]
VBRIDGE["VendorDockerVM volume seeding + direct binds"]
HOSTCHK["host-readiness check (read-only)"]
end
subgraph Container["XRd container"]
SYSTEMD["systemd (/usr/sbin/init)"]
XR["XR control plane"]
XRS["/xr-storage (persisted, live data layer)"]
end
ENV --> CREATE --> SYSTEMD
ENV --> MASK & HOSTCFG
XC --> CFGINJ
XV --> VBRIDGE --> XRS
HOSTCHK -.->|"warn: inotify/file-max/fuse"| Server
```
## Mechanisms added (all generic, XRd is just the first consumer)
| Mechanism | Interface | Effect | Where |
|-----------|-----------|--------|-------|
| shm size | `GNS3_SHM_SIZE=1024` (MB) in `environment` | native `HostConfig.ShmSize` at create time — works with or without init.sh | `docker_vm.py` `create()` |
| host devices | `GNS3_DEVICES=/dev/fuse` (`docker run --device` syntax, space-separated) | native `HostConfig.Devices` | `docker_vm.py` `_format_devices()` |
| config injection | `extra_configs: [{target, content}]` (template/node/appliance schema field) | content written under the node dir, bind-mounted **read-only** at `target` — seeds NOS startup configs without rebuilding the image | `docker_vm.py` `_mount_binds()`; persisted in `docker_templates.extra_configs` (Alembic migration) |
| udev masking | `GNS3_MASK_UDEV=1` | `/dev/null` over the 5 udev systemd units **and** `/bin|/sbin|/usr/bin/udevadm` | `docker_vm.py` `create()` |
| generic unit mask | `GNS3_MASK_SYSTEMD=u1,u2` | `/dev/null` over arbitrary `/etc/systemd/system/<unit>` | `docker_vm.py` `create()` |
| graceful stop | `GNS3_STOP_TIMEOUT=60` (seconds; default 60, max 210) | explicit user stop sends SIGTERM + a grace period (Docker SIGKILLs once it expires) instead of the base class' immediate kill — systemd NOS images require a graceful shutdown; internal paths (delete/update/close) keep the immediate kill since the container is force-deleted right after. Max 210 keeps the +30 s HTTP margin inside the controller's 240 s stop budget | `vendor_docker_vm.py` `_terminate_container()` |
| host check | automatic at Docker connect | read-only `/proc` check of inotify/file-max/FUSE; warns with exact fix commands (server is unprivileged — it can only check) | `compute/docker/__init__.py` `_check_host_readiness()` |
`GNS3_*` variables are consumed host-side only and never forwarded into the
container (existing GNS3 behaviour); `XR_*` variables pass through normally.
## Host-disturbance root causes (all fixed)
A privileged systemd container can disturb the *host* desktop. Three
independent causes were isolated with plain-`docker run` A/B/C experiments
(udevd coldplug / busybox chown crash / direct `udevadm trigger`):
| Host symptom | Root cause | Fix |
|---|---|---|
| Audio muted on every node start | container `systemd-udevd` coldplug replays **all** devices it can see (privileged → host `/sys`) | `GNS3_MASK_UDEV=1` (unit masks) |
| USB reconnects (mouse notification), journal noise | XRd's own `xr_startup.sh` calls `udevadm trigger --action=add --parent-match=<usb>` (USB license-dongle probing) — a direct binary call, unit masks don't stop it | `GNS3_MASK_UDEV=1` (udevadm null-bind) |
| Same USB/journal noise + broken persistence | static busybox `chown` dlopens container NSS modules → glibc abort → per-file coredump storm → host `systemd-coredump` rescans devices | vendor volume path prefers the container's own `chown` (`vendor_docker_vm.py`) |
Diagnostics: `udevadm monitor --kernel --udev` (uevent stream),
`docker exec <cid> grep -n udevadm /opt/cisco/install-iosxr/base/etc/xr_startup.sh`.
Note: "journal corrupted" messages with varying machine-IDs come from the
*container's* journald (random machine-id per start), not the host journal.
## XRd appliance recipe
| Field | Value |
|-------|-------|
| `image` | official `ios-xr/xrd-control-plane:<ver>` — no wrapper image needed |
| `console_type` | `docker_exec` |
| `extra_volumes` | `["/xr-storage", "/xr-storage-shadow"]` |
| `extra_configs` | `{target: /firstboot.cfg, content: <XR CLI first-boot config>}` |
```
GNS3_SKIP_INIT=1
GNS3_CONSOLE_CMD=/pkg/bin/xr_cli.sh
GNS3_CONSOLE_RESIZE=0
GNS3_MASK_UDEV=1
GNS3_SHM_SIZE=1024
GNS3_DEVICES=/dev/fuse
GNS3_STOP_TIMEOUT=40
XR_FIRST_BOOT_CONFIG=/firstboot.cfg
XR_MGMT_INTERFACES=linux:eth0,xr_name=Mg0/RP0/CPU0/0,chksum,snoop_v4,snoop_v6
XR_INTERFACES=linux:eth1,xr_name=Gi0/0/0/0;linux:eth2,xr_name=Gi0/0/0/1;...
```
`GNS3_CONSOLE_RESIZE=0` (console geometry lock): the XR pager pages on the
PTY window size and ignores `terminal length 0`, so the exec PTY must stay at
the tall no-paging default for **every** client. The docker_exec console is a
single shared exec — one browser's terminal-size resize (WS control frames →
NAWS) would change the geometry concurrent netmiko/copilot sessions see and
bring `--More--` back. XRd's CLI is line-oriented, so browsers lose nothing
by not resizing. See
[docker-exec-console.md](./docker-exec-console.md#terminal-geometry-and-size-forwarding).
XRd-specific gotchas (image-side, not GNS3):
- Management interface xr_name is **`Mg0/RP0/CPU0/0`** (short prefix, `CPU0`
without slash). `MgmtEth0/RP0/CPU/0` is rejected: "not a valid
rack/slot/instance/port combination".
- `XR_INTERFACES` must list exactly `adapters − 1` data interfaces (eth0 is
management). Changing the adapter count requires regenerating the string.
- **Persistence layout**: in the *image*, `/xr-storage/{config,disk1,log,
scratch}` are symlinks into `/xr-storage-shadow` (a pristine spare copy of
the initial state). At boot the bootstrap replaces the symlinks with real
directories, and XR writes everything — committed config (`commitdb`,
`running`) included — into **`/xr-storage`**, never touching the shadow
again. This mirrors containerlab, which bind-mounts `/xr-storage`
(`nodes/xrd/xrd.go`: "persist data by mounting /xr-storage"). The
appliance persists **both** paths so writes land on host regardless of
whether they happen before or after the symlink→directory transition.
- `XR_FIRST_BOOT_CONFIG` only applies when XR's config storage is empty
(first boot). To re-seed, delete and recreate the node.
- The official image ships no default login; the first-boot config must
create one (e.g. `username admin / group root-lr / secret ...`).
- Docker mounts are fixed at container *create* time: after changing a
template's `extra_volumes`, existing nodes must be deleted and recreated
(a stop/start keeps the old mounts).
- Host sysctls (XRd's own requirements, same for containerlab):
`fs.inotify.max_user_instances=64000`, `max_user_watches=524288`,
`fs.file-max=1000000`, FUSE module loaded. GNS3 warns about these at
Docker connect; the admin raises them once. XRd also warns (non-fatal)
about `net.core.*` socket buffer sizes.
## Business process
```mermaid
sequenceDiagram
participant U as User
participant S as gns3-server
participant D as Docker daemon
participant X as XRd container
U->>S: create node from template
S->>S: parse GNS3_* env host-side
S->>D: seed volume host dirs from image (docker create + cp, first time only)
S->>D: container create (ShmSize, Devices, /dev/null binds, firstboot.cfg RO bind, volumes bound directly at /xr-storage*)
U->>S: start
S->>X: container start (native entrypoint /usr/sbin/init)
Note over X: systemd boots; udevd + udevadm masked → host untouched
S->>X: docker exec permission fix (container's own chown)
U->>S: open console
S->>X: docker exec pty: /pkg/bin/xr_cli.sh
X-->>U: IOS XR CLI (first boot: apply /firstboot.cfg, save to /xr-storage-shadow)
```
## Troubleshooting
| Symptom | Cause / fix |
|---|---|
| Node exits 139, `Fatal glibc error ... sym != NULL` in logs | init.sh wrapper path — set `GNS3_SKIP_INIT=1` **and** `console_type: docker_exec` (the flag is only honoured on the vendor class) |
| `XR_FIRST_BOOT_CONFIG ... File not found` | env path and `extra_configs` target disagree (e.g. `/firstboot.cfg` vs `/first_boot.cfg`), or entry missing |
| Console stuck at `Username:` with no credentials | image has no default user; provide a first-boot config creating one, then **recreate** the node (first-boot only runs on empty config storage) |
| `Invalid interface entries ... XR_MGMT_INTERFACES` | use `xr_name=Mg0/RP0/CPU0/0` |
| Host audio muted / USB reconnects when the node starts | set `GNS3_MASK_UDEV=1` |
| Config lost across stop/start | `extra_volumes` must include `/xr-storage` (XR's live data layer; the shadow alone is only a pristine spare). Changing `extra_volumes` requires deleting and recreating the node — Docker mounts are fixed at create time |
| Two nodes can't ping, only one side ARPs | GNS3 link wiring bug (UDP self-loop on one end), not XRd — fixed (port-allocation race); on older builds delete and re-create the link; see [link-udp-self-loop](../bugs/link-udp-self-loop.md) |
| Compute log: busybox coredump storm | fixed by the container-chown change; verify gns3-server is current |
## Notes
- All four mechanisms are opt-in: nodes that don't set the variables or the
field get byte-identical container configuration.
- `extra_configs` is a schema field (unlike the env knobs) because the
`environment` field is line-delimited and cannot carry multi-line file
content.
- Template fields live in three places (pydantic schema, DB column, Alembic
migration) — see the `extra_configs` DB migration when adding new ones.
- `net.core.*` socket-buffer requirements are not yet part of the
host-readiness check (XRd warns about them itself, non-fatally).
## References
- `gns3server/compute/docker/docker_vm.py` — HostConfig env injection,
`_UDEV_UNITS`/`_UDEVADM_PATHS`, `extra_configs` binds, `_format_devices()`
- `gns3server/compute/docker/vendor_docker_vm.py` — vendor path, volume
seeding + direct binds, container-chown
- `gns3server/compute/docker/__init__.py` — `_check_host_readiness()`
- `gns3server/schemas/common.py` — `ExtraConfig`
- `gns3server/db/models/templates.py` + `db_migrations/` — persistence
- [docker-exec-console.md](./docker-exec-console.md) — the vendor NOS base
(docker_exec console, SKIP_INIT volume persistence)
- containerlab `nodes/xrd/xrd.go` — reference for XRd env defaults and
`/xr-storage` persistence
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.6 | 2026-08-21 | SKIP_INIT volume persistence rebuilt: host-side seeding at create time (`docker create` + `docker cp`) and direct bind mounts at the real in-container paths replace the post-start `docker exec` bridge, which raced the NOS reading its startup config (visible on SR Linux: factory boot after a server restart + project reload; XRd was immune only because systemd touches `/xr-storage` tens of seconds in). No behaviour change for XRd beyond the race removal. |
| 1.5 | 2026-08-20 | Appliance env gains `GNS3_CONSOLE_RESIZE=0`: client-driven console resizes are ignored so the shared exec PTY stays at the tall no-paging geometry for concurrent netmiko/copilot sessions (browsers included). |
| 1.4 | 2026-08-15 | Code-review hardening: stop-query HTTP timeout scales with `GNS3_STOP_TIMEOUT` (values >300 s no longer abort); overlapping mask/config bind targets deduplicated (Docker "Duplicate mount point"); `ExtraConfig.target` validated at save time and directory forms rejected; host-readiness check no longer aborts on one unreadable `/proc/sys` key; base env parser strips trailing commas; vendor env knobs re-parsed on create (PUT environment takes effect); graceful stop limited to explicit user stop (delete/update/close keep the immediate kill); extra_configs under a persisted volume warns. |
| 1.3 | 2026-08-14 | Persistence corrected: XR's live data layer is `/xr-storage` (the image's symlink farm is materialized into real directories at bootstrap; `/xr-storage-shadow` is a pristine spare) — the appliance persists both. Vendor containers now stop gracefully (SIGTERM + `GNS3_STOP_TIMEOUT` grace, default 60 s) instead of being SIGKILLed on the spot. |
| 1.2 | 2026-08-14 | Link UDP self-loop root-caused to a port-allocation race and fixed — see [link-udp-self-loop](../bugs/link-udp-self-loop.md) (now marked Fixed). |
| 1.1 | 2026-08-14 | Datapath validated end-to-end (XRd brings its own interfaces up; ARP/ICMP bidirectional). Add troubleshooting entry for the one-way-link symptom (GNS3 link UDP self-loop bug, see bugs/link-udp-self-loop.md). |
| 1.0 | 2026-08-14 | Initial documentation of the XRd control-plane adaptation: vendor path requirement, shm/devices/extra_configs/udev-mask mechanisms, host-disturbance root causes, appliance recipe. |
+402
View File
@@ -0,0 +1,402 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# VNC WebSocket Console
## Overview
GNS3 server supports WebSocket-based VNC console access, enabling browser-based graphical console connections to QEMU and Docker VMs without requiring standalone VNC client applications.
This implementation uses GNS3's API layer as a transparent WebSocket-to-TCP proxy, forwarding binary VNC protocol data between the browser and the VM's VNC server.
## Architecture
### Connection Flow
```mermaid
graph LR
A[Browser noVNC] -->|WebSocket binary| B[GNS3 Controller]
B -->|WebSocket + BasicAuth + SSL| C[GNS3 Compute]
C -->|TCP| D[QEMU/Docker VNC :5900]
```
**Controller** acts as a WebSocket-to-WebSocket relay (JWT auth, IPv6 handling).
**Compute** acts as a WebSocket-to-TCP bridge (validates node state, opens VNC TCP connection).
### Components
1. **Browser (noVNC)**
- HTML5 VNC client running in the browser
- Connects via WebSocket using `binary` subprotocol
- Handles RFB protocol (Remote Frame Buffer) for VNC
2. **GNS3 Controller API**
- WebSocket endpoint: `/v3/projects/{project_id}/nodes/{node_id}/console/vnc`
- Authentication: JWT token via query parameter
- Authorization: RBAC privilege check via `has_privilege_on_websocket("Node.Console")`
- Proxies WebSocket to compute node (WebSocket-to-WebSocket relay)
- Handles IPv6 addresses by wrapping in brackets
3. **GNS3 Compute API**
- WebSocket endpoint: `/v3/compute/projects/{project_id}/{node_type}/nodes/{node_id}/console/vnc`
- Authentication: HTTP Basic Auth via `ws_compute_authentication()`
- Establishes TCP connection to VNC server, bridges WebSocket ↔ TCP
4. **Node (QEMU/Docker)**
- VNC server listening on configured port (default: 5900+)
- RFB protocol for remote display
## API Endpoints
### Controller WebSocket Endpoint
**URL**: `ws://{controller_host}:{port}/v3/projects/{project_id}/nodes/{node_id}/console/vnc?token={jwt_token}`
**Authentication**:
- JWT token via query parameter, **or** a short-lived console ticket (`gns3t_…`, valid 10 min, bound to this node's console endpoints — no MCP tool currently mints these; the redemption path is reserved for handing node console access to external clients)
- User must have `Node.Console` privilege
**WebSocket Subprotocols**:
- Accepts: `binary`
- Used by noVNC for binary data transfer
**Request Example**:
```javascript
const token = "eyJ0eXAiOiJKV1QiLCJhbGc...";
const wsUrl = `ws://localhost:3080/v3/projects/${projectId}/nodes/${nodeId}/console/vnc?token=${token}`;
const ws = new WebSocket(wsUrl, 'binary');
ws.binaryType = 'arraybuffer';
```
### Compute WebSocket Endpoint
**URL**: `ws://{compute_host}:{port}/v3/compute/projects/{project_id}/{node_type}/nodes/{node_id}/console/vnc`
**Authentication**:
- HTTP Basic Auth via `ws_compute_authentication()` dependency
- Configured via `settings.Server.compute_username` (default: `gns3`) and `settings.Server.compute_password` (default: empty)
**Response**:
- Bidirectional binary WebSocket connection
- Transparent VNC protocol forwarding
## Supported Node Types
### QEMU VMs
**Console Type Configuration**:
```json
{
"console_type": "vnc",
"console": 5900,
"console_resolution": "1024x768"
}
```
**QEMU Parameters**:
```bash
-vnc :0 # VNC on display 0 (port = 5900 + display)
```
**Implementation**:
- File: `gns3server/api/routes/compute/qemu_nodes.py`
- Endpoint: `/{node_id}/console/vnc`
- Method: `start_vnc_websocket_console(websocket)`
### Docker Containers
**Console Type Configuration**:
```json
{
"console_type": "vnc",
"console": 5900,
"console_resolution": "1024x768",
"console_http_port": 8080,
"console_http_path": "/"
}
```
**Implementation**:
- File: `gns3server/api/routes/compute/docker_nodes.py`
- Endpoint: `/{node_id}/console/vnc`
- Method: `start_vnc_websocket_console(websocket)`
## WebSocket Data Forwarding
### Compute Layer (WebSocket ↔ TCP)
**Location**: `gns3server/compute/base_node.py` — `start_vnc_websocket_console()`
1. Validates node is started and `console_type == "vnc"`; closes WebSocket with code 1000 otherwise
2. Opens TCP connection to VNC server at `console_host:console_port`
3. Runs two concurrent tasks via `asyncio.wait(FIRST_COMPLETED)`:
- `ws_forward()`: WebSocket → TCP (catches `WebSocketDisconnect`)
- `vnc_forward()`: TCP → WebSocket (reads 65536-byte buffer)
4. Cancels pending tasks, closes TCP writer on completion
### Controller Layer (WebSocket ↔ WebSocket)
**Location**: `gns3server/api/routes/controller/nodes.py` — `vnc_console()`
1. Authenticates user via `has_privilege_on_websocket("Node.Console")` dependency
2. Constructs compute URL with IPv6 bracket handling
3. Connects to compute WebSocket using `aiohttp.ws_connect()` with HTTP Basic Auth and SSL context
4. Uses `asyncio.ensure_future()` for client→compute forwarding, `async for msg` iteration for compute→client
### Data Flow
```mermaid
sequenceDiagram
participant B as Browser (noVNC)
participant C as Controller
participant W as Compute
participant V as VNC Server
B->>C: WebSocket connect (binary, JWT token)
C->>W: WebSocket connect (binary, BasicAuth, SSL)
W->>V: TCP connect (asyncio.open_connection)
Note over B,V: Bidirectional binary forwarding active
B->>C: WebSocket binary frame
C->>W: aiohttp send_bytes()
W->>V: TCP write(data)
V->>W: TCP data (read 65536)
W->>C: WebSocket binary frame
C->>B: send_bytes()
```
## Authentication & Authorization
### Controller Layer
1. **Authentication**:
- JWT token validation via `has_privilege_on_websocket("Node.Console")` dependency
- Token passed as query parameter: `?token={jwt}` (the server also redeems node-bound console tickets, `gns3t_…`, on these routes)
2. **Authorization**:
- RBAC privilege check: `Node.Console`
- Per-node access control
3. **WebSocket Subprotocol**:
- Client requests: `binary`
- Server accepts: `binary` (if requested)
### Compute Layer
1. **Authentication**:
- HTTP Basic Auth
- Credentials from controller config
- Username: `settings.Server.compute_username`
- Password: `settings.Server.compute_password`
2. **Node Validation**:
- Check node exists
- Check node is started
- Check console type is `vnc`
## Configuration
### Server Settings
**Controller Configuration** (`gns3-server.conf`):
```ini
[Server]
host = 0.0.0.0
port = 3080
```
**Compute Configuration** (same file):
```ini
[Server]
compute_username = gns3
compute_password = # empty by default, must be set for compute auth
```
### VNC Port Range
VNC console ports are allocated from a configurable range (`gns3server/schemas/config.py`):
| Setting | Default | Range |
|---------|---------|-------|
| `vnc_console_start_port_range` | 5900 | 5900–65535 |
| `vnc_console_end_port_range` | 10000 | 5900–65535 |
Validation: `vnc_console_end_port_range` must be greater than `vnc_console_start_port_range`.
### Node Settings
**QEMU VM Example**:
```json
{
"name": "vm-1",
"node_type": "qemu",
"console_type": "vnc",
"console": 5900,
"console_resolution": "1280x720",
"properties": {
"qemu_path": "/usr/bin/qemu-system-x86_64"
}
}
```
**Docker Container Example**:
```json
{
"name": "container-1",
"node_type": "docker",
"console_type": "vnc",
"console": 5900,
"console_resolution": "1024x768",
"console_http_port": 8080
}
```
## Troubleshooting
### Common Issues
**1. "Node is not started"**
- **Symptom**: WebSocket closes immediately
- **Solution**: Start the VM before opening console
- **API Check**: `GET /v3/projects/{project_id}/nodes/{node_id}` → verify `status == "started"`
**2. "Console type is not vnc"**
- **Symptom**: WebSocket closes with error
- **Solution**: Set node console_type to "vnc"
- **API Update**: `PUT /v3/projects/{project_id}/nodes/{node_id}` with `{"console_type": "vnc"}`
**3. "Cannot connect to VNC server"**
- **Symptom**: Connection timeout
- **Possible Causes**:
- VNC server not listening
- Port conflict
- Firewall blocking connection
- **Verification**:
```bash
# Check if VNC is listening
netstat -tlnp | grep 5900
# Check QEMU process
ps aux | grep qemu
```
**4. WebSocket Subprotocol Negotiation Failed**
- **Symptom**: Connection rejected during handshake
- **Solution**: Ensure noVNC sends `binary` subprotocol
- **Browser Console Check**:
```javascript
console.log(ws.protocol); // Should be "binary"
```
**5. Authentication Errors**
- **Symptom**: HTTP 401/403 responses
- **Controller**: Check JWT token is valid and not expired
- **Compute**: Verify compute username/password in config
### Debug Logging
**Enable Detailed Logging**:
```ini
[gns3server]
debug = true
```
**Check Controller Logs**:
```bash
# Look for WebSocket connection messages
grep "VNC console WebSocket" /var/log/gns3/gns3.log
```
**Check Compute Logs**:
```bash
# Look for VNC forwarding messages
grep "Connected to VNC server" /var/log/gns3/gns3.log
```
**Browser Console**:
```javascript
// Enable noVNC debugging
RFB.messages.log = function(msg) { console.log(msg); };
```
## Security
### Authentication
1. **Controller → Client**
- JWT token with expiration
- RBAC authorization
- Privilege: `Node.Console`
2. **Controller → Compute**
- HTTP Basic Auth via `aiohttp.BasicAuth`
- SSL context from `Controller.instance().ssl_context()`
- Raises `ControllerForbiddenError` if `compute_username` is not set
3. **VNC Server**
- Optional VNC password (QEMU only)
- Configured via node properties
### Network Security
**Recommendations**:
1. Use HTTPS/WSS for production deployments
2. Firewall compute API ports
3. Use short-lived JWT tokens
4. Enable VNC password for sensitive VMs
**Example**:
```bash
# Controller with TLS
gns3server --ssl --cert /path/to/cert.pem --key /path/to/key.pem
# VNC with password
qemu-system-x86_64 -vnc :0,password
```
### WebSocket Security
**Subprotocol Validation**:
- Only `binary` subprotocol is accepted
- Prevents protocol downgrade attacks
**Origin Validation**:
- Browser enforces same-origin policy
- Configure CORS if using separate domains
## Limitations
1. **Single Client per VNC Port**
- VNC protocol supports one client at a time
- New connections disconnect existing clients
2. **No Audio Redirection**
- VNC protocol does not support audio
3. **No USB Redirection**
- VNC protocol does not support device redirection
4. **Performance Overhead**
- WebSocket-to-TCP bridging adds processing overhead compared to native VNC clients
## References
- [RFB Protocol 3.8](https://tools.ietf.org/html/rfc6143) - VNC Protocol Specification
- [noVNC Documentation](https://github.com/novnc/noVNC) - HTML5 VNC Client
- [FastAPI WebSocket](https://fastapi.tiangolo.com/advanced/websockets/) - WebSocket Implementation
- [GNS3 Documentation](https://docs.gns3.com/) - General GNS3 Documentation
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.1 | 2026-04-19 | Review against code: fix buffer size, auth details, add port range config, remove unverified content |
| 1.0 | 2026-03-17 | Initial VNC WebSocket documentation |
+65
View File
@@ -0,0 +1,65 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is AI-generated with reference to actual code and verified against real-kernel testing. AI can make mistakes — please verify against the source code when in doubt.
# VPCS kernel datapath
A VPCS node's single adapter anchors on a **persistent TAP** that the server creates and the vpcs process *attaches to* (`vpcs -e -d <anchor> -n`), the same server-creates/guest-attaches shape as QEMU's netdev. Links between a VPCS node and any other anchoring node type on the same compute are wired in the kernel (per-link Linux bridge) instead of the uBridge UDP relay; the compute side is the shared `KernelDatapathMixin`, which is anchor-agnostic.
## Architecture
The anchor follows the shared naming contract of `gns3server/utils/kernel_anchor.py`: `gp{node_id[:8]}e0p0` (14 chars, within the kernel's 16-byte `IFNAMSIZ`). The startup sequence is ordered — the TAP must exist before the process that reads it:
```
server → uBridge: tap create "gp70264b59e0p0" open /dev/net/tun + TUNSETIFF + TUNSETPERSIST; born administratively DOWN
server → uBridge: tap set_owner gp70264b59e0p0 <uid> hand the device to the server's own uid (vpcs is its child process)
server → vpcs: vpcs -e -d gp70264b59e0p0 -n tap mode, attach to that device, no host-side configuration
```
vpcs's `open_tap()` opens `/dev/net/tun` and issues `TUNSETIFF` with that name: the device already exists and its owner is vpcs's own uid, so the kernel takes the *attach* path — no privileges needed. (Only *creating* a tun/tap device needs `CAP_NET_ADMIN`; attaching to an owned one does not.) uBridge is never in the data path: a frame travels `vpcs read/write ↔ tap fd ↔ gp anchor ↔ per-link bridge ↔ peer anchor`, and every interface-level operation afterwards — carrier (`link set up/down`), bridge membership, tc filters, capture, markers — is the server driving uBridge over its control channel. The per-link bridge, filters, capture, markers and suspend all ride the same mixin paths as every other anchor-backed node type — including the Ethernet switch fast path (a switch link absorbs the `gp` anchor into the switch's own bridge).
The `setcap cap_net_admin` in the vpcs install target covers *standalone* use, where vpcs creates and activates its own TAP: creation always needs `CAP_NET_ADMIN`, and so does the `open_tap()` IFF_UP activation. Under GNS3 the capability is unnecessary — the activation silently no-ops without it (the server drives the anchor's carrier itself), which is why the server-side gating never asks for it.
```mermaid
flowchart LR
subgraph VA["vpcs process"]
ip["user-space IP stack"]
end
subgraph RootNS["root namespace"]
gpA["gp anchor TAP"]
BR["per-link bridge"]
end
ip <-->|"tap fd (-e -d)"| gpA
gpA <-->|"bridge port"| BR
```
## The three vpcs-side requirements
The stock vpcs build cannot carry this datapath; three things have to be true of the binary, all verified against [the vpcs fork](https://github.com/GNS3/vpcs):
* **`-n` (no host auto-configuration)** — without it, every guest `ip` command runs `ifconfig <tap> <addr> netmask <mask> up` on the *anchor itself*: the server owns the anchor's addresses and bridge membership, so the guest reconfiguring it ranges from noise (a failed `ifconfig` on a name that cannot resolve) to sabotage (an address on an L2-only anchor). `-n` also needs the `ifconfig` to follow the `-d` name when it does run — the stock build hardcodes `tap0`.
* **`-d` only in single-VPC mode** — `-i 1` is how the server always launches vpcs, so this is free.
* **`IFNAMSIZ`, not `IFNAMESIZ`** — upstream vpcs has a one-letter bug: `globle.h` defines its own `IFNAMESIZ 12`, `open_tap()` sizes its name buffer with it (`char dev[IFNAMESIZ]`) while the length guard checks the kernel's `IFNAMSIZ` (16). A 14-char anchor name passes the guard, overflows the 12-byte buffer, and reaches `TUNSETIFF` truncated to 12 chars — a nonexistent device, which the kernel tries to *create*, which needs `CAP_NET_ADMIN`, which the unprivileged vpcs does not have: `EPERM`, every time. The fork uses `IFNAMSIZ` consistently (worth an upstream PR; names up to 12 chars never trip it, which is why four years of `-d tap0` never noticed).
## Gating and fallback
A compute reports two capabilities for this (`/capabilities`, probed like every other kernel-datapath capability): `ubridge_tap` (uBridge's persistent-TAP module) and `vpcs_tap` (the binary answers `-n` in its usage — probed once per binary identity). A kernel link needs both strict-True on the compute; anything else keeps the node on the relay, where it always works. The node also decides its own datapath at start: without the probes it keeps the legacy local-UDP-tunnel shape (`-s/-c/-t` to the uBridge relay), with them it anchors and a relay link rides the anchor as an AF_PACKET endpoint — the relay-mode negative control covers both shapes.
## Stop order and the delete race
The vpcs process holds the anchor's fd, so stop is the QEMU order: terminate the process first, then `tap delete` — a held device refuses deletion and the suppressed delete would leak it. vpcs's daemon parent additionally kills its console child and exits *before* the child's fds are actually released, so the server can reap the tracked parent while the tap is still held: the shared `_delete_anchor_taps` now verifies each tap is gone from `/sys/class/net` and retries a bounded three times with a grace period (this race is not VPCS-specific — any holder that releases its fd a beat after its process was reaped hits it).
## Verified (real kernel, real vpcs)
The e2e scenario (`tests/e2e/test_vpcs_kernel_datapath.py`) drives two real VPCS nodes through the controller API and their TCP consoles:
* kernel link reports `kernel_datapath`, anchors exist from node start, the per-link bridge enslaves exactly the two of them; real ICMP crosses the tap-fd leg both ways;
* the L2-anchor spec §E.1 (the anchor stays address-free — the assertion `-n` exists for) and §E.2 (a VPCS sends nothing spontaneously, so the silence window needs no guest shutdown);
* `delay 100` lands as netem on both anchors (RTT grows ~200 ms); suspend admin-downs the anchor and kills the traffic; a capture on the link writes a real pcap;
* link delete releases the anchor but it survives (the running vpcs holds it); re-creating the link re-enslaves it;
* node stop terminates vpcs, deletes the anchor and the orphan bridges; a restart recreates the TAP, rewires the link from the NIO and the reconfigured VPCS pings again;
* deleting the project leaves no anchors and no bridges behind;
* the relay negative control (isolated relay-configured instance) wires nothing into the kernel and still pings, with the relay filters served by the uBridge bridge engine — verified with both the fork binary (relay on the anchor) and a stock binary (the legacy UDP tunnel).
+121
View File
@@ -0,0 +1,121 @@
# Cross-compute VXLAN links
## Overview
A link whose endpoints live on two different computes normally flows through the uBridge UDP relay: each end's anchor is attached to a userspace relay bridge and the frames cross the network as plain UDP payloads pumped by uBridge. This feature adds a second, **kernel-native** cross-compute datapath: each end creates a **VXLAN device** (uBridge's `vxlan` module, rtnetlink) and enslaves it into the same per-link kernel bridge the same-host datapath uses, so the kernel encapsulates and decapsulates and no userspace process is on the data path.
It is **opt-in and off by default** (`Server.enable_vxlan_cross_compute`). The reason is MTU: a tunnel can only carry what the underlay carries minus the outer headers, so its sweet spot is a fabric that moves jumbo frames. The relay stays the default cross-compute datapath and the fallback whenever a tunnel cannot be wired — it always works, at the price of a userspace hop.
## Terms
| Term | Meaning |
|---|---|
| Anchor | The host-side interface an adapter owns (a veth host end, a persistent TAP); links attach *to* it, never create it |
| Relay | The default cross-compute datapath: uBridge userspace bridges pumping UDP tunnels between the computes |
| Tunnel device | The per-end VXLAN device (`gvl…`) carrying one link's frames to the peer compute |
| VNI | The VXLAN network identifier — the kernel's demux key for received frames; both ends of a link must use the same one |
| dstport | The UDP port every tunnel of a deployment listens on; the kernel serves one socket per port and demuxes its traffic by VNI |
| Lower device | The underlay interface the route to the peer resolves to; the kernel derives the tunnel's MTU from it |
## Architecture
```mermaid
flowchart LR
subgraph GA["guest A"]
EA["eth0"]
end
subgraph CA["compute A"]
AA["anchor"] --> BA["bridge"]
BA --> VA["tunnel device"]
end
subgraph U["underlay"]
UD["UDP to the peer, demuxed by VNI"]
end
subgraph CB["compute B"]
VB["tunnel device"] --> BB["bridge"]
BB --> AB["anchor"]
end
subgraph GB["guest B"]
EB["eth0"]
end
EA --> AA
VA --> UD
UD --> VB
AB --> EB
```
Everything on the anchor side is shared with the same-host kernel datapath: filters (the full tc surface including the netem extensions the relay cannot run), markers, capture and suspend all run on the anchor, so they behave identically on a tunneled link. The controller picks the VNI and the device names and hands the peer's address to each end; the kernel does the rest. The device names are a pure function of the link id (bridge, `gvl` device) and the endpoint's node id (device), so each machine can recognise its own leftovers without asking anyone.
## Datapath selection
The controller's `UDPLink._kernel_datapath_eligible` decides at NIO prepare time, on every link (re)creation:
| Condition | Outcome |
|---|---|
| Both endpoints on one compute, both able to anchor | Kernel link (per-link bridge, unchanged) |
| Cross-compute, `enable_vxlan_cross_compute` on, both computes report `ubridge_vxlan`, both ends anchorable, addresses on a common subnet and distinct | **VXLAN tunnel** |
| Same-host pair (both computes resolve to one address) | Relay — the kernel keeps one socket per dstport, so a tunnel pair collides with itself on one host |
| Ethernet switch on either end (cross-compute), serial / non-Ethernet ports, unix-socket vendor containers | Relay |
| Capability missing, flag off, or the link was already downgraded | Relay |
On project (re)open every link re-runs the same decision, so flipping the flag upgrades or downgrades links the same way the same-host datapath is chosen.
## Link creation
Each end's compute owns its own machine: it resolves the lower device from the peer address locally, creates the device and enslaves it. The resolution is per tunnel, not a host setting: a connected UDP socket makes the kernel run the route lookup for the peer (nothing is sent), the chosen source address is matched back to the interface that holds it, and that interface becomes the `dev=` — carrying both the derived MTU and the outer source address along the actual routed path, policy routing included. Two peers reachable through different interfaces therefore ride different lower devices with independently derived MTUs; a peer with no route, or a source address no interface owns, is a wiring error and the link degrades to the relay. The two sides never talk to each other; the controller's VNI is what makes them a pair.
```mermaid
sequenceDiagram
participant C as Controller
participant UA as Compute A uBridge
participant UB as Compute B uBridge
C->>UA: NIO: bridge, VNI, dstport, peer address
C->>UB: NIO: bridge, VNI, dstport, peer address
par compute A
UA->>UA: vxlan show, delete a leftover
UA->>UA: vxlan create with the local lower device
UA->>UA: brctl addif bridge anchor, tunnel
and compute B
UB->>UB: vxlan show, delete a leftover
UB->>UB: vxlan create with the local lower device
UB->>UB: brctl addif bridge anchor, tunnel
end
Note over C: a refused create retries with a fresh VNI, then degrades the link to the relay
```
The `vxlan show` step is the idempotency contract: a device found under the link's deterministic name belongs to this link (a crashed run's leftover, the previous instance of a node restart) and is replaced, never refused. A create that fails with the name free can only be the VNI — the kernel refuses one already registered on the shared socket — so the controller bumps the derivation salt and retries, and after the retries run out it marks the link downgraded and rebuilds it on the relay. The same shape covers project open: a refused entry is reported per link by the batch route, retried on fresh VNIs up to the same candidate count an interactive creation gets, then degraded, so a VNI collision can never make a project unopenable. And a link wired while its nodes were stopped meets its collision only at node start — the controller's `Node.start` recognises the refused device (its name names the link), stops the half-started node, re-wires the link on a fresh VNI or, on a second refusal, degrades it to the relay, and retries: no path can fail permanently over a VNI.
## Interfaces
| Interface | Where | Notes |
|---|---|---|
| `nio_bridge.vxlan` (name, vni, remote, dstport) | Compute API, NIO create/update body | Present only on cross-compute kernel links; ignored by update (the device persists) |
| `ubridge_vxlan` | `GET /capabilities` and `GET /computes/{id}` | Probed with a scratch create/delete on a scratch port; `null` (unknown) keeps links on the relay |
| `kernel_datapath` | Link REST payload | True for tunneled links, like any kernel link |
## Configuration
| Key | Default | Meaning |
|---|---|---|
| `Server.enable_vxlan_cross_compute` | `false` | Wire eligible cross-compute links as VXLAN tunnels |
| `Server.vxlan_dstport` | `4789` | The UDP port all tunnels of the deployment listen on (one kernel socket per port; the IANA-assigned VXLAN port — change it when other VXLAN software on the computes already owns it, since a shared socket merges demux tables) |
## Known caveats
* **MTU is the whole story.** The kernel derives the tunnel device's MTU from the lower device (`underlay − 50` for an IPv4 underlay, `− 70` for IPv6; the 50 is 20 outer IPv4 + 8 UDP + 8 VXLAN + 14 inner Ethernet header — a VXLAN packet carries the guest's complete inner frame, per `vxlan_headroom()` in `include/net/vxlan.h`) and the per-link bridge, which carries no MTU of its own, reports the minimum of its ports — i.e. the derived value. A frame past it is dropped at the bridge egress **silently** (no ICMP, no log), which is why the datapath is opt-in: on a 1500-byte fabric a tunnel caps guests at 1450 while the relay carries 1500 with no tax. Guests set their own interface MTU, exactly like a VM or container raising eth0 on the same-host datapath.
* **Asymmetric underlays give one-way jumbo.** The derivation is per machine: a 9000-MTU compute paired with a 1500-MTU one forwards large frames in one direction only. Keep the fabric's MTU uniform between computes.
* **The MTU is derived at device creation and never tracks the underlay afterwards** — the vxlan driver registers no `NETDEV_CHANGEMTU` handler. Re-creation re-derives — and re-resolves the lower device, so a route change is picked up with it — and the wiring path deletes and re-creates the device (`_ensure_vxlan_device`) on every node start and link (re)creation, so the operational fix is: change the underlay MTU on **both** computes, then stop/start the nodes (or re-create the link, or reopen the project). A manual `ip link set <tunnel> mtu` on a live deployment also sticks: the bridge, unlike the tunnel, follows its ports' MTU at runtime (`NETDEV_CHANGEMTU → br_mtu_auto_adjust`), up and down, as long as the bridge MTU was never set by hand — ours never is.
* **VNI collisions self-heal, not never happen.** The VNI is drawn from the upper VNI space (1M–16.7M) but two links of one deployment can still collide on a host. Every path where the kernel's refusal can surface carries its own heal: link creation retries a fresh VNI then degrades to the relay, project open re-dispatches refused entries the same way, and node start (a link wired while its nodes were stopped) stops the half-started node, re-wires the link on a fresh VNI or degrades it on a second refusal, and retries the start. A reopen re-rolls every link's VNI, so an unlucky link is not permanently unlucky.
* **Security is the relay's, unchanged.** VXLAN carries no authentication; the VNI and the shared port are the only demux, and anyone who can reach the port can inject into any VNI. Treat the compute fabric as trusted, exactly as for the relay's UDP tunnels.
* **Same-host compute pairs stay on the relay**, as do switch links, serial ports and unix-socket vendor containers — the tunnel is a per-link-bridge shape, and those cases are not (or would collide with themselves on one host).
## Verification
* Unit: `tests/controller/test_kernel_datapath_link.py` (selection matrix, tunnel spec derivation, VNI retry, downgrade), `tests/utils/test_vxlan.py`, `tests/compute/docker/test_docker_kernel_datapath.py` (device lifecycle, leftover replacement, teardown ordering), `tests/api/routes/compute/test_capabilities.py`.
* Live: no automated scenario — a second network stack on one machine means a network namespace, which needs root and host-specific routing and proved too environment-coupled for the suite. Validate on a real two-compute deployment (two machines, or a namespace-isolated second server): both ends agree on the VNI and dstport, each per-link bridge enslaves exactly `[anchor, tunnel]`, the derived MTU crosses while one past it is dropped at the bridge egress, traffic and filters behave as on the same-host datapath, and link delete plus project close/reopen leave no devices behind.
## Roadmap
* PMTU probing between computes to pick the datapath (and pin the MTU) per pair instead of a deployment-wide flag.
* Ethernet switch links tunneled through the switch's own bridge (the absorbed-anchor shape) instead of falling back to the relay.
* VNI-space bookkeeping to make collisions impossible by construction rather than self-healing.
@@ -0,0 +1,620 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Web Wireshark Feature - Business Process Documentation
## Overview
The **Web Wireshark** feature enables users to run Wireshark packet capture analysis directly in a web browser without requiring a desktop environment or VNC connection. This is achieved through an **xpra** (persistent remote applications) HTML5 client running inside a Docker container.
## Feature Summary
- **Core Capability**: Web-based packet capture visualization using Wireshark
- **Technology Stack**: Docker container + xpra + HTML5 WebSocket proxy
- **Target Users**: Network engineers and students who need to analyze network traffic in GNS3 topologies
- **Key Benefit**: Zero-install, browser-based packet capture analysis
---
## Installation
Before using Web Wireshark, install the GNS3 server and set up the Docker image:
```bash
# Development install
pip install -e . && gns3server-web-wireshark-setup
# Production install
pip install gns3-server && gns3server-web-wireshark-setup
```
This command will:
1. Install the gns3-server package
2. Pull the `gns3/web-wireshark:latest` image from Docker Hub
3. If pull fails, build the image locally using the included Dockerfile
The `wireshark` command shows the raw output from `docker pull` or `docker build`, allowing you to see the full progress.
---
## Architecture Overview
```mermaid
graph TD
subgraph GNS3Server["GNS3 Server"]
WebUI["Web UI<br/>(Browser)"]
Controller["GNS3 Controller"]
LinkCtrl["Link Controller<br/>(start_capture / stop_capture)"]
Manager["WebWiresharkManager<br/>(called directly, not via CLI)"]
DockerClient["DockerHTTPClient<br/>(HTTP via Unix Socket)"]
end
subgraph DockerDaemon["Docker Daemon"]
Container["gns3-wireshark-{project_id}"]
Xvfb["Xvfb (virtual framebuffer)"]
Xpra["xpra server"]
Wireshark["Wireshark"]
end
ClientBrowser["Client Browser<br/>(HTML5 Client)"]
ClientBrowser -->|REST API| WebUI
WebUI -->|capture/start| Controller
Controller --> LinkCtrl
LinkCtrl -->|start/stop/restart session| Manager
Manager -->|Docker API<br/>/var/run/docker.sock| DockerClient
DockerClient -->|container lifecycle| Container
Container --- Xvfb
Container --- Xpra
Container --- Wireshark
ClientBrowser -.->|WebSocket proxy| Xpra
Xpra -.->|xpra HTML5| ClientBrowser
style GNS3Server fill:#e8f4fd,stroke:#2196f3
style DockerDaemon fill:#fff3e0,stroke:#ff9800
style ClientBrowser fill:#e8f5e9,stroke:#4caf50
```
---
## Component Description
### 1. Web UI (Client Browser)
- User interface for starting/stopping packet capture
- Receives WebSocket URL for connecting to xpra HTML5 client
- No plugins required - pure HTML5/JavaScript
### 2. GNS3 Controller
- Orchestrates the capture workflow
- Validates user permissions (RBAC)
- Manages link capture state
### 3. manage_wireshark.py (Management CLI)
- Command-line interface for container and session management
- **For manual debugging and testing only** — the server calls `WebWiresharkManager` directly at runtime
- Handles Docker container lifecycle
- Manages xpra sessions per link
### 4. WebWiresharkManager
- Core business logic for Web Wireshark
- Handles container creation, session startup/shutdown
- Deterministic port allocation based on link_id
### 5. DockerHTTPClient
- Async HTTP client for Docker API
- Communicates via Unix socket (/var/run/docker.sock)
- Manages container lifecycle
### 6. Docker Container (gns3-wireshark-{project_id})
- Runs xpra server with HTML5 support
- Contains Xvfb (virtual framebuffer) for headless Wireshark
- Streams display to browser via WebSocket
---
## Business Processes
### Process 1: Start Packet Capture with Web Wireshark
```mermaid
sequenceDiagram
actor User
participant WebUI as Web UI
participant Controller as Controller
participant LinkCtrl as Link Controller
participant Manager as WebWiresharkManager
User->>WebUI: 1. Start Capture
WebUI->>Controller: 2. POST /capture/start
Controller->>LinkCtrl: 3. _start_web_wireshark(jwt_token)
LinkCtrl->>Manager: 4. start_wireshark_session()
Note right of Manager: 5. Ensure network exists
Note right of Manager: 6. Get/create container
Note right of Manager: 7. Start xpra session<br/>(display + port)
Note right of Manager: 8. Start Wireshark<br/>(curl | wireshark -i - -k)
Manager-->>LinkCtrl: ws_url
LinkCtrl-->>Controller: ws_url
Controller-->>WebUI: 10. {capturing: true, ws_url: "ws://..."}
WebUI-->>User: 9. ws_url
Note over User,Manager: 11-12. Browser connects via WebSocket<br/>Server proxies to container xpra
```
**API Endpoint**: `POST /v3/projects/{project_id}/links/{link_id}/capture/start`
**Request Body**:
```json
{
"wireshark": true,
"data_link_type": "DLT_EN10MB",
"capture_file_name": "capture.pcap"
}
```
**Response**:
```json
{
"id": "link-uuid",
"capturing": true,
"ws_url": "ws://192.168.1.100:14500"
}
```
### Process 2: Container Lifecycle (Per Project)
```mermaid
flowchart TD
A["Project Open"] --> B["First Link Capture"]
B --> C["Container Created<br/>(one per project)"]
C --> D["Container Running"]
subgraph SessionArchitecture["Container Session Architecture"]
direction TB
D --> E["gns3-wireshark-{project_id}"]
subgraph Link1Session["Link 1 Session"]
L1Xpra["xpra :14503"]
L1Xvfb["Xvfb :14503<br/>(1920x1080x24)"]
L1WS["Wireshark<br/>(curl | wireshark -i -)"]
L1Bind["bind-ws=0.0.0.0:14503"]
L1Xpra --- L1Xvfb
L1Xpra --- L1WS
L1Xpra --- L1Bind
end
subgraph Link2Session["Link 2 Session"]
L2Xpra["xpra :11024"]
L2Xvfb["Xvfb :11024<br/>(1920x1080x24)"]
L2WS["Wireshark<br/>(curl | wireshark -i -)"]
L2Bind["bind-ws=0.0.0.0:11024"]
L2Xpra --- L2Xvfb
L2Xpra --- L2WS
L2Xpra --- L2Bind
end
E --> Link1Session
E --> Link2Session
Note1["display = port = 10000 + hash(link_id) % 10000<br/>Each xpra creates its own Xvfb (NOT shared)"]
end
D --> F["Project Close"]
F --> G["Stop Container<br/>(all sessions terminate)"]
G --> H["Container Stopped<br/>(preserved for reuse)"]
H -->|Project Reopened| D
I["Project Delete"] --> J["Delete Container"]
J --> K["Container Removed"]
style SessionArchitecture fill:#fff8e1,stroke:#ffa000
style Link1Session fill:#e3f2fd,stroke:#1976d2
style Link2Session fill:#e8f5e9,stroke:#388e3c
```
### Process 3: WebSocket Connection Flow
```mermaid
sequenceDiagram
participant Browser as Client Browser
participant Server as GNS3 Server (API Route)
participant Container as Docker Container (xpra)
Browser->>Server: 1. WSS Connect (ws://.../web-wireshark?token=jwt)
Note right of Server: 2. Validate JWT<br/>(RBAC: Link.Capture)
Note right of Server: 3. Get container IP<br/>from Docker API
Server-->>Browser: 4. Accept connection
Note right of Server: 5. Start WebSocket proxy
Server->>Container: 6. Connect to xpra<br/>ws://container:port
Container-->>Server: 7. xpra validates subprotocol
Note over Browser,Container: 8-9. Bidirectional WebSocket proxy<br/>Browser ⟺ Server ⟺ Container
Note left of Browser: 10. HTML5 client renders<br/>Wireshark window
```
**WebSocket Endpoint**: `ws://host/v3/projects/{project_id}/links/{link_id}/capture/web-wireshark?token=<jwt_token>`
### Process 4: Capture Data Flow
```mermaid
flowchart LR
subgraph GNS3Node["GNS3 Node"]
Router["Router / Switch"]
end
subgraph ComputeNode["Compute Node"]
Capture["Link Capture Buffer"]
end
Router -->|"TAP (raw packets)"| Capture
subgraph GNS3Server["GNS3 Server"]
APIRoute["GET /capture/stream<br/>Proxies pcap stream"]
end
Capture -->|"pcap stream"| APIRoute
subgraph DockerContainer["Docker Container"]
direction TB
Curl["curl -N -H 'Authorization: Bearer {jwt}'<br/>'{server}/capture/stream'"]
Wireshark["wireshark -i - -k"]
Xvfb["Xvfb :display<br/>(1920x1080x24)"]
Xpra["xpra :display<br/>ws://0.0.0.0:{port}"]
Curl -->|"stdin pipe"| Wireshark
Wireshark -->|"renders to"| Xvfb
Xvfb -->|"X11 display"| Xpra
end
APIRoute -.->|"pcap stream<br/>(curl fetches from container)"| Curl
subgraph Browser["Client Browser"]
HTML5Client["HTML5/xpra Client"]
WSUI["Wireshark Web Interface"]
HTML5Client --> WSUI
end
Xpra <-->|"WebSocket"| HTML5Client
style GNS3Node fill:#f3e5f5,stroke:#7b1fa2
style ComputeNode fill:#e8eaf6,stroke:#283593
style GNS3Server fill:#e8f4fd,stroke:#2196f3
style DockerContainer fill:#fff3e0,stroke:#ff9800
style Browser fill:#e8f5e9,stroke:#4caf50
```
---
## Port Allocation Strategy
### Deterministic Port Mapping
```mermaid
flowchart LR
LinkID["link_id (UUID)"] --> Hash["MD5 Hash"] --> Modulo["hash % 10000"]
Modulo --> Offset["+ 10000"]
Offset --> Result["display = port<br/>Range: 10000 - 19999"]
style LinkID fill:#e3f2fd,stroke:#1976d2
style Result fill:#e8f5e9,stroke:#388e3c
```
| link_id | port/display |
|---------|-------------|
| `f233f27f-7432-49c3-9aa2-50e326a10eec` | 14503 |
| `a1b2c3d4-1234-5678-90ab-cdef12345678` | 11024 |
| `12345678-90ab-cdef-1234-567890abcdef` | 17892 |
**Benefits**:
- Same link always gets same port (deterministic)
- Display number = port number (same hash)
- No port conflicts between sessions
- Easy to predict and debug
---
## Network Architecture
```mermaid
graph TD
subgraph HostMachine["Host Machine"]
subgraph GNS3ServerHost["GNS3 Server<br/>192.168.1.100:3080"]
WSProxy["WebSocket Proxy"]
end
subgraph DockerNetwork["Docker Bridge: gns3-wireshark<br/>Subnet: 172.31.0.0/22"]
Gateway["Bridge Gateway<br/>172.31.0.1"]
Container["gns3-wireshark-{project_id}<br/>172.31.0.x"]
Gateway --- Container
end
end
Client["Client Browser"] -->|"ws://192.168.1.100:3080<br/>/capture/web-wireshark"| WSProxy
WSProxy -->|"via gateway 172.31.0.1<br/>ws://172.31.0.x:{port}"| Container
style HostMachine fill:#fafafa,stroke:#9e9e9e
style DockerNetwork fill:#e3f2fd,stroke:#1976d2
style GNS3ServerHost fill:#e8f5e9,stroke:#388e3c
```
---
## Session Management Commands
> **Note**: These commands are for manual debugging and testing only. The GNS3 server calls `WebWiresharkManager` directly at runtime.
### start
Starts Web Wireshark session for a specific link.
| Argument | Required | Default | Description |
|----------|----------|---------|-------------|
| `--project-id` | Yes | - | Project UUID |
| `--link-id` | Yes | - | Link UUID |
| `--jwt-token` | Yes | - | JWT authentication token |
| `--capture-url` | No | auto-detected | PCAP stream URL |
| `--image` | No | `gns3/web-wireshark:latest` | Docker image |
| `--memory` | No | `2g` | Memory limit |
| `--cpus` | No | `1.0` | CPU cores |
| `--pids-limit` | No | `1000` | Process limit |
```bash
python manage_wireshark.py start \
--project-id "5af0fe00-..." \
--link-id "f233f27f-..." \
--jwt-token "eyJhbG..."
```
### Other Commands
| Command | Description | Key Arguments |
|---------|-------------|---------------|
| `stop` | Stop session for a specific link | `--project-id`, `--link-id` |
| `restart` | Restart session (reopens Wireshark window) | `--project-id`, `--link-id`, `--jwt-token` |
| `stop-all` | Stop all sessions for a project | `--project-id` |
| `delete` | Delete container (alias for delete-container) | `--project-id` |
| `stop-container` | Stop container without deleting | `--project-id` |
| `delete-container` | Delete the container | `--project-id` |
---
## Project Close/Delete Workflow
```mermaid
flowchart TD
A["Project Close"] --> B["_stop_web_wireshark_container()"]
B --> C["WebWiresharkManager.stop_container(project_id)"]
C --> D["docker stop<br/>(all xpra/Xvfb/Wireshark terminate)"]
D --> E["Container Stopped<br/>(preserved for reuse)"]
E -->|Project Reopened| F["First Capture Start"]
F --> G["docker start<br/>(container already exists, fast)"]
G --> H["New xpra sessions created"]
I["Project Delete"] --> J["_cleanup_web_wireshark_container()"]
J --> K["WebWiresharkManager.delete_container(project_id)"]
K --> L["docker rm<br/>(container removed)"]
style A fill:#e3f2fd,stroke:#1976d2
style I fill:#ffebee,stroke:#c62828
style E fill:#fff8e1,stroke:#ffa000
style L fill:#ffebee,stroke:#c62828
```
---
## API Endpoints Summary
| Method | Endpoint | Description | Privilege |
|--------|----------|-------------|-----------|
| POST | `/v3/projects/{id}/links/{id}/capture/start` | Start capture with Web Wireshark | Link.Capture |
| POST | `/v3/projects/{id}/links/{id}/capture/stop` | Stop capture | Link.Capture |
| POST | `/v3/projects/{id}/links/{id}/capture/wireshark/restart` | Restart Wireshark window | Link.Capture |
| GET | `/v3/projects/{id}/links/{id}/capture/stream` | Stream PCAP data | Link.Capture |
| GET | `/v3/projects/{id}/links/{id}/capture/file` | Download PCAP file | Link.Capture |
| WS | `/v3/projects/{id}/links/{id}/capture/web-wireshark` | WebSocket proxy for xpra | Link.Capture |
---
## Security Considerations
1. **RBAC Authentication**: All endpoints require `Link.Capture` privilege
2. **JWT Token Validation**: WebSocket connections validate JWT token
3. **WebSocket Subprotocol Negotiation**: Proper xpra subprotocol handling
4. **Container Isolation**: Each project gets its own container with isolated resources
5. **Network Segmentation**: Container runs on isolated Docker network (not host network)
---
## Performance Characteristics
### Startup & Shutdown Performance
| Step | Before Optimization | After Optimization | Improvement |
|------|---------------------|-------------------|-------------|
| **Health Check** | ~1.0s | ~0s | Docker native status |
| **Gateway Detection** | 0.85s | ~0.001s | Docker API vs exec |
| **Process Cleanup** | ~850ms | ~40ms | Host perspective recursive tree walk |
| **Xpra Startup** | 6.4s | ~3s | HTML5 client disabled |
| **Wireshark Launch** | ~1s | ~1s | No change |
| **Total Startup** | **~15s** | **~5-6s** | **67% faster** |
| Step | Before Optimization | After Optimization | Improvement |
|------|---------------------|-------------------|-------------|
| **Process Termination** | ~8s | ~20-40ms | Recursive tree walk, no orphans |
| **File Cleanup** | ~850ms | ~850ms | Docker exec (safety) |
| **Total Shutdown** | **~9s** | **~2s** | **78% faster** |
#### Startup Breakdown: First vs Subsequent
| Phase | First Startup (Container stopped) | Subsequent Startup (Container running) |
|-------|-----------------------------------|----------------------------------------|
| Container startup | ~1-2s | ~0s (already running) |
| Container health check | ~1s (unhealthy→healthy) | ~0s (already healthy) |
| Gateway detection | ~0.001s | ~0.001s |
| Process cleanup | ~40ms | ~40ms |
| Xpra startup | ~3s | ~3s |
| Wireshark launch | ~1s | ~1s |
| **Total** | **~6s** | **~5s** |
#### Measured Performance Data
**Startup (from production logs):**
```
13:46:53 → 13:46:59 = 6s (first startup with container start)
13:47:38 → 13:47:43 = 5s (subsequent startup, container running)
```
**Shutdown (from production logs):**
```
13:48:15 → 13:48:17 = 2s (complete cleanup, no orphan processes)
13:48:50 → 13:48:52 = 2s (complete cleanup, no orphan processes)
```
#### Key Optimizations
- **Complete Process Cleanup**: Recursive process tree traversal eliminates orphaned processes (Xvfb, pulseaudio, ibus-daemon)
- **Fast Gateway Detection**: Docker API query instead of container exec
- **Smart Health Check**: Trust Docker built-in status, no manual ping
- **Xpra Optimization**: Disabled unnecessary HTML5 client (`--html=off`)
- **Reduced Docker Exec Calls**: Combined X lock and xpra socket cleanup into single exec call
### Docker Exec Performance Limitations
**Important**: Docker daemon has internal queuing for concurrent exec requests to the same container.
#### Test Results (Same Container)
| Test Scenario | Execution Time | Avg Per Exec |
|--------------|----------------|--------------|
| Single docker exec | 0.854s | 0.854s |
| Serial 7 docker exec | 7.225s | 1.032s |
| Parallel 7 docker exec | 10.253s | 1.465s |
**Key Finding**: Parallel execution is **42% slower** than serial execution.
```
Serial: 7.225s (7 requests processed sequentially)
Parallel: 10.253s (Docker daemon still processes sequentially + context switch overhead)
```
#### Impact on Web Wireshark
When stopping multiple capture sessions quickly:
- Each stop requires 1 docker exec (cleanup files)
- Docker daemon processes exec requests sequentially
- 7 sessions × ~1s each = ~7-10 seconds total
- User requests appear to "queue" even though they're concurrent
#### Optimization Strategy
Since Docker exec cannot be parallelized effectively:
1. **Minimize exec calls** - Already implemented: 2 calls → 1 call
2. **Accept serial processing** - No benefit to parallel execution
3. **Focus on fast exec content** - Use simple `rm -f` commands
#### Future Optimization Options
- Use Docker API instead of exec (requires container filesystem access)
- Delay cleanup to next startup (increases startup complexity)
- Batch multiple stops into single operation (requires API changes)
### Resource Usage (Per Wireshark Instance)
| Resource | Typical Usage |
|----------|---------------|
| Memory | 150-250 MB |
| CPU | 0.5-2% (idle to active) |
| Threads | ~30 threads |
| Disk I/O | Minimal |
### Container Configuration
Configured via `WebWiresharkSettings` in `gns3server/schemas/config.py`:
| Parameter | Default | Recommended | Description |
|-----------|---------|-------------|-------------|
| enabled | true | - | Enable/disable Web Wireshark feature |
| image | gns3/web-wireshark:latest | - | Docker image name |
| network_subnet | 172.31.0.0/22 | - | Docker bridge network subnet |
| Memory | 2GB | 2-4GB | Container memory limit |
| CPUs | 1.0 | 1.0-2.0 | Container CPU limit |
| PIDs Limit | 1000 | 1000 | Container process limit |
### Scaling Guidelines
| Instances | Memory | Use Case |
|-----------|--------|----------|
| 1-3 | 450-750 MB | Light projects |
| 4-6 | 600-1.5 GB | Medium projects |
| 7-10 | 1-2.5 GB | Large projects |
| 10+ | >2.5 GB | Increase memory |
---
## Docker API Compatibility
### Version Negotiation Mechanism
The Web Wireshark feature implements automatic Docker API version negotiation to ensure compatibility across different Docker versions:
1. **Primary**: Try API version 1.44 first
- Supports Docker 29.3+ (API 1.54+), which requires minimum API 1.44
2. **Fallback**: If server rejects 1.44 with 400 error, downgrade to API 1.40
- Supports Docker 20.10 (API 1.41)
### Tested Configurations
| Docker Version | API Version | API 1.40 | API 1.44 | Solution |
|----------------|-------------|----------|----------|----------|
| 20.10 | 1.41 | ✓ | ✗ | Fallback to 1.40 |
| 29.3+ | 1.54+ | ✗ | ✓ | Use 1.44 |
### Container IP Retrieval
The `get_container_ip()` method implements a dual-strategy approach for retrieving container IP addresses:
1. **Primary Method**: Query Docker Container API
- Uses `docker inspect` via HTTP API
- Safe access to `NetworkSettings.Networks` field using `.get()`
- Handles missing fields gracefully (fixes KeyError bug)
2. **Fallback Method**: Execute `hostname -I` command inside container
- Works when Docker API response lacks network information
- Compatible with containers without `ip` command
- Returns first IP address from `hostname -I` output
This dual approach ensures compatibility across different Docker API versions that may have varying response formats.
---
## Known Limitations
1. **JWT Token Visibility**: Token passed via command-line arguments (visible in `/proc/<pid>/cmdline`)
2. **Single Container**: All Wireshark instances run in a single container per project
3. **Docker Dependency**: Requires Docker daemon running on the server
4. **Browser Support**: Requires modern browser with WebSocket support
5. **Port Range**: Limited to 10,000 unique ports (10000-19999)
---
## File Structure
```
gns3server/
├── controller/
│ ├── link.py # Link capture lifecycle
│ └── project.py # Project cleanup hooks
├── api/routes/controller/
│ └── links.py # REST/WebSocket API endpoints
└── agent/web_wireshark/
├── setup_wireshark_image.py # Docker image setup tool
├── manage_wireshark.py # CLI management tool (manual/debug use only)
├── manager.py # Session management logic (called by server)
├── docker_client.py # Docker API client
├── stats.py # Container statistics collection
├── docker/
│ └── Dockerfile # Container image definition
└── WEB_WIRESHARK.md # Technical documentation
```
@@ -0,0 +1,169 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
# GNS3-Copilot AI Assistant Overview
## Overall Architecture
```mermaid
flowchart TB
subgraph "Client"
A["Web UI"] --> B["SSE Streaming"]
end
subgraph "FastAPI Route Layer"
B --> C["POST /chat/stream\nPOST /chat/inject"]
C --> D["Auth + LLM Config Loading\nSet ContextVars"]
end
subgraph "AgentService (Project-level)"
D --> E["LangGraph Agent\nStateGraph"]
E --> F["SQLite Checkpointer\ncopilot_checkpoints.db"]
end
subgraph "LangGraph Workflow"
E --> G["llm_call node\nmodel invocation"]
E --> H["tool_node\ntool execution"]
E --> I["title_generator_node\nauto title"]
E --> J["abort_handler_node\ninterrupt handling"]
end
subgraph "Three Copilot Modes"
G --> K["teaching_assistant\ndiagnostic read-only"]
G --> L["lab_automation_assistant\nfull control"]
G --> M["troubleshooting_injection\nfault injection"]
end
subgraph "LLM Config System"
D --> N["User configs\nGroup config inheritance\nAPI key encryption"]
end
```
## API Endpoints
| Endpoint | Function |
|---|---|
| `POST /v3/projects/{pid}/chat/stream` | Streaming conversation (SSE), supports three copilot modes |
| `POST /v3/projects/{pid}/chat/inject` | Fault injection entry, auto-switches to `troubleshooting_injection` mode |
| `GET /v3/projects/{pid}/chat/sessions` | List sessions (supports filtering, pagination) |
| `DELETE /v3/projects/{pid}/chat/sessions/{sid}` | Delete session |
| `PATCH /v3/projects/{pid}/chat/sessions/{sid}` | Update session (rename, pin) |
| `POST /v3/projects/{pid}/chat/sessions/{sid}/abort` | Abort an active session |
## LangGraph Agent Workflow
```mermaid
sequenceDiagram
participant U as User
participant API as FastAPI
participant AS as AgentService
participant LLM as LLM Node
participant Tool as Tool Node
participant TGen as Title Node
U->>API: send message
API->>AS: stream_chat()
AS->>AS: set ContextVars<br/>(jwt_token, llm_config)
Note over AS,LLM: llm_call node
AS->>LLM: invoke pre-compiled model
LLM->>LLM: pre_model_hook<br/>inject topology + trim context
LLM-->>AS: AI reply (may include tool_calls)
opt has tool calls
AS->>Tool: execute tools
Tool-->>AS: tool results
AS->>LLM: continue LLM call
end
opt first turn and no title
AS->>TGen: auto-generate title
TGen-->>AS: session title
end
AS-->>API: SSE streaming response
API-->>U: stream output
```
## Three Copilot Modes
### Mode Comparison
| Mode | Tool Scope | Use Case |
|---|---|---|
| `teaching_assistant` (default) | Diagnostic read-only + packet analysis + node management | Teaching demos, troubleshooting guidance |
| `lab_automation_assistant` | All tools (including config changes) | Lab automation, device configuration |
| `troubleshooting_injection` | Fault injection tool set | Troubleshooting practice, fault simulation |
### Tool Binding Details
| Tool | teaching_assistant | lab_automation_assistant | troubleshooting_injection |
|---|---|---|---|
| `template_list` / `template_get` templates | ✓ | ✓ | |
| `node_create` create nodes | ✓ | ✓ | |
| `node_list` / `node_get` inspect nodes | ✓ | ✓ | |
| `node_update` rename | ✓ | ✓ | |
| `node_start` start nodes | ✓ | ✓ | |
| `node_stop` / `node_suspend` stop/suspend | | ✓ | |
| `node_console_exec` raw console access | | ✓ | |
| `link_create` create links (native, port names) | ✓ | ✓ | |
| `link_list` inspect links | ✓ | | |
| `link_marker` traffic-insight markers | ✓ | | |
| `drawing_create_*` canvas annotations | ✓ | ✓ | |
| `device_show_run` read-only commands | ✓ | ✓ | ✓ |
| `device_config_send` config commands | | ✓ | ✓ |
| `vpcs_config_set` VPCS commands | | ✓ | |
| `device_skill_get` device skills | ✓ | ✓ | |
| `snapshot_list` / `snapshot_create` / `snapshot_delete` / `snapshot_restore` snapshots | | ✓ | |
| `link_update` / `link_available_filters` fault filters | | | ✓ |
| `link_capture_start` / `link_capture_stop` / `link_capture_download` capture | | | ✓ |
| `marker_definition` project-wide markers | | | ✓ |
| `injection_skill_get` fault injection skills | | | ✓ |
| `wait_seconds` boot wait (native) | ✓ | ✓ | |
| `packet_analysis` live packet analysis (native) | ✓ | ✓ | |
| `packet_analysis_skills` protocol knowledge (native) | ✓ | ✓ | |
| `gns3_topology_reader` topology info (native) | | | ✓ |
The mode is selected in the `llm_call` node via `copilot_mode`, which picks the corresponding tool list and binds it to the LLM model instance through `create_base_model_with_tools(mode_tools, llm_config)`.
## Context Window Management
```mermaid
flowchart LR
A["LLM call triggered"] --> B["pre_model_hook"]
B --> C["Inject topology\ninto System Prompt"]
B --> D["Estimate tool definition\ntoken cost"]
B --> E["trim_messages\nby strategy"]
E --> F["conservative 60%\nbalanced 75%\naggressive 85%"]
F --> G["Invoke LLM"]
```
- Accurate token counting via tiktoken (`cl100k_base`)
- Three trimming strategies: conservative / balanced / aggressive
- Auto-injects `{{topology_info}}` into System Prompt
## Session Management
- Per-project independent SQLite database (`gns3-copilot/copilot_checkpoints.db`)
- Supports pin, rename, delete, history query
- Auto-records token usage, message count, LLM call count
## LLM Config System
| Feature | Description |
|---|---|
| User-level configs | Each user can independently configure provider / model / api_key |
| Group inheritance | Users auto-inherit group config when no personal config is set |
| API key encryption | Auto-encrypted at database storage |
| Optimistic locking | `version` field prevents concurrent modification conflicts |
## Key Design Points
1. **Project-level Isolation** — Each GNS3 project has its own Agent instance and SQLite storage
2. **ContextVars Safe Passing** — JWT token, API key exist only in memory, auto-cleared when request ends
3. **LangGraph StateGraph** — Custom nodes + conditional edges, supports ReAct loop and recursion limits
4. **SSE Streaming** — Real-time push of content / tool_call / tool_start / tool_end / error / done events
5. **Hot Reload** — System Prompt, Skills, Protocols all support runtime reload
6. **Mode-based Tool Sets** — Three copilot modes bind different tools, safely isolated by scenario
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,224 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Command Security Configuration
## Overview
GNS3-Copilot includes multiple security layers to prevent execution of commands that may cause issues in the lab environment:
- **Command Filtering**: Prevents commands that may timeout or lock up the console
- **Configuration Safety**: Restricts dangerous configuration changes (AAA, passwords, etc.)
- **Multi-line Command Handling**: Properly processes commands with embedded newlines (banner, etc.)
## Architecture
```mermaid
graph TD
A[Tool Request] --> B{Command Filter}
B -->|allowed| C[Nornir/Netmiko Execution]
B -->|blocked| D[blocked_commands_info]
C --> E[Process Results]
D --> E
E --> F[Return Result]
subgraph Command Filter
B1[Load forbidden_commands.txt]
B2[Prefix match per command]
B1 --> B2
end
subgraph Security Layers
S1[Layer 1: Command Filter<br/>prefix-based blocking]
S2[Layer 2: AI Prompt Rules<br/>AAA/password guidance only]
S3[Layer 3: Multi-line Expansion<br/>banner/ACL handling]
S1 --> S2 --> S3
end
```
## Business Process
### Command Filtering Flow
```mermaid
flowchart TD
Start([Tool receives commands]) --> Load[Load forbidden patterns<br/>from config file]
Load --> Loop{For each command}
Loop -->|next command| Prefix{Command starts with<br/>forbidden pattern?}
Prefix -->|yes| Block[Add to blocked_commands_info]
Prefix -->|no| Allow[Add to allowed list]
Block --> Loop
Allow --> Loop
Loop -->|all checked| Empty{Allowed list empty?}
Empty -->|yes| Return1[Return partial_success<br/>with blocked info only]
Empty -->|no| Exec[Execute allowed commands<br/>via Nornir/Netmiko]
Exec --> HasBlocked{Has blocked commands?}
HasBlocked -->|yes| Return2[Return partial_success<br/>with output + blocked info]
HasBlocked -->|no| Return3[Return success<br/>with output]
```
### Multi-line Command Expansion Flow
```mermaid
flowchart TD
A[config_tools receives commands] --> B{Command contains \n?}
B -->|yes| C[Split by newline]
C --> D[Filter empty lines]
D --> E[Add expanded lines to command list]
B -->|no| F[Keep command as-is]
E --> G[Execute via netmiko_send_config]
F --> G
```
## Tools Using Command Security
| Tool | File | Filter | Multi-line Expansion | Result Fields |
|------|------|--------|---------------------|---------------|
| `device_show_run` | `gns3_client/device_show_commands.py` | Yes | No | `diagnostic_commands` |
| `device_config_send` | `gns3_client/device_config_commands.py` | Yes | Yes | `config_commands` |
## Command Filtering System
### Forbidden Commands Configuration
The forbidden commands list is loaded from the external [GNS3-Skills](https://github.com/gns3/gns3-skills) repository at `config/forbidden_commands.txt`.
**Format:**
- One command pattern per line
- **Prefix matching** (case-insensitive) — matches the beginning of each command
- Empty lines and lines starting with `#` are ignored
**Default patterns (used when skills repository is unavailable):**
| Pattern | Reason |
|---------|--------|
| `traceroute` | Can run 30+ seconds, exceeds tool timeout |
| `tracepath` | Similar to traceroute, long execution time |
| `tracert` | Windows traceroute, same timeout issues |
| `ping -f` | Flood ping can overwhelm lab devices |
| `debug` | Can produce overwhelming output and destabilize devices |
| `test` | May affect device stability |
### Result Format
**Status values:**
| Status | Condition |
|--------|-----------|
| `"success"` | All commands executed, none blocked |
| `"partial_success"` | Some commands blocked (including all blocked + execution succeeded) |
| `"failed"` | Execution failed (device not found, connection error, etc.) |
**Example — partial success (display tool):**
```json
{
"device_name": "R-1",
"status": "partial_success",
"output": "...",
"diagnostic_commands": ["show version", "show ip int brief"],
"blocked_commands": ["traceroute 8.8.8.8"],
"blocked_info": {
"traceroute 8.8.8.8": "Command 'traceroute 8.8.8.8' is not allowed because it matches the forbidden pattern 'traceroute'. ..."
}
}
```
> **Note:** `diagnostic_commands` is specific to display tools. Config tools use `config_commands` instead.
## Module Structure
**Command Filter:** `gns3server/agent/gns3_copilot/utils/command_filter.py`
| Function | Purpose |
|----------|---------|
| `filter_forbidden_commands(commands)` | Returns `(allowed_commands, blocked_commands_info)` |
| `is_command_forbidden(command)` | Check if a single command matches a forbidden pattern |
| `get_forbidden_commands()` | Get current forbidden patterns list |
| `reload_forbidden_commands()` | Directly load and cache commands from skills repository |
**Integration points:**
- `gns3_client/device_show_commands.py` — `_filter_forbidden_commands_from_device_configs()`
- `gns3_client/device_config_commands.py` — `_filter_forbidden_commands_from_device_configs()` + `_expand_multiline_commands()`
## Configuration Safety (AI Prompt Level)
In addition to the command filter, the AI agent is instructed via system prompt (`lab_automation_assistant_prompt.py`) to handle sensitive configuration commands with caution:
**Prompt-enforced rules:**
- **FORBIDDEN (guidance only):** `enable secret`, `username`, `aaa new-model`, `service password-encryption`, `line vty` — AI provides configuration guidance instead of executing
- **Caution required:** `reload`, `erase`, `format` — AI warns user before executing destructive operations
> These are prompt-level rules, not code-level enforcement. Users can always execute commands directly via device console or SSH/Telnet.
## Multi-line Command Handling
Commands containing `\n` are automatically split before execution by `device_config_commands.py:_expand_multiline_commands()`.
**Example:** `["banner motd #\nWelcome\n#"]` becomes `["banner motd #", "Welcome", "#"]`
Applies to any command with embedded newlines: `banner`, multi-line ACLs, route-maps, etc.
## Configuration
### Customizing Forbidden Commands
Edit `config/forbidden_commands.txt` in the [GNS3-Skills repository](https://github.com/gns3/gns3-skills) and push the changes, then call `POST /copilot/reload/skills` to apply them without restarting the server.
## Implementation Verification
### Test Results (Live GNS3 Environment)
**Scenario:** IOU-L2-1 (Cisco IOS L3 switch), mixed allowed/forbidden commands.
```json
{
"device_name": "IOU-L2-1",
"status": "partial_success",
"diagnostic_commands": [
"show ip route", "show ip interface brief",
"ping 10.0.0.1", "ping 10.0.0.2", "ping 10.0.0.4"
],
"blocked_commands": ["traceroute 10.0.0.2"],
"blocked_info": {
"traceroute 10.0.0.2": "Command 'traceroute 10.0.0.2' is not allowed because it matches the forbidden pattern 'traceroute'. ..."
}
}
```
| Feature | Status | Notes |
|---------|--------|-------|
| Prefix match filtering | Verified | `traceroute` correctly matched and blocked |
| Partial execution | Verified | Other commands executed successfully |
| `partial_success` status | Verified | Set correctly when blocked + succeeded |
| Multi-device support | Verified | Each device filtered independently |
| Non-blocking behavior | Verified | No tool timeouts or console issues |
## Future Enhancements
- **Regex support** for more sophisticated pattern matching
- **Per-project override files** for forbidden commands
- **Web UI configuration** for managing forbidden commands
- **Audit logging** for blocked command analysis
- **Per-command timeouts** instead of blocking
- **Interrupt mechanism** (Ctrl+C) for long-running commands
## Troubleshooting
| Problem | Solution |
|---------|----------|
| Command blocked unexpectedly | Check `blocked_commands` in result, identify matching pattern, edit `forbidden_commands.txt` |
| "File not found, using defaults" | Verify `config/forbidden_commands.txt` exists and is readable |
| Changes not taking effect | Call `POST /copilot/reload/skills` or restart server |
## Related Documentation
- [Skills Repository](skills-repository.md)
- [Fault Injection](fault-injection.md)
- [Chat API](chat-api.md)
@@ -0,0 +1,203 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# LLM Context Window Management
## Overview
GNS3 Copilot's context window management prevents LLM context overflow by trimming conversation history to fit within configured token limits. It uses tiktoken for accurate token counting, supports three context strategies (conservative/balanced/aggressive), and automatically injects GNS3 topology information into the system prompt before each LLM call.
## Architecture
```mermaid
graph TD
subgraph "context_manager.py"
A[create_pre_model_hook] --> B[_inject_topology_into_system]
A --> C[estimate_tool_tokens]
A --> D[trim_messages via LangChain]
E[count_tokens via tiktoken]
E --> C
E --> F[_count_tokens_for_message]
F --> D
end
subgraph "gns3_copilot.py"
G[llm_call node] --> H[Get topology via gns3_topology_reader]
H --> A
A --> I[model_with_tools.invoke]
end
style A fill:#4a9eff,color:#fff
style D fill:#ff6b6b,color:#fff
style E fill:#51cf66,color:#fff
```
## Key Components
| Function | File | Purpose |
|----------|------|---------|
| `create_pre_model_hook()` | `context_manager.py` | Factory that creates the preprocessing hook |
| `_inject_topology_into_system()` | `context_manager.py` | Injects topology into system prompt via `{{topology_info}}` placeholder |
| `count_tokens()` | `context_manager.py` | Accurate token counting using tiktoken (`cl100k_base`) |
| `estimate_tool_tokens()` | `context_manager.py` | Estimates token cost of tool definitions (JSON serialization) |
| `_count_tokens_for_message()` | `context_manager.py` | Token counter adapter for LangChain's `trim_messages` |
| `llm_call()` | `gns3_copilot.py` | StateGraph node that orchestrates the full LLM call pipeline |
**Token Counting**: Uses tiktoken `cl100k_base` encoding (GPT-4 compatible, 95%+ accuracy for most modern LLMs).
**tiktoken Cache**: Encoding files are cached locally at `<agent_package>/cache/tiktoken/` to avoid repeated downloads. This is configured before tiktoken import via `TIKTOKEN_CACHE_DIR` environment variable.
**Required Dependency**: `tiktoken>=0.8.0` — if not installed, `ModuleNotFoundError` is raised at startup.
## Trimming Process
```mermaid
flowchart TD
A[llm_call node invoked] --> B[Get topology via gns3_topology_reader]
B --> C[Create pre_model_hook]
C --> D[Inject topology into system prompt]
D --> E{topology data available?}
E -->|Yes| F[Replace placeholder with topology content]
E -->|No| G[Replace placeholder with 'No topology information available']
F --> H[Estimate tool definition tokens]
G --> H
H --> I[Calculate trim_messages budget]
I --> J[trim_messages with strategy='last']
J --> K[Return prepared messages]
K --> L[model.invoke with prepared messages]
```
### Token Budget Calculation
```mermaid
flowchart LR
A["context_limit<br/>(e.g. 128K)"] -->|"× strategy_ratio"| B["Input Budget<br/>(e.g. 96K @ balanced)"]
B -->|"− tool_tokens"| C["trim_messages Budget<br/>(includes system message)"]
C --> D["trim_messages<br/>max_tokens parameter"]
```
**Key**: `max_tokens` passed to `trim_messages` **includes** the system message. System tokens are NOT subtracted separately — `trim_messages` handles system message preservation via `include_system=True`.
### Budget Calculation Example
| Step | Calculation | Result |
|------|------------|--------|
| Context limit | 128 (configured) | 128K tokens |
| Strategy ratio | balanced = 0.75 | 128 × 1000 × 0.75 = 96,000 |
| Tool definitions | estimated from JSON schema | ~1,725 tokens |
| trim_messages budget | 96,000 − 1,725 | **94,275 tokens** (includes system) |
### Trimming Priority
| Priority | Content | Behavior |
|----------|---------|----------|
| 1 | System Message (system prompt + topology) | Always kept (`include_system=True`) |
| 2 | Latest conversation messages | Kept from newest to oldest |
| 3 | Older conversation history | Discarded first when exceeding budget |
**Note**: System prompt and topology are merged into a single `SystemMessage` via the `{{topology_info}}` template variable and cannot be trimmed independently.
### Edge Case Handling
| Scenario | Behavior |
|----------|----------|
| System + tools > input budget | ERROR log with recommendations (reduce prompt/tools, use larger model, switch to conservative). `trim_messages` is still called — `include_system=True` ensures system message is kept, but no history messages will fit. |
| Trim budget < system × 1.5 | WARNING log: minimal room for conversation history |
| Invalid context_strategy | Falls back to `balanced` with WARNING log |
| `trim_messages` throws exception | Returns untrimmed messages (graceful degradation) |
| Missing `{{topology_info}}` placeholder | Returns original messages without injection, WARNING log |
| Topology retrieval fails | Injects `"(No topology information available)"` placeholder |
## Integration with GNS3 Copilot
**File**: `gns3server/agent/gns3_copilot/agent/gns3_copilot.py`
### Why Direct Call, Not Config-based?
The agent uses a **custom StateGraph** (`StateGraph(MessagesState)`), not LangGraph's pre-built agent. LangGraph's `pre_model_hook` config parameter only works with pre-built agents like `create_react_agent`.
| Agent Type | pre_model_hook Support |
|------------|------------------------|
| `create_react_agent` | Via `config={"configurable": {"pre_model_hook": ...}}` |
| `chat_agent_executor` | Via `config={"configurable": {"pre_model_hook": ...}}` |
| **Custom StateGraph** | **Not supported** — must call directly |
### Execution Flow
In the `llm_call` node of `gns3_copilot.py`:
1. Get `llm_config` from request-scoped context variable
2. Get `project_id` from `config["configurable"]`
3. Retrieve topology via `gns3_topology_reader._run(project_id)`
4. Select tools based on `copilot_mode` (`teaching_assistant` vs `lab_automation_assistant`)
5. Load system prompt and create `pre_model_hook`
6. **Directly call** `pre_hook({"messages": messages, "topology_info": topology_info})` to prepare messages
7. Invoke `model_with_tools.invoke(prepared_messages)`
> **Note**: The actual `llm_call` function also includes defensive checks for missing config, empty messages, and topology retrieval errors — see source code for full details.
## Strategy Implementation
### Context Strategy Ratios
Defined as `CONTEXT_STRATEGY_RATIOS` in `context_manager.py`, with default `DEFAULT_CONTEXT_STRATEGY = "balanced"`.
| Strategy | Input Ratio | Output Reserved | Calculation |
|----------|-------------|-----------------|-------------|
| Conservative | 60% | 40% | `context_limit × 1000 × 0.60` |
| Balanced | 75% | 25% | `context_limit × 1000 × 0.75` |
| Aggressive | 85% | 15% | `context_limit × 1000 × 0.85` |
## Log Output
### Normal Case (topology injected)
```
INFO: Calling pre_hook to prepare 1 messages
INFO: ✓ Topology injected: 7722 chars, nodes: ['netshoot-1', 'R1', 'R2', 'IOU-L3-1', 'IOU-L3-2']
INFO: Context ready: 2 msgs, ~3815 tokens + 1725 tools = 5540 / 128K (4.3%), strategy=conservative
INFO: Messages prepared: 1 → 2
INFO: LLM call completed: tool_calls=0
```
### When Trimming Occurs
```
INFO: Calling pre_hook to prepare 50 messages
INFO: ✓ Topology injected: 8500 chars, nodes: ['R1', 'R2', ...]
INFO: Messages trimmed: 50 → 25 msgs. Total: ~82000 tokens + 1725 tools = 83725 / 128K (65.4%), strategy=balanced
INFO: Messages prepared: 50 → 25
```
### When Topology is None
```
INFO: Calling pre_hook to prepare 1 messages
WARNING: ✗ Topology data is None, injecting placeholder
INFO: Context ready: 2 msgs, ~800 tokens + 1725 tools = 2525 / 128K (2.0%), strategy=balanced
```
## Error Handling
| Error | Behavior | Resolution |
|-------|----------|------------|
| tiktoken not installed | `ModuleNotFoundError` at startup | `pip install tiktoken>=0.8.0` |
| `context_limit` missing | `ValueError` raised | Add `context_limit` to LLM config |
| Invalid `context_limit` | `ValueError` raised | Must be positive integer |
| Invalid `context_strategy` | WARNING, fallback to `balanced` | Use `conservative`/`balanced`/`aggressive` |
| `trim_messages` failure | ERROR log, returns untrimmed messages | Check message format compatibility |
## Deprecated API
`prepare_context_messages()` is deprecated. It remains in `context_manager.py` for backward compatibility but emits `DeprecationWarning`. Use `create_pre_model_hook()` instead.
## Related Source Files
- `gns3server/agent/gns3_copilot/agent/context_manager.py` — Context management core logic
- `gns3server/agent/gns3_copilot/agent/gns3_copilot.py` — LLM call node (StateGraph)
- `gns3server/agent/gns3_copilot/agent/model_factory.py` — Model creation and tool binding
@@ -0,0 +1,104 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
# GNS3-Copilot Fault Injection Overview
## Core Flow
```mermaid
flowchart TB
subgraph "① API Trigger & Mode Switch"
A["POST /chat/inject\nUser requests fault injection"] --> B["Verify project is opened"]
B --> C["Set copilot_mode =\ntroubleshooting_injection"]
C --> D["Start Agent\nwith fault injection tool set"]
end
subgraph "② Topology Analysis & Fault Selection"
D --> E["gns3_topology_reader\nget topology info"]
E --> F["device_show_run\nget device configs"]
F --> G["injection_skill_get\nquery available fault types"]
G --> H{"Injection Skills Repository\ngns3/gns3-skills"}
H --> I["Return matching fault definitions\nwith config injection commands"]
end
subgraph "③ Fault Injection"
I --> J["Choose injection method"]
J --> K["device_config_send\ninject config changes"]
J --> L["link_update\ninject link-layer faults"]
end
subgraph "④ Result Confirmation"
K --> M["Verify fault is active"]
L --> M
M --> N["Document fault details\nincluding restore commands"]
end
```
## Tool Overview
| Tool | Source File | Purpose | Available Modes |
|---|---|---|---|
| `injection_skill_get` | `registry.py` (skills module) | Query protocol-level fault definitions (config change commands) | troubleshooting_injection |
| `link_update` | MCP tool via `tools_v2/mcp_bridge.py` | Link-layer fault injection (delay, loss, corruption, BPF) | troubleshooting_injection |
| `device_config_send` | `gns3_client/device_config_commands.py` | Batch device config changes | troubleshooting_injection |
| `device_show_run` | `gns3_client/device_show_commands.py` | Read device configurations (read-only) | troubleshooting_injection |
| `gns3_topology_reader` | `gns3_client` | Get project topology information | troubleshooting_injection |
## Fault Injection API
| Endpoint | Function |
|---|---|
| `POST /v3/projects/{pid}/chat/inject` | Trigger fault injection, sets `troubleshooting_injection` mode then starts Agent |
**Prerequisite**: Project must be in `opened` status, otherwise returns 403.
## link_update Link Filters
| Filter Type | Function | Parameters |
|---|---|---|
| `delay` | Latency + jitter | `[latency(0-32767), jitter(0-32767)]` |
| `packet_loss` | Packet loss percentage | `[chance(0-100)]` |
| `corrupt` | Packet corruption percentage | `[chance(0-100)]` |
| `frequency_drop` | Drop every Nth packet | `[frequency(-1~32767)]` |
| `bpf` | Berkeley Packet Filter | expression text |
## Agent Workflow (LangGraph)
```mermaid
sequenceDiagram
participant U as User
participant API as POST /chat/inject
participant LLM as LLM Node
participant Topo as gns3_topology_reader
participant DC as device_show_run
participant CC as device_config_send
participant Skill as injection_skill_get
participant Filter as link_update
U->>API: Inject an OSPF fault
API->>LLM: set mode=troubleshooting_injection
LLM->>Topo: get topology
Topo-->>LLM: topology info
LLM->>DC: read device configs
DC-->>LLM: running configs
LLM->>Skill: list context=["ospf"]
Skill-->>LLM: matching fault types
LLM->>Skill: get device_type=injection_ospf_issues
Skill-->>LLM: fault definition + injection commands
LLM->>CC: execute config injection
CC-->>LLM: injection result
LLM->>Filter: set filters={delay:[200,50]}
Filter-->>LLM: link delay injected successfully
LLM-->>U: Fault injected, restore commands included
```
## Key Design Points
1. **Dedicated API Endpoint** — `POST /chat/inject` is the dedicated entry point, automatically switching to `troubleshooting_injection` mode
2. **LLM-driven Fault Selection** — The LLM analyzes the topology then queries matching faults via `injection_skill_get`; no hardcoded fault scenarios
3. **Dual-Layer Injection** — Device-level config changes + link-level network impairment, covering complete troubleshooting scenarios
4. **Fully Reversible** — Every injection includes restore commands; link filters can be cleared with `action: clear`
5. **Safety First** — BPF syntax is pre-validated via tshark; config commands are restricted by `command_filter`
6. **Context Filtering** — `injection_skill_get` requires a `context` parameter, returning only faults matching the topology protocols
@@ -0,0 +1,159 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Fault Injection Feature
## Overview
The fault injection feature enables GNS3 Copilot to automatically inject realistic network faults into GNS3 labs for troubleshooting training. The agent analyzes the topology, selects an appropriate fault based on the configured protocols, injects it, and documents the results.
## Architecture
```mermaid
graph TD
subgraph "Agent Workflow"
TG[Topology Gathering]
CFG[Config Collection]
FA[Fault Analysis]
FI[Fault Injection]
FD[Fault Documentation]
end
subgraph "Skills Repository"
IS[INJECTION_SKILLS_REGISTRY<br/>39 categories, 368 issues]
SK[injection_skill_get Tool]
end
subgraph "Tools"
DC[device_show_run]
CC[device_config_send]
GK[gns3_topology_reader]
end
TG -->|Get topology| GK
CFG -->|Get configs| DC
FA -->|Query filtered skills| IS
FA -->|Select fault| SK
FI -->|Inject config changes| CC
FD -->|Output report| FD
```
## Injection Skills Tool
The `injection_skill_get` (LangChain `BaseTool`) is the primary interface for querying available faults.
### Listing Faults (with context filter)
The LLM MUST pass topology context when listing faults:
```json
{"action": "list", "context": ["ospf", "bgp", "vlan"]}
```
This returns only faults matching the protocols found in the topology. The tool rejects calls without `context`:
```json
{
"error": "context parameter is required when action='list'",
"hint": "Analyze the topology and device configurations first...",
"available_categories": ["bgp", "interface", "mpls", "ospf", ...]
}
```
### Getting Fault Details
Token-efficient usage pattern:
```json
// Step 1: List issue names only (~300 tokens)
{"device_type": "injection_ospf_issues", "detail": "index"}
// Step 2: Get single issue detail (~500 tokens)
{"device_type": "injection_ospf_issues", "issue": "ospf_hello_dead_mismatch"}
```
### Parameters
| Parameter | Required | Description |
|-----------|----------|-------------|
| `action` | No (`"get"`) | `"list"` to browse, `"get"` for details |
| `context` | **Yes** for `action="list"` | Protocols found in topology: `["ospf", "bgp"]` |
| `device_type` | Yes for `action="get"` | e.g. `"injection_ospf_issues"` |
| `detail` | No (`"full"`) | `"index"` (names), `"summary"` (+desc), `"full"` (all) |
| `issue` | No | Single issue key for targeted detail |
## Fault Injection Workflow
```mermaid
sequenceDiagram
participant LLM
participant injection_skill_get
participant TopologyTool
participant DeviceCommands
LLM->>TopologyTool: Get topology info
TopologyTool-->>LLM: Topology + device types
LLM->>DeviceCommands: Get device configs
DeviceCommands-->>LLM: Running configurations
Note over LLM: Analyze which protocols are in use
LLM->>injection_skill_get: {"action": "list", "context": ["ospf", "vlan"]}
injection_skill_get-->>LLM: Matching fault categories
LLM->>injection_skill_get: {"device_type": "injection_ospf_issues", "detail": "index"}
injection_skill_get-->>LLM: Issue names (token-efficient)
LLM->>injection_skill_get: {"device_type": "injection_ospf_issues", "issue": "ospf_hello_dead_mismatch"}
injection_skill_get-->>LLM: Full fault detail + config commands
LLM->>DeviceCommands: Inject fault configuration
DeviceCommands-->>LLM: Execution result
Note over LLM: Document fault in response
```
## Injection Skills Repository
Skills are organized by protocol/category in the external [GNS3-Skills](https://github.com/gns3/gns3-skills) repository:
| Category | File | Example Issues |
|----------|------|----------------|
| OSPF | `injection/ospf_issues.yaml` | Hello/Dead mismatch, MTU mismatch, area mismatch |
| BGP | `injection/bgp_issues.yaml` | AS-path prepend, next-hop unreachable, route filtering |
| VLAN | `injection/vlan_issues.yaml` | Trunk allowed mismatch, native VLAN mismatch |
| STP | `injection/stp_issues.yaml` | Root guard, loop guard, port priority |
| MPLS | `injection/mpls_issues.yaml` | LDP session down, label binding failure |
| ... | 34 more files | 368 issues total |
## Recovery
Each injected fault includes restore commands in the documentation. The LLM always provides commands to fully revert all changes.
## API Endpoint
### POST /copilot/projects/{project_id}/chat/inject
Dedicated endpoint for fault injection. Internally sets `copilot_mode` to `troubleshooting_injection` and runs the agent.
**Request:**
```json
{
"message": "Inject a network fault for troubleshooting practice",
"session_id": "optional-session-uuid"
}
```
**Response:** Server-Sent Events (SSE) stream identical to the chat stream endpoint.
## Related Documentation
- [Skills Repository](skills-repository.md)
- [Command Security](command-security.md)
- [Chat API](chat-api.md)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,775 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Multi-Vendor Network Device Support
## Overview
GNS3-Copilot supports network devices from multiple vendors through Netmiko and Nornir integration. The system includes a custom Netmiko driver for Huawei devices in GNS3 emulation environments and supports dynamic device type detection.
## Supported Vendors
| Vendor | Device Type | Protocol | Status |
|--------|-------------|----------|--------|
| **Cisco** | `cisco_ios_telnet` | Telnet | ✅ Tested |
| **Huawei** | `gns3_huawei_telnet_ce` | Telnet | ✅ Tested (Custom Driver) |
| **Ruijie (锐捷)** | `gns3_ruijie_telnet` | Telnet | ✅ Tested (Custom Driver) |
| **VPCS** | `gns3_vpcs_telnet` | Telnet | ✅ Tested (Custom Driver, Simulator) |
## Custom VPCS Driver (`VPCSTelnet`)
### Problem Statement
VPCS (Virtual PC Simulator) is a lightweight virtual PC simulator used in GNS3 lab environments. Unlike network devices (routers/switches), VPCS devices:
1. **No authentication** - Direct console access without username/password
2. **Simple command interface** - No configuration modes
3. **Simple prompt pattern** - `PC1>`, `PC2>`, etc.
### Solution: Lightweight Custom Driver
```mermaid
graph TD
A[BaseConnection<br/>Netmiko base class] --> B[VPCSTelnet<br/>Custom GNS3 driver]
B --> C[No authentication]
B --> D[Simple prompt: PC\d+]
B --> E[No config mode]
B --> F[ANSI stripping]
```
**Why Not Use Standard Telnet Driver?**
- Standard drivers attempt authentication (times out)
- No support for VPCS-specific prompt patterns (`PC\d+>`)
- No need for configuration mode handling
### VPCSTelnet Implementation
#### Location
```
gns3server/agent/gns3_copilot/utils/custom_netmiko/vpcs_telnet.py
```
#### Key Features
**1. No Authentication**
```python
def telnet_login(self, pri_prompt_terminator=r"PC\d+>", ...):
# Send returns until VPCS prompt detected
for i in range(max_loops):
self.write_channel(self.RETURN)
output = self.read_channel()
if re.search(pri_prompt_terminator, output):
return output # Success - VPCS prompt detected
```
**2. Simple Prompt Recognition**
```
PC1> ip 10.10.0.12/24 10.10.0.254
PC1> ping 10.10.0.254
```
**3. No Configuration Mode**
```python
def check_config_mode(self) -> bool:
return False # VPCS has no config mode
def config_mode(self) -> str:
return "" # No config mode to enter
def exit_config_mode(self) -> str:
return "" # No config mode to exit
```
**4. No Paging**
```python
def disable_paging(self) -> str:
return "" # VPCS doesn't use paging
```
**5. Custom `send_command`**
VPCS overrides `send_command` with non-standard defaults:
- `strip_prompt=False`, `strip_command=False`, `normalize=False` — VPCS output doesn't need standard Netmiko processing
- Uses `_strip_ansi_codes()` to clean terminal escape sequences from VPCS output
**6. ANSI Escape Code Stripping**
VPCS output often contains ANSI terminal codes. The `_strip_ansi_codes()` method strips bold, underline, reset, and color codes before returning output to callers.
### VPCS Tool Usage
The VPCS driver is used by the `vpcs_config_set` tool:
> File: `gns3server/agent/gns3_copilot/gns3_client/vpcs_commands.py`
**VPCS Connection Parameters:**
VPCS devices use additional Netmiko parameters for reliable connections:
| Parameter | Value | Reason |
|-----------|-------|--------|
| `fast_cli` | `False` | VPCS is slow, disable fast CLI mode |
| `global_delay_factor` | `2.0` | Double the delay between commands |
```python
"connection_options": {
"netmiko": {
"extras": {
"device_type": "gns3_vpcs_telnet",
"fast_cli": False,
"global_delay_factor": 2.0,
}
}
}
```
### VPCS Built-in Template Configuration
**✨ Automatic Tags - No Manual Configuration Required**
VPCS nodes created from the built-in template automatically include the necessary tags:
| Tag | Value | Purpose |
|-----|-------|---------|
| `device_type` | `gns3_vpcs_telnet` | Netmiko driver selection |
**Built-in Template Definition:**
> File: `gns3server/services/templates.py`
The VPCS built-in template includes `"tags": ["device_type:gns3_vpcs_telnet"]`, which is automatically applied to all VPCS nodes created from the template.
**User Benefits:**
- ✅ **No manual tagging required** — Tags are applied automatically when creating VPCS nodes
- ✅ **Automatic driver selection** — Copilot tools automatically use the correct Netmiko driver
- ✅ **Consistent behavior** — All VPCS nodes from the built-in template work identically
- ✅ **Zero configuration** — Users don't need to understand device_type tags
**How It Works:**
1. User creates a VPCS node from the built-in "VPCS" template
2. Node automatically inherits the tag: `device_type:gns3_vpcs_telnet`
3. Copilot tools read the tag and select the appropriate VPCS Netmiko driver
4. Commands execute using the VPCS-optimized driver (no authentication, simple prompts)
### Supported VPCS Commands
| Command | Description | Example |
|---------|-------------|---------|
| `ip` | Configure/show IP address | `ip 10.10.0.12/24 10.10.0.254` |
| `ping` | Test connectivity | `ping 10.10.0.254` |
| `arp` | Display ARP table | `arp` |
| `show ip` | Show IP configuration | `show ip` |
| `version` | Show VPCS version | `version` |
| `save` | Save configuration | `save` |
| `load` | Load configuration | `load` |
### Architecture Benefits
**Unified Tool Architecture:**
- ✅ Uses Nornir for connection management (same as network device tools)
- ✅ Uses Netmiko for command execution (consistent with other tools)
- ✅ Follows same patterns as `gns3_client/device_config_commands.py` and `gns3_client/device_show_commands.py`
- ✅ Simplified codebase - no need for separate telnetlib3 implementation
**Migration from telnetlib3:**
| Aspect | Old (telnetlib3) | New (Netmiko + Nornir) |
|--------|-----------------|-------------------------|
| Library | telnetlib3 | Netmiko |
| Framework | Manual threading | Nornir |
| Code Lines | ~490 lines | ~580 lines (with better structure) |
| Consistency | Unique implementation | Same as other tools |
| Maintenance | Separate code path | Unified architecture |
---
## Custom Huawei Driver (`GNS3HuaweiTelnetCE`)
### Problem Statement
GNS3-emulated Huawei devices connect via console **without requiring authentication**. Standard Netmiko drivers attempt username/password authentication, causing connection timeouts.
**Standard Driver Behavior:**
```
Telnet Connection → Wait for username prompt → Send username → Wait for password → Send password → Access
^ Times out after 20 seconds
```
**GNS3 Huawei Device:**
```
Telnet Connection → Direct access to command line (no login prompts)
<HUAWEI>
```
### Solution: Custom Driver Architecture
```mermaid
graph TD
A[BaseConnection] --> B[CiscoBaseConnection]
B --> C[HuaweiBase<br/>VRP support, system-view,<br/>prompt patterns, paging]
C --> D[GNS3HuaweiTelnetCE<br/>Overrides telnet_login only]
D --> E[Skip authentication]
D --> F[Auto-commit before exit]
D --> G[y/n auto-confirm]
```
**Why Inherit from HuaweiBase?**
- ✅ Built-in VRP (Versatile Routing Platform) command handling
- ✅ Huawei-specific configuration mode (`system-view`)
- ✅ Huawei prompt patterns (`<...>`, `[...]`)
- ✅ Huawei paging disable (`screen-length 0 temporary`)
- ✅ Minimal code changes - only override authentication
### GNS3HuaweiTelnetCE Implementation
#### Location
```
gns3server/agent/gns3_copilot/utils/custom_netmiko/huawei_ce.py
```
**Package Structure:**
```
custom_netmiko/
├── __init__.py # Package initialization, auto-registers all drivers
├── huawei_ce.py # Huawei CloudEngine custom driver
├── README.md # Driver development guide
└── tests/ # Unit tests
├── __init__.py
└── test_huawei_ce.py # Huawei CE driver tests
```
#### Key Features
1. **Skip Authentication**
- Directly detect Huawei prompt patterns
- No username/password prompts
- Connection ready in < 1 second
2. **VRP Prompt Recognition**
```
User view: <HUAWEI>
System view: [HUAWEI]
Interface: [HUAWEI-GigabitEthernet0/0/1]
```
3. **Automatic Confirmation Handling**
- Detects and responds to `[y/n]` prompts
- Example: `return` command asks "Return to user view? [y/n]:"
- Automatically sends `y` to confirm
4. **Proper Output Collection**
- Uses Netmiko's `read_channel_timing()` for reliable output
- Waits for command completion (2s no new data = done)
- 30-second absolute timeout prevents hanging
5. **Auto-Commit Before Exit**
- Automatically sends `commit` command before exiting config mode
- Prevents "Uncommitted configurations [Y/N/C]" prompt
- Ensures configuration changes are saved
#### Limitations
**Why Not Use the Standard `huawei_telnet` Driver?**
- The standard Netmiko Huawei driver (`huawei_telnet`) has known issues in GNS3 emulation environments
- This is the primary reason the custom `gns3_huawei_telnet_ce` driver was developed
- The custom driver is designed for GNS3 devices **without authentication**
- If your GNS3 Huawei device has been configured with authentication, remove it for GNS3 testing to use the custom driver
**When to Use:**
| Scenario | Recommendation |
|----------|---------------|
| GNS3 Huawei device | Always use `gns3_huawei_telnet_ce` |
| GNS3 device has auth configured | Remove auth, then use `gns3_huawei_telnet_ce` |
#### Method Overrides
**1. `telnet_login` - Skip Authentication**
```python
def telnet_login(self, pri_prompt_terminator=r"<\S+>|>\s*$",
alt_prompt_terminator=r"\[\S+\]", ...) -> str:
# Clear buffer
self.read_channel()
# Send returns until prompt detected
for i in range(max_loops):
self.write_channel(self.RETURN)
output = self.read_channel()
# Check for Huawei prompts
if re.search(pri_prompt_terminator, output):
return output # Success!
return output # Best effort
```
**2. `send_config_set` - Configuration Commands**
```python
def send_config_set(self, config_commands, **kwargs) -> str:
# Enter config mode
output += self.config_mode(config_command="system-view")
# Send all commands
for cmd in config_commands:
self.write_channel(f"{cmd}{self.RETURN}")
time.sleep(delay_factor * 0.05)
# Collect output using Netmiko standard method
output += self.read_channel_timing(read_timeout=30, last_read=2.0)
# Auto-commit before exit (prevents [Y/N/C] prompt)
self.write_channel(f"commit{self.RETURN}")
time.sleep(0.5 * self.global_delay_factor)
output += self.read_channel()
# Exit config mode
output += self.exit_config_mode()
return output
```
**3. `exit_config_mode` - Handle Confirmation**
```python
def exit_config_mode(self, exit_config="return", pattern=r"<\S+>|>\s*$") -> str:
self.write_channel(f"return{self.RETURN}")
# Look for confirmation prompt
for _ in range(20):
new_output = self.read_channel()
if re.search(r"\[y/n\]", new_output):
self.write_channel(f"y{self.RETURN}") # Auto-confirm
if re.search(pattern, new_output):
return output # Back to user view
return output
```
### Device Type Registration
The custom driver must be registered with Netmiko's global mappings:
```python
def register_custom_device_type() -> None:
import importlib
sd = importlib.import_module("netmiko.ssh_dispatcher")
# Register in CLASS_MAPPER (for ConnectHandler)
sd.CLASS_MAPPER["gns3_huawei_telnet_ce"] = GNS3HuaweiTelnetCE
sd.CLASS_MAPPER["huawei_ce"] = GNS3HuaweiTelnetCE
# Register in CLASS_MAPPER_BASE (for base class definitions)
sd.CLASS_MAPPER_BASE["gns3_huawei_telnet_ce"] = GNS3HuaweiTelnetCE
sd.CLASS_MAPPER_BASE["huawei_ce"] = GNS3HuaweiTelnetCE
# CRITICAL: Rebuild static lists
sd.platforms = list(sd.CLASS_MAPPER.keys())
sd.platforms.sort()
sd.telnet_platforms = [x for x in sd.platforms if "telnet" in x]
```
**Important: Static List Problem**
- `ssh_dispatcher.platforms` is computed at module import time
- Modifying `CLASS_MAPPER` doesn't automatically update `platforms`
- Must manually rebuild the list after registration
**Auto-Registration**
```python
# Automatically runs on module import
try:
register_custom_device_type()
except Exception as e:
logger.warning(f"Failed to register custom device type: {e}")
```
## Custom Ruijie Driver (`RuijieTelnetEnhanced`)
### Problem Statement
Ruijie (锐捷) network devices exhibit Cisco-like command syntax but have interactive prompts during configuration that can cause standard Netmiko drivers to fail.
**Common Issue - OSPF Router-ID:**
```
Router(config-router)#router-id 10.0.0.1
Change router-id and update OSPF process! [yes/no]:
```
Standard Netmiko's `send_config_set()` waits for a prompt pattern, but the `[yes/no]:` prompt doesn't match the expected config mode pattern, causing:
1. **ReadTimeout**: Netmiko times out waiting for the prompt
2. **Command Failure**: Subsequent commands are not executed
3. **Device Lockup**: Console remains in the waiting state
### Solution: Hybrid Strategy with Interactive Prompt Handling
```mermaid
graph TD
A[BaseConnection] --> B[CiscoBaseConnection]
B --> C[RuijieOSBase<br/>Netmiko built-in]
C --> D[RuijieTelnetEnhanced<br/>Interactive prompt handling]
D --> E[Preprocessing<br/>Insert yes after known commands]
D --> F[Batch send<br/>Fast path 2-3s]
D --> G[Fallback one-by-one<br/>Slow but reliable ~10s]
```
**Why Hybrid Strategy?**
1. **Preprocessing**: Automatically insert `yes` after known interactive commands
2. **Fast Path**: Batch send for most commands (2-3 seconds for 13 commands)
3. **Fallback**: One-by-one send with real-time detection (reliable but slower)
### RuijieTelnetEnhanced Implementation
#### Location
```
gns3server/agent/gns3_copilot/utils/custom_netmiko/ruijie_telnet.py
```
#### Key Features
**1. Preprocessing - Known Interactive Commands**
```python
INTERACTIVE_PATTERNS = [
re.compile(r"^router-id\s+", re.IGNORECASE), # OSPF/EIGRP/BGP router-id
re.compile(r"^erase\s+", re.IGNORECASE), # erase startup-config
re.compile(r"^delete\s+", re.IGNORECASE), # delete files
re.compile(r"^format\s+", re.IGNORECASE), # format filesystem
re.compile(r"^reload\b", re.IGNORECASE), # reload/reboot
re.compile(r"^boot\s+system\s+", re.IGNORECASE), # change boot image
]
```
**2. Hybrid Send Strategy**
```mermaid
flowchart TD
A[Input Configuration Commands] --> B[Preprocessing]
B --> B1[Detect interactive commands]
B1 --> B2[Insert 'yes' after them]
B2 --> C[Try Batch Send - Fast]
C --> C1[Write all commands rapidly]
C1 --> C2[Read output once, last_read=2.0s]
C2 --> D{Success?}
D -->|Yes| E[Return output]
D -->|No| F[Fallback: One-by-One]
F --> F1[Send each command individually]
F1 --> F2[Detect prompts after each]
F2 --> F3[Send 'yes' when needed, last_read=0.5s]
F3 --> E
```
**3. Batch Send Performance**
- **13 commands** with 1 interactive command
- **Fast path**: ~2-3 seconds (includes device processing time)
- **Fallback**: ~10 seconds (if batch fails)
**4. Real-time Detection (Fallback)**
```python
# After each command
new_output = self.read_channel_timing(read_timeout=10, last_read=0.5)
# Check for [yes/no] prompt
if re.search(r"\[yes/no\]", new_output, re.IGNORECASE):
self.write_channel(f"yes{self.RETURN}")
output += self.read_channel_timing(read_timeout=30, last_read=0.5)
```
#### GNS3 Node Tag Configuration
**For Ruijie devices in GNS3:**
```
device_type:gns3_ruijie_telnet
```
**Example Usage:**
```python
from netmiko import ConnectHandler
from gns3server.agent.gns3_copilot.utils import custom_netmiko
device = {
"device_type": "gns3_ruijie_telnet",
"host": "127.0.0.1",
"port": 5000,
}
with ConnectHandler(**device) as conn:
# These commands include router-id (interactive)
config = [
"router ospf 1",
"router-id 10.0.0.1", # Triggers [yes/no] prompt
"network 192.168.1.0 0.0.0.255 area 0",
]
# Automatically handles the [yes/no] prompt
output = conn.send_config_set(config)
```
#### Limitations
**Interactive Command Coverage:**
- **Covered**: `router-id`, `erase`, `delete`, `format`, `reload`, `boot system`
- **Not Covered**: Unknown or vendor-specific interactive prompts
- **Fallback**: If batch fails, falls back to one-by-one with real-time detection
**When to Use:**
| Scenario | Use Driver |
|----------|------------|
| GNS3 Ruijie (known interactive commands) | `gns3_ruijie_telnet` (batch + auto-fallback) |
| GNS3 Ruijie (unknown interactive prompts) | `gns3_ruijie_telnet` (auto-fallback to one-by-one) |
## Dynamic Device Type Detection
### GNS3 Node Tags
Device type is extracted from GNS3 node tags:
```
device_type:gns3_huawei_telnet_ce → Netmiko driver selection
```
**Tag Examples:**
| Vendor | Device Type Tag | Template Source |
|--------|----------------|-----------------|
| Cisco IOS | `device_type:cisco_ios_telnet` | User appliance |
| Huawei CE | `device_type:gns3_huawei_telnet_ce` | User appliance |
| Ruijie | `device_type:gns3_ruijie_telnet` | User appliance |
| **VPCS** | `device_type:gns3_vpcs_telnet` | **Built-in ✅** |
**VPCS Built-in Template:**
- VPCS has a **built-in template** with pre-configured `device_type` tag
- The tag is **automatically applied** when creating VPCS nodes
- No manual configuration required — works out of the box
- Other devices require users to import appliances and configure tags manually
### Nornir Best Practice: Host-Level Connection Configuration
The system uses **Nornir's configuration priority** (host > group > defaults) to handle multi-vendor environments efficiently:
```python
# From get_gns3_device_port.py
hosts_data[device_name] = {
"port": console_port,
"groups": ["network_devices"], # All devices share one group
"connection_options": {
"netmiko": {
"extras": {"device_type": device_type} # Device-specific driver
}
},
}
```
**Why Host-Level `connection_options`?**
- ✅ Each device has its own `device_type` (host-level config)
- ✅ All devices share common settings via group inheritance (`hostname`, `timeout`)
- ✅ No need to dynamically create multiple groups for each device type
- ✅ Cleaner code structure — single generic group for all devices
- ✅ Follows Nornir best practice: "configuration proximity"
**Configuration Priority:**
```mermaid
graph TD
A["Host Level<br/>connection_options.device_type<br/>(gns3_huawei_telnet_ce, cisco_ios_telnet, etc.)"]
B["Group Level<br/>hostname=127.0.0.1, timeout=120<br/>username, password"]
C["Defaults Level<br/>data.location=gns3"]
A -->|overrides| B
B -->|overrides| C
```
| Aspect | Old: Dynamic Groups | New: Host-Level Config |
|--------|--------------------|-----------------------|
| Group count | One per vendor type | Single `network_devices` group |
| Device type location | Group `connection_options` | Host `connection_options` |
| Complexity | Dynamic group creation logic | No dynamic group logic |
## Architecture Evolution
### Problem: Multi-Vendor Device Support
**Initial Challenge:**
```mermaid
graph TD
A[Topology: Cisco R1 + Huawei SW1 + Juniper SRX] --> B[Need: Different Netmiko drivers per device]
B --> C[Question: How to configure Nornir for multiple device types?]
```
### Solution Evolution
| Approach | Strategy | Issue |
|----------|----------|-------|
| ❌ Approach 1 | Single group with first device's `device_type` | All devices use wrong driver |
| ❌ Approach 2 | Dynamic groups per vendor (`huawei_telnet`, `cisco_telnet`, ...) | Complex logic, code duplication, not Nornir best practice |
| ✅ Approach 3 (Current) | **Host-level `connection_options`** + single generic group | Clean, follows Nornir host > group > defaults priority |
> See `get_gns3_device_port.py:get_device_ports_from_topology()` for the current implementation.
### Configuration Priority Demonstration
```mermaid
graph TD
A["Host Level (highest)<br/>device_type: gns3_huawei_telnet_ce"]
B["Group Level (middle)<br/>hostname: 127.0.0.1, timeout: 120"]
C["Defaults Level (lowest)<br/>data.location: gns3"]
A -->|overrides| B -->|overrides| C
D[Result] --> D1["Each device uses its own device_type"]
D --> D2["All share hostname, timeout from group"]
D --> D3["All share data.location from defaults"]
```
## Usage Examples
### Direct Netmiko Usage
**Custom driver auto-registers on import. No username/password needed for GNS3 devices.**
| Device Type | `device_type` | Auth | Notes |
|-------------|---------------|------|-------|
| Huawei CE | `gns3_huawei_telnet_ce` | None | Custom driver, skip auth |
| Ruijie | `gns3_ruijie_telnet` | None | Custom driver, interactive prompts handled |
| VPCS | `gns3_vpcs_telnet` | None | Custom driver, no config mode |
| Cisco IOS | `cisco_ios_telnet` | Required | Standard Netmiko driver |
### GNS3 Copilot Tool Usage
> Tools: `gns3_client/device_show_commands.py`, `gns3_client/device_config_commands.py`, `gns3_client/vpcs_commands.py`
Each tool reads node tags to determine `device_type`, builds host-level Nornir inventory, and dispatches commands to the appropriate Netmiko driver. Multi-vendor topologies are handled transparently — each device uses its own driver.
## Module Structure
```
gns3server/agent/gns3_copilot/
├── utils/
│ ├── custom_netmiko/ # Custom Netmiko drivers package
│ │ ├── __init__.py # Auto-registers all drivers on import
│ │ ├── huawei_ce.py # Huawei CloudEngine driver
│ │ ├── ruijie_telnet.py # Ruijie enhanced driver
│ │ ├── vpcs_telnet.py # VPCS simulator driver
│ │ ├── README.md # Driver development guide
│ │ └── tests/ # Unit tests (52 total)
│ │ ├── __init__.py
│ │ ├── test_huawei_ce.py # Huawei CE driver tests (9)
│ │ ├── test_ruijie_telnet.py # Ruijie driver tests (15)
│ │ └── test_vpcs_telnet.py # VPCS driver tests (28)
│ └── get_gns3_device_port.py # Device port extraction
│ └── get_device_ports_from_topology() # Extract ports + device_type from tags
├── tools_v2/
│ ├── device_show_commands.py # Multi-vendor display commands (shared w/ MCP)
│ ├── device_config_commands.py # Multi-vendor config commands (shared w/ MCP)
│ │ └── _expand_multiline_commands() # Expand banner commands
│ └── vpcs_commands.py # VPCS commands using Nornir + Netmiko (shared w/ MCP)
│ └── vpcs_config_set class # VPCS tool (MCP-shared)
```
**Key Architectural Changes (2026-03-14):**
- ❌ Removed: `vpcs_tools_telnetlib3.py` - Replaced with Netmiko implementation
- ✅ Added: `vpcs_telnet.py` - Custom VPCS driver for Netmiko
- ✅ Added: `gns3_client/vpcs_commands.py` - VPCS tool using Nornir + Netmiko
- ✅ Simplified: Unified tool architecture - all tools use Nornir + Netmiko
- ✅ Updated: Module structure - all tools follow same pattern
**Key Architectural Changes (2026-03-13):**
- ❌ Removed: `_get_nornir_groups_config()` - No longer needed
- ❌ Removed: `_get_nornir_group()` - No longer needed
- ✅ Simplified: `_initialize_nornir()` - Uses single generic group
- ✅ Updated: `get_gns3_device_port.py()` - Returns host-level `connection_options`
- ✅ Added: `ruijie_telnet.py` - Custom Ruijie driver with interactive prompt handling
- ✅ Added: `_expand_multiline_commands()` - Auto-expands banner and multi-line commands
- ✅ Added: device_type tag validation with error feedback (inline in `_run`)
## Unit Testing
### Test Coverage
> Test files located at: `gns3server/agent/gns3_copilot/utils/custom_netmiko/tests/`
**Total: 52 tests across 3 test files**
| Test File | Tests | Coverage Focus |
|-----------|-------|----------------|
| `test_huawei_ce.py` | 9 | Registration, inheritance, VRP methods, mock connection |
| `test_ruijie_telnet.py` | 15 | Registration, interactive patterns, preprocessing, batch/fallback |
| `test_vpcs_telnet.py` | 28 | Registration, login, command sending, ANSI stripping, config mode |
#### Huawei CE Tests (`TestHuaweiTelnetCEDriver` + `TestHuaweiTelnetCEIntegration`)
- Device type registration in CLASS_MAPPER
- Inheritance from HuaweiBase
- VRP-specific methods (`config_mode`, `check_config_mode`, `exit_config_mode`)
- Prompt pattern constants
- Mock telnet connection
#### Ruijie Tests (`TestRuijieTelnetEnhancedDriver` + `TestRuijieTelnetEnhancedIntegration`)
- Device type registration
- Inheritance from RuijieOSBase
- Interactive pattern matching (`router-id`, `erase`, `delete`, etc.)
- Preprocessing of interactive commands
- Batch and fallback send strategies
#### VPCS Tests (`TestVPCSTelnetDriver` + 5 more test classes)
- Device type registration
- Inheritance from BaseConnection
- No-auth login with `PC\d+>` prompt
- `send_command` / `send_command_timing` overrides
- ANSI escape code stripping (8 dedicated tests)
- Config mode always returns empty/false
**Running Tests:**
```bash
source venv/bin/activate
python -m pytest gns3server/agent/gns3_copilot/utils/custom_netmiko/tests/
```
**Current Test Status:** ✅ All 52 tests passing
## Related Documentation
- [Custom Netmiko README](../../../../../gns3server/agent/gns3_copilot/utils/custom_netmiko/README.md) - Driver development guide
- [Node Control Tools](./node-control-tools.md) - Device lifecycle management
- [Command Security](./command-security.md) - Command filtering and validation
- [Chat API](./chat-api.md) - Session management and SSE
## References
- [Netmiko Documentation](https://ktbyers.github.io/netmiko/)
- [Netmiko PLATFORMS.md](https://github.com/ktbyers/netmiko/blob/master/PLATFORMS.md)
- [Nornir Documentation](https://nornir.readthedocs.io/)
---
_Implementation Date: 2026-03-12_
_Last Updated: 2026-04-20 (Documentation review: fixed VPCS template tags, updated test coverage, added Mermaid diagrams, removed code bloat)_
_Status: ✅ Implemented - Custom drivers for Huawei, Ruijie, and VPCS; multi-vendor support with Cisco IOS, Huawei, Ruijie, and VPCS tested_
_Architecture: Nornir best practice - host-level connection_options with single generic group_
_Unit Tests: ✅ 52/52 passing (9 Huawei + 15 Ruijie + 28 VPCS)_
_Changelog:_
- **2026-03-14**: Added VPCS support and unified tool architecture
- Implemented `VPCSTelnet` custom Netmiko driver for VPCS simulator
- Replaced `vpcs_tools_telnetlib3.py` with `gns3_client/vpcs_commands.py`
- Unified all tools to use Nornir + Netmiko architecture
- Removed dependency on telnetlib3 for VPCS devices
- Improved code consistency and maintainability
- **2026-03-13 (Evening)**: Added Ruijie enhanced driver and interactive command handling
- Implemented `RuijieTelnetEnhanced` with hybrid batch/fallback strategy
- Added automatic `yes` insertion for known interactive commands (`router-id`, `erase`, etc.)
- Achieves ~2-3 seconds for 13 commands (vs 10+ seconds for one-by-one)
- Auto-fallback to real-time detection for unknown interactive prompts
- Registered `gns3_ruijie_telnet` device type
- **2026-03-13 (Afternoon)**: Enhanced configuration safety and command handling
- Added AAA/password configuration prohibition in system prompts
- Implemented multi-line command expansion (`_expand_multiline_commands()`)
- Added `device_type` tag validation with error feedback
- Prevents execution of commands that could lock users out of devices
- Properly handles banner and other multi-line configuration commands
- **2026-03-13 (Morning)**: Refactored to use host-level `connection_options` instead of dynamic groups
- Removed `_get_nornir_groups_config()` and `_get_nornir_group()` helper functions
- Simplified `_initialize_nornir()` to use single generic group
- Updated `get_gns3_device_port.py()` to return host-level configuration
- **2026-03-12**: Initial implementation with custom Huawei driver
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,74 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
# GNS3-Copilot Real-time Packet AI Analysis Overview
## Core Flow
```mermaid
flowchart TB
subgraph "① Analysis Trigger & Knowledge Query"
A["User asks\n'e.g. Analyze OSPF neighbor state'"] --> B["LLM calls\npacket_analysis_skills"]
B --> C{"Protocol Knowledge Repository\ngns3/gns3-skills"}
C --> D["Returns protocol definition\nfields/base_filter/check_rules"]
B --> E["LLM calls\nsearch_fields mode"]
E --> F["tshark -G fields\nfield name search"]
F --> G["Returns valid field names"]
end
subgraph "② Live Capture & Analysis"
D --> H["LLM constructs tshark_args"]
G --> H
H --> I["packet_analysis\ncapture analysis mode"]
I --> J["GET /capture/file\ndownload live PCAP"]
J --> K["Pre-validate -e field names"]
K --> L["tshark -r pcap\nrun analysis"]
L --> M["Return analysis results"]
end
```
## Tool Overview
| Tool | Source File | Purpose | Available Modes |
|---|---|---|---|
| `packet_analysis` | `packet_analysis_tool.py` | Download live PCAP + tshark analysis | teaching / lab_automation |
| `packet_analysis_skills` | `registry.py` (skills module) | Query protocol-level analysis knowledge (fields, filters) | teaching / lab_automation |
## Agent Workflow (LangGraph)
```mermaid
sequenceDiagram
participant U as User
participant LLM as LLM Node
participant Skills as packet_analysis_skills
participant Pcap as packet_analysis
U->>LLM: OSPF neighbors can't establish, analyze
LLM->>Skills: get protocol=ospf
Skills-->>LLM: OSPF fields, filter definitions
LLM->>Pcap: search_fields query=ospf.hello
Pcap-->>LLM: valid -e field names
LLM->>Pcap: download PCAP + tshark_args
Pcap-->>LLM: tshark output results
LLM->>LLM: analysis reveals Dead interval mismatch
LLM-->>U: OSPF Dead interval mismatch detected
```
## Server Capture API
| Endpoint | Function |
|---|---|
| `POST /v3/projects/{pid}/links/{lid}/capture/start` | Start packet capture on a link |
| `POST /v3/projects/{pid}/links/{lid}/capture/stop` | Stop packet capture |
| `GET /v3/projects/{pid}/links/{lid}/capture/file` | Download PCAP file (available even while capture is active) |
| `GET /v3/projects/{pid}/links/{lid}/capture/stream` | Stream PCAP data |
| `WS /v3/projects/{pid}/links/{lid}/capture/web-wireshark` | Web Wireshark WebSocket proxy |
## Key Design Points
1. **LLM-driven Analysis** — The LLM constructs tshark parameters itself; the framework does not hardcode protocol logic, only performs safety validation
2. **Live PCAP** — Captures can be downloaded and analyzed while running, no need to stop capturing
3. **Dual Knowledge Sources** — External repository provides protocol-specific knowledge; local tshark field registry provides exact field names
4. **Safety First** — Pre-validation of tshark field names prevents execution failures from invalid fields
@@ -0,0 +1,182 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Protocol-Oriented Packet Analysis
## Overview
GNS3 Copilot provides protocol-oriented packet analysis that allows the AI assistant to diagnose network issues from live GNS3 captures. Protocol definitions (tshark fields, display filters, check rules) are stored as YAML files in the external GNS3-Skills repository and loaded into memory at startup.
The system exposes two LangChain tools: `packet_analysis_skills` queries protocol definitions, and `packet_analysis` runs tshark against downloaded pcap files using the LLM-constructed arguments.
## Architecture
```mermaid
graph TD
subgraph "GNS3-Skills Repository"
YAML[packet_analysis/*.yaml<br/>40+ protocol files]
end
subgraph "GNS3 Server"
SM[SkillsManager]
SL[SkillsLoader]
REG[PACKET_ANALYSIS_REGISTRY<br/>in-memory dict]
SKILL[packet_analysis_skills<br/>query protocol definitions]
TOOL[packet_analysis<br/>run tshark on captures]
end
subgraph "tshark"
FIELDS["tshark -G fields"<br/>live field registry]
CAP["tshark -r pcap"<br/>packet capture analysis]
end
YAML -->|load at startup / reload| SL
SL --> REG
SM --> SL
SKILL -->|read protocol fields/filters| REG
TOOL -->|validate -e fields| FIELDS
TOOL -->|download pcap + run tshark| CAP
```
## Supported Protocols
Definitions are loaded from `GNS3-Skills/packet_analysis/*.yaml`. The following protocol families are covered:
| Category | Protocols |
|----------|-----------|
| Network Layer | ip, ipv6, arp, icmp, icmpv6 |
| Transport Layer | tcp, udp |
| Data Link | ethernet, ppp, hdlc, frame_relay, vlan, isl, llc |
| Routing | ospf, eigrp, rip, bgp, isis, pim, dvmrp |
| Link Protocols | l2tp, lacp, pagp, udld |
| Infrastructure | cdp, lldp, stp, vtp, dtp |
| Management | snmp, telnet, ssh, radius, tacacs |
| Application | dns, http, bootp, dhcp |
| Tunneling / Security | gre, esp, ah, mpls, eapol, ssl, isakmp |
| Miscellaneous | nbns, slarp, ocsp, wccp, auto_rp, loop |
Each protocol YAML contains:
```yaml
name: "OSPF Packet Analysis"
description: "Analyze OSPF routing protocol packets"
protocol_key: "ospf"
display_filter: "ospf"
fields:
- label: "Source IP"
tshark_field: "ip.src"
description: "Source IPv4 address"
- label: "OSPF Message Type"
tshark_field: "ospf.msg"
description: "1=Hello, 2=DBD, 3=LSR, 4=LSU, 5=LSAck"
filter_examples:
- description: "Show OSPF Hello packets"
filter: "ospf.msg == 1"
checks:
- name: hello_dead_mismatch
severity: critical
message: "Hello/Dead Interval mismatch between neighbors"
```
## Analysis Flow
```mermaid
sequenceDiagram
participant LLM as LLM Agent
participant SKILL as packet_analysis_skills
participant TOOL as packet_analysis
participant tshark as tshark
participant GNS3 as GNS3 Server
LLM->>SKILL: {"action": "list"}
SKILL-->>LLM: Available protocols
LLM->>SKILL: {"action": "get", "protocol": "ospf"}
SKILL-->>LLM: Fields, filters, check rules
Note over LLM: LLM constructs tshark_args<br/>using protocol knowledge
LLM->>TOOL: {project_id, link_id,<br/>tshark_args: "-Y ospf -T fields -e ip.src -e ospf.msg"}
TOOL->>TOOL: Validate -e field names<br/>against tshark -G fields
TOOL->>GNS3: Download pcap for link_id
GNS3-->>TOOL: Capture file
TOOL->>tshark: tshark -r pcap -Y ospf -T fields -e ip.src -e ospf.msg
tshark-->>TOOL: Tab-separated output
TOOL-->>LLM: Raw tshark output
```
## Tool Registration
The packet analysis tools are available in two copilot modes:
| Tool | Teaching Assistant | Lab Automation | Troubleshooting Injection |
|------|:------------------:|:--------------:|:-------------------------:|
| `packet_analysis` | Yes | Yes | No |
| `packet_analysis_skills` | Yes | Yes | No |
## Tool Interface
### packet_analysis_skills
Queries protocol definitions from the `PACKET_ANALYSIS_REGISTRY`. Used before running tshark to look up valid field names, display filters, and anomaly checks.
| Action | Input | Output |
|--------|-------|--------|
| List protocols | `{"action": "list"}` | `{count, protocols: [{protocol, name, description}]}` |
| Get protocol | `{"action": "get", "protocol": "ospf"}` | Protocol definition with fields, filters, checks |
### packet_analysis
Runs tshark against a downloaded GNS3 capture file. Supports two modes:
**Capture analysis mode:**
| Parameter | Required | Description |
|-----------|----------|-------------|
| `project_id` | Yes | UUID of the GNS3 project |
| `link_id` | Yes | UUID of the link to analyze |
| `tshark_args` | Yes | tshark arguments (after `-r <pcap>`) |
**Field search mode:**
| Parameter | Required | Description |
|-----------|----------|-------------|
| `action` | Yes | `"search_fields"` |
| `query` | Yes | Single keyword (e.g., `"ospf.lsa"`, `"bgp.open"`) |
### Validation and Error Handling
Before downloading the capture, the tool validates `-e` field names against the live tshark field registry (`tshark -G fields`). Invalid field names are rejected early with a hint to use `search_fields`.
| Scenario | Response |
|----------|----------|
| Invalid `-e` field name | `{error, hint, invalid_fields}` |
| tshark filter/field error | `{error: "tshark argument error", hints}` |
| Empty capture file | `{error: "Capture file is empty"}` |
| No matching packets | `{result: "No matching packets found", hints}` |
| tshark timeout (30s) | `{error: "tshark timeout after 30 seconds"}` |
| tshark not installed | `{error: "tshark not installed"}` |
When `-c` is used and no results are found, the tool hints that `-c` limits total packets read (not matched count), and suggests removing it or piping to `head`.
## Hot Reload
Packet analysis protocols can be reloaded without restarting the server via the existing reload API:
```
POST /v3/copilot/reload/skills
```
This triggers `SkillsManager.reload_packet_analysis_protocols()`, which re-reads all YAML files from the `packet_analysis/` directory and updates `PACKET_ANALYSIS_REGISTRY` in place.
## Related Documentation
- [External Skills Repository](skills-repository.md)
- [Fault Injection](fault-injection.md)
- [Chat API](chat-api.md)
@@ -0,0 +1,105 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
# Server Settings API
## Overview
REST API for reading and updating `gns3_server.conf` at runtime, enabling a server settings page in the Web UI. Updates are persisted with a read-modify-write strategy (unknown options in the file are preserved), validated before anything touches disk, and hot-reloaded into the running server; the response tells the caller which changes require a restart.
## Architecture
```mermaid
flowchart LR
U["Web UI / Client"] -->|"GET /v3/settings"| R["routes/controller/settings.py"]
U -->|"PUT /v3/settings"| R
R -->|"Server.Audit / Server.Modify"| RBAC["privilege check"]
R --> RS["SettingsResponse / SettingsUpdate schemas<br/>(extra=forbid, secret masking)"]
RS --> UC["Config.update_config()<br/>read-modify-write"]
UC --> FILE["gns3_server.conf<br/>(atomic replace, mode 0600)"]
UC --> RN["reload_and_notify()"]
RN --> CB["file-watch callbacks<br/>(runtime hot reload)"]
R --> NOTIF["notification stream:<br/>settings.updated"]
```
- **Exposure** — all sections except the deprecated `VirtualBox`/`VMware`: `Server`, `Controller`, `VPCS`, `Dynamips`, `IOU`, `Qemu`, `WebWireshark`. `Controller.jwt_secret_key` is excluded entirely: it is loaded from `<secrets_dir>/gns3_jwt_secret_key` and writing it to the configuration file is a no-op.
- **Schema metadata** — every field carries a pydantic `description`, default value and validation bounds. They flow into `/openapi.json` (the `SettingsResponse` component), so clients can render the settings form — labels, tooltips, initial values, input validation — from the OpenAPI schema alone, without maintaining a field table. The human-readable annotated reference is `gns3server/config_samples/gns3_server.conf`, kept in sync with the schema.
- **Write strategy** — `Config.update_config()` re-reads the configuration files with `configparser`, applies only the submitted options, and atomically rewrites the main configuration file. Comments and formatting are lost (accepted trade-off); options unknown to the schema are preserved.
- **Validate before write** — the merged view of all configuration files is validated as `ServerConfig` *before* any disk write. A validation error must never reach disk: the `FileWatcher` reload callback would raise and permanently stop polling that file.
## Business Process (PUT)
```mermaid
sequenceDiagram
participant C as Client
participant R as PUT /v3/settings
participant U as Config.update_config()
participant D as gns3_server.conf
C->>R: PUT {"Section": {"option": value | null}}
R->>R: schema validation (unknown key/section → 422)
R->>U: changes (masked/empty secrets skipped)
U->>U: locate owning file per option (later file wins)
alt option owned by a non-main configuration file
U-->>R: ConfigConflictError → 409 (nothing written)
else
U->>U: set / remove option (null removes, value falls back to default)
U->>U: validate merged ServerConfig (failure → 400, file untouched)
U->>D: atomic write (.tmp + os.replace, mode 0600)
U->>U: reload_and_notify() → runtime hot reload
R-->>C: 200 — new values + restart_required
R->>C: notification settings.updated (option names only, no values)
end
```
## API Endpoints
| Method | Path | Description | Privilege |
|--------|------|-------------|-----------|
| GET | `/v3/settings` | Return all current server settings | `Server.Audit` |
| PUT | `/v3/settings` | Update and persist server settings | `Server.Modify` |
Request example:
```json
{
"Server": {
"report_errors": true,
"allowed_interfaces": ["eth0", "lo"],
"compute_password": "**********"
},
"Qemu": {
"enable_monitor": false
}
}
```
Response example (abbreviated):
```json
{
"Server": { "report_errors": true, "allowed_interfaces": ["eth0", "lo"], "...": "..." },
"Qemu": { "enable_monitor": false },
"restart_required": ["Server.port"]
}
```
## Notes
- **Secrets** — `SecretStr` fields are masked in responses. An empty secret (e.g. `compute_password` before the server generates one) serializes as `""` rather than the mask. On PUT, the mask or an empty string means "leave unchanged"; only an explicit new value is written, in clear text like a hand-edited file.
- **`restart_required`** — options that only take effect after a server restart (bind host/port, protocol, TLS and certificates, port ranges, image/symbol/config paths, GNS3 VM credentials, skills paths, …). Everything else hot-reloads via `Config.instance().settings`.
- **GET reflects runtime values** — in-memory settings may differ from disk (e.g. the generated `compute_password`, the resolved `secrets_dir`); the mask/empty skip rule guarantees PUT never writes echoed values back.
- **Privileges** — `Server.Audit`/`Server.Modify` are seeded into the `Administrator` role at table creation only; existing databases need a manual grant. Superadmins bypass RBAC.
- **Hardening** — the file watcher callback is exception-guarded (`utils/file_watcher.py`): a callback failure is logged instead of silently killing the polling loop.
### Related Files
| File | Role |
|------|------|
| `gns3server/config.py` | `Config.update_config()` (read-modify-write, validate-before-write), `reload_and_notify()` |
| `gns3server/utils/file_watcher.py` | callback exception hardening |
| `gns3server/schemas/controller/settings.py` | response/update models, `SECRET_MASK` |
| `gns3server/api/routes/controller/settings.py` | GET/PUT endpoints, `restart_required`, notification |
| `gns3server/db/models/privileges.py` | `Server.Audit` / `Server.Modify` privilege seeds |
| `gns3server/config_samples/gns3_server.conf` | annotated sample configuration, human-readable reference kept in sync with the schema |
@@ -0,0 +1,195 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# External Skills Repository
## Overview
GNS3 Copilot loads all skills, prompts, and security configurations from an external Git repository at [github.com/gns3/gns3-skills](https://github.com/gns3/gns3-skills). This enables dynamic updates without server redeployment.
The repository provides:
- **Injection skills** (39 categories): Network fault scenarios for troubleshooting practice
- **Device skills**: Device-specific command knowledge (VPCS, etc.) — large devices split into per-protocol **topics**
- **Feature skills**: Topology planning, network design
- **System prompts**: Agent personality and behavior definitions
- **Forbidden commands**: Security rules for command filtering
## Architecture
```mermaid
graph TD
subgraph "GNS3-Skills Repository"
YAML[injection/*.yaml<br/>device/*.yaml + device/*/*.yaml<br/>feature/*.yaml]
MD[prompts/*.md]
CFG[config/forbidden_commands.txt]
end
subgraph "GNS3 Server"
SM[SkillsManager]
SL[SkillsLoader]
REG[Registry<br/>SKILLS_REGISTRY<br/>INJECTION_SKILLS_REGISTRY]
PROMPT[PROMPTS_CACHE]
FC[command_filter]
end
YAML --> SL
MD --> SL
CFG --> FC
SL --> REG
SL --> PROMPT
SM --> SL
SM -->|git pull| YAML
```
## Repository Structure
```
GNS3-Skills/
├── injection/ # 39 YAML files, one per protocol/category
│ ├── ospf_issues.yaml
│ ├── bgp_issues.yaml
│ ├── vlan_issues.yaml
│ └── ...
├── device/ # Device-specific skills
│ ├── vpcs.yaml # small devices: one single file
│ └── frr/ # large devices: split per protocol topic
│ ├── _base.yaml # device-level skill (console model, notes, aliases)
│ ├── ospf.yaml # topic file (merged under "topics" at load time)
│ └── bgp.yaml
├── feature/ # Feature skills
│ └── topology_planner.yaml
├── prompts/ # System prompts (Markdown)
│ ├── teaching_assistant.md
│ ├── lab_automation_assistant.md
│ ├── troubleshooting_injection.md
│ └── title.md
└── config/ # Security configuration
└── forbidden_commands.txt
```
## Device Topics
A device with knowledge for many protocols would grow one YAML file indefinitely. Such devices use a split layout instead: `device/<device>/_base.yaml` holds the device-level skill, and one file per protocol topic (`ospf.yaml`, `bgp.yaml`, ...) holds its commands and troubleshooting entries. The loader merges them into a single `SKILLS_REGISTRY` entry:
```
SKILLS_REGISTRY["frr_vtysh"] = { ..._base.yaml..., "topics": { "ospf": {...}, "bgp": {...} } }
```
Topic files must declare `device_type` (matching their `_base.yaml`), `topic` and `name`; the CI validator in the skills repository enforces this.
The `device_skill_get` tool exposes a three-step drill-down (mirroring `injection_skill_get`'s list → index → issue pattern):
```json
{"action": "list"}
{"device_type": "frr_vtysh", "detail": "index"}
{"device_type": "frr_vtysh", "topic": "bgp"}
```
Topic bodies are only served on an explicit `topic` request — every other detail level returns a topic index — so adding topics to a device does not grow the token cost of device-level lookups.
## Configuration
Skills repository settings are configured in `gns3_server.conf` under the `[Server]` section:
```ini
[Server]
skills_repo_url = https://github.com/gns3/gns3-skills.git
skills_repo_branch = main
skills_auto_update = true
```
| Setting | Default | Description |
|---------|---------|-------------|
| `skills_repo_url` | `https://github.com/gns3/gns3-skills.git` | Git repository URL |
| `skills_repo_branch` | `main` | Git branch to track |
| `skills_auto_update` | `true` | Automatically pull on reload |
## Initialization Flow
```mermaid
sequenceDiagram
participant Server
participant agent/__init__.py
participant SkillsManager
participant Git
Server->>agent/__init__.py: Import module
agent/__init__.py->>SkillsManager: Start background init thread
Note over SkillsManager: Thread.join(5s timeout)
SkillsManager->>Git: Check local repo exists?
alt No local repo
Git->>SkillsManager: git clone (with timeout env)
else Local repo exists
SkillsManager->>Git: Check uncommitted changes?
alt Has uncommitted changes
Git-->>SkillsManager: Warn, skip pull
else No changes
SkillsManager->>Git: git fetch (timeout 10s)
SkillsManager->>Git: Behind remote?
alt Behind
Git->>SkillsManager: git pull
else Up to date
Git-->>SkillsManager: Nothing to do
end
end
end
SkillsManager->>SkillsManager: reload_skills() - load YAML files
SkillsManager->>SkillsManager: reload_prompts() - load Markdown files
```
### Git Timeout Configuration
Git operations use per-command environment variables to prevent hanging:
```python
_GIT_TIMEOUT_ENV = {
"GIT_HTTP_TIMEOUT": "10", # Connection timeout (default: 120s)
"GIT_HTTP_LOW_SPEED_TIME": "5", # Slow speed threshold window
"GIT_HTTP_LOW_SPEED_LIMIT": "1000", # < 1 KB/s = slow → abort
}
```
These apply only to the specific `clone`/`fetch`/`pull` subprocess, not to the global environment.
## API Endpoint
### POST /copilot/reload/skills
Triggers a full reload of the skills repository. Performs one git update check, then reloads all skills, prompts, and forbidden commands from local files.
**Response:**
```json
{
"success": true,
"skills": true,
"skill_count": 39,
"prompts": true,
"prompt_count": 4,
"forbidden_commands": 6,
"version": "abc123def456..."
}
```
| Field | Description |
|-------|-------------|
| `success` | Overall success (true if skills or prompts loaded) |
| `skills` | Skills reload result |
| `skill_count` | Number of injection skills loaded |
| `prompts` | Prompts reload result |
| `prompt_count` | Number of prompts loaded |
| `forbidden_commands` | Number of forbidden command patterns |
| `version` | Git commit hash of the repository |
## Related Documentation
- [Fault Injection](fault-injection.md)
- [Command Security](command-security.md)
- [Chat API](chat-api.md)
+255
View File
@@ -0,0 +1,255 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Netmiko Supported Devices
**Netmiko Version:** 4.6.0
**Generated:** 2026-03-14 13:10:00
**Last Updated:** 2026-03-14 (Added VPCS support)
---
## Summary
- **Total Device Types:** 366
- **SSH Devices:** 154
- **Telnet Devices:** 55
- **Custom Devices:** 3
## Custom GNS3 Drivers
GNS3-Copilot includes custom Netmiko drivers optimized for GNS3 emulation:
| Platform | Device Type | Description |
|----------|-------------|-------------|
| Huawei CE | `gns3_huawei_telnet_ce` | Huawei CloudEngine driver with no authentication |
| Ruijie | `gns3_ruijie_telnet` | Ruijie OS enhanced driver with interactive command handling |
| VPCS | `gns3_vpcs_telnet` | VPCS simulator driver with ANSI code stripping |
## SSH Supported Devices
| Platform | Device Type | Source |
|----------|-------------|--------|
| A10 | `a10_ssh` | Netmiko |
| Accedian | `accedian_ssh` | Netmiko |
| Adtran | `adtran_os_ssh` | Netmiko |
| Adva | `adva_fsp150f2_ssh` | Netmiko |
| Adva | `adva_fsp150f3_ssh` | Netmiko |
| Alaxala | `alaxala_ax26s_ssh` | Netmiko |
| Alaxala | `alaxala_ax36s_ssh` | Netmiko |
| Alcatel | `alcatel_aos_ssh` | Netmiko |
| Alcatel | `alcatel_sros_ssh` | Netmiko |
| Allied | `allied_telesis_awplus_ssh` | Netmiko |
| Apresia | `apresia_aeos_ssh` | Netmiko |
| Arista | `arista_eos_ssh` | Netmiko |
| Arris | `arris_cer_ssh` | Netmiko |
| Aruba | `aruba_aoscx_ssh` | Netmiko |
| Aruba | `aruba_os_ssh` | Netmiko |
| Aruba | `aruba_osswitch_ssh` | Netmiko |
| Aruba | `aruba_procurve_ssh` | Netmiko |
| Asterfusion | `asterfusion_asternos_ssh` | Netmiko |
| Audiocode | `audiocode_66_ssh` | Netmiko |
| Audiocode | `audiocode_72_ssh` | Netmiko |
| Audiocode | `audiocode_shell_ssh` | Netmiko |
| Avaya | `avaya_ers_ssh` | Netmiko |
| Avaya | `avaya_vsp_ssh` | Netmiko |
| Bintec | `bintec_boss_ssh` | Netmiko |
| Broadcom | `broadcom_icos_ssh` | Netmiko |
| Brocade | `brocade_fastiron_ssh` | Netmiko |
| Brocade | `brocade_fos_ssh` | Netmiko |
| Brocade | `brocade_netiron_ssh` | Netmiko |
| Brocade | `brocade_nos_ssh` | Netmiko |
| Brocade | `brocade_vdx_ssh` | Netmiko |
| Brocade | `brocade_vyos_ssh` | Netmiko |
| Calix | `calix_b6_ssh` | Netmiko |
| Casa | `casa_cmts_ssh` | Netmiko |
| Cdot | `cdot_cros_ssh` | Netmiko |
| Centec | `centec_os_ssh` | Netmiko |
| Check Point | `checkpoint_gaia_ssh` | Netmiko |
| Ciena | `ciena_saos10_ssh` | Netmiko |
| Ciena | `ciena_saos_ssh` | Netmiko |
| Ciena | `ciena_waveserver_ssh` | Netmiko |
| Cisco | `cisco_apic_ssh` | Netmiko |
| Cisco | `cisco_asa_ssh` | Netmiko |
| Cisco | `cisco_ftd_ssh` | Netmiko |
| Cisco | `cisco_ios_ssh` | Netmiko |
| Cisco | `cisco_nxos_ssh` | Netmiko |
| Cisco | `cisco_s200_ssh` | Netmiko |
| Cisco | `cisco_s300_ssh` | Netmiko |
| Cisco | `cisco_tp_ssh` | Netmiko |
| Cisco | `cisco_viptela_ssh` | Netmiko |
| Cisco | `cisco_wlc_ssh` | Netmiko |
| Cisco | `cisco_xe_ssh` | Netmiko |
| Cisco | `cisco_xr_ssh` | Netmiko |
| Cloudgenix | `cloudgenix_ion_ssh` | Netmiko |
| Corelight | `corelight_linux_ssh` | Netmiko |
| Coriant | `coriant_ssh` | Netmiko |
| Cumulus | `cumulus_linux_ssh` | Netmiko |
| Dell | `dell_dnos9_ssh` | Netmiko |
| Dell | `dell_force10_ssh` | Netmiko |
| Dell | `dell_isilon_ssh` | Netmiko |
| Dell | `dell_os10_ssh` | Netmiko |
| Dell | `dell_os6_ssh` | Netmiko |
| Dell | `dell_os9_ssh` | Netmiko |
| Dell | `dell_powerconnect_ssh` | Netmiko |
| Dell | `dell_sonic_ssh` | Netmiko |
| Digi | `digi_transport_ssh` | Netmiko |
| Dlink | `dlink_ds_ssh` | Netmiko |
| Edgecore | `edgecore_sonic_ssh` | Netmiko |
| Ekinops | `ekinops_ek360_ssh` | Netmiko |
| Eltex | `eltex_esr_ssh` | Netmiko |
| Eltex | `eltex_ssh` | Netmiko |
| Endace | `endace_ssh` | Netmiko |
| Enterasys | `enterasys_ssh` | Netmiko |
| Ericsson | `ericsson_ipos_ssh` | Netmiko |
| Ericsson | `ericsson_mltn63_ssh` | Netmiko |
| Ericsson | `ericsson_mltn66_ssh` | Netmiko |
| Extreme | `extreme_ers_ssh` | Netmiko |
| Extreme | `extreme_exos_ssh` | Netmiko |
| Extreme | `extreme_netiron_ssh` | Netmiko |
| Extreme | `extreme_nos_ssh` | Netmiko |
| Extreme | `extreme_slx_ssh` | Netmiko |
| Extreme | `extreme_ssh` | Netmiko |
| Extreme | `extreme_tierra_ssh` | Netmiko |
| Extreme | `extreme_vdx_ssh` | Netmiko |
| Extreme | `extreme_vsp_ssh` | Netmiko |
| Extreme | `extreme_wing_ssh` | Netmiko |
| F5 | `f5_linux_ssh` | Netmiko |
| F5 | `f5_ltm_ssh` | Netmiko |
| F5 | `f5_tmsh_ssh` | Netmiko |
| Fiberstore | `fiberstore_fsos_ssh` | Netmiko |
| Fiberstore | `fiberstore_fsosv2_ssh` | Netmiko |
| Fiberstore | `fiberstore_networkos_ssh` | Netmiko |
| Flexvnf | `flexvnf_ssh` | Netmiko |
| Fortinet | `fortinet_ssh` | Netmiko |
| Garderos | `garderos_grs_ssh` | Netmiko |
| Generic | `generic_ssh` | Netmiko |
| Generic | `generic_termserver_ssh` | Netmiko |
| H3C (华三) | `h3c_comware_ssh` | Netmiko |
| HP | `hp_comware_ssh` | Netmiko |
| HP | `hp_procurve_ssh` | Netmiko |
| Hillstone | `hillstone_stoneos_ssh` | Netmiko |
| Huawei | `huawei_olt_ssh` | Netmiko |
| Huawei | `huawei_smartax_ssh` | Netmiko |
| Huawei | `huawei_smartaxmmi_ssh` | Netmiko |
| Huawei | `huawei_ssh` | Netmiko |
| Huawei | `huawei_vrp_ssh` | Netmiko |
| Huawei | `huawei_vrpv8_ssh` | Netmiko |
| Infinera | `infinera_packet_ssh` | Netmiko |
| Ipinfusion | `ipinfusion_ocnos_ssh` | Netmiko |
| Juniper | `juniper_junos_ssh` | Netmiko |
| Juniper | `juniper_screenos_ssh` | Netmiko |
| Juniper | `juniper_ssh` | Netmiko |
| Keymile | `keymile_nos_ssh` | Netmiko |
| Keymile | `keymile_ssh` | Netmiko |
| Lancom | `lancom_lcossx4_ssh` | Netmiko |
| Linux | `linux_ssh` | Netmiko |
| Maipu (迈普) | `maipu_ssh` | Netmiko |
| Mellanox | `mellanox_mlnxos_ssh` | Netmiko |
| Mellanox | `mellanox_ssh` | Netmiko |
| Mikrotik | `mikrotik_routeros_ssh` | Netmiko |
| Mikrotik | `mikrotik_switchos_ssh` | Netmiko |
| Mrv | `mrv_lx_ssh` | Netmiko |
| Mrv | `mrv_optiswitch_ssh` | Netmiko |
| Nec | `nec_ix_ssh` | Netmiko |
| Netapp | `netapp_cdot_ssh` | Netmiko |
| Netgear | `netgear_prosafe_ssh` | Netmiko |
| Netscaler | `netscaler_ssh` | Netmiko |
| Nokia | `nokia_srl_ssh` | Netmiko |
| Nokia | `nokia_sros_ssh` | Netmiko |
| Oneaccess | `oneaccess_oneos_ssh` | Netmiko |
| Ovs | `ovs_linux_ssh` | Netmiko |
| Palo Alto | `paloalto_panos_ssh` | Netmiko |
| Pluribus | `pluribus_ssh` | Netmiko |
| Quanta | `quanta_mesh_ssh` | Netmiko |
| Rad | `rad_etx_ssh` | Netmiko |
| Raisecom | `raisecom_roap_ssh` | Netmiko |
| Ruckus | `ruckus_fastiron_ssh` | Netmiko |
| Ruijie (锐捷) | `ruijie_os_ssh` | Netmiko |
| Silverpeak | `silverpeak_vxoa_ssh` | Netmiko |
| Sixwind | `sixwind_os_ssh` | Netmiko |
| Sophos | `sophos_sfos_ssh` | Netmiko |
| Supermicro | `supermicro_smis_ssh` | Netmiko |
| Telcosystems | `telcosystems_binos_ssh` | Netmiko |
| Teldat | `teldat_cit_ssh` | Netmiko |
| Tplink | `tplink_jetstream_ssh` | Netmiko |
| Ubiquiti | `ubiquiti_edge_ssh` | Netmiko |
| Ubiquiti | `ubiquiti_edgerouter_ssh` | Netmiko |
| Ubiquiti | `ubiquiti_edgeswitch_ssh` | Netmiko |
| Ubiquiti | `ubiquiti_unifiswitch_ssh` | Netmiko |
| Vertiv | `vertiv_mph_ssh` | Netmiko |
| Vyatta | `vyatta_vyos_ssh` | Netmiko |
| Vyos | `vyos_ssh` | Netmiko |
| Watchguard | `watchguard_fireware_ssh` | Netmiko |
| Yamaha | `yamaha_ssh` | Netmiko |
| ZTE (中兴) | `zte_zxros_ssh` | Netmiko |
| Zyxel | `zyxel_os_ssh` | Netmiko |
## Telnet Supported Devices
| Platform | Device Type | Source |
|----------|-------------|--------|
| Adtran | `adtran_os_telnet` | Netmiko |
| Apresia | `apresia_aeos_telnet` | Netmiko |
| Arista | `arista_eos_telnet` | Netmiko |
| Aruba | `aruba_procurve_telnet` | Netmiko |
| Audiocode | `audiocode_66_telnet` | Netmiko |
| Audiocode | `audiocode_72_telnet` | Netmiko |
| Audiocode | `audiocode_shell_telnet` | Netmiko |
| Bintec | `bintec_boss_telnet` | Netmiko |
| Brocade | `brocade_fastiron_telnet` | Netmiko |
| Brocade | `brocade_netiron_telnet` | Netmiko |
| Calix | `calix_b6_telnet` | Netmiko |
| Centec | `centec_os_telnet` | Netmiko |
| Ciena | `ciena_saos_telnet` | Netmiko |
| Cisco | `cisco_ios_telnet` | Netmiko |
| Cisco | `cisco_nxos_telnet` | Netmiko |
| Cisco | `cisco_s200_telnet` | Netmiko |
| Cisco | `cisco_s300_telnet` | Netmiko |
| Cisco | `cisco_xr_telnet` | Netmiko |
| Dell | `dell_dnos6_telnet` | Netmiko |
| Dell | `dell_powerconnect_telnet` | Netmiko |
| Dlink | `dlink_ds_telnet` | Netmiko |
| Extreme | `extreme_exos_telnet` | Netmiko |
| Extreme | `extreme_netiron_telnet` | Netmiko |
| Extreme | `extreme_telnet` | Netmiko |
| Fiberstore | `fiberstore_fsosv2_telnet` | Netmiko |
| Generic | `generic_telnet` | Netmiko |
| Generic | `generic_termserver_telnet` | Netmiko |
| Genexis | `genexis_solt33_telnet` | Netmiko |
| HP | `hp_comware_telnet` | Netmiko |
| HP | `hp_procurve_telnet` | Netmiko |
| Huawei | `huawei_olt_telnet` | Netmiko |
| Huawei | `huawei_telnet` | Netmiko |
| Huawei | `gns3_huawei_telnet_ce` | Custom ✨ (GNS3) |
| Infinera | `infinera_packet_telnet` | Netmiko |
| Ipinfusion | `ipinfusion_ocnos_telnet` | Netmiko |
| Juniper | `juniper_junos_telnet` | Netmiko |
| Maipu (迈普) | `maipu_telnet` | Netmiko |
| Nec | `nec_ix_telnet` | Netmiko |
| Nokia | `nokia_sros_telnet` | Netmiko |
| Oneaccess | `oneaccess_oneos_telnet` | Netmiko |
| Optilink | `optilink_eolt11444_telnet` | Netmiko |
| Optilink | `optilink_eolt9702_telnet` | Netmiko |
| Palo Alto | `paloalto_panos_telnet` | Netmiko |
| Rad | `rad_etx_telnet` | Netmiko |
| Raisecom | `raisecom_telnet` | Netmiko |
| Ruckus | `ruckus_fastiron_telnet` | Netmiko |
| Ruijie (锐捷) | `ruijie_os_telnet` | Netmiko |
| Ruijie (锐捷) | `gns3_ruijie_telnet` | Custom ✨ (GNS3 Enhanced) |
| Supermicro | `supermicro_smis_telnet` | Netmiko |
| VPCS | `gns3_vpcs_telnet` | Custom ✨ (GNS3 VPCS Simulator) |
| Telcosystems | `telcosystems_binos_telnet` | Netmiko |
| Teldat | `teldat_cit_telnet` | Netmiko |
| Tplink | `tplink_jetstream_telnet` | Netmiko |
| Yamaha | `yamaha_telnet` | Netmiko |
| ZTE (中兴) | `zte_zxros_telnet` | Netmiko |
---
*This document was generated automatically by the Netmiko device list script.*
@@ -0,0 +1,280 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This document is a roadmap/planning document. The described features have not been implemented yet.
# AIOps Fault Injection Testing Pipeline — Roadmap
## Overview
Build a realistic testing pipeline that duplicates the company's production network architecture into GNS3, then systematically injects network faults using the AI Copilot's fault injection capabilities to validate and train the AIOps module before production deployment.
```
┌─────────────────────────────────────────────────────────────────┐
│ AIOps Testing Pipeline │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ Network │ │ Fault │ │ AIOps │ │
│ │ Duplication │───▶│ Injection │───▶│ Validation │ │
│ │ (Phase 1) │ │ (Phase 2) │ │ (Phase 3) │ │
│ └──────────────┘ └──────────────┘ └──────────────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ GNS3 Network │ │ Fault │ │ Results & │ │
│ │ Replica │ │ Scenarios │ │ Reporting │ │
│ └──────────────┘ └──────────────┘ └──────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
```
## Core Concept
1. **Duplicate** the company's production network architecture into a GNS3 simulation environment
2. **Select** a set of fault types to test (OSPF, BGP, VxLAN, STP, packet filter, etc.)
3. **Inject** faults automatically using the AI Copilot's fault injection capabilities
4. **Validate** whether the AIOps module correctly identifies and reports each fault
5. **Loop** through all selected fault scenarios, building a comprehensive test matrix
6. **Train** the AIOps module on results to improve accuracy before production deployment
## Phase 1: Network Architecture Duplication
### Goal
Create a high-fidelity replica of the company production network in GNS3.
### Key Tasks
- [ ] **Topology Mapping**: Document production network topology (devices, links, protocols)
- [ ] **Device Selection**: Map production devices to GNS3-compatible images (Cisco IOSv, XRv, Juniper vSRX, etc.)
- [ ] **Configuration Extraction**: Export sanitized production configs (remove passwords, public IPs, sensitive data)
- [ ] **GNS3 Deployment**: Build the network in GNS3 with accurate device placement and links
- [ ] **Config Replication**: Apply adapted configurations to GNS3 devices
- [ ] **Connectivity Validation**: Verify OSPF/BGP adjacencies, VLANs, VRFs, and end-to-end reachability
- [ ] **Baseline Capture**: Record normal operation metrics (CPU, memory, interface counters, routing tables)
### Considerations
- Sanitize all production configurations before importing into GNS3
- Use environment-specific IP addressing where necessary (loopbacks, management)
- Document all deviations from production for traceability
## Phase 2: Fault Injection Pipeline
### Goal
Systematically inject network faults and validate AIOps detection using the existing AI Copilot fault injection infrastructure.
### Components
```
┌──────────────────────────────────────────────────────────────────┐
│ Fault Injection Pipeline │
├──────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────┐ │
│ │ Scenario │ │ Inject │ │ AIOps │ │ Record │ │
│ │ Selector │──▶│ Fault │──▶│ Validate │──▶│ & Report │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────────┘ │
│ │ │ │ │ │
│ │ │ │ │ │
│ └──────────────┴──────────────┴───────────────┘ │
│ │ │
│ ▼ │
│ Loop until all scenarios tested │
└──────────────────────────────────────────────────────────────────┘
```
### 2.1 Scenario Selector
- Read fault scenarios from the GNS3-Skills repository
- Support filtering by:
- Protocol (OSPF, BGP, VxLAN, STP, VLAN, etc.)
- Severity (critical, high, medium, low)
- Difficulty (beginner, intermediate, advanced)
- Track which scenarios have been tested
- Randomize selection order to avoid bias
- Exclude previously tested scenarios
### 2.2 Fault Injection
- Use existing `link_update` tool for network-level faults
- Use existing `device_config_send` for configuration faults
- Use existing `InjectionSkillsTool` to query and select appropriate faults
- Support combined faults (multiple simultaneous issues)
- Auto-recovery between scenarios (restore baseline state)
### 2.3 AIOps Validation
- Feed network state (after fault injection) to the AIOps module
- Record AIOps diagnosis output
- Compare AIOps results against expected fault definition:
- **Correct identification**: AIOps names the exact fault
- **Partial identification**: AIOps identifies related symptoms but not root cause
- **Missed**: AIOps fails to detect any issue
- **False positive**: AIOps reports a fault that doesn't exist
### 2.4 Test Execution Flow
```
1. Reset network to clean baseline state
2. Select next untested fault scenario
3. Inject the fault into the GNS3 network
4. Wait for convergence (configurable delay)
5. Query AIOps module for diagnosis
6. Compare AIOps output with expected fault definition
7. Record result (pass/fail/partial)
8. Restore network to baseline
9. Repeat from step 2 until all scenarios completed
```
## Phase 3: Traffic Injection (Enhanced Realism)
### Goal
Add realistic network traffic to the GNS3 simulation so that AIOps has real telemetry data to analyze, rather than a static network.
### Approaches
#### 3.1 Traffic Generators in GNS3
- Deploy traffic generator appliances in GNS3 (e.g., TRex, Ostinato, Scapy on Linux nodes)
- Generate realistic traffic patterns:
- VoIP/RTP streams
- HTTP/HTTPS web traffic
- Database replication
- Routing protocol updates (OSPF hellos, BGP keepalives)
- ICMP monitoring traffic
#### 3.2 tcpreplay with Captured Traffic
- Capture real production traffic (sanitized)
- Use `tcpreplay` to replay traffic through the GNS3 network
- More realistic than synthetic traffic generators
#### 3.3 Integration with Network Monitoring
- Feed simulated device telemetry (SNMP, syslog, NetFlow) to the AIOps module
- Enable AIOps to analyze real-time telemetry during fault conditions
- Validate that AIOps can distinguish between traffic anomalies and actual faults
## Success Metrics
| Metric | Target | Measurement Method |
|--------|--------|-------------------|
| Fault detection rate | >95% | AIOps correctly identifies injected faults |
| False positive rate | <5% | AIOps reports fault when none exists |
| Time to detection | <30s | Duration from injection to AIOps alert |
| Coverage | >80% of defined scenarios | Percentage of scenarios tested |
| Accuracy improvement | Measurable per cycle | Compare pass rates across test cycles |
## Technical Architecture
```
┌────────────────────────────────────────────────────────────────────┐
│ Test Orchestrator │
│ ┌──────────────────────────────────────────────────────────────┐ │
│ │ Test Runner (Python) │ │
│ │ - Scenario selection & scheduling │ │
│ │ - Fault injection coordination │ │
│ │ - AIOps query & result collection │ │
│ │ - Report generation │ │
│ └──────────┬────────────────────────────────────────────┬───────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌────────────────────┐ ┌────────────────────┐ │
│ │ GNS3 Controller │ │ AIOps Module │ │
│ │ (gns3-server) │ │ │ │
│ │ - Network mgmt │ │ - Fault diagnosis │ │
│ │ - Fault injection │ │ - Alert detection │ │
│ │ - State queries │ │ - Root cause │ │
│ └────────────────────┘ └────────────────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────────┐ │
│ │ GNS3 Network │ │
│ │ Replica │ │
│ │ - Devices │ │
│ │ - Traffic │ │
│ │ - Telemetry │ │
│ └────────────────────┘ │
└────────────────────────────────────────────────────────────────────┘
```
## Reporting
Each test cycle produces:
- **Summary report**: Pass/fail rates, coverage, trends
- **Detailed per-scenario report**: Injection details, AIOps response, comparison
- **Regression tracker**: Which scenarios regressed since last cycle
- **Accuracy trend**: Improvement or degradation over time
### Example Report Entry
```yaml
test_cycle: 7
date: "2026-06-01"
scenarios_planned: 20
scenarios_completed: 18
failed_injections: 1
skipped: 1
results:
- scenario: ospf_hello_dead_mismatch
protocol: ospf
severity: major
injection_method: device_config
target_device: R1
aiops_detection: true
aiops_diagnosis: "OSPF Hello/Dead interval mismatch between R1 and R2"
detection_latency_ms: 12000
match: exact
- scenario: packet_loss_heavy
protocol: performance
severity: high
injection_method: packet_filter
target_link: "R1 ↔ R2 (ethernet)"
aiops_detection: true
aiops_diagnosis: "High packet loss detected on link R1-R2"
detection_latency_ms: 45000
match: partial
```
## Dependencies
- [ ] GNS3 network replica ready and validated
- [ ] AI Copilot fault injection tools operational
- [ ] AIOps module query interface available
- [ ] Traffic generation tools deployed (for Phase 3)
- [ ] Test orchestrator framework (to be built)
- [ ] Result database and reporting system
## Timeline
| Phase | Duration | Deliverable |
|-------|----------|-------------|
| P1: Network Duplication | 2-4 weeks | GNS3 replica of production network |
| P2: Fault Injection Pipeline | 2-3 weeks | Automated test runner + first results |
| P3: Traffic Injection | 2-4 weeks | Realistic traffic simulation integrated |
## Status
- [ ] P1: Network architecture duplication
- [ ] Topology mapping documented
- [ ] Device configurations sanitized and adapted
- [ ] GNS3 replica deployed
- [ ] Baseline connectivity verified
- [ ] P2: Fault injection pipeline
- [ ] Scenario selection framework
- [ ] Automated fault injection
- [ ] AIOps validation interface
- [ ] Report generation
- [ ] Loop/retry mechanism
- [ ] P3: Traffic injection
- [ ] Traffic generator deployment
- [ ] Traffic pattern library
- [ ] AIOps telemetry integration
@@ -0,0 +1,64 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This document is a roadmap/planning document. The described features have not been implemented yet.
# Injection Fault Tracking — Roadmap
## Problem
When using the AI Copilot in troubleshooting injection mode across multiple chat sessions within the same project, there is no mechanism to prevent the same fault from being injected repeatedly. Each new session starts with a clean slate, unaware of what faults have already been used. This leads to:
- Duplicate injection scenarios across different sessions
- No visibility for instructors into which faults have been used
- No record of which devices were affected or whether faults were resolved
## Proposed Solution
Track injected faults per chat session and feed the history into the LLM's system prompt as context, so the model actively avoids repeating scenarios.
### 1. Storage
The existing `chat_sessions` table has `metadata` and `stats` JSON columns. After each fault injection, the agent records:
```json
// stored in chat_session.metadata
{
"injected_fault": {
"fault_type": "injection_ospf",
"issue_key": "ospf_hello_dead_mismatch",
"issue_name": "OSPF Hello/Dead Interval Mismatch",
"device": "R1",
"severity": "major",
"injected_at": "2026-05-11T23:00:00Z",
"resolved": false
}
}
```
### 2. Context Injection
When starting a new troubleshooting session, query all previous sessions for the project, filter by `copilot_mode = "troubleshooting_injection"`, extract `injected_fault` data, and inject a summary into the system prompt via a placeholder (similar to the existing `{{topology_info}}` mechanism):
```
Previously injected faults in this project:
1. OSPF Hello/Dead Interval Mismatch on R1 (2026-05-11) — resolved
2. BGP Route Reflector misconfiguration on R3 (2026-05-10) — resolved
Select a fault that has NOT been used before.
```
### 3. Prompt Update
The `troubleshooting_injection.md` prompt in the GNS3-Skills repository gains an `{{injection_history}}` placeholder, and the agent is instructed to choose a fault not in the history list.
## Status
- [ ] GNS3-Skills: add `{{injection_history}}` placeholder to `troubleshooting_injection.md`
- [ ] gns3-server: implement injection fault recording in agent chat session flow
- [ ] gns3-server: implement injection history query across sessions per project
- [ ] gns3-server: inject history into system prompt via `context_manager.py`
- [ ] gns3-server: add `exclude` parameter to `injection_skill_get` for filtering used faults
@@ -0,0 +1,621 @@
# RBAC User Isolation Roadmap
## Overview
GNS3 3.0 ships with a complete RBAC framework (ACE + Role + Privilege models), but the user isolation layer is incomplete. Users can see resources they should not have access to because:
- Resource creation does not auto-grant the creator an ACE
- List endpoints return unfiltered results
- Two GET endpoints have RBAC checks bypassed via FIXME
**This document has been updated to reflect the implemented solution in `feature/simple-user-isolation` branch.**
## Current State
| Resource | Route Check | List Filtering | Auto-ACE on Create | ACE Cleanup on Delete |
|---|---|---|---|---|
| Project | `Project.Audit/Modify/Allocate` | **Implemented** — Three-step filtering | **Not needed** | Done |
| Template | `Template.Audit` **FIXME** | None — all templates returned | **Missing** | Done |
| Node | `Node.Audit/Modify/Allocate` | N/A (inherits project) | Inherits project | N/A |
| Link | `Link.Audit/Modify/Allocate` | N/A (inherits project) | Inherits project | N/A |
| Drawing | `Drawing.Audit/Modify/Allocate` | N/A (inherits project) | Inherits project | N/A |
| Snapshot | `Snapshot.Audit/Allocate/Restore` | N/A (inherits project) | Inherits project | N/A |
| Image | `Image.Audit/Allocate` | None — all images returned | **Missing** | Missing |
| Compute | `Compute.Audit` **FIXME** | None — all computes returned | N/A (shared infra) | Done |
| Appliance | `Appliance.Audit/Allocate` | None — all appliances returned | N/A (builtin) | N/A |
| Symbol | `Symbol.Audit/Allocate` | None — all symbols returned | N/A (builtin) | N/A |
## Implemented Solution: Project Isolation
### Three-Step Permission Check Logic
**Status**: ✅ Implemented in `feature/simple-user-isolation` branch
```python
# Step 1: ACE check - basic access permission
# Get projects user has ACE for
ace_projects = []
for project in controller.projects.values():
project_path = f"/projects/{project.id}"
if await rbac_repo.check_user_has_privilege(current_user.user_id, project_path, "Project.Audit"):
ace_projects.append(project)
# Step 2: Filter ace_projects by created_by - user's own projects
# Project sharing is only available through resource pools
user_projects = [p.asdict() for p in ace_projects if p.created_by == current_user.username]
projects.extend(user_projects)
# Step 3: Resource pool projects
# Projects shared through resource pools
user_pool_resources = await rbac_repo.get_user_pool_resources(current_user.user_id, "Project.Audit")
project_ids_in_pools = [str(r.resource_id) for r in user_pool_resources if r.resource_type == "project"]
pool_projects = [p.asdict() for p in controller.projects.values() if p.id in project_ids_in_pools]
projects.extend(pool_projects)
```
### Key Design Principles
1. **ACE for basic access control**: Controls whether user can access the system
2. **created_by for user isolation**: Controls which specific resources user can access
3. **Resource pools for project sharing**: The only mechanism for sharing projects between users
4. **No direct ACE sharing**: Users cannot configure ACE directly on specific projects to share them
### Advantages of This Approach
- **Fault tolerance**: Even with broad ACE configuration (`path: "/" + propagate: true`), user isolation remains effective
- **Clear separation**: Basic access, data ownership, and team sharing are clearly separated
- **Simple mechanism**: No complex auto-ACE or seen_project_ids tracking required
- **Performance**: Leverages existing created_by field, no schema changes needed
## Updated Architecture
```mermaid
graph TD
subgraph Client
WebUI
CLI
end
subgraph "Controller API"
Auth[get_current_active_user]
Routes[Resource Routes]
ACE_Check[Step 1: ACE Check]
Owner_Filter[Step 2: Filter by created_by]
Pool_Check[Step 3: Resource Pools]
end
subgraph "RBAC Engine"
ACE[(ACE table)]
Role[(Role table)]
Privilege[(Privilege table)]
Checker[check_user_has_privilege]
end
WebUI --> Auth
CLI --> Auth
Auth --> Routes
Routes --> ACE_Check
ACE_Check --> Checker
ACE_Check --> Owner_Filter
Owner_Filter --> Pool_Check
Pool_Check --> Checker
Checker --> ACE
Checker --> Role
Role --> Privilege
```
## Business Process
### Project listing with three-step filtering
```mermaid
sequenceDiagram
actor U as User
participant API as GET /projects
participant Controller as Controller
participant RBAC as RBAC Engine
U->>API: List projects
API->>API: get_current_active_user (not superadmin)
API->>RBAC: Step 1: ACE check on each project
loop Each project
RBAC-->>API: ACE results
end
API->>API: Step 2: Filter by created_by
API-->>U: User's own projects
API->>RBAC: Step 3: Resource pool projects
RBAC-->>API: Pool projects
API-->>U: Combined list (own + pool)
```
## Updated Phased Plan
### ✅ Phase 1 — MVP: Project isolation (COMPLETED)
**Goal**: Users only see projects they created or were granted access to through resource pools.
| Task | Files | Status | Detail |
|---|---|---|---|
| Fix project list filtering | `projects.py` — `get_projects()` | ✅ **Implemented** | Three-step filtering: ACE check → created_by filter → resource pools |
**Result**:
- ✅ Users can only see projects they created
- ✅ Team collaboration through resource pools works
- ✅ Fault tolerance: Works correctly even with broad ACE configurations
- ✅ No schema changes required
- ✅ ~30 lines changed
### Phase 2 — Template isolation
**Goal**: Users see their own templates + builtin templates only.
| Task | Files | Detail |
|---|---|---|
| Apply same pattern to templates | `templates.py` — `get_templates()` | Use same three-step filtering as projects |
| Uncomment `Template.Audit` | `templates.py` | Restore `has_privilege("Template.Audit")` checks |
**Dependency**: Web UI must handle 403 from `GET /templates/{id}`. Mitigation: keep builtin templates unconditionally visible so the UI always has data.
### Phase 3 — Image isolation (optional)
**Goal**: Users see only images they uploaded.
| Task | Files |
|---|---|
| Apply same pattern to images | `images.py` — `get_images()` |
| Fix image list filtering | `images.py` |
| ACE cleanup on delete | `images.py` — `delete_image()` |
### Phase 4 — Default ACE for "Users" group (optional)
**Goal**: Users in "Users" group can create/list resources without admin ACE intervention.
| Task | Detail |
|---|---|
| Default ACE on `/projects` | Grant "Users" group → User role → `/projects` (propagate=False) |
| Default ACE on `/templates` | Grant "Users" group → User role → `/templates` (propagate=False) |
## API Endpoints Changed
### Phase 1 (Implemented)
| Method | Path | Change |
|---|---|---|
| `GET` | `/v3/projects` | Three-step filtering: ACE → created_by → resource pools |
### Phase 2 (Planned)
| Method | Path | Change |
|---|---|---|
| `GET` | `/v3/templates` | Apply same three-step filtering |
| `GET` | `/v3/templates/{id}` | Restore `Template.Audit` check |
## Key Design Decisions
1. **Project sharing through resource pools only**: Users cannot configure ACE directly to share specific projects. All sharing must go through resource pools. This prevents permission configuration chaos and maintains clear ownership semantics.
2. **No auto-ACE required**: The three-step filtering logic works without needing automatic ACE creation on project creation. The created_by field provides sufficient ownership information.
3. **Fault-tolerant to ACE configuration**: Even if administrators configure broad ACE permissions (like `path: "/" + propagate: true`), user isolation remains effective because Step 2 filters by created_by.
4. **No DB migration required**: Uses existing ACE/role/privilege tables and created_by field. No schema changes needed.
5. **Performance**: Project list filtering is O(n) where n is the total number of projects. Each project requires one ACE check. Acceptable for < 500 projects. Can optimize later with batch ACE queries if needed.
## Updated References
- **Implementation**: `gns3server/api/routes/controller/projects.py` (feature/simple-user-isolation branch)
- **Discussion**: https://github.com/GNS3/gns3-server/discussions/1949
- **RBAC models**: `gns3server/db/models/acl.py`, `roles.py`, `privileges.py`
- **RBAC repository**: `gns3server/db/repositories/rbac.py`
- **Auth dependency**: `gns3server/api/routes/controller/dependencies/authentication.py`
- **RBAC dependency**: `gns3server/api/routes/controller/dependencies/rbac.py`
- **Resource pools**: `gns3server/db/models/pools.py` and `gns3server/db/repositories/pools.py`
## Implementation Notes
### What Was Implemented
The `feature/simple-user-isolation` branch implements a robust user isolation mechanism that:
1. **Integrates with existing RBAC framework** without breaking changes
2. **Leverages the created_by field** that already exists in the Project model
3. **Uses three-step pipeline filtering** to avoid complex seen_project_ids tracking
4. **Supports team collaboration** through existing resource pool functionality
5. **Is fault-tolerant to ACE misconfiguration** - broad ACE permissions don't break user isolation
### What Was Not Implemented
The original roadmap's Phase 1 included auto-ACE creation on project creation. This was determined to be unnecessary because:
- The three-step filtering logic achieves user isolation without auto-ACE
- Auto-ACE would add complexity without significant benefit
- Project sharing through resource pools is cleaner than direct ACE configuration
### Future Work
The same three-step filtering pattern can be applied to:
- **Templates**: Replace the FIXME comment with proper filtering logic
- **Images**: Apply the same pattern for user image isolation
- **Other resources**: Extend the pattern as needed
This implementation provides a solid foundation for user isolation in GNS3 3.0+ while maintaining compatibility with the existing RBAC framework.
## Phase 5 — ACE Architecture Refactoring (Future)
**Goal**: Improve ACE manageability by supporting multiple paths and resource pools in a single ACE entry.
### Current Problem
With the current design where one ACE = one path:
- **ACE explosion**: 5 user groups × 10 resource pools = 50 ACE entries
- **Management complexity**: Difficult to maintain and understand ACE purpose
- **Performance impact**: Permission checking must iterate through many ACE entries
### Proposed Solution
Redesign ACE structure to support multiple paths and resource pools in a single ACE entry:
```json
{
"name": "Development Team Access",
"description": "Full access for development team",
"ace_type": "group",
"group_id": "...",
"role_id": "...",
"paths": ["/projects", "/templates", "/images"],
"resource_pools": ["pool-id-1", "pool-id-2"],
"propagate": true,
"allowed": true
}
```
### Database Changes Required
1. **Add name and description to ACE table**:
```sql
ALTER TABLE acl ADD COLUMN name VARCHAR;
ALTER TABLE acl ADD COLUMN description TEXT;
```
2. **Create association tables**:
```sql
CREATE TABLE ace_paths (
ace_id UUID REFERENCES acl(ace_id),
path VARCHAR,
PRIMARY KEY (ace_id, path)
);
CREATE TABLE ace_pools (
ace_id UUID REFERENCES acl(ace_id),
resource_pool_id UUID REFERENCES resource_pools(resource_pool_id),
PRIMARY KEY (ace_id, resource_pool_id)
);
```
3. **Update permission checking logic** to check both paths and resource_pools tables
### Benefits
- ✅ **Reduced ACE entries**: One ACE covers multiple related paths/pools
- ✅ **Better organization**: Logical grouping with clear names and descriptions
- ✅ **Easier management**: Edit one ACE instead of multiple related entries
- ✅ **Improved performance**: Fewer ACE entries to check during permission validation
### Implementation Considerations
- **Migration path**: Need to migrate existing single-path ACEs to new structure
- **Backward compatibility**: API should support both old and new formats during transition
- **UI updates**: ACE management interface needs to support multi-path/pool selection
- **Permission checking**: Update `check_user_has_privilege` to check association tables
## Phase 6 — Frontend Permission Query API (Future)
**Goal**: Provide an API endpoint for the Web UI to query the current user's permissions, enabling dynamic UI rendering based on role and ACE configuration.
### Problem
Currently the Web UI cannot determine what the authenticated user is allowed to see or do:
- ❌ Users see menu items and buttons they don't have permission to use
- ❌ Clicking a forbidden action results in a 403 error (unexpected UX)
- ❌ No way to hide/show UI elements based on actual permissions
### Proposed Solution
Create a `GET /v3/me/permissions` endpoint that returns the current user's effective permissions:
```json
{
"user_id": "uuid",
"is_superadmin": false,
"permissions": [
{"path": "/projects", "privileges": ["Project.Audit", "Project.Allocate"]},
{"path": "/projects/{id}", "privileges": ["Project.Audit", "Project.Modify"]},
{"path": "/templates", "privileges": ["Template.Audit"]}
],
"pools": [
{"path": "/pools/{id}", "name": "Team Projects", "privileges": ["Pool.Audit"]}
]
}
```
### Benefits
- ✅ **Dynamic UI**: Frontend can hide inaccessible menus/buttons
- ✅ **Better UX**: Users only see what they can actually use
- ✅ **Reduced errors**: Fewer 403 responses from hidden operations
- ✅ **Faster feedback**: Permission checks happen at render time, not request time
### Dependencies
- **Phase 5 (ACE refactoring)** may change how permissions are stored, which would affect this API's implementation
## Phase 7 — Resource Pool Renaming (Future)
**Goal**: Rename "Resource Pool" to a more descriptive name that better reflects its actual purpose.
### Problem
The current name "Resource Pool" is too generic and doesn't clearly convey its actual function:
- ❌ **Ambiguous name**: "Resource Pool" could refer to compute pools, connection pools, etc.
- ❌ **Unclear purpose**: Users don't understand it's primarily for sharing projects
- ❌ **Discoverability**: Hard to find the right feature when looking for project sharing
### Actual Function
Resource pools in GNS3 are used for:
- **Project sharing**: Allow users to access projects created by other users
- **Team collaboration**: Enable team members to work on shared projects
- **Access control**: Provide fine-grained permissions for project access through three-step filtering (ACE check → created_by filter → resource pools)
### Proposed Name Options
| Option | Pros | Cons |
|--------|-------|-------|
| **Project Pool** | More explicit, indicates it contains projects | Still uses "pool" terminology |
| **Shared Projects** | Directly describes the function | Loses the "collection" concept |
| **Team Projects** | Emphasizes collaboration use case | Doesn't cover non-team sharing scenarios |
**Recommended**: **Project Pool** - strikes a balance between clarity and consistency with existing terminology.
### Implementation Scope
Renaming would require changes to:
- Database tables: `resource_pools` → `project_pools`
- API routes: `/v3/pools` → `/v3/project_pools`
- Schema classes and field names throughout the codebase
- All documentation and help text
- Migration script to preserve existing data
### Benefits
- ✅ **Improved discoverability**: Users can easily find the project sharing feature
- ✅ **Better onboarding**: New users understand the purpose without confusion
- ✅ **Clearer API**: API endpoints and schemas more self-documenting
### Implementation Considerations
- **Breaking change**: Requires API version bump or backward compatibility layer
- **Data migration**: Existing resource pools must be preserved during table rename
- **Documentation updates**: All references in docs, tutorials, and API specs need updating
- **UI changes**: Frontend labels and navigation menus need to match new terminology
## Phase 8 — Per-User Project Namespace (Future)
**Goal**: Allow project names to be unique per user instead of globally unique, enabling better user experience.
### Current Problem
Although Phase 1 implements user isolation (users only see projects they created or have access to through resource pools), project names remain globally unique:
- ❌ **Naming conflicts**: Alice and Bob cannot both create a project named "My Project"
- ❌ **Unnecessary restrictions**: Even though projects are isolated, users must coordinate globally unique names
- ❌ **Poor user experience**: Users get confusing error messages when trying to use common names like "Test Project"
### Proposed Solution
Change project uniqueness from global to per-user:
**Current:**
```sql
UNIQUE(name) -- Project names must be globally unique
```
**Proposed:**
```sql
UNIQUE(user_id, name) -- Project names unique per user
```
### Benefits
- ✅ **Better UX**: Users can name projects whatever they want without worrying about global conflicts
- ✅ **Natural naming**: Common names like "Test Project" or "Demo" can coexist between users
- ✅ **No coordination needed**: Teams don't need to maintain a shared project naming registry
- ✅ **Consistent isolation**: Projects are isolated both in visibility AND naming
### Implementation Scope
Changes required:
- **Database schema**: Modify Project table unique constraint from `(name)` to `(user_id, name)`
- **Migration script**: Handle existing projects with conflicting names
- **API validation**: Update project creation validation logic
- **Frontend**: Remove global name uniqueness checks from UI
### Migration Considerations
**Handling existing name conflicts:**
If the database already has projects with the same name but different users:
- Option 1: Keep existing names, only enforce uniqueness for new projects
- Option 2: Append suffixes to duplicates (e.g., "My Project (alice)", "My Project (bob)")
- Option 3: Require admin resolution for conflicts before enabling new constraint
**Recommended**: Option 1 (grandfather existing projects) for minimal disruption.
### Dependencies
- **Phase 1 (User isolation)**: Must be completed first
- Database migration required to modify unique constraint
## Phase 9 — User Self-Registration (Future)
**Goal**: Allow users to register their own accounts without requiring manual admin creation.
### Current State
Currently, user accounts can only be created by administrators or through direct database operations:
- ❌ **Admin burden**: Every new user requires manual account creation
- ❌ **Poor scalability**: Not suitable for public deployments or large organizations
- ❌ **Friction**: Users cannot immediately start using the system
### Proposed Features
**Self-Registration Flow:**
1. User provides email, username, and password
2. System validates input and creates account
3. Optional email verification to confirm email address
4. Account created with default role (typically "User" role)
5. User can immediately log in and start creating projects
**Email Verification (Optional):**
- Send verification email with confirmation link/code
- Verify email address before granting full access
- Prevent spam account creation
- Require SMTP server configuration
### Implementation Components
1. **New API endpoint**: `POST /v3/access/register` (public, no authentication required)
2. **Email service**: Integration with SMTP server for sending emails
3. **Configuration**: SMTP settings (host, port, credentials, encryption)
4. **Rate limiting**: Prevent abuse of self-registration
5. **Captcha integration**: Optional bot protection
### Configuration
```yaml
Server:
email:
enabled: true
smtp_host: smtp.example.com
smtp_port: 587
smtp_username: noreply@example.com
smtp_password: secret
use_tls: true
registration:
require_email_verification: true
default_role: "User"
allow_public_registration: true
```
### Security Considerations
- ✅ **Rate limiting**: Prevent spam account creation
- ✅ **Email verification**: Confirm email ownership
- ✅ **Default permissions**: New users get limited default role
- ✅ **Admin approval** (optional): Require admin approval before account activation
- ❌ **Superadmin creation**: Never allow self-registration as superadmin
### Dependencies
- **Phase 10 (Email service)**: SMTP integration required for email verification
## Phase 10 — Email Service Integration (Future)
**Goal**: Implement email sending capability for notifications, verification, and alerts.
### Use Cases
1. **User registration**: Email verification links/codes
2. **Password reset**: Secure password reset emails
3. **System alerts**: Error notifications, system updates
4. **Project sharing**: Notify users when projects are shared via resource pools
5. **Usage reports**: Periodic usage summaries or quota alerts
### Proposed Implementation
**Email Service Architecture:**
- Abstract email service interface
- Support multiple email providers (SMTP, SendGrid, AWS SES, etc.)
- Email templates with Jinja2 for customization
- Async email sending to avoid blocking API responses
- Email queue for retry logic on failures
**Email Templates:**
- Registration verification
- Password reset
- Project shared notification
- System alerts
- Usage reports
**API Endpoints:**
```python
# Configuration (admin only)
POST /v3/access/config/email
GET /v3/access/config/email
PUT /v3/access/config/email
# Test email (admin only)
POST /v3/access/config/email/test
# Password reset (public)
POST /v3/access/users/password/reset/request
POST /v3/access/users/password/reset/confirm
# Email verification (public)
POST /v3/access/users/verify/email
POST /v3/access/users/verify/confirm
```
### Database Schema
New table for email tracking:
```sql
CREATE TABLE email_verification_tokens (
token_id UUID PRIMARY KEY,
user_id UUID REFERENCES users(user_id) ON DELETE CASCADE,
token VARCHAR(255), # Verification code
purpose VARCHAR(50), # 'registration', 'password_reset', etc.
expires_at DATETIME,
created_at DATETIME,
used BOOLEAN DEFAULT FALSE
);
```
### Configuration
```yaml
Server:
email:
enabled: true
provider: "smtp" # or "sendgrid", "aws_ses", etc.
from_address: "noreply@example.com"
from_name: "GNS3 Server"
reply_to: "support@example.com"
smtp:
host: smtp.example.com
port: 587
username: noreply@example.com
password: encrypted_password
use_tls: true
templates_dir: /etc/gns3/email_templates
```
### Security Considerations
- ✅ **Encrypted credentials**: SMTP passwords stored encrypted in database
- ✅ **Token expiration**: Verification tokens expire after configurable time
- ✅ **Rate limiting**: Prevent email spamming
- ✅ **Async sending**: Don't block API responses on email operations
- ✅ **Retry logic**: Handle temporary email service failures
- ✅ **Privacy**: Don't expose user information in error messages
### Dependencies
- **Phase 9 (Self-registration)**: User self-registration requires email verification
- Encryption utilities for storing SMTP credentials securely
@@ -0,0 +1,318 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This documentation is organized by AI with reference to actual code. AI can make mistakes — please verify against the source code when in doubt.
# Skills Editor API
## Overview
A management API that allows the Web UI to browse, edit, save, and contribute skill files (prompts, fault injection, device skills, packet analysis protocols) back to the upstream GNS3-Skills repository via Pull Requests.
Today, skills are read-only from the server's perspective — the only management endpoint is `POST /copilot/reload/skills` for hot-reloading. This API adds full CRUD operations on the local skills repository plus Git commit/push/PR workflows.
## Architecture
```mermaid
graph TD
subgraph "Web UI"
UI[Skills Editor Page]
end
subgraph "GNS3 Server API"
API[skills_editor.py<br/>/copilot/skills/*]
FM[SkillsFileManager]
SM[SkillsManager]
end
subgraph "Local Git Repo"
INJ[injection/*.yaml]
DEV[device/*.yaml]
PA[packet_analysis/*.yaml]
PRM[prompts/*.md]
CFG[config/*.txt]
end
subgraph "Remote"
GH[GitHub API<br/>Pull Requests]
REPO[gns3/gns3-skills]
end
UI -->|CRUD + PR| API
API --> FM
FM -->|file read/write| INJ
FM -->|file read/write| DEV
FM -->|file read/write| PA
FM -->|file read/write| PRM
FM -->|file read/write| CFG
FM -->|git commit/push| REPO
FM -->|create PR| GH
SM -->|hot reload| INJ
SM -->|hot reload| DEV
SM -->|hot reload| PA
SM -->|hot reload| PRM
```
## Business Process
### Edit and Contribute Flow
```mermaid
sequenceDiagram
participant UI as Web UI
participant API as Skills Editor API
participant FM as SkillsFileManager
participant Git as Local Git Repo
participant GH as GitHub
UI->>API: GET /copilot/skills
API-->>UI: List categories + file counts
UI->>API: GET /copilot/skills/injection
API-->>UI: List YAML files
UI->>API: GET /copilot/skills/injection/ospf_issues
API->>FM: read_file("injection", "ospf_issues")
FM-->>API: YAML content
API-->>UI: File content
UI->>API: PUT /copilot/skills/injection/ospf_issues<br/>{content: "..."}
API->>FM: write_file("injection", "ospf_issues", content)
FM->>Git: Write file to disk
FM-->>API: Success
API-->>UI: Updated
UI->>API: POST /copilot/skills/commit<br/>{message: "fix: update OSPF fault"}
API->>FM: commit_changes(message, files)
FM->>Git: git add + git commit
FM-->>API: Commit hash
API-->>UI: Committed
UI->>API: POST /copilot/skills/pull-request<br/>{title, body, branch}
API->>FM: create_pull_request(...)
FM->>Git: git push origin <branch>
FM->>GH: POST /repos/{owner}/{repo}/pulls
GH-->>FM: PR URL
FM-->>API: PR created
API-->>UI: PR URL
UI->>API: POST /copilot/skills/reload
API->>FM: Hot reload all registries
API-->>UI: Reloaded
```
## Valid Categories
| Category | Directory | File Extension | Content |
|----------|-----------|---------------|---------|
| `prompts` | `prompts/` | `.md` | System prompts (teaching_assistant, lab_automation_assistant, etc.) |
| `injection` | `injection/` | `.yaml` | Fault injection skill definitions (OSPF, BGP, VLAN, etc.) |
| `device` | `device/` | `.yaml` | Device-specific command knowledge |
| `packet_analysis` | `packet_analysis/` | `.yaml` | Protocol definitions for tshark-based analysis |
| `config` | `config/` | `.txt` | Security and configuration files (forbidden_commands, etc.) |
## API Endpoints
All endpoints require **superadmin** authentication. Prefix: `/v3/copilot/skills`.
| Method | Path | Description |
|--------|------|-------------|
| GET | `/copilot/skills` | List all categories with file counts |
| GET | `/copilot/skills/{category}` | List files in a category |
| GET | `/copilot/skills/{category}/{filename}` | Read file content (without extension) |
| POST | `/copilot/skills/{category}` | Create a new skill file |
| PUT | `/copilot/skills/{category}/{filename}` | Update existing file content |
| DELETE | `/copilot/skills/{category}/{filename}` | Delete a skill file |
| GET | `/copilot/skills/status` | Git status (modified/untracked/deleted files) + repo info |
| POST | `/copilot/skills/commit` | Stage and commit changes |
| POST | `/copilot/skills/push` | Push a branch to remote |
| POST | `/copilot/skills/pull-request` | Create a Pull Request (direct or via fork) |
| POST | `/copilot/skills/reload` | Hot reload all skills into memory (replaces `/reload/skills`) |
| POST | `/copilot/skills/rollback/{commit_hash}` | Rollback repository to a specific commit |
### Response Examples
**GET /copilot/skills** — List categories
```json
{
"categories": [
{"category": "injection", "file_count": 39, "path": "injection/"},
{"category": "device", "file_count": 2, "path": "device/"},
{"category": "packet_analysis", "file_count": 8, "path": "packet_analysis/"},
{"category": "prompts", "file_count": 4, "path": "prompts/"},
{"category": "config", "file_count": 1, "path": "config/"}
],
"repository": {
"repo_url": "https://github.com/gns3/gns3-skills.git",
"branch": "main",
"current_version": "abc123def456...",
"is_dirty": false
}
}
```
**GET /copilot/skills/injection** — List files in category
```json
{
"category": "injection",
"files": [
{"filename": "ospf_issues", "extension": ".yaml", "size": 4521, "last_modified": "2026-05-10T08:30:00Z"},
{"filename": "bgp_issues", "extension": ".yaml", "size": 3820, "last_modified": "2026-05-09T14:00:00Z"}
]
}
```
**GET /copilot/skills/injection/ospf_issues** — Read file content
```json
{
"category": "injection",
"filename": "ospf_issues",
"extension": ".yaml",
"content": "name: OSPF Fault Injection\n...\n",
"size": 4521,
"last_modified": "2026-05-10T08:30:00Z"
}
```
**PUT /copilot/skills/injection/ospf_issues** — Update file
```json
{
"content": "name: OSPF Fault Injection\n..."
}
```
Response:
```json
{
"category": "injection",
"filename": "ospf_issues",
"size": 4600,
"last_modified": "2026-05-12T10:00:00Z",
"status": "modified"
}
```
**POST /copilot/skills/commit** — Commit changes
Request:
```json
{
"message": "fix: update OSPF hello/dead interval fault descriptions",
"files": ["injection/ospf_issues.yaml"]
}
```
Response:
```json
{
"success": true,
"commit_hash": "def456abc789...",
"message": "fix: update OSPF hello/dead interval fault descriptions",
"files_committed": 1
}
```
**POST /copilot/skills/pull-request** — Create PR
Request:
```json
{
"title": "Fix OSPF fault injection descriptions",
"body": "Updated OSPF hello/dead interval fault descriptions for clarity.",
"branch": "fix/ospf-descriptions",
"target_branch": "main",
"fork_url": "https://github.com/user/GNS3-Skills.git"
}
```
Response:
```json
{
"success": true,
"pr_url": "https://github.com/gns3/gns3-skills/pull/42",
"pr_number": 42,
"branch": "fix/ospf-descriptions"
}
```
**GET /copilot/skills/status** — Git status
```json
{
"current_version": "abc123def456...",
"branch": "main",
"is_dirty": true,
"modified": ["injection/ospf_issues.yaml"],
"untracked": [],
"deleted": [],
"staged": [],
"available_versions": [
{"hash": "abc123def456", "message": "Add MPLS fault scenarios", "author": "dev", "date": "2026-05-10T08:00:00Z"}
]
}
```
## Implementation Plan
### New Files
| File | Purpose |
|------|---------|
| `gns3server/agent/gns3_copilot/skills/file_manager.py` | `SkillsFileManager` class — file CRUD, git commit/push, GitHub PR API |
| `gns3server/api/routes/controller/skills_editor.py` | FastAPI router with all endpoints above |
### Modified Files
| File | Change |
|------|--------|
| `gns3server/agent/gns3_copilot/skills/manager.py` | Add `get_file_manager()` method returning a `SkillsFileManager` |
| `gns3server/api/routes/controller/__init__.py` | Register `skills_editor` router under `/copilot/skills` prefix |
| `gns3server/api/routes/controller/copilot.py` | Deprecate `/reload/skills` in favor of `/skills/reload` |
### SkillsFileManager Key Methods
| Method | Returns |
|--------|---------|
| `list_categories()` | `list[{category, file_count, path}]` |
| `list_files(category)` | `list[{filename, size, last_modified}]` |
| `read_file(category, filename)` | File content as string |
| `write_file(category, filename, content)` | Write (create or update) |
| `delete_file(category, filename)` | Delete file |
| `get_git_status()` | Modified/untracked/deleted file lists |
| `commit_changes(message, files)` | git add + commit |
| `push_to_remote(branch)` | git push |
| `create_pull_request(title, body, branch, target, fork_url)` | Push + GitHub PR API |
## Security
- **Authentication**: All endpoints require superadmin (`current_user.is_superadmin` check)
- **Path traversal prevention**: Category validated against whitelist; filename sanitized (no `/`, `..`, or absolute paths)
- **File extension enforcement**: `.yaml` for injection/device/packet_analysis, `.md` for prompts, `.txt` for config
- **File size limit**: Reject files > 1MB
- **YAML validation**: Validate with `yaml.safe_load` before saving
- **GitHub token**: Required for PR creation, stored in GNS3 server config
### PR Creation Modes
1. **Direct push**: Push to a new branch on the main repo, create PR via GitHub API
2. **Fork**: Push to user's fork, create PR against upstream
The `fork_url` parameter selects the mode. When omitted, the API pushes to the same repository and creates a PR directly.
## Related Documentation
- [External Skills Repository](../implemented/skills-repository.md)
- [Fault Injection](../implemented/fault-injection.md)
- [Chat API](../implemented/chat-api.md)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,307 @@
# User Node Limit Roadmap
## Overview
Implement a user-level node startup limit feature for GNS3 server to prevent single users from consuming excessive system resources. This feature is **disabled by default** and can be enabled through configuration files, supporting a three-tier configuration priority system.
## Problem Statement
Currently, GNS3 server has no mechanism to limit the number of nodes a user can start across all their projects. This can lead to:
- **Resource exhaustion**: A single user can consume all available system resources
- **Unfair usage**: Some users may prevent others from using the system
- **System instability**: Too many running nodes can degrade overall performance
- **Cost issues**: In cloud environments, this can lead to unexpected costs
## Solution Design
### Core Principles
1. **Default to no limits**: System maintains backward compatibility by defaulting to unrestricted usage
2. **Configuration-driven**: All limits can be controlled through configuration files
3. **Multi-tier priority**: User-specific > User group-specific > Global configuration
4. **Intelligent filtering**: Only count nodes that actually consume resources
5. **Clear error messages**: Users receive actionable feedback when limits are reached
### Technical Architecture
#### 1. Database Layer Extension
**Files**: `gns3server/db/models/users.py`
Add `max_nodes` field to both `User` and `UserGroup` models:
```python
# In User model
max_nodes = Column(Integer, nullable=True) # NULL = no limit
# In UserGroup model
max_nodes = Column(Integer, nullable=True) # NULL = no limit
```
#### 2. Configuration System Extension
**File**: `gns3server/schemas/config.py`
Add node limit configuration to `ControllerSettings`:
```python
class NodeLimitSettings(BaseModel):
enabled: bool = False # Feature toggle (default disabled)
default_max_nodes: int = 5 # Default limit when enabled
excluded_node_types: List[str] = Field(default_factory=lambda: ["ethernet_switch", "ethernet_hub", "cloud", "nat"])
```
#### 3. Core Service Implementation
**New File**: `gns3server/services/node_limit_service.py`
Implement the `NodeLimitService` class with key methods:
```python
class NodeLimitService:
async def get_user_active_node_count(self, username: str, excluded_types: List[str]) -> int:
"""Count user's active nodes across all projects"""
async def get_user_node_limit(self, user: User) -> Optional[int]:
"""Get user's node limit with priority logic"""
async def check_user_node_limit(self, user: User, project: Project) -> Tuple[bool, str]:
"""Check if user can start more nodes"""
```
#### 4. API Integration
**File**: `gns3server/api/routes/controller/nodes.py`
Add limit checking to node startup endpoint:
```python
@router.post("/{node_id}/start")
async def start_node(
node: Node = Depends(dep_node),
current_user: User = Depends(get_current_active_user),
node_limit_service: NodeLimitService = Depends(get_node_limit_service),
):
# Node limit check
can_start, error_msg = await node_limit_service.check_user_node_limit(current_user, node.project)
if not can_start:
raise HTTPException(status_code=403, detail=error_msg)
# Original startup logic
await node.start()
```
### Node Counting Logic
#### What Counts Toward the Limit
- **Status**: Only nodes in `started` or `suspended` state
- **Ownership**: Only projects where `project.created_by == current_user.username`
- **Node types**: All node types except those explicitly excluded
#### What's Excluded from the Limit
- **Always-running nodes**: Ethernet switches, hubs (nodes where `is_always_running()` returns true)
- **Infrastructure nodes**: Cloud nodes and NAT nodes
- **Stopped nodes**: Nodes in `stopped` state
- **Other users' projects**: Nodes in projects created by other users
#### Configuration Priority
```
User-specific limit (highest priority)
↓ not set
User group limit
↓ not set
Global configuration (if enabled)
↓ disabled
No limit (default)
```
### Configuration Examples
#### Scenario 1: Default No Limits (System Default)
```ini
[Controller]
node_limits_enabled = false
```
**Result**: All users have no node limits
#### Scenario 2: Enable Global Limits
```ini
[Controller]
node_limits_enabled = true
node_limits_default_max_nodes = 5
node_limits_excluded_types = ethernet_switch,ethernet_hub,cloud,nat
```
**Result**: All users limited to 5 active nodes (excluding infrastructure nodes)
#### Scenario 3: User-Specific Limits
Configuration file: `node_limits_enabled = false`
Database:
- User A: `max_nodes = 10` (limited to 10 nodes)
- User B: `max_nodes = NULL` (no limit)
- Other users: no limit
#### Scenario 4: User Group Limits
Configuration file: `node_limits_enabled = false`
Database:
- "Users" group: `max_nodes = 5`
- "Premium Users" group: `max_nodes = 20`
- "Administrators" group: `max_nodes = NULL`
**Result**: Members inherit limits from their groups
## Implementation Files
| File Path | Type | Description |
|-----------|------|-------------|
| `gns3server/db/models/users.py` | Modify | Add `max_nodes` field to User and UserGroup |
| `gns3server/db_migrations/versions/xxx_add_node_limits.py` | New | Database migration script |
| `gns3server/schemas/config.py` | Modify | Add NodeLimitSettings configuration class |
| `gns3server/schemas/controller/users.py` | Modify | Add `max_nodes` to API schemas |
| `gns3server/services/node_limit_service.py` | New | Core node limit service |
| `gns3server/api/routes/controller/nodes.py` | Modify | Add limit check to node startup |
| `gns3server/api/routes/controller/users.py` | Modify | Add user limit configuration API |
| `gns3server/api/routes/controller/groups.py` | Modify | Add group limit configuration API |
## Implementation Steps
### Phase 1: Database Layer
1. Add `max_nodes` field to `User` and `UserGroup` models
2. Create database migration file
3. Test database migration and rollback
### Phase 2: Configuration System
1. Add `NodeLimitSettings` to configuration schema
2. Update configuration file loading logic
3. Test configuration parsing and validation
### Phase 3: Core Service
1. Implement `NodeLimitService` class
2. Implement node counting logic
3. Implement limit checking logic
4. Add unit tests for service methods
### Phase 4: API Integration
1. Modify node startup endpoint to add limit check
2. Add user limit configuration endpoints
3. Add group limit configuration endpoints
4. Add user node usage statistics endpoint
### Phase 5: Testing
1. Unit tests for all core functions
2. Integration tests for API endpoints
3. End-to-end tests for complete workflows
4. Performance tests for node counting operations
## Testing Strategy
### Functional Tests
- [ ] Default state verification (no limits)
- [ ] Global limit enablement
- [ ] User-specific limits
- [ ] User group limits
- [ ] Configuration priority verification
### Boundary Tests
- [ ] Exactly at limit (can start last node)
- [ ] One over limit (startup rejected)
- [ ] Stop node then restart (should work)
- [ ] Special node type exclusion
### Integration Tests
- [ ] Multi-user concurrent startups
- [ ] Node state transitions
- [ ] Dynamic configuration changes
- [ ] Project ownership filtering
### Performance Tests
- [ ] Node counting performance with many projects
- [ ] Concurrent startup request handling
- [ ] Memory usage monitoring
## Error Messages
### User-Friendly Error Response
When a user hits their node limit:
```json
{
"detail": "节点启动限制:您当前有 5 个活跃节点,限制为 5 个。请停止一些节点后再试,或联系管理员调整限制。"
}
```
Alternative formats:
- Show current usage vs limit
- Provide action suggestions
- Include contact information for administrators
## Migration Path
### For Existing Systems
1. **Database migration**: Add new nullable fields (safe, no data loss)
2. **Configuration update**: Add new optional settings (backward compatible)
3. **API changes**: Add new optional dependency injection (no breaking changes)
4. **Behavior**: No changes to existing functionality when disabled
### Rollback Plan
If issues occur:
1. Set `node_limits_enabled = false` in configuration
2. Service automatically disables limit checking
3. System returns to pre-feature behavior
## Benefits
1. **Resource Management**: Prevent resource exhaustion
2. **Fair Usage**: Ensure equitable resource distribution
3. **Cost Control**: Manage cloud resource costs
4. **System Stability**: Maintain performance under load
5. **Flexibility**: Support different usage patterns and tiers
6. **Backward Compatible**: No impact on existing deployments
## Future Enhancements
- Per-project limits (in addition to global user limits)
- Time-based limits (different limits for different times)
- Burst limits (temporary allowance for peak usage)
- Usage quotas with reset periods (daily/weekly/monthly)
- Monitoring and alerting for limit approaching
- Administrative override capabilities
- Usage history and analytics
## Documentation Updates
- [ ] Update API documentation with new endpoints
- [ ] Add configuration guide to admin documentation
- [ ] Update user guide with limit information
- [ ] Add troubleshooting section for limit issues
- [ ] Provide migration guide for existing deployments
## Status
**Current Status**: Design Phase
**Next Steps**:
1. Review and approve this roadmap
2. Begin Phase 1 implementation (Database Layer)
3. Create detailed technical specification
4. Set up development and testing environment
---
**Document Version**: 1.0
**Last Updated**: 2026-05-27
**Author**: GNS3 Development Team
@@ -0,0 +1,60 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This document is a roadmap/planning document. The described features have not been implemented yet.
# User Preferences API — Roadmap
## Problem
Currently, user-specific preferences (UI theme, language, AI Copilot settings, workspace layout, etc.) can only be stored in browser `localStorage`. This has several drawbacks:
1. **localStorage clearing** — clearing browser data or switching devices loses all settings
2. **No cross-device sync** — users must reconfigure preferences on each device
3. **No API access** — CLI tools and third-party clients cannot read/write preferences
4. **Fragile persistence** — localStorage can be cleared by browser maintenance or incognito mode
## Proposed API
| Method | Path | Description |
|--------|------|-------------|
| `GET` | `/v3/access/users/me/preferences` | Get all preferences for current user |
| `PUT` | `/v3/access/users/me/preferences` | Merge preferences (top-level merge, not replace) |
| `DELETE` | `/v3/access/users/me/preferences` | Clear all preferences |
### Storage
A `preferences` JSON column on the existing `users` table:
- Type: `JSON`, non-nullable, default `'{}'`
- No schema enforcement — clients can store arbitrary key-value pairs
- Examples: `{"theme": "dark", "language": "zh-CN", "copilot_default_mode": "teaching_assistant"}`
### Implementation Plan
1. Add `preferences` JSON column to `User` ORM model
2. Create Alembic migration
3. Add `UserPreferencesUpdate` Pydantic schema with `extra="allow"`
4. Add `get_user_preferences()` and `update_user_preferences()` to `UsersRepository`
5. Add three endpoints to `users.py` router: `GET/PUT/DELETE /me/preferences`
### Related Files
| File | Role |
|------|------|
| `gns3server/db/models/user.py` | User ORM model |
| `gns3server/db/repositories/users.py` | UsersRepository with database operations |
| `gns3server/api/routes/controller/users.py` | User API router |
| `gns3server/schemas/` | Pydantic schemas |
| `gns3server/db/versions/` | Alembic migrations |
## Status
- [ ] Add `preferences` JSON column to User ORM model
- [ ] Create Alembic migration
- [ ] Add `UserPreferencesUpdate` schema
- [ ] Add repository methods
- [ ] Add API endpoints to users.py router
@@ -0,0 +1,372 @@
<!--
SPDX-License-Identifier: CC-BY-SA-4.0
See LICENSE file for licensing information.
-->
> This document is a roadmap/planning document. The described features have not been implemented yet.
# Web Wireshark Docker Image Size Optimization — Roadmap
## Problem
The `gns3/web-wireshark` Docker image currently occupies **~2GB** of disk space, which impacts:
- Initial pull/download time for users
- Storage requirements on Docker Hub
- Deployment flexibility in resource-constrained environments
### Current Size Breakdown
Based on `docker history gns3/web-wireshark:latest`:
| Component | Size | Percentage |
|-----------|------|------------|
| `debian:trixie` base image | 120 MB | 6% |
| xpra + dependencies | 65.1 MB | 3.3% |
| Wireshark + GUI stack (Qt, GTK, X11) | 1.82 GB | 91% |
| **Total** | **~2 GB** | **100%** |
### Detailed File System Analysis
Analysis of container file system reveals significant cleanup opportunities:
| Directory | Size | Cleanup Potential |
|-----------|------|-------------------|
| `/usr/lib` | 1.3 GB | ~50MB (static libraries) |
| `/usr/share/locale` | 151 MB | **~145MB** (192 locales → 1) |
| `/usr/share/ibus` | 130 MB | **~130MB** (input framework) |
| `/usr/share/doc` | 76 MB | **~76MB** (documentation) |
| `/usr/share/backgrounds` | 37 MB | **~37MB** (desktop backgrounds) |
| `/usr/share/man` | 27 MB | **~27MB** (man pages) |
| `/usr/share/icons` | 16 MB | ~5MB (keep essential) |
| Development packages | ~50 MB | **~50MB** (21 `-dev` packages) |
| Static libraries (`*.a`, `*.la`) | 16 MB | **~16MB** |
| Sounds/help/perl | ~20 MB | **~20MB** |
| **Total Cleanable** | **~570 MB** | |
**Key Findings**:
- 192 locale languages installed (only need en_US)
- ibus input framework installed (not needed in headless container)
- 21 development packages with headers/headers
- 161 static library files (`.a`, `.la`)
- Complete documentation and man pages
- Desktop environment components (backgrounds, sounds)
## Proposed Optimizations
### Phase 1: Safe Optimizations (Estimated: -300~400MB)
Low-risk changes that maintain full compatibility.
#### 1. Use Slim Base Image (-50MB)
```dockerfile
FROM debian:trixie-slim # Instead of debian:trixie
```
**Impact**: Reduces base from 120MB to ~70MB
**Risk**: Low - slim variant contains all essential runtime libraries
**Testing Required**: Verify xpra and Wireshark launch without errors
#### 2. Install Without Recommended Packages (-150~200MB)
```dockerfile
RUN apt-get install -y --no-install-recommends \
wireshark-common \
wireshark \
xpra=6.4.3* \
xpra-x11 \
xvfb \
curl \
x11-utils
```
**Impact**: Prevents installation of non-essential recommended packages
**Risk**: Low - only excludes recommended packages, not required dependencies
**Testing Required**: Full functionality test (capture, analysis, WebSocket)
#### 3. Cleanup Unnecessary Files (-400~500MB)
```dockerfile
RUN apt-get install -y --no-install-recommends \
wireshark-common wireshark xpra=6.4.3* xpra-x11 xvfb curl x11-utils \
# Remove documentation and man pages
&& rm -rf /var/lib/apt/lists/* \
&& rm -rf /usr/share/doc/* /usr/share/man/* /usr/share/help/* \
# Remove unnecessary locales (keep only en_US)
&& rm -rf /usr/share/locale/* \
&& localedef -i en_US -f UTF-8 en_US.UTF-8 \
# Remove desktop environment components
&& rm -rf /usr/share/backgrounds/* /usr/share/sounds/* \
# Remove static libraries
&& find /usr/lib -name '*.a' -delete \
&& find /usr/lib -name '*.la' -delete \
# Remove unnecessary packages
&& apt-get purge -y -y \
ibus ibus-data ibus-gtk* python3-ibus-1.0 \
gnome-backgrounds \
&& apt-get autoremove -y \
&& apt-get clean
```
**Impact**: Removes documentation, locales, desktop components, input framework
**Risk**: Low - all removed components are unnecessary in headless container
**Testing Required**: Verify Wireshark GUI renders correctly without icons/themes
### Phase 2: Experimental (Requires Testing, -200~500MB)
Higher-risk optimizations that need extensive validation.
#### 4. Alpine Linux Alternative (-500MB~1GB)
```dockerfile
FROM alpine:3.19
RUN apk add --no-cache wireshark xpra xvfb curl ...
```
**Impact**: Could reduce image to ~500MB-1GB
**Risk**: **High** - Wireshark and xpra have complex Qt/GTK dependencies
**Challenges**:
- Wireshark Qt dependencies may not be available in Alpine repos
- xpra package availability and compatibility
- X11 library differences
- May require building dependencies from source
**Testing Required**:
- [ ] Verify Wireshark package availability in Alpine
- [ ] Test xpra compilation/installation on Alpine
- [ ] Validate all GUI libraries work correctly
- [ ] Full integration testing
**Recommendation**: Do not pursue unless Phase 1 insufficient
## Compression Feasibility Analysis
### Question: Can we reduce image size through compression?
**Short Answer**: **Not recommended** - limited benefit with performance trade-offs
### Current Compression Status
Docker images already use compression:
| Format | Size | Compression Rate | Use Case |
|--------|------|------------------|----------|
| Runtime size | 2.0 GB | - | Container running |
| docker save (raw) | 1.9 GB | 5% | Docker internal compression |
| docker save + gzip | 718 MB | **64%** | Standard transfer |
| docker save + xz | 563 MB | **72%** | Maximum compression |
| docker save + zstd | ~600 MB | **70%** | Fast compression |
### Binary Compression Analysis
#### File Already Stripped
All binaries already have debug symbols removed:
```bash
wireshark: ELF 64-bit... stripped
python3.13: ELF 64-bit... stripped
libc.so.6: ELF 64-bit... stripped
```
**No further stripping possible**
#### UPX Executable Compression (Limited Benefit)
Test results compressing major executables:
| Binary | Original | UPX Compressed | Savings | Startup Impact |
|--------|----------|----------------|---------|----------------|
| wireshark (11MB) | 11.0 MB | 4.2 MB | 62% | +0.3s |
| Xvfb (2.1MB) | 2.1 MB | 0.9 MB | 57% | +0.1s |
| python3.13 (6.6MB) | 6.6 MB | 2.8 MB | 58% | +0.2s |
| **Total** | **19.7 MB** | **7.9 MB** | **60%** | **+0.6s** |
**Overall Impact**: Only ~20MB savings (1%) with 0.6s startup penalty
### Why Compression Has Limited Benefit
1. **Small Executable Footprint**: Binaries are only 74MB (3.7% of image)
2. **Libraries Are Data Files**: `/usr/lib` contains mostly data, not code
3. **Already Compressed**: Docker storage drivers compress layers automatically
4. **Resource Files Dominate**: Fonts, icons, themes don't compress well
### Compression Trade-offs
| Method | Potential Savings | Performance Impact | Complexity | Risk |
|--------|-------------------|-------------------|------------|------|
| **File cleanup** | 400-500MB (20-25%) | None | Low | Low |
| UPX compression | 50-100MB (2.5-5%) | +0.6s startup | Medium | Medium |
| Layer squashing | 10-50MB (0.5-2.5%) | None | Low | Low |
| Transfer compression | 1.4GB (70%) | None (transfer only) | None | None |
### Recommendation
**Do not pursue binary compression** because:
- ✅ File cleanup is **4-10x more effective**
- ✅ No performance penalty
- ✅ Simpler build process
- ✅ Better compatibility
**For transfer/storage optimization**, use standard tools:
```bash
# For archiving (use zstd for best speed/ratio)
docker save gns3/web-wireshark:latest | \
zstd -19 -o web-wireshark.tar.zst
# For maximum compression (slow)
docker save gns3/web-wireshark:latest | \
xz -9 -T 0 > web-wireshark.tar.xz
```
## Implementation Plan
### Step 1: Create Optimized Dockerfile
Create `gns3server/agent/web_wireshark/docker/Dockerfile.optimized` with Phase 1 changes.
### Step 2: Local Testing
```bash
# Build optimized image
cd gns3server/agent/web_wireshark/docker
docker build -f Dockerfile.optimized -t gns3/web-wireshark:optimized .
# Verify size reduction
docker images | grep web-wireshark
# Test Wireshark functionality
docker run --rm gns3/web-wireshark:optimized wireshark --version
# Test xpra functionality
docker run --rm gns3/web-wireshark:optimized xpra --version
```
### Step 3: Integration Testing
```bash
# Test with actual GNS3 server
pip install . && gns3server-web-wireshark-setup
# Start a test session
python3 gns3server/agent/web_wireshark/manage_wireshark.py \
--verbose start \
--project-id "test-optimized" \
--link-id "test-link-1" \
--jwt-token "test-token" \
--image "gns3/web-wireshark:optimized"
# Verify WebSocket connectivity and packet capture
```
### Step 4: Production Rollout
1. Tag optimized image: `gns3/web-wireshark:v1.6-optimized`
2. Deploy to staging environment
3. Monitor for 1 week with real workloads
4. If stable, promote to `latest` tag
5. Keep old image available for rollback
## Testing Checklist
Before marking as complete:
- [ ] Wireshark launches without errors
- [ ] xpra HTML5 client connects successfully
- [ ] Packet capture works end-to-end
- [ ] Packet analysis and filtering functional
- [ ] WebSocket proxy integration works
- [ ] Multi-session handling tested (3+ simultaneous captures)
- [ ] Image size measured and documented
- [ ] Tested on Docker 20.10, 24.x, 29.x
- [ ] Startup time not negatively impacted
- [ ] Memory/CPU usage unchanged
- [ ] All existing tests pass
## Expected Results
### Phase 1: Safe Optimizations (Recommended)
| Metric | Current | Target | Improvement |
|--------|---------|--------|-------------|
| Image Size | 2GB | ~1.5GB | **-25% (500MB)** |
| Pull Time | 3-5 min | 2-3 min | **-40%** |
| Startup Time | 5-6s | 5-6s | No change |
| Functionality | Full | Full | No regression |
| Compatibility | All | All | No change |
### Phase 2: Experimental (If Needed)
| Metric | Current | Target | Improvement |
|--------|---------|--------|-------------|
| Image Size | 2GB | ~1GB | **-50% (1GB)** |
| Pull Time | 3-5 min | 1-2 min | **-60%** |
| Startup Time | 5-6s | 5-7s | Slight increase |
| Functionality | Full | Full | Risk of regressions |
| Compatibility | All | Alpine only | Significant testing required |
### Compression Comparison (Not Recommended)
| Method | Size | Savings | Trade-offs |
|--------|------|---------|------------|
| **File cleanup** | ~1.5GB | 500MB | None |
| UPX compression | ~1.9GB | 100MB | +0.6s startup, compatibility risk |
| Transfer compression | 600MB | 1.4GB | Transfer only, no runtime benefit |
## Related Files
| File | Current State | Changes Needed |
|------|---------------|----------------|
| `gns3server/agent/web_wireshark/docker/Dockerfile` | Current 2GB image | Create optimized variant |
| `gns3server/agent/web_wireshark/setup_wireshark_image.py` | Pulls/builds current image | Support optimized image option |
| `gns3server/schemas/config.py` | WebWiresharkSettings | Add image variant config |
| `gns3server/agent/web_wireshark/WEB_WIRESHARK.md` | Documents current image | Update with optimization notes |
## Status
### Phase 1: Safe Optimizations
- [ ] Create `Dockerfile.optimized` with slim base + --no-install-recommends + cleanup
- [ ] Local build and size verification
- [ ] Functional testing (Wireshark, xpra, WebSocket)
- [ ] Integration testing with GNS3 server
- [ ] Document actual size reduction achieved
- [ ] Deploy to staging for 1-week observation
- [ ] Promote to production if stable
### Phase 2: Experimental (Only if Phase 1 insufficient)
- [ ] Research Alpine Wireshark/xpra package availability
- [ ] Prototype Alpine build if feasible
- [ ] Extensive compatibility testing
- [ ] Performance benchmarking vs. Phase 1
## Notes
- All size estimates based on actual `docker history` and container filesystem analysis
- Phase 1 optimizations are conservative and should be safe
- Compression techniques (UPX, layer squashing) provide minimal benefit (1-5%)
- File cleanup is **10x more effective** than compression (25% vs 2.5%)
- Phase 2 requires significant research and testing effort
- Backward compatibility must be maintained during transition
- Consider maintaining both `latest` and `optimized` tags during migration period
### Key Findings from Analysis
1. **Major space waste**: 570MB of cleanable files (28.5% of image)
- Locale files: 151MB → 6MB (keep only en_US)
- ibus input framework: 130MB → 0MB (not needed in headless container)
- Documentation: 76MB → 0MB (docs, man pages, help)
- Desktop components: 37MB → 0MB (backgrounds, sounds)
- Development packages: 50MB → 0MB (21 -dev packages)
2. **Compression not viable**:
- Binaries already stripped (no debug symbols)
- UPX only saves 20MB (1%) with 0.6s startup penalty
- Docker already compresses layers internally
- Resource files (fonts, themes) don't compress well
3. **Best approach**: Clean up unnecessary files rather than compress
- 25x better compression ratio than UPX
- No performance impact
- Simpler build process
- Better compatibility
+22 -18
View File
@@ -2,27 +2,31 @@
<!DOCTYPE html>
<html>
<head>
<title>GNS3 controller API - ReDoc</title>
<!-- needed for adaptive design -->
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css">
<link rel="shortcut icon" href="https://fastapi.tiangolo.com/img/favicon.png">
<!--
ReDoc doesn't change outer page styles
-->
<style>
body {
margin: 0;
padding: 0;
}
</style>
<title>GNS3 controller API - Swagger UI</title>
</head>
<body>
<redoc spec-url="openapi.json"></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"> </script>
<div id="swagger-ui">
</div>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
<!-- `SwaggerUIBundle` is now available on the page -->
<script>
const ui = SwaggerUIBundle({
url: 'openapi.json',
"dom_id": "#swagger-ui",
"layout": "BaseLayout",
"deepLinking": true,
"showExtensions": true,
"showCommonExtensions": true,
oauth2RedirectUrl: window.location.origin + '/docs/oauth2-redirect',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
})
</script>
</body>
</html>
+1 -1
View File
@@ -1 +1 @@
{"openapi": "3.0.2", "info": {"title": "GNS3 controller API", "description": "This page describes the public controller API for GNS3", "version": "v2"}, "paths": {"/": {"get": {"tags": ["controller"], "summary": "Root", "operationId": "root__get", "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {}}}}}}}, "/debug": {"get": {"tags": ["controller"], "summary": "Debug", "operationId": "debug_debug_get", "responses": {"200": {"description": "Successful Response", "content": {"text/html": {"schema": {"type": "string"}}}}}, "deprecated": true}}, "/static/web-ui/{file_path}": {"get": {"tags": ["controller"], "summary": "Web Ui", "description": "Web user interface", "operationId": "web_ui_static_web_ui__file_path__get", "parameters": [{"required": true, "schema": {"title": "File Path", "type": "string"}, "name": "file_path", "in": "path"}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/v2/shutdown": {"post": {"tags": ["Controller"], "summary": "Shutdown", "description": "Shutdown the local server", "operationId": "shutdown_v2_shutdown_post", "responses": {"204": {"description": "Successful Response"}, "403": {"description": "Server shutdown not allowed", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}}}}, "/v2/version": {"get": {"tags": ["Controller"], "summary": "Version", "description": "Return the server version number.", "operationId": "version_v2_version_get", "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Version"}}}}}}, "post": {"tags": ["Controller"], "summary": "Check Version", "description": "Check if version is the same as the server.\n\n:param request:\n:param response:\n:return:", "operationId": "check_version_v2_version_post", "requestBody": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/Version"}}}, "required": true}, "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Version"}}}}, "409": {"description": "Invalid version", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/v2/iou_license": {"get": {"tags": ["Controller"], "summary": "Get Iou License", "description": "Return the IOU license settings", "operationId": "get_iou_license_v2_iou_license_get", "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/IOULicense"}}}}}}, "put": {"tags": ["Controller"], "summary": "Update Iou License", "description": "Update the IOU license settings.", "operationId": "update_iou_license_v2_iou_license_put", "requestBody": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/IOULicense"}}}, "required": true}, "responses": {"201": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/IOULicense"}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/v2/statistics": {"get": {"tags": ["Controller"], "summary": "Statistics", "description": "Return server statistics.", "operationId": "statistics_v2_statistics_get", "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {}}}}}}}, "/v2/appliances": {"get": {"tags": ["Appliances"], "summary": "Get Appliances", "description": "Return all appliances known by the controller.", "operationId": "get_appliances_v2_appliances_get", "parameters": [{"required": false, "schema": {"title": "Update", "type": "boolean"}, "name": "update", "in": "query"}, {"required": false, "schema": {"title": "Symbol Theme", "type": "string", "default": "Classic"}, "name": "symbol_theme", "in": "query"}], "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}}}, "/v2/computes": {"get": {"tags": ["Computes"], "summary": "Get Computes", "description": "Return all computes known by the controller.", "operationId": "get_computes_v2_computes_get", "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"title": "Response Get Computes V2 Computes Get", "type": "array", "items": {"$ref": "#/components/schemas/Compute"}}}}}}}, "post": {"tags": ["Computes"], "summary": "Create ComputeLine truncated
{"openapi": "3.1.0", "info": {"title": "GNS3 controller API", "description": "This page describes the public controller API for GNS3", "version": "3.1.0.dev8"}, "servers": [{"url": "/"}], "paths": {"/v3/version": {"get": {"tags": ["Controller"], "summary": "Get Version", "description": "Return the server version number.", "operationId": "controller_get_version", "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Version"}}}}}}, "post": {"tags": ["Controller"], "summary": "Check Version", "description": "Check if version is the same as the server.", "operationId": "controller_check_version", "requestBody": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/Version"}}}, "required": true}, "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Version"}}}}, "409": {"description": "Invalid version", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}, "422": {"description": "Request validation error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}}}}, "/v3/reload": {"post": {"tags": ["Controller"], "summary": "Reload", "description": "Reload the controller", "operationId": "controller_reload", "responses": {"204": {"description": "Successful Response"}, "422": {"description": "Request validation error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}, "401": {"description": "Authentication is required or the credentials are invalid", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}, "403": {"description": "Not enough privileges to perform this operation", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}}, "security": [{"OAuth2PasswordBearer": []}]}}, "/v3/shutdown": {"post": {"tags": ["Controller"], "summary": "Shutdown", "description": "Shutdown the server", "operationId": "controller_shutdown", "responses": {"204": {"description": "Successful Response"}, "403": {"description": "Not enough privileges to perform this operation", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}, "422": {"description": "Request validation error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}, "401": {"description": "Authentication is required or the credentials are invalid", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}}, "security": [{"OAuth2PasswordBearer": []}]}}, "/v3/iou_license": {"get": {"tags": ["Controller"], "summary": "Get Iou License", "description": "Return the IOU license settings", "operationId": "controller_get_iou_license", "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/IOULicense"}}}}, "422": {"description": "Request validation error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}, "401": {"description": "Authentication is required or the credentials are invalid", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}, "403": {"description": "Not enough privileges to perform this operation", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}}, "security": [{"OAuth2PasswordBearer": []}]}, "put": {"tags": ["Controller"], "summary": "Update Iou License", "description": "Update the IOU license settings.", "operationId": "controller_update_iou_license", "requestBody": {"content": {"application/json": {"schema": {"$ref": "#/components/schemas/IOULicense"}}}, "required": true}, "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/IOULicense"}}}}, "422": {"description": "Request validation error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}, "401": {"description": "Authentication is required or the credentials are invalid", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}, "403": {"description": "Not enough privileges to perform this operation", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}}, "security": [{"OAuth2PasswordBearer": []}]}}, "/v3/statistics": {"get": {"tags": ["Controller"], "summary": "Statistics", "description": "Return server statistics including compute resources, projects, and nodes.", "operationId": "controller_statistics", "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ServerStatistics"}}}}, "422": {"description": "Request validation error", "content": {"application/jLine truncated
+21 -21
View File
@@ -2,30 +2,30 @@
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3.30.0/swagger-ui.css">
<title>GNS3 controller API - ReDoc</title>
<!-- needed for adaptive design -->
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
<link rel="shortcut icon" href="https://fastapi.tiangolo.com/img/favicon.png">
<title>GNS3 controller API - Swagger UI</title>
<!--
ReDoc doesn't change outer page styles
-->
<style>
body {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="swagger-ui">
</div>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3.30.0/swagger-ui-bundle.js"></script>
<!-- `SwaggerUIBundle` is now available on the page -->
<script>
const ui = SwaggerUIBundle({
url: 'openapi.json',
oauth2RedirectUrl: window.location.origin + '/docs/oauth2-redirect',
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
layout: "BaseLayout",
deepLinking: true,
showExtensions: true,
showCommonExtensions: true
})
</script>
<noscript>
ReDoc requires Javascript to function. Please enable it to browse the documentation.
</noscript>
<redoc spec-url="openapi.json"></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js"> </script>
</body>
</html>
+1 -1
View File
@@ -14,4 +14,4 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .version import __version__
from .version import __version__ as __version__
+107
View File
@@ -0,0 +1,107 @@
#
# Copyright (C) 2025 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Agent module with optional AI Copilot and MCP support.
This module provides the AI Copilot and MCP (Model Context Protocol)
functionality as optional features. If the respective dependencies are
not installed, the affected features will be disabled but will not
prevent the server from starting.
Installation:
pip install gns3-server[ai-features] # Install all AI features
"""
import logging
import threading
# Feature flag: AI Copilot is available
AI_COPILOT_AVAILABLE = False
# Try to import AI Copilot components
try:
from .gns3_copilot.project_agent_manager import ProjectAgentManager, get_project_agent_manager
AI_COPILOT_AVAILABLE = True
# Start skills repository initialization in background.
# Clones/pulls GNS3-Skills during server startup.
# Git network timeouts are configured in SkillsManager (_GIT_TIMEOUT_ENV).
# The daemon thread auto-terminates when the process exits.
from gns3server.agent.gns3_copilot.skills.registry import _ensure_skills_manager
threading.Thread(target=_ensure_skills_manager, daemon=True).start()
except ImportError as e:
# AI dependencies not installed, disable AI Copilot feature
logging.warning(
f"AI Copilot dependencies not installed: {e}. "
"AI features will be disabled. "
"Install with: pip install gns3-server[ai-features]"
)
AI_COPILOT_AVAILABLE = False
# Provide stub functions that raise helpful errors
async def get_project_agent_manager() -> "ProjectAgentManager":
"""
Get the global ProjectAgentManager singleton instance.
Raises:
RuntimeError: If AI Copilot dependencies are not installed
"""
raise RuntimeError(
"AI Copilot is not available. Install AI dependencies with: pip install gns3-server[ai-features]"
)
class ProjectAgentManager: # type: ignore[no-redef]
"""
Stub class for ProjectAgentManager when AI dependencies are not installed.
"""
def __init__(self):
raise RuntimeError(
"AI Copilot is not available. Install AI dependencies with: pip install gns3-server[ai-features]"
)
# Feature flag: MCP (Model Context Protocol) is available
MCP_AVAILABLE = False
# Try to import MCP dependencies
try:
# Use importlib so the top-level SDK name "mcp" is not bound in this
# namespace — it would shadow the gns3server.agent.mcp subpackage.
import importlib
importlib.import_module("mcp.server.mcpserver")
MCP_AVAILABLE = True
except ImportError:
# MCP dependencies not installed, disable MCP feature
logging.warning(
"MCP dependencies not installed. "
"MCP features will be disabled. "
"Install with: pip install gns3-server[ai-features]"
)
MCP_AVAILABLE = False
__all__ = [
"AI_COPILOT_AVAILABLE",
"MCP_AVAILABLE",
"ProjectAgentManager",
"get_project_agent_manager",
]
+44
View File
@@ -0,0 +1,44 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#
# GNS3-Copilot - AI-powered Network Lab Assistant for GNS3
#
# This file is part of GNS3-Copilot project.
#
# GNS3-Copilot is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# GNS3-Copilot is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNS3-Copilot. If not, see <https://www.gnu.org/licenses/>.
#
# Copyright (C) 2025 Yue Guobin (岳国宾)
# Author: Yue Guobin (岳国宾)
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
GNS3-Copilot - AI-powered network automation assistant for GNS3.
This package provides a command-line interface for launching the GNS3-Copilot
Streamlit application with support for Streamlit parameter passthrough.
"""
# Dynamic version management
__version__: str = "unknown"
try:
from importlib.metadata import version
__version__ = str(version("gns3-copilot"))
except Exception:
__version__ = "unknown"
__author__ = "Yue Guobin (岳国宾)"
__description__ = "AI-powered network automation assistant for GNS3"
__url__ = "https://github.com/yueguobin/gns3-copilot"
@@ -0,0 +1,50 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#
# GNS3-Copilot - AI-powered Network Lab Assistant for GNS3
#
# This file is part of GNS3-Copilot project.
#
# GNS3-Copilot is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# GNS3-Copilot is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNS3-Copilot. If not, see <https://www.gnu.org/licenses/>.
#
# Copyright (C) 2025 Yue Guobin (岳国宾)
# Author: Yue Guobin (岳国宾)
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
GNS3-Copilot Agent Package
This package contains the main GNS3-Copilot agent implementation for
network automation tasks using LangGraph workflow orchestration.
"""
from .gns3_copilot import agent_builder
# Dynamic version management
try:
from importlib.metadata import version
__version__ = version("gns3-copilot")
except Exception:
__version__ = "unknown"
__author__ = "Yue Guobin (岳国宾)"
__description__ = "AI-powered network automation assistant for GNS3"
__url__ = "https://github.com/yueguobin/gns3-copilot"
__all__ = [
"agent_builder",
]
@@ -0,0 +1,607 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#
# GNS3-Copilot - AI-powered Network Lab Assistant for GNS3
#
# Copyright (C) 2025 Yue Guobin (岳国宾)
# Author: Yue Guobin (岳国宾)
#
# This file is part of GNS3-Copilot project.
#
# GNS3-Copilot is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# GNS3-Copilot is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNS3-Copilot. If not, see <https://www.gnu.org/licenses/>.
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
Context Manager for GNS3-Copilot - Using LangGraph pre_model_hook
This module provides context window management using LangGraph's recommended
pre_model_hook approach with accurate token counting:
Key Features:
- Accurate token counting using tiktoken (95%+ accuracy)
- Template variable injection for topology info
- Context strategy ratios (conservative/balanced/aggressive)
- Message trimming using LangChain's native trim_messages
- Tool definition token estimation
- Detailed token breakdown logging
Requirements:
- tiktoken>=0.8.0 (required)
"""
import json
import logging
import os
import warnings
from pathlib import Path
from typing import Any, Callable
# Configure tiktoken cache directory (must be set before importing tiktoken)
_cache_dir = Path(__file__).parent.parent / "cache" / "tiktoken"
_cache_dir.mkdir(parents=True, exist_ok=True)
os.environ["TIKTOKEN_CACHE_DIR"] = str(_cache_dir)
import tiktoken
from langchain_core.messages import BaseMessage, SystemMessage, trim_messages
logger = logging.getLogger(__name__)
# ============================================================================
# Token Counter Setup
# ============================================================================
# Initialize tiktoken encoding (required dependency)
import time
logger.debug("Initializing tiktoken encoding (cl100k_base)...")
logger.debug(f"Cache directory: {_cache_dir}")
logger.debug(
"This may take a moment on first run (downloading ~1.6MB encoding file from openaipublic.blob.core.windows.net)"
)
start_time = time.time()
_tiktoken_encoding = tiktoken.get_encoding("cl100k_base")
elapsed = time.time() - start_time
logger.debug(f"✓ tiktoken encoding loaded successfully (took {elapsed:.2f}s)")
# ============================================================================
# Constants
# ============================================================================
# Context strategy ratios (percentage of context limit to use for input)
CONTEXT_STRATEGY_RATIOS = {
"conservative": 0.60,
"balanced": 0.75,
"aggressive": 0.85,
}
DEFAULT_CONTEXT_STRATEGY = "balanced"
# Token unit conversion
TOKENS_PER_K = 1000
# ============================================================================
# Token Counting Functions
# ============================================================================
def count_tokens(text: str) -> int:
"""
Count tokens in text using tiktoken.
Uses cl100k_base encoding (GPT-4) which provides accurate counting
for most modern LLMs (OpenAI, Anthropic, DeepSeek, etc.).
Args:
text: Text to count tokens for
Returns:
Exact token count (not estimated)
"""
if not text:
return 0
return len(_tiktoken_encoding.encode(text))
def estimate_tool_tokens(tools: list[Any]) -> int:
"""
Estimate token consumption for tool definitions.
Tool definitions are serialized as JSON and sent to LLM with each request.
This function estimates their token cost.
Args:
tools: List of LangChain tool objects
Returns:
Estimated token count for all tool definitions
"""
if not tools:
return 0
total_tokens = 0
for tool in tools:
try:
# Build tool schema in OpenAI format
tool_schema: dict[str, Any] = {
"type": "function",
"function": {
"name": tool.name,
"description": tool.description,
},
}
# Add parameters schema if available
if hasattr(tool, "args_schema") and tool.args_schema:
try:
# Try Pydantic v2 method (model_json_schema)
tool_schema["function"]["parameters"] = tool.args_schema.model_json_schema()
except AttributeError:
# Fallback to Pydantic v1 method (schema)
try:
tool_schema["function"]["parameters"] = tool.args_schema.schema()
except Exception:
# Both methods failed, use empty schema
tool_name = getattr(tool, "name", "unknown")
logger.debug(
"Failed to get schema for tool %s, using empty parameters",
tool_name,
)
tool_schema["function"]["parameters"] = {}
except Exception as e:
# model_json_schema() raised an exception
tool_name = getattr(tool, "name", "unknown")
logger.debug(
"model_json_schema() failed for tool %s: %s, trying v1 fallback",
tool_name,
e,
)
try:
tool_schema["function"]["parameters"] = tool.args_schema.schema()
except Exception:
tool_schema["function"]["parameters"] = {}
# Serialize to JSON and count tokens
schema_str = json.dumps(tool_schema, ensure_ascii=False)
tokens = count_tokens(schema_str)
total_tokens += tokens
except Exception as e:
tool_name = getattr(tool, "name", "unknown")
logger.debug(
"Failed to estimate tokens for tool %s: %s",
tool_name,
e,
)
# Rough fallback: 1000 tokens per tool
total_tokens += 1000
return total_tokens
def _count_tokens_for_message(message: BaseMessage) -> int:
"""
Token counter for LangChain's trim_messages.
This function is called by trim_messages for each message.
Args:
message: A single message (HumanMessage, AIMessage, SystemMessage,
etc.)
Returns:
Estimated token count for the message
"""
content = ""
if hasattr(message, "content") and message.content:
content = str(message.content)
return count_tokens(content)
# ============================================================================
# Pre-Model Hook Factory
# ============================================================================
def create_pre_model_hook(
system_prompt: str,
get_topology_func: Callable[[dict], Any] | None = None,
get_llm_config_func: Callable[[], dict[str, Any] | None] | None = None,
get_tools_func: Callable[[], list[Any]] | None = None,
) -> Callable[[dict], dict]:
"""
Create a pre_model_hook function for LangGraph agent.
This hook will be automatically called before each LLM invocation,
handling topology injection, tool token estimation, and message
trimming.
IMPORTANT USAGE REQUIREMENTS:
This hook MUST be passed via model.invoke() config, NOT used as
a Node return value.
CORRECT Usage:
model.invoke(messages,
config={"configurable": {"pre_model_hook": pre_hook}})
INCORRECT Usage:
# ❌ Don't use as Node return value
def my_node(state):
return pre_hook(state) # Wrong!
# ❌ Don't use with StateGraph if state uses add_messages reducer
class State(TypedDict):
messages: Annotated[list, add_messages] # Incompatible!
COMPATIBILITY:
- Works with: model.invoke(config={"configurable":
{"pre_model_hook": ...}})
- Does NOT work as: StateGraph Node return value
- Does NOT work with: Annotated[list, add_messages] state reducers
The hook returns a complete message list that overwrites the model
input, which is correct for invoke() but wrong for state updates with
add_messages.
Args:
system_prompt: System prompt template (must contain
{{topology_info}} placeholder)
get_topology_func: Function to extract topology from state
get_llm_config_func: Function to get LLM config from context
get_tools_func: Optional function to get tools list for token
estimation
Returns:
A pre_model_hook function for use with model.invoke(config=...)
Thread Safety:
Thread-safe if get_llm_config_func uses request-scoped context
(e.g., contextvars)
Performance Notes:
- SystemMessage is reconstructed on each LLM call (intentional
design)
- Overhead: ~1-2ms per call (negligible compared to LLM latency)
- Trade-off: Simplicity > micro-optimization
- In ReAct loops with multiple LLM calls, topology is re-injected
each time
- This is acceptable for GNS3-Copilot's usage patterns (low
concurrency, short conversations)
"""
def pre_model_hook(state: dict) -> dict:
"""
LangGraph pre_model_hook - called before each LLM invocation.
This function is NOT a StateGraph Node. It is a preprocessing hook
that modifies the input to the LLM, not the agent state.
Usage Context:
Called automatically by LangChain when passed via:
model.invoke(messages,
config={"configurable":
{"pre_model_hook": this}})
Args:
state: Current agent state containing messages and topology_info
Returns:
dict with 'messages' key containing prepared and trimmed messages
Note: This return value is used by LangChain to replace the model
input, NOT to update the agent state.
Raises:
ValueError: If context_limit is missing or invalid
"""
logger.debug(
"pre_model_hook invoked: messages=%d",
len(state.get("messages", [])),
)
messages = state.get("messages", [])
if not messages:
logger.debug("No messages in state, returning empty list")
return {"messages": []}
# Get LLM config
llm_config = get_llm_config_func() if get_llm_config_func else None
if not llm_config:
logger.error("LLM config not found. context_limit is required.")
raise ValueError("LLM config not found. context_limit is required.")
if "context_limit" not in llm_config:
logger.error(
"context_limit not found in LLM config. This is a required field. Please configure context_limit."
)
raise ValueError("context_limit is required in LLM config")
limit = llm_config["context_limit"]
if not isinstance(limit, int) or limit <= 0:
logger.error("Invalid context_limit: %s", limit)
raise ValueError(f"Invalid context_limit: {limit}")
context_limit_k = limit
strategy = llm_config.get("context_strategy", DEFAULT_CONTEXT_STRATEGY)
if strategy not in CONTEXT_STRATEGY_RATIOS:
logger.warning(
"Invalid context_strategy '%s', using '%s'",
strategy,
DEFAULT_CONTEXT_STRATEGY,
)
strategy = DEFAULT_CONTEXT_STRATEGY
# Step 1: Estimate tool tokens
tool_tokens = 0
if get_tools_func:
try:
tools = get_tools_func()
tool_tokens = estimate_tool_tokens(tools)
logger.debug(
"Tool definitions estimated at ~%d tokens (%d tools)",
tool_tokens,
len(tools),
)
except Exception as e:
logger.warning("Failed to estimate tool tokens: %s", e)
# Step 2: Inject topology into system prompt
messages_with_system = _inject_topology_into_system(
messages=messages,
system_prompt=system_prompt,
state=state,
get_topology_func=get_topology_func,
)
# Step 3: Calculate token breakdown for logging and validation
system_message = messages_with_system[0]
system_tokens = _count_tokens_for_message(system_message)
# Calculate tokens for messages_with_system (including system)
messages_with_system_tokens = sum(_count_tokens_for_message(m) for m in messages_with_system)
# Calculate available budget
model_limit_tokens = context_limit_k * TOKENS_PER_K
strategy_ratio = CONTEXT_STRATEGY_RATIOS[strategy]
max_input_tokens = int(model_limit_tokens * strategy_ratio)
# Calculate max tokens for trim_messages
# Important: trim_messages counts ALL messages (including system),
# so we only subtract tool_tokens here, NOT system_tokens.
# Let trim_messages handle system.
max_tokens_for_trim = max_input_tokens - tool_tokens
# Validate budget and provide actionable warnings
if system_tokens + tool_tokens > max_input_tokens:
logger.error(
"System prompt (%d tokens) + tools (%d tokens) EXCEED input "
"budget (%d tokens). This will likely cause LLM call failures. "
"Recommendations: 1) Reduce system prompt length, 2) Reduce "
"number of tools, 3) Use a model with larger context window, "
"or 4) Switch to 'conservative' strategy.",
system_tokens,
tool_tokens,
max_input_tokens,
)
elif max_tokens_for_trim < system_tokens * 1.5:
# Less than 1.5x system tokens means very little room for history
logger.warning(
"System prompt (%d tokens) + tools (%d tokens) leave minimal "
"room for conversation history (%d tokens remaining). "
"Consider reducing system prompt length or number of tools.",
system_tokens,
tool_tokens,
max_tokens_for_trim - system_tokens,
)
# Debug log with clear terminology
logger.debug(
"Token breakdown: system=%d, all_messages=%d (system+history), "
"tools=%d, trim_budget=%d (limit=%dK, strategy=%s)",
system_tokens,
messages_with_system_tokens,
tool_tokens,
max_tokens_for_trim,
context_limit_k,
strategy,
)
# Step 4: Trim messages to fit
# Note: max_tokens_for_trim INCLUDES system message, trim_messages
# will handle it
try:
trimmed = trim_messages(
messages=messages_with_system,
max_tokens=max_tokens_for_trim,
strategy="last",
token_counter=_count_tokens_for_message,
include_system=True,
)
# Calculate final token counts
final_total = sum(_count_tokens_for_message(m) for m in trimmed)
usage_percent = (final_total + tool_tokens) / model_limit_tokens * 100
if len(trimmed) < len(messages_with_system):
logger.info(
"Messages trimmed: %d → %d msgs. Total: ~%d tokens + %d tools = %d / %dK (%.1f%%), strategy=%s",
len(messages_with_system),
len(trimmed),
final_total,
tool_tokens,
final_total + tool_tokens,
context_limit_k,
usage_percent,
strategy,
)
else:
logger.info(
"Context ready: %d msgs, ~%d tokens + %d tools = %d / %dK (%.1f%%), strategy=%s",
len(trimmed),
final_total,
tool_tokens,
final_total + tool_tokens,
context_limit_k,
usage_percent,
strategy,
)
return {"messages": trimmed}
except Exception as e:
logger.error("Failed to trim messages: %s", e)
logger.warning("Returning original messages due to trimming error")
return {"messages": messages_with_system}
return pre_model_hook
def _inject_topology_into_system(
messages: list,
system_prompt: str,
state: dict,
get_topology_func: Callable[[dict], Any] | None = None,
) -> list:
"""
Inject topology information into system prompt.
Args:
messages: Message list
system_prompt: System prompt template
state: Current state
get_topology_func: Optional function to extract topology
Returns:
Message list with system message prepended
"""
if "{{topology_info}}" not in system_prompt:
logger.warning("system_prompt missing {{topology_info}} placeholder")
return messages
topology_data = None
if get_topology_func:
try:
topology_data = get_topology_func(state)
except Exception as e:
logger.warning("Failed to get topology: %s", e)
if topology_data:
topology_str = str(topology_data)
formatted_prompt = system_prompt.replace("{{topology_info}}", f"\n\n## Current Topology\n{topology_str}")
logger.info(
"✓ Topology injected: %d chars, nodes: %s",
len(topology_str),
list(topology_data.get("nodes", {}).keys())[:5],
) # Show first 5 node names
logger.debug("Full topology data: %s", topology_str[:500]) # First 500 chars
else:
formatted_prompt = system_prompt.replace("{{topology_info}}", "(No topology information available)")
logger.warning("✗ Topology data is None, injecting placeholder")
# Filter out existing SystemMessage instances
non_system_messages = [m for m in messages if not isinstance(m, SystemMessage)]
filtered_count = len(messages) - len(non_system_messages)
if filtered_count > 0:
logger.debug("Filtered out %d existing SystemMessage(s)", filtered_count)
return [SystemMessage(content=formatted_prompt), *non_system_messages]
# ============================================================================
# Legacy Compatibility (Deprecated)
# ============================================================================
def prepare_context_messages(
state_messages: list[Any],
system_prompt: str,
topology_context: str | None = None,
model_name: str = "gpt-4o",
llm_config: dict[str, Any] | None = None,
tools: list[Any] | None = None,
) -> list[Any]:
"""
**DEPRECATED**: Use create_pre_model_hook() instead.
"""
warnings.warn(
"prepare_context_messages() is deprecated. Use create_pre_model_hook() instead.",
DeprecationWarning,
stacklevel=2,
)
if "{{topology_info}}" not in system_prompt:
formatted_prompt = system_prompt
elif topology_context:
formatted_prompt = system_prompt.replace("{{topology_info}}", f"\n\n## Current Topology\n{topology_context}")
else:
formatted_prompt = system_prompt.replace("{{topology_info}}", "(No topology information available)")
return [SystemMessage(content=formatted_prompt), *state_messages]
# ============================================================================
# Module Test
# ============================================================================
if __name__ == "__main__":
from langchain_core.messages import HumanMessage
print("=== Context Manager Module Test ===\n")
# Test token counting
print("Test 1: Token Counting")
print(" tiktoken encoding: cl100k_base")
test_text = "Hello world 你好世界"
tokens = count_tokens(test_text)
print(f" '{test_text}' → {tokens} tokens")
# Test hook creation
print("\nTest 2: Create pre_model_hook")
system_prompt = "You are GNS3 Copilot.\n\n{{topology_info}}"
def mock_get_topology(state):
return {"project_id": "test", "nodes": 5}
def mock_get_config():
return {"context_limit": 8, "context_strategy": "conservative"}
def mock_get_tools():
return [] # No tools for test
hook = create_pre_model_hook(
system_prompt=system_prompt,
get_topology_func=mock_get_topology,
get_llm_config_func=mock_get_config,
get_tools_func=mock_get_tools,
)
print("✓ pre_model_hook created successfully")
# Test invocation
print("\nTest 3: Invoke pre_model_hook")
test_state = {
"messages": [HumanMessage(f"Message {i}: {'x' * 50}") for i in range(5)],
"topology_info": {"project_id": "test123", "nodes": 3},
}
result = hook(test_state)
print(f"✓ Hook invoked: {len(result['messages'])} messages returned")
print("\n=== All Tests Passed ===")
Loaded 100 of 988 files, more files were not shown because too many files have changed in this diff. Show more