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
233 changed files with 85836 additions and 7204 deletions

No files matched your search

+2 -2
View File
@@ -25,8 +25,8 @@ var
sdist
develop-eggs
.installed.cfg
lib
lib64
/lib
/lib64
# Installer logs
pip-log.txt
+13 -13
View File
@@ -8,20 +8,20 @@
# Core AI and Automation Framework
# Note: aiosqlite is in core requirements.txt
langchain>=1.2.10
langchain-core>=1.2.16
langgraph>=1.0.9
langchain-core>=1.7.3
langgraph>=1.2.19
langgraph-checkpoint>=4.0.0
langgraph-checkpoint-sqlite>=3.0.3
langgraph-checkpoint-sqlite>=3.1.3
langgraph-checkpoint-postgres>=3.0.4
# Model Providers
langchain-openai>=1.1.10
langchain-anthropic>=1.3.4
langchain-google-genai>=4.2.1
langchain-aws>=1.8.1
langchain-ollama>=1.0.1
langchain-deepseek>=1.0.1
langchain-xai>=1.2.2
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
@@ -30,15 +30,15 @@ tiktoken>=0.14.0
langsmith>=0.14.7
# Network Automation
paramiko>=5.0.0 # install version >= 5.0.0 to address CVE-2026-44405
paramiko>=5.1.0 # install version >= 5.0.0 to address CVE-2026-44405
netmiko>=4.8.0
nornir>=3.5.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.1
python-dotenv>=1.2.4
# Authentication
PyJWT>=2.15.1
+6 -6
View File
@@ -1,10 +1,10 @@
pytest==9.1.1
pytest==9.2.0
pytest-timeout==2.4.0
pytest-asyncio==1.4.0
pytest-asyncio==1.4.1
httpx==0.28.1
httpx_ws==0.7.2 # upgrading leads to failures in tests
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.16.9
mypy==2.4.0
rust-just==1.58.0 # provides the `just` command runner, see justfile
ruff==0.17.3
mypy==2.4.1
rust-just==1.59.0 # provides the `just` command runner, see justfile
+1
View File
@@ -139,6 +139,7 @@ Proposed `image_type` discriminator on Docker templates plus a compute-side prof
- [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)
---
@@ -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.
@@ -142,8 +142,14 @@ direction, `loss gemodel 5 45 100` drops 10 %.
(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_SEED` (u64 allowed) — makes random draws reproducible
for tests. When omitted keep the current behaviour (kernel picks).
* 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)
+119 -46
View File
@@ -2,7 +2,7 @@
## 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 SSE (Server-Sent Events) transport.
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.
@@ -11,21 +11,24 @@ The MCP service exposes GNS3 project management operations as MCP tools that can
| Path | Method | Description |
|------|--------|-------------|
| `/v3/mcp/` | GET | MCP service metadata |
| `/v3/mcp/transport/sse` | GET | SSE stream (MCP connection) |
| `/v3/mcp/transport/messages/` | POST | JSON-RPC messages |
| `/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
The SSE endpoint supports two types of credentials, passed the same way.
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 don't support custom headers):
2. **Query parameter** (for clients that can't set headers, e.g. browser EventSource):
```
GET /v3/mcp/transport/sse?token=<jwt_or_api_key>
GET /v3/mcp/transport?token=<jwt_or_api_key>
```
### Option 1: JWT Token (24h expiry)
@@ -74,13 +77,18 @@ Both JWT tokens and API keys work for MCP and REST API endpoints interchangeably
When connecting with an API key:
```
SSE connect → Authorization: Bearer gns3_<uuid>_<secret>
POST initialize → Authorization: Bearer gns3_<uuid>_<secret>
↓
MCP auth wrapper extracts UUID → single DB query → 1 bcrypt (thread pool)
↓
Generates a fresh short-lived JWT → stored in ContextVar for the session
Generates a fresh 24h JWT → stored in ContextVar for the session
↓
All subsequent tool handler REST API calls use this JWT → zero extra bcrypt
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
@@ -94,7 +102,7 @@ All subsequent tool handler REST API calls use this JWT → zero extra bcrypt
## Available Tools
**76 tools** across 11 categories:
**80 tools** across 11 categories:
### Project (14)
@@ -127,7 +135,7 @@ All subsequent tool handler REST API calls use this JWT → zero extra bcrypt
| `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` | Get WebSocket console URL |
| `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 |
@@ -224,13 +232,27 @@ they require a vision-capable model to be genuinely useful. Revisit later.
| `server_version` | Get GNS3 server version |
| `server_statistics` | Get server statistics (computes, projects, nodes) |
### Device Config (3)
### Device Config & Skills (5)
| Tool | Description |
|------|-------------|
| `device_config_send` | Push config commands to devices via console (Nornir + Netmiko). Supports Jinja2 `template` + `vars` |
| `device_show_run` | Run read-only show commands on devices. Supports Jinja2 `template` + `vars` |
| `vpcs_config_set` | Configure VPCS devices (IP, gateway, etc.) |
| `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.
@@ -296,6 +318,35 @@ 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
@@ -341,8 +392,8 @@ sequenceDiagram
```bash
# Option A: Using API key (recommended — never expires)
claude mcp add --transport sse My_GNS3_Server \
http://localhost:3080/v3/mcp/transport/sse \
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)
@@ -351,14 +402,29 @@ TOKEN=$(curl -s -X POST http://localhost:3080/v3/access/users/authenticate \
-d '{"username": "admin", "password": "admin"}' | python3 -c \
"import sys,json; print(json.load(sys.stdin)['access_token'])")
claude mcp add --transport sse My_GNS3_Server \
http://localhost:3080/v3/mcp/transport/sse \
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 FastMCP's DNS rebinding protection to prevent attackers from
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
@@ -389,7 +455,7 @@ mcp_allowed_origins = http://127.0.0.1:*,http://localhost:*,http://192.168.1.3:*
### Protection Mechanism
When protection is enabled, the MCP server validates the `Host` header of
incoming SSE connection requests:
incoming MCP requests:
```python
# Verify the request's Host header matches allowed patterns
@@ -421,8 +487,8 @@ sequenceDiagram
participant Auth as Auth
participant GNS3 as GNS3 REST API
Note over Client: 1. Connect with API Key or JWT
Client->>MCP: GET /sse (Authorization: Bearer <key>)
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)
@@ -432,28 +498,44 @@ sequenceDiagram
Auth-->>MCP: Token valid
end
MCP-->>Client: event: endpoint /messages/?session_id=xxx
MCP-->>Client: initialize result + Mcp-Session-Id header
Note over Client: 2. Initialize & Call Tools
Client->>MCP: POST /messages/ (tools/call ...)
MCP->>GNS3: HTTP request (with JWT from step 1)
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: event: message (tool result)
MCP-->>Client: tool result (SSE or JSON response body)
```
## Internal Implementation
- **FastMCP** (Anthropic MCP SDK) is used for tool registration and SSE transport
- The SSE app is mounted as a Starlette sub-application under `/v3/mcp/transport`
- **Auth:** JWT validation via `auth_service`. API key (`gns3_<uuid>_<secret>`) extracts UUID for O(1) DB lookup, runs bcrypt in thread pool, returns a fresh JWT — subsequent calls use the JWT with zero extra bcrypt.
- **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`)
- 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`
### Console WebSocket
### Node Console Execution
The `node_console` tool returns a WebSocket URL for connecting to a node's console. The URL includes a short-lived **access ticket** (10 min) — a short random string (`gns3t_…`, 22 chars) minted server-side and bound to that node's console endpoints. `link_capture_download` uses the same kind of ticket bound to one exact resource path instead of embedding a Bearer JWT in the returned curl command. Tickets replaced the long JWTs previously embedded in these URLs/commands: LLM clients retyping them into shell commands reliably corrupted a ~200-char JWT, while a short ticket survives copying. Re-request the URL when the ticket expires (logging out also invalidates outstanding tickets). This endpoint is protocol-agnostic — it works for **telnet**, **ssh**, and **vnc** console types alike. The WebSocket simply proxies raw byte streams between the client and the compute node; protocol negotiation (e.g. SSH key exchange) happens on the compute side.
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.
The WebSocket URL is constructed using the server's `_server_url()`, which resolves the host as follows:
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 |
|:---|:---|
@@ -462,22 +544,13 @@ The WebSocket URL is constructed using the server's `_server_url()`, which resol
| `::` (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 returned WebSocket 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 in the URL without modification.
Use `websocat` to connect from the command line (use the `command` returned by `node_console` verbatim — never reconstruct the URL by hand):
```bash
# The host in the URL is automatically resolved to a reachable address
websocat ws://192.168.1.3:3080/v3/projects/{project_id}/nodes/{node_id}/console/ws?token=<console_ticket>
```
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` | FastMCP server, tool decorators, SSE transport, JWT auth wrapper |
| `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 |
+3 -3
View File
@@ -76,7 +76,7 @@ On the kernel datapath the 13 types ride three kernel objects on the anchor. The
| `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 |
| `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) |
@@ -96,7 +96,7 @@ The API surface of the 13 types — parameters, ranges and cross-filter rules, v
| `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 |
| `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 |
@@ -229,7 +229,7 @@ Choosing parameters: pick the target mean M and average burst length L (packets)
|---|---|
| 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.
**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]}`.
+1 -1
View File
@@ -122,7 +122,7 @@ if await asyncio.to_thread(bcrypt.checkpw, secret.encode(), db_key.key_hash.enco
**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 SSE session — zero extra bcrypt.
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:
+2 -2
View File
@@ -58,7 +58,7 @@ graph LR
**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_…`, minted per node by the `node_console` MCP tool, valid 10 min, bound to this node's console endpoints)
- 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**:
@@ -179,7 +179,7 @@ sequenceDiagram
1. **Authentication**:
- JWT token validation via `has_privilege_on_websocket("Node.Console")` dependency
- Token passed as query parameter: `?token={jwt}`, or a console ticket (`gns3t_…`) redeemable only on the node it was minted for
- 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`
@@ -101,22 +101,30 @@ sequenceDiagram
| Tool | teaching_assistant | lab_automation_assistant | troubleshooting_injection |
|---|---|---|---|
| `GNS3TemplateTool` get templates | ✓ | ✓ | |
| `GNS3CreateNodeTool` create nodes | ✓ | ✓ | |
| `GNS3LinkTool` create links | ✓ | ✓ | |
| `GNS3StartNodeTool` start nodes | ✓ | ✓ | |
| `GNS3UpdateNodeNameTool` rename | ✓ | ✓ | |
| `GNS3StopNodeTool` stop nodes | | ✓ | |
| `GNS3SuspendNodeTool` suspend nodes | | ✓ | |
| `ExecuteMultipleDeviceCommands` read-only commands | ✓ | ✓ | ✓ |
| `ExecuteMultipleDeviceConfigCommands` config commands | | ✓ | ✓ |
| `VPCSCommands` VPCS commands | | ✓ | |
| `PacketAnalysisTool` live packet analysis | ✓ | ✓ | |
| `PacketAnalysisSkillsTool` protocol knowledge | ✓ | ✓ | |
| `DeviceSkillsTool` device skills | ✓ | ✓ | |
| `GNS3PacketFilterTool` link filters | | | ✓ |
| `InjectionSkillsTool` fault injection skills | | | ✓ |
| `GNS3TopologyTool` topology info | | | ✓ |
| `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)`.
+12 -11
View File
@@ -285,7 +285,7 @@ Chat API uses Server-Sent Events (SSE) for streaming transmission.
"tool_call": {
"id": "call_123",
"type": "function",
"function": {"name": "execute_multiple_device_commands", "arguments": ""}
"function": {"name": "device_show_run", "arguments": ""}
},
"session_id": "xxx"
}
@@ -296,7 +296,7 @@ Chat API uses Server-Sent Events (SSE) for streaming transmission.
"tool_call": {
"id": "call_123",
"type": "function",
"function": {"name": "execute_multiple_device_commands", "arguments": "{\"device_names\": [\"R1\"], "}
"function": {"name": "device_show_run", "arguments": "{\"device_names\": [\"R1\"], "}
},
"session_id": "xxx"
}
@@ -307,7 +307,7 @@ Chat API uses Server-Sent Events (SSE) for streaming transmission.
"tool_call": {
"id": "call_123",
"type": "function",
"function": {"name": "execute_multiple_device_commands", "arguments": "{\"device_names\": [\"R1\"], \"commands\": [\"show ver\"]}"}
"function": {"name": "device_show_run", "arguments": "{\"device_names\": [\"R1\"], \"commands\": [\"show ver\"]}"}
},
"session_id": "xxx"
}
@@ -319,7 +319,7 @@ Chat API uses Server-Sent Events (SSE) for streaming transmission.
"id": "call_123",
"type": "function",
"function": {
"name": "execute_multiple_device_commands",
"name": "device_show_run",
"arguments": "{\"device_names\": [\"R1\"], \"commands\": [\"show ver\"]}",
"complete": true
}
@@ -330,7 +330,7 @@ Chat API uses Server-Sent Events (SSE) for streaming transmission.
// Tool starts execution (associated via tool_call_id)
{
"type": "tool_start",
"tool_name": "execute_multiple_device_commands",
"tool_name": "device_show_run",
"tool_call_id": "call_123",
"session_id": "xxx"
}
@@ -338,7 +338,7 @@ Chat API uses Server-Sent Events (SSE) for streaming transmission.
// Tool execution complete
{
"type": "tool_end",
"tool_name": "execute_multiple_device_commands",
"tool_name": "device_show_run",
"tool_output": "[\n {\n \"device_name\": \"R-1\",\n \"status\": \"success\",\n \"output\": \"Cisco IOS Software, \\n IOSv Software (X86_64_LINUX_IOSD-UNIVERSALK9-M), Version 15.2(1.90)\"\n },\n {\n \"device_name\": \"R-2\",\n \"status\": \"failed\",\n \"error\": \"Connection timeout\"\n }\n]",
"session_id": "xxx"
}
@@ -821,15 +821,16 @@ OpenAI-compatible message model.
3. First interaction without title → `title_generator_node`
4. Otherwise → `END`
- **recursion_limit_continue** (after `tool_node`): Routes to `llm_call` or `END` based on:
- **recursion_limit_continue** (after `tool_node`): Routes to `llm_call`, `budget_wrapup` or `END` based on:
1. Check abort flag → `END`
2. Remaining steps < 4 → `END` (prevent infinite loops)
2. Remaining steps < 4 → `budget_wrapup` (one final summary call, no tools)
3. Otherwise → `llm_call`
**State** (`MessagesState`):
- `messages`: Conversation messages (cumulative with `operator.add`)
- `llm_calls`: LLM invocation counter
- `remaining_steps`: Recursion depth tracker (initial: 20)
- `remaining_steps`: LangGraph managed value (`recursion_limit - step`); the limit is the per-mode default or `max_steps` from the LLM config. Passing it in inputs has no effect
- `budget_exhausted`: Set by `budget_wrapup`, reset at the start of every user turn
- `conversation_title`: Auto-generated title
- `topology_info`: GNS3 project topology data
- `session_id`: Session identifier (for abort tracking)
@@ -841,8 +842,8 @@ The agent supports two tool sets, selected by `copilot_mode` in the user's LLM c
| Mode | Tools | Description |
|------|-------|-------------|
| `teaching_assistant` (default) | GNS3Template, GNS3CreateNode, GNS3Link, GNS3StartNode, GNS3UpdateNodeName, ExecuteMultipleDeviceCommands, PacketCapture, DeviceSkills | Read-only diagnostic + node creation |
| `lab_automation_assistant` | All teaching_assistant tools + GNS3StopNode, GNS3SuspendNode, ExecuteMultipleDeviceConfigCommands, VPCSCommands | Full diagnostic + configuration tools |
| `teaching_assistant` (default) | GNS3Template, GNS3CreateNode, GNS3Link, GNS3StartNode, GNS3UpdateNodeName, device_show_run, PacketCapture, DeviceSkills | Read-only diagnostic + node creation |
| `lab_automation_assistant` | All teaching_assistant tools + node_stop, node_suspend, device_config_send, vpcs_config_set | Full diagnostic + configuration tools |
**Why Serialize in tool_node?**
@@ -79,8 +79,8 @@ flowchart TD
| Tool | File | Filter | Multi-line Expansion | Result Fields |
|------|------|--------|---------------------|---------------|
| `ExecuteMultipleDeviceCommands` | `display_tools_nornir.py` | Yes | No | `diagnostic_commands` |
| `ExecuteMultipleDeviceConfigCommands` | `config_tools_nornir.py` | Yes | Yes | `config_commands` |
| `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
@@ -143,8 +143,8 @@ The forbidden commands list is loaded from the external [GNS3-Skills](https://gi
| `reload_forbidden_commands()` | Directly load and cache commands from skills repository |
**Integration points:**
- `display_tools_nornir.py` — `_filter_forbidden_commands_from_device_configs()`
- `config_tools_nornir.py` — `_filter_forbidden_commands_from_device_configs()` + `_expand_multiline_commands()`
- `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)
@@ -158,7 +158,7 @@ In addition to the command filter, the AI agent is instructed via system prompt
## Multi-line Command Handling
Commands containing `\n` are automatically split before execution by `config_tools_nornir.py:_expand_multiline_commands()`.
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", "#"]`
@@ -27,7 +27,7 @@ graph TD
end
subgraph "gns3_copilot.py"
G[llm_call node] --> H[Get topology via GNS3TopologyTool]
G[llm_call node] --> H[Get topology via gns3_topology_reader]
H --> A
A --> I[model_with_tools.invoke]
end
@@ -58,7 +58,7 @@ graph TD
```mermaid
flowchart TD
A[llm_call node invoked] --> B[Get topology via GNS3TopologyTool]
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?}
@@ -133,7 +133,7 @@ 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 `GNS3TopologyTool._run(project_id)`
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
@@ -16,17 +16,17 @@ flowchart TB
end
subgraph "② Topology Analysis & Fault Selection"
D --> E["GNS3TopologyTool\nget topology info"]
E --> F["ExecuteMultipleDeviceCommands\nget device configs"]
F --> G["InjectionSkillsTool\nquery available fault types"]
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["ExecuteMultipleDeviceConfigCommands\ninject config changes"]
J --> L["GNS3PacketFilterTool\ninject link-layer faults"]
J --> K["device_config_send\ninject config changes"]
J --> L["link_update\ninject link-layer faults"]
end
subgraph "④ Result Confirmation"
@@ -40,11 +40,11 @@ flowchart TB
| Tool | Source File | Purpose | Available Modes |
|---|---|---|---|
| `InjectionSkillsTool` | `registry.py` (skills module) | Query protocol-level fault definitions (config change commands) | troubleshooting_injection |
| `GNS3PacketFilterTool` | `gns3_packet_filter.py` | Link-layer fault injection (delay, loss, corruption, BPF) | troubleshooting_injection |
| `ExecuteMultipleDeviceConfigCommands` | `config_tools_nornir.py` | Batch device config changes | troubleshooting_injection |
| `ExecuteMultipleDeviceCommands` | `display_tools_nornir.py` | Read device configurations (read-only) | troubleshooting_injection |
| `GNS3TopologyTool` | `gns3_client` | Get project topology information | troubleshooting_injection |
| `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
@@ -54,7 +54,7 @@ flowchart TB
**Prerequisite**: Project must be in `opened` status, otherwise returns 403.
## GNS3PacketFilterTool Link Filters
## link_update Link Filters
| Filter Type | Function | Parameters |
|---|---|---|
@@ -71,11 +71,11 @@ sequenceDiagram
participant U as User
participant API as POST /chat/inject
participant LLM as LLM Node
participant Topo as GNS3TopologyTool
participant DC as ExecuteMultipleDeviceCommands
participant CC as ExecuteMultipleDeviceConfigCommands
participant Skill as InjectionSkillsTool
participant Filter as GNS3PacketFilterTool
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
@@ -85,7 +85,7 @@ sequenceDiagram
DC-->>LLM: running configs
LLM->>Skill: list context=["ospf"]
Skill-->>LLM: matching fault types
LLM->>Skill: get device_type=injection_ospf
LLM->>Skill: get device_type=injection_ospf_issues
Skill-->>LLM: fault definition + injection commands
LLM->>CC: execute config injection
CC-->>LLM: injection result
@@ -97,8 +97,8 @@ sequenceDiagram
## 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 `InjectionSkillsTool`; no hardcoded fault scenarios
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** — `InjectionSkillsTool` requires a `context` parameter, returning only faults matching the topology protocols
6. **Context Filtering** — `injection_skill_get` requires a `context` parameter, returning only faults matching the topology protocols
@@ -26,13 +26,13 @@ graph TD
subgraph "Skills Repository"
IS[INJECTION_SKILLS_REGISTRY<br/>39 categories, 368 issues]
SK[injection_skills Tool]
SK[injection_skill_get Tool]
end
subgraph "Tools"
DC[execute_multiple_device_commands]
CC[execute_multiple_device_config_commands]
GK[GNS3TopologyTool]
DC[device_show_run]
CC[device_config_send]
GK[gns3_topology_reader]
end
TG -->|Get topology| GK
@@ -45,7 +45,7 @@ graph TD
## Injection Skills Tool
The `InjectionSkillsTool` (LangChain `BaseTool`) is the primary interface for querying available faults.
The `injection_skill_get` (LangChain `BaseTool`) is the primary interface for querying available faults.
### Listing Faults (with context filter)
@@ -71,10 +71,10 @@ Token-efficient usage pattern:
```json
// Step 1: List issue names only (~300 tokens)
{"device_type": "injection_ospf", "detail": "index"}
{"device_type": "injection_ospf_issues", "detail": "index"}
// Step 2: Get single issue detail (~500 tokens)
{"device_type": "injection_ospf", "issue": "ospf_hello_dead_mismatch"}
{"device_type": "injection_ospf_issues", "issue": "ospf_hello_dead_mismatch"}
```
### Parameters
@@ -83,7 +83,7 @@ Token-efficient usage pattern:
|-----------|----------|-------------|
| `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"` |
| `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 |
@@ -92,7 +92,7 @@ Token-efficient usage pattern:
```mermaid
sequenceDiagram
participant LLM
participant InjectionSkillsTool
participant injection_skill_get
participant TopologyTool
participant DeviceCommands
@@ -104,14 +104,14 @@ sequenceDiagram
Note over LLM: Analyze which protocols are in use
LLM->>InjectionSkillsTool: {"action": "list", "context": ["ospf", "vlan"]}
InjectionSkillsTool-->>LLM: Matching fault categories
LLM->>injection_skill_get: {"action": "list", "context": ["ospf", "vlan"]}
injection_skill_get-->>LLM: Matching fault categories
LLM->>InjectionSkillsTool: {"device_type": "injection_ospf", "detail": "index"}
InjectionSkillsTool-->>LLM: Issue names (token-efficient)
LLM->>injection_skill_get: {"device_type": "injection_ospf_issues", "detail": "index"}
injection_skill_get-->>LLM: Issue names (token-efficient)
LLM->>InjectionSkillsTool: {"device_type": "injection_ospf", "issue": "ospf_hello_dead_mismatch"}
InjectionSkillsTool-->>LLM: Full fault detail + config commands
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
@@ -225,6 +225,8 @@ For a complete list of LangChain-supported providers, see: https://python.langch
| `max_tokens` | integer | **⚠️ Reserved for future use, not currently implemented** |
| `context_strategy` | string | Context trimming strategy: "conservative" (60%), "balanced" (75%), "aggressive" (85%). Default: "balanced" |
| `copilot_mode` | string | GNS3-Copilot mode: "teaching_assistant" (diagnostics only, default) or "lab_automation_assistant" (full configuration access) |
| `max_steps` | integer | Step budget of one copilot turn, as the LangGraph recursion limit (1 LLM call + 1 tool run = 2 steps). Defaults: 25 teaching_assistant, 50 lab_automation_assistant, 100 troubleshooting_injection |
| `request_timeout` | number | LLM request timeout in seconds (openai/deepseek/anthropic/xai). Default 120. A silent connection fails fast instead of waiting for the SDK default of 600s |
| `is_default` | boolean | Set as default (default: false) |
**Important Notes:**
@@ -253,6 +255,8 @@ For a complete list of LangChain-supported providers, see: https://python.langch
| `context_strategy` | string (optional) | Context trimming strategy |
| `is_default` | boolean (optional) | Default flag |
| `copilot_mode` | string (optional) | GNS3-Copilot mode: "teaching_assistant" or "lab_automation_assistant" |
| `max_steps` | integer (optional) | Step budget of one copilot turn (LangGraph recursion limit). Leave empty for the per-mode default |
| `request_timeout` | number (optional) | LLM request timeout in seconds. Leave empty for the 120s default |
| `expected_version` | integer (optional) | **Optimistic locking version** |
**Note:** When using `expected_version`, the API will verify the version hasn't changed since you read the data. If it has, you'll receive a 409 Conflict error.
@@ -261,7 +265,7 @@ For a complete list of LangChain-supported providers, see: https://python.langch
- `max_tokens`: Reserved for future implementation. Currently not used by the system. The maximum output tokens are controlled automatically by the LLM provider based on the model and input size.
**Update Limitations:**
- `context_strategy` and `copilot_mode` can be set to new values but **cannot be cleared to null** via update. This is because the API filters out null values before processing.
- `context_strategy`, `copilot_mode` and `max_steps` can be set to new values but **cannot be cleared to null** via update. This is because the API filters out null values before processing.
### LLMModelConfigResponse
@@ -104,9 +104,9 @@ VPCS output often contains ANSI terminal codes. The `_strip_ansi_codes()` method
### VPCS Tool Usage
The VPCS driver is used by the `execute_vpcs_commands` tool:
The VPCS driver is used by the `vpcs_config_set` tool:
> File: `gns3server/agent/gns3_copilot/tools_v2/vpcs_tools_netmiko.py`
> File: `gns3server/agent/gns3_copilot/gns3_client/vpcs_commands.py`
**VPCS Connection Parameters:**
@@ -172,7 +172,7 @@ The VPCS built-in template includes `"tags": ["device_type:gns3_vpcs_telnet"]`,
**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 `config_tools_nornir.py` and `display_tools_nornir.py`
- ✅ 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:**
@@ -634,7 +634,7 @@ graph TD
### GNS3 Copilot Tool Usage
> Tools: `tools_v2/display_tools_nornir.py`, `tools_v2/config_tools_nornir.py`, `tools_v2/vpcs_tools_netmiko.py`
> 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.
@@ -657,17 +657,17 @@ gns3server/agent/gns3_copilot/
│ └── get_gns3_device_port.py # Device port extraction
│ └── get_device_ports_from_topology() # Extract ports + device_type from tags
├── tools_v2/
│ ├── display_tools_nornir.py # Multi-vendor display commands
│ ├── config_tools_nornir.py # Multi-vendor config commands
│ ├── 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_tools_netmiko.py # VPCS commands using Nornir + Netmiko
│ └── VPCSCommands # VPCS tool class
│ └── 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: `vpcs_tools_netmiko.py` - VPCS tool using Nornir + 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
@@ -752,7 +752,7 @@ _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 `vpcs_tools_netmiko.py`
- 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
@@ -12,11 +12,13 @@ See LICENSE file for licensing information.
GNS3-Copilot provides tools for managing the lifecycle of network devices and topology in GNS3 projects. These tools enable AI agents to create, connect, start, stop, suspend, and manage nodes as part of automated lab management workflows.
> **Tool source (single source of truth):** most copilot tools are no longer hand-written LangChain wrappers. They are adapted from the MCP server's tool registration by `tools_v2/mcp_bridge.py` — tool names, descriptions and argument schemas are identical to the MCP tools (`node_create`, `node_start`, `device_show_run`, ...). The bridge filters the MCP registration down to project-scoped tools (the copilot runs inside one open project; `project_*`, `compute_*`, `appliance_*`, `image_*` and server administration tools are excluded) and bridges the copilot's request JWT into the MCP context. Copilot-native tools remain only where they add value: `link_create` (port-name resolution), `wait_seconds`, `packet_analysis`, `packet_analysis_skills`, `gns3_topology_reader`.
## Available Tools
### GNS3TemplateTool 🆕
### template_list 🆕
**Tool Name:** `get_gns3_templates`
**Tool Name:** `template_list`
**Description:** Retrieves all available device templates from the GNS3 server, including template names, IDs, and types. Filters out built-in utility templates that are not useful for network device configuration.
@@ -70,13 +72,13 @@ The following built-in utility templates are excluded as they are not actual net
**Use Cases:**
- Discover available device types before creating nodes
- Get template_id for GNS3CreateNodeTool
- Get template_id for node_create
- Template inventory management
- Focus on network devices rather than utility templates
### GNS3CreateNodeTool 🆕
### node_create 🆕
**Tool Name:** `create_gns3_node`
**Tool Name:** `node_create`
**Description:** Creates multiple nodes in a GNS3 project using specified templates and coordinates.
@@ -94,7 +96,8 @@ The following built-in utility templates are excluded as they are not actual net
{
"template_id": "uuid-of-template2",
"x": -200,
"y": 300
"y": 300,
"compute_id": "uuid-of-remote-compute"
}
]
}
@@ -127,6 +130,7 @@ The following built-in utility templates are excluded as they are not actual net
- Uses templates for consistent node configuration
- X/Y coordinate positioning for topology layout
- Optional `name` field to set node name directly (if omitted, GNS3 assigns default name)
- Optional `compute_id` field to place the node on a remote compute (if omitted, `local`)
- **Important**: Ensure distance between any two nodes is greater than 250px for clear interface labels
**Use Cases:**
@@ -136,12 +140,12 @@ The following built-in utility templates are excluded as they are not actual net
**Implementation Details:**
- Calls `POST /projects/{project_id}/nodes` for each node
- Uses template_id from GNS3TemplateTool
- Uses template_id from template_list
- Assigns default names sequentially (e.g., R1, R2, R3)
### GNS3LinkTool 🆕
**Tool Name:** `create_gns3_link`
**Tool Name:** `link_create`
**Description:** Creates one or more links between nodes in a GNS3 project by connecting their network ports.
@@ -155,6 +159,13 @@ The following built-in utility templates are excluded as they are not actual net
"port1": "Ethernet0/0",
"node_id2": "uuid-of-node2",
"port2": "Ethernet0/0"
},
{
"node_id1": "uuid-of-node2",
"port1": "Serial0/0/0",
"node_id2": "uuid-of-node3",
"port2": "Serial0/0/0",
"link_type": "serial"
}
]
}
@@ -176,6 +187,7 @@ The following built-in utility templates are excluded as they are not actual net
**Features:**
- Batch create multiple links
- Automatic port discovery by name
- Optional `link_type` field per link (`ethernet` default, or `serial`)
- Error handling for individual link failures
- Port names must match topology data
@@ -190,9 +202,9 @@ The following built-in utility templates are excluded as they are not actual net
- Uses adapter_number and port_number for port identification
- Supports both physical and virtual interfaces
### GNS3UpdateNodeNameTool 🆕
### node_update 🆕
**Tool Name:** `update_gns3_node_name`
**Tool Name:** `node_update`
**Description:** Updates the name of one or multiple nodes in a GNS3 project.
@@ -240,9 +252,9 @@ The following built-in utility templates are excluded as they are not actual net
- Cannot rename while node is started (except special node types)
- CAN rename while node is suspended
### GNS3StartNodeTool
### node_start
**Tool Name:** `start_gns3_node`
**Tool Name:** `node_start`
**Description:** Starts one or multiple nodes in a GNS3 project with progress tracking and status monitoring. Features dynamic wait time calculation based on device types for optimal performance.
@@ -317,7 +329,7 @@ The tool automatically detects node types and calculates optimal wait times:
- Logs device types and selected wait strategy
- Progress bar displays calculated wait time
### GNS3StartNodeQuickTool 🆕
### node_start 🆕
**Tool Name:** `start_gns3_node_quick`
@@ -355,7 +367,7 @@ The tool automatically detects node types and calculates optimal wait times:
**When to Use Quick vs Regular Start:**
| Scenario | Use `start_gns3_node` | Use `start_gns3_node_quick` |
| Scenario | Use `node_start` | Use `start_gns3_node_quick` |
|----------|----------------------|-----------------------------|
| Interactive lab startup | ✅ | ❌ |
| CI/CD pipeline | ❌ | ✅ |
@@ -367,11 +379,11 @@ The tool automatically detects node types and calculates optimal wait times:
- Calls `POST /projects/{project_id}/nodes/{node_id}/start` for each node
- Returns immediately after sending start commands (no progress bar)
- Status reflects command send result, not boot completion
- Source: `gns3_start_node.py` (same file as `GNS3StartNodeTool`)
- Source: MCP tool `node_start`, adapted via `tools_v2/mcp_bridge.py`
### GNS3StopNodeTool
### node_stop
**Tool Name:** `stop_gns3_node`
**Tool Name:** `node_stop`
**Description:** Stops one or multiple nodes in a GNS3 project.
@@ -416,9 +428,9 @@ The tool automatically detects node types and calculates optimal wait times:
- Retrieves updated status after stop command
- Returns detailed results for each node
### GNS3SuspendNodeTool
### node_suspend
**Tool Name:** `suspend_gns3_node`
**Tool Name:** `node_suspend`
**Description:** Suspends one or multiple nodes in a GNS3 project. Suspended nodes preserve their state in memory and can be quickly resumed.
@@ -502,21 +514,18 @@ The tool automatically detects node types and calculates optimal wait times:
```
gns3server/agent/gns3_copilot/tools_v2/
├── gns3_create_node.py # Node creation tool 🆕
├── gns3_create_link.py # Link creation tool 🆕
├── gns3_get_node_temp.py # Template retrieval tool 🆕
├── gns3_update_node_name.py # Node rename tool 🆕
├── gns3_start_node.py # Start node tool (+ GNS3StartNodeQuickTool)
├── gns3_stop_node.py # Stop node tool
├── gns3_suspend_node.py # Suspend node tool
├── config_tools_nornir.py # Configuration command execution
├── display_tools_nornir.py # Display command execution
└── packet_capture_tools.py # Packet capture analysis
├── mcp_bridge.py # Adapts MCP server tools into LangChain tools (most tools)
├── gns3_create_link.py # Native link_create (port-name resolution)
├── gns3_wait.py # Native wait_seconds (boot wait timer)
├── packet_analysis_tool.py # Native packet_analysis (tshark)
├── device_config_commands.py # Shared runner behind MCP device_config_send
├── device_show_commands.py # Shared runner behind MCP device_show_run
└── vpcs_commands.py # Shared runner behind MCP vpcs_config_set
```
### API Integration
The tools call the shared REST handler layer (`gns3_copilot.gns3_client.api_handlers`), the same functions the MCP service exposes as MCP tools:
Most tools are generated from the MCP server registration (`agent/mcp/__init__.py`) by `mcp_bridge.adapted_mcp_tools()` — the MCP registration is the single source of truth for names, descriptions and argument schemas. Underneath, both the MCP tools and the copilot-native tools call the shared REST handler layer (`gns3_copilot.gns3_client.api_handlers`):
```python
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
@@ -558,7 +567,7 @@ listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
### Progress Tracking
**GNS3StartNodeTool** includes visual progress bar with dynamic wait time:
**node_start** includes visual progress bar with dynamic wait time:
```
Starting 3 node(s), please wait...
@@ -567,15 +576,15 @@ Starting 3 node(s), please wait...
Wait time is calculated by `calculate_startup_time()` based on node types (see Dynamic Wait Time Strategy above). No hardcoded duration.
**GNS3StartNodeQuickTool** does NOT include progress tracking:
**node_start** does NOT include progress tracking:
- Returns immediately after sending start commands
- Nodes boot in background
**GNS3StopNodeTool** does not include progress tracking:
**node_stop** does not include progress tracking:
- Stop operations are typically fast (< 5 seconds)
- Immediate API response provides status feedback
**GNS3SuspendNodeTool** does not include progress tracking:
**node_suspend** does not include progress tracking:
- Suspend operations are typically fast (< 10 seconds)
- Immediate API response provides status feedback
@@ -602,59 +611,67 @@ stateDiagram-v2
| **Suspended** | ✅ Yes | ✅ Yes | ❌ No | ✅ Yes |
*Except special node types: cloud, nat, ethernet_switch, ethernet_hub, frame_relay_switch, atm_switch
Note: These special node types are filtered out by GNS3TemplateTool and won't appear in template listings for network lab creation.
Note: These special node types are filtered out by template_list and won't appear in template listings for network lab creation.
## Copilot Mode Integration
### Teaching Assistant Mode
**Tools Available:**
- `GNS3TemplateTool` - List available device templates 🆕
- `GNS3CreateNodeTool` - Create nodes in topology 🆕
- `GNS3LinkTool` - Create links between nodes 🆕
- `GNS3UpdateNodeNameTool` - Rename nodes 🆕
- `GNS3StartNodeTool` - For diagnostics requiring started nodes
- `ExecuteMultipleDeviceCommands` - Execute show/display/debug commands (READ-ONLY)
- `PacketCaptureTool` - Analyze packets from active capture
- `DeviceSkillsTool` - Get device-specific skills and command knowledge
- `template_list` / `template_get` - List and inspect device templates
- `node_create` - Create nodes in topology
- `node_list` / `node_get` - Inspect nodes (field projection keeps responses small)
- `node_update` - Rename nodes
- `node_start` - For diagnostics requiring started nodes
- `link_create` - Create links between nodes (native: port-name resolution)
- `link_list` - Inspect links
- `link_marker` - Traffic-insight markers (highlight matching packets)
- `drawing_create_*` - Canvas annotations (text, rectangle, ellipse)
- `device_show_run` - Execute show/display/debug commands (READ-ONLY)
- `device_skill_get` - Get device-specific skills and command knowledge
- `wait_seconds` - Boot wait timer
- `packet_analysis` / `packet_analysis_skills` - Analyze packets and query protocol knowledge
**Capabilities:**
- READ-ONLY diagnostic tools
- Can create and manage topology (nodes, links, names)
- READ-ONLY device diagnostics
- Can create and manage topology (nodes, links, names, annotations)
- Traffic-insight markers for teaching scenarios
- Cannot stop or suspend nodes (prevents disruption of active labs)
- Cannot execute configuration commands
### Lab Automation Assistant Mode
**Tools Available:**
- `GNS3TemplateTool` - List available device templates 🆕
- `GNS3CreateNodeTool` - Create nodes in topology 🆕
- `GNS3LinkTool` - Create links between nodes 🆕
- `GNS3UpdateNodeNameTool` - Rename nodes 🆕
- `GNS3StartNodeTool` - Full lab deployment
- `GNS3StopNodeTool` - Full lab shutdown
- `GNS3SuspendNodeTool` - Lab pause with state preservation
- `ExecuteMultipleDeviceCommands` - Execute show/display/debug commands (READ-ONLY)
- `ExecuteMultipleDeviceConfigCommands` - Execute configuration commands
- `VPCSCommands` - Execute VPCS commands using Netmiko
- `PacketCaptureTool` - Analyze packets from active capture
- `DeviceSkillsTool` - Get device-specific skills and command knowledge
- `template_list` / `template_get` - List and inspect device templates
- `node_create` / `node_update` / `node_list` - Create, rename, inspect nodes
- `node_start` / `node_stop` / `node_suspend` - Full lifecycle control
- `node_console_exec` - Raw console access (works without a device_type tag)
- `link_create` - Create links between nodes (native: port-name resolution)
- `drawing_create_*` - Canvas annotations (text, rectangle, ellipse)
- `device_show_run` - Execute show/display/debug commands (READ-ONLY)
- `device_config_send` - Execute configuration commands (Jinja2 templates supported)
- `vpcs_config_set` - Execute VPCS commands using Netmiko
- `device_skill_get` - Get device-specific skills and command knowledge
- `snapshot_list` / `snapshot_create` / `snapshot_delete` / `snapshot_restore` - Project snapshots
- `wait_seconds` - Boot wait timer
- `packet_analysis` / `packet_analysis_skills` - Analyze packets and query protocol knowledge
**Capabilities:**
- Full diagnostic and configuration tools
- Complete topology and lifecycle management (create, connect, start/stop/suspend)
- Device configuration via Nornir/Netmiko
- Device configuration via Nornir/Netmiko (Jinja2 template batch mode)
- Generic console access for Docker/Linux/VPCS nodes
- Automated workflows with state preservation
- Lab snapshot capabilities for later resumption
- Project snapshot save/restore
## Usage Examples
### Example 1: Start Nodes with Progress
```python
from gns3server.agent.gns3_copilot.tools_v2 import GNS3StartNodeTool
from gns3server.agent.gns3_copilot.tools_v2 import node_start
tool = GNS3StartNodeTool()
tool = node_start()
result = tool._run(json.dumps({"project_id": "abc-123-def", "node_ids": ["node-1", "node-2", "node-3"]}))
# Output includes progress bar and final status
@@ -663,9 +680,9 @@ result = tool._run(json.dumps({"project_id": "abc-123-def", "node_ids": ["node-1
### Example 2: Stop Nodes
```python
from gns3server.agent.gns3_copilot.tools_v2 import GNS3StopNodeTool
from gns3server.agent.gns3_copilot.tools_v2 import node_stop
tool = GNS3StopNodeTool()
tool = node_stop()
result = tool._run(json.dumps({"project_id": "abc-123-def", "node_ids": ["node-1", "node-2"]}))
# Immediate return with stop status
@@ -675,30 +692,30 @@ result = tool._run(json.dumps({"project_id": "abc-123-def", "node_ids": ["node-1
```python
# Lab deployment
start_tool = GNS3StartNodeTool()
start_tool = node_start()
start_result = start_tool._run(json.dumps({"project_id": project_id, "node_ids": all_node_ids}))
# ... Run tests ...
# Lab shutdown
stop_tool = GNS3StopNodeTool()
stop_tool = node_stop()
stop_result = stop_tool._run(json.dumps({"project_id": project_id, "node_ids": all_node_ids}))
```
### Example 4: Lab Pause and Resume
```python
from gns3server.agent.gns3_copilot.tools_v2 import GNS3SuspendNodeTool
from gns3server.agent.gns3_copilot.tools_v2 import node_suspend
# Start lab
start_tool = GNS3StartNodeTool()
start_tool = node_start()
start_result = start_tool._run(json.dumps({"project_id": project_id, "node_ids": all_node_ids}))
# ... Configure devices ...
# ... Run some tests ...
# Suspend lab (preserves all state)
suspend_tool = GNS3SuspendNodeTool()
suspend_tool = node_suspend()
suspend_result = suspend_tool._run(json.dumps({"project_id": project_id, "node_ids": all_node_ids}))
# Nodes suspended - state preserved in memory
@@ -712,14 +729,14 @@ start_result = start_tool._run(json.dumps({"project_id": project_id, "node_ids":
### Example 5: Suspend While Renaming Nodes
```python
from gns3server.agent.gns3_copilot.tools_v2 import GNS3SuspendNodeTool, GNS3UpdateNodeNameTool
from gns3server.agent.gns3_copilot.tools_v2 import node_suspend, node_update
# Suspend nodes first (allows renaming)
suspend_tool = GNS3SuspendNodeTool()
suspend_tool = node_suspend()
suspend_result = suspend_tool._run(json.dumps({"project_id": project_id, "node_ids": node_ids}))
# Now rename nodes (possible while suspended!)
rename_tool = GNS3UpdateNodeNameTool()
rename_tool = node_update()
rename_result = rename_tool._run(
json.dumps(
{
@@ -739,9 +756,9 @@ rename_result = rename_tool._run(
### Example 6: Get Available Templates 🆕
```python
from gns3server.agent.gns3_copilot.tools_v2 import GNS3TemplateTool
from gns3server.agent.gns3_copilot.tools_v2 import template_list
tool = GNS3TemplateTool()
tool = template_list()
result = tool._run("")
# Returns all available device templates
@@ -756,9 +773,9 @@ result = tool._run("")
### Example 7: Create Topology Nodes 🆕
```python
from gns3server.agent.gns3_copilot.tools_v2 import GNS3CreateNodeTool
from gns3server.agent.gns3_copilot.tools_v2 import node_create
tool = GNS3CreateNodeTool()
tool = node_create()
result = tool._run(
json.dumps(
{
@@ -808,9 +825,9 @@ result = tool._run(
### Example 9: Apply Naming Convention 🆕
```python
from gns3server.agent.gns3_copilot.tools_v2 import GNS3UpdateNodeNameTool
from gns3server.agent.gns3_copilot.tools_v2 import node_update
tool = GNS3UpdateNodeNameTool()
tool = node_update()
result = tool._run(
json.dumps(
{
@@ -832,20 +849,20 @@ result = tool._run(
```python
from gns3server.agent.gns3_copilot.tools_v2 import (
GNS3TemplateTool,
GNS3CreateNodeTool,
template_list,
node_create,
GNS3LinkTool,
GNS3UpdateNodeNameTool,
GNS3StartNodeTool,
node_update,
node_start,
)
# Step 1: Get available templates
template_tool = GNS3TemplateTool()
template_tool = template_list()
templates = template_tool._run("")
# Find router and switch template_ids...
# Step 2: Create nodes
create_tool = GNS3CreateNodeTool()
create_tool = node_create()
nodes = create_tool._run(
json.dumps(
{
@@ -884,7 +901,7 @@ links = link_tool._run(
)
# Step 4: Apply naming
name_tool = GNS3UpdateNodeNameTool()
name_tool = node_update()
names = name_tool._run(
json.dumps(
{
@@ -899,7 +916,7 @@ names = name_tool._run(
)
# Step 5: Start nodes
start_tool = GNS3StartNodeTool()
start_tool = node_start()
start_result = start_tool._run(
json.dumps({"project_id": project_id, "node_ids": [n["node_id"] for n in nodes["created_nodes"]]})
)
@@ -1016,7 +1033,7 @@ _Status: ✅ Implemented - Topology management tools available in both modes. Fu
_Changelog:_
- **2026-03-14 (Evening)**: Added dynamic wait time calculation
- `GNS3StartNodeTool` now calculates optimal wait times based on device types
- `node_start` now calculates optimal wait times based on device types
- Fast devices (VPCS: 15s, IOU: 25s) start much faster than before
- Conservative timing accounts for slower hardware environments
- Slow devices (QEMU, Dynamips, etc.) use conservative 120s base time
@@ -1025,6 +1042,6 @@ _Changelog:_
- Logs selected strategy and detected device types
- **2026-03-14 (Morning)**: Added template filtering
- `GNS3TemplateTool` now filters out built-in utility templates (cloud, nat, ethernet_hub, ethernet_switch, frame_relay_switch, atm_switch)
- `template_list` now filters out built-in utility templates (cloud, nat, ethernet_hub, ethernet_switch, frame_relay_switch, atm_switch)
- Focuses on network devices suitable for lab configuration
- Logs filtered count for transparency
@@ -10,7 +10,7 @@ See LICENSE file for licensing information.
```mermaid
flowchart TB
subgraph "① Analysis Trigger & Knowledge Query"
A["User asks\n'e.g. Analyze OSPF neighbor state'"] --> B["LLM calls\nPacketAnalysisSkillsTool"]
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"]
@@ -21,7 +21,7 @@ flowchart TB
subgraph "② Live Capture & Analysis"
D --> H["LLM constructs tshark_args"]
G --> H
H --> I["PacketAnalysisTool\ncapture analysis mode"]
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"]
@@ -33,8 +33,8 @@ flowchart TB
| Tool | Source File | Purpose | Available Modes |
|---|---|---|---|
| `PacketAnalysisTool` | `packet_analysis_tool.py` | Download live PCAP + tshark analysis | teaching / lab_automation |
| `PacketAnalysisSkillsTool` | `registry.py` (skills module) | Query protocol-level analysis knowledge (fields, filters) | teaching / lab_automation |
| `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)
@@ -42,8 +42,8 @@ flowchart TB
sequenceDiagram
participant U as User
participant LLM as LLM Node
participant Skills as PacketAnalysisSkillsTool
participant Pcap as PacketAnalysisTool
participant Skills as packet_analysis_skills
participant Pcap as packet_analysis
U->>LLM: OSPF neighbors can't establish, analyze
LLM->>Skills: get protocol=ospf
@@ -12,7 +12,7 @@ See LICENSE file for licensing information.
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: `PacketAnalysisSkillsTool` queries protocol definitions, and `PacketAnalysisTool` runs tshark against downloaded pcap files using the LLM-constructed arguments.
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
@@ -26,8 +26,8 @@ graph TD
SM[SkillsManager]
SL[SkillsLoader]
REG[PACKET_ANALYSIS_REGISTRY<br/>in-memory dict]
SKILL[PacketAnalysisSkillsTool<br/>query protocol definitions]
TOOL[PacketAnalysisTool<br/>run tshark on captures]
SKILL[packet_analysis_skills<br/>query protocol definitions]
TOOL[packet_analysis<br/>run tshark on captures]
end
subgraph "tshark"
@@ -89,8 +89,8 @@ checks:
```mermaid
sequenceDiagram
participant LLM as LLM Agent
participant SKILL as PacketAnalysisSkillsTool
participant TOOL as PacketAnalysisTool
participant SKILL as packet_analysis_skills
participant TOOL as packet_analysis
participant tshark as tshark
participant GNS3 as GNS3 Server
@@ -117,12 +117,12 @@ The packet analysis tools are available in two copilot modes:
| Tool | Teaching Assistant | Lab Automation | Troubleshooting Injection |
|------|:------------------:|:--------------:|:-------------------------:|
| `PacketAnalysisTool` | Yes | Yes | No |
| `PacketAnalysisSkillsTool` | Yes | Yes | No |
| `packet_analysis` | Yes | Yes | No |
| `packet_analysis_skills` | Yes | Yes | No |
## Tool Interface
### PacketAnalysisSkillsTool (`packet_analysis_skills`)
### 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.
@@ -131,7 +131,7 @@ Queries protocol definitions from the `PACKET_ANALYSIS_REGISTRY`. Used before ru
| List protocols | `{"action": "list"}` | `{count, protocols: [{protocol, name, description}]}` |
| Get protocol | `{"action": "get", "protocol": "ospf"}` | Protocol definition with fields, filters, checks |
### PacketAnalysisTool (`packet_analysis`)
### packet_analysis
Runs tshark against a downloaded GNS3 capture file. Supports two modes:
@@ -82,7 +82,7 @@ SKILLS_REGISTRY["frr_vtysh"] = { ..._base.yaml..., "topics": { "ospf": {...}, "b
Topic files must declare `device_type` (matching their `_base.yaml`), `topic` and `name`; the CI validator in the skills repository enforces this.
The `device_skills` tool exposes a three-step drill-down (mirroring `injection_skills`'s list → index → issue pattern):
The `device_skill_get` tool exposes a three-step drill-down (mirroring `injection_skill_get`'s list → index → issue pattern):
```json
{"action": "list"}
@@ -101,8 +101,8 @@ Systematically inject network faults and validate AIOps detection using the exis
### 2.2 Fault Injection
- Use existing `manage_gns3_packet_filter` tool for network-level faults
- Use existing `execute_multiple_device_config_commands` for configuration faults
- 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)
@@ -61,4 +61,4 @@ The `troubleshooting_injection.md` prompt in the GNS3-Skills repository gains an
- [ ] 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 `InjectionSkillsTool` for filtering used faults
- [ ] gns3-server: add `exclude` parameter to `injection_skill_get` for filtering used faults
@@ -161,7 +161,7 @@ User Request: "Configure OSPF on all routers"
│ │
│ Process: │
│ 1. Render template with parameters (0 tokens) │
│ 2. Call existing ExecuteMultipleDeviceConfigCommands │
│ 2. Call existing device_config_send │
│ 3. Return execution results │
└─────────────────────────────────────────────────────────────┘
```
@@ -2068,7 +2068,7 @@ langgraph>=0.0.20
### Integration Points
- `gns3server/agent/gns3_copilot/tools_v2/config_tools_nornir.py` (existing)
- `gns3server/agent/gns3_copilot/gns3_client/device_config_commands.py` (existing)
- `gns3server/agent/gns3_copilot/prompts/lab_automation_assistant_prompt.py` (update)
- `gns3server/agent/gns3_copilot/gns3_client/gns3_topology_reader.py` (existing)
- `gns3server/agent/gns3_copilot/utils/command_filter.py` (existing)
+1 -1
View File
@@ -1 +1 @@
{"openapi": "3.1.0", "info": {"title": "GNS3 controller API", "description": "This page describes the public controller API for GNS3", "version": "3.0.0"}, "paths": {"/v3/version": {"get": {"tags": ["Controller"], "summary": "Get Version", "description": "Return the server version number.", "operationId": "get_version_v3_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.", "operationId": "check_version_v3_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"}}}}}}}, "/v3/reload": {"post": {"tags": ["Controller"], "summary": "Reload", "description": "Reload the controller", "operationId": "reload_v3_reload_post", "responses": {"204": {"description": "Successful Response"}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}, "security": [{"OAuth2PasswordBearer": []}]}}, "/v3/shutdown": {"post": {"tags": ["Controller"], "summary": "Shutdown", "description": "Shutdown the server", "operationId": "shutdown_v3_shutdown_post", "responses": {"204": {"description": "Successful Response"}, "403": {"description": "Server shutdown not allowed", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorMessage"}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}, "security": [{"OAuth2PasswordBearer": []}]}}, "/v3/iou_license": {"get": {"tags": ["Controller"], "summary": "Get Iou License", "description": "Return the IOU license settings", "operationId": "get_iou_license_v3_iou_license_get", "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/IOULicense"}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}, "security": [{"OAuth2PasswordBearer": []}]}, "put": {"tags": ["Controller"], "summary": "Update Iou License", "description": "Update the IOU license settings.", "operationId": "update_iou_license_v3_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"}}}}}, "security": [{"OAuth2PasswordBearer": []}]}}, "/v3/statistics": {"get": {"tags": ["Controller"], "summary": "Statistics", "description": "Return server statistics including compute resources, projects, and nodes.", "operationId": "statistics_v3_statistics_get", "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"additionalProperties": true, "type": "object", "title": "Response Statistics V3 Statistics Get"}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}, "security": [{"OAuth2PasswordBearer": []}]}}, "/v3/notifications": {"get": {"tags": ["Controller"], "summary": "Controller Http Notifications", "description": "Receive controller notifications about the controller from HTTP stream.", "operationId": "controller_http_notifications_v3_notifications_get", "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {}}}}, "422": {"description": "Validation Error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/HTTPValidationError"}}}}}, "security": [{"OAuth2PasswordBearer": []}]}}, "/v3/settings": {"get": {"tags": ["Server settings"], "summary": "Get Server Settings", "description": "Return the server settings.\n\nThe values reflect the running configuration (which may include command\nline overrides). Secret fields are masked.", "operationId": "get_server_settings_v3_settings_get", "responses": {"200": {"description": "Successful Response", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/SettingsResponse"}}}}, "401": {"description": "Unauthorized", "cLine 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
+1 -1
View File
@@ -87,7 +87,7 @@ try:
# namespace — it would shadow the gns3server.agent.mcp subpackage.
import importlib
importlib.import_module("mcp.server.fastmcp")
importlib.import_module("mcp.server.mcpserver")
MCP_AVAILABLE = True
except ImportError:
# MCP dependencies not installed, disable MCP feature
@@ -49,6 +49,7 @@ Copilot Modes:
import json
import logging
import operator
import time
from datetime import datetime
from typing import Annotated, Literal
@@ -64,6 +65,7 @@ from gns3server.agent.gns3_copilot.agent.context_manager import (
create_pre_model_hook,
)
from gns3server.agent.gns3_copilot.agent.model_factory import (
create_base_model,
create_base_model_with_tools,
create_title_model,
)
@@ -72,26 +74,14 @@ from gns3server.agent.gns3_copilot.gns3_client.context_helpers import (
get_current_llm_config,
)
from gns3server.agent.gns3_copilot.prompts import load_system_prompt
from gns3server.agent.gns3_copilot.skills import DeviceSkillsTool, InjectionSkillsTool, PacketAnalysisSkillsTool
from gns3server.agent.gns3_copilot.skills import PacketAnalysisSkillsTool
from gns3server.agent.gns3_copilot.skills.registry import get_prompt
from gns3server.agent.gns3_copilot.tools_v2 import (
ExecuteMultipleDeviceCommands,
ExecuteMultipleDeviceConfigCommands,
GNS3CreateEllipseDrawingTool,
GNS3CreateNodeTool,
GNS3CreateRectangleDrawingTool,
GNS3CreateTextDrawingTool,
GNS3LinkTool,
GNS3PacketFilterTool,
GNS3StartNodeTool,
GNS3StopNodeTool,
GNS3SuspendNodeTool,
GNS3TemplateTool,
GNS3UpdateNodeNameTool,
GNS3WaitTool,
PacketAnalysisTool,
adapted_mcp_tools,
)
from gns3server.agent.gns3_copilot.tools_v2.vpcs_tools_netmiko import VPCSCommands
# Set up logger for GNS3-Copilot
logger = logging.getLogger(__name__)
@@ -100,69 +90,151 @@ logger = logging.getLogger(__name__)
# system. The model_factory module handles model creation with configuration
# from the database.
# Define tools for different copilot modes
# Teaching assistant mode: READ-ONLY diagnostic tools only
# Define tools for different copilot modes.
#
# MCP-backed tools are adapted from the MCP server registration (single
# source of truth for names, descriptions and argument schemas — see
# tools_v2/mcp_bridge.py). Only project-scoped tools are eligible: the
# copilot runs inside one open project, so project management and server
# administration tools are filtered out by the bridge.
#
# Copilot-native tools remain where they add value over the MCP version:
# - GNS3LinkTool ("link_create"): resolves port NAMES to adapter/port
# numbers so the model does not need a node_get round-trip per link
# - GNS3WaitTool ("wait_seconds"): boot wait timer, pairs with node_start
# - PacketAnalysisTool/PacketAnalysisSkillsTool: tshark analysis, no MCP
# counterpart by design (server-side pcap analysis was rejected)
# - GNS3TopologyTool: aggregated nodes+links+ports view in one call
# Teaching assistant mode: read-only diagnostics, topology building and
# traffic-insight visibility (markers highlight packets on links)
TEACHING_ASSISTANT_MODE_TOOLS = [
GNS3TemplateTool(), # Get GNS3 node templates
GNS3CreateNodeTool(), # Create new nodes in GNS3
GNS3LinkTool(), # Create links between nodes
GNS3CreateTextDrawingTool(), # Add text labels to the canvas
GNS3CreateRectangleDrawingTool(), # Add rectangle annotations to the canvas
GNS3CreateEllipseDrawingTool(), # Add ellipse annotations to the canvas
GNS3StartNodeTool(), # Start GNS3 nodes (returns immediately)
GNS3WaitTool(), # Wait for nodes to boot (pair with start_gns3_node)
GNS3UpdateNodeNameTool(), # Update node name
ExecuteMultipleDeviceCommands(), # Execute show/display/debug commands
# (READ-ONLY)
PacketAnalysisTool(), # Protocol-oriented packet analysis with tshark
PacketAnalysisSkillsTool(), # Query packet analysis protocol definitions
DeviceSkillsTool(), # Get device-specific skills and command knowledge
*adapted_mcp_tools(
names=[
"template_list",
"template_get",
"node_create",
"node_update",
"node_list",
"node_get",
"drawing_create_text",
"drawing_create_rectangle",
"drawing_create_ellipse",
"node_start",
"link_list",
"link_marker",
"device_show_run",
"device_skill_get",
]
),
GNS3LinkTool(), # native: port-name resolution
GNS3WaitTool(), # wait for nodes to boot (pairs with node_start)
PacketAnalysisTool(), # protocol-oriented packet analysis with tshark
PacketAnalysisSkillsTool(), # query packet analysis protocol definitions
]
# Lab automation assistant mode: Full diagnostic AND configuration tools
# Lab automation assistant mode: full diagnostic AND configuration tools,
# plus generic console access (node_console_exec works without a
# device_type tag — Docker/Linux/VPCS nodes) and project snapshots
LAB_AUTOMATION_ASSISTANT_MODE_TOOLS = [
GNS3TemplateTool(), # Get GNS3 node templates
GNS3CreateNodeTool(), # Create new nodes in GNS3
GNS3LinkTool(), # Create links between nodes
GNS3CreateTextDrawingTool(), # Add text labels to the canvas
GNS3CreateRectangleDrawingTool(), # Add rectangle annotations to the canvas
GNS3CreateEllipseDrawingTool(), # Add ellipse annotations to the canvas
GNS3StartNodeTool(), # Start GNS3 nodes (returns immediately)
GNS3WaitTool(), # Wait for nodes to boot (pair with start_gns3_node)
GNS3StopNodeTool(), # Stop GNS3 nodes
GNS3SuspendNodeTool(), # Suspend GNS3 nodes (preserve state)
GNS3UpdateNodeNameTool(), # Update node name
ExecuteMultipleDeviceCommands(), # Execute show/display/debug commands
# (READ-ONLY)
ExecuteMultipleDeviceConfigCommands(), # Execute configuration commands
VPCSCommands(), # Execute VPCS commands using Netmiko
PacketAnalysisTool(), # Protocol-oriented packet analysis with tshark
PacketAnalysisSkillsTool(), # Query packet analysis protocol definitions
DeviceSkillsTool(), # Get device-specific skills and command knowledge
*adapted_mcp_tools(
names=[
"template_list",
"template_get",
"node_create",
"node_update",
"node_list",
"node_start",
"node_stop",
"node_suspend",
"node_console_exec",
"drawing_create_text",
"drawing_create_rectangle",
"drawing_create_ellipse",
"device_show_run",
"device_config_send",
"vpcs_config_set",
"device_skill_get",
"snapshot_list",
"snapshot_create",
"snapshot_delete",
"snapshot_restore",
]
),
GNS3LinkTool(), # native: port-name resolution
GNS3WaitTool(), # wait for nodes to boot (pairs with node_start)
PacketAnalysisTool(), # protocol-oriented packet analysis with tshark
PacketAnalysisSkillsTool(), # query packet analysis protocol definitions
]
# Troubleshooting injection mode: Tools for injecting network faults
# Focused on configuration commands and injection skills for fault injection
# Troubleshooting injection mode: fault injection plus the capture loop
# (inject → capture the link → verify with the downloaded pcap)
TROUBLESHOOTING_INJECTION_MODE_TOOLS = [
ExecuteMultipleDeviceCommands(), # Get device configurations (READ-ONLY)
ExecuteMultipleDeviceConfigCommands(), # Inject configuration changes
GNS3PacketFilterTool(), # Manage packet filters on links (delay, loss, corrupt, etc.)
InjectionSkillsTool(), # Query injection skills and fault types
GNS3TopologyTool(), # Get topology information
*adapted_mcp_tools(
names=[
"device_show_run",
"device_config_send",
"link_update",
"link_available_filters",
"link_capture_start",
"link_capture_stop",
"link_capture_download",
"marker_definition",
"injection_skill_get",
]
),
GNS3TopologyTool(), # aggregated topology view (nodes + links + ports)
]
# Default tools (legacy support - will be overridden by mode-specific tools)
tools = LAB_AUTOMATION_ASSISTANT_MODE_TOOLS
# LangGraph recursion limit per copilot mode: the hard cap on super-steps
# per user turn. One LLM call plus one tool execution costs two steps, so
# 25 is about 11 tool rounds; lab mode needs more room (topology build,
# configure, verify), fault injection more still.
MODE_RECURSION_LIMITS = {
"teaching_assistant": 25,
"lab_automation_assistant": 50,
"troubleshooting_injection": 100,
}
DEFAULT_RECURSION_LIMIT = 25
def resolve_recursion_limit(llm_config: dict | None) -> int:
"""Resolve the LangGraph recursion limit for one user turn.
``max_steps`` in the LLM model config wins when set to a positive
integer; otherwise the per-mode default applies. The value is a hard
safety cap, not a quality target: without it a tool loop or a routing
bug can spin forever and burn tokens.
"""
config = llm_config or {}
mode = (config.get("copilot_mode") or "teaching_assistant").lower()
default = MODE_RECURSION_LIMITS.get(mode, DEFAULT_RECURSION_LIMIT)
try:
configured = int(config.get("max_steps"))
except (TypeError, ValueError):
return default
return configured if configured > 0 else default
# Injected before the final LLM call when the step budget runs out. The
# model gets no tools in that call, so it can only produce text.
BUDGET_WRAPUP_INSTRUCTION = (
"The tool-step budget for this turn is exhausted. Do not call any tools. "
"Reply with a short summary: what you completed, what is still unfinished, "
"and what the user should do next (for example, ask to continue)."
)
# Create combined tool lookup for tool_node (supports all modes)
# tool_node will receive tool calls based on mode-specific tools bound to the
# model
# Combine all tools from all modes and deduplicate by tool name
# model. The registry must cover every mode: a tool bound to the model but
# missing here would raise KeyError when the LLM calls it.
ALL_TOOLS = LAB_AUTOMATION_ASSISTANT_MODE_TOOLS
tools_by_name = {tool.name: tool for tool in ALL_TOOLS}
# Add troubleshooting injection tools to the global tool registry
for tool in TROUBLESHOOTING_INJECTION_MODE_TOOLS:
for tool in TEACHING_ASSISTANT_MODE_TOOLS + TROUBLESHOOTING_INJECTION_MODE_TOOLS:
if tool.name not in tools_by_name:
tools_by_name[tool.name] = tool
@@ -228,7 +300,11 @@ class MessagesState(TypedDict):
operator.add
llm_calls: Counter for tracking the number of LLM invocations
remaining_steps: Is automatically managed by LangGraph's RemainingSteps
to track and limit recursion depth.
to track and limit recursion depth. The value comes from
the recursion_limit in the run config, not from inputs.
budget_exhausted: True once the step budget ran out and the graph
switched to the final summary call (no tools bound).
Reset to False at the start of every user turn.
conversation_title: Optional conversation title for session
identification and management
topology_info: Dictionary containing GNS3 project topology information
@@ -242,6 +318,9 @@ class MessagesState(TypedDict):
remaining_steps: RemainingSteps
# True when the step budget is used up and the turn ends with a summary
budget_exhausted: bool
# Optional conversation title
conversation_title: str | None
@@ -352,15 +431,26 @@ def llm_call(state: dict, config: RunnableConfig | None = None):
# token estimation
)
# Create fresh model with tools for each LLM call
logger.debug(
"Creating model with tools: provider=%s, model=%s, mode=%s, tools=%d",
llm_config.get("provider"),
llm_config.get("model"),
copilot_mode,
len(mode_tools),
)
model_with_tools = create_base_model_with_tools(mode_tools, llm_config=llm_config)
# When the step budget ran out, this is the final summary call: no tools
# are bound, so the model can only answer in text, and an instruction
# tells it to wrap up instead of planning more work.
budget_exhausted = bool(state.get("budget_exhausted"))
if budget_exhausted:
logger.warning(
"Step budget exhausted; making the final summary call without tools (provider=%s, model=%s)",
llm_config.get("provider"),
llm_config.get("model"),
)
model_to_call = create_base_model(llm_config)
else:
logger.debug(
"Creating model with tools: provider=%s, model=%s, mode=%s, tools=%d",
llm_config.get("provider"),
llm_config.get("model"),
copilot_mode,
len(mode_tools),
)
model_to_call = create_base_model_with_tools(mode_tools, llm_config=llm_config)
# Call pre_hook directly to prepare messages (topology injection +
# trimming)
@@ -371,8 +461,14 @@ def llm_call(state: dict, config: RunnableConfig | None = None):
prepared_messages = prepared_state["messages"]
logger.info("Messages prepared: %d → %d", len(messages), len(prepared_messages))
# Invoke model with prepared messages
response = model_with_tools.invoke(prepared_messages)
if budget_exhausted:
prepared_messages = [*prepared_messages, SystemMessage(content=BUDGET_WRAPUP_INSTRUCTION)]
# Invoke model with prepared messages. The elapsed time makes a slow
# first token or an SDK retry visible in the logs.
started_at = time.monotonic()
response = model_to_call.invoke(prepared_messages)
elapsed_s = time.monotonic() - started_at
# Add metadata with created_at timestamp to AI response
if hasattr(response, "metadata"):
@@ -390,8 +486,9 @@ def llm_call(state: dict, config: RunnableConfig | None = None):
logger.warning("Could not add metadata to AI response")
logger.info(
"LLM call completed: tool_calls=%d",
"LLM call completed: tool_calls=%d, elapsed=%.1fs",
len(response.tool_calls) if hasattr(response, "tool_calls") else 0,
elapsed_s,
)
return {
@@ -608,6 +705,11 @@ def should_continue(
if last_message.tool_calls:
return "tool_node"
# Final summary after the step budget ran out: end the turn, skip the
# title call (it would need one more super-step we may not have)
if state.get("budget_exhausted"):
return END
# First full interaction completed and title not yet generated
if current_title in [None, "New Conversation"]:
return "title_generator_node"
@@ -616,23 +718,41 @@ def should_continue(
return END
def budget_wrapup(state: MessagesState) -> dict:
"""Switch the graph to the final summary call after the step budget ran out.
The next llm_call binds no tools and appends BUDGET_WRAPUP_INSTRUCTION,
so the turn ends with a text answer that tells the user where the work
stopped instead of ending silently on a tool result.
"""
logger.warning(
"Step budget nearly exhausted (remaining_steps=%s); switching to the summary call",
state.get("remaining_steps"),
)
return {"budget_exhausted": True, "session_id": state.get("session_id")}
# Routing logic after the tool node, Check remaining_steps
def recursion_limit_continue(state: MessagesState) -> Literal["llm_call", END]:
def recursion_limit_continue(state: MessagesState) -> Literal["llm_call", "budget_wrapup", END]:
"""
Routing logic after tool execution to prevent infinite recursion.
Determines whether to continue with another LLM call or end the
conversation based on remaining steps and message type.
Determines whether to continue with another LLM call, switch to the
final summary call, or end the conversation based on remaining steps and
message type.
Args:
state: Current conversation state with messages and remaining steps
Returns:
"llm_call" to continue processing, END to terminate conversation
"llm_call" to continue processing, "budget_wrapup" for the final
summary call, END to terminate the conversation.
Logic:
- If abort flag is set → end the conversation
- If the last message is ToolMessage and steps >= 4: continue to LLM
- If the last message is ToolMessage and steps < 4: wrap up with one
final summary call (no tools bound)
- Otherwise: end the conversation to prevent infinite loops
"""
# Check abort flag first
@@ -643,7 +763,7 @@ def recursion_limit_continue(state: MessagesState) -> Literal["llm_call", END]:
last_message = state["messages"][-1]
if isinstance(last_message, ToolMessage):
if state["remaining_steps"] < 4:
return END
return "budget_wrapup"
return "llm_call"
return END
@@ -656,6 +776,7 @@ agent_builder = StateGraph(MessagesState)
# Add nodes
agent_builder.add_node("llm_call", llm_call)
agent_builder.add_node("tool_node", tool_node)
agent_builder.add_node("budget_wrapup", budget_wrapup)
agent_builder.add_node("title_generator_node", generate_title)
agent_builder.add_node("abort_handler_node", abort_handler_node)
@@ -684,9 +805,11 @@ agent_builder.add_conditional_edges(
{
"llm_call": "llm_call", # Continue to LLM if tools executed and steps
# remain
"budget_wrapup": "budget_wrapup", # Final summary call, no tools
END: END, # End conversation to prevent infinite loops
},
)
agent_builder.add_edge("budget_wrapup", "llm_call")
agent_builder.add_edge("title_generator_node", END)
agent_builder.add_edge("abort_handler_node", END)
@@ -38,6 +38,38 @@ from langchain.chat_models import init_chat_model
logger = logging.getLogger(__name__)
# Request controls for providers whose chat models accept the OpenAI-style
# parameters. Others (ollama, google-genai, ...) reject unknown kwargs at
# construction time, so the parameters are added only where they work.
_REQUEST_CONTROL_PROVIDERS = frozenset({"openai", "deepseek", "anthropic", "xai"})
# Without a timeout a wedged connection waits for the SDK default of 600s
# (seen in the field: one request stayed silent for 10 minutes, then the
# SDK retried on a fresh connection and got 200 OK in under a second).
# 120s is long enough for a slow first token and short enough to fail fast.
DEFAULT_REQUEST_TIMEOUT_S = 120.0
DEFAULT_MAX_RETRIES = 1
def _request_controls(llm_config: Optional[dict[str, Any]]) -> dict[str, Any]:
"""Build timeout/retry/usage kwargs for the chat model.
``request_timeout`` in the LLM model config overrides the default.
``stream_usage`` keeps usage_metadata available when the model streams
(astream_events makes it stream even with streaming=False).
"""
config = llm_config or {}
if config.get("provider") not in _REQUEST_CONTROL_PROVIDERS:
return {}
timeout = config.get("request_timeout", DEFAULT_REQUEST_TIMEOUT_S)
try:
timeout = float(timeout)
except (TypeError, ValueError):
timeout = DEFAULT_REQUEST_TIMEOUT_S
if timeout <= 0:
timeout = DEFAULT_REQUEST_TIMEOUT_S
return {"timeout": timeout, "max_retries": DEFAULT_MAX_RETRIES, "stream_usage": True}
def _load_llm_config(
llm_config: Optional[dict[str, Any]] = None,
@@ -117,6 +149,7 @@ def create_base_model(
"temperature": config_vars["temperature"],
"configurable_fields": "any",
"config_prefix": "foo",
**_request_controls(llm_config),
}
# Disable DeepSeek thinking mode to avoid reasoning_content handling issues
@@ -184,6 +217,7 @@ def create_title_model(
"temperature": "1.0", # Higher temperature for more creative titles
"configurable_fields": "any",
"config_prefix": "foo",
**_request_controls(llm_config),
}
# Disable DeepSeek thinking mode to avoid reasoning_content handling issues
+13 -17
View File
@@ -43,7 +43,10 @@ import aiosqlite
from langchain_core.messages import HumanMessage
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
from gns3server.agent.gns3_copilot.agent.gns3_copilot import agent_builder
from gns3server.agent.gns3_copilot.agent.gns3_copilot import (
agent_builder,
resolve_recursion_limit,
)
from gns3server.agent.gns3_copilot.chat_sessions_repository import (
ChatSessionsRepository,
)
@@ -282,13 +285,13 @@ class AgentService:
)
# Build config - only thread-safe identifiers
# Determine recursion_limit based on copilot_mode
# The recursion limit is the step budget of one user turn: the
# per-mode default, or max_steps from the LLM model config when set.
# RemainingSteps is a managed value derived from this limit; passing
# it in inputs has no effect.
copilot_mode = (llm_config or {}).get("copilot_mode", "teaching_assistant").lower()
if copilot_mode == "troubleshooting_injection":
recursion_limit = 100 # Need more recursion depth for fault injection workflow
log.debug("Using extended recursion_limit for troubleshooting_injection mode: 100")
else:
recursion_limit = 25 # Default recursion limit
recursion_limit = resolve_recursion_limit(llm_config)
log.debug("Using recursion_limit %d for copilot_mode %s", recursion_limit, copilot_mode)
config = {
"configurable": {
@@ -302,15 +305,8 @@ class AgentService:
"recursion_limit": recursion_limit,
}
# Build inputs
# Determine remaining_steps based on copilot_mode
# Troubleshooting injection mode needs more steps for multi-tool workflow
if copilot_mode == "troubleshooting_injection":
remaining_steps = 50 # Need more steps for fault injection workflow
log.debug("Using extended remaining_steps for troubleshooting_injection mode: 50")
else:
remaining_steps = 20 # Default for other modes
# Build inputs. budget_exhausted is reset per user turn: the
# checkpoint keeps it from a previous turn that ended on a summary.
inputs = {
"messages": [
HumanMessage(
@@ -320,7 +316,7 @@ class AgentService:
)
],
"llm_calls": 0,
"remaining_steps": remaining_steps,
"budget_exhausted": False,
"session_id": session_id,
"abort": False,
}
@@ -47,14 +47,12 @@ Copilot-side callers build the context with :func:`build_gns3_ctx`, which
pulls the request-scoped user JWT from the context variables.
"""
import hashlib
import logging
from concurrent.futures import ThreadPoolExecutor
from typing import Any
from gns3server.agent.gns3_copilot.gns3_client.connector import Gns3Connector
from gns3server.services import access_ticket_service
from gns3server.services.access_tickets import DEFAULT_TICKET_TTL
from gns3server.utils.drawings import build_ellipse_svg, build_rectangle_svg, build_text_svg
log = logging.getLogger(__name__)
@@ -448,56 +446,6 @@ def update_node_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> dic
return conn.http_call("put", url, json_data=update_data).json()
def get_node_console_info_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> dict[str, Any]:
project_id = params.get("project_id")
node_id = params.get("node_id")
if not project_id or not node_id:
return {"error": "project_id and node_id are required"}
conn = _get_connector(gns3_ctx)
node = conn.http_call("get", f"{conn.base_url}/projects/{project_id}/nodes/{node_id}").json()
console_type = node.get("console_type", "unknown")
# Short-lived console ticket (10 min, multi-use, bound to this node's
# console endpoints). Deliberately a short random string instead of a JWT:
# LLM clients retype this URL into shell commands and reliably corrupted
# the ~200-char JWT previously embedded here (dropped header segment →
# "Missing 'alg' value in header" on the server).
username = gns3_ctx.get("jwt_username")
ticket = (
access_ticket_service.mint(
username,
token_version=gns3_ctx.get("jwt_token_version", 0),
project_id=project_id,
node_id=node_id,
)
if username
else None
)
raw_url = f"{gns3_ctx['server_url']}/v3/projects/{project_id}/nodes/{node_id}/console/ws"
if ticket:
raw_url += f"?token={ticket}"
# Convert http scheme to ws for direct websocat usage
ws_url = raw_url.replace("https://", "wss://").replace("http://", "ws://")
result = {
"node_id": node_id,
"node_name": node.get("name"),
"console_type": console_type,
"ws_url": ws_url,
"command": f"websocat -t --no-close {ws_url}",
}
if ticket:
# Fingerprint of the minted token: compare it against what actually reached the
# server (logged on WebSocket auth rejection) to detect copy corruption, and
# re-request the URL once token_ttl_seconds has elapsed.
result["token_sha256_prefix"] = hashlib.sha256(ticket.encode()).hexdigest()[:8]
result["token_ttl_seconds"] = DEFAULT_TICKET_TTL
if console_type in ("vnc",) and ticket:
# Same node binding covers the vnc endpoint (identical path params)
result["vnc_url"] = f"/v3/projects/{project_id}/nodes/{node_id}/console/vnc?token={ticket}"
return result
# ── Node file handlers ────────────────────────────────────────────────────
@@ -28,8 +28,8 @@ This module provides a tool to execute configuration commands on multiple
devices in a GNS3 topology using Nornir.
⚠️ WARNING: This module is shared with the MCP (Model Context Protocol) service.
ExecuteMultipleDeviceConfigCommands._run() is called by the MCP device_config_send handler.
The jwt_token/url parameters were added for MCP compatibility.
DeviceConfigCommandRunner.run() is called by the MCP device_config_send handler
and by the copilot through the MCP tool bridge.
Modifications must be tested with BOTH gns3-copilot AND MCP.
"""
@@ -38,8 +38,6 @@ import logging
import re
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from netmiko.exceptions import ReadTimeout
from nornir import InitNornir
from nornir.core import Nornir
@@ -113,84 +111,57 @@ def _get_nornir_defaults() -> dict[str, Any]:
return {"data": {"location": "gns3"}}
class ExecuteMultipleDeviceConfigCommands(BaseTool):
class DeviceConfigCommandRunner:
"""
A tool to execute configuration commands on multiple devices in a GNS3
topology using Nornir.
This class uses Nornir to manage connections and execute configuration
commands on multiple devices concurrently.
Executes configuration commands on multiple devices in a GNS3 topology
using Nornir (one session per device, devices in parallel).
Shared implementation behind the MCP ``device_config_send`` tool; the
copilot reaches it through the MCP tool bridge. Not a LangChain tool —
the tool name/description contract lives in the MCP registration
(agent/mcp/__init__.py).
IMPORTANT SAFETY NOTE:
This tool is intended for configuration changes only. Use extreme caution
when executing configuration commands.
This runner is intended for configuration changes only. Use extreme
caution when executing configuration commands. Forbidden commands
(reload/erase/format/...) are filtered by
``utils.command_filter.filter_forbidden_commands``.
"""
name: str = "execute_multiple_device_config_commands"
description: str = """
Executes CONFIGURATION commands on multiple devices in the current GNS3
topology.
Use this tool ONLY for changing device settings (e.g., 'configure',
'interface', 'ip address', 'router ospf').
For viewing information, use the 'execute_multiple_device_commands' tool.
Input should be a JSON object containing project_id and device configs.
Example input:
{
"project_id": "<PROJECT_UUID>",
"device_configs": [
{
"device_name": "R-1",
"config_commands": [
"interface Loopback0",
"ip address 1.1.1.1 255.255.255.255",
"description CONFIG_BY_TOOL"
]
},
{
"device_name": "R-2",
"config_commands": [
"interface Loopback0",
"ip address 2.2.2.2 255.255.255.255",
"description CONFIG_BY_TOOL"
]
}
]
}
Returns a list of dicts with device name and config results.
IMPORTANT SAFETY WARNING:
Do NOT use this tool for dangerous operations that could reboot, erase,
or factory-reset devices.
Forbidden operations include but are not limited to:
- reload / reboot commands
- write erase / erase startup-config
- format / erase nvram / delete flash:
- boot system commands
- factory-reset commands
- any commands that require user confirmation prompts
- NEVER use 'exit' command - this disconnects the session and breaks subsequent commands
"""
def _run(
def run(
self,
tool_input: str, # or Union[str, List[Any], Dict[str, Any]]
run_manager: CallbackManagerForToolRun | None = None,
jwt_token: str | None = None,
url: str | None = None,
**kwargs: Any,
params: dict[str, Any] | str,
gns3_ctx: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
"""
Executes configuration commands on multiple devices in GNS3 topology.
Args:
tool_input (str): A JSON string containing project_id and device
configuration commands to execute.
jwt_token: JWT token for GNS3 API auth (MCP handlers).
url: GNS3 server URL (MCP handlers).
params: ``{"project_id", "device_configs", "template"?}``.
A JSON string is accepted for backward compatibility.
``template`` is an optional Jinja2 template rendered with
each device's ``vars`` into ``config_commands``.
gns3_ctx: handler context with ``jwt_token`` / ``server_url``.
Returns:
List[Dict[str, Any]]: A list of dicts containing device names and
configuration results.
"""
jwt_token = (gns3_ctx or {}).get("jwt_token")
url = (gns3_ctx or {}).get("server_url")
# Optional Jinja2 template: render per-device vars into config_commands
if isinstance(params, dict) and params.get("template"):
from gns3server.agent.gns3_copilot.utils.device_configs import render_device_template
rendered = render_device_template(
params["template"], params.get("device_configs", []), commands_field="config_commands"
)
if len(rendered) == 1 and "error" in rendered[0]:
return rendered
params = {**params, "device_configs": rendered}
tool_input = params
# Log received input
logger.debug("Received input: %s", tool_input)
@@ -711,12 +682,12 @@ if __name__ == "__main__":
}
)
exe_config = ExecuteMultipleDeviceConfigCommands()
exe_config = DeviceConfigCommandRunner()
failed_count = 0
for _i in range(0, 5):
exe_results = exe_config._run(tool_input=input_paras)
exe_results = exe_config.run(params=input_paras)
for result in exe_results:
for result in exe_results:
if result.get("status") == "failed":
@@ -28,8 +28,8 @@ This module provides a tool to execute display commands on multiple devices
in a GNS3 topology using Nornir.
⚠️ WARNING: This module is shared with the MCP (Model Context Protocol) service.
ExecuteMultipleDeviceCommands._run() is called by the MCP device_command_run handler.
The jwt_token/url parameters were added for MCP compatibility.
DeviceShowCommandRunner.run() is called by the MCP device_show_run handler
and by the copilot through the MCP tool bridge.
Modifications must be tested with BOTH gns3-copilot AND MCP.
"""
@@ -38,8 +38,6 @@ import logging
import re
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from netmiko.exceptions import ReadTimeout
from nornir import InitNornir
from nornir.core import Nornir
@@ -113,14 +111,16 @@ def _get_nornir_defaults() -> dict[str, Any]:
return {"data": {"location": "gns3"}}
class ExecuteMultipleDeviceCommands(BaseTool):
class DeviceShowCommandRunner:
"""
A READ-ONLY diagnostic tool for viewing network device configurations.
A READ-ONLY diagnostic runner for viewing network device configurations.
**CRITICAL: DIAGNOSIS ONLY - NO CONFIGURATION PERMISSIONS**
This tool is exclusively designed for read-only operations to inspect and
diagnose network devices. It CANNOT and MUST NOT be used for configuration.
Shared implementation behind the MCP ``device_show_run`` tool; the
copilot reaches it through the MCP tool bridge. Not a LangChain tool —
the tool name/description contract lives in the MCP registration
(agent/mcp/__init__.py).
**Allowed Command Types:**
- Display commands: show, display (Cisco/Huawei)
@@ -135,50 +135,10 @@ class ExecuteMultipleDeviceCommands(BaseTool):
- Any command that modifies device state
"""
name: str = "execute_multiple_device_commands"
description: str = """
**READ-ONLY DIAGNOSTIC TOOL** - View network device configurations.
Use this tool to inspect device information without making any changes.
**PERMITTED USE CASES:**
- View device status: show version, show running-config
- Check routing: show ip route, show ip ospf neighbor, show bgp summary
- Interface status: show ip interface brief, show interfaces
- Protocol diagnostics: show ospf database, show bgp routes, debug commands
- Connectivity testing: ping, traceroute
**STRICTLY FORBIDDEN:**
- NO configuration commands (configure terminal, interface, router, etc.)
- NO commands that modify device state
- NEVER use 'exit' command - this disconnects the session and breaks subsequent commands
- If you need to configure, provide guidance to the student instead
**Input Format:**
{
"project_id": "<PROJECT_UUID>",
"device_configs": [
{
"device_name": "R-1",
"commands": ["show version", "show ip interface brief"]
},
{
"device_name": "R-2",
"commands": ["show version", "show ip ospf neighbor"]
}
]
}
**Returns:** List of device outputs for diagnostic analysis.
"""
def _run(
def run(
self,
tool_input: str | bytes | list[Any] | dict[str, Any],
run_manager: CallbackManagerForToolRun | None = None,
jwt_token: str | None = None,
url: str | None = None,
**kwargs: Any,
params: dict[str, Any] | str,
gns3_ctx: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
"""
Executes READ-ONLY diagnostic commands on multiple devices in GNS3.
@@ -187,13 +147,30 @@ class ExecuteMultipleDeviceCommands(BaseTool):
configuration changes to network devices.
Args:
tool_input: JSON string with project_id and diagnostic commands.
jwt_token: JWT token for GNS3 API auth (MCP handlers).
url: GNS3 server URL (MCP handlers).
params: ``{"project_id", "device_configs", "template"?}``.
A JSON string is accepted for backward compatibility.
``template`` is an optional Jinja2 template rendered with
each device's ``vars`` into ``commands``.
gns3_ctx: handler context with ``jwt_token`` / ``server_url``.
Returns:
List[Dict]: A list of dicts with device names and outputs.
"""
jwt_token = (gns3_ctx or {}).get("jwt_token")
url = (gns3_ctx or {}).get("server_url")
# Optional Jinja2 template: render per-device vars into commands
if isinstance(params, dict) and params.get("template"):
from gns3server.agent.gns3_copilot.utils.device_configs import render_device_template
rendered = render_device_template(
params["template"], params.get("device_configs", []), commands_field="commands"
)
if len(rendered) == 1 and "error" in rendered[0]:
return rendered
params = {**params, "device_configs": rendered}
tool_input = params
# Log received input
logger.debug("Received input: %s", tool_input)
@@ -648,12 +625,12 @@ if __name__ == "__main__":
}
)
exe_cmd = ExecuteMultipleDeviceCommands()
exe_cmd = DeviceShowCommandRunner()
failed_count = 0
for _i in range(0, 1):
exe_results = exe_cmd._run(tool_input=device_commands)
exe_results = exe_cmd.run(params=device_commands)
for result in exe_results:
for result in exe_results:
if result.get("status") == "failed":
@@ -28,8 +28,8 @@ This module provides a tool to execute commands on VPCS devices
in a GNS3 topology using Nornir with Netmiko.
⚠️ WARNING: This module is shared with the MCP (Model Context Protocol) service.
VPCSCommands._run() is called by the MCP vpcs_config_set handler.
The jwt_token/url parameters were added for MCP compatibility.
VpcsCommandRunner.run() is called by the MCP vpcs_config_set handler
and by the copilot through the MCP tool bridge.
Modifications must be tested with BOTH gns3-copilot AND MCP.
"""
@@ -38,8 +38,6 @@ import logging
import re
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from netmiko.exceptions import ReadTimeout
from nornir import InitNornir
from nornir.core import Nornir
@@ -98,15 +96,17 @@ def _get_nornir_defaults() -> dict[str, Any]:
return {"data": {"location": "gns3"}}
class VPCSCommands(BaseTool):
class VpcsCommandRunner:
"""
A tool for VPCS (Virtual PC Simulator) devices.
Runs commands on VPCS (Virtual PC Simulator) devices in a GNS3 topology.
**VPCS-SPECIFIC TOOL** - This tool ONLY works with VPCS virtual PC devices.
**VPCS-SPECIFIC RUNNER** - This runner ONLY works with VPCS virtual PC
devices.
**IMPORTANT DISTINCTION:**
Unlike network devices (routers/switches), VPCS devices are lightweight virtual PCs.
Commands like 'ip' are basic PC IP config, NOT network device config.
Shared implementation behind the MCP ``vpcs_config_set`` tool; the
copilot reaches it through the MCP tool bridge. Not a LangChain tool —
the tool name/description contract lives in the MCP registration
(agent/mcp/__init__.py).
**Allowed VPCS Commands:**
- IP configuration: ip <address>/<mask> <gateway>
@@ -117,63 +117,26 @@ class VPCSCommands(BaseTool):
- Save/Load: save, load
"""
name: str = "execute_vpcs_commands"
description: str = """
**VPCS VIRTUAL PC TOOL** - Configure and test Virtual PC Simulator devices.
This tool ONLY works with VPCS devices, NOT routers/switches.
**IMPORTANT: VPCS vs Network Devices**
- VPCS = Lightweight virtual PCs for lab testing (NOT network infra)
- 'ip' command on VPCS = Basic PC IP config (like 'ipconfig' on Windows)
- NOT the same as configuring router interfaces or routing protocols
**When to Use This Tool:**
- Configure IP addresses on virtual PCs: ip 10.10.0.12/24 10.10.0.254
- Test connectivity from PCs: ping 10.10.0.254
- View PC IP configuration: ip, show ip
- Display ARP table: arp
- Check PC version: version
**Input Format:**
{
"project_id": "<PROJECT_UUID>",
"device_configs": [
{
"device_name": "PC1",
"commands": ["ip", "ping 10.10.0.254"]
},
{
"device_name": "PC2",
"commands": ["show ip"]
}
]
}
**Returns:** PC command outputs for IP config and connectivity testing.
**Note:** For network devices, use execute_multiple_device_commands.
"""
def _run(
def run(
self,
tool_input: str | bytes | list[Any] | dict[str, Any],
run_manager: CallbackManagerForToolRun | None = None,
jwt_token: str | None = None,
url: str | None = None,
**kwargs: Any,
params: dict[str, Any] | str,
gns3_ctx: dict[str, Any] | None = None,
) -> list[dict[str, Any]]:
"""
Execute commands on multiple VPCS devices in GNS3 topology.
Args:
tool_input: JSON string with project_id and VPCS commands.
jwt_token: JWT token for GNS3 API auth (MCP handlers).
url: GNS3 server URL (MCP handlers).
params: ``{"project_id", "device_configs"}``. A JSON string is
accepted for backward compatibility.
gns3_ctx: handler context with ``jwt_token`` / ``server_url``.
Returns:
List of dicts with device names and command outputs.
"""
jwt_token = (gns3_ctx or {}).get("jwt_token")
url = (gns3_ctx or {}).get("server_url")
tool_input = params
# Log received input
logger.debug("Received input: %s", tool_input)
@@ -450,7 +413,10 @@ class VPCSCommands(BaseTool):
}
continue
# VPCS devices use gns3_vpcs_telnet device type
# VPCS devices use gns3_vpcs_telnet device type. pcname wires the
# driver's prompt pattern to the node name: the template's startup
# script runs `set pcname <name>`, so a node renamed away from
# PC<n> prompts "<name>>" and never matches the default pattern.
host_entry = {
"port": port,
"platform": "vpcs",
@@ -459,6 +425,7 @@ class VPCSCommands(BaseTool):
"netmiko": {
"extras": {
"device_type": "gns3_vpcs_telnet",
"pcname": device_name,
"fast_cli": False,
"global_delay_factor": 2.0,
}
@@ -621,7 +588,7 @@ if __name__ == "__main__":
}
)
exe_cmd = VPCSCommands()
result = exe_cmd._run(tool_input=command_groups)
exe_cmd = VpcsCommandRunner()
result = exe_cmd.run(params=command_groups)
print("Execution results:")
print(json.dumps(result, indent=2, ensure_ascii=False))
@@ -85,7 +85,7 @@ class SkillsLoader:
if not skill_data:
logger.warning(f"Skipping empty YAML file: {yaml_file}")
continue
# Generate key from filename (e.g., "ospf_issues.yaml" -> "injection_ospf")
# Generate key from filename (e.g., "ospf_issues.yaml" -> "injection_ospf_issues")
skill_key = f"injection_{yaml_file.stem}"
skills[skill_key] = skill_data
logger.debug(f"Loaded injection skill: {skill_key} from {yaml_file}")
+98 -58
View File
@@ -101,33 +101,60 @@ class SkillsManager:
Initialize the skills repository.
Behavior:
- If no local repo → clone from remote
- If local repo exists → open and run _update_if_needed()
- No local directory → create it and clone from remote
- Local git repo → open and run _update_if_needed()
- Local directory without .git → use it as a local-only source
(cloning into a non-empty directory cannot work, and local
content must stay usable without Git)
Returns:
True if successful, False otherwise
"""
try:
if not self.local_path.exists():
logger.info(f"Creating skills directory: {self.local_path}")
self.local_path.mkdir(parents=True, exist_ok=True)
if not (self.local_path / ".git").exists():
return self._clone()
# Repo exists, open it
try:
self._repo = git.Repo(self.local_path)
except Exception as e:
logger.error(f"Failed to open existing repository: {e}")
if not self._ensure_repo():
return False
self._update_if_needed()
return True
except Exception as e:
logger.error(f"Failed to initialize skills repository: {e}")
return False
def _ensure_repo(self) -> bool:
"""Prepare the local skills directory and open/clone the repo.
A non-empty directory without .git is accepted as a local-only
skills source: automatic updates are skipped, the files still load.
"""
if not self.local_path.exists():
logger.info(f"Creating skills directory: {self.local_path}")
self.local_path.mkdir(parents=True, exist_ok=True)
if not GIT_AVAILABLE:
logger.warning("GitPython is not installed; using local files without automatic updates")
self._repo = None
return True
if not (self.local_path / ".git").exists():
try:
is_empty = not any(self.local_path.iterdir())
except OSError:
is_empty = True
if is_empty:
return self._clone()
logger.warning(
"Skills directory %s is not a git repository; using local files without automatic updates",
self.local_path,
)
self._repo = None
return True
try:
self._repo = git.Repo(self.local_path)
except Exception as e:
logger.error(f"Failed to open existing repository: {e}")
return False
return True
def _update_if_needed(self) -> None:
"""
Check local repo status and pull updates if safe.
@@ -137,7 +164,15 @@ class SkillsManager:
- Up to date → nothing
- Network error → use existing files, log warning
"""
if not GIT_AVAILABLE or self._repo is None:
if not GIT_AVAILABLE:
return
if not self.local_path.exists():
# The directory can disappear or move between reloads (manual
# clone/rename); re-create/clone instead of failing forever.
if not self._ensure_repo():
logger.warning("Skills repository is unavailable; using local files")
return
if self._repo is None:
return
# Check for uncommitted changes
@@ -190,62 +225,64 @@ class SkillsManager:
def reload_skills(self) -> bool:
"""
Hot reload skills from YAML files into the registry.
Hot reload skills from YAML files into the registries.
Loads the latest skill definitions from YAML files and updates
the INJECTION_SKILLS_REGISTRY.
Injection, device and feature skills load independently: a missing
or empty directory keeps the previously loaded entries of that
category instead of blocking the others.
Returns:
True if successful, False otherwise
True if at least one category loaded, False otherwise
"""
try:
# Import here to avoid circular dependency
from .registry import INJECTION_SKILLS_REGISTRY, SKILLS_REGISTRY
# Load new injection skills from YAML files
new_injection_skills = self.loader.load_injection_skills()
# Load and validate injection skills (invalid ones are dropped
# before merging; validate_skill_format logs the reason).
new_injection_skills = {
skill_key: skill_data
for skill_key, skill_data in self.loader.load_injection_skills().items()
if self.loader.validate_skill_format(skill_data)
}
if not new_injection_skills:
logger.warning("No injection skills loaded, keeping existing skills")
return False
# Validate injection skills (drop invalid ones before merging)
valid_injection_skills = {}
for skill_key, skill_data in new_injection_skills.items():
if self.loader.validate_skill_format(skill_data):
valid_injection_skills[skill_key] = skill_data
else:
logger.error(f"Invalid skill format for {skill_key}, skipping")
if not valid_injection_skills:
logger.warning("No valid injection skills loaded, keeping existing skills")
return False
new_injection_skills = valid_injection_skills
# Load new device skills from YAML files
# Load new device and feature skills from YAML files
new_device_skills = self.loader.load_device_skills()
# Load new feature skills from YAML files
new_feature_skills = self.loader.load_feature_skills()
# Merge device and feature skills into single registry
all_skills = {}
all_skills.update(new_device_skills)
all_skills.update(new_feature_skills)
if not new_injection_skills and not new_device_skills and not new_feature_skills:
logger.warning("No skills loaded from any category, keeping existing skills")
return False
# Update registries (safe replace - never leaves dict empty)
for k in list(INJECTION_SKILLS_REGISTRY):
if k not in new_injection_skills:
del INJECTION_SKILLS_REGISTRY[k]
INJECTION_SKILLS_REGISTRY.update(new_injection_skills)
# Injection: an absent injection/ directory keeps old entries.
if new_injection_skills:
for k in list(INJECTION_SKILLS_REGISTRY):
if k not in new_injection_skills:
del INJECTION_SKILLS_REGISTRY[k]
INJECTION_SKILLS_REGISTRY.update(new_injection_skills)
else:
logger.warning("No valid injection skills loaded, keeping existing injection skills")
for k in list(SKILLS_REGISTRY):
if k not in all_skills:
del SKILLS_REGISTRY[k]
SKILLS_REGISTRY.update(all_skills)
# Device/feature: replace each category that yielded content and
# keep the old entries of a category that yielded none.
if new_device_skills or new_feature_skills:
all_skills: Dict[str, Dict[str, Any]] = {}
all_skills.update(
new_device_skills or {k: v for k, v in SKILLS_REGISTRY.items() if v.get("category") == "device"}
)
all_skills.update(
new_feature_skills or {k: v for k, v in SKILLS_REGISTRY.items() if v.get("category") == "feature"}
)
for k in list(SKILLS_REGISTRY):
if k not in all_skills:
del SKILLS_REGISTRY[k]
SKILLS_REGISTRY.update(all_skills)
else:
logger.warning("No device/feature skills loaded, keeping existing device/feature skills")
logger.info(
f"Loaded {len(new_injection_skills)} injection skills, {len(new_device_skills)} device skills, and {len(new_feature_skills)} feature skills"
f"Loaded {len(new_injection_skills)} injection skills, "
f"{len(new_device_skills)} device skills, and {len(new_feature_skills)} feature skills"
)
return True
except Exception as e:
@@ -256,8 +293,8 @@ class SkillsManager:
"""
Hot reload packet analysis protocol definitions from YAML files.
Loads the latest protocol definitions from YAML files and updates
the PACKET_ANALYSIS_REGISTRY.
An empty result (missing or empty directory) keeps the existing
registry and reports failure, matching the skills/prompts behavior.
Returns:
True if successful, False otherwise
@@ -267,6 +304,9 @@ class SkillsManager:
# Load new packet analysis protocols from YAML files
new_protocols = self.loader.load_packet_analysis_protocols()
if not new_protocols:
logger.warning("No packet analysis protocols loaded, keeping existing protocols")
return False
# Update registry (safe replace - never leaves dict empty)
for k in list(PACKET_ANALYSIS_REGISTRY):
@@ -355,6 +355,11 @@ def get_skills_repository_info() -> dict[str, Any]:
return manager.get_repository_info()
# Descriptive keys that are not content sections; excluded from the
# section list returned for skills that have no topics/issues.
_SKILL_META_KEYS = frozenset({"name", "description", "device_type", "category", "issues", "topics"})
def get_skill(
device_type: str,
category: str | None = None,
@@ -450,6 +455,12 @@ def get_skill(
}
if topics:
result["topics"] = {k: v.get("name", k) for k, v in topics.items()}
else:
# Single-file device/feature skills have no topics: name the
# top-level sections so the index is not an empty shell.
sections = [k for k in skill if k not in _SKILL_META_KEYS]
if sections:
result["sections"] = sections
return result
if detail == "summary":
@@ -472,6 +483,10 @@ def get_skill(
result["topics"] = {
k: {"name": v.get("name", k), "description": v.get("description", "")} for k, v in topics.items()
}
else:
sections = [k for k in skill if k not in _SKILL_META_KEYS]
if sections:
result["sections"] = sections
return result
# Full detail: topic bodies are replaced by the topic index
@@ -517,7 +532,7 @@ def get_injection_skill(
Get injection fault skill by device_type, with configurable detail level.
Args:
device_type: The injection fault type (e.g., "injection_ospf")
device_type: The injection fault type (e.g., "injection_ospf_issues")
detail: Detail level - "index" (names only), "summary" (+desc/sev/diff), "full" (all)
issue: Optional specific issue key to retrieve
@@ -587,18 +602,23 @@ def list_available_injection_skills(context: list[str] | None = None) -> list[di
Args:
context: List of protocol/service keywords (e.g., ["ospf", "bgp", "vlan"]).
Only returns skills whose category matches any keyword.
A skill matches when a keyword appears in its category, its
key or one of its declared protocols (case-insensitive), so
aliases such as "ebgp" or "ospfv3" work.
Returns:
List of skill info dicts with device_type, name, and category.
"""
skills = []
keywords = [str(kw).lower() for kw in context] if context else []
for did, skill in INJECTION_SKILLS_REGISTRY.items():
category = skill.get("category", "")
if context:
# Match if skill category contains any context keyword
category_lower = category.lower()
if not any(kw.lower() in category_lower or kw.lower() in did.lower() for kw in context):
if keywords:
haystacks = [str(category).lower(), did.lower()]
protocols = skill.get("protocols")
if isinstance(protocols, list):
haystacks.extend(str(protocol).lower() for protocol in protocols)
if not any(keyword in haystack for keyword in keywords for haystack in haystacks):
continue
skills.append(
{
@@ -762,13 +782,13 @@ class InjectionSkillsTool(BaseTool):
1. List faults for YOUR topology protocols (REQUIRED):
{"action": "list", "context": ["ospf", "bgp"]}
2. Get specific fault details:
{"device_type": "injection_ospf", "issue": "ospf_hello_dead_mismatch"}
{"device_type": "injection_ospf", "detail": "index"}
{"device_type": "injection_ospf_issues", "issue": "ospf_hello_dead_mismatch"}
{"device_type": "injection_ospf_issues", "detail": "index"}
PARAMETERS:
- action: "list" or "get"
- context: [str] - REQUIRED for action="list". Protocols from your topology.
- device_type: Required for action="get" (e.g., "injection_ospf")
- device_type: Required for action="get" (e.g., "injection_ospf_issues")
- detail: "index" | "summary" | "full"
- issue: Get single fault detail by key
"""
@@ -22,53 +22,36 @@
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
"""
GNS3-Copilot Tools Package
This package provides various tools for interacting with GNS3 network simulator:
- Device configuration command execution
- Display command execution
- Multiple device command execution using Nornir
- VPCS device configuration using Netmiko
- Node and link management
- Packet filter management
Most copilot tools are now adapted from the MCP server registration via
``mcp_bridge.adapted_mcp_tools()`` — the MCP tools are the single source
of truth for names, descriptions and argument schemas (see
``mcp_bridge.MCP_ALLOWED_TOOLS`` for the project-scoped filter).
Main modules:
- config_tools_nornir: Multiple device configuration command execution tool using Nornir
- display_tools_nornir: Multiple device command execution tool using Nornir
- vpcs_tools_netmiko: VPCS device configuration tool using Netmiko
- gns3_create_node: GNS3 node creation tool
- gns3_create_link: GNS3 link creation tool
- gns3_create_drawing: GNS3 canvas drawing tools (text, rectangle, ellipse)
- gns3_start_node: GNS3 node startup tool (immediate return, no boot wait)
- gns3_wait: Wait timer tool (pair with node start to let devices boot)
- gns3_get_node_temp: GNS3 template retrieval tool
- gns3_update_node_name: GNS3 node name update tool
- gns3_packet_filter: GNS3 packet filter management tool
This package keeps only the copilot-native tools that add behavior the
MCP counterparts lack:
Note: GNS3TopologyTool is now available from gns3_client package
- gns3_create_link: link creation with port-NAME resolution ("link_create";
shadows the adapted MCP tool of the same name)
- gns3_wait: boot wait timer ("wait_seconds"; pairs with node_start)
- packet_analysis_tool: server-side tshark pcap analysis ("packet_analysis";
no MCP counterpart by design)
The Nornir/Netmiko device command runners live in the shared layer as
plain classes (gns3_client/device_config_commands.py, device_show_commands.py,
vpcs_commands.py) behind the MCP device_config_send / device_show_run /
vpcs_config_set tools, which the copilot uses through the bridge.
Author: Yue Guobin (岳国宾)
"""
# Import main tool classes
from .config_tools_nornir import ExecuteMultipleDeviceConfigCommands
from .display_tools_nornir import ExecuteMultipleDeviceCommands
from .gns3_create_drawing import (
GNS3CreateEllipseDrawingTool,
GNS3CreateRectangleDrawingTool,
GNS3CreateTextDrawingTool,
)
from .gns3_create_link import GNS3LinkTool
from .gns3_create_node import GNS3CreateNodeTool
from .gns3_get_node_temp import GNS3TemplateTool
from .gns3_packet_filter import GNS3PacketFilterTool
from .gns3_start_node import GNS3StartNodeQuickTool, GNS3StartNodeTool
from .gns3_stop_node import GNS3StopNodeTool
from .gns3_suspend_node import GNS3SuspendNodeTool
from .gns3_update_node_name import GNS3UpdateNodeNameTool
from .gns3_wait import GNS3WaitTool
from .mcp_bridge import adapted_mcp_tools
from .packet_analysis_tool import PacketAnalysisTool
# Dynamic version management
@@ -83,25 +66,10 @@ __author__ = "Yue Guobin (岳国宾)"
__description__ = "AI-powered network automation assistant for GNS3"
__url__ = "https://github.com/yueguobin/gns3-copilot"
# Export main tool classes
# Export main tool classes and the MCP bridge
__all__ = [
"ExecuteMultipleDeviceCommands",
"ExecuteMultipleDeviceConfigCommands",
"GNS3CreateEllipseDrawingTool",
"GNS3CreateNodeTool",
"GNS3CreateRectangleDrawingTool",
"GNS3CreateTextDrawingTool",
"GNS3LinkTool",
"GNS3PacketFilterTool",
"GNS3StartNodeQuickTool",
"GNS3StartNodeTool",
"GNS3StopNodeTool",
"GNS3SuspendNodeTool",
"GNS3TemplateTool",
"GNS3UpdateNodeNameTool",
"GNS3WaitTool",
"PacketAnalysisTool",
"adapted_mcp_tools",
]
# Package initialization message
# print(f"GNS3-Copilot Tools package loaded (version {__version__})")
@@ -1,162 +0,0 @@
# 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 canvas drawing tools for text, rectangle and ellipse annotations.
Thin LangChain wrappers over the shared REST handlers in
``gns3_client.api_handlers``; the Web UI compatible SVG is assembled and
validated by ``gns3server.utils.drawings`` (single implementation shared
with the MCP drawing tools).
"""
import json
import logging
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
build_gns3_ctx,
create_ellipse_drawing_handler,
create_rectangle_drawing_handler,
create_text_drawing_handler,
)
# Configure logging
logger = logging.getLogger(__name__)
class _GNS3CreateDrawingToolBase(BaseTool):
"""Shared plumbing: parse JSON input, build ctx, dispatch to a handler."""
def _dispatch(self, input_data: dict[str, Any], gns3_ctx: dict[str, Any]) -> dict[str, Any]:
raise NotImplementedError
def _run(
self,
tool_input: str,
run_manager: CallbackManagerForToolRun | None = None,
) -> dict[str, Any]:
try:
input_data = json.loads(tool_input)
gns3_ctx = build_gns3_ctx()
if gns3_ctx is None:
logger.error("Failed to create GNS3 connector")
return {"error": "Failed to connect to GNS3 server. Please check your configuration."}
return self._dispatch(input_data, gns3_ctx)
except json.JSONDecodeError as e:
logger.error("Invalid JSON input: %s", e)
return {"error": f"Invalid JSON input: {e}"}
except Exception as e:
logger.exception("Drawing creation failed")
return {"error": str(e)}
class GNS3CreateTextDrawingTool(_GNS3CreateDrawingToolBase):
"""
A LangChain tool to add a text label to the GNS3 project canvas.
**Input**:
A JSON object with project_id, x, y (top-left corner on the canvas)
and text; optional font_size (1-200, default 13), color (#RRGGBB,
default #000000), bold (default false), font_family (default
monospace) and z (default 1, keeps text above links).
Newlines in text start additional lines; XML characters are escaped
automatically; the computed width/height are returned.
**Output**:
A dictionary with the created drawing, its drawing_id and the
computed width/height/line_height, or an "error" key on failure.
"""
name: str = "create_gns3_text_drawing"
description: str = """
Adds a text label to the GNS3 project canvas.
Input: JSON with project_id, x, y (top-left corner), text and optional
font_size, color, bold, font_family, z.
Returns: the created drawing with its computed width and height.
"""
def _dispatch(self, input_data: dict[str, Any], gns3_ctx: dict[str, Any]) -> dict[str, Any]:
return create_text_drawing_handler(input_data, gns3_ctx)
class GNS3CreateRectangleDrawingTool(_GNS3CreateDrawingToolBase):
"""
A LangChain tool to add a rectangle to the GNS3 project canvas.
**Input**:
A JSON object with project_id, x, y (top-left corner), width and
height (1-2000); optional fill (#RRGGBB or "none", default #FFFFFF),
fill_opacity (0-1, default 1.0), stroke (#RRGGBB, no border by
default), stroke_width (1-20), dashed (bool), dasharray (like "4,2",
requires stroke) and rx (corner radius, default 0). z defaults to 0
so shapes stay behind nodes and text.
**Output**:
A dictionary with the created drawing, or an "error" key on failure.
"""
name: str = "create_gns3_rectangle_drawing"
description: str = """
Adds a rectangle to the GNS3 project canvas.
Input: JSON with project_id, x, y, width, height and optional fill,
fill_opacity, stroke, stroke_width, dashed, dasharray, rx, z.
Returns: the created drawing with its width and height.
"""
def _dispatch(self, input_data: dict[str, Any], gns3_ctx: dict[str, Any]) -> dict[str, Any]:
return create_rectangle_drawing_handler(input_data, gns3_ctx)
class GNS3CreateEllipseDrawingTool(_GNS3CreateDrawingToolBase):
"""
A LangChain tool to add an ellipse (or circle) to the GNS3 canvas.
**Input**:
A JSON object with project_id, x, y (bounding box top-left corner),
width and height (2-2000, equal values give a circle); the same
optional style fields as the rectangle tool. cx/cy are derived from
the bounding box; for odd width/height the drawing is 1 px smaller
than requested and the actual size is returned.
**Output**:
A dictionary with the created drawing, or an "error" key on failure.
"""
name: str = "create_gns3_ellipse_drawing"
description: str = """
Adds an ellipse or circle to the GNS3 project canvas.
Input: JSON with project_id, x, y, width, height (bounding box) and
optional fill, fill_opacity, stroke, stroke_width, dashed, dasharray, z.
Returns: the created drawing with its actual width and height.
"""
def _dispatch(self, input_data: dict[str, Any], gns3_ctx: dict[str, Any]) -> dict[str, Any]:
return create_ellipse_drawing_handler(input_data, gns3_ctx)
@@ -57,7 +57,7 @@ class GNS3LinkTool(BaseTool):
with error handling for individual link failures.
"""
name: str = "create_gns3_link"
name: str = "link_create"
description: str = """
Creates one or more links between nodes in a GNS3 project.
@@ -68,6 +68,7 @@ class GNS3LinkTool(BaseTool):
- `port1` (str): Port name of the first node (e.g., 'Ethernet0/0').
- `node_id2` (str): UUID of the second node.
- `port2` (str): Port name of the second node (e.g., 'Ethernet0/0').
- `link_type` (str, optional): Link type - "ethernet" (default) or "serial".
Note: Port names must match those from `gns3_topology_reader` tool.
Example Input:
@@ -79,6 +80,13 @@ class GNS3LinkTool(BaseTool):
"port1": "Ethernet0/0",
"node_id2": "uuid-of-node2",
"port2": "Ethernet0/0"
},
{
"node_id1": "uuid-of-node2",
"port1": "Serial0/0/0",
"node_id2": "uuid-of-node3",
"port2": "Serial0/0/0",
"link_type": "serial"
}
]
}
@@ -160,6 +168,7 @@ class GNS3LinkTool(BaseTool):
port1 = link_data.get("port1")
node_id2 = link_data.get("node_id2")
port2 = link_data.get("port2")
link_type = link_data.get("link_type")
# Validate link parameters
if not all([node_id1, port1, node_id2, port2]):
@@ -200,28 +209,29 @@ class GNS3LinkTool(BaseTool):
created_links.append({"error": error_msg})
continue
# Create the link via the shared REST handler
link_resp = create_link_handler(
{
"project_id": project_id,
"nodes": [
{
"node_id": node_id1,
"adapter_number": port1_info.get("adapter_number", 0),
"port_number": port1_info.get("port_number", 0),
"label": {"text": port1_info.get("short_name") or port1},
},
{
"node_id": node_id2,
"adapter_number": port2_info.get("adapter_number", 0),
"port_number": port2_info.get("port_number", 0),
"label": {"text": port2_info.get("short_name") or port2},
},
],
"fields": ["link_id"],
},
gns3_ctx,
)
# Create the link via the shared REST handler. link_type
# is passed only when set — the server defaults to ethernet.
link_params: dict[str, Any] = {
"project_id": project_id,
"nodes": [
{
"node_id": node_id1,
"adapter_number": port1_info.get("adapter_number", 0),
"port_number": port1_info.get("port_number", 0),
"label": {"text": port1_info.get("short_name") or port1},
},
{
"node_id": node_id2,
"adapter_number": port2_info.get("adapter_number", 0),
"port_number": port2_info.get("port_number", 0),
"label": {"text": port2_info.get("short_name") or port2},
},
],
"fields": ["link_id"],
}
if link_type:
link_params["link_type"] = link_type
link_resp = create_link_handler(link_params, gns3_ctx)
if isinstance(link_resp, list):
raise RuntimeError("Unexpected batch response when creating a single link")
if "error" in link_resp:
@@ -1,312 +0,0 @@
# 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 node creation tool for network topology building.
Provides functionality to create multiple nodes in GNS3 projects
using specified templates and coordinates through the GNS3 API.
"""
import json
import logging
from pprint import pprint
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
build_gns3_ctx,
create_node_handler,
)
# Configure logging
logger = logging.getLogger(__name__)
class GNS3CreateNodeTool(BaseTool):
"""
A LangChain tool to create multiple nodes in a GNS3 project
using specified templates and coordinates.
**Input:**
A JSON object with project_id and array of nodes with template_id,
x, y coordinates, and optional name.
Example input:
{
"project_id": "uuid-of-project",
"nodes": [
{
"template_id": "uuid-of-template",
"x": 100,
"y": -200,
"name": "R1"
},
{
"template_id": "uuid-of-template2",
"x": -200,
"y": 300,
"name": "R2"
}
]
}
**Output:**
A dictionary containing the creation results for all nodes.
Example output:
{
"project_id": "uuid-of-project",
"created_nodes": [
{
"node_id": "uuid-of-node1",
"name": "R1",
"status": "success"
},
{
"node_id": "uuid-of-node2",
"name": "R2",
"status": "success"
}
],
"total_nodes": 2,
"successful_nodes": 2,
"failed_nodes": 0
}
If error occurs during validation, returns dict with error message.
"""
name: str = "create_gns3_node"
description: str = """
Creates multiple nodes in a GNS3 project using templates and coordinates.
Input is a JSON object with project_id and array of nodes.
Each node requires: template_id, x, y. Optional: name (to set node name directly).
Example input:
{
"project_id": "uuid-of-project",
"nodes": [
{
"template_id": "uuid-of-template",
"x": 100,
"y": -200,
"name": "R1"
},
{
"template_id": "uuid-of-template2",
"x": -200,
"y": 300,
"name": "R2"
}
]
}
IMPORTANT: Ensure distance between any two nodes is greater than 250 px.
This spacing is necessary to display interface numbers clearly for better
topology visualization.
Returns a dictionary with creation results for all nodes, including
success/failure status.
If the operation fails during input validation, returns a dictionary with
an error message.
"""
def _run(
self,
tool_input: str,
run_manager: CallbackManagerForToolRun | None = None,
**kwargs: Any,
) -> dict[str, Any]:
"""
Creates nodes in a GNS3 project with templates and coordinates.
Args:
tool_input: A JSON string with project_id and an array of nodes.
run_manager: LangChain run manager (unused).
Returns:
dict: A dictionary with creation results for all nodes or an error
message.
"""
# Log received input
logger.info("Received input: %s", tool_input)
try:
# Parse input JSON
input_data = json.loads(tool_input)
project_id = input_data.get("project_id")
nodes = input_data.get("nodes", [])
# Validate input
if not project_id:
logger.error("Invalid input: Missing project_id.")
return {"error": "Missing project_id."}
if not isinstance(nodes, list) or len(nodes) == 0:
logger.error("Invalid input: nodes must be a non-empty array.")
return {"error": "nodes must be a non-empty array."}
# Validate each node in the array
for i, node_data in enumerate(nodes):
if not isinstance(node_data, dict):
logger.error("Invalid input: Node %d must be a dictionary.", i + 1)
return {"error": f"Node {i + 1} must be a dictionary."}
template_id = node_data.get("template_id")
x = node_data.get("x")
y = node_data.get("y")
name = node_data.get("name")
if not all(
[
template_id,
isinstance(x, (int, float)),
isinstance(y, (int, float)),
]
):
logger.error(
"Invalid input: Node %d missing or invalid template_id, x, or y.",
i + 1,
)
return {"error": f"Node {i + 1} missing or invalid template_id, x, or y."}
# Build handler context (JWT + server URL from request context)
logger.info("Connecting to GNS3 server...")
gns3_ctx = build_gns3_ctx()
if gns3_ctx is None:
logger.error("Failed to create GNS3 connector")
return {"error": "Failed to connect to GNS3 server. Please check your configuration."}
# Create nodes
logger.info("Creating %d nodes in project %s...", len(nodes), project_id)
results: list[dict[str, Any]] = []
for i, node_data in enumerate(nodes):
try:
template_id = node_data.get("template_id")
x = node_data.get("x")
y = node_data.get("y")
name = node_data.get("name")
logger.info(
"Creating node %d/%d with template %s at (%s, %s), name=%s...",
i + 1,
len(nodes),
template_id,
x,
y,
name,
)
# Create node via the shared REST handler
created = create_node_handler(
{
"project_id": project_id,
"template_id": template_id,
"x": x,
"y": y,
"name": name,
},
gns3_ctx,
)
if isinstance(created, list):
raise RuntimeError("Unexpected batch response when creating a single node")
if "error" in created:
raise RuntimeError(created["error"])
node_info = {
"node_id": created.get("node_id"),
"name": created.get("name"),
"status": "success",
}
results.append(node_info)
except Exception as e:
error_info = {
"error": f"Node {i + 1} creation failed: {e!s}",
"status": "failed",
}
results.append(error_info)
logger.error("Failed to create node %d: %s", i + 1, e)
# Continue with next node even if one fails
# Calculate summary statistics
successful_nodes = len([r for r in results if r.get("status") == "success"])
failed_nodes = len([r for r in results if r.get("status") == "failed"])
# Prepare final result
final_result = {
"project_id": project_id,
"created_nodes": results,
"total_nodes": len(nodes),
"successful_nodes": successful_nodes,
"failed_nodes": failed_nodes,
}
# Log the final result
logger.info(
"Node creation completed: %d successful, %d failed, %d total.",
successful_nodes,
failed_nodes,
len(nodes),
)
# Return JSON-formatted result
return final_result
except json.JSONDecodeError as e:
logger.error("Invalid JSON input: %s", e)
return {"error": f"Invalid JSON input: {e}"}
except Exception as e:
logger.error("Failed to process node creation request: %s", e)
return {"error": f"Failed to process node creation request: {e!s}"}
if __name__ == "__main__":
# Test the tool locally with multiple nodes
test_input = json.dumps(
{
# TODO: Replace with actual project UUID
"project_id": "d7fc094c-685e-4db1-ac11-5e33a1b2e066",
"nodes": [
{
# TODO: Replace with actual template UUID
"template_id": "b923a635-b7cc-4cb5-9a86-9357e04c02f7",
"x": 100,
"y": -200,
"name": "R1",
},
{
# TODO: Replace with actual template UUID
"template_id": "b923a635-b7cc-4cb5-9a86-9357e04c02f7",
"x": 200,
"y": -300,
"name": "R2",
},
],
}
)
tool = GNS3CreateNodeTool()
result = tool._run(test_input)
pprint(result)
@@ -1,178 +0,0 @@
# 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 template retrieval tool for device discovery.
Provides functionality to retrieve all available device templates
from a GNS3 server, including template names, IDs, and types.
Filters out built-in utility templates that are not useful for network labs.
"""
import json
import logging
from pprint import pprint
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client import get_gns3_connector
# Configure logging
logger = logging.getLogger(__name__)
# Built-in templates to filter out (utility templates, not actual network devices)
FILTERED_TEMPLATES = {
"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
}
def should_filter_template(template: dict[str, Any]) -> bool:
"""
Determine whether a template should be filtered out.
Filter condition:
1. Template type is in the filter list (exact match)
Args:
template: Template dictionary
Returns:
True if template should be filtered, False if it should be kept
"""
template_type = template.get("template_type", "")
# Check if template_type is in filter list
# This is the most reliable way to identify built-in utility templates
return template_type in FILTERED_TEMPLATES
class GNS3TemplateTool(BaseTool):
"""
LangChain tool to retrieve available device templates from GNS3 server.
Connects to GNS3 server and extracts name, template_id, and template_type.
Filters out built-in utility templates that are not useful for network labs.
**Input:**
No input required. Connects to GNS3 server at default URL.
**Output:**
Dict with list of dicts (name, template_id, template_type).
If error, returns dict with error message.
**Filtered Templates:**
The following built-in utility templates are excluded:
- ATM switch
- Cloud
- Ethernet hub
- Ethernet switch (built-in)
- Frame Relay switch
- NAT
"""
name: str = "get_gns3_templates"
description: str = """
Retrieves available device templates from GNS3 server for network labs.
Returns dict with list of dicts (name, template_id, template_type).
Filters out built-in utility templates (ATM switch, Cloud, Ethernet hub,
Ethernet switch, Frame Relay switch, NAT) as they are not useful for
network device configuration.
No input required.
If connection fails, returns dict with error message.
"""
def _run(
self,
tool_input: str = "",
run_manager: CallbackManagerForToolRun | None = None,
) -> dict[str, Any]:
"""
Connects to GNS3 server and retrieves available device templates.
Args:
tool_input: Optional input (not used).
run_manager: LangChain run manager (unused).
Returns:
dict: Dict with templates list or error message.
"""
try:
# Initialize Gns3Connector using factory function
logger.info("Connecting to GNS3 server...")
gns3_server = get_gns3_connector()
if gns3_server is None:
logger.error("Failed to create GNS3 connector")
return {"error": ("Failed to connect to GNS3 server. Please check your configuration.")}
# Retrieve all available templates
templates = gns3_server.http_call("get", f"{gns3_server.base_url}/templates").json()
# Filter out utility templates and extract relevant info
template_info = []
filtered_count = 0
for template in templates:
# Check if template should be filtered
if should_filter_template(template):
filtered_count += 1
logger.debug("Filtered out template: %s", template.get("name"))
continue
# Extract name, template_id, and template_type
template_info.append(
{
"name": template.get("name", "N/A"),
"template_id": template.get("template_id", "N/A"),
"template_type": template.get("template_type", "N/A"),
}
)
# Return JSON-formatted result with full logging
result = {"templates": template_info}
logger.info(
"Template retrieval completed. Total: %d, Filtered: %d, Remaining: %d",
len(templates),
filtered_count,
len(template_info),
)
logger.debug("Result: %s", json.dumps(result, indent=2, ensure_ascii=False))
return result
except Exception as e:
logger.error("Failed to connect to GNS3 server or retrieve templates: %s", e)
return {"error": f"Failed to retrieve templates: {e!s}"}
if __name__ == "__main__":
# Test's tool locally
tool = GNS3TemplateTool()
result = tool._run("")
pprint(result)
@@ -1,487 +0,0 @@
# 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 packet filter management tool for network simulation.
Provides functionality to manage packet filters on GNS3 links,
including latency, packet loss, corruption, and BPF filtering.
"""
import json
import logging
import subprocess
from pprint import pprint
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
available_filters_handler,
build_gns3_ctx,
get_link_handler,
update_link_handler,
)
# Configure logging
logger = logging.getLogger(__name__)
class GNS3PacketFilterTool(BaseTool):
"""
A LangChain tool to manage packet filters on GNS3 links.
Supports getting available filters, setting filters, and clearing filters
on network links to simulate various network conditions.
**Input:**
A JSON object with project_id, link_id, action, and optional filter parameters.
Note: show_filters_icon is automatically set to false by default to hide the filter
icon in the GNS3 Web UI.
Example input for getting available filters:
{
"project_id": "uuid-of-project",
"link_id": "uuid-of-link",
"action": "get_available"
}
Example input for setting filters:
{
"project_id": "uuid-of-project",
"link_id": "uuid-of-link",
"action": "set",
"filters": {
"delay": [100, 10],
"packet_loss": [5]
},
"show_filters_icon": false
}
Example input for getting current filters:
{
"project_id": "uuid-of-project",
"link_id": "uuid-of-link",
"action": "get"
}
Example input for clearing filters:
{
"project_id": "uuid-of-project",
"link_id": "uuid-of-link",
"action": "clear"
}
**Output:**
A dictionary containing the action result.
For "get_available": returns list of available filter types
For "set": returns updated link information with applied filters
For "get": returns current filters configured on the link
For "clear": returns confirmation that filters were cleared
"""
name: str = "manage_gns3_packet_filter"
description: str = """
Manages packet filters on GNS3 links to inject network faults and simulate network conditions.
This tool is primarily used for fault injection scenarios to create realistic network problems
for troubleshooting practice, such as latency, packet loss, and corruption.
By default, the filter icon in the GNS3 Web UI is hidden (show_filters_icon=false) to avoid
visual clutter when injecting faults for troubleshooting exercises.
Supported actions:
- "get_available": Get list of available filter types for the link
- "set": Set packet filters on the link to inject network faults
- "get": Get current filters configured on the link
Common filter types for fault injection:
- "frequency_drop": Drop every Nth packet (parameter: frequency, -1 to 32767)
- "packet_loss": Packet loss percentage (parameters: chance 0-100, optional correlation)
- "delay": Delay in ms with optional jitter and distribution (parameters: latency 0-32767,
jitter 0-32767, distribution uniform|normal|pareto|paretonormal)
- "corrupt": Packet corruption percentage (parameter: chance, 0-100)
- "bpf": Berkeley Packet Filter (parameter: filter expression text)
- "rate": Bandwidth cap, tc-style string like "512kbit" (kernel links only)
- "reorder": Packet reordering (parameters: percentage, correlation, gap; needs delay;
kernel links only)
- "gemodel": Gilbert-Elliot bursty loss (parameters: p good-to-bad transition, r bad-to-good
transition, 1-h loss in the bad state; mean loss = p/(p+r)*(1-h); kernel links only)
- "duplicate": Packet duplication percentage (kernel links only)
- "seed": Reproducible netem random draws (kernel links only)
- "limit": Impairment queue depth in packets (kernel links only)
- "quota": Byte cap — after the quota, drop with a chance (parameters: bytes, chance;
kernel links only)
- "window_drop": Time-window outage (parameters: start_ms, outage_ms, chance, optional
period_ms, jitter_ms; start is relative to when the filter is applied — any filter
update restarts the schedule; kernel links only)
Filter availability depends on the link (kernel-only types need kernel-datapath links
and compute support): always check with action "get_available" before setting.
Input is a JSON object with:
- project_id (str): GNS3 project UUID
- link_id (str): GNS3 link UUID
- action (str): One of "get_available", "set", "get", "clear"
- filters (dict, optional): Filter configuration for "set" action
Example for getting available filters:
{
"project_id": "uuid-of-project",
"link_id": "uuid-of-link",
"action": "get_available"
}
Example for setting delay and packet loss:
{
"project_id": "uuid-of-project",
"link_id": "uuid-of-link",
"action": "set",
"filters": {
"delay": [100, 10],
"packet_loss": [5]
}
}
Returns a dictionary with action result, filter information, or error message.
"""
def _run(
self,
tool_input: str,
run_manager: CallbackManagerForToolRun | None = None,
**kwargs: Any,
) -> dict[str, Any]:
"""
Manages packet filters on a GNS3 link.
Args:
tool_input: A JSON string with project_id, link_id, action, and optional filters.
run_manager: LangChain run manager (unused).
Returns:
dict: A dictionary with action result or an error message.
"""
# Log received input
logger.info("Received input: %s", tool_input)
try:
# Parse input JSON
input_data = json.loads(tool_input)
project_id = input_data.get("project_id")
link_id = input_data.get("link_id")
action = input_data.get("action")
show_filters_icon = input_data.get("show_filters_icon", False)
# Validate required fields
if not project_id:
logger.error("Invalid input: Missing project_id.")
return {"error": "Missing project_id."}
if not link_id:
logger.error("Invalid input: Missing link_id.")
return {"error": "Missing link_id."}
if not action:
logger.error("Invalid input: Missing action.")
return {"error": "Missing action."}
# Validate action
valid_actions = ["get_available", "set", "get", "clear"]
if action not in valid_actions:
logger.error("Invalid action: %s. Must be one of %s", action, valid_actions)
return {"error": f"Invalid action: {action}. Must be one of {valid_actions}"}
# Validate filters for "set" action
if action == "set":
filters = input_data.get("filters")
if not filters or not isinstance(filters, dict):
logger.error("Invalid input: 'set' action requires 'filters' dict.")
return {"error": "'set' action requires 'filters' dict with filter configuration."}
# Build handler context (JWT + server URL from request context)
logger.info("Connecting to GNS3 server...")
gns3_ctx = build_gns3_ctx()
if gns3_ctx is None:
logger.error("Failed to create GNS3 connector")
return {"error": "Failed to connect to GNS3 server. Please check your configuration."}
# Execute action
logger.info("Processing packet filter action '%s' for link %s...", action, link_id)
if action == "get_available":
result = self._get_available_filters(gns3_ctx, project_id, link_id)
elif action == "set":
filters = input_data.get("filters", {})
result = self._set_filters(gns3_ctx, project_id, link_id, filters, show_filters_icon)
elif action == "get":
result = self._get_filters(gns3_ctx, project_id, link_id)
elif action == "clear":
result = self._clear_filters(gns3_ctx, project_id, link_id, show_filters_icon)
else:
result = {"error": f"Unknown action: {action}"}
# Log result
logger.info("Packet filter action '%s' completed successfully.", action)
return result
except json.JSONDecodeError as e:
logger.error("Invalid JSON input: %s", e)
return {"error": f"Invalid JSON input: {e}"}
except Exception as e:
logger.error("Failed to process packet filter request: %s", e)
return {"error": f"Failed to process packet filter request: {e!s}"}
def _get_available_filters(self, gns3_ctx: dict, project_id: str, link_id: str) -> dict[str, Any]:
"""Get available filter types for the link."""
try:
filters = available_filters_handler({"project_id": project_id, "link_id": link_id}, gns3_ctx)
if "error" in filters:
raise RuntimeError(filters["error"])
logger.info("Retrieved %d available filter types.", len(filters))
return {
"action": "get_available",
"link_id": link_id,
"available_filters": filters,
"count": len(filters),
"status": "success",
}
except Exception as e:
logger.error("Failed to get available filters: %s", e)
return {
"action": "get_available",
"link_id": link_id,
"error": f"Failed to get available filters: {e!s}",
"status": "failed",
}
def _validate_bpf_syntax(self, bpf_expression: str) -> dict[str, Any]:
"""
Validate BPF filter expression syntax using tshark.
Args:
bpf_expression: BPF filter expression to validate
Returns:
dict with 'valid' (bool) and 'error' (str or None) keys
"""
try:
# Use tshark to validate BPF syntax with 1 second timeout
# Use -i lo (loopback) to avoid "(null)" interface in error messages
result = subprocess.run(
["tshark", "-f", bpf_expression, "-i", "lo"],
timeout=1,
capture_output=True,
text=True,
)
# Check if output contains "Invalid" indicating syntax error
if "Invalid" in result.stdout or "Invalid" in result.stderr:
error_lines: list[str] = []
if "Invalid" in result.stderr:
error_lines.extend(line for line in result.stderr.split("\n") if "Invalid" in line)
if "Invalid" in result.stdout:
error_lines.extend(line for line in result.stdout.split("\n") if "Invalid" in line)
# Strip interface suffix (e.g., "for interface 'lo'") for cleaner error
error_msg_parts = []
for line in error_lines:
clean = line.split(" for interface")[0].strip()
if clean:
error_msg_parts.append(clean)
error_msg = " ".join(error_msg_parts) if error_msg_parts else "Invalid BPF syntax"
logger.warning("BPF syntax validation failed: %s", error_msg)
return {"valid": False, "error": error_msg}
logger.info("BPF syntax validation passed")
return {"valid": True, "error": None}
except subprocess.TimeoutExpired:
# Timeout is expected behavior - tshark waits for traffic
# No "Invalid" in output means syntax is correct
logger.info("BPF syntax validation passed (timeout expected)")
return {"valid": True, "error": None}
except FileNotFoundError:
# tshark not installed - skip validation
logger.warning("tshark not found, skipping BPF syntax validation. Install tshark to enable BPF validation.")
return {"valid": True, "error": None}
except Exception as e:
logger.error("Unexpected error during BPF validation: %s", e)
return {"valid": False, "error": f"BPF validation error: {e!s}"}
def _set_filters(
self,
gns3_ctx: dict,
project_id: str,
link_id: str,
filters: dict[str, Any],
show_filters_icon: bool = False,
) -> dict[str, Any]:
"""Set packet filters on the link."""
try:
# Validate BPF syntax if BPF filter is present
if "bpf" in filters:
bpf_filters = filters["bpf"]
if isinstance(bpf_filters, list):
# Validate each BPF expression
for idx, bpf_expr in enumerate(bpf_filters):
if isinstance(bpf_expr, str):
validation = self._validate_bpf_syntax(bpf_expr)
if not validation["valid"]:
return {
"action": "set",
"link_id": link_id,
"error": f"BPF syntax error at index {idx}: {validation['error']}",
"status": "failed",
}
elif isinstance(bpf_filters, str):
# Single BPF expression
validation = self._validate_bpf_syntax(bpf_filters)
if not validation["valid"]:
return {
"action": "set",
"link_id": link_id,
"error": f"BPF syntax error: {validation['error']}",
"status": "failed",
}
# Update filters — the PUT response is the updated link
updated = update_link_handler(
{
"project_id": project_id,
"link_id": link_id,
"kwargs": {
"filters": filters,
"show_filters_icon": show_filters_icon,
},
},
gns3_ctx,
)
if "error" in updated:
raise RuntimeError(updated["error"])
logger.info("Successfully set filters on link %s", link_id)
return {
"action": "set",
"link_id": link_id,
"filters": updated.get("filters"),
"status": "success",
"message": "Filters applied successfully",
}
except Exception as e:
logger.error("Failed to set filters: %s", e)
return {
"action": "set",
"link_id": link_id,
"error": f"Failed to set filters: {e!s}",
"status": "failed",
}
def _get_filters(self, gns3_ctx: dict, project_id: str, link_id: str) -> dict[str, Any]:
"""Get current filters configured on the link."""
try:
link = get_link_handler({"project_id": project_id, "link_id": link_id}, gns3_ctx)
if "error" in link:
raise RuntimeError(link["error"])
logger.info("Retrieved current filters for link %s", link_id)
return {
"action": "get",
"link_id": link_id,
"filters": link.get("filters"),
"status": "success",
}
except Exception as e:
logger.error("Failed to get filters: %s", e)
return {
"action": "get",
"link_id": link_id,
"error": f"Failed to get filters: {e!s}",
"status": "failed",
}
def _clear_filters(
self,
gns3_ctx: dict,
project_id: str,
link_id: str,
show_filters_icon: bool = False,
) -> dict[str, Any]:
"""Clear all filters from the link."""
try:
# Clear filters by setting an empty dict — the PUT response
# is the updated link
updated = update_link_handler(
{
"project_id": project_id,
"link_id": link_id,
"kwargs": {
"filters": {},
"show_filters_icon": show_filters_icon,
},
},
gns3_ctx,
)
if "error" in updated:
raise RuntimeError(updated["error"])
logger.info("Successfully cleared filters on link %s", link_id)
return {
"action": "clear",
"link_id": link_id,
"filters": updated.get("filters"),
"status": "success",
"message": "Filters cleared successfully",
}
except Exception as e:
logger.error("Failed to clear filters: %s", e)
return {
"action": "clear",
"link_id": link_id,
"error": f"Failed to clear filters: {e!s}",
"status": "failed",
}
if __name__ == "__main__":
# Test the tool locally
# TODO: Replace with actual project and link UUIDs
test_input = json.dumps(
{
"project_id": "d7fc094c-685e-4db1-ac11-5e33a1b2e066",
"link_id": "link-uuid-here",
"action": "get_available",
}
)
tool = GNS3PacketFilterTool()
result = tool._run(test_input)
pprint(result)
@@ -1,242 +0,0 @@
# 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 node startup tool for network device activation.
Sends start commands and returns immediately — it never blocks on a fixed
boot timer. A failed start command (e.g. a 409 from the compute) is
reported in the same round-trip instead of after a two-minute progress
bar. Use the wait_seconds tool between this and any status check to give
nodes time to boot.
"""
import json
import logging
from pprint import pprint
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
build_gns3_ctx,
get_nodes_handler,
start_node_handler,
)
# Configure logging
logger = logging.getLogger(__name__)
class GNS3StartNodeTool(BaseTool):
"""
A LangChain tool to start one or multiple nodes in a GNS3 project.
Sends the start commands in a parallel batch and returns each node's
status immediately — nodes keep booting in the background. It does NOT
wait for boot completion: follow up with the wait_seconds tool and a
status/topology check to confirm nodes actually came up.
**Input**:
A JSON object with project_id and node_ids (list of node IDs).
Example:
{
"project_id": "uuid-of-project",
"node_ids": ["uuid-of-node-1", "uuid-of-node-2"]
}
**Output**:
A dict with nodes' details immediately after sending start commands:
{
"project_id": "...",
"total_nodes": 2,
"successful": 2,
"failed": 0,
"nodes": [
{"node_id": "...", "name": "...", "status": "started"},
{"node_id": "...", "name": "...", "status": "error", "error": "..."}
],
"note": "Start commands sent. Nodes are booting in background."
}
"""
name: str = "start_gns3_node"
description: str = """
Starts one or multiple nodes in a GNS3 project and returns immediately
(nodes boot in the background; start failures are reported right away).
After calling this, use wait_seconds (VPCS/IOU ~15-30s, IOS routers
~60-120s, heavy NOS images 2-5min) before checking node status.
Input: JSON with project_id and node_ids (list of node IDs).
Returns: Dict with per-node start command results.
"""
def _run(
self,
tool_input: str,
run_manager: CallbackManagerForToolRun | None = None,
) -> dict[str, Any]:
try:
# Parse input JSON
input_data = json.loads(tool_input)
project_id = input_data.get("project_id")
node_ids = input_data.get("node_ids")
# Validate input
if not project_id or not node_ids:
logger.error("Missing required fields: project_id or node_ids.")
return {"error": "Missing required fields: project_id and node_ids."}
if not isinstance(node_ids, list):
logger.error("node_ids must be a list.")
return {"error": "node_ids must be a list."}
# Build handler context (JWT + server URL from request context)
logger.info("Connecting to GNS3 server...")
gns3_ctx = build_gns3_ctx()
if gns3_ctx is None:
logger.error("Failed to create GNS3 connector")
return {"error": "Failed to connect to GNS3 server. Please check your configuration."}
# Verify nodes exist and capture pre-start info (one call)
listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
if "error" in listing:
return {"error": listing["error"]}
nodes_by_id = {n["node_id"]: n for n in listing["nodes"]}
# Send start commands for all nodes (parallel batch)
logger.info(
"Sending start commands for %d nodes in project %s...",
len(node_ids),
project_id,
)
results = []
known_ids = [nid for nid in node_ids if nid in nodes_by_id]
start_results = start_node_handler({"project_id": project_id, "node_ids": known_ids}, gns3_ctx)
start_errors = (
{r["node_id"]: r.get("error") for r in start_results if r.get("status") == "error"}
if isinstance(start_results, list)
else {}
)
# Get immediate status (likely 'starting' or 'stopped') — one call
listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
if "error" in listing:
return {"error": listing["error"]}
after_by_id = {n["node_id"]: n for n in listing["nodes"]}
for node_id in node_ids:
if node_id not in nodes_by_id:
logger.error("Node %s not found in project %s", node_id, project_id)
results.append(
{
"node_id": node_id,
"name": "N/A",
"status": "error",
"error": "Node not found",
}
)
continue
if node_id in start_errors:
logger.error(
"Failed to start node %s: %s",
node_id,
start_errors[node_id],
)
results.append(
{
"node_id": node_id,
"name": nodes_by_id[node_id].get("name") or "N/A",
"status": "error",
"error": start_errors[node_id],
}
)
continue
logger.info(
"Start command sent for node %s (%s)",
node_id,
nodes_by_id[node_id].get("name"),
)
current = after_by_id.get(node_id, nodes_by_id[node_id])
results.append(
{
"node_id": node_id,
"name": current.get("name") or "N/A",
"status": current.get("status") or "unknown",
}
)
# Analyze results (count based on successful command sending)
successful_nodes = [r for r in results if r.get("status") != "error"]
failed_nodes = [r for r in results if r.get("status") == "error"]
# Construct final response
response = {
"project_id": project_id,
"total_nodes": len(node_ids),
"successful": len(successful_nodes),
"failed": len(failed_nodes),
"nodes": results,
"note": (
"Start commands sent. Nodes are booting in background. Use wait_seconds, then check node status."
),
}
logger.info(
"Quick start commands sent: %d successful, %d failed",
len(successful_nodes),
len(failed_nodes),
)
return response
except json.JSONDecodeError as e:
logger.error("Invalid JSON input: %s", e)
return {"error": f"Invalid JSON input: {e}"}
except Exception as e:
logger.error("Failed to start nodes: %s", e)
return {"error": f"Failed to start nodes: {e!s}"}
# Backward-compat alias: the waiting variant was removed; both names now
# point at the immediate-return tool.
GNS3StartNodeQuickTool = GNS3StartNodeTool
if __name__ == "__main__":
# Test with single node
print("=== Testing single node startup ===")
test_input_single = json.dumps(
{
"project_id": "<PROJECT_UUID>", # Replace with actual project UUID
"node_ids": ["fbeda109-9a74-4d8c-a749-cc3847911a90"], # Replace with actual node UUID
}
)
tool = GNS3StartNodeTool()
result_single = tool._run(test_input_single)
pprint(result_single)
@@ -1,231 +0,0 @@
# 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 node stop tool for network device shutdown.
Provides functionality to stop one or multiple nodes in GNS3 projects.
"""
import json
import logging
from pprint import pprint
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
build_gns3_ctx,
get_nodes_handler,
stop_node_handler,
)
# Configure logging
logger = logging.getLogger(__name__)
class GNS3StopNodeTool(BaseTool):
"""
A LangChain tool to stop one or multiple nodes in a GNS3 project.
**Input**:
A JSON object with project_id and node_ids (list of node IDs).
Example:
{
"project_id": "uuid-of-project",
"node_ids": ["uuid-of-node-1", "uuid-of-node-2"]
}
**Output**:
A dictionary with all nodes' details:
{
"project_id": "...",
"total_nodes": 2,
"successful": 2,
"failed": 0,
"nodes": [
{"node_id": "...", "name": "...", "status": "stopped"},
{"node_id": "...", "name": "...", "status": "stopped"}
]
}
"""
name: str = "stop_gns3_node"
description: str = """
Stops one or multiple nodes in a GNS3 project.
Input: JSON with project_id and node_ids (list of node IDs).
Returns: A dict with all nodes' details (success/failure status).
"""
def _run(
self,
tool_input: str,
run_manager: CallbackManagerForToolRun | None = None,
) -> dict[str, Any]:
try:
# Parse input JSON
input_data = json.loads(tool_input)
project_id = input_data.get("project_id")
node_ids = input_data.get("node_ids")
# Validate input
if not project_id or not node_ids:
logger.error("Missing required fields: project_id or node_ids.")
return {"error": "Missing required fields: project_id and node_ids."}
if not isinstance(node_ids, list):
logger.error("node_ids must be a list.")
return {"error": "node_ids must be a list."}
# Build handler context (JWT + server URL from request context)
logger.info("Connecting to GNS3 server...")
gns3_ctx = build_gns3_ctx()
if gns3_ctx is None:
logger.error("Failed to create GNS3 connector")
return {"error": "Failed to connect to GNS3 server. Please check your configuration."}
# Verify nodes exist and capture names (one call)
listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
if "error" in listing:
return {"error": listing["error"]}
nodes_by_id = {n["node_id"]: n for n in listing["nodes"]}
# Stop all nodes (parallel batch) and collect results
logger.info(
"Stopping %d nodes in project %s...",
len(node_ids),
project_id,
)
results = []
known_ids = [nid for nid in node_ids if nid in nodes_by_id]
stop_results = stop_node_handler({"project_id": project_id, "node_ids": known_ids}, gns3_ctx)
stop_errors = (
{r["node_id"]: r.get("error") for r in stop_results if r.get("status") == "error"}
if isinstance(stop_results, list)
else {}
)
# Get updated status — one call
listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
if "error" in listing:
return {"error": listing["error"]}
after_by_id = {n["node_id"]: n for n in listing["nodes"]}
for node_id in node_ids:
if node_id not in nodes_by_id:
logger.error("Node %s not found in project %s", node_id, project_id)
results.append(
{
"node_id": node_id,
"name": "N/A",
"status": "error",
"error": "Node not found",
}
)
elif node_id in stop_errors:
logger.error("Failed to stop node %s: %s", node_id, stop_errors[node_id])
results.append(
{
"node_id": node_id,
"name": nodes_by_id[node_id].get("name") or "N/A",
"status": "error",
"error": stop_errors[node_id],
}
)
else:
logger.info(
"Stop command sent for node %s (%s)",
node_id,
nodes_by_id[node_id].get("name"),
)
current = after_by_id.get(node_id, nodes_by_id[node_id])
results.append(
{
"node_id": node_id,
"name": current.get("name") or "N/A",
"status": current.get("status") or "unknown",
}
)
# Analyze results
successful_nodes = [r for r in results if r.get("status") != "error"]
failed_nodes = [r for r in results if r.get("status") == "error"]
# Construct final response
response = {
"project_id": project_id,
"total_nodes": len(node_ids),
"successful": len(successful_nodes),
"failed": len(failed_nodes),
"nodes": results,
}
logger.info(
"Stop operation completed: %d successful, %d failed",
len(successful_nodes),
len(failed_nodes),
)
return response
except json.JSONDecodeError as e:
logger.error("Invalid JSON input: %s", e)
return {"error": f"Invalid JSON input: {e}"}
except Exception as e:
logger.error("Failed to stop nodes: %s", e)
return {"error": f"Failed to stop nodes: {e!s}"}
if __name__ == "__main__":
# Test with single node
print("=== Testing single node stop ===")
test_input_single = json.dumps(
{
"project_id": "<PROJECT_UUID>", # Replace with actual project UUID
"node_ids": ["fbeda109-9a74-4d8c-a749-cc3847911a90"], # Replace with actual node UUID
}
)
tool = GNS3StopNodeTool()
result_single = tool._run(test_input_single)
pprint(result_single)
# Test with multiple nodes
print("\n=== Testing multiple nodes stop ===")
test_input_multiple = json.dumps(
{
"project_id": "<PROJECT_UUID>", # Replace with actual project UUID
"node_ids": [
"fbeda109-9a74-4d8c-a749-cc3847911a90",
# Replace with actual node UUIDs
"another-node-uuid-here",
"third-node-uuid-here",
],
}
)
result_multiple = tool._run(test_input_multiple)
pprint(result_multiple)
@@ -1,242 +0,0 @@
# 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 node suspend tool for pausing network devices.
Provides functionality to suspend one or multiple nodes in GNS3 projects.
Suspended nodes preserve their state in memory and can be quickly resumed.
"""
import json
import logging
from pprint import pprint
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
build_gns3_ctx,
get_nodes_handler,
suspend_node_handler,
)
# Configure logging
logger = logging.getLogger(__name__)
class GNS3SuspendNodeTool(BaseTool):
"""
A LangChain tool to suspend one or multiple nodes in a GNS3 project.
**Input**:
A JSON object with project_id and node_ids (list of node IDs).
Example:
{
"project_id": "uuid-of-project",
"node_ids": ["uuid-of-node-1", "uuid-of-node-2"]
}
**Output**:
A dictionary with all nodes' details:
{
"project_id": "...",
"total_nodes": 2,
"successful": 2,
"failed": 0,
"nodes": [
{"node_id": "...", "name": "...", "status": "suspended"},
{"node_id": "...", "name": "...", "status": "suspended"}
]
}
**Note**: Suspended nodes preserve their state in memory and can be quickly
resumed. Use this when you want to pause a lab and continue later.
"""
name: str = "suspend_gns3_node"
description: str = """
Suspends one or multiple nodes in a GNS3 project.
Suspended nodes preserve their state and can be quickly resumed.
Use this to pause a lab temporarily and continue later.
Input: JSON with project_id and node_ids (list of node IDs).
Returns: A dict with all nodes' details (success/failure status).
"""
def _run(
self,
tool_input: str,
run_manager: CallbackManagerForToolRun | None = None,
) -> dict[str, Any]:
try:
# Parse input JSON
input_data = json.loads(tool_input)
project_id = input_data.get("project_id")
node_ids = input_data.get("node_ids")
# Validate input
if not project_id or not node_ids:
logger.error("Missing required fields: project_id or node_ids.")
return {"error": "Missing required fields: project_id and node_ids."}
if not isinstance(node_ids, list):
logger.error("node_ids must be a list.")
return {"error": "node_ids must be a list."}
# Build handler context (JWT + server URL from request context)
logger.info("Connecting to GNS3 server...")
gns3_ctx = build_gns3_ctx()
if gns3_ctx is None:
logger.error("Failed to create GNS3 connector")
return {"error": "Failed to connect to GNS3 server. Please check your configuration."}
# Verify nodes exist and capture names (one call)
listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
if "error" in listing:
return {"error": listing["error"]}
nodes_by_id = {n["node_id"]: n for n in listing["nodes"]}
# Suspend all nodes (parallel batch) and collect results
logger.info(
"Suspending %d nodes in project %s...",
len(node_ids),
project_id,
)
results = []
known_ids = [nid for nid in node_ids if nid in nodes_by_id]
suspend_results = suspend_node_handler({"project_id": project_id, "node_ids": known_ids}, gns3_ctx)
suspend_errors = (
{r["node_id"]: r.get("error") for r in suspend_results if r.get("status") == "error"}
if isinstance(suspend_results, list)
else {}
)
# Get updated status — one call
listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
if "error" in listing:
return {"error": listing["error"]}
after_by_id = {n["node_id"]: n for n in listing["nodes"]}
for node_id in node_ids:
if node_id not in nodes_by_id:
logger.error("Node %s not found in project %s", node_id, project_id)
results.append(
{
"node_id": node_id,
"name": "N/A",
"status": "error",
"error": "Node not found",
}
)
elif node_id in suspend_errors:
logger.error(
"Failed to suspend node %s: %s",
node_id,
suspend_errors[node_id],
)
results.append(
{
"node_id": node_id,
"name": nodes_by_id[node_id].get("name") or "N/A",
"status": "error",
"error": suspend_errors[node_id],
}
)
else:
logger.info(
"Suspend command sent for node %s (%s)",
node_id,
nodes_by_id[node_id].get("name"),
)
current = after_by_id.get(node_id, nodes_by_id[node_id])
results.append(
{
"node_id": node_id,
"name": current.get("name") or "N/A",
"status": current.get("status") or "unknown",
}
)
# Analyze results
successful_nodes = [r for r in results if r.get("status") != "error"]
failed_nodes = [r for r in results if r.get("status") == "error"]
# Construct final response
response = {
"project_id": project_id,
"total_nodes": len(node_ids),
"successful": len(successful_nodes),
"failed": len(failed_nodes),
"nodes": results,
"note": ("Suspended nodes preserve their state in memory. Use resume to continue where you left off."),
}
logger.info(
"Suspend operation completed: %d successful, %d failed",
len(successful_nodes),
len(failed_nodes),
)
return response
except json.JSONDecodeError as e:
logger.error("Invalid JSON input: %s", e)
return {"error": f"Invalid JSON input: {e}"}
except Exception as e:
logger.error("Failed to suspend nodes: %s", e)
return {"error": f"Failed to suspend nodes: {e!s}"}
if __name__ == "__main__":
# Test with single node
print("=== Testing single node suspend ===")
test_input_single = json.dumps(
{
"project_id": "<PROJECT_UUID>", # Replace with actual project UUID
"node_ids": ["fbeda109-9a74-4d8c-a749-cc3847911a90"], # Replace with actual node UUID
}
)
tool = GNS3SuspendNodeTool()
result_single = tool._run(test_input_single)
pprint(result_single)
# Test with multiple nodes
print("\n=== Testing multiple nodes suspend ===")
test_input_multiple = json.dumps(
{
"project_id": "<PROJECT_UUID>", # Replace with actual project UUID
"node_ids": [
"fbeda109-9a74-4d8c-a749-cc3847911a90",
# Replace with actual node UUIDs
"another-node-uuid-here",
"third-node-uuid-here",
],
}
)
result_multiple = tool._run(test_input_multiple)
pprint(result_multiple)
@@ -1,281 +0,0 @@
# 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 node name update tool for renaming network devices.
Provides functionality to update the name of one or multiple nodes
in GNS3 projects.
"""
import json
import logging
from pprint import pprint
from typing import Any
from langchain.tools import BaseTool
from langchain_core.callbacks import CallbackManagerForToolRun
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
build_gns3_ctx,
get_nodes_handler,
update_node_handler,
)
# Configure logging
logger = logging.getLogger(__name__)
class GNS3UpdateNodeNameTool(BaseTool):
"""
A LangChain tool to update the name of one or multiple nodes
in a GNS3 project.
**Input**:
A JSON object with project_id and nodes array containing
node_id and new_name.
Example:
{
"project_id": "uuid-of-project",
"nodes": [
{"node_id": "uuid-of-node-1", "new_name": "Router1"},
{"node_id": "uuid-of-node-2", "new_name": "Switch1"}
]
}
**Output**:
A dictionary with all nodes' update results:
{
"project_id": "...",
"total_nodes": 2,
"successful": 2,
"failed": 0,
"nodes": [
{
"node_id": "...",
"old_name": "...",
"new_name": "...",
"status": "success"
},
{
"node_id": "...",
"old_name": "...",
"new_name": "...",
"status": "success"
}
]
}
"""
name: str = "update_gns3_node_name"
description: str = """
Updates the name of one or multiple nodes in a GNS3 project.
Input: JSON with project_id and nodes array.
Each node must have node_id and new_name.
Returns: A dictionary with all nodes' update results
including success/failure status.
"""
def _run(
self,
tool_input: str,
run_manager: CallbackManagerForToolRun | None = None,
) -> dict[str, Any]:
try:
# Parse input JSON
input_data = json.loads(tool_input)
project_id = input_data.get("project_id")
nodes = input_data.get("nodes", [])
# Validate input
if not project_id:
logger.error("Missing required field: project_id.")
return {"error": "Missing required field: project_id."}
if not isinstance(nodes, list) or len(nodes) == 0:
logger.error("nodes must be a non-empty list.")
return {"error": "nodes must be a non-empty list."}
# Validate each node entry
for i, node_data in enumerate(nodes):
if not isinstance(node_data, dict):
logger.error("Node %d must be a dictionary.", i + 1)
return {"error": f"Node {i + 1} must be a dictionary."}
if "node_id" not in node_data or "new_name" not in node_data:
logger.error("Node %d missing node_id or new_name.", i + 1)
return {"error": f"Node {i + 1} missing node_id or new_name."}
# Build handler context (JWT + server URL from request context)
logger.info("Connecting to GNS3 server...")
gns3_ctx = build_gns3_ctx()
if gns3_ctx is None:
logger.error("Failed to create GNS3 connector")
return {"error": "Failed to connect to GNS3 server. Please check your configuration."}
# Fetch current node names in one call (old names + existence)
listing = get_nodes_handler({"project_id": project_id}, gns3_ctx)
if "error" in listing:
return {"error": listing["error"]}
nodes_by_id = {n["node_id"]: n for n in listing["nodes"]}
# Update node names
logger.info(
"Updating names for %d nodes in project %s...",
len(nodes),
project_id,
)
results = []
for i, node_data in enumerate(nodes):
try:
node_id = node_data.get("node_id")
new_name = node_data.get("new_name")
logger.info(
"Updating node %d/%d: %s -> %s",
i + 1,
len(nodes),
node_id,
new_name,
)
node = nodes_by_id.get(node_id)
if node is None:
raise ValueError("Node not found")
old_name = node.get("name")
# Update node name — the PUT response is the updated node
updated = update_node_handler(
{
"project_id": project_id,
"node_id": node_id,
"name": new_name,
},
gns3_ctx,
)
if "error" in updated:
raise RuntimeError(updated["error"])
current_name = updated.get("name")
if current_name == new_name:
node_info = {
"node_id": node_id,
"old_name": old_name,
"new_name": new_name,
"status": "success",
}
results.append(node_info)
logger.info(
"Successfully updated node name: %s -> %s",
old_name,
new_name,
)
else:
error_info = {
"node_id": node_id,
"old_name": old_name,
"new_name": new_name,
"current_name": current_name,
"status": "failed",
"error": "Name verification failed",
}
results.append(error_info)
logger.error("Failed to update node name for %s", node_id)
except Exception as e:
error_info = {
"node_id": node_data.get("node_id"),
"new_name": node_data.get("new_name"),
"status": "failed",
"error": str(e),
}
results.append(error_info)
logger.error("Failed to update node %d: %s", i + 1, e)
# Analyze results
successful_nodes = [r for r in results if r.get("status") == "success"]
failed_nodes = [r for r in results if r.get("status") == "failed"]
# Construct final response
response = {
"project_id": project_id,
"total_nodes": len(nodes),
"successful": len(successful_nodes),
"failed": len(failed_nodes),
"nodes": results,
}
logger.info(
"Name update completed: %d successful, %d failed",
len(successful_nodes),
len(failed_nodes),
)
return response
except json.JSONDecodeError as e:
logger.error("Invalid JSON input: %s", e)
return {"error": f"Invalid JSON input: {e}"}
except Exception as e:
logger.error("Failed to update node names: %s", e)
return {"error": f"Failed to update node names: {e!s}"}
if __name__ == "__main__":
# Test with single node
print("=== Testing single node name update ===")
test_input_single = json.dumps(
{
# Replace with actual project UUID
"project_id": "your-project-uuid",
"nodes": [
{
# Replace with actual node UUID
"node_id": "your-node-uuid",
"new_name": "Router1",
}
],
}
)
tool = GNS3UpdateNodeNameTool()
result_single = tool._run(test_input_single)
pprint(result_single)
# Test with multiple nodes
print("\n=== Testing multiple nodes name update ===")
test_input_multiple = json.dumps(
{
# Replace with actual project UUID
"project_id": "your-project-uuid",
"nodes": [
{"node_id": "node-uuid-1", "new_name": "Router1"},
{"node_id": "node-uuid-2", "new_name": "Switch1"},
{"node_id": "node-uuid-3", "new_name": "PC1"},
],
}
)
result_multiple = tool._run(test_input_multiple)
pprint(result_multiple)
@@ -26,10 +26,10 @@
GNS3-Copilot wait tool.
start_gns3_node returns as soon as the start commands are accepted — nodes
node_start returns as soon as the start commands are accepted — nodes
keep booting in the background. This tool gives the agent a deliberate
pause it controls itself (instead of a hard-coded progress bar inside the
start tool), so the usual flow is: start_gns3_node → wait_seconds → check
start tool), so the usual flow is: node_start → wait_seconds → check
node status / run show commands.
"""
@@ -67,7 +67,7 @@ class GNS3WaitTool(BaseTool):
name: str = "wait_seconds"
description: str = """
Pause execution for a given number of seconds (1-600), then continue.
Use after start_gns3_node (which returns immediately) to let nodes
Use after node_start (which returns immediately) to let nodes
boot before checking status: VPCS/IOU ~15-30s, IOS/IOL routers
~60-120s, heavy NOS images (XRd, SR Linux) 2-5min. Prefer several
short waits with a status check in between over one long blind wait.
@@ -0,0 +1,280 @@
# 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
#
"""
Bridge that reuses the MCP server's tools inside the copilot agent.
The copilot and the MCP server used to maintain two parallel wrapper
layers (LangChain BaseTool classes vs @mcp.tool() functions) over the
same handlers in ``gns3_client.api_handlers`` — descriptions and
parameters drifted apart (compute_id and link_type were missing on the
copilot side for months). This bridge makes the MCP registration the
single source of truth: tool names, descriptions and argument schemas
are taken from the MCP server and wrapped into LangChain tools.
Scope: the copilot runs INSIDE one project, so project management and
server administration tools are filtered out (see MCP_ALLOWED_TOOLS).
``NATIVE_TOOL_NAMES`` lists the opposite case — copilot-native wrappers
that are richer than their MCP counterpart (link_create resolves port
names) and therefore shadow the adapted version.
Context bridging: the MCP tool functions read their JWT from contextvars
set by the MCP transport's auth wrapper. The copilot carries its own
request-scoped token, so the bridge sets those contextvars inside the
coroutine right before invoking the tool function (asyncio.to_thread
propagates the calling context, verified in agent/mcp/__init__.py).
"""
import asyncio
import json
import logging
from concurrent.futures import ThreadPoolExecutor
from typing import Any
from langchain_core.tools import BaseTool, StructuredTool
from pydantic import BaseModel, Field, create_model
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import build_gns3_ctx
from gns3server.services import auth_service
logger = logging.getLogger(__name__)
# Project-scoped tools the copilot may use. Everything else the MCP server
# registers is server/project administration (project_*, template_create/
# update/delete, compute_*, appliance_*, image_*, server_*) and stays out
# because the copilot operates inside a single already-open project.
MCP_ALLOWED_TOOLS = frozenset(
{
# nodes
"node_list",
"node_get",
"node_start",
"node_stop",
"node_suspend",
"node_create",
"node_delete",
"node_update",
"node_duplicate",
"node_isolate",
"node_unisolate",
"node_links",
"node_start_all",
"node_stop_all",
"node_suspend_all",
"node_console_exec",
# node files
"node_file_list",
"node_file_get",
"node_file_write",
"node_file_delete",
# links
"link_list",
"link_get",
"link_delete",
"link_update",
"link_available_filters",
"link_reset",
"link_capture_start",
"link_capture_stop",
"link_capture_download",
"link_marker",
"marker_definition",
# drawings
"drawing_list",
"drawing_create_text",
"drawing_create_rectangle",
"drawing_create_ellipse",
"drawing_get",
"drawing_update",
"drawing_delete",
# snapshots
"snapshot_list",
"snapshot_create",
"snapshot_delete",
"snapshot_restore",
# templates (read-only; create/update/delete are admin tasks)
"template_list",
"template_get",
# device configuration
"device_config_send",
"device_show_run",
"vpcs_config_set",
# skills
"device_skill_get",
"injection_skill_get",
}
)
# Copilot-native wrappers that shadow their MCP namesake because they add
# value the MCP tool lacks (link_create accepts port NAMES and resolves
# them to adapter/port numbers). These names are never adapted.
NATIVE_TOOL_NAMES = frozenset({"link_create"})
_JSON_SCHEMA_TYPE_MAP = {
"string": str,
"integer": int,
"number": float,
"boolean": bool,
"array": list,
"object": dict,
}
# Cache of adapted tools keyed by MCP tool name — the MCP registration is
# immutable after import, so the wrap happens once per process.
_adapted_cache: dict[str, BaseTool] = {}
def _build_args_model(mcp_tool: Any) -> type[BaseModel]:
"""Build a pydantic args model from the MCP tool's JSON schema."""
schema = mcp_tool.parameters or {}
properties = schema.get("properties", {})
required = set(schema.get("required") or [])
fields: dict[str, Any] = {}
for param_name, param_spec in properties.items():
param_type = _JSON_SCHEMA_TYPE_MAP.get(param_spec.get("type"))
if param_type is None:
param_type = Any
description = param_spec.get("description")
if param_name in required:
fields[param_name] = (param_type, Field(..., description=description))
elif "default" in param_spec:
fields[param_name] = (param_type, Field(default=param_spec["default"], description=description))
else:
fields[param_name] = (param_type | None, Field(default=None, description=description))
return create_model(f"{mcp_tool.name}_args", **fields)
def _run_coro_sync(coro: Any) -> Any:
"""Run a coroutine to completion from synchronous code.
In a plain worker thread (no running loop) asyncio.run is enough.
When called from inside a running event loop (sync tool executed on
the loop thread), the coroutine runs on a fresh loop in a helper
thread; the contextvars are set inside the coroutine itself, so the
thread hop loses nothing.
"""
try:
asyncio.get_running_loop()
except RuntimeError:
return asyncio.run(coro)
with ThreadPoolExecutor(max_workers=1) as pool:
return pool.submit(asyncio.run, coro).result()
def _unwrap_mcp_content(raw: Any) -> Any:
"""Unwrap MCP content blocks ([{"type": "text", "text": ...}]) to plain data."""
if isinstance(raw, list) and raw and all(isinstance(block, dict) and block.get("type") == "text" for block in raw):
texts = [block.get("text", "") for block in raw]
if len(texts) == 1:
try:
return json.loads(texts[0])
except (json.JSONDecodeError, TypeError):
return texts[0]
return texts
return raw
def _invoke_mcp_tool(mcp_tool: Any, kwargs: dict[str, Any]) -> Any:
"""Invoke one MCP tool function with the copilot's credentials."""
ctx = build_gns3_ctx()
if ctx is None or not ctx.get("jwt_token"):
return {"error": "No GNS3 authentication token available in this request context."}
# Handlers that mint short-lived tickets (link_capture_download,
# node_console_exec) need the username and token_version; decode them
# from the copilot's own JWT. Handlers that do not need them tolerate
# the fallbacks.
username: str | None = None
token_version = 0
try:
token_data = auth_service.get_token_data(ctx["jwt_token"])
username = token_data.username
token_version = token_data.token_version
except Exception:
logger.debug("Could not decode the copilot JWT for username/token_version")
async def _call() -> Any:
# Set inside the coroutine: whatever thread/loop ends up running
# the handler thread inherits these via asyncio.to_thread's
# context copy (see _gns3_ctx in agent/mcp/__init__.py).
from gns3server.agent.mcp import _jwt_token_var, _jwt_token_version_var, _jwt_username_var
_jwt_token_var.set(ctx["jwt_token"])
_jwt_username_var.set(username)
_jwt_token_version_var.set(token_version)
return await mcp_tool.fn(**kwargs)
try:
raw = _run_coro_sync(_call())
except Exception as e:
logger.error("MCP tool %s failed via copilot bridge: %s", mcp_tool.name, e, exc_info=True)
return {"error": f"{type(e).__name__}: {e!s}"}
return _unwrap_mcp_content(raw)
def _adapt(mcp_tool: Any) -> BaseTool:
"""Wrap one MCP Tool into a LangChain StructuredTool."""
def _run(**kwargs: Any) -> Any:
return _invoke_mcp_tool(mcp_tool, kwargs)
return StructuredTool.from_function(
func=_run,
name=mcp_tool.name,
description=mcp_tool.description or "",
args_schema=_build_args_model(mcp_tool),
)
def adapted_mcp_tools(names: list[str] | None = None) -> list[BaseTool]:
"""Return LangChain tools adapted from the MCP server registration.
Args:
names: restrict to these MCP tool names (must also be allowed).
None means every allowed tool except native-shadowed ones.
"""
# Function-level import: gns3server.agent.mcp pulls the whole MCP
# stack and imports back into gns3_copilot.gns3_client, so importing
# it lazily keeps this module safe during package initialization.
from gns3server.agent.mcp import mcp
if not _adapted_cache:
for mcp_tool in mcp._tool_manager.list_tools():
if mcp_tool.name in MCP_ALLOWED_TOOLS and mcp_tool.name not in NATIVE_TOOL_NAMES:
_adapted_cache[mcp_tool.name] = _adapt(mcp_tool)
if names is None:
return list(_adapted_cache.values())
missing = [name for name in names if name not in _adapted_cache]
if missing:
# Fail loudly at agent construction: a typo or a renamed MCP tool
# must never silently shrink the copilot toolset.
raise RuntimeError(
f"MCP tools not available to the copilot: {missing}. "
f"Allowed pool has {len(_adapted_cache)} tools; check MCP_ALLOWED_TOOLS "
"and the MCP registration."
)
return [_adapted_cache[name] for name in names]
@@ -240,9 +240,10 @@ class TestVPCSTelnetSendCommand(unittest.TestCase):
"""Test that send_command uses VPCS prompt as default expect_string."""
import inspect
# Check that expect_string defaults to r"PC\d+>"
# The default expect_string is the per-instance prompt pattern built
# in __init__ from pcname (falls back to PC<n>/VPCS>).
source = inspect.getsource(self.VPCSTelnet.send_command)
self.assertIn('expect_string = r"PC\\d+>"', source)
self.assertIn("expect_string = self._prompt_pattern", source)
def test_send_command_timing_calls_send_command(self):
"""Test that send_command_timing delegates to send_command."""
@@ -283,9 +284,11 @@ class TestVPCSTelnetTelnetLogin(unittest.TestCase):
"""Test that telnet_login has correct default prompt pattern."""
import inspect
# Check default prompt terminator
# The default prompt terminator is the per-instance prompt pattern
# built in __init__ from pcname (None -> self._prompt_pattern).
source = inspect.getsource(self.VPCSTelnet.telnet_login)
self.assertIn('pri_prompt_terminator: str = r"PC\\d+>"', source)
self.assertIn("pri_prompt_terminator: str | None = None", source)
self.assertIn("pri_prompt_terminator = self._prompt_pattern", source)
def test_telnet_login_sends_newlines(self):
"""Test that telnet_login sends 4 newlines."""
@@ -429,10 +432,12 @@ IP/MASK : 192.168.1.20/24"""
instance = self.VPCSTelnet.__new__(self.VPCSTelnet)
# Mock necessary attributes
# Mock necessary attributes. The read loop polls read_channel
# (netmiko's decorated method needs the session lock, which only
# __init__ creates), not read_until_pattern.
instance.remote_conn = MagicMock()
instance.remote_conn.write = MagicMock()
instance.read_until_pattern = MagicMock(return_value="\x1b[1mNAME\x1b[0m : PC2\nPC2>")
instance.read_channel = MagicMock(return_value="\x1b[1mNAME\x1b[0m : PC2\nPC2>")
# Mock _strip_ansi_codes to verify it's called
instance._strip_ansi_codes = Mock(return_value="NAME : PC2\nPC2>")
@@ -53,6 +53,13 @@ logger = logging.getLogger(__name__)
# Matches sequences like: [1m (bold), [0m (reset), [4m (underline), etc.
ANSI_ESCAPE_PATTERN = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
# VPCS prompt = "<node name>>" (the template's startup script runs
# `set pcname <name>`, so a template-created node named PC1 prompts "PC1>").
# The bare-binary default "VPCS>" shows up only when no startup script set a
# name (e.g. raw API node creation) — kept as a fallback. A node name passed
# via the `pcname` kwarg takes precedence (regex-escaped).
DEFAULT_PROMPT_PATTERN = r"(?:PC\d+>|VPCS>)"
class VPCSTelnet(BaseConnection):
"""
@@ -66,12 +73,28 @@ class VPCSTelnet(BaseConnection):
- No configuration modes
"""
# Class-level default (overridden per instance when pcname is given);
# lets methods work on instances built without __init__ (unit tests).
_prompt_pattern = DEFAULT_PROMPT_PATTERN
def __init__(
self,
*args,
pcname: str | None = None,
**kwargs,
) -> None:
"""Initialize VPCS Telnet connection."""
"""Initialize VPCS Telnet connection.
Args:
pcname: the GNS3 node name. The VPCS prompt is "<node name>>"
(set by the template's startup script), so a matching
prompt pattern is built from it. Falls back to the
default "PC<n>"/"VPCS>" patterns when not provided.
"""
self._prompt_pattern = DEFAULT_PROMPT_PATTERN
if pcname:
self._prompt_pattern = rf"(?:{re.escape(pcname)}>|{DEFAULT_PROMPT_PATTERN})"
# Set device type to identify this as a VPCS device
kwargs.setdefault("device_type", "gns3_vpcs_telnet")
@@ -88,7 +111,7 @@ class VPCSTelnet(BaseConnection):
def telnet_login(
self,
pri_prompt_terminator: str = r"PC\d+>",
pri_prompt_terminator: str | None = None,
alt_prompt_terminator: str = r"",
username_pattern: str = r"(?:user:|username|login|user name)",
pwd_pattern: str = r"assword",
@@ -103,11 +126,12 @@ class VPCSTelnet(BaseConnection):
Strategy (matching telnetlib3 implementation):
1. Send 4 newlines with 0.5s delay between each
2. Wait for VPCS prompt pattern (PC1>, PC2>, etc.)
2. Wait for VPCS prompt pattern (node name, PC<n>, or VPCS>)
3. Return once prompt is detected
Args:
pri_prompt_terminator: Primary prompt pattern (default: r"PC\\d+>")
pri_prompt_terminator: Prompt pattern (defaults to the node-name
pattern built in __init__)
alt_prompt_terminator: Not used for VPCS
username_pattern: Not used (kept for signature compatibility)
pwd_pattern: Not used (kept for signature compatibility)
@@ -117,6 +141,8 @@ class VPCSTelnet(BaseConnection):
Returns:
Output from the connection process
"""
if pri_prompt_terminator is None:
pri_prompt_terminator = self._prompt_pattern
delay_factor = self.select_delay_factor(delay_factor)
return_msg = ""
@@ -166,10 +192,10 @@ class VPCSTelnet(BaseConnection):
"""
Prepare the session after connection is established.
VPCS doesn't require special session preparation.
The telnet_login method already handles initialization with 4 newlines.
VPCS requires no session preparation — the node name (and thus the
prompt) is set by the node's own startup script, not by us: renaming
the PC here would change what the user sees in their topology.
"""
# No additional preparation needed
logger.debug("VPCS session preparation completed")
def send_command(
@@ -187,16 +213,16 @@ class VPCSTelnet(BaseConnection):
"""
Send a command to VPCS and return the output.
This method exactly matches the telnetlib3 implementation:
1. Encode command as ASCII and append newline
2. Write command+newline as single byte sequence
3. Sleep for 5 seconds
4. Wait for prompt pattern and capture output
5. Return captured output
2. Drain stale output from a previous command on this cached session
3. Write command+newline as a single byte sequence
4. Read until the prompt pattern appears; on timeout return the
partial output collected so far instead of discarding it
Args:
command_string: The command to send
expect_string: Pattern to expect (default: VPCS prompt r"PC\\d+>")
expect_string: Pattern to expect (default: the prompt pattern
built in __init__ from pcname)
read_timeout: Timeout for reading output
delay_factor: Not used (kept for signature compatibility)
max_loops: Not used (kept for signature compatibility)
@@ -210,29 +236,42 @@ class VPCSTelnet(BaseConnection):
"""
# Use VPCS prompt as default expect_string
if expect_string is None:
expect_string = r"PC\d+>"
expect_string = self._prompt_pattern
# CRITICAL: Match telnetlib3 behavior exactly
# tn.write(command.encode(encoding="ascii") + b"\n")
cmd_bytes = command_string.encode(encoding="ascii") + b"\n"
# Drain stale output from a previous command on this cached session
# before writing, so it cannot bleed into this command's result.
try:
self.read_channel()
except Exception:
pass
self.remote_conn.write(cmd_bytes)
logger.debug("VPCS: Sent command '%s' (%d bytes)", command_string, len(cmd_bytes))
# Sleep for 5 seconds (matching telnetlib3: sleep(5))
time.sleep(5)
# Wait for prompt pattern and capture output
# This matches telnetlib3: tn.expect([rb"PC\d+>"]) + tn.read_very_eager()
# read_until_pattern returns the output including the matched pattern
try:
output = self.read_until_pattern(pattern=expect_string, read_timeout=10)
logger.debug("VPCS: read_until_pattern returned %d chars", len(output))
except Exception as e:
# If pattern not found, try to read whatever is available
logger.debug("VPCS: Pattern not found, reading available output: %s", e)
output = self.read_channel()
logger.debug("VPCS: read_channel returned %d chars", len(output) if output else 0)
# The read loop is owned here rather than delegated to netmiko's
# read_until_pattern: on timeout that helper RAISES and discards the
# output it has already read, so a command slower than the timeout
# (e.g. a ping whose output lands after ARP resolution) would return
# an empty string that looks like success. The prompt appears as soon
# as the device finishes the command; on timeout the partial output is
# returned instead (the timeout stays the backstop — no fixed sleep).
timeout = read_timeout or 10
deadline = time.monotonic() + timeout
output = ""
while True:
chunk = self.read_channel() or ""
if chunk:
output += chunk
if re.search(expect_string, output):
logger.debug("VPCS: prompt detected after %d chars", len(output))
break
if time.monotonic() >= deadline:
logger.debug("VPCS: prompt not seen within %.1fs; returning partial output", timeout)
break
time.sleep(0.05)
if isinstance(output, bytes):
output = output.decode("utf-8", errors="replace")
@@ -266,12 +305,12 @@ class VPCSTelnet(BaseConnection):
"""
Send command using timing-based delay.
For VPCS, timing-based and pattern-based methods are identical,
both use the telnetlib3 implementation pattern with fixed 5s delay.
For VPCS, timing-based and pattern-based methods are identical —
both delegate to send_command's prompt-pattern read loop.
Args:
command_string: The command to send
delay_factor: Not used (fixed 5s delay for VPCS)
delay_factor: Not used (the read loop is deadline-based)
max_loops: Not used (kept for signature compatibility)
strip_prompt: Remove prompt from output
strip_command: Remove command from output
@@ -23,15 +23,23 @@
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
Device config entry normalization shared by the tools_v2 executors.
Device config entry normalization shared by the device command runners.
Callers (LLM agents via MCP, or gns3-copilot directly) may send the same
device several times in one batch. Every downstream stage keys by
device_name, so duplicates must merge before execution, not after.
Callers (LLM agents via MCP, or the copilot through the MCP tool bridge)
may send the same device several times in one batch. Every downstream
stage keys by device_name, so duplicates must merge before execution, not
after. This module also renders the optional per-device Jinja2 template
into the commands field.
"""
import logging
from typing import Any
from jinja2 import Template as JinjaTemplate
from jinja2 import TemplateError as JinjaError
logger = logging.getLogger(__name__)
def merge_duplicate_device_configs(
device_configs: list[Any],
@@ -76,3 +84,52 @@ def merge_duplicate_device_configs(
entry[commands_field] = commands
merged[name] = entry
return list(merged.values())
def render_device_template(
template: str,
device_configs: list[dict[str, Any]],
commands_field: str = "config_commands",
) -> list[dict[str, Any]]:
"""
Render a Jinja2 template for each device's vars into the commands field.
Entries with the same device_name are merged into a single entry
so they share one Nornir session and avoid output fragmentation.
Each device in device_configs can have:
- "vars": dict of template variables (rendered into commands_field)
- commands_field: existing commands merged after rendering if present
Returns a one-entry error list on template failure so callers can pass
it straight through to the LLM.
Args:
commands_field: field name for the rendered commands, e.g. "config_commands", "commands"
"""
try:
jinja = JinjaTemplate(template)
except JinjaError as e:
# a syntactically invalid template must not escape as a raw exception
error_msg = f"Template rendering failed: {e}"
logger.error(error_msg)
return [{"status": "failed", "error": error_msg}]
merged: dict[str, dict[str, Any]] = {}
for dev in device_configs:
name = dev.get("device_name")
if not name:
continue
vars_data = dev.get("vars", {})
if name not in merged:
merged[name] = {"device_name": name, commands_field: list(dev.get(commands_field, []))}
entry = merged[name]
if vars_data:
try:
output = jinja.render(**vars_data)
lines = [line for line in output.splitlines() if line.strip()]
entry[commands_field].extend(lines)
except JinjaError as e:
error_msg = f"Template rendering failed for '{name}': {e}"
logger.error(error_msg)
return [{"status": "failed", "error": error_msg}]
return list(merged.values())
+366 -66
View File
@@ -18,19 +18,22 @@
"""
MCP (Model Context Protocol) service for GNS3 server.
Implements the standard MCP protocol over SSE transport using FastMCP:
Implements the standard MCP protocol over the Streamable HTTP transport
using the official MCP SDK (mcp.server.mcpserver.MCPServer):
/v3/mcp/sse — SSE stream
/v3/mcp/messages/ — JSON-RPC messages
/v3/mcp/transport — POST (JSON-RPC), GET (optional server stream),
DELETE (session termination)
Tools are registered via @mcp.tool() decorators.
"""
import asyncio
import contextlib
import contextvars
import json
import logging
import socket
import time
from typing import Annotated, Any
from urllib.parse import parse_qs
from uuid import UUID
@@ -38,7 +41,7 @@ from uuid import UUID
import bcrypt
from fastapi import APIRouter
from fastapi.responses import Response
from mcp.server.fastmcp import FastMCP
from mcp.server.mcpserver import MCPServer
from mcp.server.transport_security import TransportSecuritySettings
from pydantic import Field
from sqlalchemy.ext.asyncio import AsyncSession
@@ -57,7 +60,6 @@ from gns3server.agent.gns3_copilot.gns3_client.api_handlers import (
duplicate_node_handler,
get_link_handler,
get_links_handler,
get_node_console_info_handler,
get_node_file_handler,
get_node_handler,
get_node_links_handler,
@@ -106,6 +108,7 @@ from .computes import (
get_compute_images_handler,
list_computes_handler,
)
from .console_exec import DEFAULT_TIMEOUT_S, DIRECT_LINES, FULL_LINES, MAX_TIMEOUT_S, console_exec
from .device_config import (
device_config_send_handler,
device_show_run_handler,
@@ -145,6 +148,7 @@ from .server import (
get_statistics_handler,
get_version_handler,
)
from .skills import device_skills_handler, injection_skills_handler
from .snapshots import (
create_snapshot_handler,
delete_snapshot_handler,
@@ -221,8 +225,11 @@ async def wait_for_mcp_ready() -> bool:
# ── Per‑connection JWT token ─────────────────────────────────────────
# Set during SSE authentication, read by tool handlers running in the
# same asyncio task (contextvars propagate through asyncio.to_thread).
# Set during request authentication, read by tool handlers running in the
# session task that inherited it (contextvars propagate through
# asyncio.to_thread). In stateful Streamable HTTP the session task is
# created by the opening (initialize) request, so handlers see the token
# presented when the session was established.
_jwt_token_var: contextvars.ContextVar[str | None] = contextvars.ContextVar("mcp_jwt_token", default=None)
# Username extracted during token validation — used by handlers to generate
@@ -232,10 +239,36 @@ _jwt_username_var: contextvars.ContextVar[str | None] = contextvars.ContextVar("
# download/console URLs must carry the same version, or the revocation check
# (token_data.token_version != user.token_version) rejects them as "revoked".
_jwt_token_version_var: contextvars.ContextVar[int] = contextvars.ContextVar("mcp_jwt_token_version", default=0)
# The raw API key the session authenticated with (None for JWT logins). The
# session task cannot see contextvars set by later requests, so the JWT it
# inherited at initialize ages past its 24h lifetime while the transport
# keeps authenticating fine — _gns3_ctx() uses this key to renew that JWT.
_jwt_api_key_var: contextvars.ContextVar[str | None] = contextvars.ContextVar("mcp_jwt_api_key", default=None)
# ── Token validation ──────────────────────────────────────────────────
# Short-lived cache of API-key resolutions. Streamable HTTP authenticates
# every request (not once per connection like SSE), and each API-key check
# costs a bcrypt round (~hundreds of ms of CPU). Cache the minted JWT (and
# the username/token_version contextvars) for a few minutes per key.
# Revocation lag is bounded by the TTL — the minted 24h JWT outlives the
# cache anyway, so this matches the previous per-connection behavior.
_API_KEY_CACHE_TTL = 300.0 # seconds
_API_KEY_CACHE_MAX = 128
_api_key_cache: dict[str, tuple[float, str, str, int]] = {} # token -> (expires_at, jwt, username, token_version)
def _cache_api_key(token: str, jwt: str, username: str, token_version: int) -> None:
"""Store an API-key resolution, pruning the cache when it exceeds the size cap."""
now = time.monotonic()
if len(_api_key_cache) >= _API_KEY_CACHE_MAX:
for stale in [k for k, v in _api_key_cache.items() if v[0] <= now]:
del _api_key_cache[stale]
if len(_api_key_cache) >= _API_KEY_CACHE_MAX:
_api_key_cache.pop(next(iter(_api_key_cache)))
_api_key_cache[token] = (now + _API_KEY_CACHE_TTL, jwt, username, token_version)
async def _resolve_token(token: str) -> str | None:
"""Validate a token (JWT or API key) and return the effective JWT to use.
@@ -246,7 +279,7 @@ async def _resolve_token(token: str) -> str | None:
Returns None if the token is invalid.
"""
# API keys (gns3_...) are never valid JWTs — skip the JWT attempt for them
# so it doesn't log a spurious "JWT rejected" line on every API-key connection.
# so it doesn't log a spurious "JWT rejected" line on every API-key request.
if not token.startswith("gns3_"):
try:
token_data = auth_service.get_token_data(token)
@@ -256,6 +289,15 @@ async def _resolve_token(token: str) -> str | None:
except Exception:
pass
cached = _api_key_cache.get(token)
if cached is not None:
expires_at, jwt, username, token_version = cached
if expires_at > time.monotonic():
_jwt_username_var.set(username)
_jwt_token_version_var.set(token_version)
return jwt
del _api_key_cache[token]
# Try API key — format: gns3_<api_key_id>_<random_secret> → O(1) lookup
if token.startswith("gns3_") and _app is not None:
db_engine = getattr(_app.state, "_db_engine", None)
@@ -279,6 +321,7 @@ async def _resolve_token(token: str) -> str | None:
fresh_token = auth_service.create_access_token(
user.username, token_version=user.token_version
)
_cache_api_key(token, fresh_token, user.username, user.token_version)
return fresh_token
except Exception:
pass
@@ -304,28 +347,27 @@ def _server_url() -> str:
return f"{scheme}://{host}:{cfg.Server.port}"
# ── FastMCP Server ────────────────────────────────────────────────────
# ── MCP Server ────────────────────────────────────────────────────────
def _create_mcp_server() -> FastMCP:
"""Create MCP server with security settings from configuration."""
def _create_mcp_server() -> MCPServer:
"""Create the MCP server (transport security is applied when the HTTP app is built)."""
return MCPServer("GNS3 MCP Server")
def _transport_security() -> TransportSecuritySettings:
"""Build transport security settings from configuration."""
cfg = Config.instance().settings.Server
# Always pass an explicit TransportSecuritySettings to prevent FastMCP
# Always pass an explicit TransportSecuritySettings to prevent the SDK
# from auto-enabling protection when host is localhost (its default).
if cfg.mcp_enable_dns_rebinding_protection:
transport_security = TransportSecuritySettings(
return TransportSecuritySettings(
enable_dns_rebinding_protection=True,
allowed_hosts=cfg.mcp_allowed_hosts or ["127.0.0.1:*", "localhost:*"],
allowed_origins=cfg.mcp_allowed_origins or ["http://127.0.0.1:*", "http://localhost:*"],
)
else:
transport_security = TransportSecuritySettings(
enable_dns_rebinding_protection=False,
)
mcp = FastMCP("GNS3 MCP Server", transport_security=transport_security)
return mcp
return TransportSecuritySettings(enable_dns_rebinding_protection=False)
mcp = _create_mcp_server()
@@ -334,15 +376,59 @@ mcp = _create_mcp_server()
# ── Tool handlers ─────────────────────────────────────────────────────
def _run_handler_sync(handler, params: dict[str, Any]) -> list[dict[str, Any]]:
"""Run a synchronous Gns3Connector handler in a thread."""
ctx = {
def _renew_expired_jwt(token: str | None, api_key: str | None, username: str | None, token_version: int) -> str | None:
"""Renew the session task's JWT once it has aged past its lifetime.
Tool handlers run in the session task created at initialize and inherit
its context; contextvars set by later requests never reach them. For
API-key sessions (the documented long-lived setup — keys never expire)
that means the minted 24h JWT eventually expires under a healthy
transport: every request still re-validates the key, but tool calls
would send the stale JWT and fail with 401.
The renewal is cheap by construction: every tools/call POST passes the
auth wrapper first, which re-validates the API key and refreshes the
module-level _api_key_cache with a freshly minted JWT — so by the time a
tool handler runs, a current JWT for this key is already cached. Only
when that cache entry has gone stale (idle gap) do we re-mint here
synchronously; no DB round-trip, the username/token_version validated at
initialize are re-used.
Returns the effective JWT, or None when renewal is not possible (JWT
login: the client's own credential expiring is the client's business).
"""
if not token or not api_key:
return token
try:
auth_service.get_token_data(token)
return token # still valid
except Exception:
pass
cached = _api_key_cache.get(api_key)
if cached is not None and cached[0] > time.monotonic():
return cached[1]
fresh = auth_service.create_access_token(username or "", token_version=token_version)
_cache_api_key(api_key, fresh, username or "", token_version)
log.info("Renewed the MCP session's expired JWT from its API key (user %s)", username)
return fresh
def _gns3_ctx() -> dict[str, Any]:
"""Build the Gns3Connector context from the request's contextvars."""
return {
"server_url": _server_url(),
"jwt_token": _jwt_token_var.get(),
"jwt_token": _renew_expired_jwt(
_jwt_token_var.get(), _jwt_api_key_var.get(), _jwt_username_var.get(), _jwt_token_version_var.get()
),
"jwt_username": _jwt_username_var.get(),
"jwt_token_version": _jwt_token_version_var.get(),
}
def _run_handler_sync(handler, params: dict[str, Any]) -> list[dict[str, Any]]:
"""Run a synchronous Gns3Connector handler in a thread."""
ctx = _gns3_ctx()
def run(h, p):
return h(p, ctx)
@@ -668,38 +754,95 @@ async def node_update(
@mcp.tool()
async def node_console(
async def node_console_exec(
project_id: Annotated[str, Field(description="Project name or UUID containing the node")],
node_id: Annotated[str, Field(description="Node name or UUID to get console info for")],
) -> list[dict[str, Any]]:
"""Get WebSocket console connection info for a node.
node_id: Annotated[str, Field(description="Node name or UUID to run commands on")],
command: Annotated[
str,
Field(
description="Commands, one per line (\\n-separated). Empty = a single Enter (wake the console / read the prompt)."
),
] = "",
timeout: Annotated[ # noqa: ASYNC109 - timeout is the session length, not an async deadline
float,
Field(
description=f"Session length in seconds, 1-{int(MAX_TIMEOUT_S)} (default {int(DEFAULT_TIMEOUT_S)}). "
"The session stays open the FULL window — set it just above the expected output time."
),
] = DEFAULT_TIMEOUT_S,
grep: Annotated[
str | None,
Field(
description="Optional Python regex (superset of grep -E). Only matching lines of the output are returned, "
"e.g. 'ospf|bgp', '^R1#'."
),
] = None,
regrep: Annotated[
bool,
Field(
description="Re-use this node's last captured output instead of running a new session "
"(no re-run, no side effects). Combine with grep= or full=true."
),
] = False,
full: Annotated[
bool,
Field(
description=f"Return the last {FULL_LINES} lines / 64 KiB of output instead of the {DIRECT_LINES}-line summary."
),
] = False,
) -> str:
"""Run commands on a node's text console and return the output (one call = one complete session).
Returns the console type (telnet/ssh/vnc) and a ready-to-run websocat
command with a short-lived access token (10 min) already embedded.
The server connects to the node's console WebSocket, sends your command
lines, keeps collecting output until the timeout expires, disconnects,
and returns everything that came back as plain text. Works for telnet and
ssh console types on all computes (the controller proxies the WebSocket).
Node-side state persists between calls (config mode, running pings,
pager position) — a new session lands where the previous one ended.
IMPORTANT — copy the returned values EXACTLY:
- Run the returned "command" string verbatim; it already contains the
full URL with token. NEVER construct or edit the URL yourself, and
NEVER copy the token by hand — a mistyped token is rejected.
- The token expires after token_ttl_seconds (10 min): call this tool
again to get a fresh one; do not reuse an old URL.
Console input:
- command: one command per line (\\n-separated). Each line is sent with a
console line ending, lines are paced ~0.3 s apart so none is dropped.
- A line containing only a control character is a keypress, not a
command: interrupt a running command with a real Ctrl-C character — in
JSON tool arguments that is "\\u0003" as its own line. The 4-character
spelling "\\x03" is NOT translated and would arrive as text.
- command="" sends a single Enter — wakes an idle console and shows the
prompt.
- QEMU serial getty login: send the username and the password in the SAME
call. login flushes typed-ahead input before printing "Password: ", so
a password sent in a separate call is lost (Login incorrect loop). The
logged-in shell then persists across calls.
Sending device commands after connecting:
> timeout 10 websocat -t --no-close "ws://..." <<< $'\\r\\nenable\\r\\nshow version\\r\\nexit\\r\\n'
Timeout: the session stays open for the FULL window (like
`timeout N websocat`). Output keeps arriving the whole time; there is no
early return. ~15 s fits a few show commands; big config blocks or
`show tech-support` need 30 s or more.
- Use \\r\\n (not \\n) to match console protocol line endings
- Use $'...' format for escape sequences in bash
- --no-close keeps the WebSocket open after stdin (heredoc) hits EOF, so
device output is not cut off before it arrives
- Set a timeout to prevent hanging connections
Output is raw console bytes decoded as UTF-8 with replacement — telnet
negotiation and ANSI escape sequences may show up as stray bytes; that
is expected. When more than 50 lines would come back, only a 10-line
sample returns, with instructions to narrow (grep=), re-filter the cached
capture without re-running (regrep=true), dump its tail (full=true), or
download the whole capture with curl.
Failures (node not started, VNC console, websocat missing on the server
host, silent console) return plain text describing the problem — there
is no status field, read the text itself.
Example — two checks on one router, 20 s window:
node_console_exec(project_id="ospf-lab", node_id="R1",
command="show ip ospf neighbor\\nshow ip route summary", timeout=20)
"""
return await asyncio.to_thread(
_run_handler_sync,
get_node_console_info_handler,
{
"project_id": project_id,
"node_id": node_id,
},
return await console_exec(
project_id,
node_id,
command,
timeout,
grep=grep,
regrep=regrep,
full=full,
gns3_ctx=_gns3_ctx(),
)
@@ -712,7 +855,7 @@ async def link_list(
fields: Annotated[
list[str] | None,
Field(
description='Optional: return only these fields. e.g. ["link_id","nodes"]. Available: link_id, project_id, link_type, kernel_datapath, nodes, suspend, filters, capturing, capture_file_name, link_style'
description='Optional: return only these fields. e.g. ["link_id","nodes"]. Available: link_id, project_id, link_type, kernel_datapath, nodes, suspend, filters, show_filters_icon, capturing, capture_file_name, link_style'
),
] = None,
) -> list[dict[str, Any]]:
@@ -802,6 +945,9 @@ async def link_update(
Supported kwargs:
- suspend: boolean - Suspend or resume the link
- show_filters_icon: boolean - Show the filter icon in the Web UI (server
default true). Set false to keep the canvas clean when injecting
practice faults
- filters: dict - Packet filters (values MUST be positional arrays). Types
marked (K) run on kernel-datapath links only (both endpoints on one
compute with an anchor of their own) and are rejected with 409 on relay
@@ -829,7 +975,8 @@ async def link_update(
steady-state mean loss = p/(p+r)*(1-h) per direction; mutually
exclusive with packet_loss
* duplicate (K): [pct, correl?] - Duplication percentage
* seed (K): [u32] - Makes netem random draws reproducible
* seed (K): [u32] - Makes netem random draws reproducible (needs
kernel >= 6.6; older kernels silently ignore the seed)
* limit (K): [pkts] - Impairment queue depth (default 1000; raise for
low rate + long delay)
* quota (K): [bytes, pct] - After the byte quota is consumed, each
@@ -1474,6 +1621,7 @@ async def snapshot_list(
async def snapshot_create(
project_id: Annotated[str, Field(description="Project name or UUID")],
name: Annotated[str, Field(description="Name for the new snapshot")],
description: Annotated[str | None, Field(description="Optional description for the snapshot")] = None,
) -> list[dict[str, Any]]:
"""Create a new snapshot of a project.
@@ -1487,6 +1635,7 @@ async def snapshot_create(
{
"project_id": project_id,
"name": name,
"description": description,
},
)
@@ -2059,7 +2208,7 @@ async def device_show_run(
- Each node must have a device_type:<type> tag set in GNS3
(e.g. device_type:cisco_ios_telnet, device_type:gns3_huawei_telnet_ce).
Nodes without this tag will fail with "device_type tag not found".
Docker/Linux nodes are not supported (use node_console instead).
Docker/Linux nodes are not supported (use node_console_exec instead).
Error contract: every failure is reported in-band as an entry with
status "failed" and an "error" message (per-device entries also carry
@@ -2103,17 +2252,131 @@ async def vpcs_config_set(
)
# ── Auth‑wrapped SSE app ──────────────────────────────────────────────
@mcp.tool()
async def device_skill_get(
device_type: Annotated[
str | None,
Field(description="Skill key exactly as action='list' returns it, e.g. 'frr_vtysh', 'cisco_ios_telnet'"),
] = None,
action: Annotated[str | None, Field(description='"list" to enumerate skills; "get" (default) to fetch one')] = None,
category: Annotated[str | None, Field(description='Optional category filter, e.g. "device" or "feature"')] = None,
topic: Annotated[
str | None,
Field(
description='Protocol topic key from the topic index, e.g. "ospf", "bgp". '
"Topic bodies load ONLY on an explicit topic request — every other call returns the base skill plus the topic index"
),
] = None,
detail: Annotated[str | None, Field(description='"index" | "summary" | "full" (default)')] = None,
issue: Annotated[str | None, Field(description="Single troubleshooting-issue key from the skill")] = None,
) -> list[dict[str, Any]]:
"""Read device knowledge from the GNS3-Skills repository — BEFORE driving an unfamiliar console.
TOKEN-EFFICIENT USAGE (same protocol as the copilot's device_skills tool):
1. List every skill: device_skill_get(action="list")
2. Device skill list (topics): device_skill_get(device_type="frr_vtysh")
3. ONE targeted topic body: device_skill_get(device_type="frr_vtysh", topic="bgp")
Step 2 returns the base skill plus the topic index; step 3 loads the
targeted body. Pass the key exactly as step 1 returned it.
Devices without topics (single-file skills such as gns3_vpcs_telnet
or nokia_srlinux_cli) are complete at step 2 with the default full
detail — there is no topic step, and detail="index" only lists their
sections (config_commands, display_commands, ...).
category="device" or "feature" narrows both list and get.
Skills carry the operational quirks the generic tools cannot know:
FRR's console lands directly in vtysh (no -c on its ping, 'do' prefixes
inside scripted config), VPCS command syntax, IOS paging pitfalls.
Requires the skills repository to be configured (cloned); an
uninitialized repository fails with a clear error, while an empty but
initialized repository returns an empty list.
IF YOUR CLIENT OFFERS SUBAGENTS: on long tasks, delegate steps 1-2
to a subagent and ask it to return the exact command/quirk snippets
you need — not a prose summary. The full skill bodies then never
occupy this conversation's context.
"""
params: dict[str, Any] = {"action": action}
if device_type is not None:
params["device_type"] = device_type
if category is not None:
params["category"] = category
if topic is not None:
params["topic"] = topic
if detail is not None:
params["detail"] = detail
if issue is not None:
params["issue"] = issue
return await asyncio.to_thread(_run_handler_sync, device_skills_handler, params)
@mcp.tool()
async def injection_skill_get(
action: Annotated[
str | None,
Field(description='"list" (requires context) to find fault categories; "get" (default with device_type)'),
] = None,
context: Annotated[
list[str] | None,
Field(
description='REQUIRED for action="list": protocols/services found in the topology, '
'e.g. ["ospf", "bgp"]. Returns only the matching fault categories'
),
] = None,
device_type: Annotated[
str | None,
Field(description="Fault category key from action='list', e.g. 'injection_ospf_issues'"),
] = None,
detail: Annotated[str | None, Field(description='"index" | "summary" | "full" (default)')] = None,
issue: Annotated[
str | None,
Field(description="Single fault key from the category's issue index, e.g. 'ospf_hello_dead_mismatch'"),
] = None,
) -> list[dict[str, Any]]:
"""Read fault-injection knowledge from the GNS3-Skills repository.
Multi-call by design — analyze the topology first, then:
1. Find the fault categories that fit it (context REQUIRED):
injection_skill_get(action="list", context=["ospf", "bgp"])
2. Get one category's fault index (names only):
injection_skill_get(device_type="injection_ospf_issues", detail="index")
3. Get ONE fault's full detail:
injection_skill_get(device_type="injection_ospf_issues", issue="ospf_hello_dead_mismatch")
Then inject it with device_config_send, and verify with device_show_run.
context matches the skill's category, key and declared protocols
(case-insensitive), so aliases such as "ebgp" and "ospfv3" work.
Category keys are derived from the repository filenames — always pass
the key exactly as action="list" returned it.
"""
params: dict[str, Any] = {"action": action}
if context is not None:
params["context"] = context
if device_type is not None:
params["device_type"] = device_type
if detail is not None:
params["detail"] = detail
if issue is not None:
params["issue"] = issue
return await asyncio.to_thread(_run_handler_sync, injection_skills_handler, params)
# ── Auth‑wrapped Streamable HTTP app ──────────────────────────────────
def _make_auth_wrapper(inner_app):
"""Wrap the SSE app with JWT validation.
"""Wrap the Streamable HTTP app with JWT validation.
Every request (POST / GET / DELETE) is authenticated. This is stricter
than the SSE transport, where only the opening GET was checked and
POSTs were trusted by session.
Supports two ways to pass the token (checked in order):
1. Authorization: Bearer <jwt> header
2. ?token=<jwt> query parameter
POST messages are passed through (authenticated by their session).
2. ?token=<jwt> query parameter (kept for GET streams opened by
clients that cannot set headers)
"""
async def auth_wrapper(scope, receive, send):
@@ -2130,7 +2393,7 @@ def _make_auth_wrapper(inner_app):
await response(scope, receive, send)
return
if scope["type"] == "http" and scope["method"] == "GET":
if scope["type"] == "http":
token = None
headers = dict(scope.get("headers", []))
auth = headers.get(b"authorization", b"").decode()
@@ -2151,6 +2414,11 @@ def _make_auth_wrapper(inner_app):
await response(scope, receive, send)
return
_jwt_token_var.set(resolved)
# Remember the raw API key: the session task created by the
# initialize request inherits this context and uses it to renew
# its JWT once the minted one ages out (see _renew_expired_jwt).
if token.startswith("gns3_"):
_jwt_api_key_var.set(token)
await inner_app(scope, receive, send)
return auth_wrapper
@@ -2169,19 +2437,51 @@ async def mcp_root():
"version": "1.0.0",
"authentication": ["Authorization: Bearer <jwt>", "?token=<jwt>"],
"transports": {
"sse": "/v3/mcp/transport/sse",
"streamable_http": "/v3/mcp/transport",
},
}
# The auth-wrapped Streamable HTTP app — built once, mounted on the FastAPI
# app by register_starlette_routes() and reused by mcp_session_manager_lifespan().
_streamable_app = None
def _ensure_streamable_app():
"""Build the auth-wrapped Streamable HTTP app on first use."""
global _streamable_app
if _streamable_app is None:
_streamable_app = _make_auth_wrapper(
mcp.streamable_http_app(
streamable_http_path="/transport",
transport_security=_transport_security(),
)
)
return _streamable_app
@contextlib.asynccontextmanager
async def mcp_session_manager_lifespan():
"""Run the Streamable HTTP session manager for the lifetime of the GNS3 app.
Starlette does not run lifespans of mounted sub-apps, so the manager must
be entered in the FastAPI lifespan (gns3server.core.tasks.lifespan).
Enter it before startup finishes: the MCP ready gate opens at the end of
startup, and no request may pass it before the session manager is running
(its task group would otherwise reject the request).
"""
_ensure_streamable_app()
async with mcp.session_manager.run():
yield
def register_starlette_routes(app):
"""Mount MCP transports on the FastAPI app."""
"""Mount the MCP Streamable HTTP transport on the FastAPI app."""
global _app
_app = app
sse_app = _make_auth_wrapper(mcp.sse_app(mount_path=""))
app.mount("/v3/mcp/transport", sse_app, name="mcp-sse")
log.info("MCP SSE server mounted at /v3/mcp/transport")
app.mount("/v3/mcp", _ensure_streamable_app(), name="mcp-streamable-http")
log.info("MCP Streamable HTTP server mounted at /v3/mcp/transport")
# Log registered MCP tools for verification
tool_names = list(mcp._tool_manager._tools.keys())
log.info("MCP tools registered (%d): %s", len(tool_names), ", ".join(sorted(tool_names)))
tool_names = sorted(tool.name for tool in mcp._tool_manager.list_tools())
log.info("MCP tools registered (%d): %s", len(tool_names), ", ".join(tool_names))
+415
View File
@@ -0,0 +1,415 @@
#
# Copyright (C) 2026 GNS3 Technologies Inc.
# Author: Yue Guobin
#
# 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 a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
node_console_exec: one-shot node console executor.
Server-side equivalent of the client-side chain this workflow used to need:
node_console (mint URL+ticket) -> bash: { sleep ..; printf 'cmd\r\n'; .. }
| timeout N websocat -b --no-close '<url>'
One tool call is one complete console session: the server spawns
``timeout N websocat -b --no-close <url>``, feeds the command lines through
stdin, keeps reading stdout until the timeout kills websocat, and returns the
collected output as plain text. No session state survives the call; node-side
state (config mode, running pings) persists across calls by nature of the
console itself.
The transport is deliberately the host's websocat binary instead of a
self-built WebSocket client — the same wire behavior as the field-proven
bash template, including its quirks (raw byte stream, no early return).
Output funnel: up to DIRECT_LINES lines are returned as-is. Beyond that a
SAMPLE_LINES excerpt comes back with retrieval hints — re-filter the cached
capture (regrep), dump its tail (full), or download the whole capture written
to the node's files. The raw capture is cached per node so a second look at a
command's output never re-runs it (and never repeats its side effects).
"""
import asyncio
import contextlib
import logging
import math
import os
import re
import signal
from typing import Any
from gns3server.services import access_ticket_service
log = logging.getLogger(__name__)
# Wall clock of the whole session (connect + send + receive), matching
# `timeout N websocat`. Field-tested sizing: 2-3 verification commands fit
# in 15 s; 46-50 config lines (~15 s of paced input) need 30 s or more.
DEFAULT_TIMEOUT_S = 15.0
MAX_TIMEOUT_S = 300.0
# Pacing between command lines. Consoles ingest lines much slower than a
# local shell (IOL polls its console ~50 ms per key; remote pty echo lags),
# and dumping 50 lines at once can drop input.
LINE_INTERVAL_S = 0.3
# Output funnel thresholds.
DIRECT_LINES = 50
SAMPLE_LINES = 10
FULL_LINES = 400
MAX_OUTPUT_BYTES = 64 * 1024
# Flood guard for one session: stop collecting after this much raw output.
MAX_CAPTURE_BYTES = 8 * 1024 * 1024
CAPTURE_FILE = "console-capture.txt"
# Newest raw output per node (resolved UUIDs) — the regrep/full target.
_OUTPUT_CACHE: dict[tuple[str, str], str] = {}
def prepare_payloads(command: str) -> list[str]:
"""Split a command string into console-ready stdin payloads.
Each line becomes one write:
- a plain line gets ``\\r\\n`` appended (consoles need the carriage
return; a bare ``\\n`` does not execute on most NOS),
- a line already ending in ``\\r`` only gets the ``\\n``,
- a line containing control characters (``\\x03`` and friends) is sent
verbatim with no line ending — it is a keypress, not a command.
"""
payloads = []
for line in command.split("\n"):
if line.endswith("\r"):
payloads.append(line + "\n")
elif any(ord(ch) < 0x20 and ch != "\t" for ch in line):
payloads.append(line)
else:
payloads.append(line + "\r\n")
return payloads
def _ws_url(server_url: str, project_id: str, node_id: str, token: str) -> str:
"""Console WS URL on the controller (it proxies to the node's compute)."""
url = f"{server_url}/v3/projects/{project_id}/nodes/{node_id}/console/ws"
url = url.replace("https://", "wss://").replace("http://", "ws://")
# JWTs are base64url + dots, safe in a query string as-is.
return f"{url}?token={token}"
async def _resolve_console_node(
project_id: str,
node_id: str,
gns3_ctx: dict[str, Any],
validate_console: bool = True,
) -> tuple[dict[str, Any] | None, str | None]:
"""Fetch the node (resolving names to UUIDs) and validate its console.
Returns (node dict, None) or (None, plain error text). Name resolution
goes through the same ``resolve_locators`` choke point as every other
tool (known-names fast failure included). With ``validate_console`` off,
only existence is required (the regrep path reads a capture from a node
that may since have been stopped).
"""
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import _get_connector
from gns3server.agent.mcp.locators import resolve_locators
def resolve_and_fetch() -> dict[str, Any]:
resolved, resolution_error = resolve_locators(
{"project_id": project_id, "node_id": node_id},
lambda handler, params: handler(params, gns3_ctx),
)
if resolved is None:
assert resolution_error is not None # resolve_locators' None-error contract
return resolution_error
conn = _get_connector(gns3_ctx)
url = f"{conn.base_url}/projects/{resolved['project_id']}/nodes/{resolved['node_id']}"
return conn.http_call("get", url).json()
try:
node = await asyncio.to_thread(resolve_and_fetch)
except Exception as e:
return None, f"could not resolve project '{project_id}' / node '{node_id}': {e}"
if "error" in node: # resolution failure dict from resolve_locators
return None, str(node["error"])
if not validate_console:
return node, None
name = node.get("name", node_id)
if (node.get("console_type") or "telnet") == "vnc":
return None, f"node '{name}' has a VNC console (pixel stream) — there is no text command channel"
if not node.get("console"):
return None, f"node '{name}' has no console"
if node.get("status") != "started":
return None, f"node '{name}' is {node.get('status')} — start it before using the console"
return node, None
async def _spawn(url: str, seconds: int) -> asyncio.subprocess.Process:
"""Start ``timeout <seconds> websocat -b --no-close <url>``.
Binary mode is mandatory, not a preference: in text mode (-t, and also
the default) websocat appends a ``\\n`` 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 arrives
diced into short lines mid-word (field symptom: prompts split into
pieces, "narrow columns"). ``-b`` is byte-exact in both directions;
binary command frames are still handled as data by the compute console
handler.
The subprocess gets its own process group: websocat is a child of
``timeout``, and a cancelled call must take down the whole tree (an
externally killed ``timeout`` alone could orphan websocat).
"""
return await asyncio.create_subprocess_exec(
"timeout",
str(seconds),
"websocat",
"-b",
"--no-close",
url,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
start_new_session=True,
)
async def _feed_lines(stdin: asyncio.StreamWriter, payloads: list[str]) -> None:
"""Write one payload per turn with pacing, then half-close stdin."""
try:
for payload in payloads:
stdin.write(payload.encode("utf-8", errors="replace"))
await stdin.drain()
await asyncio.sleep(LINE_INTERVAL_S)
finally:
stdin.close()
async def _drain_stream(stream: asyncio.StreamReader | None, cap: int) -> bytes:
"""Read a subprocess stream to EOF, stopping at ``cap`` bytes."""
if stream is None:
return b""
chunks: list[bytes] = []
total = 0
while total < cap:
block = await stream.read(65536)
if not block:
break
chunks.append(block)
total += len(block)
return b"".join(chunks)
async def _run_session(url: str, payloads: list[str], seconds: int) -> tuple[bytes, bytes, int | None]:
"""Run one websocat session: feed the payloads, collect stdout until EOF.
Returns (stdout, stderr, returncode). Exit code 124 (the ``timeout``
kill) is the normal end of a session; websocat exiting on its own means
the console side dropped the connection.
"""
try:
proc = await _spawn(url, seconds)
except FileNotFoundError:
return b"", b"timeout binary not found", -1
# stdin/stdout/stderr were requested as PIPE, so the Optional is static only
assert proc.stdin is not None and proc.stdout is not None and proc.stderr is not None
feed_task = asyncio.create_task(_feed_lines(proc.stdin, payloads))
stderr_task = asyncio.create_task(_drain_stream(proc.stderr, 64 * 1024))
try:
stdout = await _drain_stream(proc.stdout, MAX_CAPTURE_BYTES)
returncode = await proc.wait()
return stdout, await stderr_task, returncode
except asyncio.CancelledError:
with contextlib.suppress(ProcessLookupError, PermissionError):
os.killpg(proc.pid, signal.SIGTERM)
raise
finally:
feed_task.cancel()
stderr_task.cancel()
with contextlib.suppress(asyncio.CancelledError, BrokenPipeError, ConnectionResetError):
await feed_task
with contextlib.suppress(asyncio.CancelledError):
await stderr_task
if proc.returncode is None:
with contextlib.suppress(ProcessLookupError):
proc.kill()
with contextlib.suppress(asyncio.CancelledError):
await proc.wait()
def _session_error(stderr: bytes, returncode: int | None, seconds: int) -> str:
"""Classify an output-less session into plain error text."""
err = stderr.decode("utf-8", errors="replace").strip()
# coreutils timeout exits 125 when it cannot run the command; the
# message text is the reliable marker for a missing websocat.
if "failed to run command" in err or returncode in (125, 127):
return (
"websocat is not installed on the server host — install it "
"(https://github.com/vi/websocat/releases or `cargo install websocat`) and retry"
)
if returncode == 124:
return (
f"no console output within {seconds}s — the console may still be booting or silent; "
"retry with a larger timeout"
)
detail = f": {err[-400:]}" if err else ""
return f"websocat exited with code {returncode}{detail}"
def _tail_bytes(text: str, cap: int) -> tuple[str, bool]:
"""Byte-cap a string from the end; returns (text, was_capped)."""
encoded = text.encode("utf-8", errors="replace")
if len(encoded) <= cap:
return text, False
return encoded[-cap:].decode("utf-8", errors="replace"), True
def shape_view(text: str, grep: str | None, full: bool) -> tuple[str, dict[str, Any] | None]:
"""Filter and size the captured text for return.
Returns (reply_body, None) for a final reply — including the plain-error
cases (invalid pattern, grep miss) — or (header, metadata) when the
output exceeded DIRECT_LINES: the caller appends retrieval hints to the
metadata-carrying header (it knows the download URL).
"""
shown = text.splitlines()
if grep is not None:
try:
pattern = re.compile(grep)
except re.error as e:
return f"invalid grep pattern {grep!r}: {e}", None
shown = [line for line in shown if pattern.search(line)]
if not shown:
return (
f"grep {grep!r} matched nothing — {len(text.splitlines())} lines captured. "
"Retry with a wider pattern and regrep=true (re-filters the capture, no re-run), "
f"or regrep=true + full=true to dump its last {FULL_LINES} lines.",
None,
)
if full:
tail = shown[-FULL_LINES:]
body, capped = _tail_bytes("\n".join(tail), MAX_OUTPUT_BYTES)
header = f"output: last {len(tail)} of {len(shown)} lines"
if len(shown) > FULL_LINES:
header += f" (line cap {FULL_LINES})"
if capped:
header += f" (byte cap {MAX_OUTPUT_BYTES // 1024} KiB)"
return f"{header}\n{body}", None
if len(shown) > DIRECT_LINES:
sample = "\n".join(shown[:SAMPLE_LINES])
header = f"output: {len(shown)} lines total — first {SAMPLE_LINES} shown:\n{sample}\n---"
return header, {"lines": len(shown), "grep": grep}
body = "\n".join(shown) if grep is not None else text
return f"output:\n{body}", None
def _write_capture_and_url(text: str, project_id: str, node_id: str, gns3_ctx: dict[str, Any]) -> str | None:
"""Persist the raw capture into the node's files; return a ticketed download URL.
The file route and the path-bound access ticket are the same mechanism
the capture-download tool uses. Any failure here only costs the hint,
not the reply — return None and let the caller fall back.
"""
from gns3server.agent.gns3_copilot.gns3_client.api_handlers import _get_connector
username = gns3_ctx.get("jwt_username")
if not username:
return None
try:
conn = _get_connector(gns3_ctx)
conn.http_call(
"post",
f"{conn.base_url}/projects/{project_id}/nodes/{node_id}/files/{CAPTURE_FILE}",
data=text,
headers={"Content-Type": "text/plain"},
)
except Exception as e:
log.warning("Could not write the console capture file for node %s: %s", node_id, e)
return None
path = f"/v3/projects/{project_id}/nodes/{node_id}/files/{CAPTURE_FILE}"
ticket = access_ticket_service.mint(username, token_version=gns3_ctx.get("jwt_token_version", 0), path=path)
return f"{gns3_ctx['server_url']}{path}?token={ticket}"
async def console_exec(
project_id: str,
node_id: str,
command: str,
timeout: float, # noqa: ASYNC109 - operation-specific timeout is intentional
grep: str | None = None,
regrep: bool = False,
full: bool = False,
gns3_ctx: dict[str, Any] | None = None,
) -> str:
"""Run one one-shot console session (or re-view its capture) as plain text."""
assert gns3_ctx is not None
node, error = await _resolve_console_node(project_id, node_id, gns3_ctx, validate_console=not regrep)
if error is not None:
return error
assert node is not None
key = (str(node["project_id"]), str(node["node_id"]))
if regrep:
text = _OUTPUT_CACHE.get(key)
if text is None:
return (
f"no captured output for node '{node.get('name', node_id)}' yet — "
"run a command first, then re-filter it with regrep=true"
)
else:
url = _ws_url(gns3_ctx["server_url"], key[0], key[1], gns3_ctx.get("jwt_token") or "")
payloads = prepare_payloads(command) or ["\r\n"]
seconds = max(1, math.ceil(min(max(float(timeout), 1.0), MAX_TIMEOUT_S)))
stdout, stderr, returncode = await _run_session(url, payloads, seconds)
if not stdout:
return _session_error(stderr, returncode, seconds)
# Raw console bytes decoded with replacement only — telnet/ANSI noise
# is left in on purpose (no stripping layer between AI and console).
text = stdout.decode("utf-8", errors="replace")
_OUTPUT_CACHE[key] = text
body, too_long = shape_view(text, grep, full)
if too_long is None:
return body
download_url = await asyncio.to_thread(_write_capture_and_url, text, key[0], key[1], gns3_ctx)
hints = [
f"{too_long['lines']} lines is too long to return whole. Without re-running the command:",
"- regrep=true + grep=<pattern> re-filters the captured output",
f"- regrep=true + full=true returns its last {FULL_LINES} lines",
]
if too_long["grep"] is None:
hints.append("- grep=<pattern> re-runs the command with the filter applied")
if download_url:
hints.append(f"- download the full capture: curl -o {CAPTURE_FILE} '{download_url}'")
return "\n".join([body, *hints])
+11 -125
View File
@@ -1,6 +1,6 @@
#
# Copyright (C) 2026 GNS3 Technologies Inc.
# Author: Yue Guobin
# Author: YueGuobin
#
# 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
@@ -22,6 +22,10 @@ These tools connect to network device consoles via telnet/SSH and execute
configuration or diagnostic commands. Device connection info is automatically
discovered from the project topology using the device's tags for device_type.
The actual execution lives in the shared runners under
``gns3_copilot/gns3_client/`` (plain classes, no LangChain): the MCP handlers
below and the copilot (through the MCP tool bridge) call the same code.
Prerequisites:
- Device must be started (use node_start / node_start_all)
- Device must have a 'device_type:<type>' tag set in GNS3
@@ -29,141 +33,23 @@ Prerequisites:
- Device must have a console port assigned
"""
import json
import logging
from typing import Any
from jinja2 import Template as JinjaTemplate
from jinja2 import TemplateError as JinjaError
log = logging.getLogger(__name__)
def _render_template(template: str, device_configs: list[dict], commands_field: str = "config_commands") -> list[dict]:
"""Render a Jinja2 template for each device's vars into the specified commands field.
Entries with the same device_name are merged into a single entry
so they share one Nornir session and avoid output fragmentation.
Each device in device_configs can have:
- "vars": dict of template variables (rendered into commands_field)
- commands_field: existing commands merged after rendering if present
Args:
commands_field: field name for the rendered commands, e.g. "config_commands", "commands"
"""
try:
jinja = JinjaTemplate(template)
except JinjaError as e:
# a syntactically invalid template must not escape as a raw exception
error_msg = f"Template rendering failed: {e}"
log.error(error_msg)
return [{"status": "failed", "error": error_msg}]
merged: dict[str, dict] = {}
for dev in device_configs:
name = dev.get("device_name")
if not name:
continue
vars_data = dev.get("vars", {})
if name not in merged:
merged[name] = {"device_name": name, commands_field: list(dev.get(commands_field, []))}
entry = merged[name]
if vars_data:
try:
output = jinja.render(**vars_data)
lines = [l for l in output.splitlines() if l.strip()]
entry[commands_field].extend(lines)
except JinjaError as e:
error_msg = f"Template rendering failed for '{name}': {e}"
log.error(error_msg)
return [{"status": "failed", "error": error_msg}]
return list(merged.values())
# ── Tool handlers ──────────────────────────────────────────────────────────
from gns3server.agent.gns3_copilot.gns3_client.device_config_commands import DeviceConfigCommandRunner
from gns3server.agent.gns3_copilot.gns3_client.device_show_commands import DeviceShowCommandRunner
from gns3server.agent.gns3_copilot.gns3_client.vpcs_commands import VpcsCommandRunner
def device_config_send_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> list[dict[str, Any]]:
"""Send configuration commands to network devices via console."""
project_id = params.get("project_id")
device_configs = params.get("device_configs")
template = params.get("template")
if not project_id or not device_configs:
return [{"status": "failed", "error": "project_id and device_configs are required"}]
if template:
device_configs = _render_template(template, device_configs, commands_field="config_commands")
if len(device_configs) == 1 and "error" in device_configs[0]:
return device_configs
from gns3server.agent.gns3_copilot.tools_v2.config_tools_nornir import ExecuteMultipleDeviceConfigCommands
tool = ExecuteMultipleDeviceConfigCommands()
input_data = json.dumps(
{
"project_id": project_id,
"device_configs": device_configs,
}
)
return tool._run(
input_data,
jwt_token=gns3_ctx["jwt_token"],
url=gns3_ctx["server_url"],
)
return DeviceConfigCommandRunner().run(params, gns3_ctx)
def device_show_run_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> list[dict[str, Any]]:
"""Run read-only diagnostic (show) commands on network devices."""
project_id = params.get("project_id")
device_configs = params.get("device_configs")
template = params.get("template")
if not project_id or not device_configs:
return [
{
"status": "failed",
"error": "project_id and device_configs (list of {device_name, commands}) are required",
}
]
if template:
device_configs = _render_template(template, device_configs, commands_field="commands")
if len(device_configs) == 1 and "error" in device_configs[0]:
return device_configs
from gns3server.agent.gns3_copilot.tools_v2.display_tools_nornir import ExecuteMultipleDeviceCommands
tool = ExecuteMultipleDeviceCommands()
input_data = json.dumps(
{
"project_id": project_id,
"device_configs": device_configs,
}
)
return tool._run(
input_data,
jwt_token=gns3_ctx["jwt_token"],
url=gns3_ctx["server_url"],
)
return DeviceShowCommandRunner().run(params, gns3_ctx)
def vpcs_config_set_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> list[dict[str, Any]]:
"""Configure VPCS devices (set IP, gateway, etc.)."""
project_id = params.get("project_id")
device_configs = params.get("device_configs")
if not project_id or not device_configs:
return [{"status": "failed", "error": "project_id and device_configs are required"}]
from gns3server.agent.gns3_copilot.tools_v2.vpcs_tools_netmiko import VPCSCommands
tool = VPCSCommands()
input_data = json.dumps(
{
"project_id": project_id,
"device_configs": device_configs,
}
)
return tool._run(
input_data,
jwt_token=gns3_ctx["jwt_token"],
url=gns3_ctx["server_url"],
)
return VpcsCommandRunner().run(params, gns3_ctx)
+150
View File
@@ -0,0 +1,150 @@
#
# Copyright (C) 2026 GNS3 Technologies Inc.
# Author: Yue Guobin
#
# 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 a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
MCP surface of the GNS3-Skills repository: device_skill_get and
injection_skill_get.
Both reuse the copilot's framework-free core instead of the LangChain
tool shell, so the access protocols stay in step by construction:
- device_skill_get: list -> device topic index -> one topic body
(get_skill / list_available_skills over SKILLS_REGISTRY).
- injection_skill_get: topology context -> fault category -> one fault
(get_injection_skill / list_available_injection_skills over
INJECTION_SKILLS_REGISTRY).
The caller picks each key from the previous call and passes it back
unchanged; there is no name guessing in this layer.
"""
import logging
from typing import Any
log = logging.getLogger(__name__)
def device_skills_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> dict[str, Any]:
"""List or fetch skills from the GNS3-Skills repository.
action "list" -> every loaded skill (device_type, name, topic_count).
Otherwise one skill by the key the list returned.
"""
try:
from gns3server.agent.gns3_copilot.skills import registry
except Exception as e:
log.debug("device_skill_get: skills registry unavailable: %s", e)
return {"status": "failed", "error": f"Skills subsystem unavailable: {e}"}
# First call on a fresh server may race the background repository
# load; triggering the (idempotent, retryable) init avoids returning
# an empty list just because the clone has not finished yet.
if not registry.SKILLS_REGISTRY and registry.get_skills_manager() is None:
return {
"status": "failed",
"error": "Skills repository is not initialized. Configure the GNS3-Skills repository "
"(skills_repo_url) and retry — the initial clone may still be running.",
}
action = params.get("action")
if not action:
# No explicit action: list when nothing to get, get otherwise.
action = "list" if not params.get("device_type") else "get"
if action == "list":
skills = registry.list_available_skills(params.get("category"))
return {"status": "ok", "count": len(skills), "skills": skills}
device_type = params.get("device_type")
if not device_type:
return {
"status": "failed",
"error": "Provide device_type (the skill key)",
"hint": "device_skill_get(action='list') enumerates what is loaded",
}
result = registry.get_skill(
device_type,
category=params.get("category"),
detail=params.get("detail", "full"),
issue=params.get("issue"),
topic=params.get("topic"),
)
if "error" in result:
return {"status": "failed", **result}
return {"status": "ok", "skill": result}
def injection_skills_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) -> dict[str, Any]:
"""List or fetch fault-injection skills from the GNS3-Skills repository.
action "list" requires ``context`` — the protocols/services found in
the topology — and returns only the matching fault categories.
Otherwise one category (detail index/summary/full) or a single issue.
"""
try:
from gns3server.agent.gns3_copilot.skills import registry
except Exception as e:
log.debug("injection_skill_get: skills registry unavailable: %s", e)
return {"status": "failed", "error": f"Skills subsystem unavailable: {e}"}
if not registry.INJECTION_SKILLS_REGISTRY and registry.get_skills_manager() is None:
return {
"status": "failed",
"error": "Skills repository is not initialized. Configure the GNS3-Skills repository "
"(skills_repo_url) and retry — the initial clone may still be running.",
}
action = params.get("action")
if not action:
# No explicit action: list when there is no category to fetch.
action = "list" if not params.get("device_type") else "get"
if action == "list":
context = params.get("context")
if not isinstance(context, list) or not context:
return {
"status": "failed",
"error": "context is required when action='list'",
"hint": 'Pass the protocols/services found in the topology, e.g. {"context": ["ospf", "bgp"]}',
"total_available": len(registry.INJECTION_SKILLS_REGISTRY),
}
skills = registry.list_available_injection_skills(context=context)
return {
"status": "ok",
"count": len(skills),
"total_available": len(registry.INJECTION_SKILLS_REGISTRY),
"context": context,
"fault_types": skills,
}
device_type = params.get("device_type")
if not device_type:
return {
"status": "failed",
"error": "Provide device_type (the fault category key from the list), e.g. 'injection_ospf_issues'",
"hint": "injection_skill_get(action='list', context=[...]) enumerates the matching categories",
}
result = registry.get_injection_skill(
device_type,
detail=params.get("detail", "full"),
issue=params.get("issue"),
)
if "error" in result:
return {"status": "failed", **result}
return {"status": "ok", "skill": result}
+5 -1
View File
@@ -56,8 +56,12 @@ def create_snapshot_handler(params: dict[str, Any], gns3_ctx: dict[str, Any]) ->
name = params.get("name")
if not project_id or not name:
return {"error": "project_id and name are required"}
body: dict[str, Any] = {"name": name}
description = params.get("description")
if description:
body["description"] = description
conn = _get_connector(gns3_ctx)
result = conn.http_call("post", f"{conn.base_url}/projects/{project_id}/snapshots", json_data={"name": name}).json()
result = conn.http_call("post", f"{conn.base_url}/projects/{project_id}/snapshots", json_data=body).json()
return {"message": f"Snapshot '{name}' created", "snapshot": result}
+8 -5
View File
@@ -20,7 +20,7 @@ Readable and unique OpenAPI operationIds.
"""
import re
from typing import Callable
from typing import Callable, Sequence
from fastapi import APIRouter
from fastapi.routing import APIRoute
@@ -46,10 +46,13 @@ def generate_operation_id(route: APIRoute) -> str:
return name
def add_stub_routes(router: APIRouter, endpoint: Callable, name: str) -> None:
def add_stub_routes(router: APIRouter, endpoint: Callable, name: str, paths: Sequence[str] = ("/{path:path}",)) -> None:
"""
Registers a catch-all route per HTTP method so that every method gets its own operationId.
Registers a stub route per path and HTTP method so that every method gets its own operationId.
The default path is a catch-all for everything under the router prefix.
"""
for method in STUB_METHODS:
router.add_api_route("/{path:path}", endpoint, methods=[method], name=f"{name}_{method.lower()}")
for index, path in enumerate(paths):
suffix = f"_{index}" if len(paths) > 1 else ""
for method in STUB_METHODS:
router.add_api_route(path, endpoint, methods=[method], name=f"{name}{suffix}_{method.lower()}")
+1 -10
View File
@@ -31,7 +31,6 @@ from gns3server.compute.compute_error import (
)
from gns3server.compute.error import ImageMissingError, NodeError
from gns3server.compute.ubridge.ubridge_error import UbridgeError
from gns3server.controller.gns3vm.gns3_vm_error import GNS3VMError
from gns3server.version import __api_version__
from . import (
@@ -68,6 +67,7 @@ compute_api = FastAPI(
)
compute_api.state.controller_host = None
compute_api.state.exiting = False
@compute_api.exception_handler(ComputeError)
@@ -115,15 +115,6 @@ async def compute_not_found_error_handler(request: Request, exc: ComputeNotFound
)
@compute_api.exception_handler(GNS3VMError)
async def compute_gns3vm_error_handler(request: Request, exc: GNS3VMError):
log.error(f"Compute GNS3 VM error: {exc}")
return JSONResponse(
status_code=409,
content={"message": str(exc)},
)
@compute_api.exception_handler(ImageMissingError)
async def image_missing_error_handler(request: Request, exc: ImageMissingError):
log.error(f"Compute image missing error: {exc}")
+74 -3
View File
@@ -19,16 +19,24 @@ API routes for images.
"""
import os
import time
import urllib.parse
from typing import List, Optional
from fastapi import APIRouter, Body, HTTPException, Query, Request, status
from fastapi import APIRouter, Body, HTTPException, Path, Query, Request, status
from fastapi.responses import FileResponse
from gns3server.compute.docker import Docker
from gns3server.compute.docker.docker_error import DockerError
from gns3server.compute.dynamips import Dynamips
from gns3server.compute.iou import IOU
from gns3server.compute.notification_manager import NotificationManager
from gns3server.compute.qemu import Qemu
from gns3server.utils.images import DOCKER_IMAGE_NAME_PATTERN, validate_docker_image_name
# Daemon progress lines arrive dozens of times per second per layer: emit at
# most one downloading event per second per pull.
PULL_PROGRESS_INTERVAL = 1.0
router = APIRouter()
@@ -44,13 +52,55 @@ async def get_docker_images() -> List[dict]:
@router.post("/docker/images/pull", status_code=status.HTTP_204_NO_CONTENT)
async def pull_docker_image(image: str = Body(..., embed=True, min_length=1, pattern=r"^\S+$")) -> None:
async def pull_docker_image(
image: str = Body(..., embed=True, min_length=1, pattern=r"^\S+$"),
progress_id: Optional[str] = Query(
None, pattern=r"^\S+$", description="Client supplied id to correlate progress notifications"
),
) -> None:
"""
Pull or update a Docker image.
The pull progress is reported as docker.image.pull notifications: a
started event, throttled downloading events and a terminal completed or
failed event. The optional progress_id is echoed in every event so a
client can correlate them with its own request.
"""
docker_manager = Docker.instance()
await docker_manager.pull_image(image, force=True)
def emit(state: str, message: Optional[str] = None, progress: Optional[dict] = None) -> None:
event = {"image": image, "state": state}
if message is not None:
event["message"] = message
if progress is not None:
event["layers_total"] = progress["layers_total"]
event["layers_done"] = progress["layers_done"]
if progress_id is not None:
event["progress_id"] = progress_id
NotificationManager.instance().emit("docker.image.pull", event)
last_emit = 0.0
def progress_callback(progress: dict) -> None:
nonlocal last_emit
# the started event comes from the pull itself, once it owns the lock,
# and is never throttled
if progress.get("state") == "started":
emit("started", progress["message"])
return
now = time.monotonic()
if now - last_emit < PULL_PROGRESS_INTERVAL:
return
last_emit = now
emit("downloading", progress["message"], progress)
try:
await docker_manager.pull_image(image, progress_callback=progress_callback, force=True)
except DockerError as e:
emit("failed", str(e))
raise
emit("completed", f"Success pulling image {image}")
@router.post("/docker/images/load", status_code=status.HTTP_204_NO_CONTENT)
@@ -73,6 +123,27 @@ async def load_docker_image(
await docker_manager.load_image(request.stream(), image=image, digest=digest)
@router.delete("/docker/images/{image:path}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_docker_image(
image: str = Path(..., pattern=DOCKER_IMAGE_NAME_PATTERN),
force: bool = Query(False, description="Remove the image even if a container uses it"),
) -> None:
"""
Delete a Docker image from the Docker daemon.
The daemon refuses to delete an image used by a container (even a stopped
one) and answers a conflict, unless force is set.
"""
image = urllib.parse.unquote(image)
try:
validate_docker_image_name(image)
except ValueError as e:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(e)) from e
docker_manager = Docker.instance()
await docker_manager.delete_image(image, force=force)
@router.get("/dynamips/images")
async def get_dynamips_images() -> List[dict]:
"""
@@ -44,7 +44,7 @@ async def project_ws_notifications(websocket: Union[None, WebSocket] = Depends(w
log.info(f"New client {client} has connected to compute WebSocket")
try:
with NotificationManager.instance().queue() as queue:
while True:
while not websocket.app.state.exiting:
notification = await queue.get_json(5)
await websocket.send_text(notification)
except (ConnectionClosed, WebSocketDisconnect):
@@ -329,7 +329,8 @@ async def console_ws(
Console WebSocket.
"""
await node.start_websocket_console(websocket)
if websocket:
await node.start_websocket_console(websocket)
@router.post(
+2 -1
View File
@@ -301,7 +301,8 @@ async def console_ws(
Console WebSocket.
"""
await node.start_websocket_console(websocket)
if websocket:
await node.start_websocket_console(websocket)
@router.post(
+32 -24
View File
@@ -21,6 +21,37 @@ from gns3server.agent import AI_COPILOT_AVAILABLE
from gns3server.api.operation_ids import add_stub_routes
from gns3server.config import Config
# The LLM model configuration routes share the /access prefix with users, groups and API keys,
# so their stub must cover only their own paths: a catch-all under /access would answer 501 for
# every /access route included after it (e.g. creating an API key).
LLM_STUB_PATHS = (
"/users/{user_id}/llm-model-configs{rest:path}",
"/groups/{group_id}/llm-model-configs{rest:path}",
)
async def ai_not_available():
raise HTTPException(
status_code=status.HTTP_501_NOT_IMPLEMENTED,
detail="AI Copilot is not available. Install AI dependencies with: pip install gns3-server[ai-features]",
)
def build_ai_stub_routers() -> tuple[APIRouter, APIRouter, APIRouter]:
"""
Stub routers (chat, copilot, LLM model configurations) that answer 501
when the AI dependencies are not installed.
"""
chat_router = APIRouter()
copilot_router = APIRouter()
llm_router = APIRouter()
add_stub_routes(chat_router, ai_not_available, "chat_not_available")
add_stub_routes(copilot_router, ai_not_available, "copilot_not_available")
add_stub_routes(llm_router, ai_not_available, "llm_not_available", paths=LLM_STUB_PATHS)
return chat_router, copilot_router, llm_router
# Conditionally import AI-dependent routes
if AI_COPILOT_AVAILABLE:
from . import chat, copilot, llm_model_configs
@@ -29,25 +60,7 @@ if AI_COPILOT_AVAILABLE:
_copilot_router = copilot.router
_llm_router = llm_model_configs.router
else:
# Create stub routers that return 501 for all AI endpoints
_chat_router = APIRouter()
_copilot_router = APIRouter()
_llm_router = APIRouter()
@_chat_router.api_route("/{path:path}", methods=["GET", "POST", "DELETE", "PATCH", "PUT"], include_in_schema=False)
@_copilot_router.api_route(
"/{path:path}", methods=["GET", "POST", "DELETE", "PATCH", "PUT"], include_in_schema=False
)
@_llm_router.api_route("/{path:path}", methods=["GET", "POST", "DELETE", "PATCH", "PUT"], include_in_schema=False)
async def ai_not_available(path: str = ""):
raise HTTPException(
status_code=status.HTTP_501_NOT_IMPLEMENTED,
detail="AI Copilot is not available. Install AI dependencies with: pip install gns3-server[ai-features]",
)
add_stub_routes(_chat_router, ai_not_available, "chat_not_available")
add_stub_routes(_copilot_router, ai_not_available, "copilot_not_available")
add_stub_routes(_llm_router, ai_not_available, "llm_not_available")
_chat_router, _copilot_router, _llm_router = build_ai_stub_routers()
from . import (
@@ -57,7 +70,6 @@ from . import (
computes,
controller,
drawings,
gns3vm,
groups,
images,
links,
@@ -121,10 +133,6 @@ router.include_router(netmiko.router, prefix="/netmiko", tags=["Netmiko"])
router.include_router(pools.router, prefix="/pools", tags=["Resource pools"])
router.include_router(
gns3vm.router, dependencies=[Depends(get_current_active_user)], deprecated=True, prefix="/gns3vm", tags=["GNS3 VM"]
)
router.include_router(
_llm_router,
prefix="/access",
-3
View File
@@ -203,9 +203,6 @@ async def create_ace(
Required privilege: ACE.Allocate
"""
for route_path in _iter_route_paths(request.app.routes, include_mounted_routes=True):
print(route_path)
for route_path in _iter_route_paths(request.app.routes, include_mounted_routes=True):
# remove the prefix (e.g. "/v3") from the route path
normalized_path = re.sub(r"^/v[0-9]", "", route_path)
+104 -3
View File
@@ -21,7 +21,7 @@ API routes for computes.
from typing import Any, List, Optional, Union
from uuid import UUID
from fastapi import APIRouter, Body, Depends, Query, status
from fastapi import APIRouter, Body, Depends, HTTPException, Path, Query, Request, status
import gns3server.db.models as models
from gns3server import schemas
@@ -29,7 +29,13 @@ from gns3server.controller import Controller
from gns3server.controller.controller_error import ControllerBadRequestError, ControllerError
from gns3server.db.repositories.computes import ComputesRepository
from gns3server.db.repositories.rbac import RbacRepository
from gns3server.db.repositories.templates import TemplatesRepository
from gns3server.services.computes import ComputesService
from gns3server.utils.images import (
DOCKER_IMAGE_NAME_PATTERN,
canonical_docker_image_name,
validate_docker_image_name,
)
from .dependencies.database import get_repository
from .dependencies.rbac import has_privilege
@@ -215,16 +221,111 @@ async def docker_get_images(compute_id: Union[str, UUID]) -> List[schemas.Comput
dependencies=[Depends(has_privilege("Compute.Modify"))],
)
async def docker_pull_image(
compute_id: Union[str, UUID], image: str = Body(..., embed=True, min_length=1, pattern=r"^\S+$")
compute_id: Union[str, UUID],
image: str = Body(..., embed=True, min_length=1, pattern=r"^\S+$"),
progress_id: Optional[str] = Query(
None, pattern=r"^\S+$", description="Client supplied id to correlate progress notifications"
),
) -> None:
"""
Pull or update a Docker image on a compute.
The pull progress is reported on the controller notification stream as
docker.image.pull events (started, downloading, completed or failed). The
optional progress_id is echoed in every event so a client can correlate
them with its own request.
Required privilege: Compute.Modify
"""
compute = Controller.instance().get_compute(str(compute_id))
await compute.forward("POST", "docker", "images/pull", data={"image": image})
params = {"progress_id": progress_id} if progress_id is not None else None
await compute.forward("POST", "docker", "images/pull", data={"image": image}, params=params)
@router.post(
"/{compute_id}/docker/images/load",
status_code=status.HTTP_204_NO_CONTENT,
dependencies=[Depends(has_privilege("Compute.Modify"))],
)
async def docker_load_image(compute_id: Union[str, UUID], request: Request) -> None:
"""
Load a Docker image on a compute from a docker save tar stream.
The tar archive (plain or gzip compressed) is streamed to the compute
and loaded into its Docker daemon, without buffering the whole file
in the controller memory.
Required privilege: Compute.Modify
"""
compute = Controller.instance().get_compute(str(compute_id))
await compute.http_query("POST", "/docker/images/load", data=request.stream(), timeout=None)
@router.delete(
"/{compute_id}/docker/images/{image:path}",
status_code=status.HTTP_204_NO_CONTENT,
dependencies=[Depends(has_privilege("Compute.Modify"))],
)
async def docker_delete_image(
compute_id: Union[str, UUID],
image: str = Path(..., pattern=DOCKER_IMAGE_NAME_PATTERN),
force: bool = Query(False, description="Remove the image even if a container uses it"),
templates_repo: TemplatesRepository = Depends(get_repository(TemplatesRepository)),
) -> None:
"""
Delete a Docker image on a compute.
The deletion is refused while templates reference the image, unless force
is set. The compute also refuses an image used by a container (even a
stopped one) and answers a conflict naming the GNS3 nodes and projects
using it.
After a successful deletion a docker.image.deleted notification is
emitted on the controller notification stream, with the templates that
referenced the image, so clients can refresh their image lists.
Required privilege: Compute.Modify
"""
try:
validate_docker_image_name(image)
except ValueError as e:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(e)) from e
canonical_image = canonical_docker_image_name(image)
referencing_templates = [
str(template.name)
for template in await templates_repo.get_templates()
if isinstance(template, models.DockerTemplate)
and template.image
and canonical_docker_image_name(str(template.image)) == canonical_image
]
if referencing_templates and not force:
# refuse before touching the compute: the client can prompt the user
# and repeat with force once the user confirms
raise ControllerError(
f"Image '{image}' is referenced by template(s): {', '.join(referencing_templates)}. "
f"Delete the templates first or repeat with force=true.",
code="image_referenced_by_templates",
details={"referenced_by_templates": referencing_templates},
)
compute = Controller.instance().get_compute(str(compute_id))
await compute.http_query("DELETE", f"/docker/images/{image}", params={"force": str(force).lower()})
# tell the clients the image changed on this compute: they can refresh
# their image lists, and the templates that referenced the image can no
# longer start their nodes
Controller.instance().notification.controller_emit(
"docker.image.deleted",
{
"compute_id": str(compute_id),
"image": image,
"referenced_by_templates": referencing_templates,
},
)
@router.get("/{compute_id}/virtualbox/vms", response_model=List[schemas.ComputeVirtualBoxVM])
+1 -10
View File
@@ -308,7 +308,7 @@ async def controller_ws_notifications(
log.info(f"New client {client} has connected to controller WebSocket")
try:
with Controller.instance().notification.controller_queue() as queue:
while True:
while not websocket.app.state.exiting:
notification = await queue.get_json(5)
await websocket.send_text(notification)
except (ConnectionClosed, WebSocketDisconnect):
@@ -340,15 +340,6 @@ async def controller_ws_notifications(
# # If something is wrong we log the info to the log and we hope the log will be include correctly to the debug export
# log.error("Could not export debug information {}".format(e), exc_info=1)
#
# try:
# if Controller.instance().gns3vm.engine == "vmware":
# vmx_path = Controller.instance().gns3vm.current_engine().vmx_path
# if vmx_path:
# shutil.copy(vmx_path, os.path.join(debug_dir, os.path.basename(vmx_path)))
# except OSError as e:
# # If something is wrong we log the info to the log and we hope the log will be include correctly to the debug export
# log.error("Could not copy VMware VMX file {}".format(e), exc_info=1)
#
# for compute in list(Controller.instance().computes.values()):
# try:
# r = await compute.get("/debug", raw=True)
@@ -191,10 +191,13 @@ async def get_current_active_user_from_websocket(
try:
if token.startswith(TICKET_PREFIX):
# Node-bound access tickets ("gns3t_…"): short-lived credentials
# for one node's console endpoints, minted by the node_console
# MCP tool. redeem() confines them to the route matching their
# binding, so they cannot authenticate the notification/wireshark
# sockets that share this dependency.
# for one node's console endpoints. No MCP tool currently mints
# them (node_console_exec connects server-side with the session
# JWT), but the redemption path is kept as the designated
# mechanism for handing node console access to external clients.
# redeem() confines them to the route matching their binding, so
# they cannot authenticate the notification/wireshark sockets
# that share this dependency.
ticket = access_ticket_service.redeem(token, websocket.path_params)
if ticket is None:
raise HTTPException(
@@ -1,72 +0,0 @@
#!/usr/bin/env python
#
# Copyright (C) 2020 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 a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
API routes for managing the GNS3 VM.
"""
from typing import List
from fastapi import APIRouter
from fastapi.encoders import jsonable_encoder
from gns3server import schemas
from gns3server.controller import Controller
router = APIRouter()
@router.get("/engines", response_model=List[schemas.GNS3VMEngineInfo])
async def get_engines() -> List[dict]:
"""
Return the list of supported engines for the GNS3VM.
"""
gns3_vm = Controller().instance().gns3vm
return gns3_vm.engine_list()
@router.get("/engines/{engine}/vms", response_model=List[schemas.GNS3VMInfo])
async def get_vms(engine: str) -> List[dict]:
"""
Return all the available VMs for a specific virtualization engine.
"""
vms = await Controller.instance().gns3vm.list(engine)
return vms
@router.get("", response_model=schemas.GNS3VM)
async def get_gns3vm_settings() -> schemas.GNS3VM:
"""
Return the GNS3 VM settings.
"""
return Controller.instance().gns3vm.asdict()
@router.put("", response_model=schemas.GNS3VM, response_model_exclude_unset=True)
async def update_gns3vm_settings(gns3vm_data: schemas.GNS3VM) -> schemas.GNS3VM:
"""
Update the GNS3 VM settings.
"""
controller = Controller().instance()
gns3_vm = controller.gns3vm
await gns3_vm.update_settings(jsonable_encoder(gns3vm_data, exclude_unset=True))
controller.save()
return gns3_vm.asdict()
+1 -1
View File
@@ -140,7 +140,7 @@ async def delete_user_group(
success = await users_repo.delete_user_group(user_group_id)
if not success:
raise ControllerError(f"User group '{user_group_id}' could not be deleted")
await rbac_repo.delete_all_ace_starting_with_path(f"/groups/{user_group_id}")
await rbac_repo.delete_all_ace_starting_with_path(f"/access/groups/{user_group_id}")
@router.get(
+14 -23
View File
@@ -33,7 +33,6 @@ from fastapi.routing import APIRoute
from gns3server import schemas
from gns3server.api.openapi import binary_request_body, binary_response
from gns3server.config import Config
from gns3server.controller import Controller
from gns3server.controller.controller_error import (
ControllerBadRequestError,
@@ -859,18 +858,15 @@ async def ws_console(
try:
# forward WebSocket data in both directions between the client and the compute console WebSocket
log.info(f"Forwarding console WebSocket to '{ws_console_compute_url}'")
server_config = Config.instance().settings.Server
user = server_config.compute_username
password = server_config.compute_password
if not user:
raise ControllerForbiddenError("Compute username is not set")
user = user.strip()
if user and password:
auth = aiohttp.BasicAuth(user, password.get_secret_value(), "utf-8")
else:
auth = aiohttp.BasicAuth(user, "")
# authenticate with the credentials of this compute, not with the local server
# credentials: they only match for the local compute
headers = {}
if compute.auth_header:
headers["Authorization"] = compute.auth_header
ssl_context = Controller.instance().ssl_context()
async with HTTPClient.get_client().ws_connect(ws_console_compute_url, auth=auth, ssl_context=ssl_context) as ws:
async with HTTPClient.get_client().ws_connect(
ws_console_compute_url, headers=headers, ssl_context=ssl_context
) as ws:
tasks = [
asyncio.ensure_future(ws_receive(ws)),
asyncio.ensure_future(ws_send(ws)),
@@ -957,19 +953,14 @@ async def vnc_console(
try:
# forward WebSocket data in both directions between the client and the compute VNC console WebSocket
log.info(f"Forwarding VNC console WebSocket to '{vnc_console_compute_url}'")
server_config = Config.instance().settings.Server
user = server_config.compute_username
password = server_config.compute_password
if not user:
raise ControllerForbiddenError("Compute username is not set")
user = user.strip()
if user and password:
auth = aiohttp.BasicAuth(user, password.get_secret_value(), "utf-8")
else:
auth = aiohttp.BasicAuth(user, "")
# authenticate with the credentials of this compute, not with the local server
# credentials: they only match for the local compute
headers = {}
if compute.auth_header:
headers["Authorization"] = compute.auth_header
ssl_context = Controller.instance().ssl_context()
async with HTTPClient.get_client().ws_connect(
vnc_console_compute_url, auth=auth, ssl_context=ssl_context
vnc_console_compute_url, headers=headers, ssl_context=ssl_context
) as ws:
tasks = [
asyncio.ensure_future(vnc_receive(ws)),
+50 -4
View File
@@ -126,10 +126,12 @@ async def get_projects(
# Step 2: Filter direct ACE projects by created_by
# Direct project sharing is only available through resource pools
# Projects created before the created_by field existed (GNS3 < 3.1) have no
# owner: fall back to the ACE-only visibility rule instead of hiding them.
for p in controller.projects.values():
if name is not None and p.name != name:
continue
if p.id in direct_ace_ids and p.created_by == current_user.username:
if p.id in direct_ace_ids and (p.created_by is None or p.created_by == current_user.username):
if p.id not in seen_project_ids:
projects.append(p.asdict())
seen_project_ids.add(p.id)
@@ -189,6 +191,46 @@ def get_project(response: Response, project: Project = Depends(dep_project)) ->
return project_dict
@router.get(
"/{project_id}/me/privileges",
response_model=schemas.ProjectPrivileges,
responses=GET_RESPONSES,
dependencies=[Depends(has_privilege("Project.Audit"))],
)
async def get_logged_in_user_privileges_on_project(
current_user: schemas.User = Depends(get_current_active_user),
project: Project = Depends(dep_project),
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository)),
) -> schemas.ProjectPrivileges:
"""
Get the effective privileges of the current user on this project.
Unlike /access/users/me/privileges (flattened across all resource paths),
each privilege is evaluated on the project's resource path, so the result
reflects ACEs scoped to this project and resource pools containing it.
This is meant for rendering purposes (e.g. showing or hiding buttons in
the project view): the server remains the authority for permission checks.
Required privilege: Project.Audit
Example: curl -X GET http://host:port/v3/projects/{project_id}/me/privileges -H "Authorization: Bearer <token>"
"""
if current_user.is_superadmin:
privilege_names = sorted(privilege.name for privilege in await rbac_repo.get_privileges())
return schemas.ProjectPrivileges(is_superadmin=True, privileges=privilege_names)
path = f"/projects/{project.id}"
# the flat view is the superset: only privileges granted somewhere can be
# granted on this path, so only those need to be evaluated against it
candidates = await rbac_repo.get_user_privileges(current_user.user_id)
project_privileges = []
for name in candidates:
if await rbac_repo.check_user_has_privilege(current_user.user_id, path, name):
project_privileges.append(name)
return schemas.ProjectPrivileges(is_superadmin=False, privileges=sorted(project_privileges))
@router.put(
"/{project_id}",
response_model=schemas.Project,
@@ -659,7 +701,7 @@ async def project_ws_notifications(
log.info(f"New client has connected to the notification stream for project ID '{project.id}' (WebSocket method)")
try:
with controller.notification.project_queue(project.id) as queue:
while True:
while not websocket.app.state.exiting:
notification = await queue.get_json(5)
await websocket.send_text(notification)
except (ConnectionClosed, WebSocketDisconnect):
@@ -701,7 +743,7 @@ async def project_marker_ws_notifications(
)
try:
with controller.notification.project_marker_queue(project.id) as queue:
while True:
while not websocket.app.state.exiting:
notification = await queue.get_json(5)
await websocket.send_text(notification)
except (ConnectionClosed, WebSocketDisconnect):
@@ -884,7 +926,11 @@ async def duplicate_project(
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
reset_mac_addresses = project_data.reset_mac_addresses
new_project = await project.duplicate(name=project_data.name, reset_mac_addresses=reset_mac_addresses)
new_project = await project.duplicate(
name=project_data.name,
reset_mac_addresses=reset_mac_addresses,
user=current_user.username,
)
# Add the new project in the same resource pools if the duplicated project belongs to any
if pool_memberships:
+1 -1
View File
@@ -135,7 +135,7 @@ async def delete_role(
success = await rbac_repo.delete_role(role_id)
if not success:
raise ControllerError(f"Role '{role_id}' could not be deleted")
await rbac_repo.delete_all_ace_starting_with_path(f"/roles/{role_id}")
await rbac_repo.delete_all_ace_starting_with_path(f"/access/roles/{role_id}")
@router.get(
+19 -1
View File
@@ -67,7 +67,7 @@ async def create_snapshot(
Required privilege: Snapshot.Allocate
"""
snapshot = await project.snapshot(snapshot_data.name)
snapshot = await project.snapshot(snapshot_data.name, snapshot_data.description)
return snapshot.asdict()
@@ -88,6 +88,24 @@ def get_snapshots(project: Project = Depends(dep_project)) -> List[schemas.Snaps
return [s.asdict() for s in sorted(snapshots, key=lambda s: (s.created_at, s.name))]
@router.put(
"/{snapshot_id}",
response_model=schemas.Snapshot,
dependencies=[Depends(has_privilege("Snapshot.Allocate"))],
)
async def update_snapshot(
snapshot_data: schemas.SnapshotUpdate, snapshot_id: UUID, project: Project = Depends(dep_project)
) -> schemas.Snapshot:
"""
Update a snapshot, for example its description.
Required privilege: Snapshot.Allocate
"""
snapshot = project.update_snapshot(str(snapshot_id), snapshot_data.description)
return snapshot.asdict()
@router.delete(
"/{snapshot_id}", status_code=status.HTTP_204_NO_CONTENT, dependencies=[Depends(has_privilege("Snapshot.Allocate"))]
)
+2 -1
View File
@@ -21,6 +21,7 @@ API routes for symbols.
import logging
import os
from os.path import commonpath
from typing import Dict, List
from fastapi import APIRouter, Depends, Request, Response, status
@@ -170,7 +171,7 @@ async def delete_symbol(symbol_id: str) -> None:
# Check if it's a built-in symbol (in resource directory)
symbols_resource_dir = get_resource("symbols")
if symbols_resource_dir and os.path.commonprefix([symbols_resource_dir, symbol_path]) == symbols_resource_dir:
if symbols_resource_dir and commonpath([symbols_resource_dir, symbol_path]) == symbols_resource_dir:
raise ControllerForbiddenError("Cannot delete built-in symbols")
# Delete the file
+26 -1
View File
@@ -165,6 +165,31 @@ async def update_logged_in_user(
return await users_repo.update_user(current_user.user_id, user_update)
@router.get("/me/privileges", response_model=schemas.UserPrivileges)
async def get_logged_in_user_privileges(
current_user: schemas.User = Depends(get_current_active_user),
rbac_repo: RbacRepository = Depends(get_repository(RbacRepository)),
) -> schemas.UserPrivileges:
"""
Get the effective privileges of the current active user.
The privileges are the union of everything granted by the roles assigned
to the user (directly or through group membership), flattened across all
resource paths. This is meant for rendering purposes (e.g. showing or
hiding parts of the UI): the server remains the authority for permission
checks and can still deny a privilege on a specific resource path.
Example: curl -X GET http://host:port/v3/access/users/me/privileges -H "Authorization: Bearer <token>"
"""
if current_user.is_superadmin:
privileges = sorted(privilege.name for privilege in await rbac_repo.get_privileges())
return schemas.UserPrivileges(is_superadmin=True, privileges=privileges)
privilege_names = await rbac_repo.get_user_privileges(current_user.user_id)
return schemas.UserPrivileges(is_superadmin=False, privileges=sorted(privilege_names))
@router.get("", response_model=List[schemas.User], dependencies=[Depends(has_privilege("User.Audit"))])
async def get_users(users_repo: UsersRepository = Depends(get_repository(UsersRepository))) -> List[models.User]:
"""
@@ -265,7 +290,7 @@ async def delete_user(
success = await users_repo.delete_user(user_id)
if not success:
raise ControllerError(f"User '{user_id}' could not be deleted")
await rbac_repo.delete_all_ace_starting_with_path(f"/users/{user_id}")
await rbac_repo.delete_all_ace_starting_with_path(f"/access/users/{user_id}")
@router.get(
+3 -1
View File
@@ -123,7 +123,7 @@ def get_application() -> FastAPI:
app = get_application()
# Register MCP SSE transport routes (Starlette-level, for raw ASGI access)
# Register MCP Streamable HTTP transport route (Starlette-level, for raw ASGI access)
if MCP_AVAILABLE:
mcp.register_starlette_routes(app)
@@ -134,6 +134,8 @@ unicorn_exit_handler = UvicornServer.handle_exit
def handle_exit(*args, **kwargs):
app.state.exiting = True
# The compute API is a mounted sub-app with its own State object.
compute_api.state.exiting = True
unicorn_exit_handler(*args, **kwargs)
+57 -20
View File
@@ -9,31 +9,59 @@
"documentation_url": "http://wiki.alpinelinux.org",
"product_name": "Alpine Linux",
"product_url": "https://www.alpinelinux.org/cloud/",
"registry_version": 4,
"registry_version": 8,
"status": "stable",
"maintainer": "GNS3 Team",
"maintainer_email": "developers@gns3.net",
"usage": "\nUsername: alpine\nPassword: alpine",
"port_name_format": "Ethernet{0}",
"qemu": {
"adapter_type": "virtio-net-pci",
"adapters": 1,
"ram": 1024,
"hda_disk_interface": "virtio",
"arch": "x86_64",
"console_type": "telnet",
"boot_priority": "c",
"kvm": "require",
"options": "-nographic"
},
"settings": [
{
"name": "default",
"default": true,
"template_type": "qemu",
"template_properties": {
"port_name_format": "eth{0}",
"adapter_type": "virtio-net-pci",
"adapters": 1,
"ram": 1024,
"hda_disk_interface": "virtio",
"console_type": "telnet",
"boot_priority": "c",
"options": "-nographic",
"uefi": true
}
},
{
"name": "x86_64",
"template_type": "qemu",
"template_properties": {
"platform": "x86_64"
}
},
{
"name": "aarch64",
"template_type": "qemu",
"template_properties": {
"platform": "aarch64"
}
}
],
"images": [
{
"filename": "generic_alpine-3.21.2-x86_64-bios-cloudinit-r0.qcow2",
"version": "3.21.2",
"md5sum": "b40825dff2867e0ffaffbc4c87674462",
"filesize": 189726720,
"filename": "alpine-3.24.3-x86_64-cloudinit-r0.qcow2",
"version": "3.24.3 (x86_64)",
"md5sum": "1777b468113613662364905bb24b996a",
"filesize": 157810688,
"download_url": "https://www.alpinelinux.org/cloud/",
"direct_download_url": "https://dl-cdn.alpinelinux.org/alpine/v3.21/releases/cloud/generic_alpine-3.21.2-x86_64-bios-cloudinit-r0.qcow2"
"direct_download_url": "https://dl-cdn.alpinelinux.org/alpine/v3.24/releases/cloud/alpine-3.24.3-x86_64-cloudinit-r0.qcow2"
},
{
"filename": "alpine-3.24.3-aarch64-cloudinit-r0.qcow2",
"version": "3.24.3 (aarch64)",
"md5sum": "deb9e822f5304540329762c241dab60d",
"filesize": 157810688,
"download_url": "https://www.alpinelinux.org/cloud/",
"direct_download_url": "https://dl-cdn.alpinelinux.org/alpine/v3.24/releases/cloud/alpine-3.24.3-aarch64-cloudinit-r0.qcow2"
},
{
"filename": "alpine-cloud-init-data.iso",
@@ -46,9 +74,18 @@
],
"versions": [
{
"name": "3.21.2",
"name": "3.24.3 (x86_64)",
"settings": "x86_64",
"images": {
"hda_disk_image": "generic_alpine-3.21.2-x86_64-bios-cloudinit-r0.qcow2",
"hda_disk_image": "alpine-3.24.3-x86_64-cloudinit-r0.qcow2",
"cdrom_image": "alpine-cloud-init-data.iso"
}
},
{
"name": "3.24.3 (aarch64)",
"settings": "aarch64",
"images": {
"hda_disk_image": "alpine-3.24.3-aarch64-cloudinit-r0.qcow2",
"cdrom_image": "alpine-cloud-init-data.iso"
}
}
+6 -10
View File
@@ -23,12 +23,12 @@ import shutil
import socket
import stat
import struct
import sys
import aiofiles
log = logging.getLogger(__name__)
from os.path import commonpath
from typing import Type
from uuid import UUID, uuid4
@@ -307,10 +307,6 @@ class BaseManager:
:returns: True or False
"""
if sys.platform.startswith("darwin"):
if os.stat(executable).st_uid == 0:
return True
if os.geteuid() == 0:
# we are root, so we should have privileged access.
return True
@@ -321,9 +317,9 @@ class BaseManager:
# the executable has set UID bit.
return True
# test if the executable has the CAP_NET_RAW capability (Linux only)
# test if the executable has the CAP_NET_RAW capability
try:
if sys.platform.startswith("linux") and "security.capability" in os.listxattr(executable):
if "security.capability" in os.listxattr(executable):
caps = os.getxattr(executable, "security.capability")
required = (1 << 13) | ((1 << 12) if require_net_admin else 0)
if struct.unpack("<IIIII", caps)[1] & required == required:
@@ -485,7 +481,7 @@ class BaseManager:
path = force_unix_path(path)
for directory in valid_directory_prefices:
log.debug(f"Searching for image '{orig_path}' in '{directory}'")
if os.path.commonprefix([directory, path]) == directory:
if commonpath([directory, path]) == directory:
if os.path.exists(path):
return path
raise ImageMissingError(orig_path)
@@ -530,7 +526,7 @@ class BaseManager:
valid_directory_prefices.append(extra_dir)
for directory in valid_directory_prefices:
if os.path.commonprefix([directory, path]) == directory:
if commonpath([directory, path]) == directory:
relpath = os.path.relpath(path, directory)
# We don't allow to recurse search from the top image directory just for image type directory (compatibility with old releases)
if os.sep not in relpath or directory == img_directory:
@@ -562,7 +558,7 @@ class BaseManager:
directory = self.get_images_directory()
path = os.path.abspath(os.path.join(directory, *os.path.split(filename)))
if os.path.commonprefix([directory, path]) != directory:
if commonpath([directory, path]) != directory:
raise ComputeForbiddenError(f"Could not write image: {filename}, '{path}' is forbidden")
log.info(f"Writing image file to '{path}'")
try:
+5 -18
View File
@@ -24,7 +24,6 @@ import re
import shutil
import stat
import struct
import sys
import tempfile
import asyncssh
@@ -34,7 +33,6 @@ from fastapi import WebSocketDisconnect
from gns3server.compute.compute_error import ComputeError
from gns3server.compute.ubridge.hypervisor import Hypervisor
from gns3server.compute.ubridge.ubridge_error import UbridgeError
from gns3server.utils.interfaces import interfaces
from ..compute.port_manager import PortManager
from ..utils.asyncio import locking, wait_run_in_executor
@@ -1491,28 +1489,15 @@ class BaseNode:
except UbridgeError as e:
log.warning(f"Could not resume markers on node {self._id}: {e}")
async def _add_ubridge_ethernet_connection(self, bridge_name, ethernet_interface, block_host_traffic=False):
async def _add_ubridge_ethernet_connection(self, bridge_name, ethernet_interface):
"""
Creates a connection with an Ethernet interface in uBridge.
:param bridge_name: bridge name in uBridge
:param ethernet_interface: Ethernet interface name
:param block_host_traffic: block network traffic originating from the host OS (Windows only)
"""
if sys.platform.startswith("linux") and block_host_traffic is False:
# on Linux we use RAW sockets by default excepting if host traffic must be blocked
await self._ubridge_send(f'bridge add_nio_linux_raw {bridge_name} "{ethernet_interface}"')
else:
# on other platforms we just rely on the pcap library
await self._ubridge_send(f'bridge add_nio_ethernet {bridge_name} "{ethernet_interface}"')
source_mac = None
for interface in interfaces():
if interface["name"] == ethernet_interface:
source_mac = interface["mac_address"]
if source_mac:
await self._ubridge_send(f'bridge set_pcap_filter {bridge_name} "not ether src {source_mac}"')
log.info(f"PCAP filter applied on '{ethernet_interface}' for source MAC {source_mac}")
await self._ubridge_send(f'bridge add_nio_linux_raw {bridge_name} "{ethernet_interface}"')
def _create_local_udp_tunnel(self):
"""
@@ -1561,5 +1546,7 @@ class BaseNode:
if self.custom_adapters:
for custom_adapter in self.custom_adapters:
if custom_adapter["adapter_number"] == adapter_number:
return custom_adapter
# settings left unset are null (e.g. "adapter_type" when only the
# port is renamed): drop them so callers fall back to the node's own
return {key: value for key, value in custom_adapter.items() if value is not None}
return {}
+2 -43
View File
@@ -18,7 +18,6 @@ import logging
import os
import re
import subprocess
import sys
import gns3server.utils.asyncio
import gns3server.utils.interfaces
@@ -104,7 +103,7 @@ class Cloud(BaseNode):
}
)
if sys.platform.startswith("linux") and gns3server.utils.interfaces.is_interface_bridge(interface["name"]):
if gns3server.utils.interfaces.is_interface_bridge(interface["name"]):
host_interfaces[-1]["is_bridge"] = True
return {
@@ -340,12 +339,7 @@ class Cloud(BaseNode):
f"Interface '{port_info['interface']}' could not be found on this system, please update '{self.name}'"
)
if sys.platform.startswith("linux") or sys.platform.startswith("openbsd"):
await self._add_linux_ethernet(port_info, bridge_name)
elif sys.platform.startswith("darwin"):
await self._add_osx_ethernet(port_info, bridge_name)
else:
await self._add_windows_ethernet(port_info, bridge_name)
await self._add_linux_ethernet(port_info, bridge_name)
elif port_info["type"] == "tap":
await self._add_tap_interface(port_info, bridge_name)
@@ -376,8 +370,6 @@ class Cloud(BaseNode):
def _validate_tap_bridge(self, tap, target_bridge):
"""Validate host resources before creating or attaching a Cloud TAP."""
if not sys.platform.startswith("linux"):
raise NodeError("TAP bridge assignments are only supported on Linux")
if not all(re.fullmatch(LINUX_TAP_NAME_PATTERN, name) for name in (target_bridge, tap)):
raise NodeError("Invalid TAP or bridge interface name")
if target_bridge not in {
@@ -410,39 +402,6 @@ class Cloud(BaseNode):
else:
await self._ubridge_send(f'bridge add_nio_linux_raw {bridge_name} "{interface}"')
async def _add_osx_ethernet(self, port_info, bridge_name):
"""
Connects an Ethernet interface on OSX using libpcap.
"""
# Wireless adapters are not well supported by the libpcap on OSX
if await self._is_wifi_adapter_osx(port_info["interface"]):
raise NodeError("Connecting to a Wireless adapter is not supported on Mac OS")
if port_info["interface"].startswith("vmnet"):
# Use a special NIO to connect to VMware vmnet interfaces on OSX (libpcap doesn't support them)
await self._ubridge_send(
'bridge add_nio_fusion_vmnet {name} "{interface}"'.format(
name=bridge_name, interface=port_info["interface"]
)
)
return
if not gns3server.utils.interfaces.has_netmask(port_info["interface"]):
raise NodeError(f"Interface {port_info['interface']} has no netmask, interface down?")
await self._ubridge_send(
'bridge add_nio_ethernet {name} "{interface}"'.format(name=bridge_name, interface=port_info["interface"])
)
async def _add_windows_ethernet(self, port_info, bridge_name):
"""
Connects an Ethernet interface on Windows.
"""
if not gns3server.utils.interfaces.has_netmask(port_info["interface"]):
raise NodeError(f"Interface {port_info['interface']} has no netmask, interface down?")
await self._ubridge_send(
'bridge add_nio_ethernet {name} "{interface}"'.format(name=bridge_name, interface=port_info["interface"])
)
async def add_nio(self, nio, port_number):
"""
Adds a NIO as new port on this cloud.
@@ -230,13 +230,27 @@ class EthernetSwitch(KernelDatapathMixin, BaseNode):
this switch's UUID (kernel interface names are ≤ 15 chars). A stale
bridge from a previous crash is deleted first so ``brctl create`` never
hits EEXIST.
A server killed before ``close()`` leaves that bridge with its ports
still enslaved: a peer's persistent anchor TAP or a cascade veth end
outlives uBridge, and uBridge's ``brctl delete`` refuses a bridge that
still has ports (EBUSY). Every leftover member is released first
(same-host sysfs listing); no port of this switch is wired yet, and
the re-wiring re-enslaves the ones that are still linked.
"""
if self._bridge_created:
return
# deterministic short name — 10 chars, always fits the 15-char kernel cap
self._bridge_name = "gns3" + self._id.replace("-", "")[:6]
# crash recovery: best-effort delete any leftover bridge
# crash recovery: release any leftover bridge's ports, then delete it
try:
leftover_members = os.listdir(f"/sys/class/net/{self._bridge_name}/brif")
except OSError:
leftover_members = [] # no leftover bridge
for member in leftover_members:
with contextlib.suppress(UbridgeError):
await self._ubridge_send(f'brctl delif "{self._bridge_name}" "{member}"')
try:
await self._ubridge_send(f'brctl delete "{self._bridge_name}"')
except UbridgeError:
+11 -33
View File
@@ -16,7 +16,6 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import sys
import gns3server.utils.interfaces
from gns3server.config import Config
@@ -38,39 +37,18 @@ class Nat(Cloud):
allowed_interfaces = Config.instance().settings.Server.allowed_interfaces
if allowed_interfaces and isinstance(allowed_interfaces, str):
allowed_interfaces = allowed_interfaces.split(",")
if sys.platform.startswith("linux"):
nat_interface = Config.instance().settings.Server.default_nat_interface
if not nat_interface:
nat_interface = "virbr0"
if allowed_interfaces and nat_interface not in allowed_interfaces:
raise NodeError(
f"NAT interface {nat_interface} is not allowed be used on this server. "
"Please check the server configuration file."
)
if nat_interface not in [interface["name"] for interface in gns3server.utils.interfaces.interfaces()]:
raise NodeError(f"NAT interface {nat_interface} is missing, please install libvirt")
interface = nat_interface
else:
nat_interface = Config.instance().settings.Server.default_nat_interface
if not nat_interface:
nat_interface = "vmnet8"
if allowed_interfaces and nat_interface not in allowed_interfaces:
raise NodeError(
f"NAT interface {nat_interface} is not allowed be used on this server. "
"Please check the server configuration file."
)
interfaces = list(
filter(
lambda x: nat_interface in x.lower(),
[interface["name"] for interface in gns3server.utils.interfaces.interfaces()],
)
nat_interface = Config.instance().settings.Server.default_nat_interface
if not nat_interface:
nat_interface = "virbr0"
if allowed_interfaces and nat_interface not in allowed_interfaces:
raise NodeError(
f"NAT interface {nat_interface} is not allowed be used on this server. "
"Please check the server configuration file."
)
if not len(interfaces):
raise NodeError(
f"NAT interface {nat_interface} is missing. "
f"You need to install VMware or use the NAT node on GNS3 VM"
)
interface = interfaces[0] # take the first available interface containing the vmnet8 name
if nat_interface not in [interface["name"] for interface in gns3server.utils.interfaces.interfaces()]:
raise NodeError(f"NAT interface {nat_interface} is missing, please install libvirt")
interface = nat_interface
log.debug(f"NAT node '{name}' configured to use NAT interface '{interface}'")
ports = [{"name": "nat0", "type": "ethernet", "interface": interface, "port_number": 0}]
+5 -179
View File
@@ -35,12 +35,12 @@ from gns3server.compute.docker.docker_error import (
DockerHttp404Error,
DockerHttp409Error,
)
from gns3server.compute.docker.docker_images import DockerImagesMixin
from gns3server.compute.docker.docker_vm import DockerVM
from gns3server.compute.docker.iol_docker_vm import IOLDockerVM
from gns3server.compute.docker.vendor_docker_vm import VendorDockerVM
from gns3server.config import Config
from gns3server.utils import parse_version
from gns3server.utils.asyncio import locking
log = logging.getLogger(__name__)
@@ -49,10 +49,9 @@ log = logging.getLogger(__name__)
DOCKER_MINIMUM_API_VERSION = "1.40"
DOCKER_MINIMUM_VERSION = "19.03.8"
DOCKER_PREFERRED_API_VERSION = "1.44"
CHUNK_SIZE = 1024 * 8 # 8KB
class Docker(BaseManager):
class Docker(DockerImagesMixin, BaseManager):
_NODE_CLASS = DockerVM
def __init__(self):
@@ -291,7 +290,8 @@ class Docker(BaseManager):
:param path: Endpoint in API
:param data: Dictionary with the body. Will be transformed to a JSON
:param params: Parameters added as a query arg
:param timeout: Timeout
:param timeout: Total timeout in seconds, an aiohttp ClientTimeout object
for a finer policy (e.g. an idle socket read timeout), or None for no timeout
:returns: HTTP response
"""
@@ -302,7 +302,7 @@ class Docker(BaseManager):
# not a dict (e.g. a Docker image tar stream): let aiohttp stream the raw body
headers = {"content-type": "application/x-tar"}
if timeout is None:
timeout = 60 * 60 * 24 * 31 # One month timeout
timeout = aiohttp.ClientTimeout(total=None)
if path == "version":
url = "http://docker/" + path
@@ -354,177 +354,3 @@ class Docker(BaseManager):
url = "http://docker/v" + self._api_version + "/" + path
connection = await self._session.ws_connect(url, origin="http://docker", autoping=True)
return connection
@locking
async def pull_image(self, image, progress_callback=None, force=False):
"""
Pulls an image from the Docker repository
:params image: Image name
:params progress_callback: A function that receive a log message about image download progress
:params force: Pull the image even if it is already available locally
"""
if not force:
try:
await self.query("GET", f"images/{image}/json")
return # We already have the image skip the download
except DockerHttp404Error:
pass
if progress_callback:
progress_callback(f"Pulling '{image}' from Docker repository")
try:
response = await self.http_query("POST", "images/create", params={"fromImage": image}, timeout=None)
except DockerError as e:
raise DockerError(
f"Could not pull the '{image}' image from Docker repository, "
f"please check your Internet connection (original error: {e})"
)
# The pull api will stream status via an HTTP JSON stream
content = ""
try:
while True:
try:
chunk = await response.content.read(CHUNK_SIZE)
except aiohttp.ServerDisconnectedError as e:
raise DockerError(
f"Disconnected while pulling Docker image '{image}' from Docker repository"
) from e
except TimeoutError as e:
raise DockerError(f"Timeout while pulling Docker image '{image}' from Docker repository") from e
if not chunk:
break
content += chunk.decode("utf-8")
try:
while True:
content = content.lstrip(" \r\n\t")
answer, index = json.JSONDecoder().raw_decode(content)
if not isinstance(answer, dict):
raise DockerError(f"Invalid response while pulling Docker image '{image}'")
error_detail = answer.get("errorDetail")
error = answer.get("error")
if not error and isinstance(error_detail, dict):
error = error_detail.get("message")
if error:
raise DockerError(error)
if "progress" in answer and progress_callback:
progress_callback("Pulling image {}:{}: {}".format(image, answer["id"], answer["progress"]))
content = content[index:]
except ValueError: # Partial JSON
pass
if content.strip():
raise DockerError(f"Invalid response while pulling Docker image '{image}'")
finally:
response.close()
if progress_callback:
progress_callback(f"Success pulling image {image}")
@locking
async def load_image(self, stream, image=None, digest=None, progress_callback=None):
"""
Load a Docker image into the Docker daemon from a docker save tar stream
:param stream: An async iterable of bytes (the tar produced by docker save)
:param image: Tag of the image in the archive. Together with digest, the
(controller digest, local id) pair is remembered so that node creation
can accept the digest the controller pinned for this image
:param digest: Image id as reported by the Docker daemon on the controller
host (the value the controller pins in the node create payload)
:param progress_callback: A function that receive a log message about image load progress
"""
if progress_callback:
progress_callback("Loading Docker image from stream")
response = await self.http_query("POST", "images/load", data=stream, timeout=None)
# The load api will stream status via an HTTP JSON stream
content = ""
try:
while True:
try:
chunk = await response.content.read(CHUNK_SIZE)
except aiohttp.ServerDisconnectedError as e:
raise DockerError("Disconnected while loading Docker image") from e
except TimeoutError as e:
raise DockerError("Timeout while loading Docker image") from e
if not chunk:
break
content += chunk.decode("utf-8", errors="ignore")
try:
while True:
content = content.lstrip(" \r\n\t")
answer, index = json.JSONDecoder().raw_decode(content)
if not isinstance(answer, dict):
raise DockerError("Invalid response while loading Docker image")
error_detail = answer.get("errorDetail")
error = answer.get("error")
if not error and isinstance(error_detail, dict):
error = error_detail.get("message")
if error:
raise DockerError(error)
if "stream" in answer and progress_callback:
progress_callback(answer["stream"].rstrip())
content = content[index:]
except ValueError: # Partial JSON
pass
if content.strip():
raise DockerError("Invalid response while loading Docker image")
finally:
response.close()
if progress_callback:
progress_callback("Docker image loaded")
if image and digest:
await self._remember_image_id_translation(image, digest)
async def _remember_image_id_translation(self, image, controller_digest):
"""
Remember how the local daemon identifies an image that was just loaded
from the controller.
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 recording the pair lets
DockerVM accept that pin for the image it actually received instead of
asking for another full sync on every node creation.
"""
try:
image_infos = await self.query("GET", f"images/{image}/json")
except DockerError as e:
log.warning(f"Image '{image}' has been loaded but cannot be inspected: {e}")
return
local_id = image_infos.get("Id")
if local_id:
self._image_id_translations[image] = (controller_digest, local_id)
def image_id_translation(self, image):
"""
:returns: the (controller digest, local id) pair recorded the last time
this image was loaded from the controller, None otherwise
"""
return self._image_id_translations.get(image)
async def list_images(self):
"""
Gets Docker image list.
:returns: list of dicts
:rtype: list
"""
images = []
for image in await self.query("GET", "images/json", params={"all": 0}):
if image["RepoTags"]:
for tag in image["RepoTags"]:
if tag != "<none>:<none>":
images.append({"image": tag})
return sorted(images, key=lambda i: i["image"])
+395
View File
@@ -0,0 +1,395 @@
#
# Copyright (C) 2026 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the Free Software Foundation 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 a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
The image-management half of the Docker manager: pull, load, list and
delete images, plus the translation between the id the controller pins and
the id this daemon reports for the same content. Consumed by the Docker
manager as a mixin, so __init__.py stays focused on the daemon connection,
the HTTP layer and the node factory.
"""
import json
import logging
import re
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
import aiohttp
from gns3server.compute.compute_error import ComputeError
from gns3server.compute.docker.docker_error import (
DockerError,
DockerHttp404Error,
DockerHttp409Error,
)
from gns3server.compute.project_manager import ProjectManager
from gns3server.utils.asyncio import locking
log = logging.getLogger(__name__)
CHUNK_SIZE = 1024 * 8 # 8KB
# A pull streams progress from the daemon for its whole duration: when no data
# arrives for this many seconds the registry is unreachable and the pull would
# otherwise hang forever. This is an idle timeout, not a total time limit.
PULL_IDLE_TIMEOUT = 60
# Docker names GNS3 node containers "GNS3.{node name}.{project_id}", so a
# container name can be translated back into the node and project that block
# an image deletion. The node name may itself contain dots.
GNS3_CONTAINER_NAME_RE = re.compile(
r"^GNS3\.(?P<node>.+)\.(?P<project_id>[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})$"
)
# The containers blocking an image deletion, as named by the daemon, e.g.
# 'container 6d59f00236ff is using its referenced image d529dd0c6e55'
CONFLICTING_CONTAINER_RE = re.compile(r"container ([0-9a-f]{12,64})\b")
# Images built for reproducibility, such as the Ubuntu images assembled with
# rockcraft, carry no created timestamp in their config and Docker reports 0
# (displayed as 1970-01-01). Their build tool writes the real time in this
# OCI label instead.
OCI_CREATED_LABEL = "org.opencontainers.image.created"
def image_created_timestamp(image: dict) -> int:
"""
Build time of an image as a Unix timestamp.
The daemon timestamp wins when it is set. When it is zero, fall back to
the OCI created label, if present.
:param image: an image summary as returned by the daemon images API
"""
created = image.get("Created") or 0
if created > 0:
return created
label = (image.get("Labels") or {}).get(OCI_CREATED_LABEL, "")
if not label:
return created
try:
built = datetime.fromisoformat(label)
except ValueError:
log.warning(f"Ignoring invalid {OCI_CREATED_LABEL} label: {label!r}")
return created
if built.tzinfo is None:
built = built.replace(tzinfo=UTC)
return int(built.timestamp())
class DockerImagesMixin:
"""
Image management for the Docker manager.
The host manager (Docker) provides the daemon connection: query(),
http_query() and the _image_id_translations dict filled in its __init__.
"""
if TYPE_CHECKING:
_image_id_translations: dict[str, tuple[str, str]]
def query(self, method: str, path: str, *args: Any, **kwargs: Any) -> Any: ...
def http_query(self, method: str, path: str, *args: Any, **kwargs: Any) -> Any: ...
@locking
async def pull_image(self, image, progress_callback=None, force=False):
"""
Pulls an image from the Docker repository
:params image: Image name
:params progress_callback: A function that receives a dict with the
overall progress of the pull: layer counts and the latest daemon
message. The first call carries state="started" and happens once
the pull owns the compute pull lock, so a caller queued behind
another pull only sees it when the pull really begins.
:params force: Pull the image even if it is already available locally
"""
layers_total = 0
layers_done = 0
def report(message, state=None):
if progress_callback:
progress = {"layers_total": layers_total, "layers_done": layers_done, "message": message}
if state is not None:
progress["state"] = state
progress_callback(progress)
report(f"Pulling '{image}' from Docker repository", state="started")
if not force:
try:
await self.query("GET", f"images/{image}/json")
return # We already have the image skip the download
except DockerHttp404Error:
pass
params = {"fromImage": image}
if "@" not in image:
# Without a tag or digest the daemon pulls every tag of the
# repository. Only a ':' after the last '/' is a tag separator:
# before it, it is a registry port (e.g. registry:5000/repo).
if ":" not in image.rpartition("/")[2]:
params["tag"] = "latest"
try:
# The daemon streams progress lines for the whole pull: an idle
# socket read for a minute means the registry is unreachable and
# the pull would otherwise hang forever.
response = await self.http_query(
"POST",
"images/create",
params=params,
timeout=aiohttp.ClientTimeout(total=None, sock_read=PULL_IDLE_TIMEOUT),
)
except DockerHttp404Error as e:
raise DockerError(
f"Could not pull the '{image}' image: it was not found in the registry. "
f"Check the image name or run 'docker login' on the compute host "
f"(original error: {e})"
)
except DockerError as e:
raise DockerError(
f"Could not pull the '{image}' image from Docker repository. "
f"Check the image name, the registry authentication and your Internet connection "
f"(original error: {e})"
)
# The pull api will stream status via an HTTP JSON stream
content = ""
try:
while True:
try:
chunk = await response.content.read(CHUNK_SIZE)
except aiohttp.ServerDisconnectedError as e:
raise DockerError(
f"Disconnected while pulling Docker image '{image}' from Docker repository"
) from e
except TimeoutError as e:
raise DockerError(
f"Timeout while pulling Docker image '{image}' from Docker repository: "
f"no data received for {PULL_IDLE_TIMEOUT} seconds, "
f"please check your Internet connection or Docker registry mirror"
) from e
if not chunk:
break
content += chunk.decode("utf-8")
try:
while True:
content = content.lstrip(" \r\n\t")
answer, index = json.JSONDecoder().raw_decode(content)
if not isinstance(answer, dict):
raise DockerError(f"Invalid response while pulling Docker image '{image}'")
error_detail = answer.get("errorDetail")
error = answer.get("error")
if not error and isinstance(error_detail, dict):
error = error_detail.get("message")
if error:
raise DockerError(error)
status = answer.get("status", "")
if status == "Pulling fs layer":
layers_total += 1
elif status in ("Pull complete", "Already exists"):
layers_done += 1
message = answer.get("progress") or status
if message:
report(message)
content = content[index:]
except ValueError: # Partial JSON
pass
if content.strip():
raise DockerError(f"Invalid response while pulling Docker image '{image}'")
finally:
response.close()
@locking
async def load_image(self, stream, image=None, digest=None, progress_callback=None):
"""
Load a Docker image into the Docker daemon from a docker save tar stream
:param stream: An async iterable of bytes (the tar produced by docker save)
:param image: Tag of the image in the archive. Together with digest, the
(controller digest, local id) pair is remembered so that node creation
can accept the digest the controller pinned for this image
:param digest: Image id as reported by the Docker daemon on the controller
host (the value the controller pins in the node create payload)
:param progress_callback: A function that receive a log message about image load progress
"""
if progress_callback:
progress_callback("Loading Docker image from stream")
response = await self.http_query("POST", "images/load", data=stream, timeout=None)
# The load api will stream status via an HTTP JSON stream
content = ""
try:
while True:
try:
chunk = await response.content.read(CHUNK_SIZE)
except aiohttp.ServerDisconnectedError as e:
raise DockerError("Disconnected while loading Docker image") from e
except TimeoutError as e:
raise DockerError("Timeout while loading Docker image") from e
if not chunk:
break
content += chunk.decode("utf-8", errors="ignore")
try:
while True:
content = content.lstrip(" \r\n\t")
answer, index = json.JSONDecoder().raw_decode(content)
if not isinstance(answer, dict):
raise DockerError("Invalid response while loading Docker image")
error_detail = answer.get("errorDetail")
error = answer.get("error")
if not error and isinstance(error_detail, dict):
error = error_detail.get("message")
if error:
raise DockerError(error)
if "stream" in answer and progress_callback:
progress_callback(answer["stream"].rstrip())
content = content[index:]
except ValueError: # Partial JSON
pass
if content.strip():
raise DockerError("Invalid response while loading Docker image")
finally:
response.close()
if progress_callback:
progress_callback("Docker image loaded")
if image and digest:
await self._remember_image_id_translation(image, digest)
async def _remember_image_id_translation(self, image, controller_digest):
"""
Remember how the local daemon identifies an image that was just loaded
from the controller.
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 recording the pair lets
DockerVM accept that pin for the image it actually received instead of
asking for another full sync on every node creation.
"""
try:
image_infos = await self.query("GET", f"images/{image}/json")
except DockerError as e:
log.warning(f"Image '{image}' has been loaded but cannot be inspected: {e}")
return
local_id = image_infos.get("Id")
if local_id:
self._image_id_translations[image] = (controller_digest, local_id)
def image_id_translation(self, image):
"""
:returns: the (controller digest, local id) pair recorded the last time
this image was loaded from the controller, None otherwise
"""
return self._image_id_translations.get(image)
async def list_images(self):
"""
Gets Docker image list.
:returns: list of dicts
:rtype: list
"""
images = []
for image in await self.query("GET", "images/json", params={"all": 0}):
if image["RepoTags"]:
for tag in image["RepoTags"]:
if tag != "<none>:<none>":
images.append(
{
"image": tag,
"id": image.get("Id"),
"size": image.get("Size"),
"created": image_created_timestamp(image),
}
)
return sorted(images, key=lambda i: i["image"])
async def delete_image(self, image, force=False):
"""
Delete a Docker image from the Docker daemon.
When the daemon refuses because containers use the image, the error
names the GNS3 nodes and projects behind them instead of raw
container ids.
:param image: Image name or id
:param force: Remove the image even if a container uses it
"""
try:
await self.query("DELETE", f"images/{image}", params={"force": str(force).lower()})
except DockerHttp409Error as e:
blockers = await self._describe_containers_using_image(str(e))
if blockers:
raise DockerHttp409Error(
f"Cannot delete image '{image}': it is still used by {blockers}. "
f"Delete the node or container first, or repeat with force=true."
) from e
raise
# the image id translation recorded when this image was synced from the
# controller no longer matches anything on this daemon
self._image_id_translations.pop(image, None)
async def _describe_containers_using_image(self, daemon_error: str) -> str:
"""
Translate the container ids named in a daemon image deletion conflict
into node, project or container descriptions.
:param daemon_error: the raw daemon conflict message
:returns: a comma separated description, empty when the message names
no container
"""
descriptions = []
for container_id in CONFLICTING_CONTAINER_RE.findall(daemon_error):
try:
info = await self.query("GET", f"containers/{container_id}/json")
except DockerError:
info = None
if not info:
# the container cannot be inspected (or already vanished)
descriptions.append(f"container '{container_id}'")
continue
name = info.get("Name", container_id).lstrip("/")
state = "running" if info.get("State", {}).get("Running") else "stopped"
match = GNS3_CONTAINER_NAME_RE.match(name)
if match:
node = match.group("node")
try:
project = ProjectManager.instance().get_project(match.group("project_id"))
except ComputeError:
# the project is closed on this compute: a leftover container
descriptions.append(f"leftover container of node '{node}' ({state}, its project is closed)")
else:
descriptions.append(f"node '{node}' in project '{project.name}' ({state})")
else:
# a container created outside GNS3
descriptions.append(f"container '{name}' ({state})")
return ", ".join(descriptions)
-11
View File
@@ -26,7 +26,6 @@ import re
import shlex
import shutil
import subprocess
import sys
from ...utils.asyncio import subprocess_check_output
from ...utils.get_resource import get_resource
@@ -113,16 +112,6 @@ class Qemu(BaseManager):
paths.update(os.environ["PATH"].split(os.pathsep))
else:
log.warning("The PATH environment variable doesn't exist")
# look for Qemu binaries in the current working directory and $PATH
if sys.platform.startswith("darwin") and hasattr(sys, "frozen"):
# add specific locations on Mac OS X regardless of what's in $PATH
paths.update(["/usr/bin", "/usr/local/bin", "/opt/local/bin"])
try:
exec_dir = os.path.dirname(os.path.abspath(sys.executable))
paths.add(os.path.abspath(os.path.join(exec_dir, "qemu/bin")))
# If the user run the server by hand from outside
except FileNotFoundError:
paths.add("/Applications/GNS3.app/Contents/MacOS/qemu/bin")
return paths
@staticmethod
+280 -112
View File
@@ -24,13 +24,13 @@ import json
import logging
import math
import os
import platform
import re
import shlex
import shutil
import socket
import struct
import subprocess
import sys
import time
from pathlib import Path
@@ -63,6 +63,35 @@ log = logging.getLogger(__name__)
FORBIDDEN_OPTIONS = {"-blockdev", "-drive", "-hda", "-hdb", "-hdc", "-hdd", "-fsdev", "-virtfs", "-nic", "-netdev"}
FORBIDDEN_OPTIONS |= {"-" + opt for opt in FORBIDDEN_OPTIONS if opt.startswith("-") and not opt.startswith("--")}
CLOCKSOURCE_PATH = "/sys/devices/system/clocksource/clocksource0/current_clocksource"
# Clocksources of a Linux host running on Hyper-V without a usable TSC. The guest
# timekeeping KVM derives from the TSC there is broken with recent kernels: kvmclock
# runs thousands of times too fast (Linux guests panic with soft lockups and reboot
# in a loop) and TSC deadline timers fire far too late (guests hang while booting).
HYPERV_CLOCKSOURCES = ("hyperv_clocksource_tsc_page", "hyperv_clocksource_msr")
# guest CPU features turned off on such hosts
KVMCLOCK_OFF_FEATURES = ("kvmclock", "tsc-deadline")
PCIE_PLATFORMS = ("aarch64", "i386", "x86_64")
PCIE_ADAPTER_TYPES = ("e1000e", "igb", "virtio-net-pci", "vmxnet3")
MAX_PCIE_ADAPTERS = 232
def host_clocksource():
"""
Returns the clocksource used by the host kernel (Linux only).
:returns: clocksource name or None
"""
try:
with open(CLOCKSOURCE_PATH, encoding="utf-8") as f:
return f.read().strip()
except OSError:
return None
class QemuVM(KernelDatapathMixin, BaseNode):
module_name = "qemu"
@@ -989,25 +1018,13 @@ class QemuVM(KernelDatapathMixin, BaseNode):
log.debug(f'QEMU VM "{self._name}" [{self._id}] has set the QEMU options to {options}')
# "-no-kvm" and "-no-hax' are deprecated since Qemu v5.2
# "-no-kvm" is deprecated since Qemu v5.2
# https://www.qemu.org/docs/master/about/removed-features.html#no-kvm-removed-in-5-2
if "-no-kvm" in options:
options = options.replace("-no-kvm", "-machine accel=tcg")
if "-no-hax" in options:
options = options.replace("-no-hax", "-machine accel=tcg")
if "-enable-kvm" in options:
if not sys.platform.startswith("linux"):
# KVM can only be enabled on Linux
options = options.replace("-enable-kvm", "")
else:
options = options.replace("-enable-kvm", "-machine accel=kvm")
if "-enable-hax" in options:
if not sys.platform.startswith("darwin"):
# HAXM is only available on macOS
options = options.replace("-enable-hax", "")
else:
options = options.replace("-enable-hax", "-machine accel=hax")
options = options.replace("-enable-kvm", "-machine accel=kvm")
self._options = options.strip()
@@ -1238,7 +1255,7 @@ class QemuVM(KernelDatapathMixin, BaseNode):
await self._set_process_priority()
if self._cpu_throttling:
self._set_cpu_throttling()
if "-enable-kvm" in command_string or "-enable-hax" in command_string:
if "-machine accel=kvm" in command_string:
self._hw_virtualization = True
set_link_commands = []
@@ -2036,20 +2053,69 @@ class QemuVM(KernelDatapathMixin, BaseNode):
super(QemuVM, QemuVM).console_type.__set__(self, new_console_type)
def _arm64_options(self, additional_options, include_machine=True):
arm64_host = platform.machine() in ("aarch64", "arm64")
arm64_options = []
if include_machine:
if arm64_host:
arm64_options.extend(["-machine", "virt,gic-version=host"])
else:
arm64_options.extend(["-machine", "virt,gic-version=3"])
if "-cpu" not in additional_options:
if arm64_host:
arm64_options.extend(["-cpu", "max"])
else:
arm64_options.extend(["-cpu", "neoverse-n1"])
return arm64_options
@staticmethod
def _machine_type(additional_options):
machine_type = None
for index, option in enumerate(additional_options):
if option not in ("-machine", "-M") or index + 1 >= len(additional_options):
continue
for part in additional_options[index + 1].split(","):
if part.startswith("type="):
machine_type = part.removeprefix("type=") or machine_type
break
if "=" not in part:
machine_type = part
break
return machine_type
def _uses_pcie_network_layout(self, additional_options=()):
machine_type = self._machine_type(additional_options)
if self.platform in ("i386", "x86_64"):
machine_type = machine_type or "q35"
return machine_type == "q35" or machine_type.startswith("pc-q35-")
if self.platform == "aarch64":
machine_type = machine_type or "virt"
return machine_type == "virt" or machine_type.startswith("virt-")
return False
def _machine_options(self, additional_options):
if self.platform not in PCIE_PLATFORMS or self._machine_type(additional_options):
if self.platform == "aarch64":
return self._arm64_options(shlex.join(additional_options), include_machine=False)
return []
if self.platform == "aarch64":
return self._arm64_options(shlex.join(additional_options))
return ["-machine", "q35"]
def _serial_options(self, internal_console_port, external_console_port):
if external_console_port:
return ["-serial", f"telnet:127.0.0.1:{internal_console_port},server,nowait"]
else:
return []
def _vnc_options(self, port):
if port:
vnc_port = port - 5900 # subtract by 5900 to get the display number
return ["-vnc", f"{self._manager.port_manager.console_host}:{vnc_port}"]
else:
return []
return ["-vnc", f"{self._manager.port_manager.console_host}:{vnc_port}", "-device", "virtio-gpu-pci"]
def _spice_options(self, port):
@@ -2064,9 +2130,7 @@ class QemuVM(KernelDatapathMixin, BaseNode):
console_host = "::"
except OSError as e:
raise QemuError(f"Could not check if IPv6 is enabled: {e}")
return ["-spice", f"addr={console_host},port={port},disable-ticketing=on", "-vga", "qxl"]
else:
return []
return ["-spice", f"addr={console_host},port={port},disable-ticketing=on", "-device", "virtio-gpu-pci"]
def _spice_with_agent_options(self, port):
@@ -2094,17 +2158,29 @@ class QemuVM(KernelDatapathMixin, BaseNode):
def _console_options(self):
console_options = []
if self._console_type in ("telnet", "ssh") and self._wrap_console:
return self._serial_options(self._internal_console_port, self.console)
console_options = self._serial_options(self._internal_console_port, self.console)
elif self._console_type == "vnc":
return self._vnc_options(self.console)
console_options = self._vnc_options(self.console)
elif self._console_type == "spice":
return self._spice_options(self.console)
console_options = self._spice_options(self.console)
elif self._console_type == "spice+agent":
return self._spice_with_agent_options(self.console)
console_options = self._spice_with_agent_options(self.console)
elif self._console_type != "none":
raise QemuError(f"Console type {self._console_type} is unknown")
return []
if self._console_type in ("vnc", "spice"):
if self.platform == "aarch64":
# add a USB controller with a keyboard and mouse
console_options.extend(
["-device", "qemu-xhci,id=usb", "-device", "usb-kbd,bus=usb.0", "-device", "usb-tablet,bus=usb.0"]
)
else:
# avoiding mouse offset (see https://github.com/GNS3/gns3-server/issues/2335)
console_options.extend(["-machine", "usb=on", "-device", "usb-tablet"])
return console_options
def _aux_options(self):
@@ -2499,54 +2575,48 @@ class QemuVM(KernelDatapathMixin, BaseNode):
options.extend(["-bios", self._bios_image.replace(",", ",,")])
elif self._uefi:
system_ovmf_firmware_dir = Path(self.manager.config.settings.Qemu.ovmf_firmware_dir)
log.debug(f"Using OVMF firmware directory: {system_ovmf_firmware_dir}")
old_ovmf_vars_path = os.path.join(self.working_dir, "OVMF_VARS.fd")
if os.path.exists(old_ovmf_vars_path):
# the node has its own UEFI variables store already, we must also use the old UEFI firmware
ovmf_firmware_path = self.manager.get_abs_image_path("OVMF_CODE.fd")
if self.platform == "aarch64":
firmware_dir = Path(self.manager.config.settings.Qemu.aavmf_firmware_dir)
firmware_name = "AAVMF_CODE.fd"
vars_name = "AAVMF_VARS.fd"
else:
# Use a manual case-insensitive search instead
try:
system_ovmf_firmware_path = next(
(f for f in system_ovmf_firmware_dir.glob("*.fd") if f.name.lower() == "ovmf_code_4m.fd"), None
)
except (FileNotFoundError, StopIteration):
system_ovmf_firmware_path = None
if system_ovmf_firmware_path:
ovmf_firmware_path = str(system_ovmf_firmware_path)
firmware_dir = Path(self.manager.config.settings.Qemu.ovmf_firmware_dir)
firmware_name = "OVMF_CODE_4M.fd"
vars_name = "OVMF_VARS_4M.fd"
log.debug(f"Using UEFI firmware directory: {firmware_dir}")
old_ovmf_vars_path = os.path.join(self.working_dir, "OVMF_VARS.fd")
if self.platform != "aarch64" and os.path.exists(old_ovmf_vars_path):
# the node has its own UEFI variables store already, we must also use the old UEFI firmware
firmware_path = self.manager.get_abs_image_path("OVMF_CODE.fd")
vars_node_path = old_ovmf_vars_path
else:
system_firmware_path = next(
(f for f in firmware_dir.glob("*.fd") if f.name.lower() == firmware_name.lower()), None
)
if system_firmware_path:
firmware_path = str(system_firmware_path)
else:
# otherwise, get the UEFI firmware from the images directory
ovmf_firmware_path = self.manager.get_abs_image_path("OVMF_CODE_4M.fd")
firmware_path = self.manager.get_abs_image_path(firmware_name)
log.debug(f"Configuring UEFI boot mode using OVMF file: '{ovmf_firmware_path}'")
options.extend(["-drive", f"if=pflash,format=raw,readonly,file={ovmf_firmware_path}"])
# try to use the UEFI variables store from the system first
try:
system_ovmf_vars_path = next(
(f for f in system_ovmf_firmware_dir.glob("*.fd") if f.name.lower() == "ovmf_vars_4m.fd"), None
)
except (FileNotFoundError, StopIteration):
system_ovmf_vars_path = None
if system_ovmf_vars_path:
ovmf_vars_path = str(system_ovmf_vars_path)
else:
# otherwise, get the UEFI variables store from the images directory
ovmf_vars_path = self.manager.get_abs_image_path("OVMF_VARS_4M.fd")
# the node should have its own copy of OVMF_VARS.fd (the UEFI variables store)
if os.path.exists(old_ovmf_vars_path):
ovmf_vars_node_path = old_ovmf_vars_path
else:
ovmf_vars_node_path = os.path.join(self.working_dir, "OVMF_VARS_4M.fd")
if not os.path.exists(ovmf_vars_node_path):
# Each node must have its own writable UEFI variables store.
vars_node_path = os.path.join(self.working_dir, vars_name)
if not os.path.exists(vars_node_path):
system_vars_path = next(
(f for f in firmware_dir.glob("*.fd") if f.name.lower() == vars_name.lower()), None
)
if system_vars_path:
vars_path = str(system_vars_path)
else:
vars_path = self.manager.get_abs_image_path(vars_name)
try:
shutil.copyfile(ovmf_vars_path, ovmf_vars_node_path)
shutil.copyfile(vars_path, vars_node_path)
except OSError as e:
raise QemuError(f"Cannot copy OVMF_VARS_4M.fd file to the node working directory: {e}")
options.extend(["-drive", f"if=pflash,format=raw,file={ovmf_vars_node_path}"])
raise QemuError(f"Cannot copy {vars_name} file to the node working directory: {e}")
log.debug(f"Configuring UEFI boot mode using firmware file: '{firmware_path}'")
options.extend(["-drive", f"file={firmware_path},if=pflash,unit=0,format=raw,readonly=on"])
options.extend(["-drive", f"file={vars_node_path},if=pflash,unit=1,format=raw"])
# edk2 firmware requires a Random Number Generator (RNG) device in order to turn network adapters on
options.extend(["-object", "rng-random,filename=/dev/urandom,id=rng0"])
@@ -2637,13 +2707,62 @@ class QemuVM(KernelDatapathMixin, BaseNode):
]
return options
async def _network_options(self):
async def _network_options(self, pcie_enabled=None):
network_options = []
network_options.extend(
["-net", "none"]
) # we do not want any user networking back-end if no adapter is connected.
if pcie_enabled is None:
pcie_enabled = self._uses_pcie_network_layout()
# PCIe network layout support:
# x86 guests (i386 and x86_64) default to q35; ARM64 guests default to virt.
# Explicit selections outside those machine families use the legacy PCI layout.
#
# PCIe-capable NICs (e1000e, igb, virtio-net-pci, and vmxnet3) each attach
# to a dedicated PCIe root port at downstream slot 0. Root ports are grouped into
# eight functions per root-bus slot. This gives path-based Linux interface names
# a consistent bus/slot pattern, such as enp1s0, enp2s0, and enp3s0.
# Exact names and bus numbers still depend on guest firmware, naming policy, and
# other devices. Legacy NICs such as e1000 and rtl8139 continue to share PCI
# bridges, with up to 32 NICs per bridge group.
#
# The PCIe layout supports at most 232 NIC root ports; disks, graphics, USB, and
# user-supplied devices can impose lower resource limits. NICs with I/O BARs
# (e1000e and igb) each consume an I/O bridge window. At most nine such
# root ports and legacy PCI bridge groups are allowed in total to avoid
# exhausting PCI I/O space. Use virtio-net-pci or vmxnet3 for large PCIe
# NIC configurations. The existing 275-NIC limit remains available with legacy
# NICs on shared bridges.
custom_adapters = [self._get_custom_adapter_settings(n) for n in range(self.adapters)]
adapter_types = [settings.get("adapter_type", self._adapter_type) for settings in custom_adapters]
pcie_adapters = {
n for n, adapter_type in enumerate(adapter_types) if pcie_enabled and adapter_type in PCIE_ADAPTER_TYPES
}
if len(pcie_adapters) > MAX_PCIE_ADAPTERS:
raise QemuError(f"At most {MAX_PCIE_ADAPTERS} PCIe network adapters are supported")
if pcie_enabled:
io_ports = sum(adapter_types[n] in ("e1000e", "igb") for n in pcie_adapters)
legacy_bridges = (self.adapters - len(pcie_adapters) + 31) // 32
if io_ports + legacy_bridges > 9:
raise QemuError(
"The network layout exceeds PCI I/O space: at most 9 I/O-bearing root ports "
"and legacy PCI bridge groups are supported in total; use virtio-net-pci or vmxnet3"
)
# Eight root-port functions per slot, leaving slots 0, 1 and 31 for platform devices.
for port_number, adapter_number in enumerate(sorted(pcie_adapters)):
slot, function = 2 + port_number // 8, port_number % 8
network_options.extend(
[
"-device",
f"pcie-root-port,id=gns3-pcie-{adapter_number},bus=pcie.0,"
f"addr=0x{slot:x}.{function},multifunction=on,chassis={port_number + 1},hotplug=off",
]
)
# Legacy PCI NICs share bridges to avoid exhausting the 64 KiB I/O space.
# Each 32 PCI device we need to add a PCI bridge with max 9 bridges
# Reserve 32 devices on root pci_bridge,
# since the number of devices used by templates may differ significantly
@@ -2657,8 +2776,8 @@ class QemuVM(KernelDatapathMixin, BaseNode):
nio = adapter.get_nio(0)
custom_adapter = self._get_custom_adapter_settings(adapter_number)
adapter_type = custom_adapter.get("adapter_type", self._adapter_type)
custom_adapter = custom_adapters[adapter_number]
adapter_type = adapter_types[adapter_number]
custom_mac_address = custom_adapter.get("mac_address")
if custom_mac_address:
mac = int_to_macaddress(macaddress_to_int(custom_mac_address))
@@ -2666,8 +2785,10 @@ class QemuVM(KernelDatapathMixin, BaseNode):
device_string = f"{adapter_type},mac={mac}"
if adapter_type == "virtio-net-pci":
device_string = f"{device_string},speed=10000,duplex=full"
bridge_id = math.floor(pci_device_id / 32)
if bridge_id > 0:
if adapter_number in pcie_adapters:
device_string = f"{device_string},bus=gns3-pcie-{adapter_number},addr=0x00"
else:
bridge_id = math.floor(pci_device_id / 32)
if pci_bridges_created < bridge_id:
network_options.extend(["-device", f"i82801b11-bridge,id=dmi_pci_bridge{bridge_id}"])
network_options.extend(
@@ -2679,7 +2800,7 @@ class QemuVM(KernelDatapathMixin, BaseNode):
pci_bridges_created += 1
addr = pci_device_id % 32
device_string = f"{device_string},bus=pci-bridge{bridge_id},addr=0x{addr:02x}"
pci_device_id += 1
pci_device_id += 1
# Every adapter is backed by its own TAP (created before launch,
# see _create_taps): the netdev is a kernel-side interface the
# link attaches to, not a UDP socket into uBridge. A legacy
@@ -2690,8 +2811,14 @@ class QemuVM(KernelDatapathMixin, BaseNode):
tap = self._kernel_host_ifc(adapter_number) or self._tap_name(adapter_number)
network_options.extend(["-device", f"{device_string},netdev=gns3-{adapter_number}"])
if self._tap_datapath or isinstance(nio, NIOTAP):
# vnet_hdr=off: with QEMU's default virtio-net header the
# guest NIC offloads TCP/UDP checksums and TSO to the TAP.
# A kernel bridge finishes such frames, but the uBridge relay
# (cloud, NAT, ...) copies them off the TAP as they are, so
# receivers drop them. Without the header QEMU and the guest
# send finished frames, as with the 2.x socket netdev.
network_options.extend(
["-netdev", f"tap,id=gns3-{adapter_number},ifname={tap},script=no,downscript=no"]
["-netdev", f"tap,id=gns3-{adapter_number},ifname={tap},script=no,downscript=no,vnet_hdr=off"]
)
else:
# Legacy datapath (uBridge without the tap module): QEMU talks
@@ -2715,7 +2842,7 @@ class QemuVM(KernelDatapathMixin, BaseNode):
Disable graphics for Qemu if no graphics options are specified.
"""
if any(opt in self._options for opt in ["-display", "-nographic", "-curses", "-sdl-spice", "-vnc"]):
if any(opt in self._options for opt in ["-display", "-nographic", "-curses", "-sdl-spice", "-vnc", "-spice"]):
return []
return ["-display", "none"]
@@ -2731,8 +2858,9 @@ class QemuVM(KernelDatapathMixin, BaseNode):
enable_hardware_accel = self.manager.config.settings.Qemu.enable_hardware_acceleration
require_hardware_accel = self.manager.config.settings.Qemu.require_hardware_acceleration
if enable_hardware_accel and "-machine accel=tcg" not in options:
# Turn OFF hardware acceleration for non x86 architectures
supported_binaries = ["qemu-system-x86_64", "qemu-system-i386", "qemu-kvm"]
if platform.machine() in ("aarch64", "arm64"):
supported_binaries = ["qemu-system-aarch64"]
if os.path.basename(qemu_path) not in supported_binaries:
if require_hardware_accel:
raise QemuError(
@@ -2743,26 +2871,54 @@ class QemuVM(KernelDatapathMixin, BaseNode):
else:
return False
if sys.platform.startswith("linux") and not os.path.exists("/dev/kvm"):
if not os.path.exists("/dev/kvm"):
if require_hardware_accel:
raise QemuError(
"KVM acceleration cannot be used (/dev/kvm doesn't exist). It is possible to turn off KVM support in the gns3_server.conf by adding enable_hardware_acceleration = false to the [Qemu] section."
)
else:
return False
elif sys.platform.startswith("darwin"):
process = await asyncio.create_subprocess_shell("kextstat | grep com.intel.kext.intelhaxm")
await process.wait()
if process.returncode != 0:
if require_hardware_accel:
raise QemuError(
"HAXM acceleration support is not installed on this host (com.intel.kext.intelhaxm extension not loaded)"
)
else:
return False
return True
return False
def _kvmclock_off_reason(self):
"""
Returns why kvmclock and the TSC deadline timer must be turned off for this KVM guest.
:returns: reason (string) or None to keep them
"""
kvmclock = self.manager.config.settings.Qemu.kvmclock
if kvmclock == "disabled":
return "kvmclock = disabled in the [Qemu] server settings"
if kvmclock == "auto":
clocksource = host_clocksource()
if clocksource in HYPERV_CLOCKSOURCES:
return (
f"the host runs on Hyper-V without a usable TSC (clocksource {clocksource}), "
"set kvmclock = enabled in the [Qemu] server settings to keep them"
)
return None
def _kvmclock_off_options(self, additional_options):
"""
Turns kvmclock and the TSC deadline timer off on the -cpu of the additional
options (except the features it sets itself) or, without one, on QEMU's
default CPU model.
:param additional_options: additional options (list), updated in place
:returns: options to add to the command line
"""
for index in range(len(additional_options) - 2, -1, -1):
if additional_options[index] in ("-cpu", "--cpu"):
for feature in KVMCLOCK_OFF_FEATURES:
if feature not in additional_options[index + 1]:
additional_options[index + 1] += f",{feature}=off"
return []
cpu_model = "qemu32" if self._platform == "i386" else "qemu64"
return ["-cpu", ",".join([cpu_model] + [f"{feature}=off" for feature in KVMCLOCK_OFF_FEATURES])]
async def _clear_save_vm_stated(self, snapshot_name="GNS3_SAVED_STATE"):
drives = ["a", "b", "c", "d"]
@@ -2854,6 +3010,16 @@ class QemuVM(KernelDatapathMixin, BaseNode):
additional_options = additional_options.replace("%guest-cid%", str(self._guest_cid))
if self._console_type != "none" and self._console:
additional_options = additional_options.replace("%console-port%", str(self._console))
try:
additional_opt_list = shlex.split(additional_options)
except ValueError as e:
raise QemuError(f"Invalid additional options: {additional_options} error {e}")
allow_unsafe_options = self.manager.config.settings.Qemu.allow_unsafe_options
if allow_unsafe_options is False:
for opt in additional_opt_list:
if opt in FORBIDDEN_OPTIONS:
raise QemuError(f"Forbidden additional option: {opt}")
machine_options = self._machine_options(additional_opt_list)
command = [self.qemu_path]
command.extend(["-name", vm_name])
command.extend(["-m", f"{self._ram}M"])
@@ -2862,12 +3028,21 @@ class QemuVM(KernelDatapathMixin, BaseNode):
if self._cpus > maxcpus:
maxcpus = self._cpus
command.extend(["-smp", f"cpus={self._cpus},maxcpus={maxcpus},sockets=1"])
command.extend(machine_options)
kvm_enabled = False
if await self._run_with_hardware_acceleration(self.qemu_path, self._options):
if sys.platform.startswith("linux"):
command.extend(["-enable-kvm"])
elif sys.platform.startswith("darwin"):
command.extend(["-enable-hax"])
command.extend(["-machine", "accel=kvm"])
kvm_enabled = True
else:
self.project.emit(
"log.warning",
{
"message": f'QEMU VM "{self._name}": KVM hardware acceleration is not available, performance will be reduced'
},
)
command.extend(["-boot", f"order={self._boot_priority}"])
# Reserve root-port addresses before other devices receive automatic PCI addresses.
command.extend(await self._network_options(self._uses_pcie_network_layout(additional_opt_list)))
command.extend(self._cdrom_option())
command.extend(await self._disk_options())
command.extend(self._linux_boot_options())
@@ -2876,7 +3051,6 @@ class QemuVM(KernelDatapathMixin, BaseNode):
command.extend(self._console_options())
command.extend(self._aux_options())
command.extend(self._monitor_options())
command.extend(await self._network_options())
# bios options must be last to have predictable NIC numbering, see https://github.com/GNS3/gns3-server/issues/2838
command.extend(self._bios_option())
if self.on_close != "save_vm_state":
@@ -2887,21 +3061,15 @@ class QemuVM(KernelDatapathMixin, BaseNode):
command.extend(await self._disable_graphics())
if self._tpm:
command.extend(self._tpm_options())
if additional_options:
try:
additional_opt_list = shlex.split(additional_options)
except ValueError as e:
raise QemuError(f"Invalid additional options: {additional_options} error {e}")
allow_unsafe_options = self.manager.config.settings.Qemu.allow_unsafe_options
if allow_unsafe_options is False:
for opt in additional_opt_list:
if opt in FORBIDDEN_OPTIONS:
raise QemuError(f"Forbidden additional option: {opt}")
command.extend(additional_opt_list)
# avoiding mouse offset (see https://github.com/GNS3/gns3-server/issues/2335)
if self._console_type == "vnc":
command.extend(["-machine", "usb=on", "-device", "usb-tablet"])
if kvm_enabled:
kvmclock_off_reason = self._kvmclock_off_reason()
if kvmclock_off_reason:
log.info(
f'QEMU VM "{self._name}" [{self._id}]: kvmclock and TSC deadline timer turned off, '
f"{kvmclock_off_reason}"
)
command.extend(self._kvmclock_off_options(additional_opt_list))
command.extend(additional_opt_list)
return command
def asdict(self):
+4 -4
View File
@@ -158,10 +158,10 @@ class Hypervisor(UBridgeHypervisor):
match = re.search(r"ubridge version ([0-9a-z\.]+)", output)
if match:
self._version = match.group(1)
# uBridge >= 1.2.3 is required for the AF_UNIX control
# channel, marker filters, builtin Ethernet Switch support,
# and Docker TAP carrier control.
minimum_required_version = "1.2.3"
# uBridge >= 1.3.1 is required for the kernel datapath:
# persistent TAP anchors, kernel links, kernel markers and
# per-interface kernel captures.
minimum_required_version = "1.3.1"
if parse_version(self._version) < parse_version(minimum_required_version):
raise UbridgeError(f"uBridge executable version must be >= {minimum_required_version}")
else:
@@ -24,7 +24,6 @@ import os
import re
import shutil
import subprocess
import sys
log = logging.getLogger(__name__)
@@ -61,10 +60,6 @@ class VirtualBox(BaseManager):
vboxmanage_path = shutil.which(vboxmanage_path)
else:
log.info("A path to VBoxManage has not been configured, trying to find it...")
if sys.platform.startswith("darwin"):
vboxmanage_path_osx = "/Applications/VirtualBox.app/Contents/MacOS/VBoxManage"
if os.path.exists(vboxmanage_path_osx):
vboxmanage_path = vboxmanage_path_osx
if not vboxmanage_path:
vboxmanage_path = shutil.which("vboxmanage")
if not vboxmanage_path:
+8 -35
View File
@@ -27,7 +27,6 @@ import re
import shlex
import shutil
import subprocess
import sys
from collections import OrderedDict
from gns3server.utils import parse_version
@@ -92,10 +91,7 @@ class VMware(BaseManager):
# look for vmrun
vmrun_path = self.config.settings.VMware.vmrun_path
if not vmrun_path:
if sys.platform.startswith("darwin"):
vmrun_path = "/Applications/VMware Fusion.app/Contents/Library/vmrun"
else:
vmrun_path = "vmrun"
vmrun_path = "vmrun"
if vmrun_path and not os.path.isabs(vmrun_path):
vmrun_path = shutil.which(vmrun_path)
@@ -186,14 +182,6 @@ class VMware(BaseManager):
Check VMware version
"""
if sys.platform.startswith("darwin"):
if not os.path.isdir("/Applications/VMware Fusion.app"):
raise VMwareError(
"VMware Fusion is not installed in the standard location /Applications/VMware Fusion.app"
)
self._host_type = "fusion"
return # FIXME: no version checking on Mac OS X but we support all versions of fusion
vmware_path = VMware._get_linux_vmware_binary()
if vmware_path is None:
raise VMwareError("VMware is not installed (vmware or vmplayer executable could not be found in $PATH)")
@@ -223,11 +211,7 @@ class VMware(BaseManager):
@staticmethod
def _get_vmnet_interfaces():
if sys.platform.startswith("darwin"):
vmware_networking_file = "/Library/Preferences/VMware Fusion/networking"
else:
# location on Linux
vmware_networking_file = "/etc/vmware/networking"
vmware_networking_file = "/etc/vmware/networking"
vmnet_interfaces = {}
try:
with open(vmware_networking_file, encoding="utf-8") as f:
@@ -540,11 +524,9 @@ class VMware(BaseManager):
except LookupError:
log.warning(f"Invalid file encoding detected in '{path}': {file_encoding}")
with open(path, "w", encoding=encoding, errors="ignore") as f:
if sys.platform.startswith("linux"):
# write the shebang on the first line on Linux
vmware_path = VMware._get_linux_vmware_binary()
if vmware_path:
f.write(f"#!{vmware_path}\n")
vmware_path = VMware._get_linux_vmware_binary()
if vmware_path:
f.write(f"#!{vmware_path}\n")
for key, value in pairs.items():
entry = f'{key} = "{value}"\n'
f.write(entry)
@@ -620,10 +602,7 @@ class VMware(BaseManager):
:returns: path to the inventory file
"""
if sys.platform.startswith("darwin"):
return os.path.expanduser("~/Library/Application Support/VMware Fusion/vmInventory")
else:
return os.path.expanduser("~/.vmware/inventory.vmls")
return os.path.expanduser("~/.vmware/inventory.vmls")
@staticmethod
def get_vmware_preferences_path():
@@ -633,10 +612,7 @@ class VMware(BaseManager):
:returns: path to the preferences file
"""
if sys.platform.startswith("darwin"):
return os.path.expanduser("~/Library/Preferences/VMware Fusion/preferences")
else:
return os.path.expanduser("~/.vmware/preferences")
return os.path.expanduser("~/.vmware/preferences")
@staticmethod
def get_vmware_default_vm_paths():
@@ -646,10 +622,7 @@ class VMware(BaseManager):
:returns: path to the default VM directory
"""
if sys.platform.startswith("darwin"):
return [os.path.expanduser("~/Documents/Virtual Machines.localized")]
else:
return [os.path.expanduser("~/vmware")]
return [os.path.expanduser("~/vmware")]
async def list_vms(self):
"""
+2 -22
View File
@@ -22,7 +22,6 @@ import asyncio
import logging
import os
import platform
import sys
import tempfile
from collections import OrderedDict
@@ -260,12 +259,7 @@ class VMwareVM(BaseNode):
if self._get_vmx_setting(connected):
del self._vmx_pairs[connected]
use_ubridge = True
# use alternative method to find vmnet interfaces on macOS >= 11.0 (BigSur)
# because "bridge" interfaces are used instead and they are only created on the VM starts
if sys.platform.startswith("darwin") and parse_version(platform.mac_ver()[0]) >= parse_version("11.0.0"):
use_ubridge = False
self.manager.refresh_vmnet_list(ubridge=use_ubridge)
self.manager.refresh_vmnet_list(ubridge=True)
# then configure VMware network adapters
for adapter_number in range(0, self._adapters):
custom_adapter = self._get_custom_adapter_settings(adapter_number)
@@ -349,21 +343,7 @@ class VMwareVM(BaseNode):
vnet = self._get_vnet(adapter_number)
await self._ubridge_send(f"bridge create {vnet}")
vmnet_interface = os.path.basename(self._vmx_pairs[vnet])
block_host_traffic = self.manager.config.settings.VMware.block_host_traffic
if sys.platform.startswith("darwin"):
if parse_version(platform.mac_ver()[0]) >= parse_version("11.0.0"):
# a bridge interface (bridge100, bridge101 etc.) is used instead of a vmnet interface
# on macOS >= 11.0 (Big Sur)
vmnet_interface = self.manager.find_bridge_interface(vmnet_interface)
if not vmnet_interface:
raise VMwareError(f"Could not find bridge interface linked with {vmnet_interface}")
await self._add_ubridge_ethernet_connection(vnet, vmnet_interface, block_host_traffic)
else:
# special case on macOS, we cannot bind VMnet interfaces using the libpcap
await self._ubridge_send(f'bridge add_nio_fusion_vmnet {vnet} "{vmnet_interface}"')
else:
await self._add_ubridge_ethernet_connection(vnet, vmnet_interface, block_host_traffic)
await self._add_ubridge_ethernet_connection(vnet, vmnet_interface)
if isinstance(nio, NIOUDP):
await self._ubridge_send(f"bridge add_nio_udp {vnet} {nio.lport} {nio.rhost} {nio.rport}")
+6 -17
View File
@@ -24,10 +24,8 @@ import logging
import os
import re
import shutil
import signal
import socket
import subprocess
import sys
from gns3server.utils import parse_version
from gns3server.utils.asyncio import monitor_process, subprocess_check_output, wait_for_process_termination
@@ -262,13 +260,10 @@ class VPCSVM(KernelDatapathMixin, BaseNode):
log.info(f"Starting VPCS: {command}")
self._vpcs_stdout_file = os.path.join(self.working_dir, "vpcs.log")
log.info(f"Logging to {self._vpcs_stdout_file}")
flags = 0
if sys.platform.startswith("win32"):
flags = subprocess.CREATE_NEW_PROCESS_GROUP
with open(self._vpcs_stdout_file, "w", encoding="utf-8") as fd:
self.command_line = " ".join(command)
self._process = await asyncio.create_subprocess_exec(
*command, stdout=fd, stderr=subprocess.STDOUT, cwd=self.working_dir, creationflags=flags
*command, stdout=fd, stderr=subprocess.STDOUT, cwd=self.working_dir
)
monitor_process(self._process, self._termination_callback)
@@ -480,17 +475,11 @@ class VPCSVM(KernelDatapathMixin, BaseNode):
"""
log.info(f"Stopping VPCS instance {self.name} PID={self._process.pid}")
if sys.platform.startswith("win32"):
try:
self._process.send_signal(signal.CTRL_BREAK_EVENT)
except (SystemError, OSError):
pass
else:
try:
self._process.terminate()
# Sometime the process may already be dead when we garbage collect
except ProcessLookupError:
pass
try:
self._process.terminate()
# Sometime the process may already be dead when we garbage collect
except ProcessLookupError:
pass
def read_vpcs_stdout(self):
"""
+8 -5
View File
@@ -59,8 +59,7 @@ symbols_path = /home/gns3/GNS3/symbols
configs_path = /home/gns3/GNS3/configs
; Path where files like built-in appliances and Docker resources are stored
; The default path is the local user data directory
; (Linux: "~/.local/share/GNS3", macOS: "~/Library/Application Support/GNS3", Windows: "%APPDATA%\GNS3")
; The default path is the local user data directory ("~/.local/share/GNS3")
; resources_path = /home/gns3/GNS3/resources
; Default symbol theme
@@ -172,10 +171,8 @@ vboxmanage_path = vboxmanage
vmrun_path = vmrun
; First vmnet interface of the range that can be managed by the GNS3 server
vmnet_start_range = 2
; Last vmnet interface of the range that can be managed by the GNS3 server. It must be maximum 19 on Windows.
; Last vmnet interface of the range that can be managed by the GNS3 server
vmnet_end_range = 255
; block network traffic originating from the host OS
block_host_traffic = False
[Qemu]
; Use Qemu monitor feature to communicate with Qemu VMs
@@ -187,10 +184,16 @@ monitor_host = 127.0.0.1
enable_hardware_acceleration = True
; Require hardware acceleration in order to start VMs
require_hardware_acceleration = False
; kvmclock and TSC deadline timer of KVM guests: "auto" turns them off only when this server runs on
; Hyper-V without a usable TSC (guests panic with soft lockups or hang), "enabled" or "disabled" forces them
kvmclock = auto
; Allow unsafe additional command line options
allow_unsafe_options = False
; Path to the OVMF firmware directory
ovmf_firmware_dir = "/usr/share/OVMF"
; Path to the aarch64 UEFI firmware directory (AAVMF_CODE.fd and AAVMF_VARS.fd)
; Firmware files are also searched for in the QEMU images directory
aavmf_firmware_dir = "/usr/share/AAVMF"
[WebWireshark]
; Enable Web Wireshark feature (container-based Wireshark in browser)
-14
View File
@@ -44,8 +44,6 @@ from .appliance import Appliance as Appliance
from .appliance_manager import ApplianceManager
from .compute import Compute, ComputeError
from .controller_error import ControllerError, ControllerNotFoundError
from .gns3vm import GNS3VM
from .gns3vm.gns3_vm_error import GNS3VMError
from .node import Node
from .notification import Notification
from .project import Project
@@ -131,7 +129,6 @@ class Controller:
self._projects = {}
self._ssl_context = None
self._notification = Notification(self)
self.gns3vm = GNS3VM(self)
self.symbols = Symbols()
self._appliance_manager = ApplianceManager()
self._iou_license_settings = {"iourc_content": "", "license_check": False}
@@ -213,11 +210,6 @@ class Controller:
except (ControllerError, KeyError):
pass # Skip not available servers at loading
try:
await self.gns3vm.auto_start_vm()
except GNS3VMError as e:
log.warning(str(e))
await self.load_projects()
self._start_projects_monitor()
@@ -273,7 +265,6 @@ class Controller:
# We don't care if a compute is down at this step
except (ComputeError, ControllerError, OSError):
pass
await self.gns3vm.exit_vm()
self.save()
self._computes = {}
self._projects = {}
@@ -607,11 +598,6 @@ class Controller:
if (compute_id == "local" or compute_id == "vm") and not force:
return None
# It seem we have error with a gns3vm imported as a remote server and conflict
# with GNS3 VM settings. That's why we ignore server name gns3vm
if name == "gns3vm":
return None
for compute in self._computes.values():
if name and compute.name == name and not force:
raise ControllerError(f'Compute name "{name}" already exists')
+14 -19
View File
@@ -49,6 +49,12 @@ class ApplianceToTemplate:
Appliance installation.
"""
def __init__(self):
from . import Controller
self._controller = Controller.instance()
def new_template(self, appliance_config, version, server):
"""
Creates a new template from an appliance.
@@ -89,17 +95,11 @@ class ApplianceToTemplate:
if new_template.get("symbol") is None:
if appliance_config["category"] == "guest":
if "docker" in appliance_config:
new_template["symbol"] = ":/symbols/docker_guest.svg"
new_template["symbol"] = self._controller.symbols.resolve_symbol("docker_guest")
else:
new_template["symbol"] = ":/symbols/qemu_guest.svg"
elif appliance_config["category"] == "router":
new_template["symbol"] = ":/symbols/router.svg"
elif appliance_config["category"] == "switch":
new_template["symbol"] = ":/symbols/ethernet_switch.svg"
elif appliance_config["category"] == "multilayer_switch":
new_template["symbol"] = ":/symbols/multilayer_switch.svg"
elif appliance_config["category"] == "firewall":
new_template["symbol"] = ":/symbols/firewall.svg"
new_template["symbol"] = self._controller.symbols.resolve_symbol("qemu_guest")
else:
new_template["symbol"] = self._controller.symbols.resolve_symbol(appliance_config.get("category"))
if "qemu" in appliance_config:
new_template["template_type"] = "qemu"
@@ -114,6 +114,7 @@ class ApplianceToTemplate:
new_template["template_type"] = "docker"
self._add_docker_config(new_template, appliance_config)
print(new_template)
return new_template
def _add_qemu_config(self, new_config, appliance_config, version):
@@ -225,17 +226,11 @@ class ApplianceToTemplate:
# apply a default symbol based on the effective category and template type
if category_before_remap == "guest":
if settings["template_type"] == "docker":
new_template["symbol"] = ":/symbols/docker_guest.svg"
new_template["symbol"] = self._controller.symbols.resolve_symbol("docker_guest")
else:
new_template["symbol"] = ":/symbols/qemu_guest.svg"
new_template["symbol"] = self._controller.symbols.resolve_symbol("qemu_guest")
else:
symbols = {
"router": ":/symbols/router.svg",
"switch": ":/symbols/ethernet_switch.svg",
"multilayer_switch": ":/symbols/multilayer_switch.svg",
"firewall": ":/symbols/firewall.svg",
}
new_template["symbol"] = symbols.get(category_before_remap)
new_template["symbol"] = self._controller.symbols.resolve_symbol(category_before_remap)
if version and version.get("images"):
if settings["template_type"] == "iou":
+31 -11
View File
@@ -23,6 +23,7 @@ import logging
import socket
import sys
from asyncio import timeout as asynctimeout
from typing import Optional
import aiohttp
from fastapi import HTTPException
@@ -134,12 +135,14 @@ class Compute:
if password:
self._password = password
try:
self._auth = aiohttp.BasicAuth(self._user, self._password.get_secret_value(), "utf-8")
self._auth = aiohttp.encode_basic_auth(
self._user, self._password.get_secret_value(), encoding="utf-8"
)
except ValueError as e:
log.error(str(e))
else:
self._password = None
self._auth = aiohttp.BasicAuth(self._user, "")
self._auth = aiohttp.encode_basic_auth(self._user, "", encoding="utf-8")
def set_last_error(self, msg):
"""
@@ -293,6 +296,15 @@ class Compute:
def password(self, value):
self._set_auth(self._user, value)
@property
def auth_header(self) -> Optional[str]:
"""
Value for the Authorization header when sending requests to this compute,
or None when the compute has no user configured.
"""
return self._auth
@property
def cpu_usage_percent(self):
return self._cpu_usage_percent
@@ -353,7 +365,10 @@ class Compute:
"""
url = self._getUrl(f"/projects/{project.id}/files/{path}")
response = await self._session().request("GET", url, auth=self._auth)
request_options = {"auth": None}
if self._auth:
request_options["headers"] = {"Authorization": self._auth}
response = await self._session().request("GET", url, **request_options)
if response.status == 404:
raise ControllerNotFoundError(f"{path} not found on compute")
return response
@@ -368,7 +383,10 @@ class Compute:
"""
url = self._getUrl(f"/{image_type}/images/{image}")
response = await self._session().request("GET", url, auth=self._auth)
request_options = {"auth": None}
if self._auth:
request_options["headers"] = {"Authorization": self._auth}
response = await self._session().request("GET", url, **request_options)
if response.status == 404:
raise ControllerNotFoundError(f"{image} not found on compute")
return response
@@ -383,8 +401,6 @@ class Compute:
# a manually disconnected compute is not lazily reconnected either: the
# request fails like for any unreachable compute
if not self._connected and not self._manual_disconnect and not dont_connect:
if self._id == "vm" and not self._controller.gns3vm.running:
await self._controller.gns3vm.start()
await self.connect()
if not self._connected and not dont_connect:
raise ComputeError(f"Cannot connect to compute '{self._name}' with request {method} {path}")
@@ -525,7 +541,10 @@ class Compute:
ws_url = self._getUrl("/notifications/ws")
try:
async with self._session().ws_connect(ws_url, auth=self._auth, heartbeat=10) as ws:
connection_options = {"heartbeat": 10}
if self._auth:
connection_options["headers"] = {"Authorization": self._auth}
async with self._session().ws_connect(ws_url, **connection_options) as ws:
log.info(f"Connected to compute '{self._id}' WebSocket '{ws_url}'")
async for response in ws:
if response.type == aiohttp.WSMsgType.TEXT:
@@ -600,6 +619,8 @@ class Compute:
async with asynctimeout(delay=timeout):
url = self._getUrl(path)
headers = {"content-type": "application/json"}
if self._auth:
headers["Authorization"] = self._auth
chunked = None
if data == {}:
data = None
@@ -624,13 +645,12 @@ class Compute:
else:
data = json.dumps(data).encode("utf-8")
try:
log.debug(f"Attempting request to compute: {method} {url} {headers}")
log.debug(f"Attempting request to compute: {method} {url}")
response = await self._session().request(
method,
url,
headers=headers,
data=data,
auth=self._auth,
params=params,
chunked=chunked,
timeout=timeout,
@@ -723,13 +743,13 @@ class Compute:
async def delete(self, path, **kwargs):
return await self.http_query("DELETE", path, **kwargs)
async def forward(self, method, type, path, data=None):
async def forward(self, method, type, path, data=None, params=None):
"""
Forward a call to the emulator on compute
"""
try:
action = f"/{type}/{path}"
res = await self.http_query(method, action, data=data, timeout=None)
res = await self.http_query(method, action, data=data, timeout=None, params=params)
except aiohttp.ServerDisconnectedError:
raise ControllerError(f"Connection lost to {self._id} during {method} {action}")
return res.json
-403
View File
@@ -1,403 +0,0 @@
#!/usr/bin/env python
#
# Copyright (C) 2016 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 a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import asyncio
import copy
import ipaddress
import logging
import sys
from ...utils.asyncio import locking
from ...version import __version__
from ..compute import ComputeError
from ..controller_error import ControllerError
from .gns3_vm_error import GNS3VMError
from .hyperv_gns3_vm import HyperVGNS3VM
from .remote_gns3_vm import RemoteGNS3VM
from .virtualbox_gns3_vm import VirtualBoxGNS3VM
from .vmware_gns3_vm import VMwareGNS3VM
log = logging.getLogger(__name__)
class GNS3VM:
"""
Proxy between the controller and the GNS3 VM engine
"""
def __init__(self, controller):
self._controller = controller
# Keep instance of the loaded engines
self._engines = {}
self._settings = {
"vmname": None,
"when_exit": "stop",
"headless": False,
"enable": False,
"engine": "vmware",
"allocate_vcpus_ram": True,
"ram": 2048,
"vcpus": 1,
"port": 80,
}
def engine_list(self):
"""
:returns: Return list of engines supported by GNS3 for the GNS3VM
"""
download_url = f"https://github.com/GNS3/gns3-gui/releases/download/v{__version__}/GNS3.VM.VMware.Workstation.{__version__}.zip"
vmware_info = {
"engine_id": "vmware",
"description": f'VMware is the recommended choice for best performances.<br>The GNS3 VM can be <a href="{download_url}">downloaded here</a>.',
"support_when_exit": True,
"support_headless": True,
"support_ram": True,
}
if sys.platform.startswith("darwin"):
vmware_info["name"] = "VMware Fusion (recommended)"
else:
vmware_info["name"] = "VMware Workstation / Player (recommended)"
download_url = (
f"https://github.com/GNS3/gns3-gui/releases/download/v{__version__}/GNS3.VM.Hyper-V.{__version__}.zip"
)
hyperv_info = {
"engine_id": "hyper-v",
"name": "Hyper-V",
"description": f'Hyper-V support (Windows 10/Server 2016 and above). Nested virtualization must be supported and enabled (Intel processor only)<br>The GNS3 VM can be <a href="{download_url}">downloaded here</a>',
"support_when_exit": True,
"support_headless": False,
"support_ram": True,
}
download_url = (
f"https://github.com/GNS3/gns3-gui/releases/download/v{__version__}/GNS3.VM.VirtualBox.{__version__}.zip"
)
virtualbox_info = {
"engine_id": "virtualbox",
"name": "VirtualBox",
"description": f'VirtualBox support. Nested virtualization for both Intel and AMD processors is supported since version 6.1<br>The GNS3 VM can be <a href="{download_url}">downloaded here</a>',
"support_when_exit": True,
"support_headless": True,
"support_ram": True,
}
remote_info = {
"engine_id": "remote",
"name": "Remote",
"description": "Use a remote GNS3 server as the GNS3 VM.",
"support_when_exit": False,
"support_headless": False,
"support_ram": False,
}
engines = [vmware_info, virtualbox_info, remote_info]
if sys.platform.startswith("win"):
engines.append(hyperv_info)
return engines
def current_engine(self):
return self._get_engine(self._settings["engine"])
@property
def engine(self):
return self._settings["engine"]
@property
def ip_address(self):
"""
Returns the GNS3 VM IP address.
:returns: VM IP address
"""
return self.current_engine().ip_address
@property
def running(self):
"""
Returns if the GNS3 VM is running.
:returns: Boolean
"""
return self.current_engine().running
@property
def user(self):
"""
Returns the GNS3 VM user.
:returns: VM user
"""
return self.current_engine().user
@property
def password(self):
"""
Returns the GNS3 VM password.
:returns: VM password
"""
return self.current_engine().password
@property
def port(self):
"""
Returns the GNS3 VM port.
:returns: VM port
"""
return self.current_engine().port
@property
def protocol(self):
"""
Returns the GNS3 VM protocol.
:returns: VM protocol
"""
return self.current_engine().protocol
@property
def enable(self):
"""
The GNSVM is activated
"""
return self._settings.get("enable", False)
@property
def when_exit(self):
"""
What should be done when exit
"""
return self._settings["when_exit"]
@property
def settings(self):
return self._settings
@settings.setter
def settings(self, val):
self._settings.update(val)
async def update_settings(self, settings):
"""
Update settings and will restart the VM if require
"""
new_settings = copy.copy(self._settings)
new_settings.update(settings)
if self.settings != new_settings:
try:
await self._stop()
finally:
self._settings = settings
self._controller.save()
if self.enable:
await self.start()
else:
# When user fix something on his system and try again
if self.enable and not self.current_engine().running:
await self.start()
def _get_engine(self, engine):
"""
Load an engine
"""
if engine in self._engines:
return self._engines[engine]
if engine == "vmware":
self._engines["vmware"] = VMwareGNS3VM(self._controller)
return self._engines["vmware"]
elif engine == "hyper-v":
self._engines["hyper-v"] = HyperVGNS3VM(self._controller)
return self._engines["hyper-v"]
elif engine == "virtualbox":
self._engines["virtualbox"] = VirtualBoxGNS3VM(self._controller)
return self._engines["virtualbox"]
elif engine == "remote":
self._engines["remote"] = RemoteGNS3VM(self._controller)
return self._engines["remote"]
raise NotImplementedError(f"The engine {engine} for the GNS3 VM is not supported")
def asdict(self):
return self._settings
@locking
async def list(self, engine):
"""
List VMS for an engine
"""
engine = self._get_engine(engine)
vms = []
try:
for vm in await engine.list():
vms.append({"vmname": vm["vmname"]})
except GNS3VMError as e:
# We raise error only if user activated the GNS3 VM
# otherwise you have noise when VMware is not installed
if self.enable:
raise e
return vms
async def auto_start_vm(self):
"""
Auto start the GNS3 VM if require
"""
if self.enable:
try:
await self.start()
except GNS3VMError as e:
# User will receive the error later when they will try to use the node
try:
compute = await self._controller.add_compute(
compute_id="vm", name=f"GNS3 VM ({self.current_engine().vmname})", host=None, force=True
)
compute.set_last_error(str(e))
except ControllerError:
pass
log.error(f"Cannot start the GNS3 VM: {e}")
async def exit_vm(self):
if self.enable:
try:
if self._settings["when_exit"] == "stop":
await self._stop()
elif self._settings["when_exit"] == "suspend":
await self._suspend()
except GNS3VMError as e:
log.warning(str(e))
@locking
async def start(self):
"""
Start the GNS3 VM
"""
engine = self.current_engine()
if not engine.running:
if self._settings["vmname"] is None:
return
log.info("Start the GNS3 VM")
engine.allocate_vcpus_ram = self._settings["allocate_vcpus_ram"]
engine.vmname = self._settings["vmname"]
engine.ram = self._settings["ram"]
engine.vcpus = self._settings["vcpus"]
engine.headless = self._settings["headless"]
engine.port = self._settings["port"]
compute = await self._controller.add_compute(
compute_id="vm", name=f"GNS3 VM is starting ({engine.vmname})", host=None, force=True, connect=False
)
try:
await engine.start()
except Exception as e:
await self._controller.delete_compute("vm")
log.error(f"Cannot start the GNS3 VM: {e!s}")
await compute.update(name=f"GNS3 VM ({engine.vmname})")
compute.set_last_error(str(e))
raise e
await compute.connect() # we can connect now that the VM has started
await compute.update(
name=f"GNS3 VM ({engine.vmname})",
protocol=self.protocol,
host=self.ip_address,
port=self.port,
user=self.user,
password=self.password,
)
# check if the VM is in the same subnet as the local server, start 10 seconds later to give
# some time for the compute in the VM to be ready for requests
asyncio.get_event_loop().call_later(10, lambda: asyncio.ensure_future(self._check_network(compute)))
async def _check_network(self, compute):
"""
Check that the VM is in the same subnet as the local server
"""
try:
vm_interfaces = await compute.interfaces()
vm_interface_netmask = None
for interface in vm_interfaces:
if interface["ip_address"] == self.ip_address:
vm_interface_netmask = interface["netmask"]
break
if vm_interface_netmask:
vm_network = ipaddress.ip_interface(f"{compute.host_ip}/{vm_interface_netmask}").network
for compute_id in self._controller.computes:
if compute_id == "local":
compute = self._controller.get_compute(compute_id)
interfaces = await compute.interfaces()
netmask = None
for interface in interfaces:
if interface["ip_address"] == compute.host_ip:
netmask = interface["netmask"]
break
if netmask:
compute_network = ipaddress.ip_interface(f"{compute.host_ip}/{netmask}").network
if vm_network.compare_networks(compute_network) != 0:
msg = f"The GNS3 VM (IP={self.ip_address}, NETWORK={vm_network}) is not on the same network as the {compute_id} server (IP={compute.host_ip}, NETWORK={compute_network}), please make sure the local server binding is in the same network as the GNS3 VM"
self._controller.notification.controller_emit("log.warning", {"message": msg})
except ComputeError as e:
log.warning(f"Could not check the VM is in the same subnet as the local server: {e}")
except ControllerError as e:
log.warning(f"Could not check the VM is in the same subnet as the local server: {e}")
@locking
async def _suspend(self):
"""
Suspend the GNS3 VM
"""
engine = self.current_engine()
if "vm" in self._controller.computes:
await self._controller.delete_compute("vm")
if engine.running:
log.info("Suspend the GNS3 VM")
await engine.suspend()
@locking
async def _stop(self):
"""
Stop the GNS3 VM
"""
engine = self.current_engine()
if "vm" in self._controller.computes:
await self._controller.delete_compute("vm")
if engine.running:
log.info("Stop the GNS3 VM")
await engine.stop()
@@ -1,303 +0,0 @@
#!/usr/bin/env python
#
# Copyright (C) 2016 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 a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import psutil
log = logging.getLogger(__name__)
class BaseGNS3VM:
def __init__(self, controller):
self._controller = controller
self._vmname = None
self._ip_address = None
self._port = 80 # value not used, will be overwritten
self._headless = False
self._allocate_vcpus_ram = True
self._vcpus = 1
self._ram = 1024
self._user = ""
self.password = ""
self._protocol = "http"
self._running = False
# limit the number of vCPUs to the number of physical cores (hyper thread CPUs are excluded)
# because this is likely to degrade performances.
self._vcpus = psutil.cpu_count(logical=False)
# we want to allocate half of the available physical memory
# ram = int(psutil.virtual_memory().total / (1024 * 1024) / 2)
# value must be a multiple of 4 (VMware requirement)
# ram -= ram % 4
ram = 2048
self._ram = ram
@property
def vmname(self):
"""
Returns the GNS3 VM name.
:returns: VM name
"""
return self._vmname
@vmname.setter
def vmname(self, new_name):
"""
Sets the GNS3 VM name
:param new_name: new VM name
"""
self._vmname = new_name
@property
def protocol(self):
"""
Get the GNS3 VM protocol
:returns: Protocol as string
"""
return self._protocol
@protocol.setter
def protocol(self, val):
"""
Sets the GNS3 VM protocol
:param val: new VM protocol
"""
self._protocol = val
@property
def user(self):
"""
Get the GNS3 VM user
:returns: User as string
"""
return self._user
@user.setter
def user(self, val):
"""
Sets the GNS3 VM user
:param val: new VM user
"""
self._user = val
@property
def password(self):
"""
Get the GNS3 VM password
:returns: Password as string
"""
return self._password
@password.setter
def password(self, val):
"""
Sets the GNS3 VM password
:param val: new VM password
"""
self._password = val
@property
def port(self):
"""
Returns the GNS3 VM port.
:returns: VM port
"""
return self._port
@port.setter
def port(self, new_port):
"""
Sets the GNS3 VM port
:param new_port: new VM port
"""
self._port = new_port
@property
def ip_address(self):
"""
Returns the GNS3 VM IP address.
:returns: VM IP address
"""
return self._ip_address
@ip_address.setter
def ip_address(self, new_ip_address):
"""
Sets the GNS3 VM IP address.
:param new_ip_address: new VM IP address
"""
self._ip_address = new_ip_address
@property
def running(self):
"""
Returns whether the GNS3 VM is running or not.
:returns: boolean
"""
return self._running
@running.setter
def running(self, value):
"""
Sets whether the GNS3 VM is running or not.
:param value: boolean
"""
self._running = value
@property
def headless(self):
"""
Returns whether the GNS3 VM is headless or not.
:returns: boolean
"""
return self._headless
@headless.setter
def headless(self, value):
"""
Sets whether the GNS3 VM is headless or not.
:param value: boolean
"""
self._headless = value
@property
def allocate_vcpus_ram(self):
"""
Returns whether VCPUs and RAM settings should be configured for the GNS3 VM.
:returns: boolean
"""
return self._allocate_vcpus_ram
@allocate_vcpus_ram.setter
def allocate_vcpus_ram(self, value):
"""
Sets whether VCPUs and RAM settings should be configured for the GNS3 VM.
:param value: boolean
"""
self._allocate_vcpus_ram = value
@property
def vcpus(self):
"""
Returns the number of allocated vCPUs.
:returns: number of vCPUs.
"""
return self._vcpus
@vcpus.setter
def vcpus(self, new_vcpus):
"""
Sets the number of allocated vCPUs.
:param new_vcpus: new number of vCPUs.
"""
self._vcpus = new_vcpus
@property
def ram(self):
"""
Returns the amount of allocated RAM.
:returns: number of vCPUs.
"""
return self._ram
@ram.setter
def ram(self, new_ram):
"""
Sets the amount of allocated RAM.
:param new_ram: new amount of RAM.
"""
self._ram = new_ram
@property
def engine(self):
"""
Returns the engine (virtualization technology used to run the GNS3 VM).
:returns: engine name
"""
return self._engine
async def list(self):
"""
List all VMs
"""
raise NotImplementedError
async def start(self):
"""
Starts the GNS3 VM.
"""
raise NotImplementedError
async def suspend(self):
"""
Suspend the GNS3 VM.
"""
raise NotImplementedError
async def stop(self):
"""
Stops the GNS3 VM.
"""
raise NotImplementedError
@@ -1,28 +0,0 @@
#!/usr/bin/env python
#
# Copyright (C) 2016 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 a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class GNS3VMError(Exception):
def __init__(self, message):
super().__init__(message)
self._message = message
def __repr__(self):
return self._message
def __str__(self):
return f"GNS3VM: {self._message}"
@@ -1,346 +0,0 @@
#!/usr/bin/env python
#
# Copyright (C) 2018 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 a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import asyncio
import ipaddress
import logging
import sys
import psutil
from .base_gns3_vm import BaseGNS3VM
from .gns3_vm_error import GNS3VMError
log = logging.getLogger(__name__)
class HyperVGNS3VM(BaseGNS3VM):
_HYPERV_VM_STATE_ENABLED = 2
_HYPERV_VM_STATE_DISABLED = 3
_HYPERV_VM_STATE_SHUTDOWN = 4
_HYPERV_VM_STATE_PAUSED = 9
_WMI_JOB_STATUS_STARTED = 4096
_WMI_JOB_STATE_RUNNING = 4
_WMI_JOB_STATE_COMPLETED = 7
def __init__(self, controller):
self._engine = "hyper-v"
super().__init__(controller)
self._conn = None
self._vm = None
self._management = None
self._wmi = None
def _check_requirements(self):
"""
Checks if the GNS3 VM can run on Hyper-V.
"""
if not sys.platform.startswith("win"):
raise GNS3VMError("Hyper-V is only supported on Windows")
if sys.getwindowsversion().platform_version[0] < 10:
raise GNS3VMError(
f"Windows 10/Windows Server 2016 or a later version is required to run Hyper-V with nested virtualization enabled (version {sys.getwindowsversion().platform_version[0]} detected)"
)
is_windows_10 = (
sys.getwindowsversion().platform_version[0] == 10 and sys.getwindowsversion().platform_version[1] == 0
)
if is_windows_10 and sys.getwindowsversion().platform_version[2] < 14393:
raise GNS3VMError(
"Hyper-V with nested virtualization is only supported on Windows 10 Anniversary Update (build 10.0.14393) or later"
)
try:
import pythoncom
pythoncom.CoInitialize()
import wmi
self._wmi = wmi
conn = self._wmi.WMI()
except self._wmi.x_wmi as e:
raise GNS3VMError(f"Could not connect to WMI: {e}")
if not conn.Win32_ComputerSystem()[0].HypervisorPresent:
raise GNS3VMError("Hyper-V is not installed or activated")
if conn.Win32_Processor()[0].Manufacturer != "GenuineIntel":
if is_windows_10 and conn.Win32_Processor()[0].Manufacturer == "AuthenticAMD":
if sys.getwindowsversion().platform_version[2] < 19640:
raise GNS3VMError(
"Windows 10 (build 10.0.19640) or later is required by Hyper-V to support nested virtualization with AMD processors"
)
else:
raise GNS3VMError(
"An Intel processor is required by Hyper-V to support nested virtualization on this version of Windows"
)
# This is not reliable
# if not conn.Win32_Processor()[0].VirtualizationFirmwareEnabled:
# raise GNS3VMError("Nested Virtualization (VT-x) is not enabled on this system")
def _connect(self):
"""
Connects to local host using WMI.
"""
self._check_requirements()
try:
self._conn = self._wmi.WMI(namespace=r"root\virtualization\v2")
except self._wmi.x_wmi as e:
raise GNS3VMError(f"Could not connect to WMI: {e}")
if not self._conn.Msvm_VirtualSystemManagementService():
raise GNS3VMError("The Windows account running GNS3 does not have the required permissions for Hyper-V")
self._management = self._conn.Msvm_VirtualSystemManagementService()[0]
def _find_vm(self, vm_name):
"""
Finds a Hyper-V VM.
"""
if self._conn is None:
self._connect()
vms = self._conn.Msvm_ComputerSystem(ElementName=vm_name)
nb_vms = len(vms)
if nb_vms == 0:
return None
elif nb_vms > 1:
raise GNS3VMError(f"Duplicate VM name found for {vm_name}")
else:
return vms[0]
def _is_running(self):
"""
Checks if the VM is running.
"""
if self._vm is not None and self._vm.EnabledState == HyperVGNS3VM._HYPERV_VM_STATE_ENABLED:
return True
return False
def _get_vm_setting_data(self, vm):
"""
Gets the VM settings.
:param vm: VM instance
"""
vm_settings = vm.associators(wmi_result_class="Msvm_VirtualSystemSettingData")
return [s for s in vm_settings if s.VirtualSystemType == "Microsoft:Hyper-V:System:Realized"][0]
def _get_vm_resources(self, vm, resource_class):
"""
Gets specific VM resource.
:param vm: VM instance
:param resource_class: resource class name
"""
setting_data = self._get_vm_setting_data(vm)
return setting_data.associators(wmi_result_class=resource_class)
def _set_vcpus_ram(self, vcpus, ram):
"""
Set the number of vCPU cores and amount of RAM for the GNS3 VM.
:param vcpus: number of vCPU cores
:param ram: amount of RAM
"""
available_vcpus = psutil.cpu_count(logical=False)
if vcpus > available_vcpus:
raise GNS3VMError(
f"You have allocated too many vCPUs for the GNS3 VM! (max available is {available_vcpus} vCPUs)"
)
try:
mem_settings = self._get_vm_resources(self._vm, "Msvm_MemorySettingData")[0]
cpu_settings = self._get_vm_resources(self._vm, "Msvm_ProcessorSettingData")[0]
mem_settings.VirtualQuantity = ram
mem_settings.Reservation = ram
mem_settings.Limit = ram
self._management.ModifyResourceSettings(ResourceSettings=[mem_settings.GetText_(1)])
cpu_settings.VirtualQuantity = vcpus
cpu_settings.Reservation = vcpus
cpu_settings.Limit = 100000 # use 100% of CPU
cpu_settings.ExposeVirtualizationExtensions = True # allow the VM to use nested virtualization
self._management.ModifyResourceSettings(ResourceSettings=[cpu_settings.GetText_(1)])
log.info(f"GNS3 VM vCPU count set to {vcpus} and RAM amount set to {ram}")
except Exception as e:
raise GNS3VMError(f"Could not set to {vcpus} and RAM amount set to {ram}: {e}")
async def list(self):
"""
List all Hyper-V VMs
"""
if self._conn is None or self._management is None:
self._connect()
vms = []
try:
for vm in self._conn.Msvm_ComputerSystem():
if vm.ElementName != self._management.SystemName:
vms.append({"vmname": vm.ElementName})
except self._wmi.x_wmi as e:
raise GNS3VMError(f"Could not list Hyper-V VMs: {e}")
return vms
def _get_wmi_obj(self, path):
"""
Gets the WMI object.
"""
return self._wmi.WMI(moniker=path.replace("\\", "/"))
async def _set_state(self, state):
"""
Set the desired state of the VM
"""
if not self._vm:
self._vm = self._find_vm(self.vmname)
if not self._vm:
raise GNS3VMError(f"Could not find Hyper-V VM {self.vmname}")
job_path, ret = self._vm.RequestStateChange(state)
if ret == HyperVGNS3VM._WMI_JOB_STATUS_STARTED:
job = self._get_wmi_obj(job_path)
while job.JobState == HyperVGNS3VM._WMI_JOB_STATE_RUNNING:
await asyncio.sleep(0.1)
job = self._get_wmi_obj(job_path)
if job.JobState != HyperVGNS3VM._WMI_JOB_STATE_COMPLETED:
raise GNS3VMError(f"Error while changing state: {job.ErrorSummaryDescription}")
elif ret != 0 or ret != 32775:
raise GNS3VMError(f"Failed to change state to {state}")
async def _is_vm_network_active(self):
"""
Check if WMI is updated with VM virtual network adapters
and wait until their count becomes > 0
ProtocolIFType Unknown (0)
Other (1)
IPv4 (4096)
IPv6 (4097)
IPv4/v6 (4098)
"""
wql = (
"SELECT * FROM Msvm_GuestNetworkAdapterConfiguration WHERE InstanceID like \
'Microsoft:GuestNetwork\\"
+ self._vm.Name
+ "%' and ProtocolIFType > 0 "
)
nic_count = len(self._conn.query(wql))
while nic_count == 0:
await asyncio.sleep(0.1) # 100ms
nic_count = len(self._conn.query(wql))
async def start(self):
"""
Starts the GNS3 VM.
"""
self._vm = self._find_vm(self.vmname)
if not self._vm:
raise GNS3VMError(f"Could not find Hyper-V VM {self.vmname}")
if not self._is_running():
if self.allocate_vcpus_ram:
log.info("Update GNS3 VM settings (CPU and RAM)")
# set the number of vCPUs and amount of RAM
self._set_vcpus_ram(self.vcpus, self.ram)
# start the VM
try:
await self._set_state(HyperVGNS3VM._HYPERV_VM_STATE_ENABLED)
except GNS3VMError as e:
raise GNS3VMError(f"Failed to start the GNS3 VM: {e}")
log.info("GNS3 VM has been started")
# check if VM network is active
await self._is_vm_network_active()
# Get the guest IP address
# LIS (Linux Integration Services) must be installed on the guest
# See https://oitibs.com/hyper-v-lis-on-ubuntu-18-04/ for details.
trial = 120
guest_ip_address = ""
log.info("Waiting for GNS3 VM IP")
ports = self._get_vm_resources(self._vm, "Msvm_EthernetPortAllocationSettingData")
vnics = self._get_vm_resources(self._vm, "Msvm_SyntheticEthernetPortSettingData")
while True:
for port in ports:
try:
vnic = [v for v in vnics if port.Parent == v.path_()][0]
except IndexError:
continue
config = vnic.associators(wmi_result_class="Msvm_GuestNetworkAdapterConfiguration")
ip_addresses = config[0].IPAddresses
for ip_address in ip_addresses:
# take the first valid IPv4 address
try:
ipaddress.IPv4Address(ip_address)
guest_ip_address = ip_address
except ipaddress.AddressValueError:
continue
if len(ip_addresses):
guest_ip_address = ip_addresses[0]
break
trial -= 1
if guest_ip_address:
break
elif trial == 0:
raise GNS3VMError(f"Could not find guest IP address for {self.vmname}")
await asyncio.sleep(1)
self.ip_address = guest_ip_address
log.info(f"GNS3 VM IP address set to {guest_ip_address}")
self.running = True
async def suspend(self):
"""
Suspends the GNS3 VM.
"""
try:
await self._set_state(HyperVGNS3VM._HYPERV_VM_STATE_PAUSED)
except GNS3VMError as e:
raise GNS3VMError(f"Failed to suspend the GNS3 VM: {e}")
log.info("GNS3 VM has been suspended")
self.running = False
async def stop(self):
"""
Stops the GNS3 VM.
"""
try:
await self._set_state(HyperVGNS3VM._HYPERV_VM_STATE_SHUTDOWN)
except GNS3VMError as e:
raise GNS3VMError(f"Failed to stop the GNS3 VM: {e}")
log.info("GNS3 VM has been stopped")
self.running = False
Loaded 100 of 233 files, more files were not shown because too many files have changed in this diff. Show more